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
|
---|---|---|---|---|---|---|---|---|---|
cedb52abad4bfd5a13dc82b6d3994d26a550dff0
|
main.cpp
|
main.cpp
|
/* **** **** **** **** **** **** **** **** *
*
* _/ _/ _/
* _/_/_/ _/_/_/ _/_/_/
* _/ _/ _/ _/ _/ _/
* _/ _/ _/ _/ _/ _/
* _/_/_/ _/_/_/ _/_/_/
*
* bit by bit
* main.cpp
*
* author: ISHII 2bit
* mail: [email protected]
*
* **** **** **** **** **** **** **** **** */
#include "bit_by_bit.hpp"
#include "simple_test.hpp"
bbb_test_declaretion(test);
void reusable_array_test();
void byte_array_test();
void multithread_test(size_t num);
void range_test();
namespace iterator_delegation { void test(); };
int main(int argc, char *argv[]) {
bbb_test(test);
reusable_array_test();
byte_array_test();
multithread_test(4);
range_test();
iterator_delegation::test();
}
bbb_test_begin_definition(test)
bbb_assert(true);
bbb_test_end_definition()
#pragma mark reusable_array_test
#include <cassert>
#include <iostream>
struct particle {
int life_time;
int age;
int name;
particle() {}
particle(int life_time, int name)
: life_time(life_time)
, name(name)
, age(0) {}
void init(int life_time, int name) {
this->life_time = life_time;
this->name = name;
this->age = 0;
}
bool update() {
return ++age < life_time;
}
void print() const {
std::cout << name << ", " << (life_time - age) << std::endl;
}
};
constexpr int loop_num(1);
constexpr int elem_num(10);
void reusable_array_test() {
bbb::random::set_seed_mt(0);
auto a = bbb::random::mt();
bbb::random::set_seed_mt(0);
auto b = bbb::random::mt();
bbb::random::set_seed_mt(1);
auto c = bbb::random::mt();
assert(a == b);
assert(a != c);
bbb::stop_watch watch;
watch.start();
{
bbb::random::set_seed_mt(0);
bbb::reusable_array<particle, elem_num> f;
watch.rap();
for(int k = 0; k++ < loop_num;) {
do f.init(bbb::random::mt() % 100, f.current_size()); while(f.has_space());
while(f.current_size()) {
f.update();
}
}
watch.rap();
std::cout << "time: " << watch.getLastRapNanoseconds() << std::endl;
}
{
bbb::random::set_seed_mt(0);
bbb::shared_vector<particle> f;
watch.rap();
for(int k = 0; k++ < loop_num;) {
for(; f.size() < elem_num; f.push_back(std::shared_ptr<particle>(new particle(rand() % 100, f.size()))));
auto wrapper = bbb::make_reverse(f);
while(f.size()) for(auto e : wrapper) if(!e->update()) {
e = f.back();
f.pop_back();
}
}
watch.rap();
std::cout << "time: " << watch.getLastRapNanoseconds() << std::endl;
}
}
void byte_array_test() {
bbb::byte_array<int> barr{0x7FFFFFFF};
for(auto i = 0; i < barr.size(); i++) {
std::cout << (int)barr[i] << std::endl;
}
for(auto &b : barr) {
std::cout << (int)b << std::endl;
}
};
void multithread_test(size_t num) {
size_t sum = 0;
bool is_run = true;
bbb::stop_watch watch;
watch.start();
bbb::multithread::manager manager(num, [&sum, &is_run](size_t index, std::mutex &mutex) {
while(is_run) {
if(mutex.try_lock()) {
sum++;
mutex.unlock();
}
bbb::sleep_nanoseconds(50);
}
});
while(is_run) {
bbb::sleep_milliseconds(10);
auto lock(manager.lock_guard());
if(100000 < sum) {
is_run = false;
manager.join();
}
}
watch.rap();
std::cout << "time: " << watch.getLastRapMilliseconds() << std::endl;
}
void range_test() {
{
std::vector<int> vec;
bbb::for_each(bbb::range(10, 2), [&vec](int x) { vec.push_back(x); });
bbb::for_each(vec, [](int &x) { x *= 2; });
for(auto v : bbb::enumerate(vec)) {
std::cout << v.index << ", " << v.value << std::endl;
v.value *= 2;
}
for(auto v : bbb::enumerate(vec)) {
std::cout << v.index << ", " << v.value << std::endl;
}
}
{
const std::vector<int> cvec{1, 2, 3};
for(auto v : bbb::enumerate(cvec)) {
std::cout << v.index << ", " << v.value << std::endl;
}
}
std::cout << std::endl;
std::vector<std::string> svec{"a", "hoge", "foo"};
for(auto &v : bbb::enumerate(svec)) {
std::cout << v.index << ", " << v.value << std::endl;
}
for(const auto &v : bbb::enumerate(svec)) {
std::cout << v.index << ", " << v.value << std::endl;
}
}
#include <iostream>
#include <vector>
#include <deque>
#include <queue>
#include <list>
#include <map>
#include <string>
namespace iterator_delegation {
struct vectroid
: bbb::iterator_delegation<std::vector<int>> {
std::vector<int> body;
vectroid() : delegation(body) { };
};
struct mappoid : bbb::iterator_delegation<std::map<int, int>> {
std::map<int, int> body;
mappoid() : delegation(body) { };
};
struct introid : bbb::iterator_delegation<int> {
int body;
introid() : delegation(body) { };
};
void test() {
static_assert(bbb::iteratable_class_traits<std::vector<int>>::has_iterator, "vector<int> has iterator");
static_assert(bbb::iteratable_class_traits<std::vector<int>>::has_reverse_iterator,
"vector<int> has reverse_iterator");
static_assert(bbb::iteratable_class_traits<std::map<int, int>>::has_iterator, "map<int, int> has_iterator");
static_assert(bbb::iteratable_class_traits<std::string>::has_iterator);
static_assert(!bbb::iteratable_class_traits<int>::has_iterator);
static_assert(bbb::iteratable_class_traits<bbb::iterator_delegation<std::vector<int>>>::has_iterator);
static_assert(bbb::iteratable_class_traits<std::vector<int>>::has_insert);
static_assert(bbb::iteratable_class_traits<std::vector<int>>::has_push_back);
static_assert(!bbb::iteratable_class_traits<std::vector<int>>::has_push_front);
static_assert(bbb::iteratable_class_traits<std::deque<int>>::has_insert);
static_assert(bbb::iteratable_class_traits<std::deque<int>>::has_push_back);
static_assert(bbb::iteratable_class_traits<std::deque<int>>::has_push_front);
static_assert(bbb::iteratable_class_traits<std::list<int>>::has_insert);
static_assert(bbb::iteratable_class_traits<std::list<int>>::has_push_back);
static_assert(bbb::iteratable_class_traits<std::list<int>>::has_push_front);
static_assert(!bbb::iteratable_class_traits<std::queue<int>>::has_insert);
static_assert(!bbb::iteratable_class_traits<std::queue<int>>::has_push_back);
static_assert(!bbb::iteratable_class_traits<std::queue<int>>::has_push_front);
static_assert(!bbb::iteratable_class_traits<int>::has_insert);
static_assert(!bbb::iteratable_class_traits<int>::has_push_back);
static_assert(!bbb::iteratable_class_traits<int>::has_push_front);
vectroid v;
v.body.push_back(-1);
v.body.push_back(-2);
v.body.push_back(-3);
std::vector<int> src{1, 2, 3, 4};
std::copy(src.begin(), src.end(), std::back_inserter(v));
std::copy(src.begin(), src.end(), std::inserter(v, v.begin()));
for (const auto &i : v) {
std::cout << i << std::endl;
}
mappoid m;
m.body.insert(std::make_pair(2, 3));
m.body.insert(std::make_pair(6, 7));
m.body.insert(std::make_pair(4, 5));
m.body.insert(std::make_pair(8, 9));
for (const auto &p : m) {
std::cout << p.first << ", " << p.second << std::endl;
}
introid i;
// for(auto &it : i) {} // Error: delegated type doesn't provide iterator
}
};
|
/* **** **** **** **** **** **** **** **** *
*
* _/ _/ _/
* _/_/_/ _/_/_/ _/_/_/
* _/ _/ _/ _/ _/ _/
* _/ _/ _/ _/ _/ _/
* _/_/_/ _/_/_/ _/_/_/
*
* bit by bit
* main.cpp
*
* author: ISHII 2bit
* mail: [email protected]
*
* **** **** **** **** **** **** **** **** */
#include "bit_by_bit.hpp"
#include "simple_test.hpp"
bbb_test_declaretion(test);
void reusable_array_test();
void byte_array_test();
void multithread_test(size_t num);
void range_test();
bbb_test_declaretion(iterator_delegation);
int main(int argc, char *argv[]) {
bbb_test(test);
reusable_array_test();
byte_array_test();
multithread_test(4);
range_test();
bbb_test(iterator_delegation);
}
bbb_test_begin_definition(test)
bbb_assert(true);
bbb_test_end_definition()
#pragma mark reusable_array_test
#include <cassert>
#include <iostream>
struct particle {
int life_time;
int age;
int name;
particle() {}
particle(int life_time, int name)
: life_time(life_time)
, name(name)
, age(0) {}
void init(int life_time, int name) {
this->life_time = life_time;
this->name = name;
this->age = 0;
}
bool update() {
return ++age < life_time;
}
void print() const {
std::cout << name << ", " << (life_time - age) << std::endl;
}
};
constexpr int loop_num(1);
constexpr int elem_num(10);
void reusable_array_test() {
bbb::random::set_seed_mt(0);
auto a = bbb::random::mt();
bbb::random::set_seed_mt(0);
auto b = bbb::random::mt();
bbb::random::set_seed_mt(1);
auto c = bbb::random::mt();
assert(a == b);
assert(a != c);
bbb::stop_watch watch;
watch.start();
{
bbb::random::set_seed_mt(0);
bbb::reusable_array<particle, elem_num> f;
watch.rap();
for(int k = 0; k++ < loop_num;) {
do f.init(bbb::random::mt() % 100, f.current_size()); while(f.has_space());
while(f.current_size()) {
f.update();
}
}
watch.rap();
std::cout << "time: " << watch.getLastRapNanoseconds() << std::endl;
}
{
bbb::random::set_seed_mt(0);
bbb::shared_vector<particle> f;
watch.rap();
for(int k = 0; k++ < loop_num;) {
for(; f.size() < elem_num; f.push_back(std::shared_ptr<particle>(new particle(rand() % 100, f.size()))));
auto wrapper = bbb::make_reverse(f);
while(f.size()) for(auto e : wrapper) if(!e->update()) {
e = f.back();
f.pop_back();
}
}
watch.rap();
std::cout << "time: " << watch.getLastRapNanoseconds() << std::endl;
}
}
void byte_array_test() {
bbb::byte_array<int> barr{0x7FFFFFFF};
for(auto i = 0; i < barr.size(); i++) {
std::cout << (int)barr[i] << std::endl;
}
for(auto &b : barr) {
std::cout << (int)b << std::endl;
}
};
void multithread_test(size_t num) {
size_t sum = 0;
bool is_run = true;
bbb::stop_watch watch;
watch.start();
bbb::multithread::manager manager(num, [&sum, &is_run](size_t index, std::mutex &mutex) {
while(is_run) {
if(mutex.try_lock()) {
sum++;
mutex.unlock();
}
bbb::sleep_nanoseconds(50);
}
});
while(is_run) {
bbb::sleep_milliseconds(10);
auto lock(manager.lock_guard());
if(100000 < sum) {
is_run = false;
manager.join();
}
}
watch.rap();
std::cout << "time: " << watch.getLastRapMilliseconds() << std::endl;
}
void range_test() {
{
std::vector<int> vec;
bbb::for_each(bbb::range(10, 2), [&vec](int x) { vec.push_back(x); });
bbb::for_each(vec, [](int &x) { x *= 2; });
for(auto v : bbb::enumerate(vec)) {
std::cout << v.index << ", " << v.value << std::endl;
v.value *= 2;
}
for(auto v : bbb::enumerate(vec)) {
std::cout << v.index << ", " << v.value << std::endl;
}
}
{
const std::vector<int> cvec{1, 2, 3};
for(auto v : bbb::enumerate(cvec)) {
std::cout << v.index << ", " << v.value << std::endl;
}
}
std::cout << std::endl;
std::vector<std::string> svec{"a", "hoge", "foo"};
for(auto &v : bbb::enumerate(svec)) {
std::cout << v.index << ", " << v.value << std::endl;
}
for(const auto &v : bbb::enumerate(svec)) {
std::cout << v.index << ", " << v.value << std::endl;
}
}
#include <iostream>
#include <vector>
#include <deque>
#include <queue>
#include <list>
#include <map>
#include <string>
namespace iterator_delegation {
struct vectroid
: bbb::iterator_delegation<std::vector<int>> {
std::vector<int> body;
vectroid() : delegation(body) { };
};
struct mappoid : bbb::iterator_delegation<std::map<int, int>> {
std::map<int, int> body;
mappoid() : delegation(body) { };
};
struct introid : bbb::iterator_delegation<int> {
int body;
introid() : delegation(body) { };
};
}
bbb_test_begin_definition(iterator_delegation)
bbb_assert(bbb::iteratable_class_traits<std::vector<int>>::has_iterator);
bbb_assert(bbb::iteratable_class_traits<std::vector<int>>::has_reverse_iterator);
bbb_assert(bbb::iteratable_class_traits<std::map<int, int>>::has_iterator);
bbb_assert(bbb::iteratable_class_traits<std::string>::has_iterator);
bbb_assert(!bbb::iteratable_class_traits<int>::has_iterator);
bbb_assert(bbb::iteratable_class_traits<bbb::iterator_delegation<std::vector<int>>>::has_iterator);
bbb_assert(bbb::iteratable_class_traits<std::vector<int>>::has_insert);
bbb_assert(bbb::iteratable_class_traits<std::vector<int>>::has_push_back);
bbb_assert(!bbb::iteratable_class_traits<std::vector<int>>::has_push_front);
bbb_assert(bbb::iteratable_class_traits<std::deque<int>>::has_insert);
bbb_assert(bbb::iteratable_class_traits<std::deque<int>>::has_push_back);
bbb_assert(bbb::iteratable_class_traits<std::deque<int>>::has_push_front);
bbb_assert(bbb::iteratable_class_traits<std::list<int>>::has_insert);
bbb_assert(bbb::iteratable_class_traits<std::list<int>>::has_push_back);
bbb_assert(bbb::iteratable_class_traits<std::list<int>>::has_push_front);
bbb_assert(!bbb::iteratable_class_traits<std::queue<int>>::has_insert);
bbb_assert(!bbb::iteratable_class_traits<std::queue<int>>::has_push_back);
bbb_assert(!bbb::iteratable_class_traits<std::queue<int>>::has_push_front);
bbb_assert(!bbb::iteratable_class_traits<int>::has_insert);
bbb_assert(!bbb::iteratable_class_traits<int>::has_push_back);
bbb_assert(!bbb::iteratable_class_traits<int>::has_push_front);
vectroid v;
v.body.push_back(-1);
v.body.push_back(-2);
v.body.push_back(-3);
std::vector<int> src{1, 2, 3, 4};
std::copy(src.begin(), src.end(), std::back_inserter(v));
std::copy(src.begin(), src.end(), std::inserter(v, v.begin()));
for (const auto &i : v) {
std::cout << i << std::endl;
}
mappoid m;
m.body.insert(std::make_pair(2, 3));
m.body.insert(std::make_pair(6, 7));
m.body.insert(std::make_pair(4, 5));
m.body.insert(std::make_pair(8, 9));
for (const auto &p : m) {
std::cout << p.first << ", " << p.second << std::endl;
}
introid i;
// for(auto &it : i) {} // Error: delegated type doesn't provide iterator
bbb_test_end_definition()
|
update test
|
update test
|
C++
|
mit
|
2bbb/bit_by_bit
|
4ed02e7a72251ee398404ad56c5529e9c4722172
|
IMU/main/MPU9250.cpp
|
IMU/main/MPU9250.cpp
|
/*
* MPU9250.cpp
*
* Created on: 7. 9. 2017
* Author: michp
*/
#include "MPU9250.h"
namespace flyhero {
MPU9250& MPU9250::Instance() {
static MPU9250 instance;
return instance;
}
MPU9250::MPU9250() {
this->spi = NULL;
this->rx_buffer = NULL;
this->a_fsr = ACCEL_FSR_NOT_SET;
this->a_lpf = ACCEL_LPF_NOT_SET;
this->a_mult = 0;
this->g_fsr = GYRO_FSR_NOT_SET;
this->g_lpf = GYRO_LPF_NOT_SET;
this->g_mult = 0;
this->sample_rate = 0;
}
esp_err_t MPU9250::spi_init() {
esp_err_t ret;
spi_bus_config_t buscfg;
buscfg.miso_io_num = GPIO_NUM_25;
buscfg.mosi_io_num = GPIO_NUM_23;
buscfg.sclk_io_num = GPIO_NUM_19;
buscfg.quadwp_io_num = -1;
buscfg.quadhd_io_num = -1;
buscfg.max_transfer_sz = 0;
spi_device_interface_config_t devcfg;
devcfg.command_bits = 0;
devcfg.address_bits = 8;
devcfg.dummy_bits = 0;
devcfg.mode = 0;
devcfg.duty_cycle_pos = 128;
devcfg.cs_ena_pretrans = 0;
devcfg.cs_ena_posttrans = 0;
devcfg.clock_speed_hz = 1000000;
devcfg.spics_io_num = GPIO_NUM_22;
devcfg.flags = 0;
devcfg.queue_size = 7;
devcfg.pre_cb = 0;
devcfg.post_cb = 0;
//Initialize the SPI bus
if ( (ret = spi_bus_initialize(HSPI_HOST, &buscfg, 0)) )
return ret;
if ( (ret = spi_bus_add_device(HSPI_HOST, &devcfg, &this->spi)) )
return ret;
return ESP_OK;
}
esp_err_t MPU9250::spi_reg_read(uint8_t reg, uint8_t& data) {
esp_err_t ret;
spi_transaction_t trans;
trans.flags = SPI_TRANS_USE_RXDATA | SPI_TRANS_USE_TXDATA;
trans.cmd = 0;
trans.addr = reg | 0x80;
trans.length = 8;
trans.rxlength = 8;
trans.user = 0;
trans.tx_data[0] = 0x00;
if ( (ret = spi_device_transmit(this->spi, &trans)) )
return ret;
data = trans.rx_data[0];
return ESP_OK;
}
DRAM_ATTR static const uint8_t tx_dummy[40] = { 0x00 };
esp_err_t MPU9250::spi_regs_read(uint8_t first_reg, uint8_t count) {
return ESP_ERR_NOT_SUPPORTED;
/*count += 4 - (count % 4);
esp_err_t ret;
spi_transaction_t trans;
trans.flags = 0;
trans.cmd = 0;
trans.addr = first_reg | 0x80;
trans.length = count * 8;
trans.rxlength = count * 8;
trans.user = 0;
trans.tx_buffer = tx_dummy;
trans.rx_buffer = this->rx_buffer;
if ( (ret = spi_device_transmit(this->spi, &trans)) )
return ret;
return ESP_OK;*/
}
esp_err_t MPU9250::spi_reg_write(uint8_t reg, uint8_t data) {
esp_err_t ret;
spi_transaction_t trans;
trans.flags = SPI_TRANS_USE_TXDATA;
trans.cmd = 0;
trans.addr = reg & 0x7F;
trans.length = 8;
trans.rxlength = 0;
trans.user = 0;
trans.tx_data[0] = data;
if ( (ret = spi_device_transmit(this->spi, &trans)) )
return ret;
return ESP_OK;
}
void MPU9250::set_gyro_fsr(gyro_fsr fsr) {
if (fsr == GYRO_FSR_NOT_SET)
return;
if (fsr == this->g_fsr)
return;
// gyro FSR config shares the same register with DLPF config so we just update reg value
uint8_t gyro_config;
this->spi_reg_read(this->REGISTERS.GYRO_CONFIG, gyro_config);
this->spi_reg_write(this->REGISTERS.GYRO_CONFIG, gyro_config | fsr);
this->g_fsr = fsr;
switch (this->g_fsr) {
case GYRO_FSR_250:
this->g_mult = 250;
break;
case GYRO_FSR_500:
this->g_mult = 500;
break;
case GYRO_FSR_1000:
this->g_mult = 1000;
break;
case GYRO_FSR_2000:
this->g_mult = 2000;
break;
case GYRO_FSR_NOT_SET:
return;
}
this->g_mult /= std::pow(2, this->ADC_BITS - 1);
}
void MPU9250::set_accel_fsr(accel_fsr fsr) {
if (fsr == ACCEL_FSR_NOT_SET)
return;
if (fsr == this->a_fsr)
return;
this->spi_reg_write(this->REGISTERS.ACCEL_CONFIG, fsr);
this->a_fsr = fsr;
switch (this->a_fsr) {
case ACCEL_FSR_2:
this->a_mult = 2;
break;
case ACCEL_FSR_4:
this->a_mult = 4;
break;
case ACCEL_FSR_8:
this->a_mult = 8;
break;
case ACCEL_FSR_16:
this->a_mult = 16;
break;
case ACCEL_FSR_NOT_SET:
return;
}
this->a_mult /= std::pow(2, this->ADC_BITS - 1);
}
void MPU9250::set_gyro_lpf(gyro_lpf lpf) {
if (lpf == GYRO_LPF_NOT_SET)
return;
if (this->g_lpf == lpf)
return;
uint8_t Fchoice_b;
if (lpf == GYRO_LPF_8800HZ)
Fchoice_b = 0x01;
else if (lpf == GYRO_LPF_3600Hz)
Fchoice_b = 0x02;
else
Fchoice_b = 0x00;
// gyro DLPF config shares the same register with FSR config so we just update reg value
uint8_t gyro_config;
this->spi_reg_read(this->REGISTERS.GYRO_CONFIG, gyro_config);
this->spi_reg_write(this->REGISTERS.GYRO_CONFIG, gyro_config | Fchoice_b);
this->spi_reg_write(this->REGISTERS.CONFIG, lpf);
this->g_lpf = lpf;
}
void MPU9250::set_accel_lpf(accel_lpf lpf) {
if (lpf == ACCEL_LPF_NOT_SET)
return;
if (lpf == this->a_lpf)
return;
uint8_t accel_config2 = lpf;
if (lpf == ACCEL_LPF_1046HZ)
accel_config2 |= 0x08;
this->spi_reg_write(this->REGISTERS.ACCEL_CONFIG2, accel_config2);
this->a_lpf = lpf;
}
void MPU9250::set_sample_rate(uint16_t rate) {
// setting SMPLRT_DIV won't be effective
// 8800 Hz => sample at 32 kHz
// 3600 Hz => sample at 32 kHz
// 250 Hz => sample at 8 kHz
if (this->g_lpf == GYRO_LPF_8800HZ || this->g_lpf == GYRO_LPF_3600Hz || this->g_lpf == GYRO_LPF_250HZ)
return;
uint8_t div = (1000 - rate) / rate;
this->spi_reg_write(this->REGISTERS.SMPLRT_DIV, div);
}
void MPU9250::set_interrupt(bool enable) {
this->spi_reg_write(this->REGISTERS.INT_ENABLE, (enable ? 0x01 : 0x00));
}
void MPU9250::Init() {
esp_err_t ret;
/*this->rx_buffer = (uint8_t*)heap_caps_malloc(40, MALLOC_CAP_32BIT | MALLOC_CAP_DMA);
if (this->rx_buffer == NULL)
std::cout << "alloc error" << std::endl;*/
if ( (ret = this->spi_init()) )
return;
// reset the device
this->spi_reg_write(this->REGISTERS.PWR_MGMT_1, 0x80);
// wait until reset done
uint8_t tmp;
do {
this->spi_reg_read(this->REGISTERS.PWR_MGMT_1, tmp);
} while (tmp & 0x80);
vTaskDelay(1000 / portTICK_PERIOD_MS);
/* should not be needed
this->spi_reg_write(this->REGISTERS.SIGNAL_PATH_RESET, 0x07);
*/
// disable FIFO, I2C master; SPI mode only; reset all signal paths
this->spi_reg_write(this->REGISTERS.USER_CTRL, 0x2F);
// enable all sensors
this->spi_reg_write(this->REGISTERS.PWR_MGMT_2, 0x00);
// check device responding
uint8_t who_am_i;
this->spi_reg_read(this->REGISTERS.WHO_AM_I, who_am_i);
if (who_am_i != 0x71)
return;
this->set_interrupt(false);
// set INT pin active high, push-pull; don't use latched mode, fsync nor I2C bypass
this->spi_reg_write(this->REGISTERS.INT_PIN_CFG, 0x10);
this->set_gyro_fsr(GYRO_FSR_2000);
this->set_gyro_lpf(GYRO_LPF_250HZ);
this->set_accel_fsr(ACCEL_FSR_16);
this->set_accel_lpf(ACCEL_LPF_1046HZ);
this->set_sample_rate(8000);
this->set_interrupt(true);
std::cout << "Init complete" << std::endl;
/*timeval start, end;
gettimeofday(&start, NULL);
//this->spi_regs_read(this->REGISTERS.ACCEL_XOUT_H, 14);
gettimeofday(&end, NULL);
for (int i = 0; i < 14; i++)
std::cout << "data[" << i << "]: " << (int)(this->rx_buffer[i]) << std::endl;
std::cout << "in " << end.tv_sec - start.tv_sec << " s, " << end.tv_usec - start.tv_usec << " us" << std::endl;*/
}
} /* namespace flyhero */
|
/*
* MPU9250.cpp
*
* Created on: 7. 9. 2017
* Author: michp
*/
#include "MPU9250.h"
namespace flyhero {
MPU9250& MPU9250::Instance() {
static MPU9250 instance;
return instance;
}
MPU9250::MPU9250() {
this->spi = NULL;
this->rx_buffer = NULL;
this->a_fsr = ACCEL_FSR_NOT_SET;
this->a_lpf = ACCEL_LPF_NOT_SET;
this->a_mult = 0;
this->g_fsr = GYRO_FSR_NOT_SET;
this->g_lpf = GYRO_LPF_NOT_SET;
this->g_mult = 0;
this->sample_rate = 0;
}
esp_err_t MPU9250::spi_init() {
esp_err_t ret;
spi_bus_config_t buscfg;
buscfg.miso_io_num = GPIO_NUM_25;
buscfg.mosi_io_num = GPIO_NUM_23;
buscfg.sclk_io_num = GPIO_NUM_19;
buscfg.quadwp_io_num = -1;
buscfg.quadhd_io_num = -1;
buscfg.max_transfer_sz = 0;
spi_device_interface_config_t devcfg;
devcfg.command_bits = 0;
devcfg.address_bits = 8;
devcfg.dummy_bits = 0;
devcfg.mode = 0;
devcfg.duty_cycle_pos = 128;
devcfg.cs_ena_pretrans = 0;
devcfg.cs_ena_posttrans = 0;
devcfg.clock_speed_hz = 1000000;
devcfg.spics_io_num = GPIO_NUM_22;
devcfg.flags = 0;
devcfg.queue_size = 7;
devcfg.pre_cb = 0;
devcfg.post_cb = 0;
//Initialize the SPI bus
if ( (ret = spi_bus_initialize(HSPI_HOST, &buscfg, 0)) )
return ret;
if ( (ret = spi_bus_add_device(HSPI_HOST, &devcfg, &this->spi)) )
return ret;
return ESP_OK;
}
esp_err_t MPU9250::spi_reg_read(uint8_t reg, uint8_t& data) {
esp_err_t ret;
spi_transaction_t trans;
trans.flags = SPI_TRANS_USE_RXDATA | SPI_TRANS_USE_TXDATA;
trans.cmd = 0;
trans.addr = reg | 0x80;
trans.length = 8;
trans.rxlength = 8;
trans.user = 0;
trans.tx_data[0] = 0x00;
if ( (ret = spi_device_transmit(this->spi, &trans)) )
return ret;
data = trans.rx_data[0];
return ESP_OK;
}
DRAM_ATTR static const uint8_t tx_dummy[40] = { 0x00 };
esp_err_t MPU9250::spi_regs_read(uint8_t first_reg, uint8_t count) {
return ESP_ERR_NOT_SUPPORTED;
/*count += 4 - (count % 4);
esp_err_t ret;
spi_transaction_t trans;
trans.flags = 0;
trans.cmd = 0;
trans.addr = first_reg | 0x80;
trans.length = count * 8;
trans.rxlength = count * 8;
trans.user = 0;
trans.tx_buffer = tx_dummy;
trans.rx_buffer = this->rx_buffer;
if ( (ret = spi_device_transmit(this->spi, &trans)) )
return ret;
return ESP_OK;*/
}
esp_err_t MPU9250::spi_reg_write(uint8_t reg, uint8_t data) {
esp_err_t ret;
spi_transaction_t trans;
trans.flags = SPI_TRANS_USE_TXDATA;
trans.cmd = 0;
trans.addr = reg & 0x7F;
trans.length = 8;
trans.rxlength = 0;
trans.user = 0;
trans.tx_data[0] = data;
trans.rx_buffer = NULL;
if ( (ret = spi_device_transmit(this->spi, &trans)) )
return ret;
return ESP_OK;
}
void MPU9250::set_gyro_fsr(gyro_fsr fsr) {
if (fsr == GYRO_FSR_NOT_SET)
return;
if (fsr == this->g_fsr)
return;
// gyro FSR config shares the same register with DLPF config so we just update reg value
uint8_t gyro_config;
this->spi_reg_read(this->REGISTERS.GYRO_CONFIG, gyro_config);
this->spi_reg_write(this->REGISTERS.GYRO_CONFIG, gyro_config | fsr);
this->g_fsr = fsr;
switch (this->g_fsr) {
case GYRO_FSR_250:
this->g_mult = 250;
break;
case GYRO_FSR_500:
this->g_mult = 500;
break;
case GYRO_FSR_1000:
this->g_mult = 1000;
break;
case GYRO_FSR_2000:
this->g_mult = 2000;
break;
case GYRO_FSR_NOT_SET:
return;
}
this->g_mult /= std::pow(2, this->ADC_BITS - 1);
}
void MPU9250::set_accel_fsr(accel_fsr fsr) {
if (fsr == ACCEL_FSR_NOT_SET)
return;
if (fsr == this->a_fsr)
return;
this->spi_reg_write(this->REGISTERS.ACCEL_CONFIG, fsr);
this->a_fsr = fsr;
switch (this->a_fsr) {
case ACCEL_FSR_2:
this->a_mult = 2;
break;
case ACCEL_FSR_4:
this->a_mult = 4;
break;
case ACCEL_FSR_8:
this->a_mult = 8;
break;
case ACCEL_FSR_16:
this->a_mult = 16;
break;
case ACCEL_FSR_NOT_SET:
return;
}
this->a_mult /= std::pow(2, this->ADC_BITS - 1);
}
void MPU9250::set_gyro_lpf(gyro_lpf lpf) {
if (lpf == GYRO_LPF_NOT_SET)
return;
if (this->g_lpf == lpf)
return;
uint8_t Fchoice_b;
if (lpf == GYRO_LPF_8800HZ)
Fchoice_b = 0x01;
else if (lpf == GYRO_LPF_3600Hz)
Fchoice_b = 0x02;
else
Fchoice_b = 0x00;
// gyro DLPF config shares the same register with FSR config so we just update reg value
uint8_t gyro_config;
this->spi_reg_read(this->REGISTERS.GYRO_CONFIG, gyro_config);
this->spi_reg_write(this->REGISTERS.GYRO_CONFIG, gyro_config | Fchoice_b);
this->spi_reg_write(this->REGISTERS.CONFIG, lpf);
this->g_lpf = lpf;
}
void MPU9250::set_accel_lpf(accel_lpf lpf) {
if (lpf == ACCEL_LPF_NOT_SET)
return;
if (lpf == this->a_lpf)
return;
uint8_t accel_config2 = lpf;
if (lpf == ACCEL_LPF_1046HZ)
accel_config2 |= 0x08;
this->spi_reg_write(this->REGISTERS.ACCEL_CONFIG2, accel_config2);
this->a_lpf = lpf;
}
void MPU9250::set_sample_rate(uint16_t rate) {
// setting SMPLRT_DIV won't be effective
// 8800 Hz => sample at 32 kHz
// 3600 Hz => sample at 32 kHz
// 250 Hz => sample at 8 kHz
if (this->g_lpf == GYRO_LPF_8800HZ || this->g_lpf == GYRO_LPF_3600Hz || this->g_lpf == GYRO_LPF_250HZ)
return;
uint8_t div = (1000 - rate) / rate;
this->spi_reg_write(this->REGISTERS.SMPLRT_DIV, div);
}
void MPU9250::set_interrupt(bool enable) {
this->spi_reg_write(this->REGISTERS.INT_ENABLE, (enable ? 0x01 : 0x00));
}
void MPU9250::Init() {
esp_err_t ret;
/*this->rx_buffer = (uint8_t*)heap_caps_malloc(40, MALLOC_CAP_32BIT | MALLOC_CAP_DMA);
if (this->rx_buffer == NULL)
std::cout << "alloc error" << std::endl;*/
if ( (ret = this->spi_init()) )
return;
// reset the device
this->spi_reg_write(this->REGISTERS.PWR_MGMT_1, 0x80);
// wait until reset done
uint8_t tmp;
do {
this->spi_reg_read(this->REGISTERS.PWR_MGMT_1, tmp);
} while (tmp & 0x80);
vTaskDelay(1000 / portTICK_PERIOD_MS);
/* should not be needed
this->spi_reg_write(this->REGISTERS.SIGNAL_PATH_RESET, 0x07);
*/
// disable FIFO, I2C master; SPI mode only; reset all signal paths
this->spi_reg_write(this->REGISTERS.USER_CTRL, 0x2F);
// enable all sensors
this->spi_reg_write(this->REGISTERS.PWR_MGMT_2, 0x00);
// check device responding
uint8_t who_am_i;
this->spi_reg_read(this->REGISTERS.WHO_AM_I, who_am_i);
if (who_am_i != 0x71)
return;
this->set_interrupt(false);
// set INT pin active high, push-pull; don't use latched mode, fsync nor I2C bypass
this->spi_reg_write(this->REGISTERS.INT_PIN_CFG, 0x10);
this->set_gyro_fsr(GYRO_FSR_2000);
this->set_gyro_lpf(GYRO_LPF_250HZ);
this->set_accel_fsr(ACCEL_FSR_16);
this->set_accel_lpf(ACCEL_LPF_1046HZ);
this->set_sample_rate(8000);
this->set_interrupt(true);
std::cout << "Init complete" << std::endl;
/*timeval start, end;
gettimeofday(&start, NULL);
//this->spi_regs_read(this->REGISTERS.ACCEL_XOUT_H, 14);
gettimeofday(&end, NULL);
for (int i = 0; i < 14; i++)
std::cout << "data[" << i << "]: " << (int)(this->rx_buffer[i]) << std::endl;
std::cout << "in " << end.tv_sec - start.tv_sec << " s, " << end.tv_usec - start.tv_usec << " us" << std::endl;*/
}
} /* namespace flyhero */
|
Fix MPU9250 spi_reg_write causing StoreProhibited error
|
Fix MPU9250 spi_reg_write causing StoreProhibited error
|
C++
|
mit
|
michprev/flyhero-esp32,michprev/flyhero-esp32
|
d01ad7a42397dc171056434ae981332215b34d5f
|
ITS/ITSSDDGAINda.cxx
|
ITS/ITSSDDGAINda.cxx
|
/*
- Contact: - [email protected]
- Link: - http://www.to.infn.it/~prino/alice/RawData/run11173.date
- Run Type: - PULSER_RUN
- DA Type: - LDC
- Number of events needed: >15
- Input Files: - SDDbase_step1_ddl*c*_sid*.data
- Output Files: - SDDbase_ddl*c*_sid*.data
- Trigger types used:
*/
//////////////////////////////////////////////////////////////////////////////
// Detector Algorithm for analysis of SDD test pulse runs. //
// //
// Produces ASCII and ROOT output files with: //
// 1. anode quality bit //
// 1. Baseline values //
// 2. Raw noise //
// 3. Common mode coefficients //
// 4. Noise corrected for common mode //
// 5. Gain //
// Files are written to FXS //
// //
// Author: F. Prino ([email protected]) //
// //
//////////////////////////////////////////////////////////////////////////////
extern "C" {
#include "daqDA.h"
}
#include "event.h"
#include "monitor.h"
#include <stdio.h>
#include <stdlib.h>
// ROOT includes
#include <TFile.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TSystem.h>
#include <TROOT.h>
#include <TPluginManager.h>
#include <TObjArray.h>
#include <TObjString.h>
#include <TDatime.h>
// AliRoot includes
#include "AliRawReaderDate.h"
#include "AliITSOnlineSDDTP.h"
#include "AliITSRawStreamSDD.h"
#include "AliITSRawStreamSDDCompressed.h"
#ifdef ALI_AMORE
#include <AmoreDA.h>
#endif
/* Main routine
Arguments: list of DATE raw data files
*/
int main(int argc, char **argv) {
int status = 0;
// line added to solve IO problems
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
/* log start of process */
printf("ITS SDD TEST-PULSE algorithm program started\n");
/* check that we got some arguments = list of files */
if (argc<2) {
printf("Wrong number of arguments\n");
return -1;
}
Int_t maxNEvents=15; // maximum number of events to be analyzed
const Int_t kTotDDL=24;
const Int_t kModPerDDL=12;
const Int_t kSides=2;
UInt_t amSamplFreq=40;
UChar_t cdhAttr=0;
gSystem->Exec("rm -f SDDbase_LDC.tar");
AliITSOnlineSDDTP **tpan=new AliITSOnlineSDDTP*[kTotDDL*kModPerDDL*kSides];
TH2F **histo=new TH2F*[kTotDDL*kModPerDDL*kSides];
Bool_t isFilled[kTotDDL*kModPerDDL*kSides];
Bool_t writtenoutput=kFALSE;
Char_t hisnam[20];
for(Int_t iddl=0; iddl<kTotDDL;iddl++){
for(Int_t imod=0; imod<kModPerDDL;imod++){
for(Int_t isid=0;isid<kSides;isid++){
Int_t index=kSides*(kModPerDDL*iddl+imod)+isid;
tpan[index]=new AliITSOnlineSDDTP(iddl,imod,isid,100.);
sprintf(hisnam,"h%02dc%02ds%d",iddl,imod,isid);
histo[index]=new TH2F(hisnam,"",256,-0.5,255.5,256,-0.5,255.5);
isFilled[index]=0;
}
}
}
/* report progress */
daqDA_progressReport(10);
Int_t iev=0,iAnalyzedEv=0;
/* read the data files */
int n;
for (n=1;n<argc;n++) {
status=monitorSetDataSource( argv[n] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* report progress */
/* in this example, indexed on the number of files */
// Progress report inside the event loop as well?
daqDA_progressReport(10+80*n/argc);
/* read the file */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* get next event */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) break; /* end of monitoring file has been reached */
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* retry if got no event */
if (event==NULL) {
break;
}
if(iAnalyzedEv>=maxNEvents) break;
iev++;
/* use event - here, just write event id to result file */
eventT=event->eventType;
switch (event->eventType){
/* START OF RUN */
case START_OF_RUN:
break;
/* END OF RUN */
case END_OF_RUN:
break;
// case PHYSICS_EVENT: // comment this line for test raw data
// break; // comment this line for test raw data
case CALIBRATION_EVENT:
break; // uncomment this line for test raw data
case PHYSICS_EVENT: // uncomment this line for test raw data
printf(" event number = %i \n",iev);
AliRawReader *rawReader = new AliRawReaderDate((void*)event);
rawReader->Reset();
cdhAttr=AliITSRawStreamSDD::ReadBlockAttributes(rawReader);
amSamplFreq=AliITSRawStreamSDD::ReadAMSamplFreqFromCDH(cdhAttr);
AliITSRawStream* s=AliITSRawStreamSDD::CreateRawStreamSDD(rawReader,cdhAttr);
if(!writtenoutput){
printf("Use %s raw stream, sampling frequency %d MHz\n",s->ClassName(),amSamplFreq);
writtenoutput=kTRUE;
}
for(Int_t iddl=0; iddl<kTotDDL;iddl++){
for(Int_t imod=0; imod<kModPerDDL;imod++){
for(Int_t isid=0;isid<kSides;isid++){
Int_t index=kSides*(kModPerDDL*iddl+imod)+isid;
histo[index]->Reset();
}
}
}
while(s->Next()){
Int_t iDDL=rawReader->GetDDLID();
Int_t iCarlos=s->GetCarlosId();
if(s->IsCompletedModule()) continue;
if(s->IsCompletedDDL()) continue;
if(iDDL>=0 && iDDL<kTotDDL){
Int_t index=kSides*(kModPerDDL*iDDL+iCarlos)+s->GetChannel();
histo[index]->Fill(s->GetCoord2(),s->GetCoord1(),s->GetSignal());
isFilled[index]=1;
}
}
delete s;
delete rawReader;
for(Int_t iddl=0; iddl<kTotDDL;iddl++){
for(Int_t imod=0; imod<kModPerDDL;imod++){
for(Int_t isid=0;isid<kSides;isid++){
Int_t index=kSides*(kModPerDDL*iddl+imod)+isid;
if(amSamplFreq==20) tpan[index]->SetLastGoodTB(126);
else tpan[index]->SetLastGoodTB(254);
if(isFilled[index]) tpan[index]->AddEvent(histo[index]);
}
}
}
/* free resources */
iAnalyzedEv++;
free(event);
}
}
}
/* write report */
TDatime time;
TObjString timeinfo(Form("%02d%02d%02d%02d%02d%02d",time.GetYear()-2000,time.GetMonth(),time.GetDay(),time.GetHour(),time.GetMinute(),time.GetSecond()));
printf("Run #%s, received %d calibration events, time %s\n",getenv("DATE_RUN_NUMBER"),iAnalyzedEv,timeinfo.GetString().Data());
/* report progress */
daqDA_progressReport(90);
TObjArray* gainHistos=new TObjArray();
TObjArray* statusHistos=new TObjArray();
Char_t filnam[100],command[120];
for(Int_t iddl=0; iddl<kTotDDL;iddl++){
for(Int_t imod=0; imod<kModPerDDL;imod++){
for(Int_t isid=0;isid<kSides;isid++){
Int_t index=kSides*(kModPerDDL*iddl+imod)+isid;
if(isFilled[index]){
tpan[index]->ValidateAnodes();
tpan[index]->WriteToASCII();
gainHistos->AddLast(tpan[index]->GetGainAnodeHisto());
statusHistos->AddLast(tpan[index]->GetStatusAnodeHisto());
sprintf(filnam,"SDDbase_ddl%02dc%02d_sid%d.data",iddl,imod,isid);
sprintf(command,"tar -rf SDDbase_LDC.tar %s",filnam);
gSystem->Exec(command);
}
}
}
}
FILE *conffil=fopen("fee.conf","w");
fprintf(conffil,"%d\n",amSamplFreq);
fprintf(conffil,"%02X\n",cdhAttr);
fclose(conffil);
gSystem->Exec("tar -rf SDDbase_LDC.tar fee.conf");
status=daqDA_FES_storeFile("./SDDbase_LDC.tar","SDD_Calib");
#ifdef ALI_AMORE
amore::da::AmoreDA amoreDA(amore::da::AmoreDA::kSender);
Int_t statusamore =0;
statusamore += amoreDA.Send("TimeInfo",&timeinfo);
statusamore += amoreDA.Send("Gain",gainHistos);
statusamore += amoreDA.Send("BadChannels",corrnHistos);
if ( statusamore )
printf("Warning: Failed to write Arrays in the AMORE database\n");
else
printf("amoreDA.Send() OK\n");
#else
printf("Warning: SDDGAIN DA not compiled with AMORE support\n");
#endif
TFile *fh=new TFile("SDDgainHistos.root","RECREATE");
gainHistos->Write();
statusHistos->Write();
fh->Close();
/* report progress */
daqDA_progressReport(100);
return status;
}
|
/*
- Contact: - [email protected]
- Link: - http://www.to.infn.it/~prino/alice/RawData/run11173.date
- Run Type: - PULSER_RUN
- DA Type: - LDC
- Number of events needed: >15
- Input Files: - SDDbase_step1_ddl*c*_sid*.data
- Output Files: - SDDbase_ddl*c*_sid*.data
- Trigger types used:
*/
//////////////////////////////////////////////////////////////////////////////
// Detector Algorithm for analysis of SDD test pulse runs. //
// //
// Produces ASCII and ROOT output files with: //
// 1. anode quality bit //
// 1. Baseline values //
// 2. Raw noise //
// 3. Common mode coefficients //
// 4. Noise corrected for common mode //
// 5. Gain //
// Files are written to FXS //
// //
// Author: F. Prino ([email protected]) //
// //
//////////////////////////////////////////////////////////////////////////////
extern "C" {
#include "daqDA.h"
}
#include "event.h"
#include "monitor.h"
#include <stdio.h>
#include <stdlib.h>
// ROOT includes
#include <TFile.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TSystem.h>
#include <TROOT.h>
#include <TPluginManager.h>
#include <TObjArray.h>
#include <TObjString.h>
#include <TDatime.h>
// AliRoot includes
#include "AliRawReaderDate.h"
#include "AliITSOnlineSDDTP.h"
#include "AliITSRawStreamSDD.h"
#include "AliITSRawStreamSDDCompressed.h"
#ifdef ALI_AMORE
#include <AmoreDA.h>
#endif
/* Main routine
Arguments: list of DATE raw data files
*/
int main(int argc, char **argv) {
int status = 0;
// line added to solve IO problems
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
/* log start of process */
printf("ITS SDD TEST-PULSE algorithm program started\n");
/* check that we got some arguments = list of files */
if (argc<2) {
printf("Wrong number of arguments\n");
return -1;
}
Int_t maxNEvents=15; // maximum number of events to be analyzed
const Int_t kTotDDL=24;
const Int_t kModPerDDL=12;
const Int_t kSides=2;
UInt_t amSamplFreq=40;
UChar_t cdhAttr=0;
gSystem->Exec("rm -f SDDbase_LDC.tar");
AliITSOnlineSDDTP **tpan=new AliITSOnlineSDDTP*[kTotDDL*kModPerDDL*kSides];
TH2F **histo=new TH2F*[kTotDDL*kModPerDDL*kSides];
Bool_t isFilled[kTotDDL*kModPerDDL*kSides];
Bool_t writtenoutput=kFALSE;
Char_t hisnam[20];
for(Int_t iddl=0; iddl<kTotDDL;iddl++){
for(Int_t imod=0; imod<kModPerDDL;imod++){
for(Int_t isid=0;isid<kSides;isid++){
Int_t index=kSides*(kModPerDDL*iddl+imod)+isid;
tpan[index]=new AliITSOnlineSDDTP(iddl,imod,isid,100.);
sprintf(hisnam,"h%02dc%02ds%d",iddl,imod,isid);
histo[index]=new TH2F(hisnam,"",256,-0.5,255.5,256,-0.5,255.5);
isFilled[index]=0;
}
}
}
/* report progress */
daqDA_progressReport(10);
Int_t iev=0,iAnalyzedEv=0;
/* read the data files */
int n;
for (n=1;n<argc;n++) {
status=monitorSetDataSource( argv[n] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* report progress */
/* in this example, indexed on the number of files */
// Progress report inside the event loop as well?
daqDA_progressReport(10+80*n/argc);
/* read the file */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* get next event */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) break; /* end of monitoring file has been reached */
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* retry if got no event */
if (event==NULL) {
break;
}
if(iAnalyzedEv>=maxNEvents) break;
iev++;
/* use event - here, just write event id to result file */
eventT=event->eventType;
switch (event->eventType){
/* START OF RUN */
case START_OF_RUN:
break;
/* END OF RUN */
case END_OF_RUN:
break;
// case PHYSICS_EVENT: // comment this line for test raw data
// break; // comment this line for test raw data
case CALIBRATION_EVENT:
break; // uncomment this line for test raw data
case PHYSICS_EVENT: // uncomment this line for test raw data
printf(" event number = %i \n",iev);
AliRawReader *rawReader = new AliRawReaderDate((void*)event);
rawReader->Reset();
cdhAttr=AliITSRawStreamSDD::ReadBlockAttributes(rawReader);
amSamplFreq=AliITSRawStreamSDD::ReadAMSamplFreqFromCDH(cdhAttr);
AliITSRawStream* s=AliITSRawStreamSDD::CreateRawStreamSDD(rawReader,cdhAttr);
if(!writtenoutput){
printf("Use %s raw stream, sampling frequency %d MHz\n",s->ClassName(),amSamplFreq);
writtenoutput=kTRUE;
}
for(Int_t iddl=0; iddl<kTotDDL;iddl++){
for(Int_t imod=0; imod<kModPerDDL;imod++){
for(Int_t isid=0;isid<kSides;isid++){
Int_t index=kSides*(kModPerDDL*iddl+imod)+isid;
histo[index]->Reset();
}
}
}
while(s->Next()){
Int_t iDDL=rawReader->GetDDLID();
Int_t iCarlos=s->GetCarlosId();
if(s->IsCompletedModule()) continue;
if(s->IsCompletedDDL()) continue;
if(iDDL>=0 && iDDL<kTotDDL){
Int_t index=kSides*(kModPerDDL*iDDL+iCarlos)+s->GetChannel();
histo[index]->Fill(s->GetCoord2(),s->GetCoord1(),s->GetSignal());
isFilled[index]=1;
}
}
delete s;
delete rawReader;
for(Int_t iddl=0; iddl<kTotDDL;iddl++){
for(Int_t imod=0; imod<kModPerDDL;imod++){
for(Int_t isid=0;isid<kSides;isid++){
Int_t index=kSides*(kModPerDDL*iddl+imod)+isid;
if(amSamplFreq==20) tpan[index]->SetLastGoodTB(126);
else tpan[index]->SetLastGoodTB(254);
if(isFilled[index]) tpan[index]->AddEvent(histo[index]);
}
}
}
/* free resources */
iAnalyzedEv++;
free(event);
}
}
}
/* write report */
TDatime time;
TObjString timeinfo(Form("%02d%02d%02d%02d%02d%02d",time.GetYear()-2000,time.GetMonth(),time.GetDay(),time.GetHour(),time.GetMinute(),time.GetSecond()));
printf("Run #%s, received %d calibration events, time %s\n",getenv("DATE_RUN_NUMBER"),iAnalyzedEv,timeinfo.GetString().Data());
/* report progress */
daqDA_progressReport(90);
TObjArray* gainHistos=new TObjArray();
TObjArray* statusHistos=new TObjArray();
Char_t filnam[100],command[120];
for(Int_t iddl=0; iddl<kTotDDL;iddl++){
for(Int_t imod=0; imod<kModPerDDL;imod++){
for(Int_t isid=0;isid<kSides;isid++){
Int_t index=kSides*(kModPerDDL*iddl+imod)+isid;
if(isFilled[index]){
tpan[index]->ValidateAnodes();
tpan[index]->WriteToASCII();
gainHistos->AddLast(tpan[index]->GetGainAnodeHisto());
statusHistos->AddLast(tpan[index]->GetStatusAnodeHisto());
sprintf(filnam,"SDDbase_ddl%02dc%02d_sid%d.data",iddl,imod,isid);
sprintf(command,"tar -rf SDDbase_LDC.tar %s",filnam);
gSystem->Exec(command);
}
}
}
}
FILE *conffil=fopen("fee.conf","w");
fprintf(conffil,"%d\n",amSamplFreq);
fprintf(conffil,"%02X\n",cdhAttr);
fclose(conffil);
gSystem->Exec("tar -rf SDDbase_LDC.tar fee.conf");
status=daqDA_FES_storeFile("./SDDbase_LDC.tar","SDD_Calib");
#ifdef ALI_AMORE
amore::da::AmoreDA amoreDA(amore::da::AmoreDA::kSender);
Int_t statusamore =0;
statusamore += amoreDA.Send("TimeInfo",&timeinfo);
statusamore += amoreDA.Send("Gain",gainHistos);
if ( statusamore )
printf("Warning: Failed to write Arrays in the AMORE database\n");
else
printf("amoreDA.Send() OK\n");
#else
printf("Warning: SDDGAIN DA not compiled with AMORE support\n");
#endif
TFile *fh=new TFile("SDDgainHistos.root","RECREATE");
gainHistos->Write();
statusHistos->Write();
fh->Close();
/* report progress */
daqDA_progressReport(100);
return status;
}
|
Fix compilation error in AMORE part (F. Prino)
|
Fix compilation error in AMORE part (F. Prino)
|
C++
|
bsd-3-clause
|
jgrosseo/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,mkrzewic/AliRoot,miranov25/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,alisw/AliRoot,ecalvovi/AliRoot,jgrosseo/AliRoot,jgrosseo/AliRoot,ecalvovi/AliRoot,alisw/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,jgrosseo/AliRoot,shahor02/AliRoot,ALICEHLT/AliRoot,miranov25/AliRoot,miranov25/AliRoot,sebaleh/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,shahor02/AliRoot,coppedis/AliRoot,ALICEHLT/AliRoot,ecalvovi/AliRoot,sebaleh/AliRoot,alisw/AliRoot,miranov25/AliRoot,shahor02/AliRoot,shahor02/AliRoot,coppedis/AliRoot,coppedis/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,jgrosseo/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,ALICEHLT/AliRoot,alisw/AliRoot,mkrzewic/AliRoot,alisw/AliRoot,shahor02/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,alisw/AliRoot,shahor02/AliRoot,mkrzewic/AliRoot,ALICEHLT/AliRoot,mkrzewic/AliRoot,ecalvovi/AliRoot,mkrzewic/AliRoot,coppedis/AliRoot,coppedis/AliRoot,sebaleh/AliRoot,sebaleh/AliRoot,ecalvovi/AliRoot,miranov25/AliRoot,ALICEHLT/AliRoot,sebaleh/AliRoot,alisw/AliRoot
|
e2ec125abfc0f9773a4988ed3ab375b592322c8b
|
main.cpp
|
main.cpp
|
#include <fstream>
#include <iostream>
#include <math.h>
#include "SuperCap.hpp"
#include "DCCon_out.hpp"
#include "LoadApp.hpp"
#include "LionBat.hpp"
#include "DischargeProcess.hpp"
#include "ChargeProcess.hpp"
#include "main.hpp"
#include "powersource.hpp"
using namespace std;
int main(){
supcapacitor sp;
lionbat lb;
loadApplication load;
DischargeProcess dp;
ChargeProcess cp;
sp.SupCapReset();
// sp.SupCapSetQacc(22.91672);
sp.SupCapReconfig(4, 1);
sp.SupCapSetQacc(0.0);
// sp.SupCapSetQacc(1000);
// Set current task info
double vdd = 1.0, idd = 1.0;
double deadline = 10.0, exec_time = 10.0;
load.SetTaskParameters(vdd, idd, deadline, exec_time);
// timer staff
double time_elapsed = 0.0;
int total_time_index = 0, time_index = -1;
int hh = 11, mm = 0, ss = 0;
int start_time_sec = 3600*hh + 60*mm + ss;
int curr_time_sec = start_time_sec;
// powersource
double power_input = 0.0;
// The main loop
while (total_time_index < MAX_TIME_INDEX) {
power_input = powersource_sec(curr_time_sec);
// ChargeProcess
time_index = cp.ChargeProcessOurPolicy(power_input, &sp, &lb, &load);
// time_index = cp.ChargeProcessOptimalVcti(power_input, &sp, &lb, &load);
// DischargeProcess
if (time_index < 0) {
time_index = dp.DischargeProcessOurPolicy(power_input, &sp, &lb, &load);
// time_index = dp.DischargeProcessOptimalVcti(power_input, &sp, &lb, &load);
}
if (time_index < 0) {
cerr << "time_index can not be less than 0" << endl;
break;
}
if (sp.SupCapGetEnergy() < 0)
break;
// Advance the timer
total_time_index += time_index;
time_elapsed += (time_index * min_time_interval);
curr_time_sec += (int)(time_index * min_time_interval);
time_index = -1;
}
#ifdef _COMPLEX_MAIN_
dcconvertOUT dcout;
//powersource
double VCTI = 1.0, powerInput = 1.25, delVCTI = 0;
//DCDC converter
double dccon1_Vin = 0.0, dccon1_Vout = 0.0, dccon1_Iout = 0.0, dccon1_Iin = 0.0, dccon1_Pdcdc = 0.0;
//SuperCap
double sup_Iin = 0.0, sup_Tdur = 0.0, sup_Qacc = 0.0, sup_Vs = 0.0;
double dccon1_energy = 0.0;
bool supcap_reconfig_return = true;
// int charging_phase = 1;
double Prbank = 0.0;
int task = 1;
double task_duration = 2000.0;
string filename1("Result.txt");
string filename2("Process.txt");
FILE *fp1 = fopen(filename1.c_str(),"w");
FILE *fp2 = fopen(filename2.c_str(),"w");
fprintf(fp1,"Isup\t Vsup\t Psup\n");
fprintf(fp2,"VCTI\t Vs_sup\t Vs_dc\t del_VCTI\t Qacc\n");
while(task < 0){
dccon1_Iin = powerInput/VCTI - 1.153;
dccon1_Vin = VCTI;
double current_task_remaining_time = task_duration;
while (current_task_remaining_time > 0) {
/*
if ((charging_phase == 1) && (sp.SupCapGetEnergy() > 20)) {
charging_phase = 2;
sp.SupCapReconfig(2, 2);
}
if ((charging_phase == 2) && (sp.SupCapGetEnergy() > 90)) {
charging_phase = 3;
sp.SupCapReconfig(1, 4);
}
*/
dcout.ConverterModel_SupCap(dccon1_Vin, dccon1_Iin, dccon1_Vout, dccon1_Iout, dccon1_Pdcdc, &sp);
sup_Iin = dccon1_Iout;
sup_Tdur = min_time_interval;
while ((dccon1_Vout > dccon1_Vin) && supcap_reconfig_return) {
supcap_reconfig_return = sp.SupCapOperating(sup_Iin, VCTI, delVCTI);
dcout.ConverterModel_SupCap(dccon1_Vin, dccon1_Iin, dccon1_Vout, dccon1_Iout, dccon1_Pdcdc, &sp);
}
// If the supercapacitor can not reconfigure anymore, abort
/*
if (!supcap_reconfig_return) {
break;
}
*/
Prbank = dccon1_Iout * dccon1_Iout * sp.SupCapGetRacc();
fprintf(fp1,"%f\t%f\t%f\t%f\n", dccon1_Iout, dccon1_Vout, dccon1_Pdcdc, Prbank);
sp.SupCapCharge(sup_Iin, sup_Tdur, sup_Vs, sup_Qacc);
delVCTI = fabs(VCTI - sup_Vs);
fprintf(fp2, "%f\t%f\t%f\t%f\t%f\n", VCTI, sup_Vs, dccon1_Vout, delVCTI, sp.SupCapGetQacc());
// sp.SupCapOperating(sup_Iin, VCTI, delVCTI);
current_task_remaining_time -= min_time_interval;
time_elapsed += min_time_interval;
++time_index;
if (time_index > MAX_TIME_INDEX)
break;
dccon1_energy += dccon1_Pdcdc * min_time_interval;
}
/*
if (!supcap_reconfig_return) {
break;
}
*/
task--;
}
fclose(fp1);
fclose(fp2);
printf("energy consumed is %f, time elapsed is %f\n", dccon1_energy, time_elapsed);
#endif
return 0;
}
|
#include <fstream>
#include <iostream>
#include <math.h>
#include "SuperCap.hpp"
#include "DCCon_out.hpp"
#include "LoadApp.hpp"
#include "LionBat.hpp"
#include "DischargeProcess.hpp"
#include "ChargeProcess.hpp"
#include "main.hpp"
#include "powersource.hpp"
using namespace std;
int main(){
supcapacitor sp;
lionbat lb;
loadApplication load;
DischargeProcess dp;
ChargeProcess cp;
sp.SupCapReset();
// sp.SupCapSetQacc(22.91672);
sp.SupCapReconfig(4, 1);
sp.SupCapSetQacc(0.0);
// sp.SupCapSetQacc(1000);
// Set current task info
double vdd = 1.0, idd = 1.0;
double deadline = 10.0, exec_time = 10.0;
load.SetTaskParameters(vdd, idd, deadline, exec_time);
// timer staff
double time_elapsed = 0.0;
int total_time_index = 0, time_index = -1;
int hh = 17, mm = 0, ss = 0;
int start_time_sec = 3600*hh + 60*mm + ss;
int curr_time_sec = start_time_sec;
// powersource
double power_input = 0.0;
// The main loop
while (total_time_index < MAX_TIME_INDEX) {
// power_input = powersource_sec(curr_time_sec);
power_input = 1.75;
if ((total_time_index/100) % 2 == 1) {
// if (total_time_index == 3000) {
load.SetTaskParameters(vdd, 1.3, deadline, exec_time);
}
if ((total_time_index/100) % 2 == 0) {
// if (total_time_index == 0) {
load.SetTaskParameters(vdd, 1.0, deadline, exec_time);
}
// ChargeProcess
time_index = cp.ChargeProcessOurPolicy(power_input, &sp, &lb, &load);
// time_index = cp.ChargeProcessOptimalVcti(power_input, &sp, &lb, &load);
// DischargeProcess
if (time_index < 0) {
// time_index = dp.DischargeProcessOurPolicy(power_input, &sp, &lb, &load);
// time_index = dp.DischargeProcessOptimalVcti(power_input, &sp, &lb, &load);
}
if (time_index < 0) {
cerr << "time_index can not be less than 0" << endl;
break;
}
if (sp.SupCapGetEnergy() < 0)
break;
// Advance the timer
total_time_index += time_index;
time_elapsed += (time_index * min_time_interval);
curr_time_sec += (int)(time_index * min_time_interval);
time_index = -1;
}
#ifdef _COMPLEX_MAIN_
dcconvertOUT dcout;
//powersource
double VCTI = 1.0, powerInput = 1.25, delVCTI = 0;
//DCDC converter
double dccon1_Vin = 0.0, dccon1_Vout = 0.0, dccon1_Iout = 0.0, dccon1_Iin = 0.0, dccon1_Pdcdc = 0.0;
//SuperCap
double sup_Iin = 0.0, sup_Tdur = 0.0, sup_Qacc = 0.0, sup_Vs = 0.0;
double dccon1_energy = 0.0;
bool supcap_reconfig_return = true;
// int charging_phase = 1;
double Prbank = 0.0;
int task = 1;
double task_duration = 2000.0;
string filename1("Result.txt");
string filename2("Process.txt");
FILE *fp1 = fopen(filename1.c_str(),"w");
FILE *fp2 = fopen(filename2.c_str(),"w");
fprintf(fp1,"Isup\t Vsup\t Psup\n");
fprintf(fp2,"VCTI\t Vs_sup\t Vs_dc\t del_VCTI\t Qacc\n");
while(task < 0){
dccon1_Iin = powerInput/VCTI - 1.153;
dccon1_Vin = VCTI;
double current_task_remaining_time = task_duration;
while (current_task_remaining_time > 0) {
/*
if ((charging_phase == 1) && (sp.SupCapGetEnergy() > 20)) {
charging_phase = 2;
sp.SupCapReconfig(2, 2);
}
if ((charging_phase == 2) && (sp.SupCapGetEnergy() > 90)) {
charging_phase = 3;
sp.SupCapReconfig(1, 4);
}
*/
dcout.ConverterModel_SupCap(dccon1_Vin, dccon1_Iin, dccon1_Vout, dccon1_Iout, dccon1_Pdcdc, &sp);
sup_Iin = dccon1_Iout;
sup_Tdur = min_time_interval;
while ((dccon1_Vout > dccon1_Vin) && supcap_reconfig_return) {
supcap_reconfig_return = sp.SupCapOperating(sup_Iin, VCTI, delVCTI);
dcout.ConverterModel_SupCap(dccon1_Vin, dccon1_Iin, dccon1_Vout, dccon1_Iout, dccon1_Pdcdc, &sp);
}
// If the supercapacitor can not reconfigure anymore, abort
/*
if (!supcap_reconfig_return) {
break;
}
*/
Prbank = dccon1_Iout * dccon1_Iout * sp.SupCapGetRacc();
fprintf(fp1,"%f\t%f\t%f\t%f\n", dccon1_Iout, dccon1_Vout, dccon1_Pdcdc, Prbank);
sp.SupCapCharge(sup_Iin, sup_Tdur, sup_Vs, sup_Qacc);
delVCTI = fabs(VCTI - sup_Vs);
fprintf(fp2, "%f\t%f\t%f\t%f\t%f\n", VCTI, sup_Vs, dccon1_Vout, delVCTI, sp.SupCapGetQacc());
// sp.SupCapOperating(sup_Iin, VCTI, delVCTI);
current_task_remaining_time -= min_time_interval;
time_elapsed += min_time_interval;
++time_index;
if (time_index > MAX_TIME_INDEX)
break;
dccon1_energy += dccon1_Pdcdc * min_time_interval;
}
/*
if (!supcap_reconfig_return) {
break;
}
*/
task--;
}
fclose(fp1);
fclose(fp2);
printf("energy consumed is %f, time elapsed is %f\n", dccon1_energy, time_elapsed);
#endif
return 0;
}
|
Add different power charging status
|
Add different power charging status
|
C++
|
mit
|
eroicaleo/HEES,eroicaleo/HEES,eroicaleo/HEES,eroicaleo/HEES,eroicaleo/HEES,eroicaleo/HEES
|
68deff506c4c43e4872fcf5b80d273b0bc723755
|
main.cpp
|
main.cpp
|
#include <iostream>
#include <cstddef> // std::size_t
#include <cassert>
#include "common.h"
#include GLUT_INCLUDE
#include "Gyroid.h"
#include "Sphere.h"
#include "Decimate.h"
GLuint preDecimate(const Isosurface& surface,
float xMin, float xMax,
float yMin, float yMax,
float zMin, float zMax,
float isolevel,
std::size_t resolution)
{
GLuint list = glGenLists(1);
glNewList(list, GL_COMPILE);
decimate(surface, xMin, xMax, yMin, yMax, zMin, zMax, isolevel, resolution);
glEndList();
return list;
}
static float rotX;
static float rotY;
static struct { int x, y; } mouse = { -1, -1 };
static GLuint list;
void render()
{
glClearColor(0, 0.3, 0.6, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_shininess[] = { 50.0 };
GLfloat light_position[] = { 1.0, 1.0, -1.0, 0.0 };
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_SMOOTH);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glPushMatrix();
glRotatef(rotY, 1, 0, 0);
glRotatef(rotX, 0, 1, 0);
glutSolidCube(0.15);
glPopMatrix();
glPushMatrix();
glRotatef(rotY, 1, 0, 0);
glRotatef(rotX, 0, 1, 0);
glScalef(0.1, 0.1, 0.1);
glCallList(list);
glPopMatrix();
glutSwapBuffers();
}
void changeSize(int w, int h)
{
// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h == 0)
h = 1;
float ratio = 1.0* w / h;
// Use the Projection Matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
// Set the correct perspective.
gluPerspective(45, ratio, 1, 1000);
// Get Back to the Modelview
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Set up the camera
gluLookAt(0, 0, -3, 0, 0, 0, 0, 1, 0);
}
void mouseDown(int button, int state, int x, int y)
{
mouse.x = x;
mouse.y = y;
}
void mouseDragged(int x, int y)
{
float dx = x - mouse.x;
float dy = y - mouse.y;
rotX += dx / 10;
rotY -= dy / 10;
mouse.x = x;
mouse.y = y;
glutPostRedisplay();
}
void init()
{
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glEnable(GL_AUTO_NORMAL);
glEnable(GL_NORMALIZE);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
//Sphere surface;
Gyroid surface;
list = preDecimate(surface, -5, 5, -5, 5, -5, 5, -1, 30);
}
int main (int argc, char * argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(800, 600);
glutCreateWindow("Volume Rendering");
init();
glutDisplayFunc(render);
glutReshapeFunc(changeSize);
glutMouseFunc(mouseDown);
glutMotionFunc(mouseDragged);
glutMainLoop();
return 0;
}
|
#include <iostream>
#include <cstddef> // std::size_t
#include <cassert>
#include "common.h"
#include GLUT_INCLUDE
#include "Gyroid.h"
#include "Sphere.h"
#include "Decimate.h"
GLuint preDecimate(const Isosurface& surface,
float xMin, float xMax,
float yMin, float yMax,
float zMin, float zMax,
float isolevel,
std::size_t resolution)
{
GLuint list = glGenLists(1);
glNewList(list, GL_COMPILE);
decimate(surface, xMin, xMax, yMin, yMax, zMin, zMax, isolevel, resolution);
glEndList();
return list;
}
static float rotX;
static float rotY;
static bool mouseInitialized = false;
static struct { int x, y; } mouse;
static GLuint list;
void render()
{
glClearColor(0, 0.3, 0.6, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat mat_shininess[] = { 50.0 };
GLfloat light_position[] = { 1.0, 1.0, -1.0, 0.0 };
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_SMOOTH);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glPushMatrix();
glRotatef(rotY, 1, 0, 0);
glRotatef(rotX, 0, 1, 0);
glutSolidCube(0.15);
glPopMatrix();
glPushMatrix();
glRotatef(rotY, 1, 0, 0);
glRotatef(rotX, 0, 1, 0);
glScalef(0.1, 0.1, 0.1);
glCallList(list);
glPopMatrix();
glutSwapBuffers();
}
void changeSize(int w, int h)
{
// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h == 0)
h = 1;
float ratio = 1.0* w / h;
// Use the Projection Matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
// Set the correct perspective.
gluPerspective(45, ratio, 1, 1000);
// Get Back to the Modelview
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// Set up the camera
gluLookAt(0, 0, -3, 0, 0, 0, 0, 1, 0);
}
void mouseDown(int button, int state, int x, int y)
{
mouse.x = x;
mouse.y = y;
mouseInitialized = true;
}
void mouseDragged(int x, int y)
{
if (mouseInitialized) {
float dx = x - mouse.x;
float dy = y - mouse.y;
rotX += dx / 10;
rotY -= dy / 10;
}
mouse.x = x;
mouse.y = y;
mouseInitialized = true;
glutPostRedisplay();
}
void init()
{
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glEnable(GL_AUTO_NORMAL);
glEnable(GL_NORMALIZE);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
//Sphere surface;
Gyroid surface;
list = preDecimate(surface, -5, 5, -5, 5, -5, 5, -1, 30);
}
int main (int argc, char * argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGBA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(800, 600);
glutCreateWindow("Volume Rendering");
init();
glutDisplayFunc(render);
glutReshapeFunc(changeSize);
glutMouseFunc(mouseDown);
glutMotionFunc(mouseDragged);
glutMainLoop();
return 0;
}
|
Improve mouse handling when the program starts
|
Improve mouse handling when the program starts
|
C++
|
mit
|
Calvin-L/MarchingTetrahedrons,Calvin-L/MarchingTetrahedrons
|
2d4c77a6f1371bf93d9e17de94d6ef96e0732aff
|
src/tests/auth_stub.cpp
|
src/tests/auth_stub.cpp
|
/*
* The MIT License (MIT)
*
* Copyright (c) <2016> <Stephan Gatzka>
*
* 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 <stdbool.h>
#include "authenticate.h"
extern "C" {
bool credentials_ok(const char *user, char *passwd)
{
(void)user;
(void)passwd;
return true;
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (c) <2016> <Stephan Gatzka>
*
* 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 <stdbool.h>
#include "authenticate.h"
extern "C" {
const cJSON *credentials_ok(const char *user, char *passwd)
{
(void)user;
(void)passwd;
return NULL;
}
}
|
Correct function prototype of stub function.
|
Correct function prototype of stub function.
|
C++
|
mit
|
gatzka/cjet,mloy/cjet,gatzka/cjet,mloy/cjet,gatzka/cjet,gatzka/cjet,mloy/cjet,gatzka/cjet,mloy/cjet,mloy/cjet
|
99fc78f2cae591a81a91cabb94f7cf04ae68c5d3
|
webkit/port/bindings/v8/V8WorkerCustom.cpp
|
webkit/port/bindings/v8/V8WorkerCustom.cpp
|
// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#if ENABLE(WORKERS)
#include "v8_binding.h"
#include "v8_custom.h"
#include "v8_proxy.h"
#include "ExceptionCode.h"
#include "Frame.h"
#include "MessagePort.h"
#include "V8Document.h"
#include "V8HTMLDocument.h"
#include "V8ObjectEventListener.h"
#include "Worker.h"
#include "WorkerContextExecutionProxy.h"
namespace WebCore {
CALLBACK_FUNC_DECL(WorkerConstructor) {
INC_STATS(L"DOM.Worker.Constructor");
if (!WorkerContextExecutionProxy::isWebWorkersEnabled()) {
V8Proxy::ThrowError(V8Proxy::SYNTAX_ERROR, "Worker is not enabled.");
return v8::Undefined();
}
if (!args.IsConstructCall()) {
V8Proxy::ThrowError(V8Proxy::TYPE_ERROR,
"DOM object constructor cannot be called as a function.");
return v8::Undefined();
}
if (args.Length() == 0) {
V8Proxy::ThrowError(V8Proxy::SYNTAX_ERROR, "Not enough arguments");
return v8::Undefined();
}
v8::TryCatch try_catch;
v8::Handle<v8::String> script_url = args[0]->ToString();
if (try_catch.HasCaught()) {
v8::ThrowException(try_catch.Exception());
return v8::Undefined();
}
if (script_url.IsEmpty()) {
return v8::Undefined();
}
// Get the document.
Frame* frame = V8Proxy::retrieveFrame();
if (!frame)
return v8::Undefined();
Document* document = frame->document();
// Create the worker object.
// Note: it's OK to let this RefPtr go out of scope because we also call
// SetDOMWrapper(), which effectively holds a reference to obj.
ExceptionCode ec = 0;
RefPtr<Worker> obj = Worker::create(
ToWebCoreString(script_url), document, ec);
// Setup the standard wrapper object internal fields.
v8::Handle<v8::Object> wrapper_object = args.Holder();
V8Proxy::SetDOMWrapper(
wrapper_object, V8ClassIndex::WORKER, obj.get());
obj->ref();
V8Proxy::SetJSWrapperForActiveDOMObject(
obj.get(), v8::Persistent<v8::Object>::New(wrapper_object));
return wrapper_object;
}
// TODO(mbelshe) - merge these with XHR's CreateHiddenXHRDependency
// Use an array to hold dependents. It works like a ref-counted scheme.
// A value can be added more than once to the xhr object.
static void CreateHiddenDependency(v8::Local<v8::Object> object,
v8::Local<v8::Value> value) {
ASSERT(V8Proxy::GetDOMWrapperType(object) ==
V8ClassIndex::WORKER);
v8::Local<v8::Value> cache =
object->GetInternalField(V8Custom::kWorkerRequestCacheIndex);
if (cache->IsNull() || cache->IsUndefined()) {
cache = v8::Array::New();
object->SetInternalField(V8Custom::kWorkerRequestCacheIndex, cache);
}
v8::Local<v8::Array> cache_array = v8::Local<v8::Array>::Cast(cache);
cache_array->Set(v8::Integer::New(cache_array->Length()), value);
}
static void RemoveHiddenDependency(v8::Local<v8::Object> object,
v8::Local<v8::Value> value) {
ASSERT(V8Proxy::GetDOMWrapperType(object) == V8ClassIndex::WORKER);
v8::Local<v8::Value> cache =
object->GetInternalField(V8Custom::kWorkerRequestCacheIndex);
ASSERT(cache->IsArray());
v8::Local<v8::Array> cache_array = v8::Local<v8::Array>::Cast(cache);
for (int i = cache_array->Length() - 1; i >= 0; i--) {
v8::Local<v8::Value> cached = cache_array->Get(v8::Integer::New(i));
if (cached->StrictEquals(value)) {
cache_array->Delete(i);
return;
}
}
// We should only get here if we try to remove an event listener that was
// never added.
}
ACCESSOR_GETTER(WorkerOnmessage) {
INC_STATS(L"DOM.Worker.onmessage._get");
Worker* imp = V8Proxy::ToNativeObject<Worker>(
V8ClassIndex::WORKER, info.Holder());
if (imp->onmessage()) {
V8ObjectEventListener* listener =
static_cast<V8ObjectEventListener*>(imp->onmessage());
v8::Local<v8::Object> v8_listener = listener->getListenerObject();
return v8_listener;
}
return v8::Undefined();
}
ACCESSOR_SETTER(WorkerOnmessage) {
INC_STATS(L"DOM.Worker.onmessage._set");
Worker* imp = V8Proxy::ToNativeObject<Worker>(
V8ClassIndex::WORKER, info.Holder());
V8ObjectEventListener* old_listener =
static_cast<V8ObjectEventListener*>(imp->onmessage());
if (value->IsNull()) {
if (old_listener) {
v8::Local<v8::Object> old_v8_listener = old_listener->getListenerObject();
RemoveHiddenDependency(info.Holder(), old_v8_listener);
}
// Clear the listener
imp->setOnmessage(0);
} else {
V8Proxy* proxy = V8Proxy::retrieve(imp->scriptExecutionContext());
if (!proxy)
return;
RefPtr<EventListener> listener =
proxy->FindOrCreateObjectEventListener(value, false);
if (listener) {
if (old_listener) {
v8::Local<v8::Object> old_v8_listener =
old_listener->getListenerObject();
RemoveHiddenDependency(info.Holder(), old_v8_listener);
}
imp->setOnmessage(listener);
CreateHiddenDependency(info.Holder(), value);
}
}
}
ACCESSOR_GETTER(WorkerOnerror) {
INC_STATS(L"DOM.Worker.onerror._get");
Worker* imp = V8Proxy::ToNativeObject<Worker>(
V8ClassIndex::WORKER, info.Holder());
if (imp->onerror()) {
V8ObjectEventListener* listener =
static_cast<V8ObjectEventListener*>(imp->onerror());
v8::Local<v8::Object> v8_listener = listener->getListenerObject();
return v8_listener;
}
return v8::Undefined();
}
ACCESSOR_SETTER(WorkerOnerror) {
INC_STATS(L"DOM.Worker.onerror._set");
Worker* imp = V8Proxy::ToNativeObject<Worker>(
V8ClassIndex::WORKER, info.Holder());
V8ObjectEventListener* old_listener =
static_cast<V8ObjectEventListener*>(imp->onerror());
if (value->IsNull()) {
if (old_listener) {
v8::Local<v8::Object> old_v8_listener =
old_listener->getListenerObject();
RemoveHiddenDependency(info.Holder(), old_v8_listener);
}
// Clear the listener
imp->setOnerror(0);
} else {
V8Proxy* proxy = V8Proxy::retrieve(imp->scriptExecutionContext());
if (!proxy)
return;
RefPtr<EventListener> listener =
proxy->FindOrCreateObjectEventListener(value, false);
if (listener) {
if (old_listener) {
v8::Local<v8::Object> old_v8_listener = old_listener->getListenerObject();
RemoveHiddenDependency(info.Holder(), old_v8_listener);
}
imp->setOnerror(listener);
CreateHiddenDependency(info.Holder(), value);
}
}
}
CALLBACK_FUNC_DECL(WorkerAddEventListener) {
INC_STATS(L"DOM.Worker.addEventListener()");
Worker* imp = V8Proxy::ToNativeObject<Worker>(
V8ClassIndex::WORKER, args.Holder());
V8Proxy* proxy = V8Proxy::retrieve(imp->scriptExecutionContext());
if (!proxy)
return v8::Undefined();
RefPtr<EventListener> listener =
proxy->FindOrCreateObjectEventListener(args[1], false);
if (listener) {
String type = ToWebCoreString(args[0]);
bool useCapture = args[2]->BooleanValue();
imp->addEventListener(type, listener, useCapture);
CreateHiddenDependency(args.Holder(), args[1]);
}
return v8::Undefined();
}
CALLBACK_FUNC_DECL(WorkerRemoveEventListener) {
INC_STATS(L"DOM.Worker.removeEventListener()");
Worker* imp = V8Proxy::ToNativeObject<Worker>(
V8ClassIndex::WORKER, args.Holder());
V8Proxy* proxy = V8Proxy::retrieve(imp->scriptExecutionContext());
if (!proxy)
return v8::Undefined(); // probably leaked
RefPtr<EventListener> listener =
proxy->FindObjectEventListener(args[1], false);
if (listener) {
String type = ToWebCoreString(args[0]);
bool useCapture = args[2]->BooleanValue();
imp->removeEventListener(type, listener.get(), useCapture);
RemoveHiddenDependency(args.Holder(), args[1]);
}
return v8::Undefined();
}
} // namespace WebCore
#endif // ENABLE(WORKERS)
|
// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#if ENABLE(WORKERS)
#include "v8_binding.h"
#include "v8_custom.h"
#include "v8_proxy.h"
#include "ExceptionCode.h"
#include "Frame.h"
#include "MessagePort.h"
#include "V8Document.h"
#include "V8HTMLDocument.h"
#include "V8ObjectEventListener.h"
#include "Worker.h"
#include "WorkerContext.h"
#include "WorkerContextExecutionProxy.h"
namespace WebCore {
CALLBACK_FUNC_DECL(WorkerConstructor) {
INC_STATS(L"DOM.Worker.Constructor");
if (!WorkerContextExecutionProxy::isWebWorkersEnabled()) {
V8Proxy::ThrowError(V8Proxy::SYNTAX_ERROR, "Worker is not enabled.");
return v8::Undefined();
}
if (!args.IsConstructCall()) {
V8Proxy::ThrowError(V8Proxy::TYPE_ERROR,
"DOM object constructor cannot be called as a function.");
return v8::Undefined();
}
if (args.Length() == 0) {
V8Proxy::ThrowError(V8Proxy::SYNTAX_ERROR, "Not enough arguments");
return v8::Undefined();
}
v8::TryCatch try_catch;
v8::Handle<v8::String> script_url = args[0]->ToString();
if (try_catch.HasCaught()) {
v8::ThrowException(try_catch.Exception());
return v8::Undefined();
}
if (script_url.IsEmpty()) {
return v8::Undefined();
}
// Get the script execution context.
ScriptExecutionContext* context = 0;
WorkerContextExecutionProxy* proxy = WorkerContextExecutionProxy::retrieve();
if (proxy)
context = proxy->workerContext();
else {
Frame* frame = V8Proxy::retrieveFrame();
if (!frame)
return v8::Undefined();
context = frame->document();
}
// Create the worker object.
// Note: it's OK to let this RefPtr go out of scope because we also call
// SetDOMWrapper(), which effectively holds a reference to obj.
ExceptionCode ec = 0;
RefPtr<Worker> obj = Worker::create(
ToWebCoreString(script_url), context, ec);
// Setup the standard wrapper object internal fields.
v8::Handle<v8::Object> wrapper_object = args.Holder();
V8Proxy::SetDOMWrapper(
wrapper_object, V8ClassIndex::WORKER, obj.get());
obj->ref();
V8Proxy::SetJSWrapperForActiveDOMObject(
obj.get(), v8::Persistent<v8::Object>::New(wrapper_object));
return wrapper_object;
}
// TODO(mbelshe) - merge these with XHR's CreateHiddenXHRDependency
// Use an array to hold dependents. It works like a ref-counted scheme.
// A value can be added more than once to the xhr object.
static void CreateHiddenDependency(v8::Local<v8::Object> object,
v8::Local<v8::Value> value) {
ASSERT(V8Proxy::GetDOMWrapperType(object) ==
V8ClassIndex::WORKER);
v8::Local<v8::Value> cache =
object->GetInternalField(V8Custom::kWorkerRequestCacheIndex);
if (cache->IsNull() || cache->IsUndefined()) {
cache = v8::Array::New();
object->SetInternalField(V8Custom::kWorkerRequestCacheIndex, cache);
}
v8::Local<v8::Array> cache_array = v8::Local<v8::Array>::Cast(cache);
cache_array->Set(v8::Integer::New(cache_array->Length()), value);
}
static void RemoveHiddenDependency(v8::Local<v8::Object> object,
v8::Local<v8::Value> value) {
ASSERT(V8Proxy::GetDOMWrapperType(object) == V8ClassIndex::WORKER);
v8::Local<v8::Value> cache =
object->GetInternalField(V8Custom::kWorkerRequestCacheIndex);
ASSERT(cache->IsArray());
v8::Local<v8::Array> cache_array = v8::Local<v8::Array>::Cast(cache);
for (int i = cache_array->Length() - 1; i >= 0; i--) {
v8::Local<v8::Value> cached = cache_array->Get(v8::Integer::New(i));
if (cached->StrictEquals(value)) {
cache_array->Delete(i);
return;
}
}
// We should only get here if we try to remove an event listener that was
// never added.
}
ACCESSOR_GETTER(WorkerOnmessage) {
INC_STATS(L"DOM.Worker.onmessage._get");
Worker* imp = V8Proxy::ToNativeObject<Worker>(
V8ClassIndex::WORKER, info.Holder());
if (imp->onmessage()) {
V8ObjectEventListener* listener =
static_cast<V8ObjectEventListener*>(imp->onmessage());
v8::Local<v8::Object> v8_listener = listener->getListenerObject();
return v8_listener;
}
return v8::Undefined();
}
ACCESSOR_SETTER(WorkerOnmessage) {
INC_STATS(L"DOM.Worker.onmessage._set");
Worker* imp = V8Proxy::ToNativeObject<Worker>(
V8ClassIndex::WORKER, info.Holder());
V8ObjectEventListener* old_listener =
static_cast<V8ObjectEventListener*>(imp->onmessage());
if (value->IsNull()) {
if (old_listener) {
v8::Local<v8::Object> old_v8_listener = old_listener->getListenerObject();
RemoveHiddenDependency(info.Holder(), old_v8_listener);
}
// Clear the listener
imp->setOnmessage(0);
} else {
V8Proxy* proxy = V8Proxy::retrieve(imp->scriptExecutionContext());
if (!proxy)
return;
RefPtr<EventListener> listener =
proxy->FindOrCreateObjectEventListener(value, false);
if (listener) {
if (old_listener) {
v8::Local<v8::Object> old_v8_listener =
old_listener->getListenerObject();
RemoveHiddenDependency(info.Holder(), old_v8_listener);
}
imp->setOnmessage(listener);
CreateHiddenDependency(info.Holder(), value);
}
}
}
ACCESSOR_GETTER(WorkerOnerror) {
INC_STATS(L"DOM.Worker.onerror._get");
Worker* imp = V8Proxy::ToNativeObject<Worker>(
V8ClassIndex::WORKER, info.Holder());
if (imp->onerror()) {
V8ObjectEventListener* listener =
static_cast<V8ObjectEventListener*>(imp->onerror());
v8::Local<v8::Object> v8_listener = listener->getListenerObject();
return v8_listener;
}
return v8::Undefined();
}
ACCESSOR_SETTER(WorkerOnerror) {
INC_STATS(L"DOM.Worker.onerror._set");
Worker* imp = V8Proxy::ToNativeObject<Worker>(
V8ClassIndex::WORKER, info.Holder());
V8ObjectEventListener* old_listener =
static_cast<V8ObjectEventListener*>(imp->onerror());
if (value->IsNull()) {
if (old_listener) {
v8::Local<v8::Object> old_v8_listener =
old_listener->getListenerObject();
RemoveHiddenDependency(info.Holder(), old_v8_listener);
}
// Clear the listener
imp->setOnerror(0);
} else {
V8Proxy* proxy = V8Proxy::retrieve(imp->scriptExecutionContext());
if (!proxy)
return;
RefPtr<EventListener> listener =
proxy->FindOrCreateObjectEventListener(value, false);
if (listener) {
if (old_listener) {
v8::Local<v8::Object> old_v8_listener = old_listener->getListenerObject();
RemoveHiddenDependency(info.Holder(), old_v8_listener);
}
imp->setOnerror(listener);
CreateHiddenDependency(info.Holder(), value);
}
}
}
CALLBACK_FUNC_DECL(WorkerAddEventListener) {
INC_STATS(L"DOM.Worker.addEventListener()");
Worker* imp = V8Proxy::ToNativeObject<Worker>(
V8ClassIndex::WORKER, args.Holder());
V8Proxy* proxy = V8Proxy::retrieve(imp->scriptExecutionContext());
if (!proxy)
return v8::Undefined();
RefPtr<EventListener> listener =
proxy->FindOrCreateObjectEventListener(args[1], false);
if (listener) {
String type = ToWebCoreString(args[0]);
bool useCapture = args[2]->BooleanValue();
imp->addEventListener(type, listener, useCapture);
CreateHiddenDependency(args.Holder(), args[1]);
}
return v8::Undefined();
}
CALLBACK_FUNC_DECL(WorkerRemoveEventListener) {
INC_STATS(L"DOM.Worker.removeEventListener()");
Worker* imp = V8Proxy::ToNativeObject<Worker>(
V8ClassIndex::WORKER, args.Holder());
V8Proxy* proxy = V8Proxy::retrieve(imp->scriptExecutionContext());
if (!proxy)
return v8::Undefined(); // probably leaked
RefPtr<EventListener> listener =
proxy->FindObjectEventListener(args[1], false);
if (listener) {
String type = ToWebCoreString(args[0]);
bool useCapture = args[2]->BooleanValue();
imp->removeEventListener(type, listener.get(), useCapture);
RemoveHiddenDependency(args.Holder(), args[1]);
}
return v8::Undefined();
}
} // namespace WebCore
#endif // ENABLE(WORKERS)
|
Fix worker constructor so that nested worker can be created. Review URL: http://codereview.chromium.org/67093
|
Fix worker constructor so that nested worker can be created.
Review URL: http://codereview.chromium.org/67093
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@13619 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
902c97ceda8f32d77fafd8de978fe1128ff20bc4
|
code/Valuations.cpp
|
code/Valuations.cpp
|
#include "Valuations.h"
#include <iostream>
namespace NF
{
std::vector<double> generate_valuations
(const BooleanLattice& bl, DNest4::RNG& rng)
{
std::vector<double> v(bl.size());
for(size_t i=0; i<v.size(); ++i)
v[i] = 1000.0*rng.randn();
return v;
}
std::vector<double> generate_good_valuations
(const BooleanLattice& bl, DNest4::RNG& rng, bool fidelity_matters)
{
std::vector<double> v;
// Generate valuations until they satisfy order (and optionally, fidelity)
while(true)
{
v = generate_valuations(bl, rng);
BLV blv(bl, v);
if(check_order(blv))
{
if((!fidelity_matters) || check_fidelity(blv))
break;
}
}
return v;
}
bool check_fidelity(const BLV& blv)
{
// Unpack tuple
auto& bl = std::get<0>(blv);
auto& valuations = std::get<1>(blv);
// Loop over all pairs of statements
for(size_t i=0; i<bl.size(); ++i)
{
for(size_t j=0; j<bl.size(); ++j)
{
// Valuations must encode implication.
if(bl.implies(i, j) && valuations[j] < valuations[i])
return false;
}
}
return true;
}
bool check_order(const BLV& blv)
{
// Unpack tuple
auto& bl = std::get<0>(blv);
auto& v = std::get<1>(blv);
// Loop over all triples, but only bother with disjoint triples
for(size_t i=0; i<bl.size(); ++i)
for(size_t j=0; j<bl.size(); ++j)
for(size_t k=0; k<bl.size(); ++k)
if(bl.disjoint(i, j, k))
if(v[i] > v[j])
if(v[bl.join(i, k)] <= v[bl.join(j, k)])
return false;
return true;
}
bool check_sum_rule(const BLV& blv)
{
return true;
}
// Output a boolean lattice with valuations.
std::ostream& operator << (std::ostream& out, const BLV& blv)
{
// Unpack tuple
auto& bl = std::get<0>(blv);
auto& valuations = std::get<1>(blv);
// Output the lattice
out<<bl;
// Output the values
for(double v: valuations)
out<<v<<' ';
return out;
}
} // namespace NF
|
#include "Valuations.h"
#include <iostream>
namespace NF
{
std::vector<double> generate_valuations
(const BooleanLattice& bl, DNest4::RNG& rng)
{
std::vector<double> v(bl.size());
// Generate some values
for(size_t i=0; i<v.size(); ++i)
v[i] = 1000.0*rng.randn();
// Possiblility of duplicate values
if(rng.rand() < 0.5)
{
double copy_prob = pow(10.0, -6*rng.rand());
for(size_t i=0; i<v.size(); ++i)
{
if(rng.rand() < copy_prob)
v[i] = v[rng.rand_int(v.size())];
}
}
return v;
}
std::vector<double> generate_good_valuations
(const BooleanLattice& bl, DNest4::RNG& rng, bool fidelity_matters)
{
std::vector<double> v;
// Generate valuations until they satisfy order (and optionally, fidelity)
while(true)
{
v = generate_valuations(bl, rng);
BLV blv(bl, v);
if(check_order(blv))
{
if((!fidelity_matters) || check_fidelity(blv))
break;
}
}
return v;
}
bool check_fidelity(const BLV& blv)
{
// Unpack tuple
auto& bl = std::get<0>(blv);
auto& valuations = std::get<1>(blv);
// Loop over all pairs of statements
for(size_t i=0; i<bl.size(); ++i)
{
for(size_t j=0; j<bl.size(); ++j)
{
// Valuations must encode implication.
if(bl.implies(i, j) && valuations[j] < valuations[i])
return false;
}
}
return true;
}
bool check_order(const BLV& blv)
{
// Unpack tuple
auto& bl = std::get<0>(blv);
auto& v = std::get<1>(blv);
// Loop over all triples, but only bother with disjoint triples
for(size_t i=0; i<bl.size(); ++i)
for(size_t j=0; j<bl.size(); ++j)
for(size_t k=0; k<bl.size(); ++k)
if(bl.disjoint(i, j, k))
if(v[i] > v[j])
if(v[bl.join(i, k)] <= v[bl.join(j, k)])
return false;
return true;
}
bool check_sum_rule(const BLV& blv)
{
return true;
}
// Output a boolean lattice with valuations.
std::ostream& operator << (std::ostream& out, const BLV& blv)
{
// Unpack tuple
auto& bl = std::get<0>(blv);
auto& valuations = std::get<1>(blv);
// Output the lattice
out<<bl;
// Output the values
for(double v: valuations)
out<<v<<' ';
return out;
}
} // namespace NF
|
Allow duplicate values
|
Allow duplicate values
|
C++
|
mit
|
eggplantbren/NumericalFoundations
|
a75baec888c7f2ade04d7a8990cbbf114cf595b8
|
src/VariablesAnnotator.cpp
|
src/VariablesAnnotator.cpp
|
//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <algorithm>
#include <memory>
#include <boost/variant/variant.hpp>
#include "VariablesAnnotator.hpp"
#include "ast/Program.hpp"
#include "IsConstantVisitor.hpp"
#include "GetTypeVisitor.hpp"
#include "SemanticalException.hpp"
#include "Context.hpp"
#include "GlobalContext.hpp"
#include "FunctionContext.hpp"
#include "Types.hpp"
#include "Variable.hpp"
#include "Compiler.hpp"
#include "Options.hpp"
#include "TypeTransformer.hpp"
#include "VisitorUtils.hpp"
#include "ASTVisitor.hpp"
using namespace eddic;
struct VariablesVisitor : public boost::static_visitor<> {
AUTO_RECURSE_PROGRAM()
AUTO_RECURSE_FUNCTION_CALLS()
AUTO_RECURSE_SIMPLE_LOOPS()
AUTO_RECURSE_BRANCHES()
AUTO_RECURSE_BINARY_CONDITION()
void operator()(ast::FunctionDeclaration& declaration){
//Add all the parameters to the function context
for(auto& parameter : declaration.Content->parameters){
Type type = boost::apply_visitor(TypeTransformer(), parameter.parameterType);
declaration.Content->context->addParameter(parameter.parameterName, type);
}
visit_each(*this, declaration.Content->instructions);
}
void operator()(ast::GlobalVariableDeclaration& declaration){
if (declaration.Content->context->exists(declaration.Content->variableName)) {
throw SemanticalException("The global Variable " + declaration.Content->variableName + " has already been declared");
}
if(!boost::apply_visitor(IsConstantVisitor(), *declaration.Content->value)){
throw SemanticalException("The value must be constant");
}
BaseType baseType = stringToBaseType(declaration.Content->variableType);
Type type(baseType, declaration.Content->constant);
declaration.Content->context->addVariable(declaration.Content->variableName, type, *declaration.Content->value);
}
void operator()(ast::GlobalArrayDeclaration& declaration){
if (declaration.Content->context->exists(declaration.Content->arrayName)) {
throw SemanticalException("The global Variable " + declaration.Content->arrayName + " has already been declared");
}
BaseType baseType = stringToBaseType(declaration.Content->arrayType);
Type type(baseType, declaration.Content->arraySize);
declaration.Content->context->addVariable(declaration.Content->arrayName, type);
}
void operator()(ast::Foreach& foreach){
if(foreach.Content->context->exists(foreach.Content->variableName)){
throw SemanticalException("The foreach variable " + foreach.Content->variableName + " has already been declared");
}
foreach.Content->context->addVariable(foreach.Content->variableName, stringToType(foreach.Content->variableType));
visit_each(*this, foreach.Content->instructions);
}
void operator()(ast::ForeachIn& foreach){
if(foreach.Content->context->exists(foreach.Content->variableName)){
throw SemanticalException("The foreach variable " + foreach.Content->variableName + " has already been declared");
}
if(!foreach.Content->context->exists(foreach.Content->arrayName)){
throw SemanticalException("The foreach array " + foreach.Content->arrayName + " has not been declared");
}
static int generated = 0;
foreach.Content->var = foreach.Content->context->addVariable(foreach.Content->variableName, stringToType(foreach.Content->variableType));
foreach.Content->arrayVar = foreach.Content->context->getVariable(foreach.Content->arrayName);
foreach.Content->iterVar = foreach.Content->context->addVariable("foreach_iter" + ++generated, stringToType("int"));
visit_each(*this, foreach.Content->instructions);
}
void operator()(ast::Assignment& assignment){
if (!assignment.Content->context->exists(assignment.Content->variableName)) {
throw SemanticalException("Variable " + assignment.Content->variableName + " has not been declared");
}
visit(*this, assignment.Content->value);
assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();
}
void operator()(ast::Return& return_){
visit(*this, return_.Content->value);
}
void operator()(ast::ArrayAssignment& assignment){
if (!assignment.Content->context->exists(assignment.Content->variableName)) {
throw SemanticalException("Array " + assignment.Content->variableName + " has not been declared");
}
visit(*this, assignment.Content->indexValue);
visit(*this, assignment.Content->value);
assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();
}
void operator()(ast::VariableDeclaration& declaration){
if (declaration.Content->context->exists(declaration.Content->variableName)) {
throw SemanticalException("Variable " + declaration.Content->variableName + " has already been declared");
}
BaseType baseType = stringToBaseType(declaration.Content->variableType);
Type type(baseType, declaration.Content->const_);
if(type.isConst()){
declaration.Content->context->addVariable(declaration.Content->variableName, type);
} else {
declaration.Content->context->addVariable(declaration.Content->variableName, type, *declaration.Content->value);
}
visit(*this, *declaration.Content->value);
}
void operator()(ast::ArrayDeclaration& declaration){
if (declaration.Content->context->exists(declaration.Content->arrayName)) {
throw SemanticalException("The variable " + declaration.Content->arrayName + " has already been declared");
}
BaseType baseType = stringToBaseType(declaration.Content->arrayType);
Type type(baseType, declaration.Content->arraySize);
declaration.Content->context->addVariable(declaration.Content->arrayName, type);
}
void operator()(ast::Swap& swap){
if (swap.Content->lhs == swap.Content->rhs) {
throw SemanticalException("Cannot swap a variable with itself");
}
if (!swap.Content->context->exists(swap.Content->lhs) || !swap.Content->context->exists(swap.Content->rhs)) {
throw SemanticalException("Variable has not been declared in the swap");
}
swap.Content->lhs_var = swap.Content->context->getVariable(swap.Content->lhs);
swap.Content->rhs_var = swap.Content->context->getVariable(swap.Content->rhs);
//Reference both variables
swap.Content->lhs_var->addReference();
swap.Content->rhs_var->addReference();
}
void operator()(ast::VariableValue& variable){
if (!variable.Content->context->exists(variable.Content->variableName)) {
throw SemanticalException("Variable " + variable.Content->variableName + " has not been declared");
}
//Reference the variable
variable.Content->var = variable.Content->context->getVariable(variable.Content->variableName);
variable.Content->var->addReference();
}
void operator()(ast::ArrayValue& array){
if (!array.Content->context->exists(array.Content->arrayName)) {
throw SemanticalException("Array " + array.Content->arrayName + " has not been declared");
}
//Reference the variable
array.Content->var = array.Content->context->getVariable(array.Content->arrayName);
array.Content->var->addReference();
visit(*this, array.Content->indexValue);
}
void operator()(ast::ComposedValue& value){
visit(*this, value.Content->first);
for_each(value.Content->operations.begin(), value.Content->operations.end(),
[&](boost::tuple<char, ast::Value>& operation){ visit(*this, operation.get<1>()); });
}
void operator()(ast::TerminalNode&){
//Terminal nodes have no need for variable checking
}
};
void VariablesAnnotator::annotate(ast::Program& program) const {
VariablesVisitor visitor;
visit_non_variant(visitor, program);
}
|
//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <algorithm>
#include <memory>
#include <boost/variant/variant.hpp>
#include "VariablesAnnotator.hpp"
#include "ast/Program.hpp"
#include "IsConstantVisitor.hpp"
#include "GetTypeVisitor.hpp"
#include "SemanticalException.hpp"
#include "Context.hpp"
#include "GlobalContext.hpp"
#include "FunctionContext.hpp"
#include "Types.hpp"
#include "Variable.hpp"
#include "Compiler.hpp"
#include "Options.hpp"
#include "TypeTransformer.hpp"
#include "VisitorUtils.hpp"
#include "ASTVisitor.hpp"
using namespace eddic;
struct VariablesVisitor : public boost::static_visitor<> {
AUTO_RECURSE_PROGRAM()
AUTO_RECURSE_FUNCTION_CALLS()
AUTO_RECURSE_SIMPLE_LOOPS()
AUTO_RECURSE_BRANCHES()
AUTO_RECURSE_BINARY_CONDITION()
void operator()(ast::FunctionDeclaration& declaration){
//Add all the parameters to the function context
for(auto& parameter : declaration.Content->parameters){
Type type = boost::apply_visitor(TypeTransformer(), parameter.parameterType);
declaration.Content->context->addParameter(parameter.parameterName, type);
}
visit_each(*this, declaration.Content->instructions);
}
void operator()(ast::GlobalVariableDeclaration& declaration){
if (declaration.Content->context->exists(declaration.Content->variableName)) {
throw SemanticalException("The global Variable " + declaration.Content->variableName + " has already been declared");
}
if(!boost::apply_visitor(IsConstantVisitor(), *declaration.Content->value)){
throw SemanticalException("The value must be constant");
}
BaseType baseType = stringToBaseType(declaration.Content->variableType);
Type type(baseType, declaration.Content->constant);
declaration.Content->context->addVariable(declaration.Content->variableName, type, *declaration.Content->value);
}
void operator()(ast::GlobalArrayDeclaration& declaration){
if (declaration.Content->context->exists(declaration.Content->arrayName)) {
throw SemanticalException("The global Variable " + declaration.Content->arrayName + " has already been declared");
}
BaseType baseType = stringToBaseType(declaration.Content->arrayType);
Type type(baseType, declaration.Content->arraySize);
declaration.Content->context->addVariable(declaration.Content->arrayName, type);
}
void operator()(ast::Foreach& foreach){
if(foreach.Content->context->exists(foreach.Content->variableName)){
throw SemanticalException("The foreach variable " + foreach.Content->variableName + " has already been declared");
}
foreach.Content->context->addVariable(foreach.Content->variableName, stringToType(foreach.Content->variableType));
visit_each(*this, foreach.Content->instructions);
}
void operator()(ast::ForeachIn& foreach){
if(foreach.Content->context->exists(foreach.Content->variableName)){
throw SemanticalException("The foreach variable " + foreach.Content->variableName + " has already been declared");
}
if(!foreach.Content->context->exists(foreach.Content->arrayName)){
throw SemanticalException("The foreach array " + foreach.Content->arrayName + " has not been declared");
}
static int generated = 0;
foreach.Content->var = foreach.Content->context->addVariable(foreach.Content->variableName, stringToType(foreach.Content->variableType));
foreach.Content->arrayVar = foreach.Content->context->getVariable(foreach.Content->arrayName);
foreach.Content->iterVar = foreach.Content->context->addVariable("foreach_iter" + ++generated, stringToType("int"));
visit_each(*this, foreach.Content->instructions);
}
void operator()(ast::Assignment& assignment){
if (!assignment.Content->context->exists(assignment.Content->variableName)) {
throw SemanticalException("Variable " + assignment.Content->variableName + " has not been declared");
}
visit(*this, assignment.Content->value);
assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();
}
void operator()(ast::Return& return_){
visit(*this, return_.Content->value);
}
void operator()(ast::ArrayAssignment& assignment){
if (!assignment.Content->context->exists(assignment.Content->variableName)) {
throw SemanticalException("Array " + assignment.Content->variableName + " has not been declared");
}
visit(*this, assignment.Content->indexValue);
visit(*this, assignment.Content->value);
assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();
}
void operator()(ast::VariableDeclaration& declaration){
if (declaration.Content->context->exists(declaration.Content->variableName)) {
throw SemanticalException("Variable " + declaration.Content->variableName + " has already been declared");
}
BaseType baseType = stringToBaseType(declaration.Content->variableType);
Type type(baseType, declaration.Content->const_);
if(type.isConst()){
declaration.Content->context->addVariable(declaration.Content->variableName, type, *declaration.Content->value);
} else {
declaration.Content->context->addVariable(declaration.Content->variableName, type);
}
visit(*this, *declaration.Content->value);
}
void operator()(ast::ArrayDeclaration& declaration){
if (declaration.Content->context->exists(declaration.Content->arrayName)) {
throw SemanticalException("The variable " + declaration.Content->arrayName + " has already been declared");
}
BaseType baseType = stringToBaseType(declaration.Content->arrayType);
Type type(baseType, declaration.Content->arraySize);
declaration.Content->context->addVariable(declaration.Content->arrayName, type);
}
void operator()(ast::Swap& swap){
if (swap.Content->lhs == swap.Content->rhs) {
throw SemanticalException("Cannot swap a variable with itself");
}
if (!swap.Content->context->exists(swap.Content->lhs) || !swap.Content->context->exists(swap.Content->rhs)) {
throw SemanticalException("Variable has not been declared in the swap");
}
swap.Content->lhs_var = swap.Content->context->getVariable(swap.Content->lhs);
swap.Content->rhs_var = swap.Content->context->getVariable(swap.Content->rhs);
//Reference both variables
swap.Content->lhs_var->addReference();
swap.Content->rhs_var->addReference();
}
void operator()(ast::VariableValue& variable){
if (!variable.Content->context->exists(variable.Content->variableName)) {
throw SemanticalException("Variable " + variable.Content->variableName + " has not been declared");
}
//Reference the variable
variable.Content->var = variable.Content->context->getVariable(variable.Content->variableName);
variable.Content->var->addReference();
}
void operator()(ast::ArrayValue& array){
if (!array.Content->context->exists(array.Content->arrayName)) {
throw SemanticalException("Array " + array.Content->arrayName + " has not been declared");
}
//Reference the variable
array.Content->var = array.Content->context->getVariable(array.Content->arrayName);
array.Content->var->addReference();
visit(*this, array.Content->indexValue);
}
void operator()(ast::ComposedValue& value){
visit(*this, value.Content->first);
for_each(value.Content->operations.begin(), value.Content->operations.end(),
[&](boost::tuple<char, ast::Value>& operation){ visit(*this, operation.get<1>()); });
}
void operator()(ast::TerminalNode&){
//Terminal nodes have no need for variable checking
}
};
void VariablesAnnotator::annotate(ast::Program& program) const {
VariablesVisitor visitor;
visit_non_variant(visitor, program);
}
|
Fix the condition
|
Fix the condition
|
C++
|
mit
|
wichtounet/eddic,vogelsgesang/eddic,wichtounet/eddic,vogelsgesang/eddic,vogelsgesang/eddic,wichtounet/eddic
|
51ab596d44c5d55828b372a820840a1040676e48
|
src/core/lib/iomgr/error.cc
|
src/core/lib/iomgr/error.cc
|
/*
*
* Copyright 2016 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/error.h"
#include <inttypes.h>
#include <string.h>
#include "absl/strings/str_format.h"
#include <grpc/impl/codegen/status.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#ifdef GPR_WINDOWS
#include <grpc/support/log_windows.h>
#endif
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/strerror.h"
#include "src/core/lib/slice/slice_internal.h"
grpc_core::DebugOnlyTraceFlag grpc_trace_error_refcount(false,
"error_refcount");
grpc_core::DebugOnlyTraceFlag grpc_trace_closure(false, "closure");
absl::Status grpc_status_create(absl::StatusCode code, absl::string_view msg,
const grpc_core::DebugLocation& location,
size_t children_count, absl::Status* children) {
absl::Status s = StatusCreate(code, msg, location, {});
for (size_t i = 0; i < children_count; ++i) {
if (!children[i].ok()) {
grpc_core::StatusAddChild(&s, children[i]);
}
}
return s;
}
std::string grpc_error_std_string(absl::Status error) {
return grpc_core::StatusToString(error);
}
absl::Status grpc_os_error(const grpc_core::DebugLocation& location, int err,
const char* call_name) {
auto err_string = grpc_core::StrError(err);
absl::Status s =
StatusCreate(absl::StatusCode::kUnknown, err_string, location, {});
grpc_core::StatusSetInt(&s, grpc_core::StatusIntProperty::kErrorNo, err);
grpc_core::StatusSetStr(&s, grpc_core::StatusStrProperty::kOsError,
err_string);
grpc_core::StatusSetStr(&s, grpc_core::StatusStrProperty::kSyscall,
call_name);
return s;
}
#ifdef GPR_WINDOWS
absl::Status grpc_wsa_error(const grpc_core::DebugLocation& location, int err,
const char* call_name) {
char* utf8_message = gpr_format_message(err);
absl::Status s =
StatusCreate(absl::StatusCode::kUnavailable, "WSA Error", location, {});
StatusSetInt(&s, grpc_core::StatusIntProperty::kWsaError, err);
StatusSetInt(&s, grpc_core::StatusIntProperty::kRpcStatus,
GRPC_STATUS_UNAVAILABLE);
StatusSetStr(&s, grpc_core::StatusStrProperty::kOsError, utf8_message);
StatusSetStr(&s, grpc_core::StatusStrProperty::kSyscall, call_name);
gpr_free(utf8_message);
return s;
}
#endif
grpc_error_handle grpc_error_set_int(grpc_error_handle src,
grpc_core::StatusIntProperty which,
intptr_t value) {
if (src.ok()) {
src = absl::UnknownError("");
StatusSetInt(&src, grpc_core::StatusIntProperty::kRpcStatus,
GRPC_STATUS_OK);
}
grpc_core::StatusSetInt(&src, which, value);
return src;
}
bool grpc_error_get_int(grpc_error_handle error,
grpc_core::StatusIntProperty which, intptr_t* p) {
absl::optional<intptr_t> value = grpc_core::StatusGetInt(error, which);
if (value.has_value()) {
*p = *value;
return true;
} else {
// TODO(veblush): Remove this once absl::Status migration is done
if (which == grpc_core::StatusIntProperty::kRpcStatus) {
switch (error.code()) {
case absl::StatusCode::kOk:
*p = GRPC_STATUS_OK;
return true;
case absl::StatusCode::kResourceExhausted:
*p = GRPC_STATUS_RESOURCE_EXHAUSTED;
return true;
case absl::StatusCode::kCancelled:
*p = GRPC_STATUS_CANCELLED;
return true;
default:
break;
}
}
return false;
}
}
grpc_error_handle grpc_error_set_str(grpc_error_handle src,
grpc_core::StatusStrProperty which,
absl::string_view str) {
if (src.ok()) {
src = absl::UnknownError("");
StatusSetInt(&src, grpc_core::StatusIntProperty::kRpcStatus,
GRPC_STATUS_OK);
}
if (which == grpc_core::StatusStrProperty::kDescription) {
// To change the message of absl::Status, a new instance should be created
// with a code and payload because it doesn't have a setter for it.
absl::Status s = absl::Status(src.code(), str);
src.ForEachPayload(
[&](absl::string_view type_url, const absl::Cord& payload) {
s.SetPayload(type_url, payload);
});
return s;
} else {
grpc_core::StatusSetStr(&src, which, str);
}
return src;
}
bool grpc_error_get_str(grpc_error_handle error,
grpc_core::StatusStrProperty which, std::string* s) {
if (which == grpc_core::StatusStrProperty::kDescription) {
// absl::Status uses the message field for
// grpc_core::StatusStrProperty::kDescription instead of using payload.
absl::string_view msg = error.message();
if (msg.empty()) {
return false;
} else {
*s = std::string(msg);
return true;
}
} else {
absl::optional<std::string> value = grpc_core::StatusGetStr(error, which);
if (value.has_value()) {
*s = std::move(*value);
return true;
} else {
// TODO(veblush): Remove this once absl::Status migration is done
if (which == grpc_core::StatusStrProperty::kGrpcMessage) {
switch (error.code()) {
case absl::StatusCode::kOk:
*s = "";
return true;
case absl::StatusCode::kResourceExhausted:
*s = "RESOURCE_EXHAUSTED";
return true;
case absl::StatusCode::kCancelled:
*s = "CANCELLED";
return true;
default:
break;
}
}
return false;
}
}
}
grpc_error_handle grpc_error_add_child(grpc_error_handle src,
grpc_error_handle child) {
if (src.ok()) {
return child;
} else {
if (!child.ok()) {
grpc_core::StatusAddChild(&src, child);
}
return src;
}
}
bool grpc_log_error(const char* what, grpc_error_handle error, const char* file,
int line) {
GPR_DEBUG_ASSERT(!error.ok());
gpr_log(file, line, GPR_LOG_SEVERITY_ERROR, "%s: %s", what,
grpc_core::StatusToString(error).c_str());
return false;
}
|
/*
*
* Copyright 2016 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/error.h"
#include <inttypes.h>
#include <string.h>
#include "absl/strings/str_format.h"
#include <grpc/impl/codegen/status.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#ifdef GPR_WINDOWS
#include <grpc/support/log_windows.h>
#endif
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/gprpp/strerror.h"
#include "src/core/lib/slice/slice_internal.h"
grpc_core::DebugOnlyTraceFlag grpc_trace_error_refcount(false,
"error_refcount");
grpc_core::DebugOnlyTraceFlag grpc_trace_closure(false, "closure");
absl::Status grpc_status_create(absl::StatusCode code, absl::string_view msg,
const grpc_core::DebugLocation& location,
size_t children_count, absl::Status* children) {
absl::Status s = StatusCreate(code, msg, location, {});
for (size_t i = 0; i < children_count; ++i) {
if (!children[i].ok()) {
grpc_core::StatusAddChild(&s, children[i]);
}
}
return s;
}
std::string grpc_error_std_string(absl::Status error) {
return grpc_core::StatusToString(error);
}
absl::Status grpc_os_error(const grpc_core::DebugLocation& location, int err,
const char* call_name) {
auto err_string = grpc_core::StrError(err);
absl::Status s =
StatusCreate(absl::StatusCode::kUnknown, err_string, location, {});
grpc_core::StatusSetInt(&s, grpc_core::StatusIntProperty::kErrorNo, err);
grpc_core::StatusSetStr(&s, grpc_core::StatusStrProperty::kOsError,
err_string);
grpc_core::StatusSetStr(&s, grpc_core::StatusStrProperty::kSyscall,
call_name);
return s;
}
#ifdef GPR_WINDOWS
absl::Status grpc_wsa_error(const grpc_core::DebugLocation& location, int err,
const char* call_name) {
char* utf8_message = gpr_format_message(err);
absl::Status s =
StatusCreate(absl::StatusCode::kUnavailable, "WSA Error", location, {});
StatusSetInt(&s, grpc_core::StatusIntProperty::kWsaError, err);
StatusSetInt(&s, grpc_core::StatusIntProperty::kRpcStatus,
GRPC_STATUS_UNAVAILABLE);
StatusSetStr(&s, grpc_core::StatusStrProperty::kOsError, utf8_message);
StatusSetStr(&s, grpc_core::StatusStrProperty::kSyscall, call_name);
gpr_free(utf8_message);
return s;
}
#endif
grpc_error_handle grpc_error_set_int(grpc_error_handle src,
grpc_core::StatusIntProperty which,
intptr_t value) {
if (src.ok()) {
src = absl::UnknownError("");
StatusSetInt(&src, grpc_core::StatusIntProperty::kRpcStatus,
GRPC_STATUS_OK);
}
grpc_core::StatusSetInt(&src, which, value);
return src;
}
bool grpc_error_get_int(grpc_error_handle error,
grpc_core::StatusIntProperty which, intptr_t* p) {
absl::optional<intptr_t> value = grpc_core::StatusGetInt(error, which);
if (value.has_value()) {
*p = *value;
return true;
} else {
// TODO(veblush): Remove this once absl::Status migration is done
if (which == grpc_core::StatusIntProperty::kRpcStatus) {
switch (error.code()) {
case absl::StatusCode::kOk:
*p = GRPC_STATUS_OK;
return true;
case absl::StatusCode::kResourceExhausted:
*p = GRPC_STATUS_RESOURCE_EXHAUSTED;
return true;
case absl::StatusCode::kCancelled:
*p = GRPC_STATUS_CANCELLED;
return true;
default:
break;
}
}
return false;
}
}
grpc_error_handle grpc_error_set_str(grpc_error_handle src,
grpc_core::StatusStrProperty which,
absl::string_view str) {
if (src.ok()) {
src = absl::UnknownError("");
StatusSetInt(&src, grpc_core::StatusIntProperty::kRpcStatus,
GRPC_STATUS_OK);
}
if (which == grpc_core::StatusStrProperty::kDescription) {
// To change the message of absl::Status, a new instance should be created
// with a code and payload because it doesn't have a setter for it.
absl::Status s = absl::Status(src.code(), str);
src.ForEachPayload(
[&](absl::string_view type_url, const absl::Cord& payload) {
s.SetPayload(type_url, payload);
});
return s;
} else {
grpc_core::StatusSetStr(&src, which, str);
}
return src;
}
bool grpc_error_get_str(grpc_error_handle error,
grpc_core::StatusStrProperty which, std::string* s) {
if (which == grpc_core::StatusStrProperty::kDescription) {
// absl::Status uses the message field for
// grpc_core::StatusStrProperty::kDescription instead of using payload.
absl::string_view msg = error.message();
if (msg.empty()) {
return false;
} else {
*s = std::string(msg);
return true;
}
} else {
absl::optional<std::string> value = grpc_core::StatusGetStr(error, which);
if (value.has_value()) {
*s = std::move(*value);
return true;
} else {
// TODO(veblush): Remove this once absl::Status migration is done
if (which == grpc_core::StatusStrProperty::kGrpcMessage) {
switch (error.code()) {
case absl::StatusCode::kOk:
*s = "";
return true;
case absl::StatusCode::kCancelled:
*s = "CANCELLED";
return true;
default:
break;
}
}
return false;
}
}
}
grpc_error_handle grpc_error_add_child(grpc_error_handle src,
grpc_error_handle child) {
if (src.ok()) {
return child;
} else {
if (!child.ok()) {
grpc_core::StatusAddChild(&src, child);
}
return src;
}
}
bool grpc_log_error(const char* what, grpc_error_handle error, const char* file,
int line) {
GPR_DEBUG_ASSERT(!error.ok());
gpr_log(file, line, GPR_LOG_SEVERITY_ERROR, "%s: %s", what,
grpc_core::StatusToString(error).c_str());
return false;
}
|
remove unnecessary conversion (#31342)
|
remove unnecessary conversion (#31342)
|
C++
|
apache-2.0
|
stanley-cheung/grpc,grpc/grpc,stanley-cheung/grpc,stanley-cheung/grpc,stanley-cheung/grpc,stanley-cheung/grpc,stanley-cheung/grpc,stanley-cheung/grpc,grpc/grpc,grpc/grpc,jtattermusch/grpc,grpc/grpc,jtattermusch/grpc,jtattermusch/grpc,jtattermusch/grpc,stanley-cheung/grpc,stanley-cheung/grpc,jtattermusch/grpc,grpc/grpc,jtattermusch/grpc,jtattermusch/grpc,jtattermusch/grpc,grpc/grpc,stanley-cheung/grpc,grpc/grpc,jtattermusch/grpc,grpc/grpc,grpc/grpc,jtattermusch/grpc,grpc/grpc,jtattermusch/grpc,grpc/grpc,jtattermusch/grpc,stanley-cheung/grpc,grpc/grpc,stanley-cheung/grpc
|
ff30a20738726922e1889f99000e23980b9c9c62
|
Source/PLT/SDL2/Bitmap.cpp
|
Source/PLT/SDL2/Bitmap.cpp
|
//------------------------------------------------------------------------------
// Copyright (c) 2016 John D. Haughton
//
// 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.
//------------------------------------------------------------------------------
// SDL2 Bitmap implementation
#include "SDL_headers.h"
#ifdef __clahng__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdocumentation"
#endif
#include "SDL_image.h"
#ifdef __clahng__
#pragma clang diagnostic pop
#endif
#include "PLT/Bitmap.h"
namespace PLT {
//! Memory image buffer
class Bitmap::Impl
{
public:
Impl() = default;
~Impl()
{
resize(0, 0);
}
void resize(unsigned width_, unsigned height_)
{
if (surface != nullptr)
{
SDL_FreeSurface(surface);
}
if ((width_ == 0) || (height_ == 0))
{
return;
}
#if 0
surface = SDL_CreateRGBSurfaceWithFormat(0, width_, height_, 32, PIXEL_FORMAT);
#else
// XXX replace with code above when SDL2.0.5 is more widely available
surface = SDL_CreateRGBSurface(0, width_, height_, 32,
0x00FF0000,
0x0000FF00,
0x000000FF,
0xFF000000);
#endif
}
uint8_t* getData(unsigned& width_, unsigned& height_, unsigned& pitch_)
{
if(surface == nullptr)
{
return nullptr;
}
width_ = surface->w;
height_ = surface->h;
pitch_ = surface->pitch;
return (uint8_t*)surface->pixels;
}
void* getHandle() const { return surface; }
private:
SDL_Surface* surface{nullptr};
};
Bitmap::Bitmap(unsigned width_, unsigned height_)
: Image(width_, height_)
{
pimpl = new Impl();
resize(width_, height_);
}
Bitmap::~Bitmap()
{
delete pimpl;
}
void Bitmap::resize(unsigned width_, unsigned height_)
{
pimpl->resize(width_, height_);
buffer = pimpl->getData(width, height, pitch);
}
void* Bitmap::getHandle() const
{
return pimpl->getHandle();
}
} // namespace PLT
|
//------------------------------------------------------------------------------
// Copyright (c) 2016 John D. Haughton
//
// 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.
//------------------------------------------------------------------------------
// SDL2 Bitmap implementation
#include "SDL_headers.h"
#include "PLT/Bitmap.h"
namespace PLT {
//! Memory image buffer
class Bitmap::Impl
{
public:
Impl() = default;
~Impl()
{
resize(0, 0);
}
void resize(unsigned width_, unsigned height_)
{
if (surface != nullptr)
{
SDL_FreeSurface(surface);
}
if ((width_ == 0) || (height_ == 0))
{
return;
}
#if 0
surface = SDL_CreateRGBSurfaceWithFormat(0, width_, height_, 32, PIXEL_FORMAT);
#else
// XXX replace with code above when SDL2.0.5 is more widely available
surface = SDL_CreateRGBSurface(0, width_, height_, 32,
0x00FF0000,
0x0000FF00,
0x000000FF,
0xFF000000);
#endif
}
uint8_t* getData(unsigned& width_, unsigned& height_, unsigned& pitch_)
{
if(surface == nullptr)
{
return nullptr;
}
width_ = surface->w;
height_ = surface->h;
pitch_ = surface->pitch;
return (uint8_t*)surface->pixels;
}
void* getHandle() const { return surface; }
private:
SDL_Surface* surface{nullptr};
};
Bitmap::Bitmap(unsigned width_, unsigned height_)
: Image(width_, height_)
{
pimpl = new Impl();
resize(width_, height_);
}
Bitmap::~Bitmap()
{
delete pimpl;
}
void Bitmap::resize(unsigned width_, unsigned height_)
{
pimpl->resize(width_, height_);
buffer = pimpl->getData(width, height, pitch);
}
void* Bitmap::getHandle() const
{
return pimpl->getHandle();
}
} // namespace PLT
|
Fix SDL2_image.h header issue
|
Fix SDL2_image.h header issue
|
C++
|
mit
|
AnotherJohnH/Platform,AnotherJohnH/Platform,AnotherJohnH/Platform,AnotherJohnH/Platform
|
8b570aa5c6698800b061f29a6cbfb2bf6d71158e
|
src/Mod/Assembly/App/Item.cpp
|
src/Mod/Assembly/App/Item.cpp
|
/***************************************************************************
* Copyright (c) 2010 Juergen Riegel <[email protected]> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Base/Placement.h>
#include <Base/Uuid.h>
#include "Item.h"
#include "ItemPy.h"
using namespace Assembly;
namespace Assembly {
PROPERTY_SOURCE_ABSTRACT(Assembly::Item, App::GeoFeature)
Item::Item()
{
ADD_PROPERTY_TYPE(CreatedBy,(""),0,App::Prop_None,"The creator of the Item");
ADD_PROPERTY_TYPE(CreationDate,(Base::TimeInfo::currentDateTimeString()),0,App::Prop_ReadOnly,"Date of creation");
ADD_PROPERTY_TYPE(LastModifiedBy,(""),0,App::Prop_None,0);
ADD_PROPERTY_TYPE(LastModifiedDate,("Unknown"),0,App::Prop_ReadOnly,"Date of last modification");
ADD_PROPERTY_TYPE(Company,(""),0,App::Prop_None,"Additional tag to save the the name of the company");
ADD_PROPERTY_TYPE(Comment,(""),0,App::Prop_None,"Additional tag to save a comment");
ADD_PROPERTY_TYPE(Meta,(),0,App::Prop_None,"Map with additional meta information");
ADD_PROPERTY_TYPE(Material,(),0,App::Prop_None,"Map with material properties");
// create the uuid for the document
Base::Uuid id;
ADD_PROPERTY_TYPE(Id,(""),0,App::Prop_None,"ID (Part-Number) of the Item");
ADD_PROPERTY_TYPE(Uid,(id.UuidStr),0,App::Prop_None,"UUID of the Item");
// license stuff
ADD_PROPERTY_TYPE(License,("CC BY 3.0"),0,App::Prop_None,"License string of the Item");
ADD_PROPERTY_TYPE(LicenseURL,("http://creativecommons.org/licenses/by/3.0/"),0,App::Prop_None,"URL to the license text/contract");
// color and apperance
ADD_PROPERTY(Color,(1.0,1.0,1.0,1.0)); // set transparent -> not used
ADD_PROPERTY(Visibility,(true));
}
short Item::mustExecute() const
{
//if (Sketch.isTouched() ||
// Length.isTouched())
// return 1;
return 0;
}
App::DocumentObjectExecReturn *Item::execute(void)
{
return App::DocumentObject::StdReturn;
}
PyObject *Item::getPyObject(void)
{
if (PythonObject.is(Py::_None())){
// ref counter is set to 1
PythonObject = Py::Object(new ItemPy(this),true);
}
return Py::new_reference_to(PythonObject);
}
}
|
/***************************************************************************
* Copyright (c) 2010 Juergen Riegel <[email protected]> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Base/Placement.h>
#include <Base/Uuid.h>
#include "Item.h"
#include "ItemPy.h"
using namespace Assembly;
namespace Assembly {
PROPERTY_SOURCE_ABSTRACT(Assembly::Item, App::GeoFeature)
Item::Item()
{
ADD_PROPERTY_TYPE(CreatedBy,(""),0,App::Prop_None,"The creator of the Item");
ADD_PROPERTY_TYPE(CreationDate,(Base::TimeInfo::currentDateTimeString()),0,App::Prop_ReadOnly,"Date of creation");
ADD_PROPERTY_TYPE(LastModifiedBy,(""),0,App::Prop_None,0);
ADD_PROPERTY_TYPE(LastModifiedDate,("Unknown"),0,App::Prop_ReadOnly,"Date of last modification");
ADD_PROPERTY_TYPE(Company,(""),0,App::Prop_None,"Additional tag to save the the name of the company");
ADD_PROPERTY_TYPE(Comment,(""),0,App::Prop_None,"Additional tag to save a comment");
ADD_PROPERTY_TYPE(Meta,(),0,App::Prop_None,"Map with additional meta information");
ADD_PROPERTY_TYPE(Material,(),0,App::Prop_None,"Map with material properties");
// create the uuid for the document
Base::Uuid id;
ADD_PROPERTY_TYPE(Id,(""),0,App::Prop_None,"ID (Part-Number) of the Item");
ADD_PROPERTY_TYPE(Uid,(id),0,App::Prop_None,"UUID of the Item");
// license stuff
ADD_PROPERTY_TYPE(License,("CC BY 3.0"),0,App::Prop_None,"License string of the Item");
ADD_PROPERTY_TYPE(LicenseURL,("http://creativecommons.org/licenses/by/3.0/"),0,App::Prop_None,"URL to the license text/contract");
// color and apperance
ADD_PROPERTY(Color,(1.0,1.0,1.0,1.0)); // set transparent -> not used
ADD_PROPERTY(Visibility,(true));
}
short Item::mustExecute() const
{
//if (Sketch.isTouched() ||
// Length.isTouched())
// return 1;
return 0;
}
App::DocumentObjectExecReturn *Item::execute(void)
{
return App::DocumentObject::StdReturn;
}
PyObject *Item::getPyObject(void)
{
if (PythonObject.is(Py::_None())){
// ref counter is set to 1
PythonObject = Py::Object(new ItemPy(this),true);
}
return Py::new_reference_to(PythonObject);
}
}
|
Update Item with new UUID tool
|
Update Item with new UUID tool
|
C++
|
lgpl-2.1
|
jriegel/FreeCAD,jriegel/FreeCAD,jriegel/FreeCAD,jriegel/FreeCAD,jriegel/FreeCAD
|
e077c3425c8e14cee382c618728e54839a86eb7f
|
agent-ovs/src/SwitchConnection.cpp
|
agent-ovs/src/SwitchConnection.cpp
|
/*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
#include <sys/eventfd.h>
#include <string>
#include <boost/unordered_map.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/lock_guard.hpp>
#include <boost/foreach.hpp>
#include <boost/scope_exit.hpp>
#include "ovs.h"
#include "SwitchConnection.h"
#include "logging.h"
using namespace std;
using namespace boost;
using namespace ovsagent;
typedef lock_guard<mutex> mutex_guard;
const int LOST_CONN_BACKOFF_SEC = 5;
namespace opflex {
namespace enforcer {
SwitchConnection::SwitchConnection(const std::string& swName) :
switchName(swName) {
ofConn = NULL;
connThread = NULL;
ofProtoVersion = OFP10_VERSION;
isDisconnecting = false;
pollEventFd = eventfd(0, 0);
RegisterMessageHandler(OFPTYPE_ECHO_REQUEST, &echoReqHandler);
RegisterMessageHandler(OFPTYPE_ERROR, &errorHandler);
}
SwitchConnection::~SwitchConnection() {
Disconnect();
}
void
SwitchConnection::RegisterOnConnectListener(OnConnectListener *l) {
if (l) {
mutex_guard lock(connMtx);
onConnectListeners.push_back(l);
}
}
void
SwitchConnection::UnregisterOnConnectListener(OnConnectListener *l) {
mutex_guard lock(connMtx);
onConnectListeners.remove(l);
}
void
SwitchConnection::RegisterMessageHandler(ofptype msgType,
MessageHandler *handler)
{
if (handler) {
mutex_guard lock(connMtx);
msgHandlers[msgType].push_back(handler);
}
}
void
SwitchConnection::UnregisterMessageHandler(ofptype msgType,
MessageHandler *handler)
{
mutex_guard lock(connMtx);
HandlerMap::iterator itr = msgHandlers.find(msgType);
if (itr != msgHandlers.end()) {
itr->second.remove(handler);
}
}
int
SwitchConnection::Connect(ofp_version protoVer) {
if (ofConn != NULL) { // connection already created
return true;
}
ofProtoVersion = protoVer;
int err = DoConnect();
if (err != 0) {
LOG(ERROR) << "Failed to connect to " << switchName << ": "
<< ovs_strerror(err);
}
connThread = new boost::thread(boost::ref(*this));
return err;
}
int
SwitchConnection::DoConnect() {
string swPath;
swPath.append("unix:").append(ovs_rundir()).append("/")
.append(switchName).append(".mgmt");
uint32_t versionBitmap = 1u << ofProtoVersion;
vconn *newConn;
int error;
error = vconn_open_block(swPath.c_str(), versionBitmap, DSCP_DEFAULT,
&newConn);
if (error) {
return error;
}
/* Verify we have the correct protocol version */
ofp_version connVersion = (ofp_version)vconn_get_version(newConn);
if (connVersion != ofProtoVersion) {
LOG(WARNING) << "Remote supports version " << connVersion <<
", wanted " << ofProtoVersion;
}
LOG(INFO) << "Connected to switch " << swPath
<< " using protocol version " << ofProtoVersion;
{
mutex_guard lock(connMtx);
ofConn = newConn;
ofProtoVersion = connVersion;
}
return 0;
}
void
SwitchConnection::Disconnect() {
isDisconnecting = true;
if (connThread && SignalPollEvent()) {
connThread->join();
delete connThread;
connThread = NULL;
}
mutex_guard lock(connMtx);
if (ofConn != NULL) {
vconn_close(ofConn);
ofConn = NULL;
}
isDisconnecting = false;
}
bool
SwitchConnection::IsConnected() {
mutex_guard lock(connMtx);
return IsConnectedLocked();
}
bool
SwitchConnection::IsConnectedLocked() {
return ofConn != NULL && vconn_get_status(ofConn) == 0;
}
ofp_version
SwitchConnection::GetProtocolVersion() {
return ofProtoVersion;
}
void
SwitchConnection::operator()() {
Monitor();
}
bool
SwitchConnection::SignalPollEvent() {
uint64_t data = 1;
ssize_t szWrote = write(pollEventFd, &data, sizeof(data));
if (szWrote != sizeof(data)) {
LOG(ERROR) << "Failed to send event to poll loop: " << strerror(errno);
return false;
}
return true;
}
void
SwitchConnection::WatchPollEvent() {
poll_fd_wait(pollEventFd, POLLIN);
}
void
SwitchConnection::Monitor() {
LOG(DEBUG) << "Connection monitor started ...";
bool connLost = (IsConnected() == false);
if (!connLost) {
FireOnConnectListeners();
}
while (true) {
if (connLost) {
LOG(ERROR) << "Connection lost, trying to auto reconnect";
mutex_guard lock(connMtx);
if (ofConn != NULL) {
vconn_close(ofConn);
ofConn = NULL;
}
}
bool oldConnLost = connLost;
while (connLost && !isDisconnecting) {
sleep(LOST_CONN_BACKOFF_SEC);
connLost = (DoConnect() != 0);
}
if (isDisconnecting) {
return;
}
if (oldConnLost != connLost) {
FireOnConnectListeners();
}
WatchPollEvent();
if (!connLost) {
{
mutex_guard lock(connMtx);
vconn_run(ofConn);
vconn_run_wait(ofConn);
vconn_recv_wait(ofConn);
}
poll_block();
}
connLost = (EOF == ReceiveMessage());
}
return;
}
int
SwitchConnection::ReceiveMessage() {
do {
int err;
ofpbuf *recvMsg;
{
mutex_guard lock(connMtx);
err = vconn_recv(ofConn, &recvMsg);
}
if (err == EAGAIN) {
return 0;
} else if (err != 0) {
LOG(ERROR) << "Error while receiving message: "
<< ovs_strerror(err);
ofpbuf_delete(recvMsg);
return err;
} else {
ofptype type;
if (!ofptype_decode(&type, (ofp_header *)ofpbuf_data(recvMsg))) {
HandlerMap::const_iterator itr = msgHandlers.find(type);
if (itr != msgHandlers.end()) {
BOOST_FOREACH(MessageHandler *h, itr->second) {
h->Handle(this, type, recvMsg);
}
}
}
ofpbuf_delete(recvMsg);
}
} while (true);
return 0;
}
int
SwitchConnection::SendMessage(ofpbuf *msg) {
BOOST_SCOPE_EXIT((&msg)) {
if (!msg) {
ofpbuf_delete(msg);
}
} BOOST_SCOPE_EXIT_END
while(true) {
mutex_guard lock(connMtx);
if (!IsConnectedLocked()) {
return ENOTCONN;
}
int err = vconn_send(ofConn, msg);
if (err == 0) {
msg = NULL;
return 0;
} else if (err != EAGAIN) {
LOG(ERROR) << "Error sending message: " << ovs_strerror(err);
return err;
} else {
vconn_run(ofConn);
vconn_send_wait(ofConn);
}
}
}
void
SwitchConnection::FireOnConnectListeners() {
if (GetProtocolVersion() >= OFP12_VERSION) {
// Set controller role to MASTER
ofpbuf *b0;
ofp12_role_request *rr;
b0 = ofpraw_alloc(OFPRAW_OFPT12_ROLE_REQUEST,
GetProtocolVersion(), sizeof *rr);
rr = (ofp12_role_request*)ofpbuf_put_zeros(b0, sizeof *rr);
rr->role = htonl(OFPCR12_ROLE_MASTER);
SendMessage(b0);
}
{
// Set default miss length to non-zero value to enable
// asynchronous messages
ofpbuf *b1;
ofp_switch_config *osc;
b1 = ofpraw_alloc(OFPRAW_OFPT_SET_CONFIG,
GetProtocolVersion(), sizeof *osc);
osc = (ofp_switch_config*)ofpbuf_put_zeros(b1, sizeof *osc);
osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
SendMessage(b1);
}
{
// Set packet-in format to nicira-extended format
ofpbuf *b2;
nx_set_packet_in_format* pif;
b2 = ofpraw_alloc(OFPRAW_NXT_SET_PACKET_IN_FORMAT,
GetProtocolVersion(), sizeof *pif);
pif = (nx_set_packet_in_format*)ofpbuf_put_zeros(b2, sizeof *pif);
pif->format = NXPIF_NXM;
SendMessage(b2);
}
BOOST_FOREACH(OnConnectListener *l, onConnectListeners) {
l->Connected(this);
}
}
void
SwitchConnection::EchoRequestHandler::Handle(SwitchConnection *swConn,
ofptype msgType, ofpbuf *msg) {
LOG(DEBUG) << "Got ECHO request";
const ofp_header *rq = (const ofp_header *)ofpbuf_data(msg);
struct ofpbuf *echoReplyMsg = make_echo_reply(rq);
swConn->SendMessage(echoReplyMsg);
}
void
SwitchConnection::ErrorHandler::Handle(SwitchConnection *swConn,
ofptype msgType, ofpbuf *msg) {
const struct ofp_header *oh = (ofp_header *)ofpbuf_data(msg);
ofperr err = ofperr_decode_msg(oh, NULL);
LOG(ERROR) << "Got error reply from switch ("
<< std::hex << oh->xid << "): "
<< ofperr_get_name(err) << ": "
<< ofperr_get_description(err);
}
} // namespace enforcer
} // namespace opflex
|
/*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
#include <sys/eventfd.h>
#include <string>
#include <boost/unordered_map.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/lock_guard.hpp>
#include <boost/foreach.hpp>
#include <boost/scope_exit.hpp>
#include "ovs.h"
#include "SwitchConnection.h"
#include "logging.h"
using namespace std;
using namespace boost;
using namespace ovsagent;
typedef lock_guard<mutex> mutex_guard;
const int LOST_CONN_BACKOFF_SEC = 5;
namespace opflex {
namespace enforcer {
SwitchConnection::SwitchConnection(const std::string& swName) :
switchName(swName) {
ofConn = NULL;
connThread = NULL;
ofProtoVersion = OFP10_VERSION;
isDisconnecting = false;
pollEventFd = eventfd(0, 0);
RegisterMessageHandler(OFPTYPE_ECHO_REQUEST, &echoReqHandler);
RegisterMessageHandler(OFPTYPE_ERROR, &errorHandler);
}
SwitchConnection::~SwitchConnection() {
Disconnect();
}
void
SwitchConnection::RegisterOnConnectListener(OnConnectListener *l) {
if (l) {
mutex_guard lock(connMtx);
onConnectListeners.push_back(l);
}
}
void
SwitchConnection::UnregisterOnConnectListener(OnConnectListener *l) {
mutex_guard lock(connMtx);
onConnectListeners.remove(l);
}
void
SwitchConnection::RegisterMessageHandler(ofptype msgType,
MessageHandler *handler)
{
if (handler) {
mutex_guard lock(connMtx);
msgHandlers[msgType].push_back(handler);
}
}
void
SwitchConnection::UnregisterMessageHandler(ofptype msgType,
MessageHandler *handler)
{
mutex_guard lock(connMtx);
HandlerMap::iterator itr = msgHandlers.find(msgType);
if (itr != msgHandlers.end()) {
itr->second.remove(handler);
}
}
int
SwitchConnection::Connect(ofp_version protoVer) {
if (ofConn != NULL) { // connection already created
return true;
}
ofProtoVersion = protoVer;
int err = DoConnect();
if (err != 0) {
LOG(ERROR) << "Failed to connect to " << switchName << ": "
<< ovs_strerror(err);
}
connThread = new boost::thread(boost::ref(*this));
return err;
}
int
SwitchConnection::DoConnect() {
string swPath;
swPath.append("unix:").append(ovs_rundir()).append("/")
.append(switchName).append(".mgmt");
uint32_t versionBitmap = 1u << ofProtoVersion;
vconn *newConn;
int error;
error = vconn_open_block(swPath.c_str(), versionBitmap, DSCP_DEFAULT,
&newConn);
if (error) {
return error;
}
/* Verify we have the correct protocol version */
ofp_version connVersion = (ofp_version)vconn_get_version(newConn);
if (connVersion != ofProtoVersion) {
LOG(WARNING) << "Remote supports version " << connVersion <<
", wanted " << ofProtoVersion;
}
LOG(INFO) << "Connected to switch " << swPath
<< " using protocol version " << ofProtoVersion;
{
mutex_guard lock(connMtx);
ofConn = newConn;
ofProtoVersion = connVersion;
}
return 0;
}
void
SwitchConnection::Disconnect() {
isDisconnecting = true;
if (connThread && SignalPollEvent()) {
connThread->join();
delete connThread;
connThread = NULL;
}
mutex_guard lock(connMtx);
if (ofConn != NULL) {
vconn_close(ofConn);
ofConn = NULL;
}
isDisconnecting = false;
}
bool
SwitchConnection::IsConnected() {
mutex_guard lock(connMtx);
return IsConnectedLocked();
}
bool
SwitchConnection::IsConnectedLocked() {
return ofConn != NULL && vconn_get_status(ofConn) == 0;
}
ofp_version
SwitchConnection::GetProtocolVersion() {
return ofProtoVersion;
}
void
SwitchConnection::operator()() {
Monitor();
}
bool
SwitchConnection::SignalPollEvent() {
uint64_t data = 1;
ssize_t szWrote = write(pollEventFd, &data, sizeof(data));
if (szWrote != sizeof(data)) {
LOG(ERROR) << "Failed to send event to poll loop: " << strerror(errno);
return false;
}
return true;
}
void
SwitchConnection::WatchPollEvent() {
poll_fd_wait(pollEventFd, POLLIN);
}
void
SwitchConnection::Monitor() {
LOG(DEBUG) << "Connection monitor started ...";
bool connLost = (IsConnected() == false);
if (!connLost) {
FireOnConnectListeners();
}
while (true) {
if (connLost) {
LOG(ERROR) << "Connection lost, trying to auto reconnect";
mutex_guard lock(connMtx);
if (ofConn != NULL) {
vconn_close(ofConn);
ofConn = NULL;
}
}
bool oldConnLost = connLost;
while (connLost && !isDisconnecting) {
sleep(LOST_CONN_BACKOFF_SEC);
connLost = (DoConnect() != 0);
}
if (isDisconnecting) {
return;
}
if (oldConnLost != connLost) {
FireOnConnectListeners();
}
WatchPollEvent();
if (!connLost) {
{
mutex_guard lock(connMtx);
vconn_run(ofConn);
vconn_run_wait(ofConn);
vconn_recv_wait(ofConn);
}
poll_block();
}
connLost = (EOF == ReceiveMessage());
}
return;
}
int
SwitchConnection::ReceiveMessage() {
do {
int err;
ofpbuf *recvMsg;
{
mutex_guard lock(connMtx);
err = vconn_recv(ofConn, &recvMsg);
}
if (err == EAGAIN) {
return 0;
} else if (err != 0) {
LOG(ERROR) << "Error while receiving message: "
<< ovs_strerror(err);
ofpbuf_delete(recvMsg);
return err;
} else {
ofptype type;
if (!ofptype_decode(&type, (ofp_header *)ofpbuf_data(recvMsg))) {
HandlerMap::const_iterator itr = msgHandlers.find(type);
if (itr != msgHandlers.end()) {
BOOST_FOREACH(MessageHandler *h, itr->second) {
h->Handle(this, type, recvMsg);
}
}
}
ofpbuf_delete(recvMsg);
}
} while (true);
return 0;
}
int
SwitchConnection::SendMessage(ofpbuf *msg) {
BOOST_SCOPE_EXIT((&msg)) {
if (!msg) {
ofpbuf_delete(msg);
}
} BOOST_SCOPE_EXIT_END
while(true) {
mutex_guard lock(connMtx);
if (!IsConnectedLocked()) {
return ENOTCONN;
}
int err = vconn_send(ofConn, msg);
if (err == 0) {
msg = NULL;
return 0;
} else if (err != EAGAIN) {
LOG(ERROR) << "Error sending message: " << ovs_strerror(err);
return err;
} else {
vconn_run(ofConn);
vconn_send_wait(ofConn);
}
}
}
void
SwitchConnection::FireOnConnectListeners() {
if (GetProtocolVersion() >= OFP12_VERSION) {
// Set controller role to MASTER
ofpbuf *b0;
ofp12_role_request *rr;
b0 = ofpraw_alloc(OFPRAW_OFPT12_ROLE_REQUEST,
GetProtocolVersion(), sizeof *rr);
rr = (ofp12_role_request*)ofpbuf_put_zeros(b0, sizeof *rr);
rr->role = htonl(OFPCR12_ROLE_MASTER);
SendMessage(b0);
}
{
// Set default miss length to non-zero value to enable
// asynchronous messages
ofpbuf *b1;
ofp_switch_config *osc;
b1 = ofpraw_alloc(OFPRAW_OFPT_SET_CONFIG,
GetProtocolVersion(), sizeof *osc);
osc = (ofp_switch_config*)ofpbuf_put_zeros(b1, sizeof *osc);
osc->miss_send_len = htons(OFP_DEFAULT_MISS_SEND_LEN);
SendMessage(b1);
}
{
// Set packet-in format to nicira-extended format
ofpbuf *b2;
nx_set_packet_in_format* pif;
b2 = ofpraw_alloc(OFPRAW_NXT_SET_PACKET_IN_FORMAT,
GetProtocolVersion(), sizeof *pif);
pif = (nx_set_packet_in_format*)ofpbuf_put_zeros(b2, sizeof *pif);
pif->format = htonl(NXPIF_NXM);
SendMessage(b2);
}
BOOST_FOREACH(OnConnectListener *l, onConnectListeners) {
l->Connected(this);
}
}
void
SwitchConnection::EchoRequestHandler::Handle(SwitchConnection *swConn,
ofptype msgType, ofpbuf *msg) {
LOG(DEBUG) << "Got ECHO request";
const ofp_header *rq = (const ofp_header *)ofpbuf_data(msg);
struct ofpbuf *echoReplyMsg = make_echo_reply(rq);
swConn->SendMessage(echoReplyMsg);
}
void
SwitchConnection::ErrorHandler::Handle(SwitchConnection *swConn,
ofptype msgType, ofpbuf *msg) {
const struct ofp_header *oh = (ofp_header *)ofpbuf_data(msg);
ofperr err = ofperr_decode_msg(oh, NULL);
LOG(ERROR) << "Got error reply from switch ("
<< std::hex << oh->xid << "): "
<< ofperr_get_name(err) << ": "
<< ofperr_get_description(err);
}
} // namespace enforcer
} // namespace opflex
|
Set format value properly while setting packet-in format
|
Set format value properly while setting packet-in format
The format value is expected in big-endian, so OVS was responding
with OFPBRC_EPERM to set packet-in format requests.
Change-Id: I49b65fa96c5aad8c3b26874a6e364d3dcf64f19e
Signed-off-by: Amit Bose <[email protected]>
|
C++
|
epl-1.0
|
opendaylight/opflex,mhrobinson/opflex,opendaylight/opflex,mhrobinson/opflex,mhrobinson/opflex,mhrobinson/opflex,opendaylight/opflex,opendaylight/opflex
|
bf5dd4170ffe2b3858280c233caf2053ee47c2c7
|
bench/PicturePlaybackBench.cpp
|
bench/PicturePlaybackBench.cpp
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Benchmark.h"
#include "SkCanvas.h"
#include "SkColor.h"
#include "SkPaint.h"
#include "SkPicture.h"
#include "SkPictureRecorder.h"
#include "SkPoint.h"
#include "SkRect.h"
#include "SkString.h"
// This is designed to emulate about 4 screens of textual content
class PicturePlaybackBench : public Benchmark {
public:
PicturePlaybackBench(const char name[]) {
fName.printf("picture_playback_%s", name);
fPictureWidth = SkIntToScalar(PICTURE_WIDTH);
fPictureHeight = SkIntToScalar(PICTURE_HEIGHT);
fTextSize = SkIntToScalar(TEXT_SIZE);
}
enum {
PICTURE_WIDTH = 1000,
PICTURE_HEIGHT = 4000,
TEXT_SIZE = 10
};
protected:
virtual const char* onGetName() {
return fName.c_str();
}
virtual void onDraw(const int loops, SkCanvas* canvas) {
SkPictureRecorder recorder;
SkCanvas* pCanvas = recorder.beginRecording(PICTURE_WIDTH, PICTURE_HEIGHT, NULL, 0);
this->recordCanvas(pCanvas);
SkAutoTUnref<SkPicture> picture(recorder.endRecording());
const SkPoint translateDelta = getTranslateDelta(loops);
for (int i = 0; i < loops; i++) {
picture->playback(canvas);
canvas->translate(translateDelta.fX, translateDelta.fY);
}
}
virtual void recordCanvas(SkCanvas* canvas) = 0;
virtual SkPoint getTranslateDelta(int N) {
SkIPoint canvasSize = onGetSize();
return SkPoint::Make(SkIntToScalar((PICTURE_WIDTH - canvasSize.fX)/N),
SkIntToScalar((PICTURE_HEIGHT- canvasSize.fY)/N));
}
SkString fName;
SkScalar fPictureWidth;
SkScalar fPictureHeight;
SkScalar fTextSize;
private:
typedef Benchmark INHERITED;
};
class TextPlaybackBench : public PicturePlaybackBench {
public:
TextPlaybackBench() : INHERITED("drawText") { }
protected:
virtual void recordCanvas(SkCanvas* canvas) SK_OVERRIDE {
SkPaint paint;
paint.setTextSize(fTextSize);
paint.setColor(SK_ColorBLACK);
const char* text = "Hamburgefons";
size_t len = strlen(text);
const SkScalar textWidth = paint.measureText(text, len);
for (SkScalar x = 0; x < fPictureWidth; x += textWidth) {
for (SkScalar y = 0; y < fPictureHeight; y += fTextSize) {
canvas->drawText(text, len, x, y, paint);
}
}
}
private:
typedef PicturePlaybackBench INHERITED;
};
class PosTextPlaybackBench : public PicturePlaybackBench {
public:
PosTextPlaybackBench(bool drawPosH)
: INHERITED(drawPosH ? "drawPosTextH" : "drawPosText")
, fDrawPosH(drawPosH) { }
protected:
virtual void recordCanvas(SkCanvas* canvas) SK_OVERRIDE {
SkPaint paint;
paint.setTextSize(fTextSize);
paint.setColor(SK_ColorBLACK);
const char* text = "Hamburgefons";
size_t len = strlen(text);
const SkScalar textWidth = paint.measureText(text, len);
SkScalar* adv = new SkScalar[len];
paint.getTextWidths(text, len, adv);
for (SkScalar x = 0; x < fPictureWidth; x += textWidth) {
for (SkScalar y = 0; y < fPictureHeight; y += fTextSize) {
SkPoint* pos = new SkPoint[len];
SkScalar advX = 0;
for (size_t i = 0; i < len; i++) {
if (fDrawPosH)
pos[i].set(x + advX, y);
else
pos[i].set(x + advX, y + i);
advX += adv[i];
}
canvas->drawPosText(text, len, pos, paint);
delete[] pos;
}
}
delete[] adv;
}
private:
bool fDrawPosH;
typedef PicturePlaybackBench INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
DEF_BENCH( return new TextPlaybackBench(); )
DEF_BENCH( return new PosTextPlaybackBench(true); )
DEF_BENCH( return new PosTextPlaybackBench(false); )
|
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Benchmark.h"
#include "SkCanvas.h"
#include "SkColor.h"
#include "SkPaint.h"
#include "SkPicture.h"
#include "SkPictureRecorder.h"
#include "SkPoint.h"
#include "SkRandom.h"
#include "SkRect.h"
#include "SkString.h"
// This is designed to emulate about 4 screens of textual content
class PicturePlaybackBench : public Benchmark {
public:
PicturePlaybackBench(const char name[]) {
fName.printf("picture_playback_%s", name);
fPictureWidth = SkIntToScalar(PICTURE_WIDTH);
fPictureHeight = SkIntToScalar(PICTURE_HEIGHT);
fTextSize = SkIntToScalar(TEXT_SIZE);
}
enum {
PICTURE_WIDTH = 1000,
PICTURE_HEIGHT = 4000,
TEXT_SIZE = 10
};
protected:
virtual const char* onGetName() {
return fName.c_str();
}
virtual void onDraw(const int loops, SkCanvas* canvas) {
SkPictureRecorder recorder;
SkCanvas* pCanvas = recorder.beginRecording(PICTURE_WIDTH, PICTURE_HEIGHT, NULL, 0);
this->recordCanvas(pCanvas);
SkAutoTUnref<SkPicture> picture(recorder.endRecording());
const SkPoint translateDelta = getTranslateDelta(loops);
for (int i = 0; i < loops; i++) {
picture->playback(canvas);
canvas->translate(translateDelta.fX, translateDelta.fY);
}
}
virtual void recordCanvas(SkCanvas* canvas) = 0;
virtual SkPoint getTranslateDelta(int N) {
SkIPoint canvasSize = onGetSize();
return SkPoint::Make(SkIntToScalar((PICTURE_WIDTH - canvasSize.fX)/N),
SkIntToScalar((PICTURE_HEIGHT- canvasSize.fY)/N));
}
SkString fName;
SkScalar fPictureWidth;
SkScalar fPictureHeight;
SkScalar fTextSize;
private:
typedef Benchmark INHERITED;
};
class TextPlaybackBench : public PicturePlaybackBench {
public:
TextPlaybackBench() : INHERITED("drawText") { }
protected:
virtual void recordCanvas(SkCanvas* canvas) SK_OVERRIDE {
SkPaint paint;
paint.setTextSize(fTextSize);
paint.setColor(SK_ColorBLACK);
const char* text = "Hamburgefons";
size_t len = strlen(text);
const SkScalar textWidth = paint.measureText(text, len);
for (SkScalar x = 0; x < fPictureWidth; x += textWidth) {
for (SkScalar y = 0; y < fPictureHeight; y += fTextSize) {
canvas->drawText(text, len, x, y, paint);
}
}
}
private:
typedef PicturePlaybackBench INHERITED;
};
class PosTextPlaybackBench : public PicturePlaybackBench {
public:
PosTextPlaybackBench(bool drawPosH)
: INHERITED(drawPosH ? "drawPosTextH" : "drawPosText")
, fDrawPosH(drawPosH) { }
protected:
virtual void recordCanvas(SkCanvas* canvas) SK_OVERRIDE {
SkPaint paint;
paint.setTextSize(fTextSize);
paint.setColor(SK_ColorBLACK);
const char* text = "Hamburgefons";
size_t len = strlen(text);
const SkScalar textWidth = paint.measureText(text, len);
SkScalar* adv = new SkScalar[len];
paint.getTextWidths(text, len, adv);
for (SkScalar x = 0; x < fPictureWidth; x += textWidth) {
for (SkScalar y = 0; y < fPictureHeight; y += fTextSize) {
SkPoint* pos = new SkPoint[len];
SkScalar advX = 0;
for (size_t i = 0; i < len; i++) {
if (fDrawPosH)
pos[i].set(x + advX, y);
else
pos[i].set(x + advX, y + i);
advX += adv[i];
}
canvas->drawPosText(text, len, pos, paint);
delete[] pos;
}
}
delete[] adv;
}
private:
bool fDrawPosH;
typedef PicturePlaybackBench INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
DEF_BENCH( return new TextPlaybackBench(); )
DEF_BENCH( return new PosTextPlaybackBench(true); )
DEF_BENCH( return new PosTextPlaybackBench(false); )
// Chrome draws into small tiles with impl-side painting.
// This benchmark measures the relative performance of our bounding-box hierarchies,
// both when querying tiles perfectly and when not.
enum BBH { kNone, kRTree, kTileGrid };
enum Mode { kTiled, kRandom };
class TiledPlaybackBench : public Benchmark {
public:
TiledPlaybackBench(BBH bbh, Mode mode) : fBBH(bbh), fMode(mode), fName("tiled_playback") {
switch (fBBH) {
case kNone: fName.append("_none" ); break;
case kRTree: fName.append("_rtree" ); break;
case kTileGrid: fName.append("_tilegrid"); break;
}
switch (fMode) {
case kTiled: fName.append("_tiled" ); break;
case kRandom: fName.append("_random"); break;
}
}
virtual const char* onGetName() SK_OVERRIDE { return fName.c_str(); }
virtual SkIPoint onGetSize() SK_OVERRIDE { return SkIPoint::Make(1024,1024); }
virtual void onPreDraw() SK_OVERRIDE {
SkTileGridFactory::TileGridInfo info = { { 256, 256 }, {0,0}, {0,0} };
SkAutoTDelete<SkBBHFactory> factory;
switch (fBBH) {
case kNone: break;
case kRTree: factory.reset(new SkRTreeFactory); break;
case kTileGrid: factory.reset(new SkTileGridFactory(info)); break;
}
SkPictureRecorder recorder;
SkCanvas* canvas = recorder.beginRecording(1024, 1024, factory);
SkRandom rand;
for (int i = 0; i < 10000; i++) {
SkScalar x = rand.nextRangeScalar(0, 1024),
y = rand.nextRangeScalar(0, 1024),
w = rand.nextRangeScalar(0, 128),
h = rand.nextRangeScalar(0, 128);
SkPaint paint;
paint.setColor(rand.nextU());
paint.setAlpha(0xFF);
canvas->drawRect(SkRect::MakeXYWH(x,y,w,h), paint);
}
fPic.reset(recorder.endRecording());
}
virtual void onDraw(const int loops, SkCanvas* canvas) SK_OVERRIDE {
for (int i = 0; i < loops; i++) {
// This inner loop guarantees we make the same choices for all bench variants.
SkRandom rand;
for (int j = 0; j < 10; j++) {
SkScalar x = 0, y = 0;
switch (fMode) {
case kTiled: x = SkScalar(256 * rand.nextULessThan(4));
y = SkScalar(256 * rand.nextULessThan(4));
break;
case kRandom: x = rand.nextRangeScalar(0, 768);
y = rand.nextRangeScalar(0, 768);
break;
}
SkAutoCanvasRestore ar(canvas, true/*save now*/);
canvas->clipRect(SkRect::MakeXYWH(x,y,256,256));
fPic->playback(canvas);
}
}
}
private:
BBH fBBH;
Mode fMode;
SkString fName;
SkAutoTDelete<SkPicture> fPic;
};
DEF_BENCH( return new TiledPlaybackBench(kNone, kRandom); )
DEF_BENCH( return new TiledPlaybackBench(kNone, kTiled ); )
DEF_BENCH( return new TiledPlaybackBench(kRTree, kRandom); )
DEF_BENCH( return new TiledPlaybackBench(kRTree, kTiled ); )
DEF_BENCH( return new TiledPlaybackBench(kTileGrid, kRandom); )
DEF_BENCH( return new TiledPlaybackBench(kTileGrid, kTiled ); )
|
Add benchmark to compare different BBH query patterns.
|
Add benchmark to compare different BBH query patterns.
On my laptop:
maxrss loops min median mean max stddev samples config bench
37M 1 14ms 14.2ms 14.6ms 18.2ms 9% ▁█▁▁▁▁▂▂▂▁ gpu tiled_playback_tilegrid_tiled
40M 1 17ms 17.2ms 17.2ms 17.6ms 1% ▆▃▁█▄▇▂▁▁▁ gpu tiled_playback_tilegrid_random
40M 1 14.6ms 14.9ms 15.8ms 19.1ms 11% ▂▁▁▁▁▁▁█▅█ gpu tiled_playback_rtree_tiled
43M 1 16.5ms 16.7ms 16.8ms 17.4ms 1% ▂▃▅█▃▂▁▃▃▂ gpu tiled_playback_rtree_random
43M 1 15.9ms 16.1ms 16.5ms 18.7ms 6% ▁▁█▇▁▁▁▂▁▁ gpu tiled_playback_none_tiled
44M 1 17.9ms 17.9ms 18ms 18.1ms 1% ▂▁▅▁▇▃▁▂█▇ gpu tiled_playback_none_random
TileGrid and RTree perform pretty much the same, both beating no BBH.
BUG=skia:3085
Review URL: https://codereview.chromium.org/699313006
|
C++
|
bsd-3-clause
|
MonkeyZZZZ/platform_external_skia,rubenvb/skia,aosp-mirror/platform_external_skia,scroggo/skia,chenlian2015/skia_from_google,PAC-ROM/android_external_skia,Infinitive-OS/platform_external_skia,ominux/skia,HalCanary/skia-hc,qrealka/skia-hc,YUPlayGodDev/platform_external_skia,samuelig/skia,AOSPB/external_skia,OneRom/external_skia,noselhq/skia,geekboxzone/mmallow_external_skia,AOSP-YU/platform_external_skia,Igalia/skia,MarshedOut/android_external_skia,boulzordev/android_external_skia,OneRom/external_skia,Hikari-no-Tenshi/android_external_skia,nvoron23/skia,ominux/skia,geekboxzone/mmallow_external_skia,scroggo/skia,Jichao/skia,BrokenROM/external_skia,google/skia,samuelig/skia,pcwalton/skia,TeamExodus/external_skia,todotodoo/skia,w3nd1go/android_external_skia,DiamondLovesYou/skia-sys,vanish87/skia,BrokenROM/external_skia,UBERMALLOW/external_skia,timduru/platform-external-skia,shahrzadmn/skia,Infinitive-OS/platform_external_skia,BrokenROM/external_skia,TeamTwisted/external_skia,nfxosp/platform_external_skia,scroggo/skia,todotodoo/skia,AOSPB/external_skia,HalCanary/skia-hc,YUPlayGodDev/platform_external_skia,Igalia/skia,chenlian2015/skia_from_google,MinimalOS-AOSP/platform_external_skia,DiamondLovesYou/skia-sys,qrealka/skia-hc,timduru/platform-external-skia,geekboxzone/mmallow_external_skia,VRToxin-AOSP/android_external_skia,amyvmiwei/skia,TeamTwisted/external_skia,DiamondLovesYou/skia-sys,rubenvb/skia,ominux/skia,TeamTwisted/external_skia,geekboxzone/mmallow_external_skia,Jichao/skia,Igalia/skia,Hikari-no-Tenshi/android_external_skia,scroggo/skia,tmpvar/skia.cc,TeamTwisted/external_skia,MonkeyZZZZ/platform_external_skia,Jichao/skia,invisiblek/android_external_skia,Infinitive-OS/platform_external_skia,shahrzadmn/skia,UBERMALLOW/external_skia,DiamondLovesYou/skia-sys,boulzordev/android_external_skia,geekboxzone/mmallow_external_skia,chenlian2015/skia_from_google,OneRom/external_skia,nvoron23/skia,nfxosp/platform_external_skia,AOSPB/external_skia,ominux/skia,amyvmiwei/skia,w3nd1go/android_external_skia,TeamTwisted/external_skia,MinimalOS-AOSP/platform_external_skia,samuelig/skia,TeamTwisted/external_skia,boulzordev/android_external_skia,jtg-gg/skia,shahrzadmn/skia,MarshedOut/android_external_skia,MonkeyZZZZ/platform_external_skia,amyvmiwei/skia,aosp-mirror/platform_external_skia,chenlian2015/skia_from_google,ominux/skia,invisiblek/android_external_skia,PAC-ROM/android_external_skia,VRToxin-AOSP/android_external_skia,todotodoo/skia,qrealka/skia-hc,DiamondLovesYou/skia-sys,VRToxin-AOSP/android_external_skia,spezi77/android_external_skia,invisiblek/android_external_skia,samuelig/skia,qrealka/skia-hc,Jichao/skia,timduru/platform-external-skia,google/skia,spezi77/android_external_skia,scroggo/skia,todotodoo/skia,noselhq/skia,TeamExodus/external_skia,google/skia,boulzordev/android_external_skia,AOSP-YU/platform_external_skia,w3nd1go/android_external_skia,vanish87/skia,Infinitive-OS/platform_external_skia,todotodoo/skia,ominux/skia,chenlian2015/skia_from_google,jtg-gg/skia,YUPlayGodDev/platform_external_skia,boulzordev/android_external_skia,samuelig/skia,spezi77/android_external_skia,samuelig/skia,Jichao/skia,chenlian2015/skia_from_google,google/skia,ominux/skia,shahrzadmn/skia,AOSPB/external_skia,MarshedOut/android_external_skia,aosp-mirror/platform_external_skia,AOSPB/external_skia,aosp-mirror/platform_external_skia,amyvmiwei/skia,rubenvb/skia,YUPlayGodDev/platform_external_skia,Igalia/skia,noselhq/skia,samuelig/skia,geekboxzone/mmallow_external_skia,rubenvb/skia,jtg-gg/skia,HalCanary/skia-hc,MarshedOut/android_external_skia,AOSPB/external_skia,qrealka/skia-hc,HalCanary/skia-hc,MinimalOS-AOSP/platform_external_skia,todotodoo/skia,samuelig/skia,aosp-mirror/platform_external_skia,invisiblek/android_external_skia,ominux/skia,pcwalton/skia,scroggo/skia,PAC-ROM/android_external_skia,AOSP-YU/platform_external_skia,MonkeyZZZZ/platform_external_skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,PAC-ROM/android_external_skia,MinimalOS-AOSP/platform_external_skia,Hikari-no-Tenshi/android_external_skia,nvoron23/skia,qrealka/skia-hc,todotodoo/skia,nvoron23/skia,scroggo/skia,boulzordev/android_external_skia,YUPlayGodDev/platform_external_skia,MarshedOut/android_external_skia,rubenvb/skia,YUPlayGodDev/platform_external_skia,jtg-gg/skia,invisiblek/android_external_skia,rubenvb/skia,rubenvb/skia,geekboxzone/mmallow_external_skia,w3nd1go/android_external_skia,Igalia/skia,PAC-ROM/android_external_skia,MonkeyZZZZ/platform_external_skia,vanish87/skia,google/skia,google/skia,VRToxin-AOSP/android_external_skia,Jichao/skia,PAC-ROM/android_external_skia,TeamExodus/external_skia,google/skia,AOSP-YU/platform_external_skia,Infinitive-OS/platform_external_skia,MarshedOut/android_external_skia,VRToxin-AOSP/android_external_skia,noselhq/skia,w3nd1go/android_external_skia,TeamTwisted/external_skia,geekboxzone/mmallow_external_skia,MarshedOut/android_external_skia,timduru/platform-external-skia,tmpvar/skia.cc,shahrzadmn/skia,todotodoo/skia,Hikari-no-Tenshi/android_external_skia,vanish87/skia,invisiblek/android_external_skia,nfxosp/platform_external_skia,MinimalOS-AOSP/platform_external_skia,pcwalton/skia,nvoron23/skia,UBERMALLOW/external_skia,qrealka/skia-hc,Jichao/skia,OneRom/external_skia,nvoron23/skia,rubenvb/skia,vanish87/skia,MarshedOut/android_external_skia,OneRom/external_skia,vanish87/skia,nfxosp/platform_external_skia,boulzordev/android_external_skia,w3nd1go/android_external_skia,UBERMALLOW/external_skia,Igalia/skia,w3nd1go/android_external_skia,BrokenROM/external_skia,vanish87/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,tmpvar/skia.cc,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,noselhq/skia,Infinitive-OS/platform_external_skia,nfxosp/platform_external_skia,pcwalton/skia,geekboxzone/mmallow_external_skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,tmpvar/skia.cc,shahrzadmn/skia,BrokenROM/external_skia,VRToxin-AOSP/android_external_skia,PAC-ROM/android_external_skia,noselhq/skia,nfxosp/platform_external_skia,UBERMALLOW/external_skia,BrokenROM/external_skia,tmpvar/skia.cc,DiamondLovesYou/skia-sys,noselhq/skia,Hikari-no-Tenshi/android_external_skia,spezi77/android_external_skia,OneRom/external_skia,OneRom/external_skia,VRToxin-AOSP/android_external_skia,MarshedOut/android_external_skia,aosp-mirror/platform_external_skia,YUPlayGodDev/platform_external_skia,amyvmiwei/skia,TeamExodus/external_skia,qrealka/skia-hc,chenlian2015/skia_from_google,ominux/skia,AOSP-YU/platform_external_skia,nfxosp/platform_external_skia,pcwalton/skia,MonkeyZZZZ/platform_external_skia,nvoron23/skia,OneRom/external_skia,PAC-ROM/android_external_skia,noselhq/skia,vanish87/skia,YUPlayGodDev/platform_external_skia,TeamExodus/external_skia,UBERMALLOW/external_skia,amyvmiwei/skia,jtg-gg/skia,AOSP-YU/platform_external_skia,TeamExodus/external_skia,aosp-mirror/platform_external_skia,tmpvar/skia.cc,BrokenROM/external_skia,UBERMALLOW/external_skia,timduru/platform-external-skia,Infinitive-OS/platform_external_skia,HalCanary/skia-hc,jtg-gg/skia,MonkeyZZZZ/platform_external_skia,TeamTwisted/external_skia,invisiblek/android_external_skia,nfxosp/platform_external_skia,shahrzadmn/skia,AOSPB/external_skia,TeamTwisted/external_skia,amyvmiwei/skia,w3nd1go/android_external_skia,vanish87/skia,HalCanary/skia-hc,MinimalOS-AOSP/platform_external_skia,AOSP-YU/platform_external_skia,VRToxin-AOSP/android_external_skia,VRToxin-AOSP/android_external_skia,AOSPB/external_skia,boulzordev/android_external_skia,Igalia/skia,tmpvar/skia.cc,HalCanary/skia-hc,YUPlayGodDev/platform_external_skia,nfxosp/platform_external_skia,Infinitive-OS/platform_external_skia,Igalia/skia,Infinitive-OS/platform_external_skia,scroggo/skia,OneRom/external_skia,noselhq/skia,BrokenROM/external_skia,pcwalton/skia,MonkeyZZZZ/platform_external_skia,timduru/platform-external-skia,UBERMALLOW/external_skia,TeamExodus/external_skia,MinimalOS-AOSP/platform_external_skia,Jichao/skia,w3nd1go/android_external_skia,nvoron23/skia,shahrzadmn/skia,AOSP-YU/platform_external_skia,google/skia,DiamondLovesYou/skia-sys,tmpvar/skia.cc,MinimalOS-AOSP/platform_external_skia,TeamExodus/external_skia,Jichao/skia,AOSP-YU/platform_external_skia,PAC-ROM/android_external_skia,TeamExodus/external_skia,rubenvb/skia,timduru/platform-external-skia,amyvmiwei/skia,jtg-gg/skia,invisiblek/android_external_skia,MonkeyZZZZ/platform_external_skia,tmpvar/skia.cc,MinimalOS-AOSP/platform_external_skia,nvoron23/skia,rubenvb/skia,todotodoo/skia,pcwalton/skia,google/skia,AOSPB/external_skia,spezi77/android_external_skia,HalCanary/skia-hc,pcwalton/skia,UBERMALLOW/external_skia,shahrzadmn/skia,spezi77/android_external_skia,boulzordev/android_external_skia,pcwalton/skia
|
bc88c959840f6db596e2fd8a8d318e99d3a68825
|
backends/gpu/lib/pass/pass.cc
|
backends/gpu/lib/pass/pass.cc
|
// Copyright 2020 The TensorFlow Runtime Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "tfrt/gpu/pass/pass.h"
#include "llvm/ADT/STLExtras.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/OperationSupport.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/Types.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/DialectConversion.h"
#include "tfrt/basic_kernels/opdefs/tfrt_base.h"
#include "tfrt/basic_kernels/opdefs/types.h"
#include "tfrt/gpu/kernels/gpu_ops.h"
namespace tfrt {
namespace gpu {
Value internal::GpuAsyncOpConversionGetStream(Operation *parent) {
if (auto exec_op = dyn_cast_or_null<conversion::AsyncExecuteOp>(parent))
return exec_op.body().getArgument(1);
return Value();
}
Value internal::GpuAsyncOpConversionGetChain(Operation *parent) {
if (auto exec_op = dyn_cast_or_null<conversion::AsyncExecuteOp>(parent))
return exec_op.body().back().getTerminator()->getOperand(0);
return Value();
}
void internal::GpuAsyncOpConversionSetChain(Value chain,
PatternRewriter &rewriter) {
Operation *terminator = chain.getParentRegion()->back().getTerminator();
rewriter.updateRootInPlace(
terminator, [&] { terminator->setOperands(ValueRange(chain)); });
}
namespace {
// Wraps consecutive legal ops within a block into a
// tfrt_gpu_conversion.async.execute op.
struct WrapInAsyncExecPattern : public OpRewritePattern<FuncOp> {
WrapInAsyncExecPattern(MLIRContext *context, ConversionTarget &target);
private:
LogicalResult matchAndRewrite(FuncOp op,
PatternRewriter &rewriter) const override;
LogicalResult matchAndRewriteBlock(Block *block,
PatternRewriter &rewriter) const;
ConversionTarget ⌖
};
// Moves the body of a tfrt_gpu_conversion.async.execute op into the parent
// block and removes the op.
//
// %t0 = tfrt_gpu.cast %ch0, %stream : !gpu.async.token
// %t1 = tfrt_gpu_conversion.async.execute [%t0] {
// ^bb(%0 : !tfrt.chain, %1 : !tfrt_gpu.stream)
// ... ops using %0 and %1 ...
// tfrt.return %n : !tfrt.chain
// }
//
// will be rewritten to
//
// %t0 = tfrt_gpu.cast %ch0, %stream : !gpu.async.token
// ... ops using %ch0 and %stream ...
// %t1 = tfrt_gpu.cast %n, %stream : !gpu.async.token
//
struct UnwrapAsyncExecPattern
: public OpConversionPattern<conversion::AsyncExecuteOp> {
using OpConversionPattern::OpConversionPattern;
private:
LogicalResult matchAndRewrite(
conversion::AsyncExecuteOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override;
};
// Rewrites a function with two gpu.wait ops to take extra !tfrt.chain and
// !tfrt_gpu.stream arguments and return a !tfrt.chain.
//
// func @main(...) {
// %0 = gpu.wait async
// ...
// gpu.wait [%n]
// return
// }
//
// will be rewritten to
//
// func @main(%chain : !tfrt:chain, %stream : !tfrt_gpu.stream, ...) ->
// !tfrt.chain {
// %0 = tfrt_gpu_conversion.cast %chain, %stream : !gpu.async.token
// ...
// %result = tfrt_gpu_conversion.cast %n : !tfrt.chain
// tfrt.return %result
// }
//
struct HoistGpuWaitsPattern : public OpRewritePattern<FuncOp> {
using OpRewritePattern::OpRewritePattern;
private:
LogicalResult matchAndRewrite(FuncOp op,
PatternRewriter &rewriter) const override;
};
} // namespace
WrapInAsyncExecPattern::WrapInAsyncExecPattern(MLIRContext *context,
ConversionTarget &target)
: OpRewritePattern(context), target(target) {}
LogicalResult WrapInAsyncExecPattern::matchAndRewrite(
FuncOp op, PatternRewriter &rewriter) const {
rewriter.startRootUpdate(op);
LogicalResult result = failure();
op.walk([&](Block *block) {
if (dyn_cast<conversion::AsyncExecuteOp>(block->getParentOp()))
return WalkResult::skip();
if (succeeded(matchAndRewriteBlock(block, rewriter)))
result = success(); //
return WalkResult::advance();
});
succeeded(result) ? rewriter.finalizeRootUpdate(op)
: rewriter.cancelRootUpdate(op);
return result;
}
// Iterate over ops in block, and whenever we transition from a legal to an
// illegal op, wrap preceding legal ops in !tfrt_gpu_conversion.async.execute.
LogicalResult WrapInAsyncExecPattern::matchAndRewriteBlock(
Block *block, PatternRewriter &rewriter) const {
LogicalResult result = failure();
Operation *legal_begin = nullptr;
for (Operation *op : llvm::make_pointer_range(block->getOperations())) {
if (target.isLegal(op)) {
if (!legal_begin) // Start of legal op sequence.
legal_begin = op;
continue;
}
if (!legal_begin) // Continue in illegal op sequence.
continue;
rewriter.setInsertionPoint(legal_begin);
auto loc = legal_begin->getLoc();
auto *body = rewriter.create<conversion::AsyncExecuteOp>(loc).getBody();
// Move sequence of legal ops into !tfrt_gpu_conversion.async.execute body.
body->getOperations().splice(body->begin(), op->getBlock()->getOperations(),
legal_begin->getIterator(), op->getIterator());
legal_begin = nullptr; // Start of illegal op sequence.
result = success();
}
return result;
}
LogicalResult UnwrapAsyncExecPattern::matchAndRewrite(
conversion::AsyncExecuteOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const {
if (!op->getNumResults())
return rewriter.notifyMatchFailure(op, "has no result");
auto cast_op = [&]() -> Operation * {
if (operands.empty()) return nullptr;
return operands.front().getDefiningOp<conversion::CastOp>();
}();
if (!cast_op || cast_op->getNumOperands() != 2 ||
!cast_op->getOperand(0).getType().isa<ChainType>() ||
!cast_op->getOperand(1).getType().isa<StreamType>())
return rewriter.notifyMatchFailure(op, "no !tfrt_gpu_conversion.cast user");
// Merge !tfrt_gpu_conversion.async.execute body into parent block.
Operation *terminator = op.getBody()->getTerminator();
rewriter.mergeBlockBefore(op.getBody(), op, cast_op->getOperands());
rewriter.replaceOpWithNewOp<conversion::CastOp>(
op, rewriter.getType<mlir::gpu::AsyncTokenType>(),
ValueRange{terminator->getOperand(0), cast_op->getOperand(1)});
rewriter.eraseOp(terminator);
return success();
}
LogicalResult HoistGpuWaitsPattern::matchAndRewrite(
FuncOp op, PatternRewriter &rewriter) const {
auto range = op.body().getOps<mlir::gpu::WaitOp>();
SmallVector<Operation *, 2> wait_ops(range.begin(), range.end());
// Require 2 gpu.async.wait ops:
// wait_ops[0] needs to be of the form `%token = gpu.wait async`.
// wait_ops[1] needs to be of the form `gpu.wait [%token]`.
if (wait_ops.size() != 2)
return rewriter.notifyMatchFailure(op, "expected 2 !gpu.async.wait ops");
for (int i : {0, 1}) {
if (wait_ops[i]->getNumResults() == i || wait_ops[i]->getNumOperands() != i)
return rewriter.notifyMatchFailure(op, "unexpected !gpu.async.wait form");
}
// Add !tfrt.chain, !tfrt_gpu.stream arguments and !tfrt.chain result.
auto chain_type = rewriter.getType<ChainType>();
SmallVector<Type, 8> input_types;
input_types.reserve(op.getNumArguments() + 2);
input_types.push_back(chain_type);
input_types.push_back(rewriter.getType<StreamType>());
copy(op.getArgumentTypes(), std::back_inserter(input_types));
rewriter.updateRootInPlace(op, [&] {
op.setType(rewriter.getType<mlir::FunctionType>(input_types,
TypeRange(chain_type)));
});
// Add new function arguments to entry block. This is a bit of a dance
// so that it could be rolled back in case of conversion failure.
Block *block = &op.body().front();
Block *entry = rewriter.createBlock(block, input_types);
auto block_args = entry->getArguments();
rewriter.mergeBlocks(block, entry, block_args.drop_front(2));
// Replace wait_ops[0] with cast of new block arguments to !gpu.async.token.
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPointToStart(&op.body().front());
rewriter.replaceOpWithNewOp<conversion::CastOp>(
wait_ops[0], rewriter.getType<mlir::gpu::AsyncTokenType>(),
block_args.take_front(2));
// Replace wait_ops[1] with cast of its token operand to !tfrt.chain.
Operation *terminator = op.body().back().getTerminator();
rewriter.setInsertionPointAfter(terminator);
auto cast = rewriter.create<conversion::CastOp>(
wait_ops[1]->getLoc(), chain_type, wait_ops[1]->getOperands());
rewriter.eraseOp(wait_ops[1]);
// Return casted !tfrt.chain.
rewriter.replaceOpWithNewOp<tfrt::ReturnOp>(terminator, cast->getResults());
return success();
}
void populateGpuAsyncConversionPatterns(RewritePatternSet &patterns,
mlir::ConversionTarget &target) {
patterns.add<WrapInAsyncExecPattern>(patterns.getContext(), target);
}
void populateTfrtConversionPatterns(mlir::RewritePatternSet &patterns,
mlir::TypeConverter &converter,
mlir::ConversionTarget &target) {
patterns.add<UnwrapAsyncExecPattern, HoistGpuWaitsPattern>(
patterns.getContext());
// Cast ops are unused after conversion, but DCE needs to be run separately.
target.addLegalOp<conversion::CastOp>();
// Signature needs to be `(!tfrt.chain, !tfrt.stream, ...) -> (!tfrt.chain)`.
target.addDynamicallyLegalOp<FuncOp>([](FuncOp op) {
auto type = op.getType();
return type.getNumResults() == 1 && type.getResult(0).isa<ChainType>() &&
type.getNumInputs() >= 2 && type.getInput(0).isa<ChainType>() &&
type.getInput(1).isa<StreamType>();
});
}
} // namespace gpu
} // namespace tfrt
|
// Copyright 2020 The TensorFlow Runtime Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "tfrt/gpu/pass/pass.h"
#include "llvm/ADT/STLExtras.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/OperationSupport.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/Types.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/DialectConversion.h"
#include "tfrt/basic_kernels/opdefs/tfrt_base.h"
#include "tfrt/basic_kernels/opdefs/types.h"
#include "tfrt/gpu/kernels/gpu_ops.h"
namespace tfrt {
namespace gpu {
Value internal::GpuAsyncOpConversionGetStream(Operation *parent) {
if (auto exec_op = dyn_cast_or_null<conversion::AsyncExecuteOp>(parent))
return exec_op.body().getArgument(1);
return Value();
}
Value internal::GpuAsyncOpConversionGetChain(Operation *parent) {
if (auto exec_op = dyn_cast_or_null<conversion::AsyncExecuteOp>(parent))
return exec_op.body().back().getTerminator()->getOperand(0);
return Value();
}
void internal::GpuAsyncOpConversionSetChain(Value chain,
PatternRewriter &rewriter) {
Operation *terminator = chain.getParentRegion()->back().getTerminator();
rewriter.updateRootInPlace(
terminator, [&] { terminator->setOperands(ValueRange(chain)); });
}
namespace {
// Wraps consecutive legal ops within a block into a
// tfrt_gpu_conversion.async.execute op.
struct WrapInAsyncExecPattern : public OpRewritePattern<FuncOp> {
WrapInAsyncExecPattern(MLIRContext *context, ConversionTarget &target);
private:
LogicalResult matchAndRewrite(FuncOp op,
PatternRewriter &rewriter) const override;
LogicalResult matchAndRewriteBlock(Block *block,
PatternRewriter &rewriter) const;
ConversionTarget ⌖
};
// Moves the body of a tfrt_gpu_conversion.async.execute op into the parent
// block and removes the op.
//
// %t0 = tfrt_gpu.cast %ch0, %stream : !gpu.async.token
// %t1 = tfrt_gpu_conversion.async.execute [%t0] {
// ^bb(%0 : !tfrt.chain, %1 : !tfrt_gpu.stream)
// ... ops using %0 and %1 ...
// tfrt.return %n : !tfrt.chain
// }
//
// will be rewritten to
//
// %t0 = tfrt_gpu.cast %ch0, %stream : !gpu.async.token
// ... ops using %ch0 and %stream ...
// %t1 = tfrt_gpu.cast %n, %stream : !gpu.async.token
//
struct UnwrapAsyncExecPattern
: public OpConversionPattern<conversion::AsyncExecuteOp> {
using OpConversionPattern::OpConversionPattern;
private:
LogicalResult matchAndRewrite(
conversion::AsyncExecuteOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const override;
};
// Rewrites a function with two gpu.wait ops to take extra !tfrt.chain and
// !tfrt_gpu.stream arguments and return a !tfrt.chain.
//
// func @main(...) {
// %0 = gpu.wait async
// ...
// gpu.wait [%n]
// return
// }
//
// will be rewritten to
//
// func @main(%chain : !tfrt:chain, %stream : !tfrt_gpu.stream, ...) ->
// !tfrt.chain {
// %0 = tfrt_gpu_conversion.cast %chain, %stream : !gpu.async.token
// ...
// %result = tfrt_gpu_conversion.cast %n : !tfrt.chain
// tfrt.return %result
// }
//
struct HoistGpuWaitsPattern : public OpRewritePattern<FuncOp> {
using OpRewritePattern::OpRewritePattern;
private:
LogicalResult matchAndRewrite(FuncOp op,
PatternRewriter &rewriter) const override;
};
} // namespace
WrapInAsyncExecPattern::WrapInAsyncExecPattern(MLIRContext *context,
ConversionTarget &target)
: OpRewritePattern(context), target(target) {}
LogicalResult WrapInAsyncExecPattern::matchAndRewrite(
FuncOp op, PatternRewriter &rewriter) const {
rewriter.startRootUpdate(op);
LogicalResult result = failure();
op.walk([&](Block *block) {
if (dyn_cast<conversion::AsyncExecuteOp>(block->getParentOp()))
return WalkResult::skip();
if (succeeded(matchAndRewriteBlock(block, rewriter)))
result = success(); //
return WalkResult::advance();
});
succeeded(result) ? rewriter.finalizeRootUpdate(op)
: rewriter.cancelRootUpdate(op);
return result;
}
// Iterate over ops in block, and whenever we transition from a legal to an
// illegal op, wrap preceding legal ops in !tfrt_gpu_conversion.async.execute.
LogicalResult WrapInAsyncExecPattern::matchAndRewriteBlock(
Block *block, PatternRewriter &rewriter) const {
LogicalResult result = failure();
Operation *legal_begin = nullptr;
for (Operation *op : llvm::make_pointer_range(block->getOperations())) {
if (target.isLegal(op)) {
if (!legal_begin) // Start of legal op sequence.
legal_begin = op;
continue;
}
if (!legal_begin) // Continue in illegal op sequence.
continue;
rewriter.setInsertionPoint(legal_begin);
auto loc = legal_begin->getLoc();
auto *body = rewriter.create<conversion::AsyncExecuteOp>(loc).getBody();
// Move sequence of legal ops into !tfrt_gpu_conversion.async.execute body.
body->getOperations().splice(body->begin(), op->getBlock()->getOperations(),
legal_begin->getIterator(), op->getIterator());
legal_begin = nullptr; // Start of illegal op sequence.
result = success();
}
return result;
}
LogicalResult UnwrapAsyncExecPattern::matchAndRewrite(
conversion::AsyncExecuteOp op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const {
if (!op->getNumResults())
return rewriter.notifyMatchFailure(op, "has no result");
auto cast_op = [&]() -> Operation * {
if (operands.empty()) return nullptr;
return operands.front().getDefiningOp<conversion::CastOp>();
}();
if (!cast_op || cast_op->getNumOperands() != 2 ||
!cast_op->getOperand(0).getType().isa<ChainType>() ||
!cast_op->getOperand(1).getType().isa<StreamType>())
return rewriter.notifyMatchFailure(op, "no !tfrt_gpu_conversion.cast user");
// Merge !tfrt_gpu_conversion.async.execute body into parent block.
Operation *terminator = op.getBody()->getTerminator();
rewriter.mergeBlockBefore(op.getBody(), op, cast_op->getOperands());
rewriter.replaceOpWithNewOp<conversion::CastOp>(
op, rewriter.getType<mlir::gpu::AsyncTokenType>(),
ValueRange{terminator->getOperand(0), cast_op->getOperand(1)});
rewriter.eraseOp(terminator);
return success();
}
LogicalResult HoistGpuWaitsPattern::matchAndRewrite(
FuncOp op, PatternRewriter &rewriter) const {
auto range = op.body().getOps<mlir::gpu::WaitOp>();
SmallVector<Operation *, 2> wait_ops(range.begin(), range.end());
// Require 2 gpu.async.wait ops:
// wait_ops[0] needs to be of the form `%token = gpu.wait async`.
// wait_ops[1] needs to be of the form `gpu.wait [%token]`.
if (wait_ops.size() != 2)
return rewriter.notifyMatchFailure(op, "expected 2 !gpu.async.wait ops");
for (int i : {0, 1}) {
if (wait_ops[i]->getNumResults() == i || wait_ops[i]->getNumOperands() != i)
return rewriter.notifyMatchFailure(op, "unexpected !gpu.async.wait form");
}
// Add !tfrt.chain, !tfrt_gpu.stream arguments and !tfrt.chain result.
auto chain_type = rewriter.getType<ChainType>();
SmallVector<Type, 8> input_types;
input_types.reserve(op.getNumArguments() + 2);
input_types.push_back(chain_type);
input_types.push_back(rewriter.getType<StreamType>());
copy(op.getArgumentTypes(), std::back_inserter(input_types));
rewriter.updateRootInPlace(op, [&] {
op.setType(rewriter.getType<mlir::FunctionType>(input_types,
TypeRange(chain_type)));
});
// Add new function arguments to entry block. This is a bit of a dance
// so that it could be rolled back in case of conversion failure.
Block *block = &op.body().front();
Block *entry = rewriter.createBlock(block, input_types);
auto block_args = entry->getArguments();
rewriter.mergeBlocks(block, entry, block_args.drop_front(2));
// Replace wait_ops[0] with cast of new block arguments to !gpu.async.token.
OpBuilder::InsertionGuard guard(rewriter);
rewriter.setInsertionPointToStart(&op.body().front());
rewriter.replaceOpWithNewOp<conversion::CastOp>(
wait_ops[0], rewriter.getType<mlir::gpu::AsyncTokenType>(),
block_args.take_front(2));
// Replace wait_ops[1] with cast of its token operand to !tfrt.chain.
Operation *terminator = op.body().back().getTerminator();
rewriter.setInsertionPointAfter(terminator);
auto cast = rewriter.create<conversion::CastOp>(
wait_ops[1]->getLoc(), chain_type, wait_ops[1]->getOperands());
rewriter.eraseOp(wait_ops[1]);
// Return casted !tfrt.chain.
rewriter.replaceOpWithNewOp<tfrt::ReturnOp>(terminator, cast->getResults());
return success();
}
void populateGpuAsyncConversionPatterns(RewritePatternSet &patterns,
mlir::ConversionTarget &target) {
patterns.add<WrapInAsyncExecPattern>(patterns.getContext(), target);
}
void populateTfrtConversionPatterns(mlir::RewritePatternSet &patterns,
mlir::ConversionTarget &target) {
patterns.add<UnwrapAsyncExecPattern, HoistGpuWaitsPattern>(
patterns.getContext());
// Cast ops are unused after conversion, but DCE needs to be run separately.
target.addLegalOp<conversion::CastOp>();
// Signature needs to be `(!tfrt.chain, !tfrt.stream, ...) -> (!tfrt.chain)`.
target.addDynamicallyLegalOp<FuncOp>([](FuncOp op) {
auto type = op.getType();
return type.getNumResults() == 1 && type.getResult(0).isa<ChainType>() &&
type.getNumInputs() >= 2 && type.getInput(0).isa<ChainType>() &&
type.getInput(1).isa<StreamType>();
});
}
} // namespace gpu
} // namespace tfrt
|
Fix `populateTfrtConversionPatterns` implementation signature.
|
Fix `populateTfrtConversionPatterns` implementation signature.
PiperOrigin-RevId: 372440937
|
C++
|
apache-2.0
|
tensorflow/runtime,tensorflow/runtime,tensorflow/runtime,tensorflow/runtime
|
4c14c6f82c81dc2783f59445f56c63777765ad9e
|
src/api/bindings_common.cc
|
src/api/bindings_common.cc
|
// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/api/bindings_common.h"
#include "base/logging.h"
#include "base/values.h"
#include "content/nw/src/api/api_messages.h"
#include "content/public/renderer/render_view.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/v8_value_converter.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "ui/base/resource/resource_bundle.h"
using content::RenderView;
using content::RenderThread;
using content::V8ValueConverter;
using WebKit::WebFrame;
using WebKit::WebView;
namespace {
RenderView* GetRenderView(v8::Handle<v8::Context> ctx) {
WebFrame* frame = WebFrame::frameForContext(ctx);
if (!frame)
return NULL;
WebView* view = frame->view();
if (!view)
return NULL; // can happen during closing.
RenderView* render_view = RenderView::FromWebView(view);
return render_view;
}
}
RenderView* GetCurrentRenderView() {
v8::Local<v8::Context> ctx = v8::Context::GetCurrent();
return GetRenderView(ctx);
}
RenderView* GetEnteredRenderView() {
v8::Local<v8::Context> ctx = v8::Context::GetEntered();
return GetRenderView(ctx);
}
base::StringPiece GetStringResource(int resource_id) {
return ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id);
}
namespace remote {
v8::Handle<v8::Value> AllocateId(int routing_id) {
v8::HandleScope handle_scope;
int result = 0;
RenderThread::Get()->Send(new ShellViewHostMsg_AllocateId(
routing_id,
&result));
return v8::Integer::New(result);
}
v8::Handle<v8::Value> AllocateObject(int routing_id,
int object_id,
const std::string& type,
v8::Handle<v8::Value> options) {
v8::HandleScope handle_scope;
scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
converter->SetStripNullFromObjects(true);
scoped_ptr<base::Value> value_option(
converter->FromV8Value(options, v8::Context::GetCurrent()));
if (!value_option.get() ||
!value_option->IsType(base::Value::TYPE_DICTIONARY))
return v8::ThrowException(v8::Exception::Error(v8::String::New(
"Unable to convert 'option' passed to AllocateObject")));
DVLOG(1) << "remote::AllocateObject(routing_id=" << routing_id << ", object_id=" << object_id << ")";
RenderThread::Get()->Send(new ShellViewHostMsg_Allocate_Object(
routing_id,
object_id,
type,
*static_cast<base::DictionaryValue*>(value_option.get())));
return v8::Undefined();
}
v8::Handle<v8::Value> DeallocateObject(int routing_id,
int object_id) {
RenderThread::Get()->Send(new ShellViewHostMsg_Deallocate_Object(
routing_id, object_id));
return v8::Undefined();
}
v8::Handle<v8::Value> CallObjectMethod(int routing_id,
int object_id,
const std::string& type,
const std::string& method,
v8::Handle<v8::Value> args) {
scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
scoped_ptr<base::Value> value_args(
converter->FromV8Value(args, v8::Context::GetCurrent()));
if (!value_args.get() ||
!value_args->IsType(base::Value::TYPE_LIST))
return v8::ThrowException(v8::Exception::Error(v8::String::New(
"Unable to convert 'args' passed to CallObjectMethod")));
RenderThread::Get()->Send(new ShellViewHostMsg_Call_Object_Method(
routing_id,
object_id,
type,
method,
*static_cast<base::ListValue*>(value_args.get())));
return v8::Undefined();
}
v8::Handle<v8::Value> CallObjectMethodSync(int routing_id,
int object_id,
const std::string& type,
const std::string& method,
v8::Handle<v8::Value> args) {
scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
scoped_ptr<base::Value> value_args(
converter->FromV8Value(args, v8::Context::GetCurrent()));
if (!value_args.get() ||
!value_args->IsType(base::Value::TYPE_LIST))
return v8::ThrowException(v8::Exception::Error(v8::String::New(
"Unable to convert 'args' passed to CallObjectMethodSync")));
base::ListValue result;
RenderThread::Get()->Send(new ShellViewHostMsg_Call_Object_Method_Sync(
routing_id,
object_id,
type,
method,
*static_cast<base::ListValue*>(value_args.get()),
&result));
return converter->ToV8Value(&result, v8::Context::GetCurrent());
}
} // namespace remote
|
// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// 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 co
// pies 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 al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER 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 "content/nw/src/api/bindings_common.h"
#include "base/logging.h"
#include "base/values.h"
#include "content/nw/src/api/api_messages.h"
#include "content/public/renderer/render_view.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/v8_value_converter.h"
#include "third_party/WebKit/public/web/WebView.h"
#include "third_party/WebKit/public/web/WebFrame.h"
#include "ui/base/resource/resource_bundle.h"
using content::RenderView;
using content::RenderThread;
using content::V8ValueConverter;
using WebKit::WebFrame;
using WebKit::WebView;
namespace {
RenderView* GetRenderView(v8::Handle<v8::Context> ctx) {
WebFrame* frame = WebFrame::frameForContext(ctx);
if (!frame)
return NULL;
WebView* view = frame->view();
if (!view)
return NULL; // can happen during closing.
RenderView* render_view = RenderView::FromWebView(view);
return render_view;
}
}
RenderView* GetCurrentRenderView() {
v8::Local<v8::Context> ctx = v8::Context::GetCurrent();
return GetRenderView(ctx);
}
RenderView* GetEnteredRenderView() {
v8::Local<v8::Context> ctx = v8::Context::GetEntered();
return GetRenderView(ctx);
}
base::StringPiece GetStringResource(int resource_id) {
return ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id);
}
namespace remote {
v8::Handle<v8::Value> AllocateId(int routing_id) {
v8::HandleScope scope;
int result = 0;
RenderThread::Get()->Send(new ShellViewHostMsg_AllocateId(
routing_id,
&result));
return scope.Close(v8::Integer::New(result));
}
v8::Handle<v8::Value> AllocateObject(int routing_id,
int object_id,
const std::string& type,
v8::Handle<v8::Value> options) {
v8::HandleScope handle_scope;
scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
converter->SetStripNullFromObjects(true);
scoped_ptr<base::Value> value_option(
converter->FromV8Value(options, v8::Context::GetCurrent()));
if (!value_option.get() ||
!value_option->IsType(base::Value::TYPE_DICTIONARY))
return v8::ThrowException(v8::Exception::Error(v8::String::New(
"Unable to convert 'option' passed to AllocateObject")));
DVLOG(1) << "remote::AllocateObject(routing_id=" << routing_id << ", object_id=" << object_id << ")";
RenderThread::Get()->Send(new ShellViewHostMsg_Allocate_Object(
routing_id,
object_id,
type,
*static_cast<base::DictionaryValue*>(value_option.get())));
return v8::Undefined();
}
v8::Handle<v8::Value> DeallocateObject(int routing_id,
int object_id) {
RenderThread::Get()->Send(new ShellViewHostMsg_Deallocate_Object(
routing_id, object_id));
return v8::Undefined();
}
v8::Handle<v8::Value> CallObjectMethod(int routing_id,
int object_id,
const std::string& type,
const std::string& method,
v8::Handle<v8::Value> args) {
scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
scoped_ptr<base::Value> value_args(
converter->FromV8Value(args, v8::Context::GetCurrent()));
if (!value_args.get() ||
!value_args->IsType(base::Value::TYPE_LIST))
return v8::ThrowException(v8::Exception::Error(v8::String::New(
"Unable to convert 'args' passed to CallObjectMethod")));
RenderThread::Get()->Send(new ShellViewHostMsg_Call_Object_Method(
routing_id,
object_id,
type,
method,
*static_cast<base::ListValue*>(value_args.get())));
return v8::Undefined();
}
v8::Handle<v8::Value> CallObjectMethodSync(int routing_id,
int object_id,
const std::string& type,
const std::string& method,
v8::Handle<v8::Value> args) {
scoped_ptr<V8ValueConverter> converter(V8ValueConverter::create());
scoped_ptr<base::Value> value_args(
converter->FromV8Value(args, v8::Context::GetCurrent()));
if (!value_args.get() ||
!value_args->IsType(base::Value::TYPE_LIST))
return v8::ThrowException(v8::Exception::Error(v8::String::New(
"Unable to convert 'args' passed to CallObjectMethodSync")));
base::ListValue result;
RenderThread::Get()->Send(new ShellViewHostMsg_Call_Object_Method_Sync(
routing_id,
object_id,
type,
method,
*static_cast<base::ListValue*>(value_args.get()),
&result));
return converter->ToV8Value(&result, v8::Context::GetCurrent());
}
} // namespace remote
|
handle return v8 value correctly
|
handle return v8 value correctly
or it will crash in v8 win dbg
|
C++
|
mit
|
zhaosichao/nw.js,M4sse/nw.js,ezshine/nw.js,mcdongWang/nwjs_Chinese,jqk6/nw.js,amoylel/nw.js,xzmagic/nw.js,angeliaz/nw.js,chengky/nw.js,parksangkil/nw.js,luisbrito/nw.js,tshinnic/nw.js,Jonekee/nw.js,chinakids/nw.js,wpsmith/nw.js,GabrielNicolasAvellaneda/nw.js,yshyee/nw.js,iesus17/nw.js,trojanspike/nw.js,kurainooni/nw.js,p5150j/nw.js,weave-lab/nw.js,techlabs28/nw.js,nwjs/nw.js,askdaddy/nw.js,initialjk/node-webkit,eprincev-egor/nw.js,chinakids/nw.js,iesus17/nw.js,occupytheweb/nw.js,tshinnic/nw.js,tanzhihang/nw.js,chinakids/nw.js,mylikes/nw.js,Jonekee/nw.js,composite/nw.js,mylikes/nw.js,initialjk/node-webkit,GabrielNicolasAvellaneda/nw.js,askdaddy/nw.js,kurainooni/nw.js,Sunggil/nw.js,sumyfly/nw.js,iesus17/nw.js,Wombatpm/node-webkit,mcdongWang/nwjs_Chinese,zhangtianye/node-webkit,sumyfly/nw.js,xebitstudios/nw.js,amoylel/nw.js,mcanthony/nw.js,InnerAc/nw.js,nwjs/nw.js,weave-lab/nw.js,280455936/nw.js,dushu1203/nw.js,jaruba/nw.js,xebitstudios/nw.js,amoylel/nw.js,zhangtianye/node-webkit,mcanthony/nw.js,AustinKwang/nw.js,dougmolineux/nw.js,composite/nw.js,parlaylabs/nw.js,InnerAc/nw.js,angeliaz/nw.js,bright-sparks/nw.js,ondra-novak/nw.js,xzmagic/nw.js,eprincev-egor/nw.js,lidxgz/nw.js,jaruba/nw.js,techlabs28/nw.js,jomaf1010/nw.js,xebitstudios/nw.js,Arteris/nw.js,composite/nw.js,wpsmith/nw.js,zhangweiabc/nw.js,happy-barrage/nw.js,zhangweiabc/nw.js,tshinnic/nw.js,redgecombe/nw.js,dushu1203/nw.js,Ivshti/node-webkit,jaruba/nw.js,XenonDevelops/nw.js,amoylel/nw.js,wakermahmud/nw.js,erickuofucker/nw.js,belmer/nw.js,advisory/nw.js,initialjk/node-webkit,mcanthony/nw.js,haroldoramirez/nw.js,VolosSoftware/nw.js,PUSEN/nw.js,pdx1989/nw.js,nwjs/nw.js,advisory/nw.js,haroldoramirez/nw.js,angeliaz/nw.js,mcdongWang/nwjs_Chinese,weave-lab/nw.js,luiseduardohdbackup/nw.js,mylikes/nw.js,RobertoMalatesta/nw.js,techlabs28/nw.js,trojanspike/nw.js,haroldoramirez/nw.js,jaruba/nw.js,baiwyc119/nw.js,wakermahmud/nw.js,baiwyc119/nw.js,KaminoDice/nw.js,lifeinoppo/nw.js,280455936/nw.js,parlaylabs/nw.js,ondra-novak/nw.js,composite/nw.js,kurainooni/nw.js,kurainooni/nw.js,Jonekee/nw.js,bright-sparks/nw.js,Jonekee/nw.js,iesus17/nw.js,haroldoramirez/nw.js,iesus17/nw.js,p5150j/nw.js,pdx1989/nw.js,composite/nw.js,erickuofucker/nw.js,wpsmith/nw.js,parlaylabs/nw.js,AustinKwang/nw.js,chengky/nw.js,luiseduardohdbackup/nw.js,sumyfly/nw.js,yshyee/nw.js,techlabs28/nw.js,zcczcw/nw.js,zhangtianye/node-webkit,zhaosichao/nw.js,lifeinoppo/nw.js,belmer/nw.js,zhaosichao/nw.js,VolosSoftware/nw.js,ysjian/nw.js,AustinKwang/nw.js,ysjian/nw.js,mylikes/nw.js,baiwyc119/nw.js,luisbrito/nw.js,nwjs/nw.js,happy-barrage/nw.js,luiseduardohdbackup/nw.js,GabrielNicolasAvellaneda/nw.js,M4sse/nw.js,p5150j/nw.js,dushu1203/nw.js,bright-sparks/nw.js,yshyee/nw.js,PUSEN/nw.js,jqk6/nw.js,markYoungH/nw.js,happy-barrage/nw.js,280455936/nw.js,chengky/nw.js,jomolinare/nw.js,Arteris/nw.js,liu78778/node-webkit,glizer/nw.js,sumyfly/nw.js,imshibaji/nw.js,weave-lab/nw.js,Wombatpm/node-webkit,kurainooni/nw.js,composite/nw.js,pztrick/nw.js,parksangkil/nw.js,lifeinoppo/nw.js,zhangtianye/node-webkit,tanzhihang/nw.js,xebitstudios/nw.js,belmer/nw.js,parksangkil/nw.js,lifeinoppo/nw.js,yshyee/nw.js,M4sse/nw.js,ysjian/nw.js,zcczcw/nw.js,dushu1203/nw.js,alex-zhang/nw.js,belmer/nw.js,mcanthony/nw.js,trevorlinton/tint,chengky/nw.js,weave-lab/nw.js,angeliaz/nw.js,jomaf1010/nw.js,luiseduardohdbackup/nw.js,mvinan/nw.js,zhangweiabc/nw.js,haroldoramirez/nw.js,artBrown/nw.js,GabrielNicolasAvellaneda/nw.js,zcczcw/nw.js,chinakids/nw.js,glizer/nw.js,wpsmith/nw.js,M4sse/nw.js,xzmagic/nw.js,ysjian/nw.js,luisbrito/nw.js,zhangtianye/node-webkit,ezshine/nw.js,M4sse/nw.js,GabrielNicolasAvellaneda/nw.js,haroldoramirez/nw.js,zcczcw/nw.js,mauricionr/nw.js,PUSEN/nw.js,jomaf1010/nw.js,280455936/nw.js,youprofit/nw.js,zhaosichao/nw.js,trevorlinton/tint,fancycode/node-webkit,Wombatpm/node-webkit,advisory/nw.js,280455936/nw.js,AustinKwang/nw.js,occupytheweb/nw.js,dougmolineux/nw.js,mauricionr/nw.js,markYoungH/nw.js,Arteris/nw.js,yshyee/nw.js,ysjian/nw.js,lidxgz/nw.js,youprofit/nw.js,happy-barrage/nw.js,Jonekee/nw.js,trojanspike/nw.js,lifeinoppo/nw.js,Arteris/nw.js,mvinan/nw.js,baiwyc119/nw.js,Jonekee/nw.js,RobertoMalatesta/nw.js,zhangweiabc/nw.js,chinakids/nw.js,PUSEN/nw.js,luiseduardohdbackup/nw.js,eprincev-egor/nw.js,mvinan/nw.js,chengky/nw.js,pdx1989/nw.js,happy-barrage/nw.js,Wombatpm/node-webkit,happy-barrage/nw.js,tanzhihang/nw.js,initialjk/node-webkit,youprofit/nw.js,sumyfly/nw.js,Jonekee/nw.js,youprofit/nw.js,KaminoDice/nw.js,jqk6/nw.js,liu78778/node-webkit,Ivshti/node-webkit,jomaf1010/nw.js,redgecombe/nw.js,eprincev-egor/nw.js,iesus17/nw.js,KaminoDice/nw.js,baiwyc119/nw.js,fancycode/node-webkit,liu78778/node-webkit,InnerAc/nw.js,mauricionr/nw.js,jomaf1010/nw.js,Ivshti/node-webkit,erickuofucker/nw.js,InnerAc/nw.js,VolosSoftware/nw.js,RobertoMalatesta/nw.js,baiwyc119/nw.js,wakermahmud/nw.js,mvinan/nw.js,amoylel/nw.js,KaminoDice/nw.js,advisory/nw.js,imshibaji/nw.js,glizer/nw.js,wakermahmud/nw.js,advisory/nw.js,jaruba/nw.js,artBrown/nw.js,alex-zhang/nw.js,imshibaji/nw.js,imshibaji/nw.js,artBrown/nw.js,zhangweiabc/nw.js,mcdongWang/nwjs_Chinese,dougmolineux/nw.js,Ivshti/node-webkit,zhaosichao/nw.js,XenonDevelops/nw.js,zhangtianye/node-webkit,parksangkil/nw.js,ondra-novak/nw.js,mvinan/nw.js,zcczcw/nw.js,ezshine/nw.js,wakermahmud/nw.js,pdx1989/nw.js,wakermahmud/nw.js,luisbrito/nw.js,alex-zhang/nw.js,pztrick/nw.js,nwjs/nw.js,xebitstudios/nw.js,zcczcw/nw.js,eprincev-egor/nw.js,p5150j/nw.js,ezshine/nw.js,Ivshti/node-webkit,bright-sparks/nw.js,artBrown/nw.js,askdaddy/nw.js,redgecombe/nw.js,parlaylabs/nw.js,GabrielNicolasAvellaneda/nw.js,redgecombe/nw.js,mylikes/nw.js,KaminoDice/nw.js,glizer/nw.js,p5150j/nw.js,p5150j/nw.js,xzmagic/nw.js,Arteris/nw.js,xzmagic/nw.js,zhangweiabc/nw.js,zhangweiabc/nw.js,XenonDevelops/nw.js,alex-zhang/nw.js,dushu1203/nw.js,yshyee/nw.js,baiwyc119/nw.js,parlaylabs/nw.js,trojanspike/nw.js,amoylel/nw.js,dougmolineux/nw.js,lidxgz/nw.js,parksangkil/nw.js,belmer/nw.js,pdx1989/nw.js,AustinKwang/nw.js,techlabs28/nw.js,erickuofucker/nw.js,angeliaz/nw.js,advisory/nw.js,askdaddy/nw.js,Arteris/nw.js,lifeinoppo/nw.js,kurainooni/nw.js,artBrown/nw.js,Arteris/nw.js,RobertoMalatesta/nw.js,RobertoMalatesta/nw.js,askdaddy/nw.js,wakermahmud/nw.js,mylikes/nw.js,trevorlinton/tint,Sunggil/nw.js,XenonDevelops/nw.js,dougmolineux/nw.js,pdx1989/nw.js,InnerAc/nw.js,initialjk/node-webkit,haroldoramirez/nw.js,tshinnic/nw.js,techlabs28/nw.js,XenonDevelops/nw.js,ondra-novak/nw.js,nwjs/nw.js,markYoungH/nw.js,askdaddy/nw.js,jomolinare/nw.js,mcanthony/nw.js,lidxgz/nw.js,artBrown/nw.js,kurainooni/nw.js,parlaylabs/nw.js,jaruba/nw.js,tanzhihang/nw.js,glizer/nw.js,VolosSoftware/nw.js,zhaosichao/nw.js,weave-lab/nw.js,jomolinare/nw.js,PUSEN/nw.js,VolosSoftware/nw.js,chengky/nw.js,pztrick/nw.js,jqk6/nw.js,Sunggil/nw.js,xebitstudios/nw.js,yshyee/nw.js,Sunggil/nw.js,RobertoMalatesta/nw.js,mvinan/nw.js,ondra-novak/nw.js,liu78778/node-webkit,erickuofucker/nw.js,M4sse/nw.js,fancycode/node-webkit,mvinan/nw.js,liu78778/node-webkit,eprincev-egor/nw.js,jomolinare/nw.js,GabrielNicolasAvellaneda/nw.js,belmer/nw.js,youprofit/nw.js,ezshine/nw.js,RobertoMalatesta/nw.js,trevorlinton/tint,Wombatpm/node-webkit,markYoungH/nw.js,redgecombe/nw.js,ezshine/nw.js,VolosSoftware/nw.js,initialjk/node-webkit,bright-sparks/nw.js,jomolinare/nw.js,Wombatpm/node-webkit,occupytheweb/nw.js,luisbrito/nw.js,initialjk/node-webkit,alex-zhang/nw.js,redgecombe/nw.js,mauricionr/nw.js,mcdongWang/nwjs_Chinese,ondra-novak/nw.js,happy-barrage/nw.js,artBrown/nw.js,PUSEN/nw.js,angeliaz/nw.js,youprofit/nw.js,AustinKwang/nw.js,VolosSoftware/nw.js,eprincev-egor/nw.js,tanzhihang/nw.js,ondra-novak/nw.js,Sunggil/nw.js,mcanthony/nw.js,dushu1203/nw.js,zhaosichao/nw.js,belmer/nw.js,jqk6/nw.js,parlaylabs/nw.js,askdaddy/nw.js,weave-lab/nw.js,fancycode/node-webkit,markYoungH/nw.js,iesus17/nw.js,trojanspike/nw.js,ysjian/nw.js,KaminoDice/nw.js,wpsmith/nw.js,alex-zhang/nw.js,mylikes/nw.js,occupytheweb/nw.js,pztrick/nw.js,InnerAc/nw.js,imshibaji/nw.js,Ivshti/node-webkit,jomaf1010/nw.js,jaruba/nw.js,erickuofucker/nw.js,bright-sparks/nw.js,trojanspike/nw.js,mcanthony/nw.js,trojanspike/nw.js,xebitstudios/nw.js,jomolinare/nw.js,tshinnic/nw.js,occupytheweb/nw.js,sumyfly/nw.js,XenonDevelops/nw.js,parksangkil/nw.js,280455936/nw.js,chengky/nw.js,lidxgz/nw.js,tanzhihang/nw.js,pdx1989/nw.js,M4sse/nw.js,pztrick/nw.js,luisbrito/nw.js,ysjian/nw.js,280455936/nw.js,youprofit/nw.js,lifeinoppo/nw.js,Sunggil/nw.js,pztrick/nw.js,composite/nw.js,tshinnic/nw.js,glizer/nw.js,mcdongWang/nwjs_Chinese,alex-zhang/nw.js,luiseduardohdbackup/nw.js,techlabs28/nw.js,glizer/nw.js,trevorlinton/tint,AustinKwang/nw.js,wpsmith/nw.js,mauricionr/nw.js,tanzhihang/nw.js,Sunggil/nw.js,advisory/nw.js,trevorlinton/tint,ezshine/nw.js,zcczcw/nw.js,p5150j/nw.js,dougmolineux/nw.js,amoylel/nw.js,wpsmith/nw.js,XenonDevelops/nw.js,fancycode/node-webkit,imshibaji/nw.js,mauricionr/nw.js,imshibaji/nw.js,dougmolineux/nw.js,liu78778/node-webkit,KaminoDice/nw.js,xzmagic/nw.js,jomolinare/nw.js,sumyfly/nw.js,pztrick/nw.js,parksangkil/nw.js,PUSEN/nw.js,chinakids/nw.js,chinakids/nw.js,luiseduardohdbackup/nw.js,markYoungH/nw.js,jqk6/nw.js,luisbrito/nw.js,erickuofucker/nw.js,jomaf1010/nw.js,redgecombe/nw.js,lidxgz/nw.js,jqk6/nw.js,bright-sparks/nw.js,xzmagic/nw.js,dushu1203/nw.js,occupytheweb/nw.js,InnerAc/nw.js,angeliaz/nw.js,lidxgz/nw.js,occupytheweb/nw.js,tshinnic/nw.js,markYoungH/nw.js,fancycode/node-webkit,Wombatpm/node-webkit
|
9c5c7506056bdacdee8f23584efa4d5fdc76563e
|
src/backend/concurrency/optimistic_transaction_manager.cpp
|
src/backend/concurrency/optimistic_transaction_manager.cpp
|
//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// transaction_manager.cpp
//
// Identification: src/backend/concurrency/optimistic_transaction_manager.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimistic_transaction_manager.h"
#include "backend/common/platform.h"
#include "backend/logging/log_manager.h"
#include "backend/logging/records/transaction_record.h"
#include "backend/concurrency/transaction.h"
#include "backend/catalog/manager.h"
#include "backend/common/exception.h"
#include "backend/common/logger.h"
#include "backend/storage/data_table.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/tile_group_header.h"
namespace peloton {
namespace concurrency {
OptimisticTransactionManager &OptimisticTransactionManager::GetInstance() {
static OptimisticTransactionManager txn_manager;
return txn_manager;
}
// Visibility check
bool OptimisticTransactionManager::IsVisible(const txn_id_t &tuple_txn_id,
const cid_t &tuple_begin_cid,
const cid_t &tuple_end_cid) {
if (tuple_txn_id == INVALID_TXN_ID) {
// the tuple is not available.
return false;
}
bool own = (current_txn->GetTransactionId() == tuple_txn_id);
// there are exactly two versions that can be owned by a transaction.
if (own == true) {
if (tuple_begin_cid == MAX_CID && tuple_end_cid != INVALID_CID) {
assert(tuple_end_cid == MAX_CID);
// the only version that is visible is the newly inserted one.
return true;
} else {
// the older version is not visible.
return false;
}
} else {
bool activated = (current_txn->GetStartCommitId() >= tuple_begin_cid);
bool invalidated = (current_txn->GetStartCommitId() >= tuple_end_cid);
if (tuple_txn_id != INITIAL_TXN_ID) {
// if the tuple is owned by other transactions.
if (tuple_begin_cid == MAX_CID) {
// currently, we do not handle cascading abort. so never read an
// uncommitted version.
return false;
} else {
// the older version may be visible.
if (activated && !invalidated) {
return true;
} else {
return false;
}
}
} else {
// if the tuple is not owned by any transaction.
if (activated && !invalidated) {
return true;
} else {
return false;
}
}
}
}
bool OptimisticTransactionManager::RecordRead(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordRead(tile_group_id, tuple_id);
return true;
}
bool OptimisticTransactionManager::RecordWrite(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordWrite(tile_group_id, tuple_id);
return true;
}
bool OptimisticTransactionManager::RecordInsert(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordInsert(tile_group_id, tuple_id);
return true;
}
bool OptimisticTransactionManager::RecordDelete(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordDelete(tile_group_id, tuple_id);
return true;
}
void OptimisticTransactionManager::CommitTransaction() {
LOG_INFO("Committing peloton txn : %lu ", current_txn->GetTransactionId());
auto &manager = catalog::Manager::GetInstance();
// generate transaction id.
cid_t end_commit_id = GetNextCommitId();
// validate read set.
auto read_tuples = current_txn->GetReadTuples();
for (auto entry : read_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
if (tile_group_header->GetTransactionId(tuple_slot) ==
current_txn->GetTransactionId()) {
// the version is owned by the transaction.
continue;
} else {
if (tile_group_header->GetTransactionId(tuple_slot) == INITIAL_TXN_ID &&
tile_group_header->GetBeginCommitId(tuple_slot) <= end_commit_id &&
tile_group_header->GetEndCommitId(tuple_slot) >= end_commit_id) {
// the version is not locked and still visible.
continue;
}
}
// otherwise, validation fails. abort transaction.
AbortTransaction();
return;
}
}
auto written_tuples = current_txn->GetWrittenTuples();
// install all updates.
for (auto entry : written_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
// we must guarantee that, at any time point, only one version is visible.
tile_group_header->SetEndCommitId(tuple_slot, end_commit_id);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetBeginCommitId(new_version.offset,
end_commit_id);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
COMPILER_MEMORY_FENCE;
new_tile_group_header->SetTransactionId(new_version.offset,
INITIAL_TXN_ID);
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
}
}
// commit insert set.
auto inserted_tuples = current_txn->GetInsertedTuples();
size_t insert_count = 0;
for (auto entry : inserted_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
for (auto tuple_slot : entry.second) {
tile_group->CommitInsertedTuple(
tuple_slot, current_txn->GetTransactionId(), end_commit_id);
}
}
// commit delete set.
auto deleted_tuples = current_txn->GetDeletedTuples();
for (auto entry : deleted_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
// we must guarantee that, at any time point, only one version is visible.
tile_group_header->SetEndCommitId(tuple_slot, end_commit_id);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetBeginCommitId(new_version.offset,
end_commit_id);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
COMPILER_MEMORY_FENCE;
new_tile_group_header->SetTransactionId(new_version.offset,
INVALID_TXN_ID);
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
}
}
delete current_txn;
}
void OptimisticTransactionManager::AbortTransaction() {
LOG_INFO("Aborting peloton txn : %lu ", current_txn->GetTransactionId());
auto &manager = catalog::Manager::GetInstance();
auto written_tuples = current_txn->GetWrittenTuples();
// recover write set.
for (auto entry : written_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
tile_group_header->SetEndCommitId(tuple_slot, MAX_CID);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetTransactionId(new_version.offset,
INVALID_TXN_ID);
new_tile_group_header->SetBeginCommitId(new_version.offset, MAX_CID);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
}
}
// recover delete set.
auto deleted_tuples = current_txn->GetDeletedTuples();
for (auto entry : deleted_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
tile_group_header->SetEndCommitId(tuple_slot, MAX_CID);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetTransactionId(new_version.offset,
INVALID_TXN_ID);
new_tile_group_header->SetBeginCommitId(new_version.offset, MAX_CID);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
}
}
delete current_txn;
}
} // End storage namespace
} // End peloton namespace
|
//===----------------------------------------------------------------------===//
//
// PelotonDB
//
// transaction_manager.cpp
//
// Identification: src/backend/concurrency/optimistic_transaction_manager.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimistic_transaction_manager.h"
#include "backend/common/platform.h"
#include "backend/logging/log_manager.h"
#include "backend/logging/records/transaction_record.h"
#include "backend/concurrency/transaction.h"
#include "backend/catalog/manager.h"
#include "backend/common/exception.h"
#include "backend/common/logger.h"
#include "backend/storage/data_table.h"
#include "backend/storage/tile_group.h"
#include "backend/storage/tile_group_header.h"
namespace peloton {
namespace concurrency {
OptimisticTransactionManager &OptimisticTransactionManager::GetInstance() {
static OptimisticTransactionManager txn_manager;
return txn_manager;
}
// Visibility check
bool OptimisticTransactionManager::IsVisible(const txn_id_t &tuple_txn_id,
const cid_t &tuple_begin_cid,
const cid_t &tuple_end_cid) {
if (tuple_txn_id == INVALID_TXN_ID) {
// the tuple is not available.
return false;
}
bool own = (current_txn->GetTransactionId() == tuple_txn_id);
// there are exactly two versions that can be owned by a transaction.
if (own == true) {
if (tuple_begin_cid == MAX_CID && tuple_end_cid != INVALID_CID) {
assert(tuple_end_cid == MAX_CID);
// the only version that is visible is the newly inserted one.
return true;
} else {
// the older version is not visible.
return false;
}
} else {
bool activated = (current_txn->GetStartCommitId() >= tuple_begin_cid);
bool invalidated = (current_txn->GetStartCommitId() >= tuple_end_cid);
if (tuple_txn_id != INITIAL_TXN_ID) {
// if the tuple is owned by other transactions.
if (tuple_begin_cid == MAX_CID) {
// currently, we do not handle cascading abort. so never read an
// uncommitted version.
return false;
} else {
// the older version may be visible.
if (activated && !invalidated) {
return true;
} else {
return false;
}
}
} else {
// if the tuple is not owned by any transaction.
if (activated && !invalidated) {
return true;
} else {
return false;
}
}
}
}
bool OptimisticTransactionManager::RecordRead(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordRead(tile_group_id, tuple_id);
return true;
}
bool OptimisticTransactionManager::RecordWrite(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordWrite(tile_group_id, tuple_id);
return true;
}
bool OptimisticTransactionManager::RecordInsert(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordInsert(tile_group_id, tuple_id);
return true;
}
bool OptimisticTransactionManager::RecordDelete(const oid_t &tile_group_id, const oid_t &tuple_id) {
current_txn->RecordDelete(tile_group_id, tuple_id);
return true;
}
void OptimisticTransactionManager::CommitTransaction() {
LOG_INFO("Committing peloton txn : %lu ", current_txn->GetTransactionId());
auto &manager = catalog::Manager::GetInstance();
// generate transaction id.
cid_t end_commit_id = GetNextCommitId();
// validate read set.
auto read_tuples = current_txn->GetReadTuples();
for (auto entry : read_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
if (tile_group_header->GetTransactionId(tuple_slot) ==
current_txn->GetTransactionId()) {
// the version is owned by the transaction.
continue;
} else {
if (tile_group_header->GetTransactionId(tuple_slot) == INITIAL_TXN_ID &&
tile_group_header->GetBeginCommitId(tuple_slot) <= end_commit_id &&
tile_group_header->GetEndCommitId(tuple_slot) >= end_commit_id) {
// the version is not locked and still visible.
continue;
}
}
// otherwise, validation fails. abort transaction.
AbortTransaction();
return;
}
}
auto written_tuples = current_txn->GetWrittenTuples();
// install all updates.
for (auto entry : written_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
// we must guarantee that, at any time point, only one version is visible.
tile_group_header->SetEndCommitId(tuple_slot, end_commit_id);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetBeginCommitId(new_version.offset,
end_commit_id);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
COMPILER_MEMORY_FENCE;
new_tile_group_header->SetTransactionId(new_version.offset,
INITIAL_TXN_ID);
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
}
}
// commit insert set.
auto inserted_tuples = current_txn->GetInsertedTuples();
for (auto entry : inserted_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
for (auto tuple_slot : entry.second) {
tile_group->CommitInsertedTuple(
tuple_slot, current_txn->GetTransactionId(), end_commit_id);
}
}
// commit delete set.
auto deleted_tuples = current_txn->GetDeletedTuples();
for (auto entry : deleted_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
// we must guarantee that, at any time point, only one version is visible.
tile_group_header->SetEndCommitId(tuple_slot, end_commit_id);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetBeginCommitId(new_version.offset,
end_commit_id);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
COMPILER_MEMORY_FENCE;
new_tile_group_header->SetTransactionId(new_version.offset,
INVALID_TXN_ID);
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
}
}
delete current_txn;
current_txn = nullptr;
}
void OptimisticTransactionManager::AbortTransaction() {
LOG_INFO("Aborting peloton txn : %lu ", current_txn->GetTransactionId());
auto &manager = catalog::Manager::GetInstance();
auto written_tuples = current_txn->GetWrittenTuples();
// recover write set.
for (auto entry : written_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
tile_group_header->SetEndCommitId(tuple_slot, MAX_CID);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetTransactionId(new_version.offset,
INVALID_TXN_ID);
new_tile_group_header->SetBeginCommitId(new_version.offset, MAX_CID);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
}
}
// recover delete set.
auto deleted_tuples = current_txn->GetDeletedTuples();
for (auto entry : deleted_tuples) {
oid_t tile_group_id = entry.first;
auto tile_group = manager.GetTileGroup(tile_group_id);
auto tile_group_header = tile_group->GetHeader();
for (auto tuple_slot : entry.second) {
tile_group_header->UnlockTupleSlot(
tuple_slot, current_txn->GetTransactionId());
tile_group_header->SetEndCommitId(tuple_slot, MAX_CID);
ItemPointer new_version =
tile_group_header->GetNextItemPointer(tuple_slot);
auto new_tile_group_header =
manager.GetTileGroup(new_version.block)->GetHeader();
new_tile_group_header->SetTransactionId(new_version.offset,
INVALID_TXN_ID);
new_tile_group_header->SetBeginCommitId(new_version.offset, MAX_CID);
new_tile_group_header->SetEndCommitId(new_version.offset, MAX_CID);
}
}
delete current_txn;
current_txn = null_ptr;
}
} // End storage namespace
} // End peloton namespace
|
fix bug
|
fix bug
|
C++
|
apache-2.0
|
larryxiao/peloton,ranxian/peloton,larryxiao/peloton,amaliujia/CMUDB-peloton,ranxian/peloton,larryxiao/peloton,amaliujia/CMUDB-peloton,omegaga/peloton,amaliujia/CMUDB-peloton,larryxiao/peloton-1,omegaga/peloton,omegaga/peloton,larryxiao/peloton-1,ranxian/peloton,larryxiao/peloton-1,omegaga/peloton,amaliujia/CMUDB-peloton,larryxiao/peloton,larryxiao/peloton,larryxiao/peloton-1,ranxian/peloton,omegaga/peloton,larryxiao/peloton,ranxian/peloton,amaliujia/CMUDB-peloton,amaliujia/CMUDB-peloton,larryxiao/peloton-1,larryxiao/peloton-1,amaliujia/CMUDB-peloton,omegaga/peloton,omegaga/peloton,larryxiao/peloton,ranxian/peloton,larryxiao/peloton-1
|
889bb7993a1ca97636400bc44ce3cebc8b5ef82b
|
kernel/src/shell.cpp
|
kernel/src/shell.cpp
|
#include <cstddef>
#include <array>
#include "types.hpp"
#include "keyboard.hpp"
#include "kernel_utils.hpp"
#include "console.hpp"
#include "shell.hpp"
#include "timer.hpp"
#include "utils.hpp"
namespace {
//Declarations of the different functions
void reboot_command(const char* params);
void help_command(const char* params);
void uptime_command(const char* params);
void clear_command(const char* params);
void date_command(const char* params);
void sleep_command(const char* params);
void echo_command(const char* params);
struct command_definition {
const char* name;
void (*function)(const char*);
};
std::array<command_definition, 7> commands = {{
{"reboot", reboot_command},
{"help", help_command},
{"uptime", uptime_command},
{"clear", clear_command},
{"date", date_command},
{"sleep", sleep_command},
{"echo", echo_command}
}};
std::size_t current_input_length = 0;
char current_input[50];
void exec_command();
void keyboard_handler(){
uint8_t key = in_byte(0x60);
if(key & 0x80){
//TODO Handle shift
} else {
if(key == 0x1C){
current_input[current_input_length] = '\0';
k_print_line();
exec_command();
current_input_length = 0;
k_print("thor> ");
} else if(key == 0x0E){
set_column(get_column() - 1);
k_print(' ');
set_column(get_column() - 1);
--current_input_length;
} else {
auto qwertz_key = key_to_ascii(key);
if(qwertz_key > 0){
current_input[current_input_length++] = qwertz_key;
k_print(qwertz_key);
}
}
}
}
bool str_equals(const char* a, const char* b){
while(*a && *a == *b){
++a;
++b;
}
return *a == *b;
}
void exec_command(){
char buffer[50];
for(auto& command : commands){
const char* input_command = current_input;
if(str_contains(current_input, ' ')){
str_copy(current_input, buffer);
input_command = str_until(buffer, ' ');
}
if(str_equals(input_command, command.name)){
command.function(current_input);
return;
}
}
k_printf("The command \"%s\" does not exist\n", current_input);
}
void clear_command(const char*){
wipeout();
}
void reboot_command(const char*){
interrupt<60>();
}
void help_command(const char*){
k_print("Available commands:\n");
for(auto& command : commands){
k_print('\t');
k_print_line(command.name);
}
}
void uptime_command(const char*){
k_print("Uptime: ");
k_print(timer_seconds());
k_print_line("s");
}
#define CURRENT_YEAR 2013
#define cmos_address 0x70
#define cmos_data 0x71
int get_update_in_progress_flag() {
out_byte(cmos_address, 0x0A);
return (in_byte(cmos_data) & 0x80);
}
uint8_t get_RTC_register(int reg) {
out_byte(cmos_address, reg);
return in_byte(cmos_data);
}
void date_command(const char*){
uint8_t second;
uint8_t minute;
uint8_t hour;
uint8_t day;
uint8_t month;
unsigned int year;
uint8_t last_second;
uint8_t last_minute;
uint8_t last_hour;
uint8_t last_day;
uint8_t last_month;
uint8_t last_year;
uint8_t registerB;
//TODO When ACPI gets supported, get the address
//of the century register and use it to make
//better year calculation
while (get_update_in_progress_flag()){}; // Make sure an update isn't in progress
second = get_RTC_register(0x00);
minute = get_RTC_register(0x02);
hour = get_RTC_register(0x04);
day = get_RTC_register(0x07);
month = get_RTC_register(0x08);
year = get_RTC_register(0x09);
do {
last_second = second;
last_minute = minute;
last_hour = hour;
last_day = day;
last_month = month;
last_year = year;
while (get_update_in_progress_flag()){}; // Make sure an update isn't in progress
second = get_RTC_register(0x00);
minute = get_RTC_register(0x02);
hour = get_RTC_register(0x04);
day = get_RTC_register(0x07);
month = get_RTC_register(0x08);
year = get_RTC_register(0x09);
} while( (last_second != second) || (last_minute != minute) || (last_hour != hour) ||
(last_day != day) || (last_month != month) || (last_year != year) );
registerB = get_RTC_register(0x0B);
// Convert BCD to binary values if necessary
if (!(registerB & 0x04)) {
second = (second & 0x0F) + ((second / 16) * 10);
minute = (minute & 0x0F) + ((minute / 16) * 10);
hour = ( (hour & 0x0F) + (((hour & 0x70) / 16) * 10) ) | (hour & 0x80);
day = (day & 0x0F) + ((day / 16) * 10);
month = (month & 0x0F) + ((month / 16) * 10);
year = (year & 0x0F) + ((year / 16) * 10);
}
// Convert 12 hour clock to 24 hour clock if necessary
if (!(registerB & 0x02) && (hour & 0x80)) {
hour = ((hour & 0x7F) + 12) % 24;
}
// Calculate the full (4-digit) year
year += (CURRENT_YEAR / 100) * 100;
if(year < CURRENT_YEAR){
year += 100;
}
k_print((std::size_t) day);
k_print('.');
k_print((std::size_t) month);
k_print('.');
k_print((std::size_t) year);
k_print(' ');
k_print((std::size_t) hour);
k_print(':');
k_print((std::size_t) minute);
k_print(':');
k_print((std::size_t) second);
k_print_line();
}
void sleep_command(const char* params){
const char* delay_str = params + 6;
sleep_ms(parse(delay_str) * 1000);
}
void echo_command(const char* params){
k_print_line(params + 5);
}
} //end of anonymous namespace
void init_shell(){
current_input_length = 0;
clear_command(0);
k_print("thor> ");
register_irq_handler<1>(keyboard_handler);
}
|
#include <cstddef>
#include <array>
#include "types.hpp"
#include "keyboard.hpp"
#include "kernel_utils.hpp"
#include "console.hpp"
#include "shell.hpp"
#include "timer.hpp"
#include "utils.hpp"
namespace {
//Declarations of the different functions
void reboot_command(const char* params);
void help_command(const char* params);
void uptime_command(const char* params);
void clear_command(const char* params);
void date_command(const char* params);
void sleep_command(const char* params);
void echo_command(const char* params);
struct command_definition {
const char* name;
void (*function)(const char*);
};
std::array<command_definition, 7> commands = {{
{"reboot", reboot_command},
{"help", help_command},
{"uptime", uptime_command},
{"clear", clear_command},
{"date", date_command},
{"sleep", sleep_command},
{"echo", echo_command}
}};
std::size_t current_input_length = 0;
char current_input[50];
void exec_command();
void keyboard_handler(){
uint8_t key = in_byte(0x60);
if(key & 0x80){
//TODO Handle shift
} else {
if(key == 0x1C){
current_input[current_input_length] = '\0';
k_print_line();
exec_command();
current_input_length = 0;
k_print("thor> ");
} else if(key == 0x0E){
set_column(get_column() - 1);
k_print(' ');
set_column(get_column() - 1);
--current_input_length;
} else {
auto qwertz_key = key_to_ascii(key);
if(qwertz_key > 0){
current_input[current_input_length++] = qwertz_key;
k_print(qwertz_key);
}
}
}
}
bool str_equals(const char* a, const char* b){
while(*a && *a == *b){
++a;
++b;
}
return *a == *b;
}
void exec_command(){
char buffer[50];
for(auto& command : commands){
const char* input_command = current_input;
if(str_contains(current_input, ' ')){
str_copy(current_input, buffer);
input_command = str_until(buffer, ' ');
}
if(str_equals(input_command, command.name)){
command.function(current_input);
return;
}
}
k_printf("The command \"%s\" does not exist\n", current_input);
}
void clear_command(const char*){
wipeout();
}
void reboot_command(const char*){
interrupt<60>();
}
void help_command(const char*){
k_print("Available commands:\n");
for(auto& command : commands){
k_print('\t');
k_print_line(command.name);
}
}
void uptime_command(const char*){
k_printf("Uptime: %ds\n", timer_seconds());
}
#define CURRENT_YEAR 2013
#define cmos_address 0x70
#define cmos_data 0x71
int get_update_in_progress_flag() {
out_byte(cmos_address, 0x0A);
return (in_byte(cmos_data) & 0x80);
}
uint8_t get_RTC_register(int reg) {
out_byte(cmos_address, reg);
return in_byte(cmos_data);
}
void date_command(const char*){
uint8_t second;
uint8_t minute;
uint8_t hour;
uint8_t day;
uint8_t month;
unsigned int year;
uint8_t last_second;
uint8_t last_minute;
uint8_t last_hour;
uint8_t last_day;
uint8_t last_month;
uint8_t last_year;
uint8_t registerB;
//TODO When ACPI gets supported, get the address
//of the century register and use it to make
//better year calculation
while (get_update_in_progress_flag()){}; // Make sure an update isn't in progress
second = get_RTC_register(0x00);
minute = get_RTC_register(0x02);
hour = get_RTC_register(0x04);
day = get_RTC_register(0x07);
month = get_RTC_register(0x08);
year = get_RTC_register(0x09);
do {
last_second = second;
last_minute = minute;
last_hour = hour;
last_day = day;
last_month = month;
last_year = year;
while (get_update_in_progress_flag()){}; // Make sure an update isn't in progress
second = get_RTC_register(0x00);
minute = get_RTC_register(0x02);
hour = get_RTC_register(0x04);
day = get_RTC_register(0x07);
month = get_RTC_register(0x08);
year = get_RTC_register(0x09);
} while( (last_second != second) || (last_minute != minute) || (last_hour != hour) ||
(last_day != day) || (last_month != month) || (last_year != year) );
registerB = get_RTC_register(0x0B);
// Convert BCD to binary values if necessary
if (!(registerB & 0x04)) {
second = (second & 0x0F) + ((second / 16) * 10);
minute = (minute & 0x0F) + ((minute / 16) * 10);
hour = ( (hour & 0x0F) + (((hour & 0x70) / 16) * 10) ) | (hour & 0x80);
day = (day & 0x0F) + ((day / 16) * 10);
month = (month & 0x0F) + ((month / 16) * 10);
year = (year & 0x0F) + ((year / 16) * 10);
}
// Convert 12 hour clock to 24 hour clock if necessary
if (!(registerB & 0x02) && (hour & 0x80)) {
hour = ((hour & 0x7F) + 12) % 24;
}
// Calculate the full (4-digit) year
year += (CURRENT_YEAR / 100) * 100;
if(year < CURRENT_YEAR){
year += 100;
}
k_printf("%d.%d.%d %d:%d:%d\n",
(std::size_t) day, (std::size_t) month, (std::size_t) year,
(std::size_t) hour, (std::size_t) minute, (std::size_t) second);
}
void sleep_command(const char* params){
const char* delay_str = params + 6;
sleep_ms(parse(delay_str) * 1000);
}
void echo_command(const char* params){
k_print_line(params + 5);
}
} //end of anonymous namespace
void init_shell(){
current_input_length = 0;
clear_command(0);
k_print("thor> ");
register_irq_handler<1>(keyboard_handler);
}
|
Use printf
|
Use printf
|
C++
|
mit
|
wichtounet/thor-os,wichtounet/thor-os
|
958f66a4dec63ab4003070806b889f0a4d41bb5a
|
benchmarks/data/io_benches.cpp
|
benchmarks/data/io_benches.cpp
|
/*******************************************************************************
* benchmarks/data/file_read_write.cpp
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Tobias Sturm <[email protected]>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#include <thrill/api/context.hpp>
#include <thrill/data/block_queue.hpp>
#include <thrill/common/cmdline_parser.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/common/thread_pool.hpp>
#include <thrill/common/stats_timer.hpp>
#include <iostream>
#include <random>
#include <string>
#include <tuple>
#include "data_generators.hpp"
using namespace thrill; // NOLINT
using common::StatsTimer;
//! Writes and reads random elements from a file.
//! Elements are genreated before the timer startet
//! Number of elements depends on the number of bytes.
//! one RESULT line will be printed for each iteration
//! All iterations use the same generated data.
//! Variable-length elements range between 1 and 100 bytes per default
template <typename Type>
void FileExperiment(uint64_t bytes, size_t min_size, size_t max_size, unsigned iterations, api::Context& ctx, const std::string& type_as_string, const std::string& reader_type) {
if (reader_type != "consume" && reader_type != "non-consume")
abort();
for (unsigned i = 0; i < iterations; i++) {
auto file = ctx.GetFile();
auto writer = file.GetWriter();
auto data = Generator<Type>(bytes, min_size, max_size);
std::cout << "writing " << bytes << " bytes" << std::endl;
StatsTimer<true> write_timer(true);
while (data.HasNext()) {
writer(data.Next());
}
writer.Close();
write_timer.Stop();
std::cout << "reading " << bytes << " bytes" << std::endl;
bool consume = reader_type == "consume";
StatsTimer<true> read_timer(true);
auto reader = file.GetReader(consume);
while (reader.HasNext())
reader.Next<Type>();
read_timer.Stop();
std::cout << "RESULT"
<< " datatype=" << type_as_string
<< " size=" << bytes
<< " avg_element_size=" << (min_size + max_size) / 2.0
<< " reader=" << reader_type
<< " write_time=" << write_timer.Microseconds()
<< " read_time=" << read_timer.Microseconds()
<< std::endl;
}
}
//! Writes and reads random elements to / from block queue with 2 threads
//! Elements are genreated before the timer startet
//! Number of elements depends on the number of bytes.
//! one RESULT line will be printed for each iteration
//! All iterations use the same generated data.
//! Variable-length elements range between 1 and 100 bytes per default
template <typename Type>
void BlockQueueExperiment(uint64_t bytes, size_t min_size, size_t max_size, unsigned iterations, api::Context& ctx, const std::string& type_as_string, const std::string& reader_type) {
if (reader_type != "consume" && reader_type != "non-consume")
abort();
common::ThreadPool threads(2);
for (unsigned i = 0; i < iterations; i++) {
auto queue = data::BlockQueue(ctx.block_pool());
auto data = Generator<Type>(bytes, min_size, max_size);
StatsTimer<true> write_timer;
threads.Enqueue([bytes, &data, &write_timer, &queue]() {
std::cout << "writing " << bytes << " bytes" << std::endl;
auto writer = queue.GetWriter();
write_timer.Start();
while (data.HasNext()) {
writer(data.Next());
}
writer.Close();
write_timer.Stop();
});
StatsTimer<true> read_timer;
bool consume = reader_type == "consume";
threads.Enqueue([bytes, consume, &queue, &read_timer]() {
std::cout << "reading " << bytes << " bytes" << std::endl;
read_timer.Start();
auto reader = queue.GetReader(consume);
while (reader.HasNext())
reader.Next<Type>();
read_timer.Stop();
});
threads.LoopUntilEmpty();
std::cout << "RESULT"
<< " datatype=" << type_as_string
<< " size=" << bytes
<< " avg_element_size=" << (min_size + max_size) / 2.0
<< " reader=" << reader_type
<< " write_time=" << write_timer.Microseconds()
<< " read_time=" << read_timer.Microseconds()
<< std::endl;
}
}
int main(int argc, const char** argv) {
common::NameThisThread("benchmark");
common::CmdlineParser clp;
clp.SetDescription("thrill::data benchmark for disk I/O");
clp.SetAuthor("Tobias Sturm <[email protected]>");
unsigned iterations = 1;
uint64_t bytes = 1024;
size_t min_variable_length = 1;
size_t max_variable_length = 100;
std::string experiment;
std::string type;
std::string reader_type;
clp.AddBytes('b', "bytes", bytes, "number of bytes to process (default 1024)");
clp.AddBytes('l', "lower", min_variable_length, "lower bound for variable element length (default 1)");
clp.AddBytes('u', "upper", max_variable_length, "upper bound for variable element length (default 100)");
clp.AddUInt('n', "iterations", iterations, "Iterations (default: 1)");
clp.AddParamString("experiment", experiment,
"experiment to run (file, block_queue)");
clp.AddParamString("type", type,
"data type (size_t, string, pair, triple)");
clp.AddParamString("reader", reader_type,
"reader type (consume, non-consume)");
if (!clp.Process(argc, argv)) return -1;
using pair = std::tuple<std::string, size_t>;
using triple = std::tuple<std::string, size_t, std::string>;
if (experiment == "file") {
if (type == "size_t")
api::RunLocalSameThread(std::bind(FileExperiment<size_t>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type));
else if (type == "string")
api::RunLocalSameThread(std::bind(FileExperiment<std::string>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type));
else if (type == "pair")
api::RunLocalSameThread(std::bind(FileExperiment<pair>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type));
else if (type == "triple")
api::RunLocalSameThread(std::bind(FileExperiment<triple>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type));
else
abort();
} else if (experiment == "block_queue") {
if (type == "size_t")
api::RunLocalSameThread(std::bind(BlockQueueExperiment<size_t>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type));
else if (type == "string")
api::RunLocalSameThread(std::bind(BlockQueueExperiment<std::string>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type));
else if (type == "pair")
api::RunLocalSameThread(std::bind(BlockQueueExperiment<pair>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type));
else if (type == "triple")
api::RunLocalSameThread(std::bind(BlockQueueExperiment<triple>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type));
else
abort();
} else
abort();
}
/******************************************************************************/
|
/*******************************************************************************
* benchmarks/data/file_read_write.cpp
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Tobias Sturm <[email protected]>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#include <thrill/api/context.hpp>
#include <thrill/data/block_queue.hpp>
#include <thrill/common/cmdline_parser.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/common/thread_pool.hpp>
#include <thrill/common/stats_timer.hpp>
#include <iostream>
#include <random>
#include <string>
#include <tuple>
#include "data_generators.hpp"
using namespace thrill; // NOLINT
using common::StatsTimer;
//! Writes and reads random elements from a file.
//! Elements are genreated before the timer startet
//! Number of elements depends on the number of bytes.
//! one RESULT line will be printed for each iteration
//! All iterations use the same generated data.
//! Variable-length elements range between 1 and 100 bytes per default
template <typename Type>
void FileExperiment(uint64_t bytes, size_t min_size, size_t max_size, unsigned iterations, api::Context& ctx, const std::string& type_as_string, const std::string& reader_type, size_t block_size) {
if (reader_type != "consume" && reader_type != "non-consume")
abort();
for (unsigned i = 0; i < iterations; i++) {
auto file = ctx.GetFile();
auto writer = file.GetWriter(block_size);
auto data = Generator<Type>(bytes, min_size, max_size);
std::cout << "writing " << bytes << " bytes" << std::endl;
StatsTimer<true> write_timer(true);
while (data.HasNext()) {
writer(data.Next());
}
writer.Close();
write_timer.Stop();
std::cout << "reading " << bytes << " bytes" << std::endl;
bool consume = reader_type == "consume";
StatsTimer<true> read_timer(true);
auto reader = file.GetReader(consume);
while (reader.HasNext())
reader.Next<Type>();
read_timer.Stop();
std::cout << "RESULT"
<< " datatype=" << type_as_string
<< " size=" << bytes
<< " block_size=" << block_size
<< " avg_element_size=" << (min_size + max_size) / 2.0
<< " reader=" << reader_type
<< " write_time=" << write_timer.Microseconds()
<< " read_time=" << read_timer.Microseconds()
<< std::endl;
}
}
//! Writes and reads random elements to / from block queue with 2 threads
//! Elements are genreated before the timer startet
//! Number of elements depends on the number of bytes.
//! one RESULT line will be printed for each iteration
//! All iterations use the same generated data.
//! Variable-length elements range between 1 and 100 bytes per default
template <typename Type>
void BlockQueueExperiment(uint64_t bytes, size_t min_size, size_t max_size, unsigned iterations, api::Context& ctx, const std::string& type_as_string, const std::string& reader_type, size_t block_size) {
if (reader_type != "consume" && reader_type != "non-consume")
abort();
common::ThreadPool threads(2);
for (unsigned i = 0; i < iterations; i++) {
auto queue = data::BlockQueue(ctx.block_pool());
auto data = Generator<Type>(bytes, min_size, max_size);
StatsTimer<true> write_timer;
threads.Enqueue([bytes, &data, &write_timer, &queue, block_size]() {
std::cout << "writing " << bytes << " bytes" << std::endl;
auto writer = queue.GetWriter(block_size);
write_timer.Start();
while (data.HasNext()) {
writer(data.Next());
}
writer.Close();
write_timer.Stop();
});
StatsTimer<true> read_timer;
bool consume = reader_type == "consume";
threads.Enqueue([bytes, consume, &queue, &read_timer]() {
std::cout << "reading " << bytes << " bytes" << std::endl;
read_timer.Start();
auto reader = queue.GetReader(consume);
while (reader.HasNext())
reader.Next<Type>();
read_timer.Stop();
});
threads.LoopUntilEmpty();
std::cout << "RESULT"
<< " datatype=" << type_as_string
<< " size=" << bytes
<< " block_size=" << block_size
<< " avg_element_size=" << (min_size + max_size) / 2.0
<< " reader=" << reader_type
<< " write_time=" << write_timer.Microseconds()
<< " read_time=" << read_timer.Microseconds()
<< std::endl;
}
}
int main(int argc, const char** argv) {
common::NameThisThread("benchmark");
common::CmdlineParser clp;
clp.SetDescription("thrill::data benchmark for disk I/O");
clp.SetAuthor("Tobias Sturm <[email protected]>");
unsigned iterations = 1;
uint64_t bytes = 1024;
uint64_t block_size = data::default_block_size;
size_t min_variable_length = 1;
size_t max_variable_length = 100;
std::string experiment;
std::string type;
std::string reader_type;
clp.AddBytes('b', "bytes", bytes, "number of bytes to process (default 1024)");
clp.AddBytes('s', "block_size", block_size, "block size (system default)");
clp.AddBytes('l', "lower", min_variable_length, "lower bound for variable element length (default 1)");
clp.AddBytes('u', "upper", max_variable_length, "upper bound for variable element length (default 100)");
clp.AddUInt('n', "iterations", iterations, "Iterations (default: 1)");
clp.AddParamString("experiment", experiment,
"experiment to run (file, block_queue)");
clp.AddParamString("type", type,
"data type (size_t, string, pair, triple)");
clp.AddParamString("reader", reader_type,
"reader type (consume, non-consume)");
if (!clp.Process(argc, argv)) return -1;
using pair = std::tuple<std::string, size_t>;
using triple = std::tuple<std::string, size_t, std::string>;
if (experiment == "file") {
if (type == "size_t")
api::RunLocalSameThread(std::bind(FileExperiment<size_t>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type, block_size));
else if (type == "string")
api::RunLocalSameThread(std::bind(FileExperiment<std::string>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type, block_size));
else if (type == "pair")
api::RunLocalSameThread(std::bind(FileExperiment<pair>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type, block_size));
else if (type == "triple")
api::RunLocalSameThread(std::bind(FileExperiment<triple>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type, block_size));
else
abort();
} else if (experiment == "block_queue") {
if (type == "size_t")
api::RunLocalSameThread(std::bind(BlockQueueExperiment<size_t>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type, block_size));
else if (type == "string")
api::RunLocalSameThread(std::bind(BlockQueueExperiment<std::string>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type, block_size));
else if (type == "pair")
api::RunLocalSameThread(std::bind(BlockQueueExperiment<pair>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type, block_size));
else if (type == "triple")
api::RunLocalSameThread(std::bind(BlockQueueExperiment<triple>, bytes, min_variable_length, max_variable_length, iterations, std::placeholders::_1, type, reader_type, block_size));
else
abort();
} else
abort();
}
/******************************************************************************/
|
make block size configureable in io experiment
|
make block size configureable in io experiment
|
C++
|
bsd-2-clause
|
manpen/thrill,manpen/thrill,manpen/thrill,manpen/thrill,manpen/thrill
|
2fa9eb84f876aefa49a15c2a5ab259cbb13497a3
|
src/util/StringUtil.hxx
|
src/util/StringUtil.hxx
|
/*
* Copyright (C) 2009-2015 Max Kellermann <[email protected]>
*
* 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
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef STRING_UTIL_HXX
#define STRING_UTIL_HXX
#include <inline/compiler.h>
#include <stddef.h>
/**
* Skips whitespace at the beginning of the string, and returns the
* first non-whitespace character. If the string has no
* non-whitespace characters, then a pointer to the NULL terminator is
* returned.
*/
gcc_pure gcc_nonnull_all
const char *
StripLeft(const char *p);
gcc_pure gcc_nonnull_all
static inline char *
StripLeft(char *p)
{
return const_cast<char *>(StripLeft(p));
}
/**
* Skips whitespace at the beginning of the string, and returns the
* first non-whitespace character or the end pointer.
*/
gcc_pure
const char *
StripLeft(const char *p, const char *end);
/**
* Determine the string's end as if it was stripped on the right side.
*/
gcc_pure
const char *
StripRight(const char *p, const char *end);
/**
* Determine the string's end as if it was stripped on the right side.
*/
gcc_pure
static inline char *
StripRight(char *p, char *end)
{
return const_cast<char *>(StripRight((const char *)p,
(const char *)end));
}
/**
* Determine the string's length as if it was stripped on the right
* side.
*/
gcc_pure
size_t
StripRight(const char *p, size_t length);
/**
* Strips trailing whitespace.
*/
gcc_nonnull_all
void
StripRight(char *p);
#endif
|
/*
* Copyright (C) 2009-2015 Max Kellermann <[email protected]>
*
* 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
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef STRING_UTIL_HXX
#define STRING_UTIL_HXX
#include <inline/compiler.h>
#include <stddef.h>
/**
* Skips whitespace at the beginning of the string, and returns the
* first non-whitespace character. If the string has no
* non-whitespace characters, then a pointer to the NULL terminator is
* returned.
*/
gcc_pure gcc_nonnull_all
const char *
StripLeft(const char *p);
gcc_pure gcc_nonnull_all
static inline char *
StripLeft(char *p)
{
return const_cast<char *>(StripLeft((const char *)p));
}
/**
* Skips whitespace at the beginning of the string, and returns the
* first non-whitespace character or the end pointer.
*/
gcc_pure
const char *
StripLeft(const char *p, const char *end);
/**
* Determine the string's end as if it was stripped on the right side.
*/
gcc_pure
const char *
StripRight(const char *p, const char *end);
/**
* Determine the string's end as if it was stripped on the right side.
*/
gcc_pure
static inline char *
StripRight(char *p, char *end)
{
return const_cast<char *>(StripRight((const char *)p,
(const char *)end));
}
/**
* Determine the string's length as if it was stripped on the right
* side.
*/
gcc_pure
size_t
StripRight(const char *p, size_t length);
/**
* Strips trailing whitespace.
*/
gcc_nonnull_all
void
StripRight(char *p);
#endif
|
add missing cast
|
util/StringUtil: add missing cast
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
576d8b8eec10ee2eb8e8a63c5b432f02b7790b36
|
DecoratorTest.cpp
|
DecoratorTest.cpp
|
#include "stdafx.h"
#include "DecoratorTest.h"
#include "AutoPacket.h"
#include "AutoPacketFactory.h"
#include "AutoPacketListener.h"
#include "FilterPropertyExtractor.h"
#include "TestFixtures/Decoration.h"
using namespace std;
TEST_F(DecoratorTest, VerifyCorrectExtraction) {
vector<const type_info*> v;
// Run our prop extractor based on a known decorator:
RecipientPropertyExtractor<FilterA>::Enumerate(
[&v] (const std::type_info& ti) {
v.push_back(&ti);
}
);
ASSERT_EQ(2UL, v.size()) << "Extracted an insufficient number of types from a known filter function";
// Arguments MUST be in order:
EXPECT_EQ(typeid(Decoration<0>), *v[0]);
EXPECT_EQ(typeid(Decoration<1>), *v[1]);
// Verify both overloads wind up returning the same array:
auto ppCur = RecipientPropertyExtractor<FilterA>::Enumerate();
for(size_t i = 0; ppCur[i]; i++)
EXPECT_EQ(*v[i], *ppCur[i]) << "Two overloads of Enumerate returned contradictory types";
}
TEST_F(DecoratorTest, VerifyEmptyExtraction) {
const type_info*const* v = RecipientPropertyExtractor<Object>::Enumerate();
EXPECT_EQ(nullptr, *v) << "Extracted arguments from an object known not to have a Filter method";
}
TEST_F(DecoratorTest, VerifySimplePacketDecoration) {
AutoRequired<AutoPacketFactory> factory;
// Create the packet we will be persisting:
auto packet = factory->NewPacket();
// Add a few decorations on this packet:
auto& knownDec0 = packet->Decorate(Decoration<0>());
auto& knownDec1 = packet->Decorate(Decoration<1>());
auto& knownDec2 = packet->Decorate(Decoration<2>());
// Verify we can get these packets back--might throw exceptions here!
auto& dec0 = packet->Get<Decoration<0>>();
auto& dec1 = packet->Get<Decoration<1>>();
auto& dec2 = packet->Get<Decoration<2>>();
// Verify identities:
EXPECT_EQ(&knownDec0, &dec0) << "Decoration 0 returned at an incorrect location";
EXPECT_EQ(&knownDec1, &dec1) << "Decoration 1 returned at an incorrect location";
EXPECT_EQ(&knownDec2, &dec2) << "Decoration 2 returned at an incorrect location";
// Verify content correctness:
EXPECT_EQ(0, dec0.i) << "Decoration 0 incorrectly persisted";
EXPECT_EQ(1, dec1.i) << "Decoration 1 incorrectly persisted";
EXPECT_EQ(2, dec2.i) << "Decoration 2 incorrectly persisted";
}
TEST_F(DecoratorTest, VerifyDecoratorAwareness) {
// Create a packet while the factory has no subscribers:
AutoRequired<AutoPacketFactory> factory;
auto packet1 = factory->NewPacket();
// Verify subscription-free status:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
// Create another packet where a subscriber exists:
AutoRequired<FilterA> filterA;
ASSERT_TRUE(factory->IsSubscriber<FilterA>());
auto packet2 = factory->NewPacket();
// Verify the first packet still does not have subscriptions:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
// Verify the second one does:
EXPECT_TRUE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked an expected subscription";
}
TEST_F(DecoratorTest, VerifyDescendentAwareness) {
// Create a packet while the factory has no subscribers:
AutoRequired<AutoPacketFactory> parentFactory;
auto packet1 = parentFactory->NewPacket();
// Verify subscription-free status:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
std::shared_ptr<AutoPacket> packet2;
std::weak_ptr<AutoPacket> packet3;
std::weak_ptr<FilterA> filterChecker;
//Create a subcontext
{
AutoCreateContext subContext;
{
CurrentContextPusher pusher(subContext);
//add a filter in the subcontext
AutoRequired<FilterA> subFilter;
filterChecker = subFilter;
}
//Create a packet where a subscriber exists only in a subcontext
packet2 = parentFactory->NewPacket();
auto strongPacket3 = parentFactory->NewPacket();
packet3 = strongPacket3;
EXPECT_TRUE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked expected subscription from subcontext";
EXPECT_TRUE(packet3.lock()->HasSubscribers<Decoration<0>>()) << "Packet lacked expected subscription from subcontext";
}
EXPECT_TRUE(packet3.expired()) << "Packet was not destroyed when it's subscribers were removed";
EXPECT_TRUE(filterChecker.expired()) << "Packet keeping subcontext member alive";
//Create a packet after the subcontext has been destroyed
auto packet4 = parentFactory->NewPacket();
EXPECT_FALSE(packet4->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
// Verify the first packet still does not have subscriptions:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
packet2->Decorate(Decoration<0>());
// Verify the second one will no longe have subscriptions -
// normally removing a subscriber would mean the packet still has the subscriber, but
// in this case, the subscriber was actually destroyed so the packet has lost a subscriber.
EXPECT_FALSE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked an expected subscription";
// Verify the third one does not:
EXPECT_FALSE(packet4->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
}
TEST_F(DecoratorTest, VerifySimpleFilter) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Manually register the subscriber:
ASSERT_TRUE(factory->IsSubscriber<FilterA>());
// Obtain a packet from the factory:
auto packet = factory->NewPacket();
// Decorate with one instance:
packet->Decorate(Decoration<0>());
// Verify that no hit takes place with inadequate decoration:
EXPECT_FALSE(filterA->m_called) << "Filter called prematurely with insufficient decoration";
// Now decorate with the other requirement of the filter:
packet->Decorate(Decoration<1>());
// A hit should have taken place at this point:
EXPECT_TRUE(filterA->m_called) << "Filter was not called even though it was fully satisfied";
}
TEST_F(DecoratorTest, VerifyNoMultiDecorate) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Subscriber registration verification:
ASSERT_TRUE(factory->IsSubscriber<FilterA>());
// Obtain a packet and attempt redundant introduction:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Redundant decoration did not throw an exception as expected";
// Verify that a call has not yet been made
EXPECT_FALSE(filterA->m_called) << "A call made on an idempotent packet decoration";
// Now finish saturating the filter and ensure we get a call:
packet->Decorate(Decoration<1>());
EXPECT_TRUE(filterA->m_called) << "Filter was not called after being fully satisfied";
}
TEST_F(DecoratorTest, VerifyInterThreadDecoration) {
AutoRequired<FilterB> filterB;
AutoRequired<AutoPacketFactory> factory;
AutoCurrentContext ctxt;
// Kick off all threads:
ctxt->InitiateCoreThreads();
// Obtain a packet for processing and decorate it:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
packet->Decorate(Decoration<1>());
// Verify that the recipient has NOT yet received the message:
EXPECT_FALSE(filterB->m_called) << "A call was made to a thread which should not have been able to process it";
// Wake up the barrier and post a quit message:
filterB->m_barr.wait();
*filterB += [&filterB] { filterB->Stop(); };
filterB->Wait();
// Verify that the filter method has been called
EXPECT_TRUE(filterB->m_called) << "A deferred filter method was not called as expected";
}
TEST_F(DecoratorTest, VerifyTeardownArrangement) {
AutoRequired<AutoPacketFactory> factory;
std::weak_ptr<FilterA> filterAWeak;
{
std::shared_ptr<AutoPacket> packet;
{
// Create the filter and subscribe it
std::shared_ptr<FilterA> filterA(new FilterA);
filterAWeak = filterA;
factory->AddSubscriber(filterA);
// Create the packet--this should lock in references to all subscribers:
packet = factory->NewPacket();
}
// Verify that the subscription has not expired:
ASSERT_FALSE(filterAWeak.expired()) << "A subscriber while it was still registered";
{
std::shared_ptr<FilterA> filterA = filterAWeak.lock();
// Unsubscribe the filter:
factory->RemoveSubscriber(filterA);
}
// Verify that unsubscription STILL does not result in expiration:
ASSERT_FALSE(filterAWeak.expired()) << "A subscriber expired before all packets on that subscriber were satisfied";
//Create a new packet after having removed the only filter on it.
auto packet2 = factory->NewPacket();
ASSERT_FALSE(packet2->HasSubscribers<Decoration<0>>()) << "A packet had subscriptions after the only subscriber was removed.";
// Satisfy the packet:
packet->Decorate(Decoration<0>());
packet->Decorate(Decoration<1>());
auto packet3 = factory->NewPacket();
ASSERT_FALSE(packet3->HasSubscribers<Decoration<0>>()) << "A packet had subscriptions after the only subscriber was removed.";
}
// Filter should be expired now:
ASSERT_TRUE(filterAWeak.expired()) << "Subscriber was still left outstanding even though all references should be gone";
}
TEST_F(DecoratorTest, VerifyCheckout) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet for use with deferred decoration:
auto packet = factory->NewPacket();
{
// Verify that an unsubscribed decoration returns a correct checkout:
auto unused = packet->Checkout<Decoration<4>>();
EXPECT_FALSE(unused) << "Checkout incorrectly generated for unsubscribed decoration";
}
// Satisfy the other decoration:
packet->Decorate(Decoration<1>());
{
AutoCheckout<Decoration<0>> exterior;
{
AutoCheckout<Decoration<0>> checkout = packet->Checkout<Decoration<0>>();
// Verify we can move the original type:
AutoCheckout<Decoration<0>> checkoutMoved(std::move(checkout));
// Verify no hits yet:
EXPECT_FALSE(filterA->m_called) << "Filter called as a consequence of a checkout move operation";
// Move the checkout a second time:
exterior = std::move(checkoutMoved);
}
// Still no hits
EXPECT_FALSE(filterA->m_called) << "Filter called before a decoration checkout expired";
// Mark ready so we get committed:
exterior.Ready();
}
// Verify a hit took place now
EXPECT_TRUE(filterA->m_called) << "Filter was not called after all decorations were installed";
}
TEST_F(DecoratorTest, RollbackCorrectness) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet for use with deferred decoration:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<1>());
// Request and immediately allow the destruction of a checkout:
packet->Checkout<Decoration<0>>();
// Verify no hit took place--the checkout should have been cancelled:
EXPECT_FALSE(filterA->m_called) << "Filter was not called after all decorations were installed";
// We should not be able to obtain another checkout of this decoration on this packet:
EXPECT_ANY_THROW(packet->Checkout<Decoration<0>>()) << "An attempt to check out a decoration a second time should have failed";
// We shouldn't be able to manually decorate, either:
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "An attempt to manually add a previously failed decoration succeeded where it should not have";
}
TEST_F(DecoratorTest, VerifyAntiDecorate) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
{
// Obtain a new packet and mark an unsatisfiable decoration:
auto packet = factory->NewPacket();
packet->Unsatisfiable<Decoration<0>>();
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Decoration succeeded on a decoration marked unsatisfiable";
}
{
// Obtain a new packet and try to make a satisfied decoration unsatisfiable.
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
EXPECT_ANY_THROW(packet->Unsatisfiable<Decoration<0>>()) << "Succeeded in marking an already-existing decoration as unsatisfiable";
}
}
TEST_F(DecoratorTest, VerifyReflexiveReciept) {
AutoRequired<FilterA> filterA;
AutoRequired<FilterC> filterC;
AutoRequired<FilterD> filterD;
AutoRequired<FilterE> filterE;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet first:
auto packet = factory->NewPacket();
// The mere act of obtaining a packet should have triggered filterD to be fired:
EXPECT_TRUE(filterD->m_called) << "Trivial filter was not called as expected";
// The packet should be able to obtain a pointer to itself:
{
AutoPacketAdaptor extractor(*packet);
AutoPacket* reflex = extractor;
EXPECT_EQ(packet.get(), reflex) << "Packet reflexive reference was not an identity";
}
// Decorate--should satisfy filterC
packet->Decorate(Decoration<0>());
EXPECT_TRUE(filterC->m_called) << "FilterC should have been satisfied with one decoration";
// FilterC should have also satisfied filterA:
EXPECT_TRUE(filterA->m_called) << "FilterA should have been satisfied by FilterC";
// Release the packet, and verify that filterD gets hit only once this happens
EXPECT_FALSE(filterE->m_called) << "Packet listener was notified prematurely";
packet.reset();
EXPECT_TRUE(filterE->m_called) << "Packet listener was not notified as anticipated";
}
|
#include "stdafx.h"
#include "DecoratorTest.h"
#include "AutoPacket.h"
#include "AutoPacketFactory.h"
#include "AutoPacketListener.h"
#include "FilterPropertyExtractor.h"
#include "TestFixtures/Decoration.h"
using namespace std;
TEST_F(DecoratorTest, VerifyCorrectExtraction) {
vector<const type_info*> v;
// Run our prop extractor based on a known decorator:
RecipientPropertyExtractor<FilterA>::Enumerate(
[&v] (const std::type_info& ti) {
v.push_back(&ti);
}
);
ASSERT_EQ(2UL, v.size()) << "Extracted an insufficient number of types from a known filter function";
// Arguments MUST be in order:
EXPECT_EQ(typeid(Decoration<0>), *v[0]);
EXPECT_EQ(typeid(Decoration<1>), *v[1]);
// Verify both overloads wind up returning the same array:
auto ppCur = RecipientPropertyExtractor<FilterA>::Enumerate();
for(size_t i = 0; ppCur[i]; i++)
EXPECT_EQ(*v[i], *ppCur[i]) << "Two overloads of Enumerate returned contradictory types";
}
TEST_F(DecoratorTest, VerifyEmptyExtraction) {
const type_info*const* v = RecipientPropertyExtractor<Object>::Enumerate();
EXPECT_EQ(nullptr, *v) << "Extracted arguments from an object known not to have a Filter method";
}
TEST_F(DecoratorTest, VerifySimplePacketDecoration) {
AutoRequired<AutoPacketFactory> factory;
// Create the packet we will be persisting:
auto packet = factory->NewPacket();
// Add a few decorations on this packet:
auto& knownDec0 = packet->Decorate(Decoration<0>());
auto& knownDec1 = packet->Decorate(Decoration<1>());
auto& knownDec2 = packet->Decorate(Decoration<2>());
// Verify we can get these packets back--might throw exceptions here!
auto& dec0 = packet->Get<Decoration<0>>();
auto& dec1 = packet->Get<Decoration<1>>();
auto& dec2 = packet->Get<Decoration<2>>();
// Verify identities:
EXPECT_EQ(&knownDec0, &dec0) << "Decoration 0 returned at an incorrect location";
EXPECT_EQ(&knownDec1, &dec1) << "Decoration 1 returned at an incorrect location";
EXPECT_EQ(&knownDec2, &dec2) << "Decoration 2 returned at an incorrect location";
// Verify content correctness:
EXPECT_EQ(0, dec0.i) << "Decoration 0 incorrectly persisted";
EXPECT_EQ(1, dec1.i) << "Decoration 1 incorrectly persisted";
EXPECT_EQ(2, dec2.i) << "Decoration 2 incorrectly persisted";
}
TEST_F(DecoratorTest, VerifyDecoratorAwareness) {
// Create a packet while the factory has no subscribers:
AutoRequired<AutoPacketFactory> factory;
auto packet1 = factory->NewPacket();
// Verify subscription-free status:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
// Create another packet where a subscriber exists:
AutoRequired<FilterA> filterA;
ASSERT_TRUE(factory->IsSubscriber<FilterA>());
auto packet2 = factory->NewPacket();
// Verify the first packet still does not have subscriptions:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
// Verify the second one does:
EXPECT_TRUE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked an expected subscription";
}
TEST_F(DecoratorTest, VerifyDescendentAwareness) {
// Create a packet while the factory has no subscribers:
AutoRequired<AutoPacketFactory> parentFactory;
auto packet1 = parentFactory->NewPacket();
// Verify subscription-free status:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
std::shared_ptr<AutoPacket> packet2;
std::weak_ptr<AutoPacket> packet3;
std::weak_ptr<FilterA> filterChecker;
//Create a subcontext
{
AutoCreateContext subContext;
{
CurrentContextPusher pusher(subContext);
//add a filter in the subcontext
AutoRequired<FilterA> subFilter;
filterChecker = subFilter;
}
//Create a packet where a subscriber exists only in a subcontext
packet2 = parentFactory->NewPacket();
auto strongPacket3 = parentFactory->NewPacket();
packet3 = strongPacket3;
EXPECT_TRUE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked expected subscription from subcontext";
EXPECT_TRUE(packet3.lock()->HasSubscribers<Decoration<0>>()) << "Packet lacked expected subscription from subcontext";
}
EXPECT_TRUE(packet3.expired()) << "Packet was not destroyed when it's subscribers were removed";
EXPECT_FALSE(filterChecker.expired()) << "Packet keeping subcontext member alive";
//Create a packet after the subcontext has been destroyed
auto packet4 = parentFactory->NewPacket();
EXPECT_FALSE(packet4->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
// Verify the first packet still does not have subscriptions:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
packet2->Decorate(Decoration<0>());
// Verify the second one will no longe have subscriptions -
// normally removing a subscriber would mean the packet still has the subscriber, but
// in this case, the subscriber was actually destroyed so the packet has lost a subscriber.
EXPECT_FALSE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked an expected subscription";
// Verify the third one does not:
EXPECT_FALSE(packet4->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
}
TEST_F(DecoratorTest, VerifySimpleFilter) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Manually register the subscriber:
ASSERT_TRUE(factory->IsSubscriber<FilterA>());
// Obtain a packet from the factory:
auto packet = factory->NewPacket();
// Decorate with one instance:
packet->Decorate(Decoration<0>());
// Verify that no hit takes place with inadequate decoration:
EXPECT_FALSE(filterA->m_called) << "Filter called prematurely with insufficient decoration";
// Now decorate with the other requirement of the filter:
packet->Decorate(Decoration<1>());
// A hit should have taken place at this point:
EXPECT_TRUE(filterA->m_called) << "Filter was not called even though it was fully satisfied";
}
TEST_F(DecoratorTest, VerifyNoMultiDecorate) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Subscriber registration verification:
ASSERT_TRUE(factory->IsSubscriber<FilterA>());
// Obtain a packet and attempt redundant introduction:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Redundant decoration did not throw an exception as expected";
// Verify that a call has not yet been made
EXPECT_FALSE(filterA->m_called) << "A call made on an idempotent packet decoration";
// Now finish saturating the filter and ensure we get a call:
packet->Decorate(Decoration<1>());
EXPECT_TRUE(filterA->m_called) << "Filter was not called after being fully satisfied";
}
TEST_F(DecoratorTest, VerifyInterThreadDecoration) {
AutoRequired<FilterB> filterB;
AutoRequired<AutoPacketFactory> factory;
AutoCurrentContext ctxt;
// Kick off all threads:
ctxt->InitiateCoreThreads();
// Obtain a packet for processing and decorate it:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
packet->Decorate(Decoration<1>());
// Verify that the recipient has NOT yet received the message:
EXPECT_FALSE(filterB->m_called) << "A call was made to a thread which should not have been able to process it";
// Wake up the barrier and post a quit message:
filterB->m_barr.wait();
*filterB += [&filterB] { filterB->Stop(); };
filterB->Wait();
// Verify that the filter method has been called
EXPECT_TRUE(filterB->m_called) << "A deferred filter method was not called as expected";
}
TEST_F(DecoratorTest, VerifyTeardownArrangement) {
AutoRequired<AutoPacketFactory> factory;
std::weak_ptr<FilterA> filterAWeak;
{
std::shared_ptr<AutoPacket> packet;
{
// Create the filter and subscribe it
std::shared_ptr<FilterA> filterA(new FilterA);
filterAWeak = filterA;
factory->AddSubscriber(filterA);
// Create the packet--this should lock in references to all subscribers:
packet = factory->NewPacket();
}
// Verify that the subscription has not expired:
ASSERT_FALSE(filterAWeak.expired()) << "A subscriber while it was still registered";
{
std::shared_ptr<FilterA> filterA = filterAWeak.lock();
// Unsubscribe the filter:
factory->RemoveSubscriber(filterA);
}
// Verify that unsubscription STILL does not result in expiration:
ASSERT_FALSE(filterAWeak.expired()) << "A subscriber expired before all packets on that subscriber were satisfied";
//Create a new packet after having removed the only filter on it.
auto packet2 = factory->NewPacket();
ASSERT_FALSE(packet2->HasSubscribers<Decoration<0>>()) << "A packet had subscriptions after the only subscriber was removed.";
// Satisfy the packet:
packet->Decorate(Decoration<0>());
packet->Decorate(Decoration<1>());
auto packet3 = factory->NewPacket();
ASSERT_FALSE(packet3->HasSubscribers<Decoration<0>>()) << "A packet had subscriptions after the only subscriber was removed.";
}
// Filter should be expired now:
ASSERT_TRUE(filterAWeak.expired()) << "Subscriber was still left outstanding even though all references should be gone";
}
TEST_F(DecoratorTest, VerifyCheckout) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet for use with deferred decoration:
auto packet = factory->NewPacket();
{
// Verify that an unsubscribed decoration returns a correct checkout:
auto unused = packet->Checkout<Decoration<4>>();
EXPECT_FALSE(unused) << "Checkout incorrectly generated for unsubscribed decoration";
}
// Satisfy the other decoration:
packet->Decorate(Decoration<1>());
{
AutoCheckout<Decoration<0>> exterior;
{
AutoCheckout<Decoration<0>> checkout = packet->Checkout<Decoration<0>>();
// Verify we can move the original type:
AutoCheckout<Decoration<0>> checkoutMoved(std::move(checkout));
// Verify no hits yet:
EXPECT_FALSE(filterA->m_called) << "Filter called as a consequence of a checkout move operation";
// Move the checkout a second time:
exterior = std::move(checkoutMoved);
}
// Still no hits
EXPECT_FALSE(filterA->m_called) << "Filter called before a decoration checkout expired";
// Mark ready so we get committed:
exterior.Ready();
}
// Verify a hit took place now
EXPECT_TRUE(filterA->m_called) << "Filter was not called after all decorations were installed";
}
TEST_F(DecoratorTest, RollbackCorrectness) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet for use with deferred decoration:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<1>());
// Request and immediately allow the destruction of a checkout:
packet->Checkout<Decoration<0>>();
// Verify no hit took place--the checkout should have been cancelled:
EXPECT_FALSE(filterA->m_called) << "Filter was not called after all decorations were installed";
// We should not be able to obtain another checkout of this decoration on this packet:
EXPECT_ANY_THROW(packet->Checkout<Decoration<0>>()) << "An attempt to check out a decoration a second time should have failed";
// We shouldn't be able to manually decorate, either:
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "An attempt to manually add a previously failed decoration succeeded where it should not have";
}
TEST_F(DecoratorTest, VerifyAntiDecorate) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
{
// Obtain a new packet and mark an unsatisfiable decoration:
auto packet = factory->NewPacket();
packet->Unsatisfiable<Decoration<0>>();
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Decoration succeeded on a decoration marked unsatisfiable";
}
{
// Obtain a new packet and try to make a satisfied decoration unsatisfiable.
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
EXPECT_ANY_THROW(packet->Unsatisfiable<Decoration<0>>()) << "Succeeded in marking an already-existing decoration as unsatisfiable";
}
}
TEST_F(DecoratorTest, VerifyReflexiveReciept) {
AutoRequired<FilterA> filterA;
AutoRequired<FilterC> filterC;
AutoRequired<FilterD> filterD;
AutoRequired<FilterE> filterE;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet first:
auto packet = factory->NewPacket();
// The mere act of obtaining a packet should have triggered filterD to be fired:
EXPECT_TRUE(filterD->m_called) << "Trivial filter was not called as expected";
// The packet should be able to obtain a pointer to itself:
{
AutoPacketAdaptor extractor(*packet);
AutoPacket* reflex = extractor;
EXPECT_EQ(packet.get(), reflex) << "Packet reflexive reference was not an identity";
}
// Decorate--should satisfy filterC
packet->Decorate(Decoration<0>());
EXPECT_TRUE(filterC->m_called) << "FilterC should have been satisfied with one decoration";
// FilterC should have also satisfied filterA:
EXPECT_TRUE(filterA->m_called) << "FilterA should have been satisfied by FilterC";
// Release the packet, and verify that filterD gets hit only once this happens
EXPECT_FALSE(filterE->m_called) << "Packet listener was notified prematurely";
packet.reset();
EXPECT_TRUE(filterE->m_called) << "Packet listener was not notified as anticipated";
}
|
Fix inverted conditional check in autowiring decorator test
|
Fix inverted conditional check in autowiring decorator test
|
C++
|
apache-2.0
|
codemercenary/autowiring,leapmotion/autowiring,leapmotion/autowiring,leapmotion/autowiring,leapmotion/autowiring,codemercenary/autowiring,codemercenary/autowiring,codemercenary/autowiring,leapmotion/autowiring,codemercenary/autowiring,leapmotion/autowiring,codemercenary/autowiring
|
f426680ada62e19c4c7fa220d385a23154c4ad6a
|
natus/misc.hpp
|
natus/misc.hpp
|
/*
* Copyright (c) 2010 Nathaniel McCallum <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#ifndef MISCXX_HPP_
#define MISCXX_HPP_
#include "types.hpp"
#include "value.hpp"
#include <cstdarg>
namespace natus {
char* vsprintf(const char* format, va_list ap);
char* sprintf(const char* format, ...);
Value throwException(Value ctx, const char* type, const char* format, ...);
Value throwException(Value ctx, const char* type, const char* format, va_list ap);
Value throwException(Value ctx, const char* type, int code, const char* format, ...);
Value throwException(Value ctx, const char* type, int code, const char* format, va_list ap);
Value throwException(Value ctx, int errorno);
Value checkArguments(Value args, const char* fmt);
Value fromJSON(Value json);
Value fromJSON(Value ctx, UTF8 json);
Value fromJSON(Value ctx, UTF16 json);
Value toJSON(Value val);
}
#endif /* MISCXX_HPP_ */
|
/*
* Copyright (c) 2010 Nathaniel McCallum <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#ifndef MISCXX_HPP_
#define MISCXX_HPP_
#include "types.hpp"
#include "value.hpp"
#include <cstdarg>
#define NT_CHECK_ARGUMENTS(arg, fmt) \
Value _exc = checkArguments(arg, fmt); \
if (_exc.isException()) return _exc;
namespace natus {
char* vsprintf(const char* format, va_list ap);
char* sprintf(const char* format, ...);
Value throwException(Value ctx, const char* type, const char* format, ...);
Value throwException(Value ctx, const char* type, const char* format, va_list ap);
Value throwException(Value ctx, const char* type, int code, const char* format, ...);
Value throwException(Value ctx, const char* type, int code, const char* format, va_list ap);
Value throwException(Value ctx, int errorno);
Value checkArguments(Value args, const char* fmt);
Value fromJSON(Value json);
Value fromJSON(Value ctx, UTF8 json);
Value fromJSON(Value ctx, UTF16 json);
Value toJSON(Value val);
}
#endif /* MISCXX_HPP_ */
|
add the NT_CHECK_ARGUMENTS() macro for misc.hpp
|
add the NT_CHECK_ARGUMENTS() macro for misc.hpp
|
C++
|
mit
|
Natus/natus,Natus/natus,Natus/natus,Natus/natus
|
4ef41de71e48ac5eb52d7c5e917c879d8bc61e38
|
src/utility/FPECheck.cc
|
src/utility/FPECheck.cc
|
/***
DEVSIM
Copyright 2013 Devsim LLC
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 "FPECheck.hh"
#include <signal.h>
#ifdef __linux__
#include <fpu_control.h>
#include <fenv.h>
#endif
#ifdef _WIN32
#include <Float.h>
#endif
#ifdef __APPLE__
#include <fenv.h>
#endif
#include <cmath>
#include <cassert>
FPECheck::FPEFlag_t FPECheck::fpe_raised_ = 0;
#ifndef _WIN32
void fpehandle(int)
{
assert(0);
}
#endif
void FPECheck::InitializeFPE()
{
/// Prevent the signal handler from trapping the exception and aborting
/// This has no effect unless there is an feenableexcept
#ifndef _WIN32
signal(SIGFPE, fpehandle);
////// THIS IS TO CAUSE THE FPE TO TRIGGER A SIGNAL
#if 0
int x=fegetexcept();
feenableexcept(x| FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW);
#endif
#endif
#ifdef __linux__
// http://www.wrcad.com/linux_numerics.txt
/*
This puts the X86 FPU in 64-bit precision mode. The default
under Linux is to use 80-bit mode, which produces subtle
differences from FreeBSD and other systems, eg,
(int)(1000*atof("0.3")) is 300 in 64-bit mode, 299 in 80-bit
mode.
*/
#if 1
fpu_control_t cw;
_FPU_GETCW(cw);
cw &= ~_FPU_EXTENDED;
cw |= _FPU_DOUBLE;
_FPU_SETCW(cw);
#endif
#endif
/// Set the flags we want to catch
ClearFPE();
}
void FPECheck::ClearFPE()
{
#ifdef _WIN32
_clearfp();
#else
feclearexcept(FE_ALL_EXCEPT);
#endif
fpe_raised_ = FPECheck::getClearedFlag();
}
FPECheck::FPEFlag_t FPECheck::getFPEMask()
{
#ifdef _WIN32
return (EM_INVALID | EM_ZERODIVIDE | EM_OVERFLOW);
#else
return (FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW);
#endif
}
FPECheck::FPEFlag_t FPECheck::getFPEFlags()
{
#ifdef _WIN32
return (_statusfp() & getFPEMask()) | fpe_raised_;
#else
return fetestexcept(getFPEMask()) | fpe_raised_;
#endif
}
bool FPECheck::CheckFPE()
{
return getFPEFlags() != 0;
}
bool FPECheck::CheckFPE(FPECheck::FPEFlag_t x)
{
return (x & getFPEMask()) != 0;
}
bool FPECheck::IsInvalid(FPECheck::FPEFlag_t x)
{
#ifdef _WIN32
return (x & EM_INVALID) != 0;
#else
return (x & FE_INVALID) != 0;
#endif
}
bool FPECheck::IsDivByZero(FPECheck::FPEFlag_t x)
{
#ifdef _WIN32
return (x & EM_ZERODIVIDE) != 0;
#else
return (x & FE_DIVBYZERO) != 0;
#endif
}
bool FPECheck::IsInexact(FPECheck::FPEFlag_t x)
{
#ifdef _WIN32
return (x & EM_INEXACT) != 0;
#else
return (x & FE_INEXACT) != 0;
#endif
}
bool FPECheck::IsOverflow(FPECheck::FPEFlag_t x)
{
#ifdef _WIN32
return (x & EM_OVERFLOW) != 0;
#else
return (x & FE_OVERFLOW) != 0;
#endif
}
bool FPECheck::IsUnderflow(FPECheck::FPEFlag_t x)
{
#ifdef _WIN32
return (x & EM_UNDERFLOW) != 0;
#else
return (x & FE_UNDERFLOW) != 0;
#endif
}
std::string FPECheck::getFPEString(const FPECheck::FPEFlag_t feFlags)
{
std::string out;
if (IsInvalid(feFlags))
{
out += "Invalid";
}
if (IsDivByZero(feFlags))
{
if (!out.empty())
{
out += ", ";
}
out += "Divide-by-zero";
}
if (IsInexact(feFlags))
{
if (!out.empty())
{
out += ", ";
}
out += "Inexact";
}
if (IsOverflow(feFlags))
{
if (!out.empty())
{
out += ", ";
}
out += "Overflow";
}
if (IsUnderflow(feFlags))
{
if (!out.empty())
{
out += ", ";
}
out += "Underflow";
}
return out;
}
std::string FPECheck::getFPEString()
{
const FPECheck::FPEFlag_t feFlags = getFPEFlags();
return getFPEString(feFlags);
}
FPECheck::FPEFlag_t FPECheck::getClearedFlag()
{
return 0;
}
FPECheck::FPEFlag_t FPECheck::combineFPEFlags(FPECheck::FPEFlag_t x, FPECheck::FPEFlag_t y)
{
return x | y;
}
void FPECheck::raiseFPE(FPECheck::FPEFlag_t x)
{
/// consider making this mutexed
fpe_raised_ |= x;
}
#ifdef TEST_FPE_CODE
#include <iostream>
int main()
{
FPECheck::InitializeFPE();
double a = 1;
double b = 0;
FPECheck::ClearFPE();
double x = a/b;
if (FPECheck::CheckFPE())
{
std::cerr << "There was an FPE" << std::endl;
std::cerr << FPECheck::getFPEString();
}
FPECheck::ClearFPE();
double y = 3.0*4;
if (FPECheck::CheckFPE())
{
std::cerr << "There was an FPE" << std::endl;
std::cerr << FPECheck::getFPEString();
}
FPECheck::ClearFPE();
double z = log(0.0001);
if (FPECheck::CheckFPE())
{
std::cerr << "There was an FPE" << std::endl;
std::cerr << FPECheck::getFPEString();
}
}
#endif /*TEST_FPE_CODE*/
|
/***
DEVSIM
Copyright 2013 Devsim LLC
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 "FPECheck.hh"
#include <signal.h>
#ifdef __linux__
#include <fpu_control.h>
#endif
#include <cfenv>
#include <cmath>
#include <cassert>
FPECheck::FPEFlag_t FPECheck::fpe_raised_ = 0;
#ifndef _WIN32
void fpehandle(int)
{
assert(0);
}
#endif
void FPECheck::InitializeFPE()
{
/// Prevent the signal handler from trapping the exception and aborting
/// This has no effect unless there is an feenableexcept
#ifndef _WIN32
signal(SIGFPE, fpehandle);
////// THIS IS TO CAUSE THE FPE TO TRIGGER A SIGNAL
#if 0
int x=fegetexcept();
feenableexcept(x| FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW);
#endif
#endif
#ifdef __linux__
// http://www.wrcad.com/linux_numerics.txt
/*
This puts the X86 FPU in 64-bit precision mode. The default
under Linux is to use 80-bit mode, which produces subtle
differences from FreeBSD and other systems, eg,
(int)(1000*atof("0.3")) is 300 in 64-bit mode, 299 in 80-bit
mode.
*/
#if 1
fpu_control_t cw;
_FPU_GETCW(cw);
cw &= ~_FPU_EXTENDED;
cw |= _FPU_DOUBLE;
_FPU_SETCW(cw);
#endif
#endif
/// Set the flags we want to catch
ClearFPE();
}
void FPECheck::ClearFPE()
{
feclearexcept(FE_ALL_EXCEPT);
fpe_raised_ = FPECheck::getClearedFlag();
}
FPECheck::FPEFlag_t FPECheck::getFPEMask()
{
return (FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW);
}
FPECheck::FPEFlag_t FPECheck::getFPEFlags()
{
return fetestexcept(getFPEMask()) | fpe_raised_;
}
bool FPECheck::CheckFPE()
{
return getFPEFlags() != 0;
}
bool FPECheck::CheckFPE(FPECheck::FPEFlag_t x)
{
return (x & getFPEMask()) != 0;
}
bool FPECheck::IsInvalid(FPECheck::FPEFlag_t x)
{
return (x & FE_INVALID) != 0;
}
bool FPECheck::IsDivByZero(FPECheck::FPEFlag_t x)
{
return (x & FE_DIVBYZERO) != 0;
}
bool FPECheck::IsInexact(FPECheck::FPEFlag_t x)
{
return (x & FE_INEXACT) != 0;
}
bool FPECheck::IsOverflow(FPECheck::FPEFlag_t x)
{
return (x & FE_OVERFLOW) != 0;
}
bool FPECheck::IsUnderflow(FPECheck::FPEFlag_t x)
{
return (x & FE_UNDERFLOW) != 0;
}
std::string FPECheck::getFPEString(const FPECheck::FPEFlag_t feFlags)
{
std::string out;
if (IsInvalid(feFlags))
{
out += "Invalid";
}
if (IsDivByZero(feFlags))
{
if (!out.empty())
{
out += ", ";
}
out += "Divide-by-zero";
}
if (IsInexact(feFlags))
{
if (!out.empty())
{
out += ", ";
}
out += "Inexact";
}
if (IsOverflow(feFlags))
{
if (!out.empty())
{
out += ", ";
}
out += "Overflow";
}
if (IsUnderflow(feFlags))
{
if (!out.empty())
{
out += ", ";
}
out += "Underflow";
}
return out;
}
std::string FPECheck::getFPEString()
{
const FPECheck::FPEFlag_t feFlags = getFPEFlags();
return getFPEString(feFlags);
}
FPECheck::FPEFlag_t FPECheck::getClearedFlag()
{
return 0;
}
FPECheck::FPEFlag_t FPECheck::combineFPEFlags(FPECheck::FPEFlag_t x, FPECheck::FPEFlag_t y)
{
return x | y;
}
void FPECheck::raiseFPE(FPECheck::FPEFlag_t x)
{
/// consider making this mutexed
fpe_raised_ |= x;
}
#ifdef TEST_FPE_CODE
#include <iostream>
int main()
{
FPECheck::InitializeFPE();
double a = 1;
double b = 0;
FPECheck::ClearFPE();
double x = a/b;
if (FPECheck::CheckFPE())
{
std::cerr << "There was an FPE" << std::endl;
std::cerr << FPECheck::getFPEString();
}
FPECheck::ClearFPE();
double y = 3.0*4;
if (FPECheck::CheckFPE())
{
std::cerr << "There was an FPE" << std::endl;
std::cerr << FPECheck::getFPEString();
}
FPECheck::ClearFPE();
double z = log(0.0001);
if (FPECheck::CheckFPE())
{
std::cerr << "There was an FPE" << std::endl;
std::cerr << FPECheck::getFPEString();
}
}
#endif /*TEST_FPE_CODE*/
|
Use cenv, C++-11 for FPE handling
|
Use cenv, C++-11 for FPE handling
|
C++
|
apache-2.0
|
devsim/devsim,devsim/devsim,devsim/devsim
|
f5f07d8b8b9b89949d79411596d9d1a75453133f
|
Server/Core.cpp
|
Server/Core.cpp
|
#include "Core.h"
#include <Windows.h>
#include <Shlwapi.h>
#include <map>
#include <cstdio>
#include <mutex>
#pragma comment(lib, "Shlwapi.lib")
std::wstring g_audioPath;
std::wstring g_beatmapPath;
std::map<std::wstring, std::wstring> g_songCached;
std::mutex g_songMutex;
NamedPipe g_namedPipe
;
//
// Proxy Ǻ. (#define ǵǾ.)
// MAKE_PROXY_DEF(module, function, proxy)
// HookEngine<decltype(proxy)> proxy__hk = HookEngine<decltype(proxy)>(module, function, proxy)
// EXAMPLE :
// MAKE_PROXY_DEF(NAME_KERNEL_DLL, "ReadFile", proxyReadFile);
// ==> HookEngine< decltype(proxyReadFile) > proxyReadFile__hk = HookEngine< decltype(proxy) >(module, function, proxy);
//
MAKE_PROXY_DEF(NAME_KERNEL_DLL, "ReadFile", proxyReadFile);
MAKE_PROXY_DEF(NAME_BASS_DLL, "BASS_ChannelPlay", proxyBASS_ChannelPlay);
MAKE_PROXY_DEF(NAME_BASS_DLL, "BASS_ChannelSetPosition", proxyBASS_ChannelSetPosition);
MAKE_PROXY_DEF(NAME_BASS_DLL, "BASS_ChannelSetAttribute", proxyBASS_ChannelSetAttribute);
MAKE_PROXY_DEF(NAME_BASS_DLL, "BASS_ChannelPause", proxyBASS_ChannelPause);
void Start()
{
BeginHook(); // Begin Hooking Method.
EngineHook(proxyReadFile); // ReadFile Hook.
EngineHook(proxyBASS_ChannelPlay); // ChannelPlay Hook.
EngineHook(proxyBASS_ChannelSetPosition); // ChannelSetPosition Hook.
EngineHook(proxyBASS_ChannelSetAttribute); // ChannelSetAttribute Hook.
EngineHook(proxyBASS_ChannelPause); // ChannelPause Hook.
EndHook(); // End Hooking Method.
g_namedPipe.Start(NAME_NAMED_PIPE);
}
void Stop()
{
BeginHook(); // Begin Hooking Method.
EngineUnhook(proxyReadFile); // ReadFile Unhook.
EngineUnhook(proxyBASS_ChannelPlay); // ChannelPlay Unhook.
EngineUnhook(proxyBASS_ChannelSetPosition); // ChannelSetPostion Unhook.
EngineUnhook(proxyBASS_ChannelSetAttribute); // ChannelSetAttribute Unhook.
EngineUnhook(proxyBASS_ChannelPause); // ChannelPause Unhook.
EndHook(); // End Hooking Method.
g_namedPipe.Stop();
}
//
// TODO : currentTime tempo ǹϴ ˼ ϴ.
// ּ Ź帳ϴ.
//
void Notify(double currentTime, float tempo)
{
wchar_t message[MAX_MESSAGE_LENGTH];
long long sysTime;
GetSystemTime((LPSYSTEMTIME)&sysTime);
// ÷ϰִ proxyReadFile Ŭ̾Ʈ մϴ.
g_songMutex.lock();
swprintf(message, L"%llx|%s|%lf|%f|%s\n",
sysTime,
g_audioPath.c_str(),
currentTime,
tempo,
g_beatmapPath.c_str());
g_songMutex.unlock();
g_namedPipe.PushMessage(std::wstring(message));
}
BOOL WINAPI proxyReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
if (!SelectProxy(proxyReadFile).OriginalFunction(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped))
{
return FALSE;
}
TCHAR nameTmpFilePath[MAX_PATH];
DWORD dwTmpFilePathLength = GetFinalPathNameByHandle(hFile, nameTmpFilePath, MAX_PATH, VOLUME_NAME_DOS);
DWORD dwFilePosition = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - (*lpNumberOfBytesRead);
// //?/ ϱ 4 .
TCHAR* nameFile = &nameTmpFilePath[4];
DWORD dwFilePathLength = dwTmpFilePathLength - 4;
// д Ʈ ̰ պκ оٸ :
// ̸ Ե Path κ 4ڸ ڸ. 4ڿ .osu Ͽ osu Ȯ
if (wcsncmp(L".osu", &nameFile[dwFilePathLength - 4], 4) == 0 && dwFilePosition == 0)
{
// .osu UTF-8(Multibyte) ڵ
// strtok ҽ ϹǷ strdup ̿ؼ ڸ .
LPSTR buffer = strdup((const char*)(lpBuffer));
// for ̿ؼ ٸ strtok ߶.
for (LPSTR line = strtok(buffer, "\n"); line != NULL; line = strtok(NULL, "\n"))
{
// ߶ ٿ Token ִ Ȯϰ ƴҰ쿡 continue.
if (strnicmp(line, AUDIO_FILE_INFO_TOKEN, strlen(AUDIO_FILE_INFO_TOKEN)) != 0)
{
continue;
}
TCHAR nameAudioFile[MAX_PATH];
mbstowcs(nameAudioFile, &line[strlen(AUDIO_FILE_INFO_TOKEN)], MAX_PATH);
StrTrimW(nameAudioFile, L" \r");
TCHAR pathAudioFile[MAX_PATH];
wcscpy(pathAudioFile, nameFile);
// pathAudioFile ϸ ϴ.
PathRemoveFileSpecW(pathAudioFile);
// ϸ Path pathAudioFile nameAudioFileٿ, Path ϴ.
PathCombineW(pathAudioFile, pathAudioFile, nameAudioFile);
g_songMutex.lock();
g_beatmapPath = (std::wstring(nameFile));
g_audioPath = (std::wstring(pathAudioFile));
if (g_songCached.find(g_audioPath) == g_songCached.end())
{
g_songCached.insert(
std::pair<std::wstring, std::wstring>(pathAudioFile, nameFile));
}
g_songMutex.unlock();
break;
}
// strdup ̿ ڿ ŵϴ.
free(buffer);
}
else
{
// Beatmap ٽ ҷ ʰ Osu Cache ҷö ִµ.
// 쿡 Audioϸ Beatmap Audio
// ִ Ȯϰ ǰִ AudioFile ٲ۴.
g_songMutex.lock();
auto cachedInfo = g_songCached.find(nameFile);
if (cachedInfo != g_songCached.end())
{
g_audioPath = cachedInfo->first;
g_beatmapPath = cachedInfo->second;
}
g_songMutex.unlock();
}
return TRUE;
}
BOOL WINAPI proxyBASS_ChannelPlay(DWORD handle, BOOL restart)
{
if (!SelectProxy(proxyBASS_ChannelPlay).OriginalFunction(handle, restart))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if (info.ctype & BASS_CTYPE_STREAM)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));
float currentTempo = 0;
BASS_ChannelGetAttribute(handle, BASS_ATTRIB_TEMPO, ¤tTempo);
//Notify(currentTime, currentTempo);
}
return TRUE;
}
BOOL WINAPI proxyBASS_ChannelSetPosition(DWORD handle, QWORD pos, DWORD mode)
{
if (!SelectProxy(proxyBASS_ChannelSetPosition).OriginalFunction(handle, pos, mode))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if (info.ctype & BASS_CTYPE_STREAM)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, pos);
float currentTempo = 0;
BASS_ChannelGetAttribute(handle, BASS_ATTRIB_TEMPO, ¤tTempo);
// !! pos ,
// ϸ proxyBASS_ChannelPlay Լ ȣǰ,
// BASS_ChannelIsActive BASS_ACTIVE_PAUSED.
if (BASS_ChannelIsActive(handle) == BASS_ACTIVE_PAUSED)
{
currentTempo = -100;
}
Notify(currentTime, currentTempo);
}
return TRUE;
}
BOOL WINAPI proxyBASS_ChannelSetAttribute(DWORD handle, DWORD attrib, float value)
{
if (!SelectProxy(proxyBASS_ChannelSetAttribute).OriginalFunction(handle, attrib, value))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if ((info.ctype & BASS_CTYPE_STREAM) && attrib == BASS_ATTRIB_TEMPO)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));
Notify(currentTime, value);
}
return TRUE;
}
BOOL WINAPI proxyBASS_ChannelPause(DWORD handle)
{
if (!SelectProxy(proxyBASS_ChannelPause).OriginalFunction(handle))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if (info.ctype & BASS_CTYPE_STREAM)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));
Notify(currentTime, -100);
}
return TRUE;
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
//
// LoaderLock ؼ ȣѴ.
//
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)Start, 0, 0, 0);
break;
case DLL_PROCESS_DETACH:
Stop();
break;
}
return TRUE;
}
|
#include "Core.h"
#include <Windows.h>
#include <Shlwapi.h>
#include <map>
#include <cstdio>
#include <mutex>
#pragma comment(lib, "Shlwapi.lib")
std::wstring g_audioPath;
std::wstring g_beatmapPath;
std::map<std::wstring, std::wstring> g_songCached;
std::mutex g_songMutex;
NamedPipe g_namedPipe
;
//
// Proxy Ǻ. (#define ǵǾ.)
// MAKE_PROXY_DEF(module, function, proxy)
// HookEngine<decltype(proxy)> proxy__hk = HookEngine<decltype(proxy)>(module, function, proxy)
// EXAMPLE :
// MAKE_PROXY_DEF(NAME_KERNEL_DLL, "ReadFile", proxyReadFile);
// ==> HookEngine< decltype(proxyReadFile) > proxyReadFile__hk = HookEngine< decltype(proxy) >(module, function, proxy);
//
MAKE_PROXY_DEF(NAME_KERNEL_DLL, "ReadFile", proxyReadFile);
MAKE_PROXY_DEF(NAME_BASS_DLL, "BASS_ChannelPlay", proxyBASS_ChannelPlay);
MAKE_PROXY_DEF(NAME_BASS_DLL, "BASS_ChannelSetPosition", proxyBASS_ChannelSetPosition);
MAKE_PROXY_DEF(NAME_BASS_DLL, "BASS_ChannelSetAttribute", proxyBASS_ChannelSetAttribute);
MAKE_PROXY_DEF(NAME_BASS_DLL, "BASS_ChannelPause", proxyBASS_ChannelPause);
void Start()
{
BeginHook(); // Begin Hooking Method.
EngineHook(proxyReadFile); // ReadFile Hook.
EngineHook(proxyBASS_ChannelPlay); // ChannelPlay Hook.
EngineHook(proxyBASS_ChannelSetPosition); // ChannelSetPosition Hook.
EngineHook(proxyBASS_ChannelSetAttribute); // ChannelSetAttribute Hook.
EngineHook(proxyBASS_ChannelPause); // ChannelPause Hook.
EndHook(); // End Hooking Method.
g_namedPipe.Start(NAME_NAMED_PIPE);
}
void Stop()
{
BeginHook(); // Begin Hooking Method.
EngineUnhook(proxyReadFile); // ReadFile Unhook.
EngineUnhook(proxyBASS_ChannelPlay); // ChannelPlay Unhook.
EngineUnhook(proxyBASS_ChannelSetPosition); // ChannelSetPostion Unhook.
EngineUnhook(proxyBASS_ChannelSetAttribute); // ChannelSetAttribute Unhook.
EngineUnhook(proxyBASS_ChannelPause); // ChannelPause Unhook.
EndHook(); // End Hooking Method.
g_namedPipe.Stop();
}
//
// TODO : currentTime tempo ǹϴ ˼ ϴ.
// ּ Ź帳ϴ.
//
void Notify(double currentTime, float tempo)
{
wchar_t message[MAX_MESSAGE_LENGTH];
long long sysTime;
GetSystemTime((LPSYSTEMTIME)&sysTime);
// ÷ϰִ proxyReadFile Ŭ̾Ʈ մϴ.
g_songMutex.lock();
swprintf(message, L"%llx|%s|%lf|%f|%s\n",
sysTime,
g_audioPath.c_str(),
currentTime,
tempo,
g_beatmapPath.c_str());
g_songMutex.unlock();
g_namedPipe.PushMessage(std::wstring(message));
}
BOOL WINAPI proxyReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped)
{
if (!SelectProxy(proxyReadFile).OriginalFunction(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped))
{
return FALSE;
}
TCHAR nameTmpFilePath[MAX_PATH];
DWORD dwTmpFilePathLength = GetFinalPathNameByHandle(hFile, nameTmpFilePath, MAX_PATH, VOLUME_NAME_DOS);
DWORD dwFilePosition = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - (*lpNumberOfBytesRead);
// //?/ ϱ 4 .
TCHAR* nameFile = &nameTmpFilePath[4];
DWORD dwFilePathLength = dwTmpFilePathLength - 4;
// д Ʈ ̰ պκ оٸ :
// ̸ Ե Path κ 4ڸ ڸ. 4ڿ .osu Ͽ osu Ȯ
if (wcsncmp(L".osu", &nameFile[dwFilePathLength - 4], 4) == 0 && dwFilePosition == 0)
{
// .osu UTF-8(Multibyte) ڵ
// strtok ҽ ϹǷ strdup ̿ؼ ڸ .
LPSTR buffer = strdup((const char*)(lpBuffer));
// for ̿ؼ ٸ strtok ߶.
for (LPSTR line = strtok(buffer, "\n"); line != NULL; line = strtok(NULL, "\n"))
{
// ߶ ٿ Token ִ Ȯϰ ƴҰ쿡 continue.
if (strnicmp(line, AUDIO_FILE_INFO_TOKEN, strlen(AUDIO_FILE_INFO_TOKEN)) != 0)
{
continue;
}
TCHAR nameAudioFile[MAX_PATH];
mbstowcs(nameAudioFile, &line[strlen(AUDIO_FILE_INFO_TOKEN)], MAX_PATH);
StrTrimW(nameAudioFile, L" \r");
TCHAR pathAudioFile[MAX_PATH];
wcscpy(pathAudioFile, nameFile);
// pathAudioFile ϸ ϴ.
PathRemoveFileSpecW(pathAudioFile);
// ϸ Path pathAudioFile nameAudioFileٿ, Path ϴ.
PathCombineW(pathAudioFile, pathAudioFile, nameAudioFile);
g_songMutex.lock();
g_beatmapPath = (std::wstring(nameFile));
g_audioPath = (std::wstring(pathAudioFile));
if (g_songCached.find(g_audioPath) == g_songCached.end())
{
g_songCached.insert(
std::pair<std::wstring, std::wstring>(pathAudioFile, nameFile));
}
g_songMutex.unlock();
break;
}
// strdup ̿ ڿ ŵϴ.
free(buffer);
}
else
{
// Beatmap ٽ ҷ ʰ Osu Cache ҷö ִµ.
// 쿡 Audioϸ Beatmap Audio
// ִ Ȯϰ ǰִ AudioFile ٲ۴.
g_songMutex.lock();
auto cachedInfo = g_songCached.find(nameFile);
if (cachedInfo != g_songCached.end())
{
g_audioPath = cachedInfo->first;
g_beatmapPath = cachedInfo->second;
}
g_songMutex.unlock();
}
return TRUE;
}
BOOL WINAPI proxyBASS_ChannelPlay(DWORD handle, BOOL restart)
{
if (!SelectProxy(proxyBASS_ChannelPlay).OriginalFunction(handle, restart))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if (info.ctype & BASS_CTYPE_STREAM)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));
float currentTempo = 0;
BASS_ChannelGetAttribute(handle, BASS_ATTRIB_TEMPO, ¤tTempo);
Notify(currentTime, currentTempo);
}
return TRUE;
}
BOOL WINAPI proxyBASS_ChannelSetPosition(DWORD handle, QWORD pos, DWORD mode)
{
if (!SelectProxy(proxyBASS_ChannelSetPosition).OriginalFunction(handle, pos, mode))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if (info.ctype & BASS_CTYPE_STREAM)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, pos);
float currentTempo = 0;
BASS_ChannelGetAttribute(handle, BASS_ATTRIB_TEMPO, ¤tTempo);
// !! pos ,
// ϸ proxyBASS_ChannelPlay Լ ȣǰ,
// BASS_ChannelIsActive BASS_ACTIVE_PAUSED.
if (BASS_ChannelIsActive(handle) == BASS_ACTIVE_PAUSED)
{
currentTempo = -100;
}
Notify(currentTime, currentTempo);
}
return TRUE;
}
BOOL WINAPI proxyBASS_ChannelSetAttribute(DWORD handle, DWORD attrib, float value)
{
if (!SelectProxy(proxyBASS_ChannelSetAttribute).OriginalFunction(handle, attrib, value))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if ((info.ctype & BASS_CTYPE_STREAM) && attrib == BASS_ATTRIB_TEMPO)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));
Notify(currentTime, value);
}
return TRUE;
}
BOOL WINAPI proxyBASS_ChannelPause(DWORD handle)
{
if (!SelectProxy(proxyBASS_ChannelPause).OriginalFunction(handle))
{
return FALSE;
}
BASS_CHANNELINFO info;
BASS_ChannelGetInfo(handle, &info);
if (info.ctype & BASS_CTYPE_STREAM)
{
double currentTime = BASS_ChannelBytes2Seconds(handle, BASS_ChannelGetPosition(handle, BASS_POS_BYTE));
Notify(currentTime, -100);
}
return TRUE;
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
//
// LoaderLock ؼ ȣѴ.
//
CreateThread(0, 0, (LPTHREAD_START_ROUTINE)Start, 0, 0, 0);
break;
case DLL_PROCESS_DETACH:
Stop();
break;
}
return TRUE;
}
|
주석처리한부분 주석해제
|
주석처리한부분 주석해제
|
C++
|
mit
|
sunghwan2789/osu-Lyrics,sunghwan2789/osu-Lyrics,sunghwan2789/osu-Lyrics
|
7a2bb054043031b53de87ba0da620303fdb9f289
|
core/src/api_impl/BigIntImpl.cpp
|
core/src/api_impl/BigIntImpl.cpp
|
/*
*
* BigIntImpl
* ledger-core
*
* Created by Pierre Pollastri on 04/11/2016.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* 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 "BigIntImpl.hpp"
#include <fmt/string.h>
namespace ledger { namespace core { namespace api {
std::shared_ptr<ledger::core::api::BigInt>
BigIntImpl::add(const std::shared_ptr<ledger::core::api::BigInt> &i) {
auto result = this->_bigi + std::dynamic_pointer_cast<BigIntImpl>(i)->_bigi;
return std::shared_ptr<BigIntImpl>(new BigIntImpl(result));
}
std::shared_ptr<ledger::core::api::BigInt>
BigIntImpl::subtract(const std::shared_ptr<ledger::core::api::BigInt> &i) {
auto result = this->_bigi - std::dynamic_pointer_cast<BigIntImpl>(i)->_bigi;
return std::shared_ptr<BigIntImpl>(new BigIntImpl(result));
}
std::shared_ptr<ledger::core::api::BigInt>
BigIntImpl::multiply(const std::shared_ptr<ledger::core::api::BigInt> &i) {
auto result = this->_bigi * std::dynamic_pointer_cast<BigIntImpl>(i)->_bigi;
return std::shared_ptr<BigIntImpl>(new BigIntImpl(result));
}
std::shared_ptr<ledger::core::api::BigInt>
BigIntImpl::divide(const std::shared_ptr<ledger::core::api::BigInt> &i) {
auto result = this->_bigi / std::dynamic_pointer_cast<BigIntImpl>(i)->_bigi;
return std::shared_ptr<BigIntImpl>(new BigIntImpl(result));
}
std::vector<std::shared_ptr<ledger::core::api::BigInt>>
BigIntImpl::divideAndRemainder(const std::shared_ptr<ledger::core::api::BigInt> &i) {
auto res1 = std::shared_ptr<BigIntImpl>(new BigIntImpl(this->_bigi / std::dynamic_pointer_cast<BigIntImpl>(i)->_bigi));
auto res2 = std::shared_ptr<BigIntImpl>(new BigIntImpl(this->_bigi + std::dynamic_pointer_cast<BigIntImpl>(i)->_bigi));
return std::vector<std::shared_ptr<ledger::core::api::BigInt>>({res1, res2});
}
std::shared_ptr<ledger::core::api::BigInt> BigIntImpl::pow(int32_t exponent) {
return std::shared_ptr<BigIntImpl>(new BigIntImpl(_bigi.pow((unsigned short) exponent)));
}
std::string BigIntImpl::toDecimalString(int32_t precision, const std::string &decimalSeparator,
const std::string &thousandSeparator) {
return "";
}
int32_t BigIntImpl::intValue() {
return _bigi.toInt();
}
int32_t BigIntImpl::compare(const std::shared_ptr<ledger::core::api::BigInt> &i) {
return _bigi.compare(dynamic_cast<BigIntImpl *>(i.get())->_bigi);
}
std::string BigIntImpl::toString(int32_t radix) {
if (radix == 10)
return _bigi.toString();
else
return _bigi.toHexString();
}
std::shared_ptr<BigInt> BigInt::fromDecimalString(const std::string &s, int32_t precision,
const std::string &decimalSeparator) {
fmt::StringWriter writer;
fmt::StringWriter decimaleWriter;
auto hasReachedDecimalPart = false;
auto d = 0;
for (auto i = 0; i < s.length(); i++) {
auto c = s[i];
if (c >= '0' && c <= '9' && !hasReachedDecimalPart) {
writer << c;
} else if (c == decimalSeparator[0] && !hasReachedDecimalPart) {
hasReachedDecimalPart = true;
} else if (c >= '0' && c <= '9' && hasReachedDecimalPart) {
decimaleWriter << c;
} else {
d += 1;
}
}
while (decimaleWriter.size() < precision) {
decimaleWriter << '0';
}
writer << decimaleWriter.c_str();
return fromIntegerString(writer.c_str(), 10);
}
std::shared_ptr<BigInt> BigInt::fromIntegerString(const std::string &s, int32_t radix) {
if (radix == 10) {
return std::shared_ptr<BigIntImpl>(new BigIntImpl(ledger::core::BigInt::fromDecimal(s)));
} else {
return std::shared_ptr<BigIntImpl>(new BigIntImpl(ledger::core::BigInt::fromHex(s)));
}
}
std::shared_ptr<BigInt> BigInt::fromLong(long long value) {
return std::make_shared<BigIntImpl>(ledger::core::BigInt::fromScalar(value));
}
}
}
}
|
/*
*
* BigIntImpl
* ledger-core
*
* Created by Pierre Pollastri on 04/11/2016.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* 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 "BigIntImpl.hpp"
#include <fmt/string.h>
namespace ledger { namespace core { namespace api {
std::shared_ptr<ledger::core::api::BigInt>
BigIntImpl::add(const std::shared_ptr<ledger::core::api::BigInt> &i) {
auto result = this->_bigi + std::dynamic_pointer_cast<BigIntImpl>(i)->_bigi;
return std::shared_ptr<BigIntImpl>(new BigIntImpl(result));
}
std::shared_ptr<ledger::core::api::BigInt>
BigIntImpl::subtract(const std::shared_ptr<ledger::core::api::BigInt> &i) {
auto result = this->_bigi - std::dynamic_pointer_cast<BigIntImpl>(i)->_bigi;
return std::shared_ptr<BigIntImpl>(new BigIntImpl(result));
}
std::shared_ptr<ledger::core::api::BigInt>
BigIntImpl::multiply(const std::shared_ptr<ledger::core::api::BigInt> &i) {
auto result = this->_bigi * std::dynamic_pointer_cast<BigIntImpl>(i)->_bigi;
return std::shared_ptr<BigIntImpl>(new BigIntImpl(result));
}
std::shared_ptr<ledger::core::api::BigInt>
BigIntImpl::divide(const std::shared_ptr<ledger::core::api::BigInt> &i) {
auto result = this->_bigi / std::dynamic_pointer_cast<BigIntImpl>(i)->_bigi;
return std::shared_ptr<BigIntImpl>(new BigIntImpl(result));
}
std::vector<std::shared_ptr<ledger::core::api::BigInt>>
BigIntImpl::divideAndRemainder(const std::shared_ptr<ledger::core::api::BigInt> &i) {
auto res1 = std::shared_ptr<BigIntImpl>(new BigIntImpl(this->_bigi / std::dynamic_pointer_cast<BigIntImpl>(i)->_bigi));
auto res2 = std::shared_ptr<BigIntImpl>(new BigIntImpl(this->_bigi + std::dynamic_pointer_cast<BigIntImpl>(i)->_bigi));
return std::vector<std::shared_ptr<ledger::core::api::BigInt>>({res1, res2});
}
std::shared_ptr<ledger::core::api::BigInt> BigIntImpl::pow(int32_t exponent) {
return std::shared_ptr<BigIntImpl>(new BigIntImpl(_bigi.pow((unsigned short) exponent)));
}
std::string BigIntImpl::toDecimalString(int32_t precision, const std::string &decimalSeparator,
const std::string &thousandSeparator) {
return "";
}
int32_t BigIntImpl::intValue() {
return _bigi.toInt();
}
int32_t BigIntImpl::compare(const std::shared_ptr<ledger::core::api::BigInt> &i) {
return _bigi.compare(dynamic_cast<BigIntImpl *>(i.get())->_bigi);
}
std::string BigIntImpl::toString(int32_t radix) {
if (radix == 10)
return _bigi.toString();
else
return _bigi.toHexString();
}
std::shared_ptr<BigInt> BigInt::fromDecimalString(const std::string &s, int32_t precision,
const std::string &decimalSeparator) {
fmt::StringWriter writer;
fmt::StringWriter decimaleWriter;
auto hasReachedDecimalPart = false;
auto d = 0;
for (auto i = 0; i < s.length(); i++) {
auto c = s[i];
if (c >= '0' && c <= '9' && !hasReachedDecimalPart) {
writer << c;
} else if (c == decimalSeparator[0] && !hasReachedDecimalPart) {
hasReachedDecimalPart = true;
} else if (c >= '0' && c <= '9' && hasReachedDecimalPart) {
decimaleWriter << c;
} else {
d += 1;
}
}
while (decimaleWriter.size() < precision) {
decimaleWriter << '0';
}
writer << decimaleWriter.c_str();
return fromIntegerString(writer.c_str(), 10);
}
std::shared_ptr<BigInt> BigInt::fromIntegerString(const std::string &s, int32_t radix) {
if (radix == 10) {
return std::shared_ptr<BigIntImpl>(new BigIntImpl(ledger::core::BigInt::fromDecimal(s)));
} else {
return std::shared_ptr<BigIntImpl>(new BigIntImpl(ledger::core::BigInt::fromHex(s)));
}
}
std::shared_ptr<BigInt> BigInt::fromLong(int64_t value) {
return std::make_shared<BigIntImpl>(ledger::core::BigInt::fromScalar(value));
}
}
}
}
|
Fix api::BigInt::fromLong declaration
|
Fix api::BigInt::fromLong declaration
|
C++
|
mit
|
LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core
|
17755389f2386941d45261a0833fbf6d6dff499d
|
WumpusWorld/PrologTest.cpp
|
WumpusWorld/PrologTest.cpp
|
#define _CRT_SECURE_NO_WARNINGS
#include <SWI-cpp.h>
#include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <vector>
#include "programpath.h"
#define WORLD_LEN 6
using namespace std;
typedef struct point {
int x;
int y;
} Point;
typedef enum entity {
OURO,
WUMPUS,
ABISMO,
MORCEGO,
VAZIO
} Entity;
typedef struct wumpusState {
Entity grid[WORLD_LEN][WORLD_LEN][2];
int score;
Point agentPosition;
} WumpusState;
enum ActionType {
ANDAR,
ATIRAR,
MATAR_WUMPUS,
MATAR_MORCEGO,
EFEITO_MORCEGO,
PEGAR_OURO
};
typedef struct action {
Point location;
ActionType actionType;
} Action;
static void fillInitialState(WumpusState *state);
static void executeSearch();
static void initializeWorld();
static void restartWorld();
static void removeAll();
static void printWorld(WumpusState *state);
static void printColor(char *, int);
static void fillObstacles(WumpusState *state);
static void fillRewards (WumpusState *state);
static void updateAgentPosition(WumpusState *state);
static void getActions(vector<Action> &);
static ActionType getActionTypeFromString(char * actionString);
static void updateStateWithAction(WumpusState *state, Action action);
static int getScore();
int main(void) {
char* argv[] = {"swipl.dll", "-s", PROGRAM_PATH};
PlEngine e(3, argv);
WumpusState *state = new WumpusState();
fillInitialState(state);
printWorld(state);
executeSearch();
vector<Action> actions;
getActions(actions);
for (vector<Action>::iterator list_iter = actions.begin(); list_iter != actions.end(); list_iter++) {
_getch();
updateStateWithAction(state, *list_iter);
printWorld(state);
}
return 0;
}
static void fillInitialState(WumpusState *state) {
initializeWorld();
state->agentPosition;
state->grid[WORLD_LEN][WORLD_LEN][2];
for (int i = 0; i < WORLD_LEN; i++) {
for (int j = 0; j < WORLD_LEN; j++) {
state->grid[i][j][0] = VAZIO;
state->grid[i][j][1] = VAZIO;
}
}
state->score = getScore();
fillObstacles(state);
fillRewards(state);
updateAgentPosition(state);
}
static void executeSearch() {
PlCall("buscaOuro", NULL);
}
static void initializeWorld() {
PlCall("gerarMundoRandomico", NULL);
}
static void restartWorld() {
PlCall("reiniciarR", NULL);
}
static void removeAll() {
PlCall("removeTudo", NULL);
}
static void fillObstacles(WumpusState *state) {
PlTermv av(3);
PlQuery q("obstaculo", av);
int x, y;
char *obs;
Entity obstacle;
while (q.next_solution()) {
obs = av[2];
if (strcmp("abismo", obs) == 0) {
obstacle = ABISMO;
}
else if (strcmp("wumpus", obs) == 0) {
obstacle = WUMPUS;
}
else if (strcmp("morcego", obs) == 0) {
obstacle = MORCEGO;
}
x = (int)av[0] - 1;
y = (int)av[1] - 1;
state->grid[x][y][0] = obstacle;
}
}
static void fillRewards(WumpusState *state) {
PlTermv av(3);
PlQuery q("recompensa", av);
int x, y;
Entity reward = OURO;
while (q.next_solution()) {
x = (int) av[0] - 1;
y = (int) av[1] - 1;
state->grid[x][y][1] = reward;
}
}
static void updateAgentPosition(WumpusState *state) {
PlTermv av(2);
PlQuery q("posicao", av);
int x, y;
while (q.next_solution()) {
x = (int) av[0];
y = (int) av[1];
}
Point p;
p.x = x;
p.y = y;
state->agentPosition = p;
}
static int getScore() {
int score = 0;
PlTermv av(1);
PlQuery q("pontuacao", av);
while (q.next_solution()) {
score = (int) av[0];
}
return score;
}
static void getActions(vector<Action> &actions) {
PlTermv av(1);
PlQuery q("acao", av);
PlTerm actionsTerm(av[0]);
q.next_solution();
PlTail actionsArray(actionsTerm);
PlTerm actionTerm;
while (actionsArray.next(actionTerm)) { /* for each action */
PlTail actionArray(actionTerm);
PlTerm actionPart;
Action action;
Point p;
for (int i = 0; actionArray.next(actionPart); i++) {
switch (i) {
case 0:
p.x = (int) actionPart;
break;
case 1:
p.y = (int) actionPart;
break;
case 2:
action.actionType = getActionTypeFromString((char *) actionPart);
break;
}
}
action.location = p;
actions.push_back(action);
}
}
/* TODO */
static ActionType getActionTypeFromString(char * actionString) {
if (strcmp(actionString, "andar") == 0) {
return ANDAR;
}
if (strcmp(actionString, "atirar") == 0) {
return ATIRAR;
}
if (strcmp(actionString, "matarwumpus") == 0) {
return MATAR_WUMPUS;
}
if (strcmp(actionString, "matarmorcego") == 0) {
return MATAR_MORCEGO;
}
if (strcmp(actionString, "efeitoMorcego") == 0) {
return EFEITO_MORCEGO;
}
if (strcmp(actionString, "pegarOuro") == 0) {
return PEGAR_OURO;
}
}
static void updateStateWithAction(WumpusState *state, Action action) {
switch (action.actionType) {
case ANDAR:
state->score -= 1;
case EFEITO_MORCEGO:
state->agentPosition.x = action.location.x;
state->agentPosition.y = action.location.y;
break;
case ATIRAR:
state->score -= 10;
break;
case MATAR_WUMPUS:
state->grid[action.location.x][action.location.y][0] = VAZIO;
break;
case MATAR_MORCEGO:
state->grid[action.location.x][action.location.y][0] = VAZIO;
break;
case PEGAR_OURO:
state->grid[action.location.x][action.location.y][1] = VAZIO;
state->score += 1000;
break;
}
};
static void printWorld(WumpusState *state) {
for (int y = 0; y < WORLD_LEN; y++) {
for (int x = 0; x < WORLD_LEN; x++) {
int posx = state->agentPosition.x;
int posy = state->agentPosition.y;
if (x == posx - 1 && y == posy - 1) {
printColor("AG ", FOREGROUND_BLUE | FOREGROUND_RED);
continue;
}
char entityString[] = "XX ";
int color = 0;
switch (state->grid[x][y][0]) {
case ABISMO:
entityString[0] = 'A';
color = FOREGROUND_GREEN;
break;
case WUMPUS:
entityString[0] = 'W';
color = FOREGROUND_RED;
break;
case MORCEGO:
entityString[0] = 'M';
color = FOREGROUND_BLUE;
break;
default:
entityString[0] = 'X';
color = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN;
}
if (state->grid[x][y][1] == OURO) {
entityString[1] = 'O';
color = FOREGROUND_RED | FOREGROUND_GREEN;
}
printColor(entityString, color);
}
printf("\n");
}
printf("Score: %d", state->score);
printf("\n");
}
static void printColor(char *txt, int color) {
HANDLE console;
CONSOLE_SCREEN_BUFFER_INFO info;
console = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(console, &info);
SetConsoleTextAttribute(console, color);
printf("%s", txt);
SetConsoleTextAttribute(console, info.wAttributes);
}
|
#define _CRT_SECURE_NO_WARNINGS
#include <SWI-cpp.h>
#include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <vector>
#include "programpath.h"
#define WORLD_LEN 6
using namespace std;
typedef struct point {
int x;
int y;
} Point;
typedef enum entity {
OURO,
WUMPUS,
ABISMO,
MORCEGO,
VAZIO
} Entity;
typedef struct wumpusState {
Entity grid[WORLD_LEN][WORLD_LEN][2];
int score;
Point agentPosition;
} WumpusState;
enum ActionType {
ANDAR,
ATIRAR,
MATAR_WUMPUS,
MATAR_MORCEGO,
EFEITO_MORCEGO,
PEGAR_OURO
};
typedef struct action {
Point location;
ActionType actionType;
} Action;
static void fillInitialState(WumpusState *state);
static void executeSearch();
static void initializeWorld();
static void restartWorld();
static void removeAll();
static void printWorld(WumpusState *state);
static void printColor(char *, int);
static void fillObstacles(WumpusState *state);
static void fillRewards (WumpusState *state);
static void updateAgentPosition(WumpusState *state);
static void getActions(vector<Action> &);
static ActionType getActionTypeFromString(char * actionString);
static void updateStateWithAction(WumpusState *state, Action action);
static int getScore();
int main(void) {
char* argv[] = {"swipl.dll", "-s", PROGRAM_PATH};
PlEngine e(3, argv);
WumpusState *state = new WumpusState();
fillInitialState(state);
printWorld(state);
executeSearch();
vector<Action> actions;
getActions(actions);
for (vector<Action>::iterator list_iter = actions.begin(); list_iter != actions.end(); list_iter++) {
_getch();
updateStateWithAction(state, *list_iter);
printWorld(state);
}
return 0;
}
static void fillInitialState(WumpusState *state) {
initializeWorld();
state->agentPosition;
state->grid[WORLD_LEN][WORLD_LEN][2];
for (int i = 0; i < WORLD_LEN; i++) {
for (int j = 0; j < WORLD_LEN; j++) {
state->grid[i][j][0] = VAZIO;
state->grid[i][j][1] = VAZIO;
}
}
state->score = getScore();
fillObstacles(state);
fillRewards(state);
updateAgentPosition(state);
}
static void executeSearch() {
PlCall("buscaOuro", NULL);
}
static void initializeWorld() {
PlCall("gerarMundoRandomico", NULL);
}
static void restartWorld() {
PlCall("reiniciarR", NULL);
}
static void removeAll() {
PlCall("removeTudo", NULL);
}
static void fillObstacles(WumpusState *state) {
PlTermv av(3);
PlQuery q("obstaculo", av);
int x, y;
char *obs;
Entity obstacle;
while (q.next_solution()) {
obs = av[2];
if (strcmp("abismo", obs) == 0) {
obstacle = ABISMO;
}
else if (strcmp("wumpus", obs) == 0) {
obstacle = WUMPUS;
}
else if (strcmp("morcego", obs) == 0) {
obstacle = MORCEGO;
}
x = (int)av[0] - 1;
y = (int)av[1] - 1;
state->grid[x][y][0] = obstacle;
}
}
static void fillRewards(WumpusState *state) {
PlTermv av(3);
PlQuery q("recompensa", av);
int x, y;
Entity reward = OURO;
while (q.next_solution()) {
x = (int) av[0] - 1;
y = (int) av[1] - 1;
state->grid[x][y][1] = reward;
}
}
static void updateAgentPosition(WumpusState *state) {
PlTermv av(2);
PlQuery q("posicao", av);
int x, y;
while (q.next_solution()) {
x = (int) av[0];
y = (int) av[1];
}
Point p;
p.x = x;
p.y = y;
state->agentPosition = p;
}
static int getScore() {
int score = 0;
PlTermv av(1);
PlQuery q("pontuacao", av);
while (q.next_solution()) {
score = (int) av[0];
}
return score;
}
static void getActions(vector<Action> &actions) {
PlTermv av(1);
PlQuery q("acao", av);
PlTerm actionsTerm(av[0]);
q.next_solution();
PlTail actionsArray(actionsTerm);
PlTerm actionTerm;
while (actionsArray.next(actionTerm)) { /* for each action */
PlTail actionArray(actionTerm);
PlTerm actionPart;
Action action;
Point p;
for (int i = 0; actionArray.next(actionPart); i++) {
switch (i) {
case 0:
p.x = (int) actionPart;
break;
case 1:
p.y = (int) actionPart;
break;
case 2:
action.actionType = getActionTypeFromString((char *) actionPart);
break;
}
}
action.location = p;
actions.push_back(action);
}
}
/* TODO */
static ActionType getActionTypeFromString(char * actionString) {
if (strcmp(actionString, "andar") == 0) {
return ANDAR;
}
if (strcmp(actionString, "atirar") == 0) {
return ATIRAR;
}
if (strcmp(actionString, "matarwumpus") == 0) {
return MATAR_WUMPUS;
}
if (strcmp(actionString, "matarmorcego") == 0) {
return MATAR_MORCEGO;
}
if (strcmp(actionString, "efeitoMorcego") == 0) {
return EFEITO_MORCEGO;
}
if (strcmp(actionString, "pegarOuro") == 0) {
return PEGAR_OURO;
}
}
static void updateStateWithAction(WumpusState *state, Action action) {
switch (action.actionType) {
case ANDAR:
state->score -= 1;
case EFEITO_MORCEGO:
state->agentPosition.x = action.location.x;
state->agentPosition.y = action.location.y;
break;
case ATIRAR:
state->score -= 10;
break;
case MATAR_WUMPUS:
state->grid[action.location.x - 1][action.location.y - 1][0] = VAZIO;
break;
case MATAR_MORCEGO:
state->grid[action.location.x - 1][action.location.y - 1][0] = VAZIO;
break;
case PEGAR_OURO:
state->grid[action.location.x - 1][action.location.y - 1][1] = VAZIO;
state->score += 1000;
break;
}
};
static void printWorld(WumpusState *state) {
for (int y = 0; y < WORLD_LEN; y++) {
for (int x = 0; x < WORLD_LEN; x++) {
int posx = state->agentPosition.x;
int posy = state->agentPosition.y;
if (x == posx - 1 && y == posy - 1) {
printColor("AG ", FOREGROUND_BLUE | FOREGROUND_RED);
continue;
}
char entityString[] = "XX ";
int color = 0;
switch (state->grid[x][y][0]) {
case ABISMO:
entityString[0] = 'A';
color = FOREGROUND_GREEN;
break;
case WUMPUS:
entityString[0] = 'W';
color = FOREGROUND_RED;
break;
case MORCEGO:
entityString[0] = 'M';
color = FOREGROUND_BLUE;
break;
default:
entityString[0] = 'X';
color = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN;
}
if (state->grid[x][y][1] == OURO) {
entityString[1] = 'O';
color = FOREGROUND_RED | FOREGROUND_GREEN;
}
printColor(entityString, color);
}
printf("\n");
}
printf("Score: %d", state->score);
printf("\n");
}
static void printColor(char *txt, int color) {
HANDLE console;
CONSOLE_SCREEN_BUFFER_INFO info;
console = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(console, &info);
SetConsoleTextAttribute(console, color);
printf("%s", txt);
SetConsoleTextAttribute(console, info.wAttributes);
}
|
Fix index problem with obstacle deletion
|
Fix index problem with obstacle deletion
|
C++
|
mit
|
hugogrochau/wumpus-world
|
23fbef9e447639febb8410e3d1f6ac5b13e93408
|
src/arch/arm/stacktrace.cc
|
src/arch/arm/stacktrace.cc
|
/*
* Copyright (c) 2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Nathan Binkert
*/
#include <string>
#include "arch/arm/isa_traits.hh"
#include "arch/arm/stacktrace.hh"
#include "arch/arm/vtophys.hh"
#include "base/bitfield.hh"
#include "base/trace.hh"
#include "cpu/base.hh"
#include "cpu/thread_context.hh"
#include "mem/fs_translating_port_proxy.hh"
#include "sim/system.hh"
using namespace std;
namespace ArmISA
{
ProcessInfo::ProcessInfo(ThreadContext *_tc)
: tc(_tc)
{
Addr addr = 0;
FSTranslatingPortProxy &vp = tc->getVirtProxy();
if (!tc->getSystemPtr()->kernelSymtab->findAddress("thread_info_size", addr))
panic("thread info not compiled into kernel\n");
thread_info_size = vp.readGtoH<int32_t>(addr);
if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_size", addr))
panic("thread info not compiled into kernel\n");
task_struct_size = vp.readGtoH<int32_t>(addr);
if (!tc->getSystemPtr()->kernelSymtab->findAddress("thread_info_task", addr))
panic("thread info not compiled into kernel\n");
task_off = vp.readGtoH<int32_t>(addr);
if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_pid", addr))
panic("thread info not compiled into kernel\n");
pid_off = vp.readGtoH<int32_t>(addr);
if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_comm", addr))
panic("thread info not compiled into kernel\n");
name_off = vp.readGtoH<int32_t>(addr);
}
Addr
ProcessInfo::task(Addr ksp) const
{
return 0;
}
int
ProcessInfo::pid(Addr ksp) const
{
return -1;
}
string
ProcessInfo::name(Addr ksp) const
{
return "Implement me";
}
StackTrace::StackTrace()
: tc(0), stack(64)
{
}
StackTrace::StackTrace(ThreadContext *_tc, StaticInstPtr inst)
: tc(0), stack(64)
{
trace(_tc, inst);
}
StackTrace::~StackTrace()
{
}
void
StackTrace::trace(ThreadContext *_tc, bool is_call)
{
}
bool
StackTrace::isEntry(Addr addr)
{
return false;
}
bool
StackTrace::decodeStack(MachInst inst, int &disp)
{
return false;
}
bool
StackTrace::decodeSave(MachInst inst, int ®, int &disp)
{
return false;
}
/*
* Decode the function prologue for the function we're in, and note
* which registers are stored where, and how large the stack frame is.
*/
bool
StackTrace::decodePrologue(Addr sp, Addr callpc, Addr func,
int &size, Addr &ra)
{
return false;
}
#if TRACING_ON
void
StackTrace::dump()
{
DPRINTFN("------ Stack ------\n");
DPRINTFN(" Not implemented\n");
}
#endif
}
|
/*
* Copyright (c) 2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Nathan Binkert
*/
#include <string>
#include "arch/arm/isa_traits.hh"
#include "arch/arm/stacktrace.hh"
#include "arch/arm/vtophys.hh"
#include "base/bitfield.hh"
#include "base/trace.hh"
#include "cpu/base.hh"
#include "cpu/thread_context.hh"
#include "mem/fs_translating_port_proxy.hh"
#include "sim/system.hh"
using namespace std;
namespace ArmISA
{
ProcessInfo::ProcessInfo(ThreadContext *_tc)
: tc(_tc)
{
Addr addr = 0;
FSTranslatingPortProxy &vp = tc->getVirtProxy();
if (!tc->getSystemPtr()->kernelSymtab->findAddress("thread_info_size", addr))
panic("thread info not compiled into kernel\n");
thread_info_size = vp.readGtoH<int32_t>(addr);
if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_size", addr))
panic("thread info not compiled into kernel\n");
task_struct_size = vp.readGtoH<int32_t>(addr);
if (!tc->getSystemPtr()->kernelSymtab->findAddress("thread_info_task", addr))
panic("thread info not compiled into kernel\n");
task_off = vp.readGtoH<int32_t>(addr);
if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_pid", addr))
panic("thread info not compiled into kernel\n");
pid_off = vp.readGtoH<int32_t>(addr);
if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_comm", addr))
panic("thread info not compiled into kernel\n");
name_off = vp.readGtoH<int32_t>(addr);
}
Addr
ProcessInfo::task(Addr ksp) const
{
Addr base = ksp & ~0x1fff;
if (base == ULL(0xffffffffc0000000))
return 0;
Addr tsk;
FSTranslatingPortProxy &vp = tc->getVirtProxy();
tsk = vp.readGtoH<Addr>(base + task_off);
return tsk;
}
int
ProcessInfo::pid(Addr ksp) const
{
Addr task = this->task(ksp);
if (!task)
return -1;
uint16_t pd;
FSTranslatingPortProxy &vp = tc->getVirtProxy();
pd = vp.readGtoH<uint16_t>(task + pid_off);
return pd;
}
string
ProcessInfo::name(Addr ksp) const
{
Addr task = this->task(ksp);
if (!task)
return "unknown";
char comm[256];
CopyStringOut(tc, comm, task + name_off, sizeof(comm));
if (!comm[0])
return "startup";
return comm;
}
StackTrace::StackTrace()
: tc(0), stack(64)
{
}
StackTrace::StackTrace(ThreadContext *_tc, StaticInstPtr inst)
: tc(0), stack(64)
{
trace(_tc, inst);
}
StackTrace::~StackTrace()
{
}
void
StackTrace::trace(ThreadContext *_tc, bool is_call)
{
}
bool
StackTrace::isEntry(Addr addr)
{
return false;
}
bool
StackTrace::decodeStack(MachInst inst, int &disp)
{
return false;
}
bool
StackTrace::decodeSave(MachInst inst, int ®, int &disp)
{
return false;
}
/*
* Decode the function prologue for the function we're in, and note
* which registers are stored where, and how large the stack frame is.
*/
bool
StackTrace::decodePrologue(Addr sp, Addr callpc, Addr func,
int &size, Addr &ra)
{
return false;
}
#if TRACING_ON
void
StackTrace::dump()
{
DPRINTFN("------ Stack ------\n");
DPRINTFN(" Not implemented\n");
}
#endif
}
|
implement the ProcessInfo methods
|
ARM: implement the ProcessInfo methods
|
C++
|
bsd-3-clause
|
andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin,andrewfu0325/gem5-aladdin
|
028fdf8371d7019332644a395f9006de6f340ee8
|
src/cauthtool.cc
|
src/cauthtool.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2009 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
using namespace std;
#include "config.h"
#include "common/ConfUtils.h"
#include "common/common_init.h"
#include "auth/Crypto.h"
#include "auth/Auth.h"
#include "auth/KeyRing.h"
void usage()
{
cout << " usage: [--create-keyring] [--gen-key] [--name=<name>] [--set-uid=uid] [--caps=<filename>] [--list] [--print-key] <filename>" << std::endl;
exit(1);
}
int main(int argc, const char **argv)
{
vector<const char*> args;
argv_to_vec(argc, argv, args);
env_to_vec(args);
DEFINE_CONF_VARS(usage);
common_set_defaults(false);
common_init(args, "cauthtool", false);
const char *me = argv[0];
const char *fn = 0;
bool gen_key = false;
bool gen_print_key = false;
const char *add_key = 0;
bool list = false;
bool print_key = false;
bool create_keyring = false;
const char *caps_fn = NULL;
const char *import_keyring = NULL;
bool set_auid = false;
uint64_t auid = CEPH_AUTH_UID_DEFAULT;
const char *name = g_conf.name;
FOR_EACH_ARG(args) {
if (CONF_ARG_EQ("gen-key", 'g')) {
CONF_SAFE_SET_ARG_VAL(&gen_key, OPT_BOOL);
} else if (CONF_ARG_EQ("gen-print-key", '\0')) {
CONF_SAFE_SET_ARG_VAL(&gen_print_key, OPT_BOOL);
} else if (CONF_ARG_EQ("add-key", 'a')) {
CONF_SAFE_SET_ARG_VAL(&add_key, OPT_STR);
} else if (CONF_ARG_EQ("list", 'l')) {
CONF_SAFE_SET_ARG_VAL(&list, OPT_BOOL);
} else if (CONF_ARG_EQ("caps", '\0')) {
CONF_SAFE_SET_ARG_VAL(&caps_fn, OPT_STR);
} else if (CONF_ARG_EQ("print-key", 'p')) {
CONF_SAFE_SET_ARG_VAL(&print_key, OPT_BOOL);
} else if (CONF_ARG_EQ("create-keyring", 'c')) {
CONF_SAFE_SET_ARG_VAL(&create_keyring, OPT_BOOL);
} else if (CONF_ARG_EQ("import-keyring", '\0')) {
CONF_SAFE_SET_ARG_VAL(&import_keyring, OPT_STR);
} else if (CONF_ARG_EQ("set-uid", 'u')) {
CONF_SAFE_SET_ARG_VAL(&auid, OPT_LONGLONG);
set_auid = true;
} else if (!fn) {
fn = args[i];
} else
usage();
}
if (!fn && !gen_print_key) {
cerr << me << ": must specify filename" << std::endl;
usage();
}
if (!(gen_key ||
gen_print_key ||
add_key ||
list ||
caps_fn ||
set_auid ||
print_key ||
create_keyring ||
import_keyring)) {
cerr << "no command specified" << std::endl;
usage();
}
if (gen_key && add_key) {
cerr << "can't both gen_key and add_key" << std::endl;
usage();
}
if (caps_fn || add_key || gen_key || print_key || set_auid) {
if (!name || !(*name)) {
cerr << "must specify entity name" << std::endl;
usage();
}
}
if (gen_print_key) {
CryptoKey key;
key.create(CEPH_CRYPTO_AES);
cout << key << std::endl;
return 0;
}
// keyring --------
bool modified = false;
KeyRing keyring;
string s = name;
EntityName ename;
if (name[0] && !ename.from_str(s)) {
cerr << "'" << s << "' is not a valid entity name" << std::endl;
exit(1);
}
bufferlist bl;
int r = 0;
if (create_keyring) {
cout << "creating " << fn << std::endl;
modified = true;
} else {
r = bl.read_file(fn, true);
if (r >= 0) {
try {
bufferlist::iterator iter = bl.begin();
::decode(keyring, iter);
} catch (buffer::error *err) {
cerr << "error reading file " << fn << std::endl;
exit(1);
}
} else {
cerr << "can't open " << fn << ": " << strerror(-r) << std::endl;
exit(1);
}
}
// write commands
if (import_keyring) {
KeyRing other;
bufferlist obl;
int r = obl.read_file(import_keyring);
if (r >= 0) {
try {
bufferlist::iterator iter = obl.begin();
::decode(other, iter);
} catch (buffer::error *err) {
cerr << "error reading file " << import_keyring << std::endl;
exit(1);
}
cout << "importing contents of " << import_keyring << " into " << fn << std::endl;
//other.print(cout);
keyring.import(other);
modified = true;
} else {
cerr << "can't open " << import_keyring << ": " << strerror(-r) << std::endl;
exit(1);
}
}
if (gen_key) {
EntityAuth eauth;
eauth.key.create(CEPH_CRYPTO_AES);
keyring.add(ename, eauth);
modified = true;
}
if (add_key) {
if (!name) {
cerr << "must specify a name to add a key" << std::endl;
exit(1);
}
EntityAuth eauth;
string ekey(add_key);
try {
eauth.key.decode_base64(ekey);
} catch (buffer::error *err) {
cerr << "can't decode key '" << add_key << "'" << std::endl;
exit(1);
}
keyring.add(ename, eauth);
modified = true;
cout << "added entity " << ename << " auth " << eauth << std::endl;
}
if (caps_fn) {
ConfFile *cf = new ConfFile(caps_fn);
if (!cf->parse()) {
cerr << "could not parse caps file " << caps_fn << std::endl;
exit(1);
}
map<string, bufferlist> caps;
const char *key_names[] = { "mon", "osd", "mds", NULL };
for (int i=0; key_names[i]; i++) {
char *val;
cf->read("global", key_names[i], &val, NULL);
if (val) {
bufferlist bl;
::encode(val, bl);
string s(key_names[i]);
caps[s] = bl;
free(val);
}
}
keyring.set_caps(ename, caps);
modified = true;
}
if (set_auid) {
if (!name) {
cerr << "must specify a name to set a uid" << std::endl;
exit(1);
}
keyring.set_uid(ename, auid);
modified = true;
}
// read commands
if (list) {
keyring.print(cout);
}
if (print_key) {
CryptoKey key;
if (keyring.get_secret(ename, key)) {
cout << key << std::endl;
} else {
cerr << "entity " << ename << " not found" << std::endl;
}
}
// write result?
if (modified) {
bufferlist bl;
::encode(keyring, bl);
r = bl.write_file(fn, 0600);
if (r < 0) {
cerr << "could not write " << fn << std::endl;
}
//cout << "wrote " << bl.length() << " bytes to " << fn << std::endl;
}
return 0;
}
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2009 Sage Weil <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
using namespace std;
#include "config.h"
#include "common/ConfUtils.h"
#include "common/common_init.h"
#include "auth/Crypto.h"
#include "auth/Auth.h"
#include "auth/KeyRing.h"
void usage()
{
cout << " usage: [--create-keyring] [--gen-key] [--name=<name>] [--set-uid=uid] [--caps=<filename>] [--list] [--print-key] <filename>" << std::endl;
exit(1);
}
int main(int argc, const char **argv)
{
vector<const char*> args;
argv_to_vec(argc, argv, args);
env_to_vec(args);
DEFINE_CONF_VARS(usage);
common_set_defaults(false);
common_init(args, "cauthtool", false);
const char *me = argv[0];
const char *fn = 0;
bool gen_key = false;
bool gen_print_key = false;
const char *add_key = 0;
bool list = false;
bool print_key = false;
bool create_keyring = false;
const char *caps_fn = NULL;
const char *import_keyring = NULL;
bool set_auid = false;
uint64_t auid = CEPH_AUTH_UID_DEFAULT;
const char *name = g_conf.name;
map<string,bufferlist> caps;
FOR_EACH_ARG(args) {
if (CONF_ARG_EQ("gen-key", 'g')) {
CONF_SAFE_SET_ARG_VAL(&gen_key, OPT_BOOL);
} else if (CONF_ARG_EQ("gen-print-key", '\0')) {
CONF_SAFE_SET_ARG_VAL(&gen_print_key, OPT_BOOL);
} else if (CONF_ARG_EQ("add-key", 'a')) {
CONF_SAFE_SET_ARG_VAL(&add_key, OPT_STR);
} else if (CONF_ARG_EQ("list", 'l')) {
CONF_SAFE_SET_ARG_VAL(&list, OPT_BOOL);
} else if (CONF_ARG_EQ("caps", '\0')) {
CONF_SAFE_SET_ARG_VAL(&caps_fn, OPT_STR);
} else if (CONF_ARG_EQ("cap", '\0')) {
const char *key, *val;
CONF_SAFE_SET_ARG_VAL(&key, OPT_STR);
CONF_SAFE_SET_ARG_VAL(&val, OPT_STR);
::encode(val, caps[key]);
} else if (CONF_ARG_EQ("print-key", 'p')) {
CONF_SAFE_SET_ARG_VAL(&print_key, OPT_BOOL);
} else if (CONF_ARG_EQ("create-keyring", 'c')) {
CONF_SAFE_SET_ARG_VAL(&create_keyring, OPT_BOOL);
} else if (CONF_ARG_EQ("import-keyring", '\0')) {
CONF_SAFE_SET_ARG_VAL(&import_keyring, OPT_STR);
} else if (CONF_ARG_EQ("set-uid", 'u')) {
CONF_SAFE_SET_ARG_VAL(&auid, OPT_LONGLONG);
set_auid = true;
} else if (!fn) {
fn = args[i];
} else
usage();
}
if (!fn && !gen_print_key) {
cerr << me << ": must specify filename" << std::endl;
usage();
}
if (!(gen_key ||
gen_print_key ||
add_key ||
list ||
caps_fn ||
caps.size() ||
set_auid ||
print_key ||
create_keyring ||
import_keyring)) {
cerr << "no command specified" << std::endl;
usage();
}
if (gen_key && add_key) {
cerr << "can't both gen_key and add_key" << std::endl;
usage();
}
if (caps_fn || caps.size() || add_key || gen_key || print_key || set_auid) {
if (!name || !(*name)) {
cerr << "must specify entity name" << std::endl;
usage();
}
}
if (gen_print_key) {
CryptoKey key;
key.create(CEPH_CRYPTO_AES);
cout << key << std::endl;
return 0;
}
// keyring --------
bool modified = false;
KeyRing keyring;
string s = name;
EntityName ename;
if (name[0] && !ename.from_str(s)) {
cerr << "'" << s << "' is not a valid entity name" << std::endl;
exit(1);
}
bufferlist bl;
int r = 0;
if (create_keyring) {
cout << "creating " << fn << std::endl;
modified = true;
} else {
r = bl.read_file(fn, true);
if (r >= 0) {
try {
bufferlist::iterator iter = bl.begin();
::decode(keyring, iter);
} catch (buffer::error *err) {
cerr << "error reading file " << fn << std::endl;
exit(1);
}
} else {
cerr << "can't open " << fn << ": " << strerror(-r) << std::endl;
exit(1);
}
}
// write commands
if (import_keyring) {
KeyRing other;
bufferlist obl;
int r = obl.read_file(import_keyring);
if (r >= 0) {
try {
bufferlist::iterator iter = obl.begin();
::decode(other, iter);
} catch (buffer::error *err) {
cerr << "error reading file " << import_keyring << std::endl;
exit(1);
}
cout << "importing contents of " << import_keyring << " into " << fn << std::endl;
//other.print(cout);
keyring.import(other);
modified = true;
} else {
cerr << "can't open " << import_keyring << ": " << strerror(-r) << std::endl;
exit(1);
}
}
if (gen_key) {
EntityAuth eauth;
eauth.key.create(CEPH_CRYPTO_AES);
keyring.add(ename, eauth);
modified = true;
}
if (add_key) {
if (!name) {
cerr << "must specify a name to add a key" << std::endl;
exit(1);
}
EntityAuth eauth;
string ekey(add_key);
try {
eauth.key.decode_base64(ekey);
} catch (buffer::error *err) {
cerr << "can't decode key '" << add_key << "'" << std::endl;
exit(1);
}
keyring.add(ename, eauth);
modified = true;
cout << "added entity " << ename << " auth " << eauth << std::endl;
}
if (caps_fn) {
ConfFile *cf = new ConfFile(caps_fn);
if (!cf->parse()) {
cerr << "could not parse caps file " << caps_fn << std::endl;
exit(1);
}
map<string, bufferlist> caps;
const char *key_names[] = { "mon", "osd", "mds", NULL };
for (int i=0; key_names[i]; i++) {
char *val;
cf->read("global", key_names[i], &val, NULL);
if (val) {
bufferlist bl;
::encode(val, bl);
string s(key_names[i]);
caps[s] = bl;
free(val);
}
}
keyring.set_caps(ename, caps);
modified = true;
}
if (caps.size()) {
keyring.set_caps(ename, caps);
modified = true;
}
if (set_auid) {
if (!name) {
cerr << "must specify a name to set a uid" << std::endl;
exit(1);
}
keyring.set_uid(ename, auid);
modified = true;
}
// read commands
if (list) {
keyring.print(cout);
}
if (print_key) {
CryptoKey key;
if (keyring.get_secret(ename, key)) {
cout << key << std::endl;
} else {
cerr << "entity " << ename << " not found" << std::endl;
}
}
// write result?
if (modified) {
bufferlist bl;
::encode(keyring, bl);
r = bl.write_file(fn, 0600);
if (r < 0) {
cerr << "could not write " << fn << std::endl;
}
//cout << "wrote " << bl.length() << " bytes to " << fn << std::endl;
}
return 0;
}
|
add simpler '--cap key val' syntax
|
cauthtool: add simpler '--cap key val' syntax
This lets you avoid creating a temp filename and doing '--caps filename'.
Instead, add each cap individually, like
--cap mon 'allow *' --cap mds 'allow' --cap osd 'allow rwx'
Signed-off-by: Sage Weil <[email protected]>
|
C++
|
lgpl-2.1
|
ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph
|
1f8fa4ef0533e0049a263fd1a29cf8ebd36ad321
|
graph/bron_kerbosch.cc
|
graph/bron_kerbosch.cc
|
// Copyright 2009 Google Inc. All Rights Reserved.
// Author: [email protected] (Laurent Perron)
#include <algorithm>
#include <vector>
#include "base/callback.h"
#include "base/util.h"
#include "graph/graph.h"
namespace operations_research {
namespace {
// TODO(user) : rewrite this algorithm without the recursivity.
void Search(ResultCallback2<bool, int, int>* const graph,
ResultCallback1<bool, const vector<int>&>* const callback,
int* input_candidates,
int input_size,
int input_candidate_size,
vector<int>* actual,
bool* stop) {
vector<int> actual_candidates(input_candidate_size);
int pre_increment = 0;
int pivot = 0;
int actual_candidate_size;
int actual_size;
int start = 0;
int index = input_candidate_size;
// Find Pivot.
for (int i = 0; i < input_candidate_size && index != 0; ++i) {
int p = input_candidates[i];
int count = 0;
int position = 0;
// Count disconnections.
for (int j = input_size; j < input_candidate_size && count < index; ++j) {
if (!graph->Run(p, input_candidates[j])) {
count++;
// Save position of potential candidate.
position = j;
}
}
// Test new minimum.
if (count < index) {
pivot = p;
index = count;
if (i < input_size) {
start = position;
} else {
start = i;
// pre increment obvious candidate.
pre_increment = 1;
}
}
}
// If fixed point initially chosen from candidates then
// number of diconnections will be preincreased by one
// Backtracking step for all nodes in the candidate list CD.
for (int nod = index + pre_increment; nod >= 1; nod--) {
// Swap.
int selected = input_candidates[start];
input_candidates[start] = input_candidates[input_size];
input_candidates[input_size] = selected;
// Fill new set "not".
actual_candidate_size = 0;
for (int i = 0; i < input_size; ++i) {
if (graph->Run(selected, input_candidates[i])) {
actual_candidates[actual_candidate_size++] = input_candidates[i];
}
}
// Fill new set "candidates".
actual_size = actual_candidate_size;
for (int i = input_size + 1; i < input_candidate_size; ++i) {
if (graph->Run(selected, input_candidates[i])) {
actual_candidates[actual_size++] = input_candidates[i];
}
}
// Add to "actual relevant nodes".
actual->push_back(selected);
// We have found a maximum clique.
if (actual_size == 0) {
*stop = callback->Run(*actual);
} else {
if (actual_candidate_size < actual_size) {
Search(graph, callback, actual_candidates.data(),
actual_candidate_size, actual_size, actual, stop);
if (*stop) {
return;
}
}
}
// move node from MD to ND
// Remove from compsub
actual->pop_back();
// Add to "nod"
input_size++;
if (nod > 1) {
// Select a candidate disgraph to the fixed point
start = input_size;
while (graph->Run(pivot, input_candidates[start])) {
start++;
}
}
// end selection
}
}
class FindAndEliminate {
public:
FindAndEliminate(ResultCallback2<bool, int, int>* const graph,
int node_count,
ResultCallback1<bool, const vector<int>&>* const callback)
: graph_(graph), node_count_(node_count), callback_(callback) {}
bool GraphCallback(int node1, int node2) {
if (visited_.find(make_pair(std::min(node1, node2),
std::max(node1, node2))) != visited_.end()) {
return false;
}
return graph_->Run(node1, node2);
}
bool SolutionCallback(const vector<int>& solution) {
const int size = solution.size();
if (size > 1) {
for (int i = 0; i < size - 1; ++i) {
for (int j = i + 1; j < size; ++j) {
visited_.insert(make_pair(std::min(solution[i], solution[j]),
std::max(solution[i], solution[j])));
}
}
callback_->Run(solution);
}
return false;
}
private:
ResultCallback2<bool, int, int>* const graph_;
int node_count_;
ResultCallback1<bool, const vector<int>&>* const callback_;
hash_set<pair<int, int> > visited_;
};
} // namespace
// This method implements the 'version2' of the Bron-Kerbosch
// algorithm to find all maximal cliques in a undirected graph.
void FindCliques(ResultCallback2<bool, int, int>* const graph,
int node_count,
ResultCallback1<bool, const vector<int>&>* const callback) {
graph->CheckIsRepeatable();
callback->CheckIsRepeatable();
scoped_array<int> initial_candidates(new int[node_count]);
vector<int> actual;
scoped_ptr<ResultCallback2<bool, int, int> > graph_deleter(graph);
scoped_ptr<ResultCallback1<bool, const vector<int>&> > callback_deleter(
callback);
for (int c = 0; c < node_count; ++c) {
initial_candidates[c] = c;
}
bool stop = false;
Search(graph, callback, initial_candidates.get(), 0, node_count, &actual,
&stop);
}
void CoverArcsByCliques(
ResultCallback2<bool, int, int>* const graph,
int node_count,
ResultCallback1<bool, const vector<int>&>* const callback) {
graph->CheckIsRepeatable();
callback->CheckIsRepeatable();
scoped_ptr<ResultCallback2<bool, int, int> > graph_deleter(graph);
scoped_ptr<ResultCallback1<bool, const vector<int>&> > callback_deleter(
callback);
FindAndEliminate cache(graph, node_count, callback);
scoped_array<int> initial_candidates(new int[node_count]);
vector<int> actual;
scoped_ptr<ResultCallback2<bool, int, int> > cached_graph(
NewPermanentCallback(&cache, &FindAndEliminate::GraphCallback));
scoped_ptr<ResultCallback1<bool, const vector<int>&> >cached_callback(
NewPermanentCallback(&cache, &FindAndEliminate::SolutionCallback));
for (int c = 0; c < node_count; ++c) {
initial_candidates[c] = c;
}
bool stop = false;
Search(cached_graph.get(), cached_callback.get(),
initial_candidates.get(), 0,
node_count, &actual, &stop);
}
} // namespace operations_research
|
// Copyright 2010 Google
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <vector>
#include "base/callback.h"
#include "base/util.h"
#include "graph/graph.h"
namespace operations_research {
namespace {
// TODO(user) : rewrite this algorithm without the recursivity.
void Search(ResultCallback2<bool, int, int>* const graph,
ResultCallback1<bool, const vector<int>&>* const callback,
int* input_candidates,
int input_size,
int input_candidate_size,
vector<int>* actual,
bool* stop) {
vector<int> actual_candidates(input_candidate_size);
int pre_increment = 0;
int pivot = 0;
int actual_candidate_size;
int actual_size;
int start = 0;
int index = input_candidate_size;
// Find Pivot.
for (int i = 0; i < input_candidate_size && index != 0; ++i) {
int p = input_candidates[i];
int count = 0;
int position = 0;
// Count disconnections.
for (int j = input_size; j < input_candidate_size && count < index; ++j) {
if (!graph->Run(p, input_candidates[j])) {
count++;
// Save position of potential candidate.
position = j;
}
}
// Test new minimum.
if (count < index) {
pivot = p;
index = count;
if (i < input_size) {
start = position;
} else {
start = i;
// pre increment obvious candidate.
pre_increment = 1;
}
}
}
// If fixed point initially chosen from candidates then
// number of diconnections will be preincreased by one
// Backtracking step for all nodes in the candidate list CD.
for (int nod = index + pre_increment; nod >= 1; nod--) {
// Swap.
int selected = input_candidates[start];
input_candidates[start] = input_candidates[input_size];
input_candidates[input_size] = selected;
// Fill new set "not".
actual_candidate_size = 0;
for (int i = 0; i < input_size; ++i) {
if (graph->Run(selected, input_candidates[i])) {
actual_candidates[actual_candidate_size++] = input_candidates[i];
}
}
// Fill new set "candidates".
actual_size = actual_candidate_size;
for (int i = input_size + 1; i < input_candidate_size; ++i) {
if (graph->Run(selected, input_candidates[i])) {
actual_candidates[actual_size++] = input_candidates[i];
}
}
// Add to "actual relevant nodes".
actual->push_back(selected);
// We have found a maximum clique.
if (actual_size == 0) {
*stop = callback->Run(*actual);
} else {
if (actual_candidate_size < actual_size) {
Search(graph, callback, actual_candidates.data(),
actual_candidate_size, actual_size, actual, stop);
if (*stop) {
return;
}
}
}
// move node from MD to ND
// Remove from compsub
actual->pop_back();
// Add to "nod"
input_size++;
if (nod > 1) {
// Select a candidate disgraph to the fixed point
start = input_size;
while (graph->Run(pivot, input_candidates[start])) {
start++;
}
}
// end selection
}
}
class FindAndEliminate {
public:
FindAndEliminate(ResultCallback2<bool, int, int>* const graph,
int node_count,
ResultCallback1<bool, const vector<int>&>* const callback)
: graph_(graph), node_count_(node_count), callback_(callback) {}
bool GraphCallback(int node1, int node2) {
if (visited_.find(make_pair(std::min(node1, node2),
std::max(node1, node2))) != visited_.end()) {
return false;
}
return graph_->Run(node1, node2);
}
bool SolutionCallback(const vector<int>& solution) {
const int size = solution.size();
if (size > 1) {
for (int i = 0; i < size - 1; ++i) {
for (int j = i + 1; j < size; ++j) {
visited_.insert(make_pair(std::min(solution[i], solution[j]),
std::max(solution[i], solution[j])));
}
}
callback_->Run(solution);
}
return false;
}
private:
ResultCallback2<bool, int, int>* const graph_;
int node_count_;
ResultCallback1<bool, const vector<int>&>* const callback_;
hash_set<pair<int, int> > visited_;
};
} // namespace
// This method implements the 'version2' of the Bron-Kerbosch
// algorithm to find all maximal cliques in a undirected graph.
void FindCliques(ResultCallback2<bool, int, int>* const graph,
int node_count,
ResultCallback1<bool, const vector<int>&>* const callback) {
graph->CheckIsRepeatable();
callback->CheckIsRepeatable();
scoped_array<int> initial_candidates(new int[node_count]);
vector<int> actual;
scoped_ptr<ResultCallback2<bool, int, int> > graph_deleter(graph);
scoped_ptr<ResultCallback1<bool, const vector<int>&> > callback_deleter(
callback);
for (int c = 0; c < node_count; ++c) {
initial_candidates[c] = c;
}
bool stop = false;
Search(graph, callback, initial_candidates.get(), 0, node_count, &actual,
&stop);
}
void CoverArcsByCliques(
ResultCallback2<bool, int, int>* const graph,
int node_count,
ResultCallback1<bool, const vector<int>&>* const callback) {
graph->CheckIsRepeatable();
callback->CheckIsRepeatable();
scoped_ptr<ResultCallback2<bool, int, int> > graph_deleter(graph);
scoped_ptr<ResultCallback1<bool, const vector<int>&> > callback_deleter(
callback);
FindAndEliminate cache(graph, node_count, callback);
scoped_array<int> initial_candidates(new int[node_count]);
vector<int> actual;
scoped_ptr<ResultCallback2<bool, int, int> > cached_graph(
NewPermanentCallback(&cache, &FindAndEliminate::GraphCallback));
scoped_ptr<ResultCallback1<bool, const vector<int>&> >cached_callback(
NewPermanentCallback(&cache, &FindAndEliminate::SolutionCallback));
for (int c = 0; c < node_count; ++c) {
initial_candidates[c] = c;
}
bool stop = false;
Search(cached_graph.get(), cached_callback.get(),
initial_candidates.get(), 0,
node_count, &actual, &stop);
}
} // namespace operations_research
|
fix license
|
fix license
|
C++
|
apache-2.0
|
hj3938/or-tools,AlperSaltabas/OR_Tools_Google_API,2947721120/curly-hockeypuck,2947721120/curly-hockeypuck,ThatRfernand/or-tools,ds0nt/or-tools,linsicai/or-tools,or-tools/or-tools,2947721120/or-tools,lfiaschi/or-tools,AlperSaltabas/OR_Tools_Google_API,KapecK/or-tools,ThatRfernand/or-tools,lfiaschi/or-tools,pbomta/or-tools,Faiz7412/or-tools,legrosbuffle/or-tools,WendellDuncan/or-tools,or-tools/or-tools,Faiz7412/or-tools,WendellDuncan/or-tools,or-tools/or-tools,AlperSaltabas/OR_Tools_Google_API,or-tools/or-tools,greatmazinger/or-tools,ds0nt/or-tools,capturePointer/or-tools,ds0nt/or-tools,zhxwmessi/or-tools,ds0nt/or-tools,legrosbuffle/or-tools,greatmazinger/or-tools,2947721120/curly-hockeypuck,zhxwmessi/or-tools,zhxwmessi/or-tools,capturePointer/or-tools,legrosbuffle/or-tools,ThatRfernand/or-tools,linsicai/or-tools,WendellDuncan/or-tools,simonlynen/or-tools,abhishekgahlot/or-tools,bourreauEric/or-tools,lfiaschi/or-tools,WendellDuncan/or-tools,zhxwmessi/or-tools,KapecK/or-tools,KapecK/or-tools,capturePointer/or-tools,zhxwmessi/or-tools,greatmazinger/or-tools,lfiaschi/or-tools,pombredanne/or-tools,pombredanne/or-tools,bourreauEric/or-tools,pombredanne/or-tools,hj3938/or-tools,2947721120/or-tools,tdegrunt/or-tools,AlperSaltabas/OR_Tools_Google_API,linsicai/or-tools,lfiaschi/or-tools,or-tools/or-tools,bourreauEric/or-tools,legrosbuffle/or-tools,greatmazinger/or-tools,WendellDuncan/or-tools,capturePointer/or-tools,FreeScienceCommunity/or-tools,2947721120/curly-hockeypuck,2947721120/curly-hockeypuck,pombredanne/or-tools,linsicai/or-tools,Faiz7412/or-tools,hj3938/or-tools,pbomta/or-tools,KapecK/or-tools,greatmazinger/or-tools,AlperSaltabas/OR_Tools_Google_API,tdegrunt/or-tools,Faiz7412/or-tools,FreeScienceCommunity/or-tools,2947721120/curly-hockeypuck,simonlynen/or-tools,2947721120/or-tools,hj3938/or-tools,FreeScienceCommunity/or-tools,linsicai/or-tools,pombredanne/or-tools,2947721120/or-tools,tdegrunt/or-tools,WendellDuncan/or-tools,2947721120/or-tools,pbomta/or-tools,capturePointer/or-tools,bourreauEric/or-tools,google/or-tools,2947721120/or-tools,AlperSaltabas/OR_Tools_Google_API,bourreauEric/or-tools,abhishekgahlot/or-tools,hj3938/or-tools,FreeScienceCommunity/or-tools,Faiz7412/or-tools,ds0nt/or-tools,hj3938/or-tools,lfiaschi/or-tools,pbomta/or-tools,capturePointer/or-tools,KapecK/or-tools,Faiz7412/or-tools,greatmazinger/or-tools,legrosbuffle/or-tools,or-tools/or-tools,simonlynen/or-tools,simonlynen/or-tools,google/or-tools,abhishekgahlot/or-tools,tdegrunt/or-tools,simonlynen/or-tools,pbomta/or-tools,ThatRfernand/or-tools,abhishekgahlot/or-tools,zhxwmessi/or-tools,abhishekgahlot/or-tools,KapecK/or-tools,ThatRfernand/or-tools,pbomta/or-tools,google/or-tools,pombredanne/or-tools,tdegrunt/or-tools,FreeScienceCommunity/or-tools,bourreauEric/or-tools,FreeScienceCommunity/or-tools,abhishekgahlot/or-tools,google/or-tools,simonlynen/or-tools,google/or-tools,ds0nt/or-tools,linsicai/or-tools,tdegrunt/or-tools,google/or-tools
|
afd226524dd3b32677c35c05e1bd6fb6c41c575b
|
src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/latch_wr_vref.C
|
src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/latch_wr_vref.C
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/latch_wr_vref.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 latch_wr_vref.C
/// @brief Latches WR VREF according to JEDEC spec
///
// *HWP HWP Owner: Stephen Glancy <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB Memory
#include <vector>
#include <fapi2.H>
#include <c_str.H>
#include <lib/dimm/ddr4/mrs_load_ddr4.H>
#include <lib/dimm/ddr4/latch_wr_vref.H>
#include <lib/dimm/rank.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_DIMM;
namespace mss
{
namespace ddr4
{
///
/// @brief Add latching commands for WR VREF to the instruction array - allows for custom MR06 data
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] i_mrs06, base MRS 06 allows the user to setup custom values and pass it in
/// @param[in] i_rank, rank on which to latch MRS 06
/// @param[in,out] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode add_latch_wr_vref_commands( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs06_data& i_mrs06,
const uint64_t& i_rank,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst)
{
// JEDEC has a 3 step latching process for WR VREF
// 1) enter into VREFDQ training mode, with the desired range value is XXXXXX
// 2) set the VREFDQ value while in training mode - this actually latches the value
// 3) exit VREFDQ training mode and go into normal operation mode
// Adds both VREFDQ train enables
// Note: this isn't general - assumes Nimbus via MCBIST instruction here BRS
auto l_mr_override = i_mrs06;
// Add both to the CCS program - JEDEC step 1
enable_vref_train_enable(l_mr_override);
FAPI_TRY( mrs_engine(i_target, l_mr_override, i_rank, mss::tvrefdqe(i_target), io_inst) );
// Add both to the CCS program - JEDEC step 2
FAPI_TRY( mrs_engine(i_target, l_mr_override, i_rank, mss::tvrefdqe(i_target), io_inst) );
// Hits VREFDQ train disable - putting the DRAM's back in mainline mode
// Add both to the CCS program - JEDEC step 3
disable_vref_train_enable(l_mr_override);
FAPI_TRY( mrs_engine(i_target, l_mr_override, i_rank, mss::tvrefdqe(i_target), io_inst) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Add latching commands for WR VREF to the instruction array
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_MCA>
/// @param[in] i_rank_pair, rank pair on which to latch MRS 06 - hits all ranks in the rank pair
/// @param[in] i_train_range, VREF range to setup
/// @param[in] i_train_value, VREF value to setup
/// @param[in,out] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode latch_wr_vref_commands_by_rank_pair( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const uint64_t& i_rank_pair,
const uint8_t& i_train_range,
const uint8_t& i_train_value)
{
// Declares variables
const auto l_mcbist = find_target<fapi2::TARGET_TYPE_MCBIST>(i_target);
// Warning: l_dimm is not a valid Target and will crash Cronus if used before it gets filled in by mss::rank::get_dimm_target_from_rank
fapi2::Target<fapi2::TARGET_TYPE_DIMM> l_dimm;
mss::ccs::program<fapi2::TARGET_TYPE_MCBIST, fapi2::TARGET_TYPE_MCA> l_program;
std::vector<uint64_t> l_ranks;
// Gets the ranks on which to latch the VREF's
FAPI_TRY(mss::rank::get_ranks_in_pair( i_target, i_rank_pair, l_ranks));
// Adds in latching commands for all ranks
for (const auto& l_rank : l_ranks)
{
// Skips this rank if no rank is configured
if (l_rank == NO_RANK)
{
continue;
}
// Ensures we get a valid DIMM target / rank combo
FAPI_TRY( mss::rank::get_dimm_target_from_rank(i_target, l_rank, l_dimm) );
// Adds the latching commands to the CCS program for this current rank
FAPI_TRY(setup_latch_wr_vref_commands_by_rank(l_dimm,
l_rank,
i_train_range,
i_train_value,
l_program.iv_instructions));
}
// Executes the CCS commands
FAPI_TRY( mss::ccs::execute(l_mcbist, l_program, i_target) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Add latching commands for WR VREF to the instruction array by a given rank
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_MCA>
/// @param[in] i_rank, rank on which to latch MRS 06 - hits all ranks in the rank pair
/// @param[in] i_train_range, VREF range to setup
/// @param[in] i_train_value, VREF value to setup
/// @param[in,out] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode setup_latch_wr_vref_commands_by_rank( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const uint64_t& i_rank,
const uint8_t& i_train_range,
const uint8_t& i_train_value,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst)
{
// Check to make sure our ctor worked ok
mrs06_data l_mrs06( i_target, fapi2::current_err );
FAPI_TRY( fapi2::current_err, "Unable to construct MRS06 data from attributes");
// Setup training range if the value is not the default
if(i_train_range != wr_vref_override::USE_DEFAULT_WR_VREF_SETTINGS)
{
FAPI_INF("%s Overriding vrefdq train %s data to be 0x%02x for rank %lu", mss::c_str(i_target), "range", i_train_value,
i_rank);
// Sets up the MR information
for(uint64_t i = 0; i < MAX_RANK_PER_DIMM; ++i)
{
l_mrs06.iv_vrefdq_train_range[i] = i_train_range;
}
}
// Setup training value if the value is not the default
if(i_train_value != wr_vref_override::USE_DEFAULT_WR_VREF_SETTINGS)
{
FAPI_INF("%s Overriding vrefdq train %s data to be 0x%02x for rank %lu", mss::c_str(i_target), "value", i_train_value,
i_rank);
// Sets up the MR information
for(uint64_t i = 0; i < MAX_RANK_PER_DIMM; ++i)
{
l_mrs06.iv_vrefdq_train_value[i] = i_train_value;
}
}
// Adds the latching commands
FAPI_TRY(add_latch_wr_vref_commands(i_target,
l_mrs06,
i_rank,
io_inst));
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace DDR4
} // close namespace mss
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/latch_wr_vref.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 latch_wr_vref.C
/// @brief Latches WR VREF according to JEDEC spec
///
// *HWP HWP Owner: Stephen Glancy <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB Memory
#include <vector>
#include <fapi2.H>
#include <generic/memory/lib/utils/c_str.H>
#include <lib/dimm/ddr4/mrs_load_ddr4.H>
#include <lib/dimm/ddr4/latch_wr_vref.H>
#include <lib/dimm/rank.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_DIMM;
namespace mss
{
namespace ddr4
{
///
/// @brief Add latching commands for WR VREF to the instruction array - allows for custom MR06 data
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] i_mrs06, base MRS 06 allows the user to setup custom values and pass it in
/// @param[in] i_rank, rank on which to latch MRS 06
/// @param[in,out] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode add_latch_wr_vref_commands( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs06_data& i_mrs06,
const uint64_t& i_rank,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst)
{
// JEDEC has a 3 step latching process for WR VREF
// 1) enter into VREFDQ training mode, with the desired range value is XXXXXX
// 2) set the VREFDQ value while in training mode - this actually latches the value
// 3) exit VREFDQ training mode and go into normal operation mode
// Adds both VREFDQ train enables
// Note: this isn't general - assumes Nimbus via MCBIST instruction here BRS
auto l_mr_override = i_mrs06;
// Add both to the CCS program - JEDEC step 1
enable_vref_train_enable(l_mr_override);
FAPI_TRY( mrs_engine(i_target, l_mr_override, i_rank, mss::tvrefdqe(i_target), io_inst) );
// Add both to the CCS program - JEDEC step 2
FAPI_TRY( mrs_engine(i_target, l_mr_override, i_rank, mss::tvrefdqe(i_target), io_inst) );
// Hits VREFDQ train disable - putting the DRAM's back in mainline mode
// Add both to the CCS program - JEDEC step 3
disable_vref_train_enable(l_mr_override);
FAPI_TRY( mrs_engine(i_target, l_mr_override, i_rank, mss::tvrefdqe(i_target), io_inst) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Add latching commands for WR VREF to the instruction array
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_MCA>
/// @param[in] i_rank_pair, rank pair on which to latch MRS 06 - hits all ranks in the rank pair
/// @param[in] i_train_range, VREF range to setup
/// @param[in] i_train_value, VREF value to setup
/// @param[in,out] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode latch_wr_vref_commands_by_rank_pair( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,
const uint64_t& i_rank_pair,
const uint8_t& i_train_range,
const uint8_t& i_train_value)
{
// Declares variables
const auto l_mcbist = find_target<fapi2::TARGET_TYPE_MCBIST>(i_target);
// Warning: l_dimm is not a valid Target and will crash Cronus if used before it gets filled in by mss::rank::get_dimm_target_from_rank
fapi2::Target<fapi2::TARGET_TYPE_DIMM> l_dimm;
mss::ccs::program<fapi2::TARGET_TYPE_MCBIST, fapi2::TARGET_TYPE_MCA> l_program;
std::vector<uint64_t> l_ranks;
// Gets the ranks on which to latch the VREF's
FAPI_TRY(mss::rank::get_ranks_in_pair( i_target, i_rank_pair, l_ranks));
// Adds in latching commands for all ranks
for (const auto& l_rank : l_ranks)
{
// Skips this rank if no rank is configured
if (l_rank == NO_RANK)
{
continue;
}
// Ensures we get a valid DIMM target / rank combo
FAPI_TRY( mss::rank::get_dimm_target_from_rank(i_target, l_rank, l_dimm) );
// Adds the latching commands to the CCS program for this current rank
FAPI_TRY(setup_latch_wr_vref_commands_by_rank(l_dimm,
l_rank,
i_train_range,
i_train_value,
l_program.iv_instructions));
}
// Executes the CCS commands
FAPI_TRY( mss::ccs::execute(l_mcbist, l_program, i_target) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Add latching commands for WR VREF to the instruction array by a given rank
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_MCA>
/// @param[in] i_rank, rank on which to latch MRS 06 - hits all ranks in the rank pair
/// @param[in] i_train_range, VREF range to setup
/// @param[in] i_train_value, VREF value to setup
/// @param[in,out] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
fapi2::ReturnCode setup_latch_wr_vref_commands_by_rank( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const uint64_t& i_rank,
const uint8_t& i_train_range,
const uint8_t& i_train_value,
std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst)
{
// Check to make sure our ctor worked ok
mrs06_data l_mrs06( i_target, fapi2::current_err );
FAPI_TRY( fapi2::current_err, "Unable to construct MRS06 data from attributes");
// Setup training range if the value is not the default
if(i_train_range != wr_vref_override::USE_DEFAULT_WR_VREF_SETTINGS)
{
FAPI_INF("%s Overriding vrefdq train %s data to be 0x%02x for rank %lu", mss::c_str(i_target), "range", i_train_value,
i_rank);
// Sets up the MR information
for(uint64_t i = 0; i < MAX_RANK_PER_DIMM; ++i)
{
l_mrs06.iv_vrefdq_train_range[i] = i_train_range;
}
}
// Setup training value if the value is not the default
if(i_train_value != wr_vref_override::USE_DEFAULT_WR_VREF_SETTINGS)
{
FAPI_INF("%s Overriding vrefdq train %s data to be 0x%02x for rank %lu", mss::c_str(i_target), "value", i_train_value,
i_rank);
// Sets up the MR information
for(uint64_t i = 0; i < MAX_RANK_PER_DIMM; ++i)
{
l_mrs06.iv_vrefdq_train_value[i] = i_train_value;
}
}
// Adds the latching commands
FAPI_TRY(add_latch_wr_vref_commands(i_target,
l_mrs06,
i_rank,
io_inst));
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace DDR4
} // close namespace mss
|
Add pos API to be shared among controllers, move generic files to utils
|
Add pos API to be shared among controllers, move generic files to utils
Change-Id: I960fa560d3c61191925b32e514c1202deaa8481f
Original-Change-Id: I7daedddf83c6a34f28417c97a28e78d88ec5c9af
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/37562
Tested-by: Jenkins Server <[email protected]>
Reviewed-by: Brian R. Silver <[email protected]>
Reviewed-by: STEPHEN GLANCY <[email protected]>
Reviewed-by: LUCAS W. MULKEY <[email protected]>
Reviewed-by: Louis Stermole <[email protected]>
Tested-by: Hostboot CI <[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
|
39da61b7a25b54d5d5b587867b41c2835a7c640e
|
src/compiler.cpp
|
src/compiler.cpp
|
/*
* Copyright (c) 2017, Rauli Laine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <plorth/context.hpp>
#include <plorth/value-word.hpp>
namespace plorth
{
namespace
{
class compiler
{
public:
explicit compiler(const unistring& source,
const unistring& filename,
int line,
int column)
: m_pos(std::begin(source))
, m_end(std::end(source))
{
m_position.filename = filename;
m_position.line = line;
m_position.column = column;
}
/**
* Returns true if there are no more characters to be read from the
* source code.
*/
inline bool eof() const
{
return m_pos >= m_end;
}
/**
* Advances to the next character in source code, discarding the current
* one.
*/
inline void advance()
{
read();
}
/**
* Advances to the next character in source code and returns the current
* one.
*/
inline unichar read()
{
const unichar result = *m_pos++;
if (result == '\n')
{
++m_position.line;
m_position.column = 1;
} else {
++m_position.column;
}
return result;
}
/**
* Returns next character to be read from the source code without
* advancing any further.
*/
inline unichar peek() const
{
return *m_pos;
}
/**
* Returns true if next character to be read from the source code equals
* with one given as argument.
*/
inline bool peek(unichar expected) const
{
return !eof() && peek() == expected;
}
/**
* Returns true if next character to be read from the source code matches
* with given callback function.
*/
inline bool peek(bool (*callback)(unichar)) const
{
return !eof() && callback(peek());
}
/**
* Returns true and advances to next character if next character to be
* read from the source code equals with one given as argument.
*/
inline bool peek_read(unichar expected)
{
if (peek(expected))
{
advance();
return true;
}
return false;
}
/**
* Returns true and advances to next character if next character to be
* read from the source code equals with one given as argument. Current
* character will be stored into given slot.
*/
inline bool peek_read(unichar expected, unichar& slot)
{
if (peek(expected))
{
slot = read();
return true;
}
return false;
}
/**
* Compiles top-level script into quote.
*/
ref<quote> compile(context* ctx)
{
std::vector<ref<class value>> values;
ref<class value> value;
while (!eof())
{
if (skip_whitespace())
{
break;
}
else if (!(value = compile_value(ctx)))
{
return ref<quote>();
}
values.push_back(value);
}
return ctx->runtime()->compiled_quote(values);
}
ref<value> compile_value(context* ctx)
{
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing value.",
&m_position
);
return ref<value>();
}
switch (peek())
{
case '"':
case '\'':
return compile_string(ctx);
case '(':
return compile_quote(ctx);
case '[':
return compile_array(ctx);
case '{':
return compile_object(ctx);
case ':':
return compile_word(ctx);
default:
return compile_symbol(ctx);
}
}
ref<symbol> compile_symbol(context* ctx)
{
struct position position;
unistring buffer;
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing symbol.",
&m_position
);
return ref<symbol>();
}
position = m_position;
if (!unichar_isword(peek()))
{
ctx->error(
error::code_syntax,
U"Unexpected input; Missing symbol.",
&m_position
);
return ref<symbol>();
}
buffer.append(1, read());
while (peek(unichar_isword))
{
buffer.append(1, read());
}
return ctx->runtime()->symbol(buffer, &position);
}
ref<word> compile_word(context* ctx)
{
struct position position;
const auto& runtime = ctx->runtime();
ref<class symbol> symbol;
std::vector<ref<value>> values;
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing word.",
&m_position
);
return ref<word>();
}
position = m_position;
if (!peek_read(':'))
{
ctx->error(
error::code_syntax,
U"Unexpected input; Missing word.",
&position
);
return ref<word>();
}
if (!(symbol = compile_symbol(ctx)))
{
return ref<word>();
}
for (;;)
{
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unterminated word; Missing `;'.",
&position
);
return ref<word>();
}
else if (peek_read(';'))
{
break;
} else {
const auto value = compile_value(ctx);
if (!value)
{
return ref<word>();
}
values.push_back(value);
}
}
return runtime->value<word>(
symbol,
runtime->compiled_quote(values)
);
}
ref<quote> compile_quote(context* ctx)
{
struct position position;
std::vector<ref<value>> values;
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing quote.",
&m_position
);
return ref<quote>();
}
position = m_position;
if (!peek_read('('))
{
ctx->error(
error::code_syntax,
U"Unexpected input; Missing quote.",
&position
);
return ref<quote>();
}
for (;;)
{
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unterminated quote; Missing `)'.",
&position
);
return ref<quote>();
}
else if (peek_read(')'))
{
break;
} else {
const auto value = compile_value(ctx);
if (!value)
{
return ref<quote>();
}
values.push_back(value);
}
}
return ctx->runtime()->compiled_quote(values);
}
ref<string> compile_string(context* ctx)
{
struct position position;
unichar separator;
unistring buffer;
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing string.",
&m_position
);
return ref<string>();
}
position = m_position;
if (!peek_read('"', separator) && !peek_read('\'', separator))
{
ctx->error(
error::code_syntax,
U"Unexpected input; Missing string.",
&position
);
return ref<string>();
}
for (;;)
{
if (eof())
{
ctx->error(
error::code_syntax,
unistring(U"Unterminated string; Missing `") + separator + U"'",
&position
);
return ref<string>();
}
else if (peek_read(separator))
{
break;
}
else if (peek_read('\\'))
{
if (!compile_escape_sequence(ctx, buffer))
{
return ref<string>();
}
} else {
buffer.append(1, read());
}
}
return ctx->runtime()->string(buffer);
}
ref<array> compile_array(context* ctx)
{
struct position position;
std::vector<ref<value>> elements;
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing array.",
&m_position
);
return ref<array>();
}
position = m_position;
if (!peek_read('['))
{
ctx->error(
error::code_syntax,
U"Unexpected input; Missing array.",
&position
);
return ref<array>();
}
for (;;)
{
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unterminated array; Missing `]'.",
&position
);
return ref<array>();
}
else if (peek_read(']'))
{
break;
} else {
const auto value = compile_value(ctx);
if (!value)
{
return ref<array>();
}
elements.push_back(value);
if (skip_whitespace() || (!peek(',') && !peek(']')))
{
ctx->error(
error::code_syntax,
U"Unterminated array; Missing `]'.",
&position
);
return ref<array>();
} else {
peek_read(',');
}
}
}
return ctx->runtime()->array(elements.data(), elements.size());
}
ref<object> compile_object(context* ctx)
{
struct position position;
object::container_type properties;
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing object.",
&m_position
);
return ref<object>();
}
position = m_position;
if (!peek_read('{'))
{
ctx->error(
error::code_syntax,
U"Unexpected input; Missing object.",
&position
);
return ref<object>();
}
for (;;)
{
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unterminated object; Missing `}'.",
&position
);
return ref<object>();
}
else if (peek_read('}'))
{
break;
} else {
ref<string> key;
ref<class value> value;
if (!(key = compile_string(ctx)))
{
return ref<object>();
}
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unterminated object; Missing `}'.",
&position
);
return ref<object>();
}
if (!peek_read(':'))
{
ctx->error(
error::code_syntax,
U"Missing `:' after property key.",
&m_position
);
return ref<object>();
}
if (!(value = compile_value(ctx)))
{
return ref<object>();
}
properties[key->to_string()] = value;
if (skip_whitespace() || (!peek(',') && !peek('}')))
{
ctx->error(
error::code_syntax,
U"Unterminated object; Missing `}'.",
&position
);
return ref<object>();
} else {
peek_read(',');
}
}
}
return ctx->runtime()->value<object>(properties);
}
bool compile_escape_sequence(context* ctx, unistring& buffer)
{
struct position position;
if (eof())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing escape sequence.",
&m_position
);
return false;
}
position = m_position;
switch (read())
{
case 'b':
buffer.append(1, 010);
break;
case 't':
buffer.append(1, 011);
break;
case 'n':
buffer.append(1, 012);
break;
case 'f':
buffer.append(1, 014);
break;
case 'r':
buffer.append(1, 015);
break;
case '"':
case '\'':
case '\\':
case '/':
buffer.append(1, *(m_pos - 1));
break;
case 'u':
{
unichar result = 0;
for (int i = 0; i < 4; ++i)
{
if (eof())
{
ctx->error(
error::code_syntax,
U"Unterminated escape sequence.",
&position
);
return false;
}
else if (!std::isxdigit(peek()))
{
ctx->error(
error::code_syntax,
U"Illegal Unicode hex escape sequence.",
&position
);
return false;
}
if (peek() >= 'A' && peek() <= 'F')
{
result = result * 16 + (read() - 'A' + 10);
}
else if (peek() >= 'a' && peek() <= 'f')
{
result = result * 16 + (read() - 'a' + 10);
} else {
result = result * 16 + (read() - '0');
}
}
if (!unichar_validate(result))
{
ctx->error(
error::code_syntax,
U"Illegal Unicode hex escape sequence.",
&position
);
return false;
}
buffer.append(1, result);
}
break;
default:
ctx->error(
error::code_syntax,
U"Illegal escape sequence in string literal.",
&position
);
return false;
}
return true;
}
/**
* Skips whitespace and comments from source code.
*
* \return True if end of input has been reached, false otherwise.
*/
bool skip_whitespace()
{
while (!eof())
{
// Skip line comments.
if (peek_read('#'))
{
while (!eof())
{
if (peek_read('\n') || peek_read('\r'))
{
break;
}
}
}
else if (!std::isspace(peek()))
{
return false;
} else {
advance();
}
}
return true;
}
compiler(const compiler&) = delete;
void operator=(const compiler&) = delete;
private:
/** Current position in source code. */
unistring::const_iterator m_pos;
/** Iterator which marks end of the source code. */
const unistring::const_iterator m_end;
/** Current source code location information. */
position m_position;
};
}
ref<quote> context::compile(const unistring& source,
const unistring& filename,
int line,
int column)
{
return compiler(source, filename, line, column).compile(this);
}
}
|
/*
* Copyright (c) 2017, Rauli Laine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <plorth/context.hpp>
#include <plorth/value-word.hpp>
namespace plorth
{
namespace
{
class compiler
{
public:
explicit compiler(const unistring& source,
const unistring& filename,
int line,
int column)
: m_pos(std::begin(source))
, m_end(std::end(source))
{
m_position.filename = filename;
m_position.line = line;
m_position.column = column;
}
/**
* Returns true if there are no more characters to be read from the
* source code.
*/
inline bool eof() const
{
return m_pos >= m_end;
}
/**
* Advances to the next character in source code, discarding the current
* one.
*/
inline void advance()
{
read();
}
/**
* Advances to the next character in source code and returns the current
* one.
*/
inline unichar read()
{
const unichar result = *m_pos++;
if (result == '\n')
{
++m_position.line;
m_position.column = 1;
} else {
++m_position.column;
}
return result;
}
/**
* Returns next character to be read from the source code without
* advancing any further.
*/
inline unichar peek() const
{
return *m_pos;
}
/**
* Returns true if next character to be read from the source code equals
* with one given as argument.
*/
inline bool peek(unichar expected) const
{
return !eof() && peek() == expected;
}
/**
* Returns true if next character to be read from the source code matches
* with given callback function.
*/
inline bool peek(bool (*callback)(unichar)) const
{
return !eof() && callback(peek());
}
/**
* Returns true and advances to next character if next character to be
* read from the source code equals with one given as argument.
*/
inline bool peek_read(unichar expected)
{
if (peek(expected))
{
advance();
return true;
}
return false;
}
/**
* Returns true and advances to next character if next character to be
* read from the source code equals with one given as argument. Current
* character will be stored into given slot.
*/
inline bool peek_read(unichar expected, unichar& slot)
{
if (peek(expected))
{
slot = read();
return true;
}
return false;
}
/**
* Compiles top-level script into quote.
*/
ref<quote> compile(context* ctx)
{
std::vector<ref<class value>> values;
ref<class value> value;
while (!eof())
{
if (skip_whitespace())
{
break;
}
else if (!(value = compile_value(ctx)))
{
return ref<quote>();
}
values.push_back(value);
}
return ctx->runtime()->compiled_quote(values);
}
ref<value> compile_value(context* ctx)
{
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing value.",
&m_position
);
return ref<value>();
}
switch (peek())
{
case '"':
case '\'':
return compile_string(ctx);
case '(':
return compile_quote(ctx);
case '[':
return compile_array(ctx);
case '{':
return compile_object(ctx);
case ':':
return compile_word(ctx);
default:
return compile_symbol(ctx);
}
}
ref<symbol> compile_symbol(context* ctx)
{
struct position position;
unistring buffer;
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing symbol.",
&m_position
);
return ref<symbol>();
}
position = m_position;
if (!unichar_isword(peek()))
{
ctx->error(
error::code_syntax,
U"Unexpected input; Missing symbol.",
&m_position
);
return ref<symbol>();
}
buffer.append(1, read());
while (peek(unichar_isword))
{
buffer.append(1, read());
}
return ctx->runtime()->symbol(buffer, &position);
}
ref<word> compile_word(context* ctx)
{
struct position position;
const auto& runtime = ctx->runtime();
ref<class symbol> symbol;
std::vector<ref<value>> values;
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing word.",
&m_position
);
return ref<word>();
}
position = m_position;
if (!peek_read(':'))
{
ctx->error(
error::code_syntax,
U"Unexpected input; Missing word.",
&position
);
return ref<word>();
}
if (!(symbol = compile_symbol(ctx)))
{
return ref<word>();
}
for (;;)
{
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unterminated word; Missing `;'.",
&position
);
return ref<word>();
}
else if (peek_read(';'))
{
break;
} else {
const auto value = compile_value(ctx);
if (!value)
{
return ref<word>();
}
values.push_back(value);
}
}
return runtime->value<word>(
symbol,
runtime->compiled_quote(values)
);
}
ref<quote> compile_quote(context* ctx)
{
struct position position;
std::vector<ref<value>> values;
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing quote.",
&m_position
);
return ref<quote>();
}
position = m_position;
if (!peek_read('('))
{
ctx->error(
error::code_syntax,
U"Unexpected input; Missing quote.",
&position
);
return ref<quote>();
}
for (;;)
{
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unterminated quote; Missing `)'.",
&position
);
return ref<quote>();
}
else if (peek_read(')'))
{
break;
} else {
const auto value = compile_value(ctx);
if (!value)
{
return ref<quote>();
}
values.push_back(value);
}
}
return ctx->runtime()->compiled_quote(values);
}
ref<string> compile_string(context* ctx)
{
struct position position;
unichar separator;
unistring buffer;
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing string.",
&m_position
);
return ref<string>();
}
position = m_position;
if (!peek_read('"', separator) && !peek_read('\'', separator))
{
ctx->error(
error::code_syntax,
U"Unexpected input; Missing string.",
&position
);
return ref<string>();
}
for (;;)
{
if (eof())
{
ctx->error(
error::code_syntax,
unistring(U"Unterminated string; Missing `") + separator + U"'",
&position
);
return ref<string>();
}
else if (peek_read(separator))
{
break;
}
else if (peek_read('\\'))
{
if (!compile_escape_sequence(ctx, buffer))
{
return ref<string>();
}
} else {
buffer.append(1, read());
}
}
return ctx->runtime()->string(buffer);
}
ref<array> compile_array(context* ctx)
{
struct position position;
std::vector<ref<value>> elements;
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing array.",
&m_position
);
return ref<array>();
}
position = m_position;
if (!peek_read('['))
{
ctx->error(
error::code_syntax,
U"Unexpected input; Missing array.",
&position
);
return ref<array>();
}
for (;;)
{
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unterminated array; Missing `]'.",
&position
);
return ref<array>();
}
else if (peek_read(']'))
{
break;
} else {
const auto value = compile_value(ctx);
if (!value)
{
return ref<array>();
}
elements.push_back(value);
if (skip_whitespace() || (!peek(',') && !peek(']')))
{
ctx->error(
error::code_syntax,
U"Unterminated array; Missing `]'.",
&position
);
return ref<array>();
} else {
peek_read(',');
}
}
}
return ctx->runtime()->array(elements.data(), elements.size());
}
ref<object> compile_object(context* ctx)
{
struct position position;
object::container_type properties;
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing object.",
&m_position
);
return ref<object>();
}
position = m_position;
if (!peek_read('{'))
{
ctx->error(
error::code_syntax,
U"Unexpected input; Missing object.",
&position
);
return ref<object>();
}
for (;;)
{
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unterminated object; Missing `}'.",
&position
);
return ref<object>();
}
else if (peek_read('}'))
{
break;
} else {
ref<string> key;
ref<class value> value;
if (!(key = compile_string(ctx)))
{
return ref<object>();
}
if (skip_whitespace())
{
ctx->error(
error::code_syntax,
U"Unterminated object; Missing `}'.",
&position
);
return ref<object>();
}
if (!peek_read(':'))
{
ctx->error(
error::code_syntax,
U"Missing `:' after property key.",
&m_position
);
return ref<object>();
}
if (!(value = compile_value(ctx)))
{
return ref<object>();
}
properties[key->to_string()] = value;
if (skip_whitespace() || (!peek(',') && !peek('}')))
{
ctx->error(
error::code_syntax,
U"Unterminated object; Missing `}'.",
&position
);
return ref<object>();
} else {
peek_read(',');
}
}
}
return ctx->runtime()->value<object>(properties);
}
bool compile_escape_sequence(context* ctx, unistring& buffer)
{
struct position position;
if (eof())
{
ctx->error(
error::code_syntax,
U"Unexpected end of input; Missing escape sequence.",
&m_position
);
return false;
}
position = m_position;
switch (read())
{
case 'b':
buffer.append(1, 010);
break;
case 't':
buffer.append(1, 011);
break;
case 'n':
buffer.append(1, 012);
break;
case 'f':
buffer.append(1, 014);
break;
case 'r':
buffer.append(1, 015);
break;
case '"':
case '\'':
case '\\':
case '/':
buffer.append(1, *(m_pos - 1));
break;
case 'u':
{
unichar result = 0;
for (int i = 0; i < 4; ++i)
{
if (eof())
{
ctx->error(
error::code_syntax,
U"Unterminated escape sequence.",
&position
);
return false;
}
else if (!std::isxdigit(peek()))
{
ctx->error(
error::code_syntax,
U"Illegal Unicode hex escape sequence.",
&position
);
return false;
}
if (peek() >= 'A' && peek() <= 'F')
{
result = result * 16 + (read() - 'A' + 10);
}
else if (peek() >= 'a' && peek() <= 'f')
{
result = result * 16 + (read() - 'a' + 10);
} else {
result = result * 16 + (read() - '0');
}
}
if (!unichar_validate(result))
{
ctx->error(
error::code_syntax,
U"Illegal Unicode hex escape sequence.",
&position
);
return false;
}
buffer.append(1, result);
}
break;
default:
ctx->error(
error::code_syntax,
U"Illegal escape sequence in string literal.",
&position
);
return false;
}
return true;
}
/**
* Skips whitespace and comments from source code.
*
* \return True if end of input has been reached, false otherwise.
*/
bool skip_whitespace()
{
while (!eof())
{
// Skip line comments.
if (peek_read('#'))
{
while (!eof())
{
if (peek_read('\n') || peek_read('\r'))
{
break;
} else {
advance();
}
}
}
else if (!std::isspace(peek()))
{
return false;
} else {
advance();
}
}
return true;
}
compiler(const compiler&) = delete;
void operator=(const compiler&) = delete;
private:
/** Current position in source code. */
unistring::const_iterator m_pos;
/** Iterator which marks end of the source code. */
const unistring::const_iterator m_end;
/** Current source code location information. */
position m_position;
};
}
ref<quote> context::compile(const unistring& source,
const unistring& filename,
int line,
int column)
{
return compiler(source, filename, line, column).compile(this);
}
}
|
Fix infinite loop in comment parsing
|
Fix infinite loop in comment parsing
If line comment does not end with line terminator, parsing such comment
will currently result in infinite loops. I really need to write parser
tests soon.
|
C++
|
unknown
|
RauliL/plorth,RauliL/plorth,RauliL/plorth,RauliL/plorth,peelonet/plorth
|
fbc21b4d284c2c30d7ec6e6a830467430df7df0d
|
Brain.cpp
|
Brain.cpp
|
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/foreach.hpp>
#include <cfloat>
#include <map>
#include "Brain.h"
#define TEMP_HYSTERESIS 0.5
Brain::Brain(MHEDatabase *db, MHEHardDevContainer *hardDevContainer, int refreshInSeconds, MHEMobileNotify *notify)
: _db(db), _hardDevContainer(hardDevContainer), _notify(notify), _refreshInSeconds(refreshInSeconds), _timer(_io), _signals(_io)
{
_log = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("MHEDatabase"));
_signals.add(SIGINT);
_signals.add(SIGTERM);
#if defined(SIGQUIT)
_signals.add(SIGQUIT);
#endif //SIGQUIT
_signals.async_wait(boost::bind(&Brain::stop, this));
}
Brain::~Brain()
{
_timer.cancel();
_io.stop();
}
void Brain::start()
{
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain start..."));
computeNextLaunch();
_io.run();
}
void Brain::stop()
{
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain stop..."));
_io.stop();
}
void Brain::computeNextLaunch()
{
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
long currentMS = now.time_of_day().minutes() * 60L + now.time_of_day().seconds();
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain::computeNextLaunch - currentTime=" << to_simple_string(now.time_of_day())));
currentMS = _refreshInSeconds - (currentMS % _refreshInSeconds);
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain::computeNextLaunch - waiting=" << currentMS));
_timer.expires_from_now(boost::posix_time::seconds(currentMS));
_timer.async_wait(boost::bind(&Brain::launch, this));
}
void Brain::launch()
{
std::vector<DBRoomGraphCond> roomGraphConds = _db->getRoomGraphCondByActiveDaysAndCalendar();
std::vector<DBCondition> conditions = _db->getConditions();
std::vector<DBGraph> graphs = _db->getGraphs();
std::vector<DBRoom> rooms = _db->getRooms();
std::map<int,DBRoomGraphCond> graphByRoomId;
std::map<int,DBCondition> conditionById;
std::map<int,DBGraph> graphById;
std::map<int,DBRoom> roomById;
std::pair<int, DBRoomGraphCond> kv;
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain::launch - run..."));
BOOST_FOREACH(DBCondition &cond, conditions)
{
conditionById[cond.id] = cond;
}
BOOST_FOREACH(DBGraph &graph, graphs)
{
graphById[graph.id] = graph;
}
BOOST_FOREACH(DBRoom &room, rooms)
{
roomById[room.id] = room;
}
BOOST_FOREACH(DBRoomGraphCond &rgc, roomGraphConds)
{
DBCondition condition = conditionById[rgc.conditionId];
if (condition.deviceId != -1 && (condition.temperatureMin > FLT_MIN || condition.temperatureMax < FLT_MAX))
{
MHEDevice *dev = _hardDevContainer->getDeviceById(condition.deviceId);
if (dev != NULL)
{
float deviceTemperature = dev->getTemperature();
if (condition.temperatureMin <= deviceTemperature && deviceTemperature <= condition.temperatureMax)
graphByRoomId[rgc.roomId] = rgc;
}
}
else
graphByRoomId[rgc.roomId] = rgc;
}
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
BOOST_FOREACH(kv, graphByRoomId)
{
DBCondition condition = conditionById[kv.second.conditionId];
DBGraph graph = graphById[kv.second.graphId];
DBRoom room = roomById[kv.second.roomId];
MHEDevice *devIn = _hardDevContainer->getDeviceById(room.deviceTemperatureId);
MHEDevice *devHeater = _hardDevContainer->getDeviceById(room.deviceHeaterId);
MHEDevice *devHeating = _hardDevContainer->getDeviceById(room.deviceHeatingId);
long currentHHMM = now.time_of_day().hours() * 100L + now.time_of_day().minutes();
float temperatureOrder = NAN;
BOOST_FOREACH(DBGraphData data, graph.data)
if (currentHHMM >= data.time)
temperatureOrder = data.value;
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain::launch - room=" << (std::string)room << " condition=" << (std::string)condition));
if (isnan(temperatureOrder))
LOG4CPLUS_ERROR(_log, LOG4CPLUS_TEXT("Brain::launch - no graph data found !!! currentHHMM=" << currentHHMM));
else
{
if (_notify != NULL)
{
int lastConditionId = _lastConditionIdByRoomId[room.id];
if (lastConditionId > 0 && lastConditionId != condition.id)
{
_notify->notifyDevices(conditionLeave, conditionById[lastConditionId]);
_notify->notifyDevices(conditionEnter, condition);
}
}
_lastConditionIdByRoomId[room.id] = condition.id;
if (devHeating != NULL)
{
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain::launch - set heating temperature to: " << temperatureOrder));
devHeating->setTempHum(temperatureOrder, devHeating->getHumidity());
}
if (devHeater != NULL)
{
float temperatureMeasured = devIn->getTemperature();
if (temperatureMeasured <= (temperatureOrder - TEMP_HYSTERESIS))
{
if (_notify != NULL && !devHeater->isActivated())
_notify->notifyDevices(conditionEnter, *devHeater);
devHeater->setStatus(true);
}
else if (temperatureMeasured >= (temperatureOrder + TEMP_HYSTERESIS))
{
if (_notify != NULL && devHeater->isActivated())
_notify->notifyDevices(conditionLeave, *devHeater);
devHeater->setStatus(false);
}
}
else
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain::launch - no heater to control"));
}
}
computeNextLaunch();
}
|
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/foreach.hpp>
#include <cfloat>
#include <map>
#include "Brain.h"
#define TEMP_HYSTERESIS 0.5
Brain::Brain(MHEDatabase *db, MHEHardDevContainer *hardDevContainer, int refreshInSeconds, MHEMobileNotify *notify)
: _db(db), _hardDevContainer(hardDevContainer), _notify(notify), _refreshInSeconds(refreshInSeconds), _timer(_io), _signals(_io)
{
_log = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("Brain"));
_signals.add(SIGINT);
_signals.add(SIGTERM);
#if defined(SIGQUIT)
_signals.add(SIGQUIT);
#endif //SIGQUIT
_signals.async_wait(boost::bind(&Brain::stop, this));
}
Brain::~Brain()
{
_timer.cancel();
_io.stop();
}
void Brain::start()
{
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain start..."));
computeNextLaunch();
_io.run();
}
void Brain::stop()
{
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain stop..."));
_io.stop();
}
void Brain::computeNextLaunch()
{
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
long currentMS = now.time_of_day().minutes() * 60L + now.time_of_day().seconds();
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain::computeNextLaunch - currentTime=" << to_simple_string(now.time_of_day())));
currentMS = _refreshInSeconds - (currentMS % _refreshInSeconds);
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain::computeNextLaunch - waiting=" << currentMS));
_timer.expires_from_now(boost::posix_time::seconds(currentMS));
_timer.async_wait(boost::bind(&Brain::launch, this));
}
void Brain::launch()
{
std::vector<DBRoomGraphCond> roomGraphConds = _db->getRoomGraphCondByActiveDaysAndCalendar();
std::vector<DBCondition> conditions = _db->getConditions();
std::vector<DBGraph> graphs = _db->getGraphs();
std::vector<DBRoom> rooms = _db->getRooms();
std::map<int,DBRoomGraphCond> graphByRoomId;
std::map<int,DBCondition> conditionById;
std::map<int,DBGraph> graphById;
std::map<int,DBRoom> roomById;
std::pair<int, DBRoomGraphCond> kv;
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain::launch - run..."));
BOOST_FOREACH(DBCondition &cond, conditions)
{
conditionById[cond.id] = cond;
}
BOOST_FOREACH(DBGraph &graph, graphs)
{
graphById[graph.id] = graph;
}
BOOST_FOREACH(DBRoom &room, rooms)
{
roomById[room.id] = room;
}
BOOST_FOREACH(DBRoomGraphCond &rgc, roomGraphConds)
{
DBCondition condition = conditionById[rgc.conditionId];
if (condition.deviceId != -1 && (condition.temperatureMin > FLT_MIN || condition.temperatureMax < FLT_MAX))
{
MHEDevice *dev = _hardDevContainer->getDeviceById(condition.deviceId);
if (dev != NULL)
{
float deviceTemperature = dev->getTemperature();
if (condition.temperatureMin <= deviceTemperature && deviceTemperature <= condition.temperatureMax)
graphByRoomId[rgc.roomId] = rgc;
}
}
else
graphByRoomId[rgc.roomId] = rgc;
}
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
BOOST_FOREACH(kv, graphByRoomId)
{
DBCondition condition = conditionById[kv.second.conditionId];
DBGraph graph = graphById[kv.second.graphId];
DBRoom room = roomById[kv.second.roomId];
MHEDevice *devIn = _hardDevContainer->getDeviceById(room.deviceTemperatureId);
MHEDevice *devHeater = _hardDevContainer->getDeviceById(room.deviceHeaterId);
MHEDevice *devHeating = _hardDevContainer->getDeviceById(room.deviceHeatingId);
long currentHHMM = now.time_of_day().hours() * 100L + now.time_of_day().minutes();
float temperatureOrder = NAN;
BOOST_FOREACH(DBGraphData data, graph.data)
if (currentHHMM >= data.time)
temperatureOrder = data.value;
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain::launch - room=" << (std::string)room << " condition=" << (std::string)condition));
if (isnan(temperatureOrder))
LOG4CPLUS_ERROR(_log, LOG4CPLUS_TEXT("Brain::launch - no graph data found !!! currentHHMM=" << currentHHMM));
else
{
if (_notify != NULL)
{
int lastConditionId = _lastConditionIdByRoomId[room.id];
if (lastConditionId > 0 && lastConditionId != condition.id)
{
_notify->notifyDevices(conditionLeave, conditionById[lastConditionId]);
_notify->notifyDevices(conditionEnter, condition);
}
}
_lastConditionIdByRoomId[room.id] = condition.id;
if (devHeating != NULL)
{
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain::launch - set heating temperature to: " << temperatureOrder));
devHeating->setTempHum(temperatureOrder, devHeating->getHumidity());
}
if (devHeater != NULL)
{
float temperatureMeasured = devIn->getTemperature();
if (temperatureMeasured <= (temperatureOrder - TEMP_HYSTERESIS))
{
if (_notify != NULL && !devHeater->isActivated())
_notify->notifyDevices(conditionEnter, *devHeater);
devHeater->setStatus(true);
}
else if (temperatureMeasured >= (temperatureOrder + TEMP_HYSTERESIS))
{
if (_notify != NULL && devHeater->isActivated())
_notify->notifyDevices(conditionLeave, *devHeater);
devHeater->setStatus(false);
}
}
else
LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("Brain::launch - no heater to control"));
}
}
computeNextLaunch();
}
|
Fix logger name.
|
Fix logger name.
|
C++
|
mit
|
Teka101/MyHomeEvents,Teka101/MyHomeEvents,Teka101/MyHomeEvents,Teka101/MyHomeEvents,Teka101/MyHomeEvents
|
98d4344f4e75a2660f5f80540653fcc083c0228a
|
cpp/src/neighbors/flat_store.hpp
|
cpp/src/neighbors/flat_store.hpp
|
//
// nn_index.hpp
// Dig
//
// Created by DB on 2016-9-15
// Copyright (c) 2016 DB. All rights reserved.
//
#ifndef __FLAT_STORE_HPP
#define __FLAT_STORE_HPP
#include <memory>
#include "assert.h"
#include "Dense"
#include "nn_search.hpp"
#include "array_utils.hpp"
namespace nn {
// SELF: pick up by having the nn_index classes use (Fixed)RowArrays
// ================================================================
// Utils
// ================================================================
template<int AlignBytes, class IntT>
inline IntT aligned_length(IntT ncols) {
int16_t align_elements = AlignBytes / sizeof(IntT);
int16_t remainder = ncols % align_elements;
if (remainder > 0) {
ncols += align_elements - remainder;
}
return ncols;
}
// helper struct to get Map<> MapOptions based on alignment in bytes
template<int AlignBytes>
struct _AlignHelper { enum { AlignmentType = Eigen::Unaligned }; };
template<> struct _AlignHelper<16> { enum { AlignmentType = Eigen::Aligned }; };
template<> struct _AlignHelper<32> { enum { AlignmentType = Eigen::Aligned }; };
template<class T>
static inline T* aligned_alloc(size_t n) {
Eigen::aligned_allocator<T>{}.allocate(n);
}
template<class T>
static inline void aligned_free(T* p) {
Eigen::aligned_allocator<T>{}.free(p, 0); // 0 unused
}
// ================================================================
// RowArray
// ================================================================
// TODO maybe don't store _ncols because we have 4B dead space with it
// ------------------------------------------------ traits
// class RowArray;
// class FixedRowArray;
// template<class Derived, class Args...>
// struct row_array_traits;
// template <class Args...>
// struct row_array_traits<RowArray> {
// typedef typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixT;
// };
// template <class T, int NumCols, class Args...>
// struct row_array_traits<FixedRowArray> {
// typedef typedef Eigen::Matrix<T, Eigen::Dynamic, NumCols, Eigen::RowMajor> MatrixT;
// };
// ------------------------------------------------ BaseRowArray
template<class Derived, class T, int AlignBytes=32>
class BaseRowArray {
typedef T Scalar;
// note: using a dynamic matrix here
typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixT;
typedef Eigen::Map<MatrixT> MatrixMapT;
static const bool IsRowMajor = true;
// ------------------------ ctors
BaseRowArray(size_t initial_rows, size_t ncols):
_data(aligned_alloc<Scalar>(initial_rows * aligned_length<AlignBytes>(ncols)))
{
assert(initial_rows >= 0);
}
template<class RowMatrixT>
BaseRowArray(const RowMatrixT& X):
BaseRowArray(X.rows(), X.cols())
{
assert(X.IsRowMajor);
auto ncols = aligned_length(X.cols());
MatrixMapT mat(_data, X.rows(), ncols);
mat.topLeftCorner(X.rows(), X.cols()) = X;
}
~BaseRowArray() { aligned_free(_data); }
// ------------------------ accessors
template<class Index>
Scalar* row_ptr(const Index i) {
assert(i >= 0);
return _data + (i * Derived::cols());
}
template<class Index>
const Scalar* row_ptr(const Index i) { return row_ptr(i); }
// ------------------------ resize, insert, delete
template<class Index>
void resize(Index old_num_rows, Index new_num_rows) {
auto ncols = Derived::cols();
int64_t old_capacity = old_num_rows * ncols;
int64_t new_capacity = new_num_rows * ncols;
// std::unique_ptr<Scalar[]> new_data(new Scalar[new_capacity]);
// std::copy(_data, _data + old_capacity, new_data.get());
// _data.swap(new_data);
Scalar* new_data = aligned_alloc<Scalar>(new_capacity);
std::copy(_data, _data + old_capacity, new_data);
aligned_free(_data);
_data = new_data;
}
template<class Index, bool NeedsZeroing=true>
void insert(const Scalar* x, Index len, Index at_idx) {
auto row_start = row_ptr(at_idx);
// zero past end of inserted data (and possibly a bit before)
if (AlignBytes > 0 && NeedsZeroing) {
auto ncols = Derived::cols();
assert(AlignBytes > (sizeof(T) * ncols));
auto row_end = row_start + ncols;
auto zero_start = row_end - (AlignBytes / sizeof(T));
for (auto ptr = zero_start; ptr < row_end; ++ptr) {
*ptr = 0;
}
}
std::copy(x, x + len, row_start);
}
template<class Index>
void copy_row(Index from_idx, Index to_idx) {
assert(from_idx != to_idx);
insert<Index, false>(row_ptr(from_idx), Derived::cols(), to_idx);
}
protected:
Scalar* _data;
};
// ------------------------------------------------ RowArray
template<class T, int AlignBytes=32>
class RowArray : public BaseRowArray<RowArray<T, AlignBytes>, T, AlignBytes> {
typedef T Scalar;
typedef int32_t ColIndex;
typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixT;
typedef Eigen::Map<MatrixT> MatrixMapT;
typedef BaseRowArray<RowArray<T, AlignBytes>, T, AlignBytes> Super;
// ------------------------ ctors
template<class Index>
RowArray(Index initial_rows, Index ncols):
Super(initial_rows, aligned_length<AlignBytes>(ncols)),
_ncols(aligned_length<AlignBytes>(ncols))
{
assert(initial_rows >= 0);
}
// no copying
RowArray(const RowArray& other) = delete;
RowArray(const RowArray&& other) = delete;
// ------------------------ accessors
ColIndex cols() const { return _ncols; }
template<class Index>
MatrixMapT matrix(Index nrows) {
MatrixMapT mat(Super::_data, nrows, _ncols);
return mat;
}
private:
ColIndex _ncols;
};
// ------------------------------------------------ FixedRowArray
template<class T, int NumCols, int AlignBytes=32>
class FixedRowArray : public BaseRowArray<FixedRowArray<T, NumCols, AlignBytes>, T, AlignBytes> {
typedef T Scalar;
typedef int32_t ColIndex;
typedef Eigen::Matrix<T, Eigen::Dynamic, NumCols, Eigen::RowMajor> MatrixT;
typedef Eigen::Map<MatrixT> MatrixMapT;
typedef BaseRowArray<FixedRowArray<T, NumCols, AlignBytes>, T, AlignBytes> Super;
// ------------------------ ctors
FixedRowArray(const FixedRowArray& other) = delete;
FixedRowArray(const FixedRowArray&& other) = delete;
// ------------------------ accessors
inline constexpr ColIndex cols() const { return NumCols; }
template<class Index>
MatrixMapT matrix(Index nrows) {
MatrixMapT mat(Super::_data, nrows, NumCols);
return mat;
}
};
// ================================================================
// RowStore
// ================================================================
// stores vectors as (optionally) aligned rows in a matrix; lets us access a
// vector and know that it's 32-byte aligned, which enables using
// 32-byte SIMD instructions (as found in 256-bit AVX 2)
template<class T, int AlignBytes=32, class IdT=int64_t>
class RowStore {
public:
typedef typename Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Index Index;
typedef T Scalar;
typedef IdT Id;
typedef int8_t PadLengthT;
// typedef Eigen::Map<Eigen::Matrix<Scalar, 1, -1>, Eigen::Aligned> RowT;
typedef Eigen::Map<const Eigen::Matrix<Scalar, 1, Eigen::Dynamic>,
_AlignHelper<AlignBytes>::AlignmentType> RowT;
// Eigen::Stride<Eigen::Dynamic, 1> > RowT;
typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMatrixT;
// typedef Eigen::Map<RowMatrixT> DataMatrixT;
static const bool IsRowMajor = true;
// ------------------------ ctors
RowStore(Index capacity, Index ncols):
_pad_width(static_cast<PadLengthT>(aligned_length<AlignBytes>(ncols) - ncols)),
_data(capacity, aligned_length<AlignBytes>(ncols))
// _ncols(aligned_length<AlignBytes>(ncols)),
// _capacity(capacity),
// _data(new Scalar[capacity * _ncols]())
{
assert(capacity > 0);
if (_pad_width > 0) {
_data.topRightCorner(_data.rows(), _pad_width).setZero();
}
}
RowStore(const RowMatrixT& X):
RowStore(X.rows(), X.cols())
{
_data.topLeftCorner(X.rows(), X.cols()) = X;
_ids = ar::range(static_cast<Id>(0), static_cast<Id>(X.rows()));
}
// template<class RowMatrixT>
// RowStore(const RowMatrixT&& X) noexcept : _data(X) {}
// _ncols(aligned_length<AlignBytes>(X.cols())),
// _capacity(X.rows()),
// _data(new Scalar[_capacity * _ncols]())
// {
// assert(_capacity > 0);
// for (size_t i = 0; i < X.rows(); i++) {
// insert(X.row(i).data(), i);
// }
// }
// ------------------------ accessors
Index rows() const { return _ids.size(); }
Index cols() const { return _data.cols(); }
Index size() const { return rows() * cols(); }
Index capacity_rows() const { return _data.rows(); }
Index capacity() const { return capacity_rows() * cols(); }
Index padding() const { return _pad_width; }
const std::vector<Id>& row_ids() const { return _ids; }
Scalar* row_ptr(Index i) { return _data.row(i).data(); }
const Scalar* row_ptr(Index i) const { return _data.row(i).data(); }
// aligned Eigen::Map to get explicit vectorization
RowT row(Index i) const {
RowT r(row_ptr(i), cols());
return r;
}
auto matrix() -> decltype(std::declval<RowMatrixT>().topLeftCorner(2, 2)) {
return _data.topLeftCorner(rows(), cols());
}
auto inner_matrix() -> decltype(std::declval<RowMatrixT>().topLeftCorner(2, 2)) {
return _data.topLeftCorner(rows(), cols() - _pad_width);
}
// ------------------------ insert and delete
// insert returns 0 if no resize, else new capacity
Index insert(const Scalar* row_start, Id id) {
_ids.push_back(id);
auto cap = capacity_rows();
Index ret = 0;
if (rows() > cap) { // resize if needed
// Index new_size = std::max(capacity + 1, _capacity * 1.5) * _ncols;
// std::unique_ptr<Scalar[]> new_data(new Scalar[new_capacity]);
// std::copy(_data, _data + size(), new_data.get());
// _capacity = new_capacity;
// _data.swap(new_data);
Index new_capacity = std::max(cap + 1, cap * 1.5);
_data.conservativeResize(new_capacity, Eigen::NoChange);
ret = new_capacity;
}
// _data.row(rows()) =
// Scalar* row_start_ptr = _data + (_ncols * rows());
Scalar* row_start_ptr = row_ptr(rows());
std::copy(row_start, row_start + (cols() - _pad_width), row_start_ptr);
if (AlignBytes > 0 && _pad_width > 0) { // check alignbytes to short-circuit
for (Index i = 0; i < _pad_width; i++) {
*(row_start_ptr + cols() + i) = 0;
}
}
return ret;
}
Index erase(Id id) {
auto idx = ar::find(_ids, id);
if (idx < 0) {
return -1;
}
// move data at the end to overwrite the removed row so that
// everything remains contiguous
// auto last_idx = _ids.size() - 1;
// _ids[idx] = _ids[last_idx];
// auto last_row_start = row_ptr(last_idx);
// Scalar* replace_row_ptr = row_ptr(idx);
// std::copy(last_row_start, last_row_start + _ncols, replace_row_ptr);
_ids[idx] = _ids.back();
_ids.pop_back(); // reduce size
return idx;
}
private:
// int32_t _ncols; // 4B
// int32_t _capacity; // 4B
std::vector<Id> _ids; // 24B; size() = number of entries
RowMatrixT _data; // 24B; rows, cols = capacity, vector length
PadLengthT _pad_width; // 1B
// std::unique_ptr<Scalar[]> _data; // 8B
};
} // namespace nn
#endif // __FLAT_STORE_HPP
|
//
// nn_index.hpp
// Dig
//
// Created by DB on 2016-9-15
// Copyright (c) 2016 DB. All rights reserved.
//
#ifndef __FLAT_STORE_HPP
#define __FLAT_STORE_HPP
#include <memory>
#include "assert.h"
#include "Dense"
#include "nn_search.hpp"
#include "array_utils.hpp"
namespace nn {
// ================================================================
// Utils
// ================================================================
template<class T, int AlignBytes, class IntT>
inline IntT aligned_length(IntT ncols) {
int16_t align_elements = AlignBytes / sizeof(T);
int16_t remainder = ncols % align_elements;
if (remainder > 0) {
ncols += align_elements - remainder;
}
return ncols;
}
// helper struct to get Eigen::Map<> MapOptions based on alignment in bytes
template<int AlignBytes>
struct _AlignHelper { enum { AlignmentType = Eigen::Unaligned }; };
template<> struct _AlignHelper<16> { enum { AlignmentType = Eigen::Aligned }; };
template<> struct _AlignHelper<32> { enum { AlignmentType = Eigen::Aligned }; };
template<class T>
static inline T* aligned_alloc(size_t n) {
Eigen::aligned_allocator<T>{}.allocate(n);
}
template<class T>
static inline void aligned_free(T* p) {
Eigen::aligned_allocator<T>{}.free(p, 0); // 0 unused
}
// ================================================================
// RowArray
// ================================================================
// TODO maybe don't store _ncols because we have 4B dead space with it
// ------------------------------------------------ traits
template<class T, int AlignBytes> class DynamicRowArray;
template<class T, int NumCols, int AlignBytes> class FixedRowArray;
// set default param values here so don't have to pass them in
template<class Derived, class T=float, int NumCols=-1, int AlignBytes=-1, class... Args>
struct row_array_traits;
template <class T, int NumCols, int AlignBytes, class... Args>
struct row_array_traits<DynamicRowArray<Args...>, T, NumCols, AlignBytes> {
typedef int32_t ColIndex;
typedef Eigen::Matrix<T, 1, Eigen::Dynamic, Eigen::RowMajor> RowT;
typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixT;
};
template <class T, int NumCols, int AlignBytes, class... Args>
struct row_array_traits<FixedRowArray<T, NumCols, AlignBytes>, T, NumCols, AlignBytes, Args...> {
typedef int32_t ColIndex;
typedef Eigen::Matrix<T, 1, NumCols, Eigen::RowMajor> RowT;
typedef Eigen::Matrix<T, Eigen::Dynamic, NumCols, Eigen::RowMajor> MatrixT;
};
// ------------------------------------------------ BaseRowArray
// BaseRowArray just has a pointer to its data and knows how wide each row
// is by calling Derived::cols(). It can hand a pointer to the start of a
// row, insert into a row, and copy one of its rows into another one; it
// performs no bounds checks of any kind (and doesn't even know how long
// its data is)
//
// Also aligns each row to AlignBytes boundaries, assuming that Derived::cols()
// is guaranteed to yield a number of objects that's an even multiple of
// AlignBytes / sizeof(T)
template<class Derived, class T, int AlignBytes=32>
class BaseRowArray {
typedef T Scalar;
typedef typename row_array_traits<Derived, T>::MatrixT MatrixT;
typedef typename row_array_traits<Derived, T>::RowT RowT;
typedef Eigen::Map<MatrixT, _AlignHelper<AlignBytes>::AlignmentType> MatrixMapT;
typedef Eigen::Map<RowT, _AlignHelper<AlignBytes>::AlignmentType> RowMapT;
static const bool IsRowMajor = true;
// ------------------------ ctors
BaseRowArray(size_t initial_rows, size_t ncols):
_data(aligned_alloc<Scalar>(initial_rows * _aligned_length(ncols)))
{
assert(initial_rows >= 0);
}
template<class RowMatrixT>
BaseRowArray(const RowMatrixT& X):
BaseRowArray(X.rows(), X.cols())
{
assert(X.IsRowMajor);
auto ncols = _aligned_length(X.cols());
MatrixMapT mat(_data, X.rows(), ncols);
mat.topLeftCorner(X.rows(), X.cols()) = X;
}
~BaseRowArray() { aligned_free(_data); }
// ------------------------ accessors
template<class Index>
Scalar* row_ptr(const Index i) const {
assert(i >= 0);
return _data + (i * _cols());
}
template<class Index>
const Scalar* row_ptr(const Index i) const { return row_ptr(i); }
template<class Index>
RowMapT row(const Index i) const {
return RowMapT{row_ptr(i), _cols()};
}
template<class Index>
MatrixMapT matrix(const Index nrows) const {
return MatrixMapT{_data, nrows, _cols()};
}
// ------------------------ resize, insert, delete
template<class Index>
void resize(Index old_num_rows, Index new_num_rows) {
auto ncols = _cols();
assert (_aligned_length(ncols) == ncols);
assert(new_num_rows > old_num_rows); // for now, should only get bigger
int64_t old_capacity = old_num_rows * ncols;
int64_t new_capacity = new_num_rows * ncols;
int64_t len = std::min(old_capacity, new_capacity);
Scalar* new_data = aligned_alloc<Scalar>(new_capacity);
std::copy(_data, _data + len, new_data);
aligned_free(_data);
_data = new_data;
}
template<class Index, bool NeedsZeroing=true>
void insert(const Scalar* x, Index len, Index at_idx) {
auto row_start = row_ptr(at_idx);
// zero past end of inserted data (and possibly a bit before)
if (AlignBytes > 0 && NeedsZeroing) {
auto ncols = _cols();
assert(AlignBytes > (sizeof(T) * ncols));
auto row_end = row_start + ncols;
auto zero_start = row_end - (AlignBytes / sizeof(T));
for (auto ptr = zero_start; ptr < row_end; ++ptr) {
*ptr = 0;
}
}
std::copy(x, x + len, row_start);
}
template<class Index>
void copy_row(Index from_idx, Index to_idx) {
assert(from_idx != to_idx);
insert<Index, false>(row_ptr(from_idx), _cols(), to_idx);
}
protected:
Scalar* _data;
size_t _aligned_length(size_t ncols) {
return aligned_length<T, AlignBytes>(ncols);
}
private:
inline auto _cols() -> decltype(Derived::cols()) { return Derived::cols(); }
};
// ------------------------------------------------ DynamicRowArray
// BaseRowArray subclass with a width set at construction time
template<class T, int AlignBytes=32>
class DynamicRowArray : public BaseRowArray<DynamicRowArray<T, AlignBytes>, T, AlignBytes> {
// typedef int32_t ColIndex;
typedef typename row_array_traits<DynamicRowArray>::ColIndex ColIndex;
typedef BaseRowArray<DynamicRowArray<T, AlignBytes>, T, AlignBytes> Super;
// ------------------------ ctors
template<class Index>
DynamicRowArray(Index initial_rows, Index ncols):
Super(initial_rows, _aligned_length(ncols)),
_ncols(_aligned_length(ncols))
{
assert(initial_rows >= 0);
}
// no copying
DynamicRowArray(const DynamicRowArray& other) = delete;
DynamicRowArray(const DynamicRowArray&& other) = delete;
// ------------------------ accessors
ColIndex cols() const { return _ncols; }
private:
ColIndex _ncols;
};
// ------------------------------------------------ FixedRowArray
// BaseRowArray subclass that has a fixed width, and so doesn't need to
// store it
template<class T, int NumCols, int AlignBytes=32>
class FixedRowArray : public BaseRowArray<FixedRowArray<T, NumCols, AlignBytes>, T, AlignBytes> {
typedef typename row_array_traits<FixedRowArray>::ColIndex ColIndex;
typedef BaseRowArray<FixedRowArray<T, NumCols, AlignBytes>, T, AlignBytes> Super;
// ------------------------ ctors
FixedRowArray(const FixedRowArray& other) = delete;
FixedRowArray(const FixedRowArray&& other) = delete;
// ------------------------ accessors
inline constexpr ColIndex cols() const { return NumCols; }
};
// ================================================================
// RowStore
// ================================================================
// stores vectors as (optionally) aligned rows in a matrix; lets us access a
// vector and know that it's 32-byte aligned, which enables using
// 32-byte SIMD instructions (as found in 256-bit AVX 2)
//
// this code is somewhat redundant with RowArray code, but refactoring
// to combine them is not a priority atm
template<class T, int AlignBytes=32, class IdT=int64_t>
class RowStore {
public:
typedef typename Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Index Index;
typedef T Scalar;
typedef IdT Id;
typedef int8_t PadLengthT;
typedef Eigen::Map<const Eigen::Matrix<Scalar, 1, Eigen::Dynamic>,
_AlignHelper<AlignBytes>::AlignmentType> RowT;
typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RowMatrixT;
static const bool IsRowMajor = true;
// ------------------------ ctors
RowStore(Index capacity, Index ncols):
_pad_width(static_cast<PadLengthT>(aligned_length<Scalar, AlignBytes>(ncols) - ncols)),
_data(capacity, aligned_length<Scalar, AlignBytes>(ncols))
{
assert(capacity > 0);
if (_pad_width > 0) {
_data.topRightCorner(_data.rows(), _pad_width).setZero();
}
}
RowStore(const RowMatrixT& X):
RowStore(X.rows(), X.cols())
{
_data.topLeftCorner(X.rows(), X.cols()) = X;
_ids = ar::range(static_cast<Id>(0), static_cast<Id>(X.rows()));
}
// ------------------------ accessors
Index rows() const { return _ids.size(); }
Index cols() const { return _data.cols(); }
Index size() const { return rows() * cols(); }
Index capacity_rows() const { return _data.rows(); }
Index capacity() const { return capacity_rows() * cols(); }
Index padding() const { return _pad_width; }
const std::vector<Id>& row_ids() const { return _ids; }
Scalar* row_ptr(Index i) { return _data.row(i).data(); }
const Scalar* row_ptr(Index i) const { return _data.row(i).data(); }
// aligned Eigen::Map to get explicit vectorization
RowT row(Index i) const {
RowT r(row_ptr(i), cols());
return r;
}
auto matrix() -> decltype(std::declval<RowMatrixT>().topLeftCorner(2, 2)) {
return _data.topLeftCorner(rows(), cols());
}
auto inner_matrix() -> decltype(std::declval<RowMatrixT>().topLeftCorner(2, 2)) {
return _data.topLeftCorner(rows(), cols() - _pad_width);
}
// ------------------------ insert and delete
// insert returns 0 if no resize, else new capacity
Index insert(const Scalar* row_start, Id id) {
_ids.push_back(id);
auto cap = capacity_rows();
Index ret = 0;
if (rows() > cap) { // resize if needed
Index new_capacity = std::max(cap + 1, cap * 1.5);
_data.conservativeResize(new_capacity, Eigen::NoChange);
ret = new_capacity;
}
Scalar* row_start_ptr = row_ptr(rows());
std::copy(row_start, row_start + (cols() - _pad_width), row_start_ptr);
if (AlignBytes > 0 && _pad_width > 0) { // check alignbytes to short-circuit
for (Index i = 0; i < _pad_width; i++) {
*(row_start_ptr + cols() + i) = 0;
}
}
return ret;
}
Index erase(Id id) {
auto idx = ar::find(_ids, id);
if (idx < 0) {
return -1;
}
_ids[idx] = _ids.back();
_ids.pop_back(); // reduce size
return idx;
}
private:
std::vector<Id> _ids; // 24B; size() = number of entries
RowMatrixT _data; // 24B; rows, cols = capacity, vector length
PadLengthT _pad_width; // 1B
};
} // namespace nn
#endif // __FLAT_STORE_HPP
|
add row() accessor to RowArrays + better CRTP via type traits
|
add row() accessor to RowArrays + better CRTP via type traits
|
C++
|
mit
|
dblalock/dig,dblalock/dig,dblalock/dig
|
be9854fa7a5eedf43581ce3b180d5439b429e42e
|
PotreeConverter/src/PotreeConverter.cpp
|
PotreeConverter/src/PotreeConverter.cpp
|
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include "PotreeConverter.h"
#include "stuff.h"
#include "LASPointReader.h"
#include "PTXPointReader.h"
#include "PotreeException.h"
#include "PotreeWriter.h"
#include "LASPointWriter.hpp"
#include "BINPointWriter.hpp"
#include "BINPointReader.hpp"
#include "PlyPointReader.h"
#include "XYZPointReader.hpp"
#include <chrono>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include <math.h>
#include <fstream>
using std::stringstream;
using std::map;
using std::string;
using std::vector;
using std::find;
using std::chrono::high_resolution_clock;
using std::chrono::milliseconds;
using std::chrono::duration_cast;
using std::fstream;
using boost::iends_with;
using boost::filesystem::is_directory;
using boost::filesystem::directory_iterator;
using boost::filesystem::is_regular_file;
using boost::filesystem::path;
namespace Potree{
PointReader *PotreeConverter::createPointReader(string path, PointAttributes pointAttributes){
PointReader *reader = NULL;
if(boost::iends_with(path, ".las") || boost::iends_with(path, ".laz")){
reader = new LASPointReader(path);
}else if(boost::iends_with(path, ".ptx")){
reader = new PTXPointReader(path);
}else if(boost::iends_with(path, ".ply")){
reader = new PlyPointReader(path);
}else if(boost::iends_with(path, ".xyz") || boost::iends_with(path, ".txt")){
reader = new XYZPointReader(path, format, colorRange, intensityRange);
}else if(boost::iends_with(path, ".pts")){
vector<double> intensityRange;
if(this->intensityRange.size() == 0){
intensityRange.push_back(-2048);
intensityRange.push_back(+2047);
}
reader = new XYZPointReader(path, format, colorRange, intensityRange);
}else if(boost::iends_with(path, ".bin")){
reader = new BINPointReader(path, aabb, scale, pointAttributes);
}
return reader;
}
PotreeConverter::PotreeConverter(string workDir, vector<string> sources){
this->workDir = workDir;
this->sources = sources;
}
void PotreeConverter::prepare(){
// if sources contains directories, use files inside the directory instead
vector<string> sourceFiles;
for (const auto &source : sources) {
path pSource(source);
if(boost::filesystem::is_directory(pSource)){
boost::filesystem::directory_iterator it(pSource);
for(;it != boost::filesystem::directory_iterator(); it++){
path pDirectoryEntry = it->path();
if(boost::filesystem::is_regular_file(pDirectoryEntry)){
string filepath = pDirectoryEntry.string();
if(boost::iends_with(filepath, ".las")
|| boost::iends_with(filepath, ".laz")
|| boost::iends_with(filepath, ".xyz")
|| boost::iends_with(filepath, ".pts")
|| boost::iends_with(filepath, ".ptx")
|| boost::iends_with(filepath, ".ply")){
sourceFiles.push_back(filepath);
}
}
}
}else if(boost::filesystem::is_regular_file(pSource)){
sourceFiles.push_back(source);
}
}
this->sources = sourceFiles;
pointAttributes = PointAttributes();
pointAttributes.add(PointAttribute::POSITION_CARTESIAN);
for(const auto &attribute : outputAttributes){
if(attribute == "RGB"){
pointAttributes.add(PointAttribute::COLOR_PACKED);
}else if(attribute == "INTENSITY"){
pointAttributes.add(PointAttribute::INTENSITY);
}else if(attribute == "CLASSIFICATION"){
pointAttributes.add(PointAttribute::CLASSIFICATION);
}else if(attribute == "NORMAL"){
pointAttributes.add(PointAttribute::NORMAL_OCT16);
}
}
}
AABB PotreeConverter::calculateAABB(){
AABB aabb;
if(aabbValues.size() == 6){
Vector3<double> userMin(aabbValues[0],aabbValues[1],aabbValues[2]);
Vector3<double> userMax(aabbValues[3],aabbValues[4],aabbValues[5]);
aabb = AABB(userMin, userMax);
}else{
for(string source : sources){
PointReader *reader = createPointReader(source, pointAttributes);
AABB lAABB = reader->getAABB();
aabb.update(lAABB.min);
aabb.update(lAABB.max);
reader->close();
delete reader;
}
}
return aabb;
}
void PotreeConverter::generatePage(string name){
string pagedir = this->workDir;
string templateSourcePath = "./resources/page_template/examples/viewer_template.html";
string templateTargetPath = pagedir + "/examples/" + name + ".html";
Potree::copyDir(fs::path("./resources/page_template"), fs::path(pagedir));
fs::remove(pagedir + "/examples/viewer_template.html");
{ // change viewer template
ifstream in( templateSourcePath );
ofstream out( templateTargetPath );
string line;
while(getline(in, line)){
if(line.find("<!-- INCLUDE SETTINGS HERE -->") != string::npos){
out << "\t<script src=\"./" << name << ".js\"></script>" << endl;
}else if((outputFormat == Potree::OutputFormat::LAS || outputFormat == Potree::OutputFormat::LAZ) &&
line.find("<!-- INCLUDE ADDITIONAL DEPENDENCIES HERE -->") != string::npos){
out << "\t<script src=\"../libs/plasio/js/laslaz.js\"></script>" << endl;
out << "\t<script src=\"../libs/plasio/vendor/bluebird.js\"></script>" << endl;
out << "\t<script src=\"../build/js/laslaz.js\"></script>" << endl;
}else{
out << line << endl;
}
}
in.close();
out.close();
}
{ // write settings
stringstream ssSettings;
ssSettings << "var sceneProperties = {" << endl;
ssSettings << "\tpath: \"" << "../resources/pointclouds/" << name << "/cloud.js\"," << endl;
ssSettings << "\tcameraPosition: null, // other options: cameraPosition: [10,10,10]," << endl;
ssSettings << "\tcameraTarget: null, // other options: cameraTarget: [0,0,0]," << endl;
ssSettings << "\tfov: 60, // field of view in degrees," << endl;
ssSettings << "\tsizeType: \"Adaptive\", // other options: \"Fixed\", \"Attenuated\"" << endl;
ssSettings << "\tquality: null, // other options: \"Circles\", \"Interpolation\", \"Splats\"" << endl;
ssSettings << "\tmaterial: \"RGB\", // other options: \"Height\", \"Intensity\", \"Classification\"" << endl;
ssSettings << "\tpointLimit: 1, // max number of points in millions" << endl;
ssSettings << "\tpointSize: 1, // " << endl;
ssSettings << "\tnavigation: \"Orbit\", // other options: \"Orbit\", \"Flight\"" << endl;
ssSettings << "\tuseEDL: false, " << endl;
ssSettings << "};" << endl;
ofstream fSettings;
fSettings.open(pagedir + "/examples/" + name + ".js", ios::out);
fSettings << ssSettings.str();
fSettings.close();
}
}
void PotreeConverter::convert(){
auto start = high_resolution_clock::now();
prepare();
long long pointsProcessed = 0;
AABB aabb = calculateAABB();
cout << "AABB: " << endl << aabb << endl;
aabb.makeCubic();
cout << "cubic AABB: " << endl << aabb << endl;
if (diagonalFraction != 0) {
spacing = (float)(aabb.size.length() / diagonalFraction);
cout << "spacing calculated from diagonal: " << spacing << endl;
}
if(pageName.size() > 0){
generatePage(pageName);
workDir = workDir + "/resources/pointclouds/" + pageName;
}
PotreeWriter *writer = NULL;
if(fs::exists(fs::path(this->workDir + "/cloud.js"))){
if(storeOption == StoreOption::ABORT_IF_EXISTS){
cout << "ABORTING CONVERSION: target already exists: " << this->workDir << "/cloud.js" << endl;
cout << "If you want to overwrite the existing conversion, specify --overwrite" << endl;
cout << "If you want add new points to the existing conversion, make sure the new points ";
cout << "are contained within the bounding box of the existing conversion and then specify --incremental" << endl;
return;
}else if(storeOption == StoreOption::OVERWRITE){
fs::remove_all(workDir + "/data");
fs::remove_all(workDir + "/temp");
fs::remove(workDir + "/cloud.js");
writer = new PotreeWriter(this->workDir, aabb, spacing, maxDepth, scale, outputFormat, pointAttributes);
}else if(storeOption == StoreOption::INCREMENTAL){
writer = new PotreeWriter(this->workDir);
writer->loadStateFromDisk();
}
}else{
writer = new PotreeWriter(this->workDir, aabb, spacing, maxDepth, scale, outputFormat, pointAttributes);
}
if(writer == NULL){
return;
}
for (const auto &source : sources) {
cout << "READING: " << source << endl;
PointReader *reader = createPointReader(source, pointAttributes);
while(reader->readNextPoint()){
pointsProcessed++;
Point p = reader->getPoint();
writer->add(p);
if((pointsProcessed % (1'000'000)) == 0){
writer->processStore();
writer->waitUntilProcessed();
auto end = high_resolution_clock::now();
long long duration = duration_cast<milliseconds>(end-start).count();
float seconds = duration / 1'000.0f;
stringstream ssMessage;
ssMessage.imbue(std::locale(""));
ssMessage << "INDEXING: ";
ssMessage << pointsProcessed << " points processed; ";
ssMessage << writer->numAccepted << " points written; ";
ssMessage << seconds << " seconds passed";
cout << ssMessage.str() << endl;
}
if((pointsProcessed % (10'000'000)) == 0){
cout << "FLUSHING: ";
auto start = high_resolution_clock::now();
writer->flush();
auto end = high_resolution_clock::now();
long long duration = duration_cast<milliseconds>(end-start).count();
float seconds = duration / 1'000.0f;
cout << seconds << "s" << endl;
}
//if(pointsProcessed >= 10'000'000){
// break;
//}
}
reader->close();
delete reader;
}
cout << "closing writer" << endl;
writer->flush();
writer->close();
float percent = (float)writer->numAccepted / (float)pointsProcessed;
percent = percent * 100;
auto end = high_resolution_clock::now();
long long duration = duration_cast<milliseconds>(end-start).count();
cout << endl;
cout << "conversion finished" << endl;
cout << pointsProcessed << " points were processed and " << writer->numAccepted << " points ( " << percent << "% ) were written to the output. " << endl;
cout << "duration: " << (duration / 1000.0f) << "s" << endl;
}
}
|
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/stringbuffer.h"
#include "PotreeConverter.h"
#include "stuff.h"
#include "LASPointReader.h"
#include "PTXPointReader.h"
#include "PotreeException.h"
#include "PotreeWriter.h"
#include "LASPointWriter.hpp"
#include "BINPointWriter.hpp"
#include "BINPointReader.hpp"
#include "PlyPointReader.h"
#include "XYZPointReader.hpp"
#include <chrono>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include <math.h>
#include <fstream>
using rapidjson::Document;
using rapidjson::StringBuffer;
using rapidjson::Writer;
using rapidjson::PrettyWriter;
using rapidjson::Value;
using std::stringstream;
using std::map;
using std::string;
using std::vector;
using std::find;
using std::chrono::high_resolution_clock;
using std::chrono::milliseconds;
using std::chrono::duration_cast;
using std::fstream;
using boost::iends_with;
using boost::filesystem::is_directory;
using boost::filesystem::directory_iterator;
using boost::filesystem::is_regular_file;
using boost::filesystem::path;
namespace Potree{
PointReader *PotreeConverter::createPointReader(string path, PointAttributes pointAttributes){
PointReader *reader = NULL;
if(boost::iends_with(path, ".las") || boost::iends_with(path, ".laz")){
reader = new LASPointReader(path);
}else if(boost::iends_with(path, ".ptx")){
reader = new PTXPointReader(path);
}else if(boost::iends_with(path, ".ply")){
reader = new PlyPointReader(path);
}else if(boost::iends_with(path, ".xyz") || boost::iends_with(path, ".txt")){
reader = new XYZPointReader(path, format, colorRange, intensityRange);
}else if(boost::iends_with(path, ".pts")){
vector<double> intensityRange;
if(this->intensityRange.size() == 0){
intensityRange.push_back(-2048);
intensityRange.push_back(+2047);
}
reader = new XYZPointReader(path, format, colorRange, intensityRange);
}else if(boost::iends_with(path, ".bin")){
reader = new BINPointReader(path, aabb, scale, pointAttributes);
}
return reader;
}
PotreeConverter::PotreeConverter(string workDir, vector<string> sources){
this->workDir = workDir;
this->sources = sources;
}
void PotreeConverter::prepare(){
// if sources contains directories, use files inside the directory instead
vector<string> sourceFiles;
for (const auto &source : sources) {
path pSource(source);
if(boost::filesystem::is_directory(pSource)){
boost::filesystem::directory_iterator it(pSource);
for(;it != boost::filesystem::directory_iterator(); it++){
path pDirectoryEntry = it->path();
if(boost::filesystem::is_regular_file(pDirectoryEntry)){
string filepath = pDirectoryEntry.string();
if(boost::iends_with(filepath, ".las")
|| boost::iends_with(filepath, ".laz")
|| boost::iends_with(filepath, ".xyz")
|| boost::iends_with(filepath, ".pts")
|| boost::iends_with(filepath, ".ptx")
|| boost::iends_with(filepath, ".ply")){
sourceFiles.push_back(filepath);
}
}
}
}else if(boost::filesystem::is_regular_file(pSource)){
sourceFiles.push_back(source);
}
}
this->sources = sourceFiles;
pointAttributes = PointAttributes();
pointAttributes.add(PointAttribute::POSITION_CARTESIAN);
for(const auto &attribute : outputAttributes){
if(attribute == "RGB"){
pointAttributes.add(PointAttribute::COLOR_PACKED);
}else if(attribute == "INTENSITY"){
pointAttributes.add(PointAttribute::INTENSITY);
}else if(attribute == "CLASSIFICATION"){
pointAttributes.add(PointAttribute::CLASSIFICATION);
}else if(attribute == "NORMAL"){
pointAttributes.add(PointAttribute::NORMAL_OCT16);
}
}
}
AABB PotreeConverter::calculateAABB(){
AABB aabb;
if(aabbValues.size() == 6){
Vector3<double> userMin(aabbValues[0],aabbValues[1],aabbValues[2]);
Vector3<double> userMax(aabbValues[3],aabbValues[4],aabbValues[5]);
aabb = AABB(userMin, userMax);
}else{
for(string source : sources){
PointReader *reader = createPointReader(source, pointAttributes);
AABB lAABB = reader->getAABB();
aabb.update(lAABB.min);
aabb.update(lAABB.max);
reader->close();
delete reader;
}
}
return aabb;
}
void PotreeConverter::generatePage(string name){
string pagedir = this->workDir;
string templateSourcePath = "./resources/page_template/examples/viewer_template.html";
string templateTargetPath = pagedir + "/examples/" + name + ".html";
Potree::copyDir(fs::path("./resources/page_template"), fs::path(pagedir));
fs::remove(pagedir + "/examples/viewer_template.html");
{ // change viewer template
ifstream in( templateSourcePath );
ofstream out( templateTargetPath );
string line;
while(getline(in, line)){
if(line.find("<!-- INCLUDE SETTINGS HERE -->") != string::npos){
out << "\t<script src=\"./" << name << ".js\"></script>" << endl;
}else if((outputFormat == Potree::OutputFormat::LAS || outputFormat == Potree::OutputFormat::LAZ) &&
line.find("<!-- INCLUDE ADDITIONAL DEPENDENCIES HERE -->") != string::npos){
out << "\t<script src=\"../libs/plasio/js/laslaz.js\"></script>" << endl;
out << "\t<script src=\"../libs/plasio/vendor/bluebird.js\"></script>" << endl;
out << "\t<script src=\"../build/js/laslaz.js\"></script>" << endl;
}else{
out << line << endl;
}
}
in.close();
out.close();
}
{ // write settings
stringstream ssSettings;
ssSettings << "var sceneProperties = {" << endl;
ssSettings << "\tpath: \"" << "../resources/pointclouds/" << name << "/cloud.js\"," << endl;
ssSettings << "\tcameraPosition: null, // other options: cameraPosition: [10,10,10]," << endl;
ssSettings << "\tcameraTarget: null, // other options: cameraTarget: [0,0,0]," << endl;
ssSettings << "\tfov: 60, // field of view in degrees," << endl;
ssSettings << "\tsizeType: \"Adaptive\", // other options: \"Fixed\", \"Attenuated\"" << endl;
ssSettings << "\tquality: null, // other options: \"Circles\", \"Interpolation\", \"Splats\"" << endl;
ssSettings << "\tmaterial: \"RGB\", // other options: \"Height\", \"Intensity\", \"Classification\"" << endl;
ssSettings << "\tpointLimit: 1, // max number of points in millions" << endl;
ssSettings << "\tpointSize: 1, // " << endl;
ssSettings << "\tnavigation: \"Orbit\", // other options: \"Orbit\", \"Flight\"" << endl;
ssSettings << "\tuseEDL: false, " << endl;
ssSettings << "};" << endl;
ofstream fSettings;
fSettings.open(pagedir + "/examples/" + name + ".js", ios::out);
fSettings << ssSettings.str();
fSettings.close();
}
}
void PotreeConverter::convert(){
auto start = high_resolution_clock::now();
prepare();
long long pointsProcessed = 0;
AABB aabb = calculateAABB();
cout << "AABB: " << endl << aabb << endl;
aabb.makeCubic();
cout << "cubic AABB: " << endl << aabb << endl;
if (diagonalFraction != 0) {
spacing = (float)(aabb.size.length() / diagonalFraction);
cout << "spacing calculated from diagonal: " << spacing << endl;
}
if(pageName.size() > 0){
generatePage(pageName);
workDir = workDir + "/resources/pointclouds/" + pageName;
}
PotreeWriter *writer = NULL;
if(fs::exists(fs::path(this->workDir + "/cloud.js"))){
if(storeOption == StoreOption::ABORT_IF_EXISTS){
cout << "ABORTING CONVERSION: target already exists: " << this->workDir << "/cloud.js" << endl;
cout << "If you want to overwrite the existing conversion, specify --overwrite" << endl;
cout << "If you want add new points to the existing conversion, make sure the new points ";
cout << "are contained within the bounding box of the existing conversion and then specify --incremental" << endl;
return;
}else if(storeOption == StoreOption::OVERWRITE){
fs::remove_all(workDir + "/data");
fs::remove_all(workDir + "/temp");
fs::remove(workDir + "/cloud.js");
writer = new PotreeWriter(this->workDir, aabb, spacing, maxDepth, scale, outputFormat, pointAttributes);
}else if(storeOption == StoreOption::INCREMENTAL){
writer = new PotreeWriter(this->workDir);
writer->loadStateFromDisk();
}
}else{
writer = new PotreeWriter(this->workDir, aabb, spacing, maxDepth, scale, outputFormat, pointAttributes);
}
if(writer == NULL){
return;
}
vector<AABB> boundingBoxes;
vector<int> numPoints;
vector<string> sourceFilenames;
for (const auto &source : sources) {
cout << "READING: " << source << endl;
PointReader *reader = createPointReader(source, pointAttributes);
boundingBoxes.push_back(reader->getAABB());
numPoints.push_back(reader->numPoints());
sourceFilenames.push_back(fs::path(source).filename().string());
while(reader->readNextPoint()){
pointsProcessed++;
Point p = reader->getPoint();
writer->add(p);
if((pointsProcessed % (1'000'000)) == 0){
writer->processStore();
writer->waitUntilProcessed();
auto end = high_resolution_clock::now();
long long duration = duration_cast<milliseconds>(end-start).count();
float seconds = duration / 1'000.0f;
stringstream ssMessage;
ssMessage.imbue(std::locale(""));
ssMessage << "INDEXING: ";
ssMessage << pointsProcessed << " points processed; ";
ssMessage << writer->numAccepted << " points written; ";
ssMessage << seconds << " seconds passed";
cout << ssMessage.str() << endl;
}
if((pointsProcessed % (10'000'000)) == 0){
cout << "FLUSHING: ";
auto start = high_resolution_clock::now();
writer->flush();
auto end = high_resolution_clock::now();
long long duration = duration_cast<milliseconds>(end-start).count();
float seconds = duration / 1'000.0f;
cout << seconds << "s" << endl;
}
//if(pointsProcessed >= 10'000'000){
// break;
//}
}
reader->close();
delete reader;
}
cout << "closing writer" << endl;
writer->flush();
writer->close();
{ // write sources.json
Document d(rapidjson::kObjectType);
Value jBoundingBox(rapidjson::kObjectType);
{
Value bbMin(rapidjson::kObjectType);
Value bbMax(rapidjson::kObjectType);
bbMin.SetArray();
bbMin.PushBack(1, d.GetAllocator());
bbMin.PushBack(2, d.GetAllocator());
bbMin.PushBack(3, d.GetAllocator());
bbMax.SetArray();
bbMax.PushBack(10, d.GetAllocator());
bbMax.PushBack(20, d.GetAllocator());
bbMax.PushBack(30, d.GetAllocator());
jBoundingBox.AddMember("min", bbMin, d.GetAllocator());
jBoundingBox.AddMember("max", bbMax, d.GetAllocator());
}
Value jSources(rapidjson::kObjectType);
jSources.SetArray();
for(int i = 0; i < sourceFilenames.size(); i++){
string &source = sourceFilenames[i];
int points = numPoints[i];
AABB boundingBox = boundingBoxes[i];
Value jSource(rapidjson::kObjectType);
Value jName(source.c_str(), (rapidjson::SizeType)source.size());
Value jPoints(points);
Value jBounds(rapidjson::kObjectType);
{
Value bbMin(rapidjson::kObjectType);
Value bbMax(rapidjson::kObjectType);
bbMin.SetArray();
bbMin.PushBack(boundingBox.min.x, d.GetAllocator());
bbMin.PushBack(boundingBox.min.y, d.GetAllocator());
bbMin.PushBack(boundingBox.min.z, d.GetAllocator());
bbMax.SetArray();
bbMax.PushBack(boundingBox.max.x, d.GetAllocator());
bbMax.PushBack(boundingBox.max.y, d.GetAllocator());
bbMax.PushBack(boundingBox.max.z, d.GetAllocator());
jBounds.AddMember("min", bbMin, d.GetAllocator());
jBounds.AddMember("max", bbMax, d.GetAllocator());
}
jSource.AddMember("name", jName, d.GetAllocator());
jSource.AddMember("points", jPoints, d.GetAllocator());
jSource.AddMember("bounds", jBounds, d.GetAllocator());
jSources.PushBack(jSource, d.GetAllocator());
}
d.AddMember("bounds", jBoundingBox, d.GetAllocator());
d.AddMember("sources", jSources, d.GetAllocator());
StringBuffer buffer;
//PrettyWriter<StringBuffer> writer(buffer);
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
string sourcesPath = this->workDir + "/sources.json";
ofstream sourcesOut(sourcesPath, ios::out);
sourcesOut << buffer.GetString();
sourcesOut.close();
}
float percent = (float)writer->numAccepted / (float)pointsProcessed;
percent = percent * 100;
auto end = high_resolution_clock::now();
long long duration = duration_cast<milliseconds>(end-start).count();
cout << endl;
cout << "conversion finished" << endl;
cout << pointsProcessed << " points were processed and " << writer->numAccepted << " points ( " << percent << "% ) were written to the output. " << endl;
cout << "duration: " << (duration / 1000.0f) << "s" << endl;
}
}
|
write input file meta data to sources.json
|
write input file meta data to sources.json
|
C++
|
bsd-2-clause
|
potree/PotreeConverter,potree/PotreeConverter,potree/PotreeConverter,potree/PotreeConverter,potree/PotreeConverter,potree/PotreeConverter,potree/PotreeConverter
|
a33b34767d46aed1b029e48e462aa376b925ab48
|
src/vw/FileIO/GdalIO.cc
|
src/vw/FileIO/GdalIO.cc
|
#include <vw/FileIO/GdalIO.h>
#include <vw/Core/Exception.h>
#include <vw/Core/Log.h>
static void CPL_STDCALL gdal_error_handler(CPLErr eErrClass, int nError, const char *pszErrorMsg) {
vw::MessageLevel lvl;
switch(eErrClass) {
case CE_Debug:
case CE_Warning:
lvl = vw::WarningMessage;
break;
default:
lvl = vw::ErrorMessage;
break;
}
std::string msg;
if (pszErrorMsg)
msg = pszErrorMsg;
boost::replace_all(msg, "\n", " ");
if (eErrClass == CE_Fatal)
vw::vw_throw(vw::IOErr() << "GdalIO: " << msg << " (code = " << nError << ")");
else
vw::vw_out(lvl, "fileio") << "GdalIO: " << msg << " (code = " << nError << ")" << std::endl;
}
// GDAL is not thread-safe, so we keep a global GDAL lock (pointed to
// by gdal_mutex_ptr, below) that we hold anytime we call into the
// GDAL library itself.
namespace {
vw::RunOnce _gdal_init_once = VW_RUNONCE_INIT;
vw::Mutex* _gdal_mutex;
void init_gdal() {
CPLPushErrorHandler(gdal_error_handler);
// If we run out of handles, GDAL error out. If you have more than 400
// open, you probably have a bug.
CPLSetConfigOption("GDAL_MAX_DATASET_POOL_SIZE", "400");
GDALAllRegister();
_gdal_mutex = new vw::Mutex();
}
void kill_gdal() {
delete _gdal_mutex;
GDALDumpOpenDatasets(stderr);
GDALDestroyDriverManager();
CPLDumpSharedList(0);
CPLCleanupTLS();
CPLPopErrorHandler();
}
GDALColorInterp bcolor(const boost::shared_ptr<GDALDataset> d, size_t idx /* 1-indexed */) {
if (ssize_t(idx) > d->GetRasterCount())
return GCI_Max;
return d->GetRasterBand(idx)->GetColorInterpretation();
}
vw::ChannelTypeEnum channel_gdal_to_vw(GDALDataType gdal_type) {
switch (gdal_type) {
case GDT_Byte: return vw::VW_CHANNEL_UINT8;
case GDT_Int16: return vw::VW_CHANNEL_INT16;
case GDT_UInt16: return vw::VW_CHANNEL_UINT16;
case GDT_Int32: return vw::VW_CHANNEL_INT32;
case GDT_UInt32: return vw::VW_CHANNEL_UINT32;
case GDT_Float32: return vw::VW_CHANNEL_FLOAT32;
case GDT_Float64: return vw::VW_CHANNEL_FLOAT64;
default: vw::vw_throw( vw::IOErr() << "Unsupported GDAL channel type (" << gdal_type << ")." );
}
}
GDALDataType channel_vw_to_gdal(vw::ChannelTypeEnum vw_type) {
switch (vw_type) {
case vw::VW_CHANNEL_UINT8: return GDT_Byte;
case vw::VW_CHANNEL_INT16: return GDT_Int16;
case vw::VW_CHANNEL_UINT16: return GDT_UInt16;
case vw::VW_CHANNEL_INT32: return GDT_Int32;
case vw::VW_CHANNEL_UINT32: return GDT_UInt32;
case vw::VW_CHANNEL_FLOAT32: return GDT_Float32;
case vw::VW_CHANNEL_FLOAT64: return GDT_Float64;
default: vw::vw_throw( vw::IOErr() << "Unsupported vw channel type (" << vw_type << ")." );
}
}
}
namespace vw {
namespace fileio {
namespace detail {
vw::Mutex& gdal() {
_gdal_init_once.run( init_gdal );
return *_gdal_mutex;
}
////////////////////////////////////////////////////////////////////////////////
// Decompress
////////////////////////////////////////////////////////////////////////////////
GdalIODecompress::GdalIODecompress() { }
GdalIODecompress::~GdalIODecompress() { }
bool GdalIODecompress::ready() const { return true; }
void GdalIODecompress::read(uint8* buffer, size_t bufsize) {
size_t skip = line_bytes();
VW_ASSERT(bufsize >= m_fmt.rows * skip, LogicErr() << "Buffer is too small");
if (m_fmt.pixel_format == VW_PIXEL_SCALAR) {
// Separate bands
m_dataset->RasterIO(GF_Read, 0, 0, m_fmt.cols, m_fmt.rows, reinterpret_cast<void*>(buffer), m_fmt.cols, m_fmt.rows,
channel_vw_to_gdal(m_fmt.channel_type), num_channels(m_fmt.pixel_format), NULL, 0, 0, 0);
} else {
// Interleaved pixels
m_dataset->RasterIO(GF_Read, 0, 0, m_fmt.cols, m_fmt.rows, reinterpret_cast<void*>(buffer), m_fmt.cols, m_fmt.rows,
channel_vw_to_gdal(m_fmt.channel_type), num_channels(m_fmt.pixel_format), NULL,
m_cstride, m_rstride, 1);
}
}
void GdalIODecompress::open() {
this->bind();
m_fmt.rows = m_dataset->GetRasterYSize();
m_fmt.cols = m_dataset->GetRasterXSize();
size_t chans = m_dataset->GetRasterCount();
VW_ASSERT(chans > 0, IOErr() << "Cannot read GDAL Image: unknown number of channels");
if ( bcolor(m_dataset, 1) == GCI_GrayIndex) {
if (chans == 1) {
m_fmt.pixel_format = VW_PIXEL_GRAY;
m_fmt.planes = 1;
} else if (chans == 2 && bcolor(m_dataset, 2) == GCI_AlphaBand) {
m_fmt.pixel_format = VW_PIXEL_GRAYA;
m_fmt.planes = 1;
}
} else if ( bcolor(m_dataset, 1) == GCI_RedBand && bcolor(m_dataset, 2) == GCI_GreenBand && bcolor(m_dataset, 3) == GCI_BlueBand) {
if (chans == 3) {
m_fmt.pixel_format = VW_PIXEL_RGB;
m_fmt.planes = 1;
} else if (chans == 4 && bcolor(m_dataset, 4) == GCI_AlphaBand) {
m_fmt.pixel_format = VW_PIXEL_RGBA;
m_fmt.planes = 1;
}
}
if (m_fmt.planes == 0) {
m_fmt.planes = chans;
m_fmt.pixel_format = VW_PIXEL_SCALAR;
}
m_fmt.channel_type = channel_gdal_to_vw(m_dataset->GetRasterBand(1)->GetRasterDataType());
m_cstride = num_channels(fmt().pixel_format) * channel_size(fmt().channel_type);
m_rstride = m_cstride * m_fmt.cols;
}
////////////////////////////////////////////////////////////////////////////////
// Compress
////////////////////////////////////////////////////////////////////////////////
GdalIOCompress::GdalIOCompress(const ImageFormat& fmt) {
m_fmt = fmt;
}
GdalIOCompress::~GdalIOCompress() { }
bool GdalIOCompress::ready() const {
return true;
}
void GdalIOCompress::write(const uint8* data, size_t bufsize, size_t rows, size_t cols, size_t planes) {
size_t skip = cols * chan_bytes();
VW_ASSERT(bufsize >= rows * skip, LogicErr() << "Buffer is too small");
VW_ASSERT(planes == 1 || fmt().pixel_format==VW_PIXEL_SCALAR,
NoImplErr() << "Multi-channel multi-plane images are not supported");
m_dataset.reset(
reinterpret_cast<GDALDataset*>(GDALCreate( m_driver, m_fn.c_str(), cols, rows, num_channels(m_fmt.pixel_format), channel_vw_to_gdal(fmt().channel_type), NULL)),
GDALClose);
VW_ASSERT(m_dataset, IOErr() << "GDAL: Failed to open file for create");
if (fmt().pixel_format == VW_PIXEL_SCALAR) {
// Separate bands
m_dataset->RasterIO(GF_Write, 0, 0, cols, rows, const_cast<uint8*>(data), cols, rows,
channel_vw_to_gdal(fmt().channel_type), num_channels(m_fmt.pixel_format), NULL, 0, 0, 0);
} else {
//Interleaved pixels
m_dataset->RasterIO(GF_Write, 0, 0, cols, rows, const_cast<uint8*>(data), cols, rows,
channel_vw_to_gdal(fmt().channel_type), num_channels(m_fmt.pixel_format), NULL,
m_cstride, skip, 1);
}
m_dataset.reset();
}
void GdalIOCompress::open() {
m_driver = (GDALDriver*)GDALGetDriverByName("GTiff");
// GDAL_DCAP_VIRTUALIO was added for 1.5.0, but GTiff's support for virtual
// io predates that. Thus, the check is commented out. Uncomment it if this
// is code extended beyond tiff.
//#define VW_GDAL_BUILD_VERSION(major, minor, rev, build) (major*1000+minor*100+rev*10+build)
//#if GDAL_VERSION_NUM >= VW_GDAL_BUILD_VERSION(1,5,0,0)
// VW_ASSERT(GDALGetMetadataItem(m_driver, GDAL_DCAP_VIRTUALIO, NULL ), NoImplErr() << "GDAL's current tiff driver does not support virtual IO");
//#endif
this->bind();
m_cstride = num_channels(fmt().pixel_format) * channel_size(fmt().channel_type);
}
}}} // namespace vw::fileio::detail
|
#include <vw/FileIO/GdalIO.h>
#include <vw/Core/Exception.h>
#include <vw/Core/Log.h>
static void CPL_STDCALL gdal_error_handler(CPLErr eErrClass, int nError, const char *pszErrorMsg) {
vw::MessageLevel lvl;
switch(eErrClass) {
case CE_Debug:
case CE_Warning:
lvl = vw::WarningMessage;
break;
default:
lvl = vw::ErrorMessage;
break;
}
std::string msg;
if (pszErrorMsg)
msg = pszErrorMsg;
boost::replace_all(msg, "\n", " ");
if (eErrClass == CE_Fatal)
vw::vw_throw(vw::IOErr() << "GdalIO: " << msg << " (code = " << nError << ")");
else
vw::vw_out(lvl, "fileio") << "GdalIO: " << msg << " (code = " << nError << ")" << std::endl;
}
// GDAL is not thread-safe, so we keep a global GDAL lock (pointed to
// by gdal_mutex_ptr, below) that we hold anytime we call into the
// GDAL library itself.
namespace {
vw::RunOnce _gdal_init_once = VW_RUNONCE_INIT;
vw::Mutex* _gdal_mutex;
void init_gdal() {
CPLPushErrorHandler(gdal_error_handler);
// If we run out of handles, GDALs error out. If you have more than 400
// open, you probably have a bug.
CPLSetConfigOption("GDAL_MAX_DATASET_POOL_SIZE", "400");
GDALAllRegister();
_gdal_mutex = new vw::Mutex();
}
void kill_gdal() {
delete _gdal_mutex;
GDALDumpOpenDatasets(stderr);
GDALDestroyDriverManager();
CPLDumpSharedList(0);
CPLCleanupTLS();
CPLPopErrorHandler();
}
GDALColorInterp bcolor(const boost::shared_ptr<GDALDataset> d, size_t idx /* 1-indexed */) {
if (ssize_t(idx) > d->GetRasterCount())
return GCI_Max;
return d->GetRasterBand(idx)->GetColorInterpretation();
}
vw::ChannelTypeEnum channel_gdal_to_vw(GDALDataType gdal_type) {
switch (gdal_type) {
case GDT_Byte: return vw::VW_CHANNEL_UINT8;
case GDT_Int16: return vw::VW_CHANNEL_INT16;
case GDT_UInt16: return vw::VW_CHANNEL_UINT16;
case GDT_Int32: return vw::VW_CHANNEL_INT32;
case GDT_UInt32: return vw::VW_CHANNEL_UINT32;
case GDT_Float32: return vw::VW_CHANNEL_FLOAT32;
case GDT_Float64: return vw::VW_CHANNEL_FLOAT64;
default: vw::vw_throw( vw::IOErr() << "Unsupported GDAL channel type (" << gdal_type << ")." );
}
}
GDALDataType channel_vw_to_gdal(vw::ChannelTypeEnum vw_type) {
switch (vw_type) {
case vw::VW_CHANNEL_UINT8: return GDT_Byte;
case vw::VW_CHANNEL_INT16: return GDT_Int16;
case vw::VW_CHANNEL_UINT16: return GDT_UInt16;
case vw::VW_CHANNEL_INT32: return GDT_Int32;
case vw::VW_CHANNEL_UINT32: return GDT_UInt32;
case vw::VW_CHANNEL_FLOAT32: return GDT_Float32;
case vw::VW_CHANNEL_FLOAT64: return GDT_Float64;
default: vw::vw_throw( vw::IOErr() << "Unsupported vw channel type (" << vw_type << ")." );
}
}
}
namespace vw {
namespace fileio {
namespace detail {
vw::Mutex& gdal() {
_gdal_init_once.run( init_gdal );
return *_gdal_mutex;
}
////////////////////////////////////////////////////////////////////////////////
// Decompress
////////////////////////////////////////////////////////////////////////////////
GdalIODecompress::GdalIODecompress() { }
GdalIODecompress::~GdalIODecompress() { }
bool GdalIODecompress::ready() const { return true; }
void GdalIODecompress::read(uint8* buffer, size_t bufsize) {
size_t skip = line_bytes();
VW_ASSERT(bufsize >= m_fmt.rows * skip, LogicErr() << "Buffer is too small");
if (m_fmt.pixel_format == VW_PIXEL_SCALAR) {
// Separate bands
m_dataset->RasterIO(GF_Read, 0, 0, m_fmt.cols, m_fmt.rows, reinterpret_cast<void*>(buffer), m_fmt.cols, m_fmt.rows,
channel_vw_to_gdal(m_fmt.channel_type), num_channels(m_fmt.pixel_format), NULL, 0, 0, 0);
} else {
// Interleaved pixels
m_dataset->RasterIO(GF_Read, 0, 0, m_fmt.cols, m_fmt.rows, reinterpret_cast<void*>(buffer), m_fmt.cols, m_fmt.rows,
channel_vw_to_gdal(m_fmt.channel_type), num_channels(m_fmt.pixel_format), NULL,
m_cstride, m_rstride, 1);
}
}
void GdalIODecompress::open() {
this->bind();
m_fmt.rows = m_dataset->GetRasterYSize();
m_fmt.cols = m_dataset->GetRasterXSize();
size_t chans = m_dataset->GetRasterCount();
VW_ASSERT(chans > 0, IOErr() << "Cannot read GDAL Image: unknown number of channels");
if ( bcolor(m_dataset, 1) == GCI_GrayIndex) {
if (chans == 1) {
m_fmt.pixel_format = VW_PIXEL_GRAY;
m_fmt.planes = 1;
} else if (chans == 2 && bcolor(m_dataset, 2) == GCI_AlphaBand) {
m_fmt.pixel_format = VW_PIXEL_GRAYA;
m_fmt.planes = 1;
}
} else if ( bcolor(m_dataset, 1) == GCI_RedBand && bcolor(m_dataset, 2) == GCI_GreenBand && bcolor(m_dataset, 3) == GCI_BlueBand) {
if (chans == 3) {
m_fmt.pixel_format = VW_PIXEL_RGB;
m_fmt.planes = 1;
} else if (chans == 4 && bcolor(m_dataset, 4) == GCI_AlphaBand) {
m_fmt.pixel_format = VW_PIXEL_RGBA;
m_fmt.planes = 1;
}
}
if (m_fmt.planes == 0) {
m_fmt.planes = chans;
m_fmt.pixel_format = VW_PIXEL_SCALAR;
}
m_fmt.channel_type = channel_gdal_to_vw(m_dataset->GetRasterBand(1)->GetRasterDataType());
m_cstride = num_channels(fmt().pixel_format) * channel_size(fmt().channel_type);
m_rstride = m_cstride * m_fmt.cols;
}
////////////////////////////////////////////////////////////////////////////////
// Compress
////////////////////////////////////////////////////////////////////////////////
GdalIOCompress::GdalIOCompress(const ImageFormat& fmt) {
m_fmt = fmt;
}
GdalIOCompress::~GdalIOCompress() { }
bool GdalIOCompress::ready() const {
return true;
}
void GdalIOCompress::write(const uint8* data, size_t bufsize, size_t rows, size_t cols, size_t planes) {
size_t skip = cols * chan_bytes();
VW_ASSERT(bufsize >= rows * skip, LogicErr() << "Buffer is too small");
VW_ASSERT(planes == 1 || fmt().pixel_format==VW_PIXEL_SCALAR,
NoImplErr() << "Multi-channel multi-plane images are not supported");
int num_bands = std::max( m_fmt.planes, num_channels( m_fmt.pixel_format ) );
char** options = NULL;
try {
if(fmt().pixel_format == VW_PIXEL_GRAYA || fmt().pixel_format == VW_PIXEL_RGBA)
options = CSLSetNameValue( options, "ALPHA", "YES" );
if(fmt().pixel_format != VW_PIXEL_SCALAR )
options = CSLSetNameValue( options, "INTERLEAVE", "PIXEL" );
if( m_fmt.pixel_format == VW_PIXEL_RGB || m_fmt.pixel_format == VW_PIXEL_RGBA ||
m_fmt.pixel_format == VW_PIXEL_GENERIC_3_CHANNEL || m_fmt.pixel_format == VW_PIXEL_GENERIC_4_CHANNEL)
options = CSLSetNameValue( options, "PHOTOMETRIC", "RGB" );
m_dataset.reset(
reinterpret_cast<GDALDataset*>(GDALCreate( m_driver, m_fn.c_str(), cols, rows, num_bands, channel_vw_to_gdal(fmt().channel_type), options)),
GDALClose);
} catch (const std::exception&) {
CSLDestroy(options);
throw;
}
CSLDestroy(options);
VW_ASSERT(m_dataset, IOErr() << "GDAL: Failed to open file for create");
if (fmt().pixel_format == VW_PIXEL_SCALAR) {
// Separate bands
m_dataset->RasterIO(GF_Write, 0, 0, cols, rows, const_cast<uint8*>(data), cols, rows,
channel_vw_to_gdal(fmt().channel_type), num_bands, NULL, 0, 0, 0);
} else {
//Interleaved pixels
m_dataset->RasterIO(GF_Write, 0, 0, cols, rows, const_cast<uint8*>(data), cols, rows,
channel_vw_to_gdal(fmt().channel_type), num_bands, NULL,
m_cstride, skip, 1);
}
m_dataset.reset();
}
void GdalIOCompress::open() {
m_driver = (GDALDriver*)GDALGetDriverByName("GTiff");
// GDAL_DCAP_VIRTUALIO was added for 1.5.0, but GTiff's support for virtual
// io predates that. Thus, the check is commented out. Uncomment it if this
// is code extended beyond tiff.
//#define VW_GDAL_BUILD_VERSION(major, minor, rev, build) (major*1000+minor*100+rev*10+build)
//#if GDAL_VERSION_NUM >= VW_GDAL_BUILD_VERSION(1,5,0,0)
// VW_ASSERT(GDALGetMetadataItem(m_driver, GDAL_DCAP_VIRTUALIO, NULL ), NoImplErr() << "GDAL's current tiff driver does not support virtual IO");
//#endif
this->bind();
m_cstride = num_channels(fmt().pixel_format) * channel_size(fmt().channel_type);
}
}}} // namespace vw::fileio::detail
|
make sure mem gdal writer sets some necessary options
|
make sure mem gdal writer sets some necessary options
|
C++
|
apache-2.0
|
DougFirErickson/visionworkbench,AveRapina/visionworkbench,DougFirErickson/visionworkbench,DougFirErickson/visionworkbench,fengzhyuan/visionworkbench,AveRapina/visionworkbench,fengzhyuan/visionworkbench,fengzhyuan/visionworkbench,DougFirErickson/visionworkbench,fengzhyuan/visionworkbench,DougFirErickson/visionworkbench,AveRapina/visionworkbench,DougFirErickson/visionworkbench,fengzhyuan/visionworkbench,AveRapina/visionworkbench,fengzhyuan/visionworkbench,fengzhyuan/visionworkbench,AveRapina/visionworkbench,AveRapina/visionworkbench
|
d8738e75ae9c4547e1463914af3b6eafda9e0f05
|
paxos/group.cc
|
paxos/group.cc
|
// Copyright (c) 2016 Mirants Lu. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "paxos/group.h"
#include <unistd.h>
#include "util/mutexlock.h"
#include "paxos/node_util.h"
namespace skywalker {
Group::Group(uint32_t group_id, uint64_t node_id,
const Options& options, Network* network)
: node_id_(node_id),
config_(group_id, node_id, options, network),
instance_(&config_),
loop_(config_.GetLoop()),
bg_loop_(),
lease_timeout_(10 * 1000 * 1000),
retrie_master_(false),
membership_machine_(options, &config_),
master_machine_(&config_),
queue_(&config_),
mutex_(),
cond_(&mutex_),
propose_end_(false) {
propose_cb_ = std::bind(&ProposeQueue::ProposeComplete, &queue_,
std::placeholders::_1, std::placeholders::_2);
instance_.SetProposeCompleteCallback(propose_cb_);
instance_.AddMachine(&membership_machine_);
instance_.AddMachine(&master_machine_);
}
bool Group::Start() {
if (config_.Init() && instance_.Init()) {
membership_machine_.Recover();
master_machine_.Recover();
return true;
} else {
return false;
}
}
void Group::SyncMembership() {
instance_.SyncData();
int i = 0;
while (true) {
if (i++ > 3) {
instance_.SyncData();
}
if (!membership_machine_.HasSyncMembership()) {
MachineContext* context(
new MachineContext(membership_machine_.GetMachineId()));
ProposeHandler f(std::bind(&Group::SyncMembershipInLoop, this, context));
Status status = NewPropose(f);
if (status.ok() || status.IsConflict()) {
break;
}
} else {
break;
}
usleep(30*1000);
}
}
void Group::SyncMembershipInLoop(MachineContext* context) {
if (!membership_machine_.HasSyncMembership()) {
const Membership& m(membership_machine_.GetMembership());
std::string s;
m.SerializeToString(&s);
instance_.OnPropose(s, context);
} else {
propose_cb_(context, Status::OK());
}
}
void Group::SyncMaster() {
bg_loop_.Loop();
bg_loop_.QueueInLoop([this]() {
TryBeMaster();
});
}
void Group::TryBeMaster() {
MasterState state(master_machine_.GetMasterState());
uint64_t now = NowMicros();
if (state.lease_time() <= now ||
(state.node_id() == node_id_ && !retrie_master_)) {
uint64_t lease_time = now + lease_timeout_;
MachineContext* context(
new MachineContext(master_machine_.GetMachineId(),
reinterpret_cast<void*>(&lease_time)));
ProposeHandler f(std::bind(&Group::TryBeMasterInLoop, this, context));
Status status = NewPropose(f);
if (status.ok() || status.IsConflict()) {
state = master_machine_.GetMasterState();
} else {
state.set_lease_time(NowMicros() + lease_timeout_);
}
}
if (retrie_master_) {
retrie_master_ = false;
}
bg_loop_.RunAt(state.lease_time(), [this]() {
TryBeMaster();
});
}
void Group::TryBeMasterInLoop(MachineContext* context) {
MasterState state(master_machine_.GetMasterState());
if (state.lease_time() <= NowMicros()) {
state.set_node_id(node_id_);
state.set_lease_time(lease_timeout_);
std::string s;
state.SerializeToString(&s);
instance_.OnPropose(s, context);
} else {
propose_cb_(context, Status::Conflict(Slice()));
}
}
void Group::OnPropose(const std::string& value,
MachineContext* context,
const ProposeCompleteCallback& cb) {
queue_.Put(std::bind(&Instance::OnPropose, &instance_, value, context), cb);
}
void Group::OnReceiveContent(const std::shared_ptr<Content>& c) {
loop_->QueueInLoop([c, this]() {
instance_.OnReceiveContent(c);
});
}
void Group::AddMember(const IpPort& ip, const ProposeCompleteCallback& cb) {
uint64_t node_id(MakeNodeId(ip));
MachineContext* context(
new MachineContext(membership_machine_.GetMachineId()));
queue_.Put(std::bind(&Group::AddMemberInLoop, this, node_id, context), cb);
}
void Group::AddMemberInLoop(uint64_t node_id, MachineContext* context) {
bool res = false;
const Membership& temp(membership_machine_.GetMembership());
for (int i = 0; i < temp.node_id_size(); ++i) {
if (node_id == temp.node_id(i)) {
res = true;
break;
}
}
if (res) {
propose_cb_(context, Status::OK());
} else {
Membership m(temp);
m.add_node_id(node_id);
std::string s;
m.SerializeToString(&s);
instance_.OnPropose(s, context);
}
}
void Group::RemoveMember(const IpPort& ip, const ProposeCompleteCallback& cb) {
uint64_t node_id(MakeNodeId(ip));
MachineContext* context(
new MachineContext(membership_machine_.GetMachineId()));
queue_.Put(std::bind(&Group::RemoveMemberInLoop, this, node_id, context), cb);
}
void Group::RemoveMemberInLoop(uint64_t node_id, MachineContext* context) {
bool res = false;
const Membership& temp(membership_machine_.GetMembership());
Membership m;
for (int i = 0; i < temp.node_id_size(); ++i) {
if (node_id == temp.node_id(i)) {
res = true;
} else {
m.add_node_id(temp.node_id(i));
}
}
if (!res) {
propose_cb_(context, Status::OK());
} else {
std::string s;
m.SerializeToString(&s);
instance_.OnPropose(s, context);
}
}
void Group::ReplaceMember(const IpPort& new_i, const IpPort& old_i,
const ProposeCompleteCallback& cb) {
uint64_t i(MakeNodeId(new_i));
uint64_t j(MakeNodeId(old_i));
MachineContext* context(
new MachineContext(membership_machine_.GetMachineId()));
queue_.Put(std::bind(&Group::ReplaceMemberInLoop, this, i, j, context), cb);
}
void Group::ReplaceMemberInLoop(uint64_t new_node_id, uint64_t old_node_id,
MachineContext* context) {
bool new_res = false;
bool old_res = false;
const Membership& temp(membership_machine_.GetMembership());
Membership m;
for (int i = 0; i < temp.node_id_size(); ++i) {
if (temp.node_id(i) == new_node_id) {
new_res = true;
}
if (temp.node_id(i) == old_node_id) {
old_res = true;
} else {
m.add_node_id(temp.node_id(i));
}
}
if (new_res && (!old_res)) {
propose_cb_(context, Status::OK());
} else {
if (!new_res) {
m.add_node_id(new_node_id);
}
std::string s;
m.SerializeToString(&s);
instance_.OnPropose(s, context);
}
}
Status Group::NewPropose(const ProposeHandler& f) {
MutexLock lock(&mutex_);
propose_end_ = false;
queue_.Put(f, std::bind(&Group::ProposeComplete, this,
std::placeholders::_1, std::placeholders::_2));
while (!propose_end_) {
cond_.Wait();
}
return result_;
}
void Group::ProposeComplete(MachineContext* context,
const Status& result) {
MutexLock lock(&mutex_);
delete context;
result_ = result;
propose_end_ = true;
cond_.Signal();
}
void Group::GetMembership(std::vector<IpPort>* result) const {
membership_machine_.GetMembership(result);
}
void Group::AddMachine(StateMachine* machine) {
instance_.AddMachine(machine);
}
void Group::RemoveMachine(StateMachine* machine) {
instance_.RemoveMachine(machine);
}
void Group::SetMasterLeaseTime(uint64_t micros) {
bg_loop_.QueueInLoop([micros, this]() {
if (micros < (5 *1000 * 1000)) {
lease_timeout_ = 5 * 1000 * 1000;
} else {
lease_timeout_ = micros;
}
});
}
bool Group::GetMaster(IpPort* i, uint64_t* version) const {
return master_machine_.GetMaster(i, version);
}
bool Group::IsMaster() const {
return master_machine_.IsMaster();
}
void Group::RetireMaster() {
bg_loop_.QueueInLoop([this]() {
retrie_master_ = true;
});
}
} // namespace skywalker
|
// Copyright (c) 2016 Mirants Lu. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "paxos/group.h"
#include <unistd.h>
#include "util/mutexlock.h"
#include "paxos/node_util.h"
namespace skywalker {
Group::Group(uint32_t group_id, uint64_t node_id,
const Options& options, Network* network)
: node_id_(node_id),
config_(group_id, node_id, options, network),
instance_(&config_),
loop_(config_.GetLoop()),
bg_loop_(),
lease_timeout_(10 * 1000 * 1000),
retrie_master_(false),
membership_machine_(options, &config_),
master_machine_(&config_),
queue_(&config_),
mutex_(),
cond_(&mutex_),
propose_end_(false) {
propose_cb_ = std::bind(&ProposeQueue::ProposeComplete, &queue_,
std::placeholders::_1, std::placeholders::_2);
instance_.SetProposeCompleteCallback(propose_cb_);
instance_.AddMachine(&membership_machine_);
instance_.AddMachine(&master_machine_);
}
bool Group::Start() {
if (config_.Init() && instance_.Init()) {
membership_machine_.Recover();
master_machine_.Recover();
return true;
} else {
return false;
}
}
void Group::SyncMembership() {
instance_.SyncData();
int i = 0;
while (true) {
if (i++ > 3) {
instance_.SyncData();
}
if (!membership_machine_.HasSyncMembership()) {
MachineContext* context(
new MachineContext(membership_machine_.GetMachineId()));
ProposeHandler f(std::bind(&Group::SyncMembershipInLoop, this, context));
Status status = NewPropose(f);
if (status.ok() || status.IsConflict()) {
break;
}
} else {
break;
}
usleep(30*1000);
}
}
void Group::SyncMembershipInLoop(MachineContext* context) {
if (!membership_machine_.HasSyncMembership()) {
const Membership& m(membership_machine_.GetMembership());
std::string s;
m.SerializeToString(&s);
instance_.OnPropose(s, context);
} else {
propose_cb_(context, Status::OK());
}
}
void Group::SyncMaster() {
bg_loop_.Loop();
bg_loop_.QueueInLoop([this]() {
TryBeMaster();
});
}
void Group::TryBeMaster() {
MasterState state(master_machine_.GetMasterState());
uint64_t next_time = state.lease_time();
uint64_t now = NowMicros();
if (state.lease_time() <= now ||
(state.node_id() == node_id_ && !retrie_master_)) {
uint64_t lease_time = now + lease_timeout_;
MachineContext* context(
new MachineContext(master_machine_.GetMachineId(),
reinterpret_cast<void*>(&lease_time)));
ProposeHandler f(std::bind(&Group::TryBeMasterInLoop, this, context));
NewPropose(f);
state = master_machine_.GetMasterState();
if (state.node_id() == node_id_) {
next_time = state.lease_time() - 100 * 1000;
} else {
next_time = state.lease_time();
}
}
if (retrie_master_) {
retrie_master_ = false;
}
bg_loop_.RunAt(next_time, [this]() {
TryBeMaster();
});
}
void Group::TryBeMasterInLoop(MachineContext* context) {
MasterState state(master_machine_.GetMasterState());
if (state.lease_time() <= NowMicros() || state.node_id() == node_id_) {
state.set_node_id(node_id_);
state.set_lease_time(lease_timeout_);
std::string s;
state.SerializeToString(&s);
instance_.OnPropose(s, context);
} else {
propose_cb_(context, Status::Conflict(Slice()));
}
}
void Group::OnPropose(const std::string& value,
MachineContext* context,
const ProposeCompleteCallback& cb) {
queue_.Put(std::bind(&Instance::OnPropose, &instance_, value, context), cb);
}
void Group::OnReceiveContent(const std::shared_ptr<Content>& c) {
loop_->QueueInLoop([c, this]() {
instance_.OnReceiveContent(c);
});
}
void Group::AddMember(const IpPort& ip, const ProposeCompleteCallback& cb) {
uint64_t node_id(MakeNodeId(ip));
MachineContext* context(
new MachineContext(membership_machine_.GetMachineId()));
queue_.Put(std::bind(&Group::AddMemberInLoop, this, node_id, context), cb);
}
void Group::AddMemberInLoop(uint64_t node_id, MachineContext* context) {
bool res = false;
const Membership& temp(membership_machine_.GetMembership());
for (int i = 0; i < temp.node_id_size(); ++i) {
if (node_id == temp.node_id(i)) {
res = true;
break;
}
}
if (res) {
propose_cb_(context, Status::OK());
} else {
Membership m(temp);
m.add_node_id(node_id);
std::string s;
m.SerializeToString(&s);
instance_.OnPropose(s, context);
}
}
void Group::RemoveMember(const IpPort& ip, const ProposeCompleteCallback& cb) {
uint64_t node_id(MakeNodeId(ip));
MachineContext* context(
new MachineContext(membership_machine_.GetMachineId()));
queue_.Put(std::bind(&Group::RemoveMemberInLoop, this, node_id, context), cb);
}
void Group::RemoveMemberInLoop(uint64_t node_id, MachineContext* context) {
bool res = false;
const Membership& temp(membership_machine_.GetMembership());
Membership m;
for (int i = 0; i < temp.node_id_size(); ++i) {
if (node_id == temp.node_id(i)) {
res = true;
} else {
m.add_node_id(temp.node_id(i));
}
}
if (!res) {
propose_cb_(context, Status::OK());
} else {
std::string s;
m.SerializeToString(&s);
instance_.OnPropose(s, context);
}
}
void Group::ReplaceMember(const IpPort& new_i, const IpPort& old_i,
const ProposeCompleteCallback& cb) {
uint64_t i(MakeNodeId(new_i));
uint64_t j(MakeNodeId(old_i));
MachineContext* context(
new MachineContext(membership_machine_.GetMachineId()));
queue_.Put(std::bind(&Group::ReplaceMemberInLoop, this, i, j, context), cb);
}
void Group::ReplaceMemberInLoop(uint64_t new_node_id, uint64_t old_node_id,
MachineContext* context) {
bool new_res = false;
bool old_res = false;
const Membership& temp(membership_machine_.GetMembership());
Membership m;
for (int i = 0; i < temp.node_id_size(); ++i) {
if (temp.node_id(i) == new_node_id) {
new_res = true;
}
if (temp.node_id(i) == old_node_id) {
old_res = true;
} else {
m.add_node_id(temp.node_id(i));
}
}
if (new_res && (!old_res)) {
propose_cb_(context, Status::OK());
} else {
if (!new_res) {
m.add_node_id(new_node_id);
}
std::string s;
m.SerializeToString(&s);
instance_.OnPropose(s, context);
}
}
Status Group::NewPropose(const ProposeHandler& f) {
MutexLock lock(&mutex_);
propose_end_ = false;
queue_.Put(f, std::bind(&Group::ProposeComplete, this,
std::placeholders::_1, std::placeholders::_2));
while (!propose_end_) {
cond_.Wait();
}
return result_;
}
void Group::ProposeComplete(MachineContext* context,
const Status& result) {
MutexLock lock(&mutex_);
delete context;
result_ = result;
propose_end_ = true;
cond_.Signal();
}
void Group::GetMembership(std::vector<IpPort>* result) const {
membership_machine_.GetMembership(result);
}
void Group::AddMachine(StateMachine* machine) {
instance_.AddMachine(machine);
}
void Group::RemoveMachine(StateMachine* machine) {
instance_.RemoveMachine(machine);
}
void Group::SetMasterLeaseTime(uint64_t micros) {
bg_loop_.QueueInLoop([micros, this]() {
if (micros < (5 *1000 * 1000)) {
lease_timeout_ = 5 * 1000 * 1000;
} else {
lease_timeout_ = micros;
}
});
}
bool Group::GetMaster(IpPort* i, uint64_t* version) const {
return master_machine_.GetMaster(i, version);
}
bool Group::IsMaster() const {
return master_machine_.IsMaster();
}
void Group::RetireMaster() {
bg_loop_.QueueInLoop([this]() {
retrie_master_ = true;
});
}
} // namespace skywalker
|
fix master propose
|
fix master propose
|
C++
|
bsd-3-clause
|
QiumingLu/skywalker,QiumingLu/skywalker
|
f7fda09b599ae1d27152535eb285e4819542ae83
|
src/wx/main_toolbar.cpp
|
src/wx/main_toolbar.cpp
|
/*
* This file is part of Poedit (http://poedit.net)
*
* Copyright (C) 2014-2016 Vaclav Slavik
*
* 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 "main_toolbar.h"
#include <wx/intl.h>
#include <wx/toolbar.h>
#include <wx/xrc/xmlres.h>
class WXMainToolbar : public MainToolbar
{
public:
WXMainToolbar(wxFrame *parent)
{
m_tb = wxXmlResource::Get()->LoadToolBar(parent, "toolbar");
m_idFuzzy = XRCID("menu_fuzzy");
m_idUpdate = XRCID("toolbar_update");
#ifdef __WXMSW__
// De-uglify the toolbar a bit on Windows 10:
int osmajor = 0;
if (wxGetOsVersion(&osmajor, nullptr) == wxOS_WINDOWS_NT && osmajor == 10)
{
m_tb->SetBackgroundColour(*wxWHITE);
}
#endif
}
bool IsFuzzy() const override
{
return m_tb->GetToolState(m_idFuzzy);
}
void SetFuzzy(bool on) override
{
m_tb->ToggleTool(m_idFuzzy, on);
}
void EnableSyncWithCrowdin(bool on) override
{
auto tool = m_tb->FindById(m_idUpdate);
if (on)
{
tool->SetLabel(_("Sync"));
tool->SetShortHelp(_("Synchronize the translation with Crowdin"));
m_tb->SetToolNormalBitmap(m_idUpdate, wxArtProvider::GetBitmap("poedit-sync"));
}
else
{
tool->SetLabel(_("Update"));
tool->SetShortHelp(_("Update catalog - synchronize it with sources"));
m_tb->SetToolNormalBitmap(m_idUpdate, wxArtProvider::GetBitmap("poedit-update"));
}
}
private:
wxToolBar *m_tb;
int m_idFuzzy, m_idUpdate;
};
std::unique_ptr<MainToolbar> MainToolbar::CreateWX(wxFrame *parent)
{
return std::unique_ptr<MainToolbar>(new WXMainToolbar(parent));
}
std::unique_ptr<MainToolbar> MainToolbar::Create(wxFrame *parent)
{
return CreateWX(parent);
}
|
/*
* This file is part of Poedit (http://poedit.net)
*
* Copyright (C) 2014-2016 Vaclav Slavik
*
* 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 "main_toolbar.h"
#include <wx/intl.h>
#include <wx/settings.h>
#include <wx/toolbar.h>
#include <wx/xrc/xmlres.h>
class WXMainToolbar : public MainToolbar
{
public:
WXMainToolbar(wxFrame *parent)
{
m_tb = wxXmlResource::Get()->LoadToolBar(parent, "toolbar");
m_idFuzzy = XRCID("menu_fuzzy");
m_idUpdate = XRCID("toolbar_update");
#ifdef __WXMSW__
// De-uglify the toolbar a bit on Windows 10:
int osmajor = 0;
if (wxGetOsVersion(&osmajor, nullptr) == wxOS_WINDOWS_NT && osmajor == 10)
{
auto menuClr = wxSystemSettings::GetColour(wxSYS_COLOUR_MENUBAR);
// Windows 10 lies about this color. Check it for the default value, which is
// a shade of gray even though the menubar is actually white, and change it to
// white. This way other colors, e.g. from hi-contrast themes, will be preserved.
if (menuClr.GetRGB() == 0xF0F0F0)
menuClr.SetRGB(0xFFFFFF);
m_tb->SetBackgroundColour(menuClr);
}
#endif
}
bool IsFuzzy() const override
{
return m_tb->GetToolState(m_idFuzzy);
}
void SetFuzzy(bool on) override
{
m_tb->ToggleTool(m_idFuzzy, on);
}
void EnableSyncWithCrowdin(bool on) override
{
auto tool = m_tb->FindById(m_idUpdate);
if (on)
{
tool->SetLabel(_("Sync"));
tool->SetShortHelp(_("Synchronize the translation with Crowdin"));
m_tb->SetToolNormalBitmap(m_idUpdate, wxArtProvider::GetBitmap("poedit-sync"));
}
else
{
tool->SetLabel(_("Update"));
tool->SetShortHelp(_("Update catalog - synchronize it with sources"));
m_tb->SetToolNormalBitmap(m_idUpdate, wxArtProvider::GetBitmap("poedit-update"));
}
}
private:
wxToolBar *m_tb;
int m_idFuzzy, m_idUpdate;
};
std::unique_ptr<MainToolbar> MainToolbar::CreateWX(wxFrame *parent)
{
return std::unique_ptr<MainToolbar>(new WXMainToolbar(parent));
}
std::unique_ptr<MainToolbar> MainToolbar::Create(wxFrame *parent)
{
return CreateWX(parent);
}
|
Fix Windows 10 toolbar for high-contrast themes
|
Fix Windows 10 toolbar for high-contrast themes
|
C++
|
mit
|
alexhenrie/poedit,PKRoma/poedit,c72578/poedit,nawawi/poedit,BenKeyFSI/poedit,vslavik/poedit,c72578/poedit,c72578/poedit,PKRoma/poedit,alexhenrie/poedit,nawawi/poedit,BenKeyFSI/poedit,vslavik/poedit,nawawi/poedit,nawawi/poedit,PKRoma/poedit,BenKeyFSI/poedit,nawawi/poedit,alexhenrie/poedit,BenKeyFSI/poedit,alexhenrie/poedit,PKRoma/poedit,c72578/poedit,BenKeyFSI/poedit,alexhenrie/poedit,vslavik/poedit,vslavik/poedit,PKRoma/poedit,c72578/poedit,vslavik/poedit
|
ff113a74bf9479e37c3dcab52c3893a000d2b37a
|
src/xmppproxystream.cpp
|
src/xmppproxystream.cpp
|
#include <xmppproxystream.h>
#include <xmppproxy.h>
#include <sys/socket.h>
#include <arpa/inet.h>
//#include <netinet/in.h>
//#include <netdb.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <string.h>
using namespace std;
/**
* Конструктор
*/
XMPPProxyStream::XMPPProxyStream(XMPPProxy *prx):
proxy(prx), AsyncStream(0),
ready_read(false), ready_write(false),
pair(0), finish_count(0)
{
rx = rxsec = rxsec_limit = rxsec_switch = 0;
}
/**
* Конструктор потока XMPP-прокси
*
* @param prx ссылка на прокси
* @param s ссылка на противоположный сокет
* @param socket сокет
*/
XMPPProxyStream::XMPPProxyStream(class XMPPProxy *prx, XMPPProxyStream *s, int socket):
proxy(prx), AsyncStream(socket),
ready_read(true), ready_write(false),
pair(s), finish_count(0)
{
rx = rxsec = rxsec_limit = rxsec_switch = 0;
}
/**
* Деструктор
*/
XMPPProxyStream::~XMPPProxyStream()
{
}
/**
* Принять сокет
* @param sock принимаемый сокет
* @param ip IP сервера к которому надо приконнектисться
* @param port порт сервера
* @return TRUE - сокет принят, FALSE сокет отклонен
*/
bool XMPPProxyStream::accept(int sock, const char *ip, int port)
{
struct sockaddr_in target;
// Клиент который к нам приконнектился
fd = sock;
// Сервер к которому мы коннектимся
int server_socket = ::socket(PF_INET, SOCK_STREAM, 0);
if ( server_socket <= 0 ) return false;
target.sin_family = AF_INET;
target.sin_port = htons(port);
inet_pton(AF_INET, ip, &(target.sin_addr));
memset(target.sin_zero, '\0', 8);
if ( ::connect(server_socket, (struct sockaddr *)&target, sizeof( struct sockaddr )) == 0 )
{
fcntl(server_socket, F_SETFL, O_NONBLOCK);
this->pair = new XMPPProxyStream(proxy, this, server_socket);
ready_read = true;
proxy->daemon->addObject(this);
proxy->daemon->addObject(this->pair);
return true;
}
::close(server_socket);
// shit!
fprintf(stderr, "connect() fault\n");
::shutdown(fd, SHUT_RDWR);
return false;
}
/**
* Вернуть маску ожидаемых событий
*/
uint32_t XMPPProxyStream::getEventsMask()
{
uint32_t mask = EPOLLRDHUP | EPOLLONESHOT | EPOLLHUP | EPOLLERR;
if ( ready_read && ((rxsec_limit == 0) || (rxsec < rxsec_limit)) ) mask |= EPOLLIN;
if ( ready_write ) mask |= EPOLLOUT;
return mask;
}
/**
* Таймер-функция разблокировки потока
* @param data указатель на XMPPProxyStream который надо разблочить
*/
void XMPPProxyStream::unblock(int wid, void *data)
{
XMPPProxyStream *stream = static_cast<XMPPProxyStream *>(data);
fprintf(stderr, "unlock stream: %d\n", stream->fd);
stream->rxsec = 0;
stream->proxy->daemon->modifyObject(stream);
stream->finish(); // костыль однако
}
/**
* Событие готовности к чтению
*
* Вызывается когда в потоке есть данные,
* которые можно прочитать без блокирования
*/
void XMPPProxyStream::onRead()
{
ssize_t r = read(pair->buffer, sizeof(pair->buffer));
fprintf(stderr, "#%d: [XMPPProxyStream] read from: %d, size: %d\n", getWorkerId(), fd, r);
if ( r > 0 )
{
rx += r;
pair->len = r;
pair->written = 0;
//if ( ! pair->writeChunk() )
{
ready_read = false;
pair->ready_write = true;
proxy->daemon->modifyObject(pair);
}
// проверка ограничений
if ( rxsec_limit > 0 )
{
time_t tm = time(0);
int mask = tm & 1;
if ( rxsec_switch != mask )
{
rxsec = 0;
rxsec_switch = mask;
}
rxsec += r;
if ( rxsec > rxsec_limit )
{
fprintf(stderr, "recieved %d bytes per second, block for a while: %d\n", rxsec, fd);
lock(); // костыль однако
proxy->daemon->setTimer(tm+5, unblock, this);
}
}
}
}
/**
* Записать кусок
* @return TRUE всё записал, FALSE ничего не записал или только часть
*/
bool XMPPProxyStream::writeChunk()
{
ssize_t r = write(buffer + written, len - written);
if ( r > 0 )
{
fprintf(stderr, "#%d: [XMPPProxyStream] written to: %d, size: %d, remain: %d\n", getWorkerId(), fd, r, len - r);
len -= r;
written += r;
return len == 0;
}
return false;
}
/**
* Событие готовности к записи
*
* Вызывается, когда в поток готов принять
* данные для записи без блокировки
*/
void XMPPProxyStream::onWrite()
{
if ( writeChunk() )
{
ready_write = false;
pair->ready_read = true;
proxy->daemon->modifyObject(pair);
}
}
/**
* Блокировка потка от удаления
*/
void XMPPProxyStream::lock()
{
mutex.lock();
int x = --finish_count;
fprintf(stderr, "#%d: [XMPPProxyStream: %d] lock %d\n", getWorkerId(), fd, x);
mutex.unlock();
}
/**
* Финализация
*/
void XMPPProxyStream::finish()
{
int x;
mutex.lock();
x = ++finish_count;
fprintf(stderr, "#%d: [XMPPProxyStream: %d] finish %d\n", getWorkerId(), fd, x);
mutex.unlock();
if ( x == 1 )
{
::shutdown(pair->fd, SHUT_RDWR);
}
if ( x == 2 )
{
//proxy->daemon->removeObject(this);
delete this;
}
}
/**
* Пир (peer) закрыл поток.
*
* Мы уже ничего не можем отправить в ответ,
* можем только корректно закрыть соединение с нашей стороны.
*/
void XMPPProxyStream::onPeerDown()
{
fprintf(stderr, "#%d: [XMPPProxyStream: %d] peer down\n", getWorkerId(), fd);
::shutdown(pair->fd, SHUT_RDWR);
proxy->daemon->removeObject(this);
finish();
pair->finish();
}
/**
* Пир (peer) закрыл поток.
*
* Мы уже ничего не можем отправить в ответ,
* можем только корректно закрыть соединение с нашей стороны.
*/
void XMPPProxyStream::onShutdown()
{
fprintf(stderr, "#%d: [XMPPProxyStream: %d] shutdown\n", getWorkerId(), fd);
::shutdown(pair->fd, SHUT_RDWR);
proxy->daemon->removeObject(this);
terminate();
}
/**
* Сигнал завершения работы
*
* Сервер решил закрыть соединение, здесь ещё есть время
* корректно попрощаться с пиром (peer).
*/
void XMPPProxyStream::onTerminate()
{
fprintf(stderr, "#%d: [XMPPProxyStream: %d] onTerminate\n", getWorkerId(), fd);
::shutdown(fd, SHUT_RDWR);
::shutdown(pair->fd, SHUT_RDWR);
}
|
#include <xmppproxystream.h>
#include <xmppproxy.h>
#include <sys/socket.h>
#include <arpa/inet.h>
//#include <netinet/in.h>
//#include <netdb.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <string.h>
using namespace std;
/**
* Конструктор
*/
XMPPProxyStream::XMPPProxyStream(XMPPProxy *prx):
proxy(prx), AsyncStream(0),
ready_read(false), ready_write(false),
pair(0), finish_count(0)
{
rx = rxsec = rxsec_limit = rxsec_switch = 0;
}
/**
* Конструктор потока XMPP-прокси
*
* @param prx ссылка на прокси
* @param s ссылка на противоположный сокет
* @param socket сокет
*/
XMPPProxyStream::XMPPProxyStream(class XMPPProxy *prx, XMPPProxyStream *s, int socket):
proxy(prx), AsyncStream(socket),
ready_read(true), ready_write(false),
pair(s), finish_count(0)
{
rx = rxsec = rxsec_limit = rxsec_switch = 0;
}
/**
* Деструктор
*/
XMPPProxyStream::~XMPPProxyStream()
{
}
/**
* Принять сокет
* @param sock принимаемый сокет
* @param ip IP сервера к которому надо приконнектисться
* @param port порт сервера
* @return TRUE - сокет принят, FALSE сокет отклонен
*/
bool XMPPProxyStream::accept(int sock, const char *ip, int port)
{
struct sockaddr_in target;
// Клиент который к нам приконнектился
fd = sock;
// Сервер к которому мы коннектимся
int server_socket = ::socket(PF_INET, SOCK_STREAM, 0);
if ( server_socket <= 0 ) return false;
target.sin_family = AF_INET;
target.sin_port = htons(port);
inet_pton(AF_INET, ip, &(target.sin_addr));
memset(target.sin_zero, '\0', 8);
if ( ::connect(server_socket, (struct sockaddr *)&target, sizeof( struct sockaddr )) == 0 )
{
fcntl(server_socket, F_SETFL, O_NONBLOCK);
this->pair = new XMPPProxyStream(proxy, this, server_socket);
ready_read = true;
proxy->daemon->addObject(this);
proxy->daemon->addObject(this->pair);
return true;
}
::close(server_socket);
// shit!
fprintf(stderr, "connect() fault\n");
::shutdown(fd, SHUT_RDWR);
return false;
}
/**
* Вернуть маску ожидаемых событий
*/
uint32_t XMPPProxyStream::getEventsMask()
{
uint32_t mask = EPOLLRDHUP | EPOLLONESHOT | EPOLLHUP | EPOLLERR;
if ( ready_read && ((rxsec_limit == 0) || (rxsec < rxsec_limit)) ) mask |= EPOLLIN;
if ( ready_write ) mask |= EPOLLOUT;
return mask;
}
/**
* Таймер-функция разблокировки потока
* @param data указатель на XMPPProxyStream который надо разблочить
*/
void XMPPProxyStream::unblock(int wid, void *data)
{
XMPPProxyStream *stream = static_cast<XMPPProxyStream *>(data);
fprintf(stderr, "unlock stream: %d\n", stream->fd);
stream->rxsec = 0;
stream->proxy->daemon->modifyObject(stream);
stream->finish(); // костыль однако
}
/**
* Событие готовности к чтению
*
* Вызывается когда в потоке есть данные,
* которые можно прочитать без блокирования
*/
void XMPPProxyStream::onRead()
{
ssize_t r = read(pair->buffer, sizeof(pair->buffer));
fprintf(stderr, "#%d: [XMPPProxyStream] read from: %d, size: %d\n", getWorkerId(), fd, r);
if ( r > 0 )
{
rx += r;
pair->len = r;
pair->written = 0;
//if ( ! pair->writeChunk() )
{
ready_read = false;
pair->ready_write = true;
proxy->daemon->modifyObject(pair);
}
// проверка ограничений
if ( rxsec_limit > 0 )
{
time_t tm = time(0);
int mask = tm & 1;
if ( rxsec_switch != mask )
{
rxsec = 0;
rxsec_switch = mask;
}
rxsec += r;
if ( rxsec > rxsec_limit )
{
fprintf(stderr, "recieved %d bytes per second, block for a while: %d\n", rxsec, fd);
lock(); // костыль однако
proxy->daemon->setTimer(tm+1, unblock, this);
}
}
}
}
/**
* Записать кусок
* @return TRUE всё записал, FALSE ничего не записал или только часть
*/
bool XMPPProxyStream::writeChunk()
{
ssize_t r = write(buffer + written, len - written);
if ( r > 0 )
{
fprintf(stderr, "#%d: [XMPPProxyStream] written to: %d, size: %d, remain: %d\n", getWorkerId(), fd, r, len - r);
len -= r;
written += r;
return len == 0;
}
return false;
}
/**
* Событие готовности к записи
*
* Вызывается, когда в поток готов принять
* данные для записи без блокировки
*/
void XMPPProxyStream::onWrite()
{
if ( writeChunk() )
{
ready_write = false;
pair->ready_read = true;
proxy->daemon->modifyObject(pair);
}
}
/**
* Блокировка потка от удаления
*/
void XMPPProxyStream::lock()
{
mutex.lock();
int x = --finish_count;
fprintf(stderr, "#%d: [XMPPProxyStream: %d] lock %d\n", getWorkerId(), fd, x);
mutex.unlock();
}
/**
* Финализация
*/
void XMPPProxyStream::finish()
{
int x;
mutex.lock();
x = ++finish_count;
fprintf(stderr, "#%d: [XMPPProxyStream: %d] finish %d\n", getWorkerId(), fd, x);
mutex.unlock();
if ( x == 1 )
{
::shutdown(pair->fd, SHUT_RDWR);
}
if ( x == 2 )
{
//proxy->daemon->removeObject(this);
delete this;
}
}
/**
* Пир (peer) закрыл поток.
*
* Мы уже ничего не можем отправить в ответ,
* можем только корректно закрыть соединение с нашей стороны.
*/
void XMPPProxyStream::onPeerDown()
{
fprintf(stderr, "#%d: [XMPPProxyStream: %d] peer down\n", getWorkerId(), fd);
::shutdown(pair->fd, SHUT_RDWR);
proxy->daemon->removeObject(this);
finish();
pair->finish();
}
/**
* Пир (peer) закрыл поток.
*
* Мы уже ничего не можем отправить в ответ,
* можем только корректно закрыть соединение с нашей стороны.
*/
void XMPPProxyStream::onShutdown()
{
fprintf(stderr, "#%d: [XMPPProxyStream: %d] shutdown\n", getWorkerId(), fd);
::shutdown(pair->fd, SHUT_RDWR);
proxy->daemon->removeObject(this);
terminate();
}
/**
* Сигнал завершения работы
*
* Сервер решил закрыть соединение, здесь ещё есть время
* корректно попрощаться с пиром (peer).
*/
void XMPPProxyStream::onTerminate()
{
fprintf(stderr, "#%d: [XMPPProxyStream: %d] onTerminate\n", getWorkerId(), fd);
::shutdown(fd, SHUT_RDWR);
::shutdown(pair->fd, SHUT_RDWR);
}
|
fix время блокировки 1 сек
|
fix время блокировки 1 сек
|
C++
|
mit
|
WST/mawar,WST/mawar
|
93e2fa488740a68604a4069ac61eba398de7275d
|
test/CXX/expr/expr.prim/expr.prim.lambda/p8.cpp
|
test/CXX/expr/expr.prim/expr.prim.lambda/p8.cpp
|
// RUN: %clang_cc1 -std=c++11 %s -verify
class X0 {
void explicit_capture() {
int foo;
(void)[foo, foo] () {}; // expected-error {{'foo' can appear only once}}
(void)[this, this] () {}; // expected-error {{'this' can appear only once}}
(void)[=, foo] () {}; // expected-error {{'&' must precede a capture when}}
(void)[=, &foo] () {};
(void)[=, this] () {}; // expected-error {{'this' cannot appear}}
(void)[&, foo] () {};
(void)[&, &foo] () {}; // expected-error {{'&' cannot precede a capture when}}
(void)[&, this] () {};
}
};
|
// RUN: %clang_cc1 -std=c++11 %s -verify
class X0 {
void explicit_capture() {
int foo;
(void)[foo, foo] () {}; // expected-error {{'foo' can appear only once}}
(void)[this, this] () {}; // expected-error {{'this' can appear only once}}
(void)[=, foo] () {}; // expected-error {{'&' must precede a capture when}}
(void)[=, &foo] () {};
(void)[=, this] () {}; // expected-error {{'this' cannot appear}}
(void)[&, foo] () {};
(void)[&, &foo] () {}; // expected-error {{'&' cannot precede a capture when}}
(void)[&, this] () {};
}
};
struct S2 { void f(int i); };
void S2::f(int i) {
(void)[&, i]{ };
(void)[&, &i]{ }; // expected-error{{'&' cannot precede a capture when the capture default is '&'}}
(void)[=, this]{ }; // expected-error{{'this' cannot appear in a capture list when the capture default is '='}}
(void)[i, i]{ }; // expected-error{{'i' can appear only once in a capture list}}
}
|
Add a lambda example from the working draft.
|
Add a lambda example from the working draft.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@150239 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang
|
65b0194d0db553fec1e60c59e8d5487315a4a731
|
include/config_third.hpp
|
include/config_third.hpp
|
//=======================================================================
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef WORD_SPOTTER_CONFIG_THIRD_HPP
#define WORD_SPOTTER_CONFIG_THIRD_HPP
namespace third {
//#define THIRD_RBM_1 //One layer of RBM
//#define THIRD_RBM_2 //Two layers of RBM
//#define THIRD_RBM_3 //Three layers of RBM
//#define THIRD_CRBM_PMP_1 //One layer of CRBM with Probabilistic Max Pooling (C1)
//#define THIRD_CRBM_PMP_2 //Two layers of CRBM with Probabilistic Max Pooling (C1/C2)
//#define THIRD_CRBM_PMP_3 //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3)
//#define THIRD_CRBM_MP_1 //One layers of CRBM with Max Pooling after each layer (C1)
#define THIRD_CRBM_MP_2 //Two layers of CRBM with Max Pooling after each layer (C1/C2)
//#define THIRD_CRBM_MP_3 //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3)
//#define THIRD_PATCH_CRBM_MP_2 //Patches -> Two layers of CRBM with Max Pooling after each layer (C1/C2)
//#define THIRD_COMPLEX_2 //Architecture to play around LCN
//#define THIRD_MODERN //Architecture to play around
constexpr const std::size_t patch_height = 40; //Should not be changed
constexpr const std::size_t patch_width = 20;
// Data augmentation
constexpr const std::size_t elastic_augment = 1; //not ready
constexpr const std::size_t epochs = 10;
constexpr const std::size_t train_stride = 1;
constexpr const std::size_t test_stride = 1;
constexpr const std::size_t NF1 = 9; // 9 for ALL
constexpr const std::size_t K1 = 7; // 7 for GW, 12 for PAR/IAM
constexpr const std::size_t C1 = 2; // 2 for ALL
constexpr const std::size_t B1 = 128; // 128 for GW, 256 for PAR/IAM
constexpr const dll::unit_type VT1 = dll::unit_type::BINARY; // BINARY for ALL
constexpr const dll::unit_type HT1 = dll::unit_type::RELU1; // RELU1 for ALL
constexpr const dll::decay_type DT1 = dll::decay_type::L2; // L2 for ALL
constexpr const dll::sparsity_method SM1 = dll::sparsity_method::NONE; // NONE for ALL
constexpr const bool shuffle_1 = false; // false for ALL
constexpr const bool clipping_1 = true; // true for ALL
constexpr const std::size_t NF2 = 3; // 3 for ALL
constexpr const std::size_t K2 = 7; // 7 for GW, 12 for PAR/IAM
constexpr const std::size_t C2 = 2; // 2 for ALL
constexpr const std::size_t B2 = 128; // 128 for GW, 256 for PAR/IAM
constexpr const dll::unit_type VT2 = dll::unit_type::BINARY; // BINARY for ALL
constexpr const dll::unit_type HT2 = dll::unit_type::RELU6; // RELU6 for ALL
constexpr const dll::decay_type DT2 = dll::decay_type::L2; // L2 for ALL
constexpr const dll::sparsity_method SM2 = dll::sparsity_method::NONE; // NONE for ALL
constexpr const bool shuffle_2 = false; // false for ALL
constexpr const bool clipping_2 = true; // true for ALL
constexpr const std::size_t NF3 = 3;
constexpr const std::size_t K3 = 48;
constexpr const std::size_t C3 = 2;
constexpr const std::size_t B3 = 64;
constexpr const dll::unit_type VT3 = dll::unit_type::BINARY; // BINARY for ALL
constexpr const dll::unit_type HT3 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT3 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE;
constexpr const bool shuffle_3 = true;
constexpr const bool clipping_3 = false;
const auto rate_0 = [](weight& value) { value = 1e-4; }; //1e-4 for all ?
const auto rate_1 = [](weight& value) { value = 1e-6; }; //1e-6 for all ?
const auto rate_2 = [](weight& value) { value = 1.0 * value; };
const auto momentum_0 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_1 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_2 = [](weight& ini, weight& fin) { ini = 1.0 * ini; fin = 1.0 * fin; };
const auto wd_l1_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_2 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_2 = [](weight& value) { value = 1.0 * value; };
const auto pbias_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_2 = [](weight& value) { value = 1.0 * value; };
#if defined(THIRD_CRBM_MP_2) || defined(THIRD_PATCH_CRBM_MP_2)
const auto pbias_lambda_0 = [](weight& value) { value = 10.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 10.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };
#else
const auto pbias_lambda_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };
#endif
const auto sparsity_target_0 = [](weight& value) { value = 10.0 * value; };
const auto sparsity_target_1 = [](weight& value) { value = 10.0 * value; };
const auto sparsity_target_2 = [](weight& value) { value = 1.0 * value; };
const auto clip_norm_1 = [](weight& t) { t = 5.0; };
const auto clip_norm_2 = [](weight& t) { t = 5.0; };
const auto clip_norm_3 = [](weight& t) { t = 5.0; };
} // end of namespace third
#endif
|
//=======================================================================
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef WORD_SPOTTER_CONFIG_THIRD_HPP
#define WORD_SPOTTER_CONFIG_THIRD_HPP
namespace third {
//#define THIRD_RBM_1 //One layer of RBM
//#define THIRD_RBM_2 //Two layers of RBM
//#define THIRD_RBM_3 //Three layers of RBM
//#define THIRD_CRBM_PMP_1 //One layer of CRBM with Probabilistic Max Pooling (C1)
//#define THIRD_CRBM_PMP_2 //Two layers of CRBM with Probabilistic Max Pooling (C1/C2)
//#define THIRD_CRBM_PMP_3 //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3)
//#define THIRD_CRBM_MP_1 //One layers of CRBM with Max Pooling after each layer (C1)
#define THIRD_CRBM_MP_2 //Two layers of CRBM with Max Pooling after each layer (C1/C2)
//#define THIRD_CRBM_MP_3 //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3)
//#define THIRD_PATCH_CRBM_MP_2 //Patches -> Two layers of CRBM with Max Pooling after each layer (C1/C2)
//#define THIRD_COMPLEX_2 //Architecture to play around LCN
//#define THIRD_MODERN //Architecture to play around
constexpr const std::size_t patch_height = 40; //Should not be changed
constexpr const std::size_t patch_width = 20;
// Data augmentation
constexpr const std::size_t elastic_augment = 0; //not ready
constexpr const std::size_t epochs = 10;
constexpr const std::size_t train_stride = 1;
constexpr const std::size_t test_stride = 1;
constexpr const std::size_t NF1 = 9; // 9 for ALL
constexpr const std::size_t K1 = 7; // 7 for GW, 12 for PAR/IAM
constexpr const std::size_t C1 = 2; // 2 for ALL
constexpr const std::size_t B1 = 128; // 128 for GW, 256 for PAR/IAM
constexpr const dll::unit_type VT1 = dll::unit_type::BINARY; // BINARY for ALL
constexpr const dll::unit_type HT1 = dll::unit_type::RELU1; // RELU1 for ALL
constexpr const dll::decay_type DT1 = dll::decay_type::L2; // L2 for ALL
constexpr const dll::sparsity_method SM1 = dll::sparsity_method::NONE; // NONE for ALL
constexpr const bool shuffle_1 = false; // false for ALL
constexpr const bool clipping_1 = true; // true for ALL
constexpr const std::size_t NF2 = 3; // 3 for ALL
constexpr const std::size_t K2 = 7; // 7 for GW, 12 for PAR/IAM
constexpr const std::size_t C2 = 2; // 2 for ALL
constexpr const std::size_t B2 = 128; // 128 for GW, 256 for PAR/IAM
constexpr const dll::unit_type VT2 = dll::unit_type::BINARY; // BINARY for ALL
constexpr const dll::unit_type HT2 = dll::unit_type::RELU6; // RELU6 for ALL
constexpr const dll::decay_type DT2 = dll::decay_type::L2; // L2 for ALL
constexpr const dll::sparsity_method SM2 = dll::sparsity_method::NONE; // NONE for ALL
constexpr const bool shuffle_2 = false; // false for ALL
constexpr const bool clipping_2 = true; // true for ALL
constexpr const std::size_t NF3 = 3;
constexpr const std::size_t K3 = 48;
constexpr const std::size_t C3 = 2;
constexpr const std::size_t B3 = 64;
constexpr const dll::unit_type VT3 = dll::unit_type::BINARY; // BINARY for ALL
constexpr const dll::unit_type HT3 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT3 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE;
constexpr const bool shuffle_3 = true;
constexpr const bool clipping_3 = false;
const auto rate_0 = [](weight& value) { value = 1e-4; }; //1e-4 for all ?
const auto rate_1 = [](weight& value) { value = 1e-6; }; //1e-6 for all ?
const auto rate_2 = [](weight& value) { value = 1.0 * value; };
const auto momentum_0 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_1 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_2 = [](weight& ini, weight& fin) { ini = 1.0 * ini; fin = 1.0 * fin; };
const auto wd_l1_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_2 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_2 = [](weight& value) { value = 1.0 * value; };
const auto pbias_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_2 = [](weight& value) { value = 1.0 * value; };
#if defined(THIRD_CRBM_MP_2) || defined(THIRD_PATCH_CRBM_MP_2)
const auto pbias_lambda_0 = [](weight& value) { value = 10.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 10.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };
#else
const auto pbias_lambda_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };
#endif
const auto sparsity_target_0 = [](weight& value) { value = 10.0 * value; };
const auto sparsity_target_1 = [](weight& value) { value = 10.0 * value; };
const auto sparsity_target_2 = [](weight& value) { value = 1.0 * value; };
const auto clip_norm_1 = [](weight& t) { t = 5.0; };
const auto clip_norm_2 = [](weight& t) { t = 5.0; };
const auto clip_norm_3 = [](weight& t) { t = 5.0; };
} // end of namespace third
#endif
|
Disable elastic augmentation
|
Disable elastic augmentation
|
C++
|
mit
|
wichtounet/word_spotting,wichtounet/word_spotting,wichtounet/word_spotting
|
6e1723b85a1b601313e965e73d6da7bb4bb3445a
|
src/abaclade/io/text/file.cxx
|
src/abaclade/io/text/file.cxx
|
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2010, 2011, 2012, 2013, 2014
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abaclade.hxx>
#include <abaclade/io/text/file.hxx>
#include <abaclade/io/binary/file.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::io::text globals
namespace abc {
namespace io {
namespace text {
namespace {
std::shared_ptr<binbuf_writer> g_ptwStdErr;
std::shared_ptr<binbuf_reader> g_ptrStdIn;
std::shared_ptr<binbuf_writer> g_ptwStdOut;
/*! Instantiates a text::base specialization appropriate for the specified binary I/O object,
returning a shared pointer to it. If the binary I/O object does not implement buffering, a buffered
I/O wrapper is instanciated as well.
pbb
Pointer to a binary I/O object.
return
Shared pointer to the newly created object.
*/
std::shared_ptr<binbuf_base> _construct(
std::shared_ptr<binary::base> pbb, abc::text::encoding enc
) {
ABC_TRACE_FUNC(pbb, enc);
// Choose what type of text I/O object to create based on what type of binary I/O object we got.
// Check if it’s a buffered I/O object.
auto pbbr(std::dynamic_pointer_cast<binary::buffered_reader>(pbb));
auto pbbw(std::dynamic_pointer_cast<binary::buffered_writer>(pbb));
if (!pbbr && !pbbw) {
// Not a buffered I/O object? Get one then, and try again with the casts.
auto pbbb(binary::buffer(pbb));
pbbr = std::dynamic_pointer_cast<binary::buffered_reader>(pbbb);
pbbw = std::dynamic_pointer_cast<binary::buffered_writer>(pbbb);
}
// Now we must have a buffered reader or writer, or pbb is not something we can use.
if (pbbr) {
return std::make_shared<binbuf_reader>(std::move(pbbr), enc);
}
if (pbbw) {
return std::make_shared<binbuf_writer>(std::move(pbbw), enc);
}
// TODO: use a better exception class.
ABC_THROW(argument_error, ());
}
/*! Detects the encoding to use for a standard text I/O file, with the help of an optional
environment variable.
TODO: document this behavior and the related enviroment variables.
TODO: change to use a global “environment” map object instead of this ad-hoc code.
TODO: make the below code only pick up variables meant for this PID. This should eventually be made
more general, as a way for an Abaclade-based parent process to communicate with an Abaclade-based
child process. Thought maybe a better way is to pass a command-line argument that triggers Abaclade-
specific behavior, so that it’s inherently PID-specific.
pszEnvVarName
Environment variable name that, if set, specifies the encoding to be used.
return
Encoding appropriate for the requested standard I/O file.
*/
std::shared_ptr<binbuf_base> _construct_stdio(
std::shared_ptr<binary::base> pbb, char_t const * pszEnvVarName
) {
ABC_TRACE_FUNC(pbb, pszEnvVarName);
abc::text::encoding enc;
if (std::dynamic_pointer_cast<binary::console_file_base>(pbb)) {
// Console files can only perform I/O in the host platform’s encoding, so force the correct
// encoding here.
enc = abc::text::encoding::host;
} else {
// In all other cases, allow selecting the encoding via environment variable.
#if ABC_HOST_API_POSIX
istr sEnc;
if (char_t const * pszEnvVarValue = ::getenv(pszEnvVarName)) {
sEnc = istr(external_buffer, pszEnvVarValue);
}
#elif ABC_HOST_API_WIN32 //if ABC_HOST_API_POSIX
smstr<64> sEnc;
sEnc.set_from([pszEnvVarName] (char_t * pch, std::size_t cchMax) -> std::size_t {
// ::GetEnvironmentVariable() returns < cchMax (length without NUL) if the buffer was large
// enough, or the required size (length including NUL) otherwise.
return ::GetEnvironmentVariable(pszEnvVarName, pch, static_cast<DWORD>(cchMax));
});
#else //if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32
#error "TODO: HOST_API"
#endif //if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 … else
enc = abc::text::encoding::unknown;
if (sEnc) {
try {
enc = abc::text::encoding(sEnc);
} catch (domain_error const &) {
// Ignore this invalid encoding setting, and default to auto-detection.
// TODO: display a warning about ABC_STD*_ENCODING being ignored.
}
}
}
return _construct(std::move(pbb), enc);
}
} //namespace
std::shared_ptr<binbuf_writer> stderr() {
ABC_TRACE_FUNC();
// TODO: mutex!
if (!g_ptwStdErr) {
g_ptwStdErr = std::dynamic_pointer_cast<binbuf_writer>(
_construct_stdio(binary::stderr(), ABC_SL("ABC_STDERR_ENCODING"))
);
}
return g_ptwStdErr;
}
std::shared_ptr<binbuf_reader> stdin() {
ABC_TRACE_FUNC();
// TODO: mutex!
if (!g_ptrStdIn) {
g_ptrStdIn = std::dynamic_pointer_cast<binbuf_reader>(
_construct_stdio(binary::stdin(), ABC_SL("ABC_STDIN_ENCODING"))
);
}
return g_ptrStdIn;
}
std::shared_ptr<binbuf_writer> stdout() {
ABC_TRACE_FUNC();
// TODO: mutex!
if (!g_ptwStdOut) {
g_ptwStdOut = std::dynamic_pointer_cast<binbuf_writer>(
_construct_stdio(binary::stdout(), ABC_SL("ABC_STDOUT_ENCODING"))
);
}
return g_ptwStdOut;
}
std::shared_ptr<binbuf_base> open(
os::path const & op, access_mode am, abc::text::encoding enc /*= abc::text::encoding::unknown*/
) {
ABC_TRACE_FUNC(op, am, enc);
return _construct(binary::open(op, am), enc);
}
} //namespace text
} //namespace io
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
|
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2010, 2011, 2012, 2013, 2014
Raffaello D. Di Napoli
This file is part of Abaclade.
Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abaclade.hxx>
#include <abaclade/io/text/file.hxx>
#include <abaclade/io/binary/file.hxx>
#if ABC_HOST_API_POSIX
#include <cstdlib> // std::getenv()
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::io::text globals
namespace abc {
namespace io {
namespace text {
namespace {
std::shared_ptr<binbuf_writer> g_ptwStdErr;
std::shared_ptr<binbuf_reader> g_ptrStdIn;
std::shared_ptr<binbuf_writer> g_ptwStdOut;
/*! Instantiates a text::base specialization appropriate for the specified binary I/O object,
returning a shared pointer to it. If the binary I/O object does not implement buffering, a buffered
I/O wrapper is instanciated as well.
pbb
Pointer to a binary I/O object.
return
Shared pointer to the newly created object.
*/
std::shared_ptr<binbuf_base> _construct(
std::shared_ptr<binary::base> pbb, abc::text::encoding enc
) {
ABC_TRACE_FUNC(pbb, enc);
// Choose what type of text I/O object to create based on what type of binary I/O object we got.
// Check if it’s a buffered I/O object.
auto pbbr(std::dynamic_pointer_cast<binary::buffered_reader>(pbb));
auto pbbw(std::dynamic_pointer_cast<binary::buffered_writer>(pbb));
if (!pbbr && !pbbw) {
// Not a buffered I/O object? Get one then, and try again with the casts.
auto pbbb(binary::buffer(pbb));
pbbr = std::dynamic_pointer_cast<binary::buffered_reader>(pbbb);
pbbw = std::dynamic_pointer_cast<binary::buffered_writer>(pbbb);
}
// Now we must have a buffered reader or writer, or pbb is not something we can use.
if (pbbr) {
return std::make_shared<binbuf_reader>(std::move(pbbr), enc);
}
if (pbbw) {
return std::make_shared<binbuf_writer>(std::move(pbbw), enc);
}
// TODO: use a better exception class.
ABC_THROW(argument_error, ());
}
/*! Detects the encoding to use for a standard text I/O file, with the help of an optional
environment variable.
TODO: document this behavior and the related enviroment variables.
TODO: change to use a global “environment” map object instead of this ad-hoc code.
TODO: make the below code only pick up variables meant for this PID. This should eventually be made
more general, as a way for an Abaclade-based parent process to communicate with an Abaclade-based
child process. Thought maybe a better way is to pass a command-line argument that triggers Abaclade-
specific behavior, so that it’s inherently PID-specific.
pszEnvVarName
Environment variable name that, if set, specifies the encoding to be used.
return
Encoding appropriate for the requested standard I/O file.
*/
std::shared_ptr<binbuf_base> _construct_stdio(
std::shared_ptr<binary::base> pbb, char_t const * pszEnvVarName
) {
ABC_TRACE_FUNC(pbb, pszEnvVarName);
abc::text::encoding enc;
if (std::dynamic_pointer_cast<binary::console_file_base>(pbb)) {
// Console files can only perform I/O in the host platform’s encoding, so force the correct
// encoding here.
enc = abc::text::encoding::host;
} else {
// In all other cases, allow selecting the encoding via environment variable.
#if ABC_HOST_API_POSIX
istr sEnc;
if (char_t const * pszEnvVarValue = std::getenv(pszEnvVarName)) {
sEnc = istr(external_buffer, pszEnvVarValue);
}
#elif ABC_HOST_API_WIN32 //if ABC_HOST_API_POSIX
smstr<64> sEnc;
sEnc.set_from([pszEnvVarName] (char_t * pch, std::size_t cchMax) -> std::size_t {
// ::GetEnvironmentVariable() returns < cchMax (length without NUL) if the buffer was large
// enough, or the required size (length including NUL) otherwise.
return ::GetEnvironmentVariable(pszEnvVarName, pch, static_cast<DWORD>(cchMax));
});
#else //if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32
#error "TODO: HOST_API"
#endif //if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32 … else
enc = abc::text::encoding::unknown;
if (sEnc) {
try {
enc = abc::text::encoding(sEnc);
} catch (domain_error const &) {
// Ignore this invalid encoding setting, and default to auto-detection.
// TODO: display a warning about ABC_STD*_ENCODING being ignored.
}
}
}
return _construct(std::move(pbb), enc);
}
} //namespace
std::shared_ptr<binbuf_writer> stderr() {
ABC_TRACE_FUNC();
// TODO: mutex!
if (!g_ptwStdErr) {
g_ptwStdErr = std::dynamic_pointer_cast<binbuf_writer>(
_construct_stdio(binary::stderr(), ABC_SL("ABC_STDERR_ENCODING"))
);
}
return g_ptwStdErr;
}
std::shared_ptr<binbuf_reader> stdin() {
ABC_TRACE_FUNC();
// TODO: mutex!
if (!g_ptrStdIn) {
g_ptrStdIn = std::dynamic_pointer_cast<binbuf_reader>(
_construct_stdio(binary::stdin(), ABC_SL("ABC_STDIN_ENCODING"))
);
}
return g_ptrStdIn;
}
std::shared_ptr<binbuf_writer> stdout() {
ABC_TRACE_FUNC();
// TODO: mutex!
if (!g_ptwStdOut) {
g_ptwStdOut = std::dynamic_pointer_cast<binbuf_writer>(
_construct_stdio(binary::stdout(), ABC_SL("ABC_STDOUT_ENCODING"))
);
}
return g_ptwStdOut;
}
std::shared_ptr<binbuf_base> open(
os::path const & op, access_mode am, abc::text::encoding enc /*= abc::text::encoding::unknown*/
) {
ABC_TRACE_FUNC(op, am, enc);
return _construct(binary::open(op, am), enc);
}
} //namespace text
} //namespace io
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
|
Replace ::getenv() with std::getenv()
|
Replace ::getenv() with std::getenv()
|
C++
|
lgpl-2.1
|
raffaellod/lofty,raffaellod/lofty
|
39cffde579b370b2c8b5905c4a34fee3b4a130e1
|
src/abc-testing/test_case.cxx
|
src/abc-testing/test_case.cxx
|
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2013
Raffaello D. Di Napoli
This file is part of Application-Building Components (henceforth referred to as ABC).
ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
ABC 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 ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abc/testing/core.hxx>
#include <abc/testing/test_case.hxx>
#include <abc/trace.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case
namespace abc {
namespace testing {
test_case::test_case() {
}
/*virtual*/ test_case::~test_case() {
}
void test_case::init(runner * prunner) {
ABC_TRACE_FN((prunner));
m_prunner = prunner;
}
void test_case::assert_impl(
char const * pszFileName, unsigned iLine, bool bSuccess,
istr const & sExpr, istr const & sOp, istr const & sExpected, istr const & sActual
) {
ABC_TRACE_FN((this, pszFileName, iLine, bSuccess, sExpr, sOp, sExpected, sActual));
if (bSuccess) {
m_prunner->log_assertion_pass(pszFileName, iLine, sExpr, sOp, sExpected);
} else {
m_prunner->log_assertion_fail(pszFileName, iLine, sExpr, sOp, sExpected, sActual);
}
}
void test_case::assert_false(
char const * pszFileName, unsigned iLine, bool bActual, istr const & sExpr
) {
ABC_TRACE_FN((this, pszFileName, iLine, bActual, sExpr));
assert_impl(
pszFileName, iLine, !bActual, sExpr, istr(), !bActual ? istr() : SL("false"), SL("true")
);
}
void test_case::assert_true(
char const * pszFileName, unsigned iLine, bool bActual, istr const & sExpr
) {
ABC_TRACE_FN((this, pszFileName, iLine, bActual, sExpr));
assert_impl(
pszFileName, iLine, bActual, sExpr, istr(), bActual ? istr() : SL("true"), SL("false")
);
}
} //namespace testing
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case_factory_impl
namespace abc {
namespace testing {
/*static*/ test_case_factory_impl::list_item * test_case_factory_impl::sm_pliHead(nullptr);
// MSC16 BUG: for some reason, this will be parsed as a function declaration if written as a
// constructor call.
/*static*/ test_case_factory_impl::list_item ** test_case_factory_impl::sm_ppliTailNext = nullptr;
test_case_factory_impl::test_case_factory_impl(list_item * pli) {
if (sm_pliHead) {
// We have a head and therefore a tail as well: add *pli as the new tail.
*sm_ppliTailNext = pli;
} else {
// We don’t have a head yet: set it up now.
sm_pliHead = pli;
}
// Save the “next” pointer of *pli for the next call.
sm_ppliTailNext = &pli->pliNext;
}
} //namespace testing
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
|
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2013
Raffaello D. Di Napoli
This file is part of Application-Building Components (henceforth referred to as ABC).
ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
ABC 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 ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abc/testing/core.hxx>
#include <abc/testing/test_case.hxx>
#include <abc/trace.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case
namespace abc {
namespace testing {
test_case::test_case() {
}
/*virtual*/ test_case::~test_case() {
}
void test_case::init(runner * prunner) {
ABC_TRACE_FN((this, prunner));
m_prunner = prunner;
}
void test_case::assert_impl(
char const * pszFileName, unsigned iLine, bool bSuccess,
istr const & sExpr, istr const & sOp, istr const & sExpected, istr const & sActual
) {
ABC_TRACE_FN((this, pszFileName, iLine, bSuccess, sExpr, sOp, sExpected, sActual));
if (bSuccess) {
m_prunner->log_assertion_pass(pszFileName, iLine, sExpr, sOp, sExpected);
} else {
m_prunner->log_assertion_fail(pszFileName, iLine, sExpr, sOp, sExpected, sActual);
}
}
void test_case::assert_false(
char const * pszFileName, unsigned iLine, bool bActual, istr const & sExpr
) {
ABC_TRACE_FN((this, pszFileName, iLine, bActual, sExpr));
assert_impl(
pszFileName, iLine, !bActual, sExpr, istr(), !bActual ? istr() : SL("false"), SL("true")
);
}
void test_case::assert_true(
char const * pszFileName, unsigned iLine, bool bActual, istr const & sExpr
) {
ABC_TRACE_FN((this, pszFileName, iLine, bActual, sExpr));
assert_impl(
pszFileName, iLine, bActual, sExpr, istr(), bActual ? istr() : SL("true"), SL("false")
);
}
} //namespace testing
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case_factory_impl
namespace abc {
namespace testing {
/*static*/ test_case_factory_impl::list_item * test_case_factory_impl::sm_pliHead(nullptr);
// MSC16 BUG: for some reason, this will be parsed as a function declaration if written as a
// constructor call.
/*static*/ test_case_factory_impl::list_item ** test_case_factory_impl::sm_ppliTailNext = nullptr;
test_case_factory_impl::test_case_factory_impl(list_item * pli) {
if (sm_pliHead) {
// We have a head and therefore a tail as well: add *pli as the new tail.
*sm_ppliTailNext = pli;
} else {
// We don’t have a head yet: set it up now.
sm_pliHead = pli;
}
// Save the “next” pointer of *pli for the next call.
sm_ppliTailNext = &pli->pliNext;
}
} //namespace testing
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
|
Add missing this from ABC_TRACE_FN
|
Add missing this from ABC_TRACE_FN
|
C++
|
lgpl-2.1
|
raffaellod/lofty,raffaellod/lofty
|
cb7662f6749d5f327137c2a40e963ab4f1eb3990
|
include/hpp/core/path.hh
|
include/hpp/core/path.hh
|
//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_PATH_HH
# define HPP_CORE_PATH_HH
# include <boost/concept_check.hpp>
# include <hpp/core/fwd.hh>
# include <hpp/core/config.hh>
# include <hpp/core/constraint-set.hh>
# include <hpp/core/deprecated.hh>
namespace hpp {
namespace core {
/// Abstraction of paths: mapping from time to configuration space
///
class HPP_CORE_DLLAPI Path
{
public:
/// \name Construction, destruction, copy
/// \{
/// Destructor
virtual ~Path () throw () {}
/// Return a shared pointer to a copy of this
virtual PathPtr_t copy () const = 0;
/// Return a shared pointer to a copy of this and set constraints
///
/// \param constraints constraints to apply to the copy
/// \precond *this should not have constraints.
virtual PathPtr_t copy (const ConstraintSetPtr_t& constraints) const = 0;
/// Static cast into a derived type
template <class T> boost::shared_ptr<T> as (void)
{
BOOST_CONCEPT_ASSERT ((boost::Convertible <T*, Path*>));
assert (HPP_DYNAMIC_PTR_CAST (T, weak_.lock ()));
return HPP_STATIC_PTR_CAST (T, weak_.lock ());
}
/// Static cast into a derived type
template <class T> boost::shared_ptr<const T> as (void) const
{
BOOST_CONCEPT_ASSERT ((boost::Convertible <T*, Path*>));
assert (HPP_DYNAMIC_PTR_CAST (const T, weak_.lock ()));
return HPP_STATIC_PTR_CAST (const T, weak_.lock ());
}
/// Extraction/Reversion of a sub-path
/// \param subInterval interval of definition of the extract path
/// If upper bound of subInterval is smaller than lower bound,
/// result is reversed.
virtual PathPtr_t extract (const interval_t& subInterval) const;
/// Reversion of a path
/// \return a new path that is this one reversed.
virtual PathPtr_t reverse () const;
/// \}
Configuration_t operator () (const value_type& t) const
HPP_CORE_DEPRECATED
{
Configuration_t result (outputSize ());
impl_compute (result, t);
if (constraints_) {
constraints_->apply (result);
}
return result;
}
Configuration_t operator () (const value_type& t, bool& success) const
{
Configuration_t result (outputSize ());
success = impl_compute (result, t);
if (!success) return result;
if (constraints_) {
success = constraints_->apply (result);
}
return result;
}
bool operator () (ConfigurationOut_t result, const value_type& t)
const throw ()
{
bool success = impl_compute (result, t);
if (!success) return false;
return (!constraints_ || constraints_->apply (result));
}
/// \brief Function evaluation without applying constraints
///
/// \return true if everything went good.
virtual bool impl_compute (ConfigurationOut_t configuration,
value_type t) const = 0;
/// \name Constraints
/// \{
/// Get constraints the path is subject to
const ConstraintSetPtr_t& constraints () const
{
return constraints_;
}
/// \}
/// Get size of configuration space
size_type outputSize () const
{
return outputSize_;
}
/// Get size of velocity
size_type outputDerivativeSize () const
{
return outputDerivativeSize_;
}
/// Get interval of definition
const interval_t& timeRange () const
{
return timeRange_;
}
/// Get length of definition interval
value_type length () const
{
return timeRange_.second - timeRange_.first;
}
/// Get the initial configuration
virtual Configuration_t initial () const = 0;
/// Get the final configuration
virtual Configuration_t end () const = 0;
protected:
/// Print path in a stream
virtual std::ostream& print (std::ostream &os) const = 0;
/// Constructor
/// \param interval interval of definition of the path,
/// \param outputSize size of the output configuration,
/// \param outputDerivativeSize number of degrees of freedom of the
/// underlying robot
/// \param constraints constraints the set is subject to,
/// constraints are solved at each evaluation of the output
/// configuration.
/// \note Constraints are copied.
Path (const interval_t& interval, size_type outputSize,
size_type outputDerivativeSize,
const ConstraintSetPtr_t& constraints);
/// Constructor
/// \param interval interval of definition of the path,
/// \param outputSize size of the output configuration,
/// \param outputDerivativeSize number of degrees of freedom of the
/// underlying robot
Path (const interval_t& interval, size_type outputSize,
size_type outputDerivativeSize);
/// Copy constructor
Path (const Path& path);
/// Copy constructor with constraints
Path (const Path& path, const ConstraintSetPtr_t& constraints);
/// Store weak pointer to itself
///
/// should be called at construction of derived class instances
void init (const PathPtr_t& self);
/// should be called at copy construction of derived class instances
void initCopy (const PathPtr_t& self);
/// Interval of definition
interval_t timeRange_;
private:
/// Size of the configuration space
size_type outputSize_;
/// Number of degrees of freedom of the robot
size_type outputDerivativeSize_;
/// Constraints that apply to the robot
ConstraintSetPtr_t constraints_;
/// Weak pointer to itself
PathWkPtr_t weak_;
friend std::ostream& operator<< (std::ostream& os, const Path& path);
}; // class Path
inline std::ostream& operator<< (std::ostream& os, const Path& path)
{
return path.print (os);
}
} // namespace core
} // namespace hpp
#endif // HPP_CORE_PATH_HH
|
//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#ifndef HPP_CORE_PATH_HH
# define HPP_CORE_PATH_HH
# include <boost/concept_check.hpp>
# include <hpp/core/fwd.hh>
# include <hpp/core/config.hh>
# include <hpp/core/constraint-set.hh>
# include <hpp/core/deprecated.hh>
namespace hpp {
namespace core {
/// Abstraction of paths: mapping from time to configuration space
///
class HPP_CORE_DLLAPI Path
{
public:
/// \name Construction, destruction, copy
/// \{
/// Destructor
virtual ~Path () throw () {}
/// Return a shared pointer to a copy of this
virtual PathPtr_t copy () const = 0;
/// Return a shared pointer to a copy of this and set constraints
///
/// \param constraints constraints to apply to the copy
/// \precond *this should not have constraints.
virtual PathPtr_t copy (const ConstraintSetPtr_t& constraints) const = 0;
/// Static cast into a derived type
template <class T> boost::shared_ptr<T> as (void)
{
assert (HPP_DYNAMIC_PTR_CAST (T, weak_.lock ()));
return HPP_STATIC_PTR_CAST (T, weak_.lock ());
}
/// Static cast into a derived type
template <class T> boost::shared_ptr<const T> as (void) const
{
assert (HPP_DYNAMIC_PTR_CAST (const T, weak_.lock ()));
return HPP_STATIC_PTR_CAST (const T, weak_.lock ());
}
/// Extraction/Reversion of a sub-path
/// \param subInterval interval of definition of the extract path
/// If upper bound of subInterval is smaller than lower bound,
/// result is reversed.
virtual PathPtr_t extract (const interval_t& subInterval) const;
/// Reversion of a path
/// \return a new path that is this one reversed.
virtual PathPtr_t reverse () const;
/// \}
Configuration_t operator () (const value_type& t) const
HPP_CORE_DEPRECATED
{
Configuration_t result (outputSize ());
impl_compute (result, t);
if (constraints_) {
constraints_->apply (result);
}
return result;
}
Configuration_t operator () (const value_type& t, bool& success) const
{
Configuration_t result (outputSize ());
success = impl_compute (result, t);
if (!success) return result;
if (constraints_) {
success = constraints_->apply (result);
}
return result;
}
bool operator () (ConfigurationOut_t result, const value_type& t)
const throw ()
{
bool success = impl_compute (result, t);
if (!success) return false;
return (!constraints_ || constraints_->apply (result));
}
/// \brief Function evaluation without applying constraints
///
/// \return true if everything went good.
virtual bool impl_compute (ConfigurationOut_t configuration,
value_type t) const = 0;
/// \name Constraints
/// \{
/// Get constraints the path is subject to
const ConstraintSetPtr_t& constraints () const
{
return constraints_;
}
/// \}
/// Get size of configuration space
size_type outputSize () const
{
return outputSize_;
}
/// Get size of velocity
size_type outputDerivativeSize () const
{
return outputDerivativeSize_;
}
/// Get interval of definition
const interval_t& timeRange () const
{
return timeRange_;
}
/// Get length of definition interval
value_type length () const
{
return timeRange_.second - timeRange_.first;
}
/// Get the initial configuration
virtual Configuration_t initial () const = 0;
/// Get the final configuration
virtual Configuration_t end () const = 0;
protected:
/// Print path in a stream
virtual std::ostream& print (std::ostream &os) const = 0;
/// Constructor
/// \param interval interval of definition of the path,
/// \param outputSize size of the output configuration,
/// \param outputDerivativeSize number of degrees of freedom of the
/// underlying robot
/// \param constraints constraints the set is subject to,
/// constraints are solved at each evaluation of the output
/// configuration.
/// \note Constraints are copied.
Path (const interval_t& interval, size_type outputSize,
size_type outputDerivativeSize,
const ConstraintSetPtr_t& constraints);
/// Constructor
/// \param interval interval of definition of the path,
/// \param outputSize size of the output configuration,
/// \param outputDerivativeSize number of degrees of freedom of the
/// underlying robot
Path (const interval_t& interval, size_type outputSize,
size_type outputDerivativeSize);
/// Copy constructor
Path (const Path& path);
/// Copy constructor with constraints
Path (const Path& path, const ConstraintSetPtr_t& constraints);
/// Store weak pointer to itself
///
/// should be called at construction of derived class instances
void init (const PathPtr_t& self);
/// should be called at copy construction of derived class instances
void initCopy (const PathPtr_t& self);
/// Interval of definition
interval_t timeRange_;
private:
/// Size of the configuration space
size_type outputSize_;
/// Number of degrees of freedom of the robot
size_type outputDerivativeSize_;
/// Constraints that apply to the robot
ConstraintSetPtr_t constraints_;
/// Weak pointer to itself
PathWkPtr_t weak_;
friend std::ostream& operator<< (std::ostream& os, const Path& path);
}; // class Path
inline std::ostream& operator<< (std::ostream& os, const Path& path)
{
return path.print (os);
}
} // namespace core
} // namespace hpp
#endif // HPP_CORE_PATH_HH
|
Fix warnings generated by BOOST_CONCEPT_ASSERT.
|
Fix warnings generated by BOOST_CONCEPT_ASSERT.
|
C++
|
bsd-2-clause
|
humanoid-path-planner/hpp-core
|
2bc7c4e568a78babce8bfd38012c8084b3f2157a
|
include/nod/DiscBase.hpp
|
include/nod/DiscBase.hpp
|
#ifndef __NOD_DISC_BASE__
#define __NOD_DISC_BASE__
#include <vector>
#include <memory>
#include <string>
#include <unordered_map>
#include <stdio.h>
#include <stdint.h>
#include <functional>
#include "Util.hpp"
#include "IDiscIO.hpp"
#include "IFileIO.hpp"
namespace nod
{
using FProgress = std::function<void(size_t, const SystemString&, size_t)>;
class FSTNode
{
uint32_t typeAndNameOffset;
uint32_t offset;
uint32_t length;
public:
FSTNode(bool isDir, uint32_t nameOff, uint32_t off, uint32_t len)
{
typeAndNameOffset = nameOff & 0xffffff;
typeAndNameOffset |= isDir << 24;
typeAndNameOffset = SBig(typeAndNameOffset);
offset = SBig(off);
length = SBig(len);
}
inline bool isDir() const {return ((SBig(typeAndNameOffset) >> 24) != 0);}
inline uint32_t getNameOffset() const {return SBig(typeAndNameOffset) & 0xffffff;}
inline uint32_t getOffset() const {return SBig(offset);}
inline uint32_t getLength() const {return SBig(length);}
void incrementLength()
{
uint32_t orig = SBig(length);
++orig;
length = SBig(orig);
}
};
struct Header
{
char m_gameID[6];
char m_discNum;
char m_discVersion;
char m_audioStreaming;
char m_streamBufSz;
char m_unk[14];
uint32_t m_wiiMagic;
uint32_t m_gcnMagic;
char m_gameTitle[64];
Header(IDiscIO& dio, bool& err)
{
std::unique_ptr<IDiscIO::IReadStream> s = dio.beginReadStream(0);
if (!s)
{
err = true;
return;
}
s->read(this, sizeof(*this));
m_wiiMagic = SBig(m_wiiMagic);
m_gcnMagic = SBig(m_gcnMagic);
}
Header(const char gameID[6], const char* gameTitle, bool wii, char discNum=0, char discVersion=0,
char audioStreaming=1, char streamBufSz=0)
{
memset(this, 0, sizeof(*this));
memcpy(m_gameID, gameID, 6);
strncpy(m_gameTitle, gameTitle, 64);
m_discNum = discNum;
m_discVersion = discVersion;
m_audioStreaming = audioStreaming;
m_streamBufSz = streamBufSz;
if (wii)
m_wiiMagic = 0x5D1C9EA3;
else
m_gcnMagic = 0xC2339F3D;
}
template <class WriteStream>
void write(WriteStream& ws) const
{
Header hs(*this);
hs.m_wiiMagic = SBig(hs.m_wiiMagic);
hs.m_gcnMagic = SBig(hs.m_gcnMagic);
ws.write(&hs, sizeof(hs));
}
};
struct ExtractionContext;
class DiscBase
{
public:
virtual ~DiscBase() {}
class IPartition
{
public:
virtual ~IPartition() {}
enum class Kind : uint32_t
{
Data,
Update,
Channel
};
struct DOLHeader
{
uint32_t textOff[7];
uint32_t dataOff[11];
uint32_t textStarts[7];
uint32_t dataStarts[11];
uint32_t textSizes[7];
uint32_t dataSizes[11];
uint32_t bssStart;
uint32_t bssSize;
uint32_t entryPoint;
};
class Node
{
public:
enum class Kind
{
File,
Directory
};
private:
friend class IPartition;
const IPartition& m_parent;
Kind m_kind;
uint64_t m_discOffset;
uint64_t m_discLength;
std::string m_name;
std::vector<Node>::iterator m_childrenBegin;
std::vector<Node>::iterator m_childrenEnd;
public:
Node(const IPartition& parent, const FSTNode& node, const char* name)
: m_parent(parent),
m_kind(node.isDir() ? Kind::Directory : Kind::File),
m_discOffset(parent.normalizeOffset(node.getOffset())),
m_discLength(node.getLength()),
m_name(name) {}
inline Kind getKind() const {return m_kind;}
inline const std::string& getName() const {return m_name;}
inline uint64_t size() const {return m_discLength;}
std::unique_ptr<IPartReadStream> beginReadStream(uint64_t offset=0) const
{
if (m_kind != Kind::File)
{
LogModule.report(logvisor::Error, "unable to stream a non-file %s", m_name.c_str());
return std::unique_ptr<IPartReadStream>();
}
return m_parent.beginReadStream(m_discOffset + offset);
}
std::unique_ptr<uint8_t[]> getBuf() const
{
if (m_kind != Kind::File)
{
LogModule.report(logvisor::Error, "unable to buffer a non-file %s", m_name.c_str());
return std::unique_ptr<uint8_t[]>();
}
uint8_t* buf = new uint8_t[m_discLength];
beginReadStream()->read(buf, m_discLength);
return std::unique_ptr<uint8_t[]>(buf);
}
inline std::vector<Node>::iterator rawBegin() const {return m_childrenBegin;}
inline std::vector<Node>::iterator rawEnd() const {return m_childrenEnd;}
class DirectoryIterator : std::iterator<std::forward_iterator_tag, Node>
{
friend class Node;
std::vector<Node>::iterator m_it;
DirectoryIterator(const std::vector<Node>::iterator& it)
: m_it(it) {}
public:
inline bool operator!=(const DirectoryIterator& other) {return m_it != other.m_it;}
inline bool operator==(const DirectoryIterator& other) {return m_it == other.m_it;}
inline DirectoryIterator& operator++()
{
if (m_it->m_kind == Kind::Directory)
m_it = m_it->rawEnd();
else
++m_it;
return *this;
}
inline Node& operator*() {return *m_it;}
inline Node* operator->() {return &*m_it;}
};
inline DirectoryIterator begin() const {return DirectoryIterator(m_childrenBegin);}
inline DirectoryIterator end() const {return DirectoryIterator(m_childrenEnd);}
inline DirectoryIterator find(const std::string& name) const
{
if (m_kind == Kind::Directory)
{
DirectoryIterator it=begin();
for (; it != end() ; ++it)
{
if (!it->getName().compare(name))
return it;
}
return it;
}
return end();
}
bool extractToDirectory(const SystemString& basePath, const ExtractionContext& ctx) const;
};
protected:
uint64_t m_dolOff;
uint64_t m_fstOff;
uint64_t m_fstSz;
uint64_t m_fstMemoryAddr;
uint64_t m_apploaderSz;
std::vector<Node> m_nodes;
void parseFST(IPartReadStream& s);
std::vector<FSTNode> m_buildNodes;
std::vector<std::string> m_buildNames;
size_t m_buildNameOff = 0;
void recursiveBuildNodes(const SystemChar* dirIn, std::function<void(void)> incParents);
uint64_t m_dolSz;
void parseDOL(IPartReadStream& s);
const DiscBase& m_parent;
Kind m_kind;
uint64_t m_offset;
public:
IPartition(const DiscBase& parent, Kind kind, uint64_t offset)
: m_parent(parent), m_kind(kind), m_offset(offset) {}
virtual uint64_t normalizeOffset(uint64_t anOffset) const {return anOffset;}
inline Kind getKind() const {return m_kind;}
inline uint64_t getDiscOffset() const {return m_offset;}
virtual std::unique_ptr<IPartReadStream> beginReadStream(uint64_t offset=0) const=0;
inline std::unique_ptr<IPartReadStream> beginDOLReadStream(uint64_t offset=0) const
{return beginReadStream(m_dolOff + offset);}
inline std::unique_ptr<IPartReadStream> beginFSTReadStream(uint64_t offset=0) const
{return beginReadStream(m_fstOff + offset);}
inline std::unique_ptr<IPartReadStream> beginApploaderReadStream(uint64_t offset=0) const
{return beginReadStream(0x2440 + offset);}
inline const Node& getFSTRoot() const {return m_nodes[0];}
inline Node& getFSTRoot() {return m_nodes[0];}
bool extractToDirectory(const SystemString& path, const ExtractionContext& ctx);
inline uint64_t getDOLSize() const {return m_dolSz;}
inline std::unique_ptr<uint8_t[]> getDOLBuf() const
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[m_dolSz]);
beginDOLReadStream()->read(buf.get(), m_dolSz);
return buf;
}
inline uint64_t getFSTSize() const {return m_fstSz;}
inline std::unique_ptr<uint8_t[]> getFSTBuf() const
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[m_fstSz]);
beginFSTReadStream()->read(buf.get(), m_fstSz);
return buf;
}
inline uint64_t getFSTMemoryAddr() const {return m_fstMemoryAddr;}
inline uint64_t getApploaderSize() const {return m_apploaderSz;}
inline std::unique_ptr<uint8_t[]> getApploaderBuf() const
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[m_apploaderSz]);
beginApploaderReadStream()->read(buf.get(), m_apploaderSz);
return buf;
}
};
protected:
std::unique_ptr<IDiscIO> m_discIO;
Header m_header;
std::vector<std::unique_ptr<IPartition>> m_partitions;
public:
DiscBase(std::unique_ptr<IDiscIO>&& dio, bool& err)
: m_discIO(std::move(dio)), m_header(*m_discIO, err) {}
inline const Header& getHeader() const {return m_header;}
inline const IDiscIO& getDiscIO() const {return *m_discIO;}
inline IPartition* getDataPartition()
{
for (const std::unique_ptr<IPartition>& part : m_partitions)
if (part->getKind() == IPartition::Kind::Data)
return part.get();
return nullptr;
}
inline IPartition* getUpdatePartition()
{
for (const std::unique_ptr<IPartition>& part : m_partitions)
if (part->getKind() == IPartition::Kind::Update)
return part.get();
return nullptr;
}
inline void extractToDirectory(const SystemString& path, const ExtractionContext& ctx)
{
for (std::unique_ptr<IPartition>& part : m_partitions)
part->extractToDirectory(path, ctx);
}
};
class DiscBuilderBase
{
friend class DiscMergerWii;
public:
class PartitionBuilderBase
{
public:
virtual ~PartitionBuilderBase() {}
enum class Kind : uint32_t
{
Data,
Update,
Channel
};
protected:
std::unordered_map<SystemString, std::pair<uint64_t,uint64_t>> m_fileOffsetsSizes;
std::vector<FSTNode> m_buildNodes;
std::vector<std::string> m_buildNames;
size_t m_buildNameOff = 0;
virtual uint64_t userAllocate(uint64_t reqSz, IPartWriteStream& ws)=0;
virtual uint32_t packOffset(uint64_t offset) const=0;
bool recursiveBuildNodes(IPartWriteStream& ws, bool system, const SystemChar* dirIn, uint64_t dolInode);
bool recursiveBuildFST(const SystemChar* dirIn, uint64_t dolInode,
std::function<void(void)> incParents);
bool recursiveMergeNodes(IPartWriteStream& ws, bool system,
const DiscBase::IPartition::Node* nodeIn, const SystemChar* dirIn,
const SystemString& keyPath);
bool recursiveMergeFST(const DiscBase::IPartition::Node* nodeIn,
const SystemChar* dirIn, std::function<void(void)> incParents,
const SystemString& keyPath);
static bool RecursiveCalculateTotalSize(uint64_t& totalSz,
const DiscBase::IPartition::Node* nodeIn,
const SystemChar* dirIn);
void addBuildName(const SystemString& str)
{
SystemUTF8View utf8View(str);
m_buildNames.push_back(utf8View.utf8_str());
m_buildNameOff += str.size() + 1;
}
DiscBuilderBase& m_parent;
Kind m_kind;
char m_gameID[6];
std::string m_gameTitle;
uint64_t m_dolOffset = 0;
uint64_t m_dolSize = 0;
public:
PartitionBuilderBase(DiscBuilderBase& parent, Kind kind,
const char gameID[6], const char* gameTitle)
: m_parent(parent), m_kind(kind), m_gameTitle(gameTitle)
{
memcpy(m_gameID, gameID, 6);
}
virtual std::unique_ptr<IPartWriteStream> beginWriteStream(uint64_t offset)=0;
bool buildFromDirectory(IPartWriteStream& ws,
const SystemChar* dirIn, const SystemChar* dolIn,
const SystemChar* apploaderIn);
static uint64_t CalculateTotalSizeBuild(const SystemChar* dolIn,
const SystemChar* dirIn);
bool mergeFromDirectory(IPartWriteStream& ws,
const DiscBase::IPartition* partIn,
const SystemChar* dirIn);
static uint64_t CalculateTotalSizeMerge(const DiscBase::IPartition* partIn,
const SystemChar* dirIn);
const char* getGameID() const {return m_gameID;}
const std::string& getGameTitle() const {return m_gameTitle;}
};
protected:
SystemString m_outPath;
std::unique_ptr<IFileIO> m_fileIO;
std::vector<std::unique_ptr<PartitionBuilderBase>> m_partitions;
int64_t m_discCapacity;
public:
std::function<void(size_t idx, const SystemString&, size_t)> m_progressCB;
size_t m_progressIdx = 0;
virtual ~DiscBuilderBase() = default;
DiscBuilderBase(const SystemChar* outPath, int64_t discCapacity,
std::function<void(size_t idx, const SystemString&, size_t)> progressCB)
: m_outPath(outPath), m_fileIO(NewFileIO(outPath, discCapacity)),
m_discCapacity(discCapacity), m_progressCB(progressCB) {}
DiscBuilderBase(DiscBuilderBase&&) = default;
DiscBuilderBase& operator=(DiscBuilderBase&&) = default;
IFileIO& getFileIO() {return *m_fileIO;}
};
using Partition = DiscBase::IPartition;
using Node = Partition::Node;
}
#endif // __NOD_DISC_BASE__
|
#ifndef __NOD_DISC_BASE__
#define __NOD_DISC_BASE__
#include <vector>
#include <memory>
#include <string>
#include <unordered_map>
#include <stdio.h>
#include <stdint.h>
#include <functional>
#include "Util.hpp"
#include "IDiscIO.hpp"
#include "IFileIO.hpp"
namespace nod
{
using FProgress = std::function<void(size_t, const SystemString&, size_t)>;
class FSTNode
{
uint32_t typeAndNameOffset;
uint32_t offset;
uint32_t length;
public:
FSTNode(bool isDir, uint32_t nameOff, uint32_t off, uint32_t len)
{
typeAndNameOffset = nameOff & 0xffffff;
typeAndNameOffset |= isDir << 24;
typeAndNameOffset = SBig(typeAndNameOffset);
offset = SBig(off);
length = SBig(len);
}
inline bool isDir() const {return ((SBig(typeAndNameOffset) >> 24) != 0);}
inline uint32_t getNameOffset() const {return SBig(typeAndNameOffset) & 0xffffff;}
inline uint32_t getOffset() const {return SBig(offset);}
inline uint32_t getLength() const {return SBig(length);}
void incrementLength()
{
uint32_t orig = SBig(length);
++orig;
length = SBig(orig);
}
};
struct Header
{
char m_gameID[6];
char m_discNum;
char m_discVersion;
char m_audioStreaming;
char m_streamBufSz;
char m_unk[14];
uint32_t m_wiiMagic;
uint32_t m_gcnMagic;
char m_gameTitle[64];
Header(IDiscIO& dio, bool& err)
{
std::unique_ptr<IDiscIO::IReadStream> s = dio.beginReadStream(0);
if (!s)
{
err = true;
return;
}
s->read(this, sizeof(*this));
m_wiiMagic = SBig(m_wiiMagic);
m_gcnMagic = SBig(m_gcnMagic);
}
Header(const char gameID[6], const char* gameTitle, bool wii, char discNum=0, char discVersion=0,
char audioStreaming=1, char streamBufSz=0)
{
memset(this, 0, sizeof(*this));
memcpy(m_gameID, gameID, 6);
strncpy(m_gameTitle, gameTitle, 64);
m_discNum = discNum;
m_discVersion = discVersion;
m_audioStreaming = audioStreaming;
m_streamBufSz = streamBufSz;
if (wii)
m_wiiMagic = 0x5D1C9EA3;
else
m_gcnMagic = 0xC2339F3D;
}
template <class WriteStream>
void write(WriteStream& ws) const
{
Header hs(*this);
hs.m_wiiMagic = SBig(hs.m_wiiMagic);
hs.m_gcnMagic = SBig(hs.m_gcnMagic);
ws.write(&hs, sizeof(hs));
}
};
struct ExtractionContext;
class DiscBase
{
public:
virtual ~DiscBase() {}
class IPartition
{
public:
virtual ~IPartition() {}
enum class Kind : uint32_t
{
Data,
Update,
Channel
};
struct DOLHeader
{
uint32_t textOff[7];
uint32_t dataOff[11];
uint32_t textStarts[7];
uint32_t dataStarts[11];
uint32_t textSizes[7];
uint32_t dataSizes[11];
uint32_t bssStart;
uint32_t bssSize;
uint32_t entryPoint;
};
class Node
{
public:
enum class Kind
{
File,
Directory
};
private:
friend class IPartition;
const IPartition& m_parent;
Kind m_kind;
uint64_t m_discOffset;
uint64_t m_discLength;
std::string m_name;
std::vector<Node>::iterator m_childrenBegin;
std::vector<Node>::iterator m_childrenEnd;
public:
Node(const IPartition& parent, const FSTNode& node, const char* name)
: m_parent(parent),
m_kind(node.isDir() ? Kind::Directory : Kind::File),
m_discOffset(parent.normalizeOffset(node.getOffset())),
m_discLength(node.getLength()),
m_name(name) {}
inline Kind getKind() const {return m_kind;}
inline const std::string& getName() const {return m_name;}
inline uint64_t size() const {return m_discLength;}
std::unique_ptr<IPartReadStream> beginReadStream(uint64_t offset=0) const
{
if (m_kind != Kind::File)
{
LogModule.report(logvisor::Error, "unable to stream a non-file %s", m_name.c_str());
return std::unique_ptr<IPartReadStream>();
}
return m_parent.beginReadStream(m_discOffset + offset);
}
std::unique_ptr<uint8_t[]> getBuf() const
{
if (m_kind != Kind::File)
{
LogModule.report(logvisor::Error, "unable to buffer a non-file %s", m_name.c_str());
return std::unique_ptr<uint8_t[]>();
}
uint8_t* buf = new uint8_t[m_discLength];
beginReadStream()->read(buf, m_discLength);
return std::unique_ptr<uint8_t[]>(buf);
}
inline std::vector<Node>::iterator rawBegin() const {return m_childrenBegin;}
inline std::vector<Node>::iterator rawEnd() const {return m_childrenEnd;}
class DirectoryIterator : std::iterator<std::forward_iterator_tag, Node>
{
friend class Node;
std::vector<Node>::iterator m_it;
DirectoryIterator(const std::vector<Node>::iterator& it)
: m_it(it) {}
public:
inline bool operator!=(const DirectoryIterator& other) {return m_it != other.m_it;}
inline bool operator==(const DirectoryIterator& other) {return m_it == other.m_it;}
inline DirectoryIterator& operator++()
{
if (m_it->m_kind == Kind::Directory)
m_it = m_it->rawEnd();
else
++m_it;
return *this;
}
inline Node& operator*() {return *m_it;}
inline Node* operator->() {return &*m_it;}
};
inline DirectoryIterator begin() const {return DirectoryIterator(m_childrenBegin);}
inline DirectoryIterator end() const {return DirectoryIterator(m_childrenEnd);}
inline DirectoryIterator find(const std::string& name) const
{
if (m_kind == Kind::Directory)
{
DirectoryIterator it=begin();
for (; it != end() ; ++it)
{
if (!it->getName().compare(name))
return it;
}
return it;
}
return end();
}
bool extractToDirectory(const SystemString& basePath, const ExtractionContext& ctx) const;
};
protected:
uint64_t m_dolOff;
uint64_t m_fstOff;
uint64_t m_fstSz;
uint64_t m_fstMemoryAddr;
uint64_t m_apploaderSz;
std::vector<Node> m_nodes;
void parseFST(IPartReadStream& s);
std::vector<FSTNode> m_buildNodes;
std::vector<std::string> m_buildNames;
size_t m_buildNameOff = 0;
void recursiveBuildNodes(const SystemChar* dirIn, std::function<void(void)> incParents);
uint64_t m_dolSz;
void parseDOL(IPartReadStream& s);
const DiscBase& m_parent;
Kind m_kind;
uint64_t m_offset;
public:
IPartition(const DiscBase& parent, Kind kind, uint64_t offset)
: m_parent(parent), m_kind(kind), m_offset(offset) {}
virtual uint64_t normalizeOffset(uint64_t anOffset) const {return anOffset;}
inline Kind getKind() const {return m_kind;}
inline uint64_t getDiscOffset() const {return m_offset;}
virtual std::unique_ptr<IPartReadStream> beginReadStream(uint64_t offset=0) const=0;
inline std::unique_ptr<IPartReadStream> beginDOLReadStream(uint64_t offset=0) const
{return beginReadStream(m_dolOff + offset);}
inline std::unique_ptr<IPartReadStream> beginFSTReadStream(uint64_t offset=0) const
{return beginReadStream(m_fstOff + offset);}
inline std::unique_ptr<IPartReadStream> beginApploaderReadStream(uint64_t offset=0) const
{return beginReadStream(0x2440 + offset);}
inline const Node& getFSTRoot() const {return m_nodes[0];}
inline Node& getFSTRoot() {return m_nodes[0];}
bool extractToDirectory(const SystemString& path, const ExtractionContext& ctx);
inline uint64_t getDOLSize() const {return m_dolSz;}
inline std::unique_ptr<uint8_t[]> getDOLBuf() const
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[m_dolSz]);
beginDOLReadStream()->read(buf.get(), m_dolSz);
return buf;
}
inline uint64_t getFSTSize() const {return m_fstSz;}
inline std::unique_ptr<uint8_t[]> getFSTBuf() const
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[m_fstSz]);
beginFSTReadStream()->read(buf.get(), m_fstSz);
return buf;
}
inline uint64_t getFSTMemoryAddr() const {return m_fstMemoryAddr;}
inline uint64_t getApploaderSize() const {return m_apploaderSz;}
inline std::unique_ptr<uint8_t[]> getApploaderBuf() const
{
std::unique_ptr<uint8_t[]> buf(new uint8_t[m_apploaderSz]);
beginApploaderReadStream()->read(buf.get(), m_apploaderSz);
return buf;
}
inline size_t getNodeCount() const { return m_nodes.size(); }
};
protected:
std::unique_ptr<IDiscIO> m_discIO;
Header m_header;
std::vector<std::unique_ptr<IPartition>> m_partitions;
public:
DiscBase(std::unique_ptr<IDiscIO>&& dio, bool& err)
: m_discIO(std::move(dio)), m_header(*m_discIO, err) {}
inline const Header& getHeader() const {return m_header;}
inline const IDiscIO& getDiscIO() const {return *m_discIO;}
inline size_t getPartitonNodeCount(size_t partition = 0) const
{
if (partition > m_partitions.size())
return -1;
return m_partitions[partition]->getNodeCount();
}
inline IPartition* getDataPartition()
{
for (const std::unique_ptr<IPartition>& part : m_partitions)
if (part->getKind() == IPartition::Kind::Data)
return part.get();
return nullptr;
}
inline IPartition* getUpdatePartition()
{
for (const std::unique_ptr<IPartition>& part : m_partitions)
if (part->getKind() == IPartition::Kind::Update)
return part.get();
return nullptr;
}
inline void extractToDirectory(const SystemString& path, const ExtractionContext& ctx)
{
for (std::unique_ptr<IPartition>& part : m_partitions)
part->extractToDirectory(path, ctx);
}
};
class DiscBuilderBase
{
friend class DiscMergerWii;
public:
class PartitionBuilderBase
{
public:
virtual ~PartitionBuilderBase() {}
enum class Kind : uint32_t
{
Data,
Update,
Channel
};
protected:
std::unordered_map<SystemString, std::pair<uint64_t,uint64_t>> m_fileOffsetsSizes;
std::vector<FSTNode> m_buildNodes;
std::vector<std::string> m_buildNames;
size_t m_buildNameOff = 0;
virtual uint64_t userAllocate(uint64_t reqSz, IPartWriteStream& ws)=0;
virtual uint32_t packOffset(uint64_t offset) const=0;
bool recursiveBuildNodes(IPartWriteStream& ws, bool system, const SystemChar* dirIn, uint64_t dolInode);
bool recursiveBuildFST(const SystemChar* dirIn, uint64_t dolInode,
std::function<void(void)> incParents);
bool recursiveMergeNodes(IPartWriteStream& ws, bool system,
const DiscBase::IPartition::Node* nodeIn, const SystemChar* dirIn,
const SystemString& keyPath);
bool recursiveMergeFST(const DiscBase::IPartition::Node* nodeIn,
const SystemChar* dirIn, std::function<void(void)> incParents,
const SystemString& keyPath);
static bool RecursiveCalculateTotalSize(uint64_t& totalSz,
const DiscBase::IPartition::Node* nodeIn,
const SystemChar* dirIn);
void addBuildName(const SystemString& str)
{
SystemUTF8View utf8View(str);
m_buildNames.push_back(utf8View.utf8_str());
m_buildNameOff += str.size() + 1;
}
DiscBuilderBase& m_parent;
Kind m_kind;
char m_gameID[6];
std::string m_gameTitle;
uint64_t m_dolOffset = 0;
uint64_t m_dolSize = 0;
public:
PartitionBuilderBase(DiscBuilderBase& parent, Kind kind,
const char gameID[6], const char* gameTitle)
: m_parent(parent), m_kind(kind), m_gameTitle(gameTitle)
{
memcpy(m_gameID, gameID, 6);
}
virtual std::unique_ptr<IPartWriteStream> beginWriteStream(uint64_t offset)=0;
bool buildFromDirectory(IPartWriteStream& ws,
const SystemChar* dirIn, const SystemChar* dolIn,
const SystemChar* apploaderIn);
static uint64_t CalculateTotalSizeBuild(const SystemChar* dolIn,
const SystemChar* dirIn);
bool mergeFromDirectory(IPartWriteStream& ws,
const DiscBase::IPartition* partIn,
const SystemChar* dirIn);
static uint64_t CalculateTotalSizeMerge(const DiscBase::IPartition* partIn,
const SystemChar* dirIn);
const char* getGameID() const {return m_gameID;}
const std::string& getGameTitle() const {return m_gameTitle;}
};
protected:
SystemString m_outPath;
std::unique_ptr<IFileIO> m_fileIO;
std::vector<std::unique_ptr<PartitionBuilderBase>> m_partitions;
int64_t m_discCapacity;
public:
std::function<void(size_t idx, const SystemString&, size_t)> m_progressCB;
size_t m_progressIdx = 0;
virtual ~DiscBuilderBase() = default;
DiscBuilderBase(const SystemChar* outPath, int64_t discCapacity,
std::function<void(size_t idx, const SystemString&, size_t)> progressCB)
: m_outPath(outPath), m_fileIO(NewFileIO(outPath, discCapacity)),
m_discCapacity(discCapacity), m_progressCB(progressCB) {}
DiscBuilderBase(DiscBuilderBase&&) = default;
DiscBuilderBase& operator=(DiscBuilderBase&&) = default;
IFileIO& getFileIO() {return *m_fileIO;}
};
using Partition = DiscBase::IPartition;
using Node = Partition::Node;
}
#endif // __NOD_DISC_BASE__
|
Add DiscBase::getPartitionNodeCount
|
Add DiscBase::getPartitionNodeCount
|
C++
|
mit
|
AxioDL/NODLib,RetroView/NODLib,AxioDL/NODLib,RetroView/NODLib
|
9ecac28a5f3e7464dad912151b94fa5e4bfc605f
|
Sorting/HeapSort.cpp
|
Sorting/HeapSort.cpp
|
/*
Heap Sort :
Uses an array-implemented heap to sort a list of integers.
This is a comparison based sorting algorithm which separates the input into a
sorted and unsorted region and iteratively shrinks the unsorted region by taking
the maximum(or minimum if descending order) element and moving it to the sorted region.
It uses the heap data structure (implemented using a vector here) to find the maximum or minimum.
Time complexity:
O(N * log(N)), where N is the number of integers to be sorted.
Space complexity:
O(1).
*/
#include <iostream>
#include <vector>
#include "SortingUtils.h"
using namespace std;
//creates max heap when ascending and min heap when descending
void heapify(vector<int> &heap, int parent, const int size, const int order, const bool showState){
int child = parent*2 + 1;
while (child<size){ // travels down children
if (showState) displayState(heap);
if ((order * heap[child]) < (order * heap[child+1]) and (child+1 < size)){
child++; // child is now the larger of the parent's children
// or the smaller if the the order is descending
}
if ((order * heap[parent]) < (order * heap[child])){
swap(heap[parent],heap[child]);
// if the parent is smaller(order==ascending) or larger(order==descending), then swap
}
parent = child;
child = parent*2 + 1;
if (showState) displayState(heap);
}
}
//removes largest/smallest node, replaces it and reheapifies with new heap.
void heapsort(vector<int> &heap, const int size, const int order, const bool showState){
int last = size;
while (last > 0){
swap(heap[0], heap[last-1]);
last--;
heapify(heap,0,last, order, showState);
}
}
//Makes ordered heap by "heapify"ing from highest indexed non-leaf node(curr_node) to the top node, index[0]
void make_heap(vector<int> &heap, const int size, const int order, const bool showState){
for (int curr_node = (size/2) - 1; curr_node >= 0;curr_node--){
heapify(heap, curr_node, size, order, showState);
if (showState) displayState(heap);
}
}
int main(){
size_t size;
getInputSize(size);
vector<int> values(size);
getInputValues(values, size);
int order;
string orderText;
getOrder(order, orderText);
bool showState;
getWhetherToShowState(showState);
if (showState) cout << endl << "Showing stages of making heap" << endl;
make_heap(values, size, order, showState);
if (showState){
cout << "Initial heap has been made" << endl << endl;
cout <<"Now showing state during heapify operation" << endl;
}
heapsort(values, size, order, showState);
cout << endl << "The result in " + orderText + " order is as follows : " << endl;
displayState(values);
return 0;
}
|
/*
Heap sort
---------
A comparison-based sorting algorithm that uses an array-implemented heap to
sort a list of integers.
Time complexity
---------------
O(N * log(N)), where N is the number of elements.
Space complexity
----------------
O(1).
*/
#include <iostream>
#include <vector>
#include "SortingUtils.hpp"
using namespace std;
void heapify(vector<int>& heap, int parent, const int last) {
// creates a max heap from a vector of integers
int child = parent*2 + 1;
while (child <= last) { // travel down the children
if (child + 1 <= last and heap[child + 1] > heap[child])
child++; // child is now the larger of its siblings
if (heap[parent] < heap[child])
swap(heap[parent], heap[child]); // if the parent is smaller, swap it with its child
parent = child;
child = parent*2 + 1;
}
}
void heap_sort(vector<int>& heap, const int size, const bool to_show_state) {
// remove the largest node, replace it with the last node, and re-heapify the heap
if (to_show_state)
cout << "\nPerforming heap sort on the heap...\n";
int last = size - 1;
while (last >= 0) {
swap(heap[0], heap[last]);
last--;
heapify(heap, 0, last);
if (to_show_state)
display_state(heap);
}
}
void make_heap(vector<int>& heap, const int size, const bool to_show_state) {
/*
makes an ordered heap by heapifying from highest indexed non-leaf node (curr_node)
to the top node (index[0])
*/
if (to_show_state)
cout << "\nMaking initial heap...\n";
for (int curr_node = (size/2) - 1; curr_node >= 0; curr_node--) {
heapify(heap, curr_node, size);
if (to_show_state)
display_state(heap);
}
if (to_show_state)
cout << "Initial heap has been made.\n";
}
int main() {
size_t size;
get_input_size(size);
vector<int> values(size);
get_input_values(values, size);
int order;
string order_text;
get_order(order, order_text);
bool to_show_state;
get_whether_to_show_state(to_show_state);
make_heap(values, size, to_show_state);
heap_sort(values, size, to_show_state);
if (order == -1) // descending
reverse(values.begin(), values.end());
cout << "\nThe values in " << order_text << " order are:\n";
display_state(values);
return 0;
}
|
Simplify and refactor code
|
Simplify and refactor code
|
C++
|
mit
|
eskeype/Algos,faheel/Algos,faheel/Algos
|
6b8fac3cb043e444f3c05af0a2605ec781abbfb9
|
includes/AxisInertia.hpp
|
includes/AxisInertia.hpp
|
#ifndef COFFEE_MILL_AXIS_INERTIA
#define COFFEE_MILL_AXIS_INERTIA
#include "mathematics/LinearAlgebra.hpp"
#include <vector>
namespace coffeemill
{
class AxisInertia
{
public:
AxisInertia(): calculated(false){}
AxisInertia(const std::vector<std::pair<Realvec, double>> data)
: calculated(true), system(data)
{
calculate();
}
~AxisInertia(){}
const Realvec get_axis(const int i);
void calculate();
Realvec get_CoM();
private:
bool calculated;
std::array<Realvec, 3> axises;
std::vector<std::pair<Realvec, double>> system;//(position, mass)
};
const Realvec AxisInertia::get_axis(const int i)
{
if(i < 0 || 2 < 0)
throw std::invalid_argument("out of range");
if(!calculated)
calculate();
return axises.at(i);
}
void AxisInertia::calculate()
{
Realvec center_of_mass(get_CoM());
if(length(center_of_mass) > 1e-12)
{
for(auto iter = system.begin(); iter != system.end(); ++iter)
{
iter->first -= center_of_mass;
}
}// zeroing
Matrix3 Inertia(0e0);
for(auto iter = system.begin(); iter != system.end(); ++iter)
{
Inertia(0,0) += iter->second * (iter->first[1] * iter->first[1] +
iter->first[2] * iter->first[2]);
Inertia(1,1) += iter->second * (iter->first[0] * iter->first[0] +
iter->first[2] * iter->first[2]);
Inertia(2,2) += iter->second * (iter->first[0] * iter->first[0] +
iter->first[1] * iter->first[1]);
Inertia(0,1) -= iter->second * iter->first[0] * iter->first[1];
Inertia(0,2) -= iter->second * iter->first[2] * iter->first[0];
Inertia(1,2) -= iter->second * iter->first[1] * iter->first[2];
}
Inertia(1,0) = Inertia(0,1);
Inertia(2,0) = Inertia(0,2);
Inertia(2,1) = Inertia(1,2);
JacobiSolver<3> solver(Inertia);
std::cout << "solved" << std::endl;
axises.at(0) = solver.get_eigenvec(0);
axises.at(1) = solver.get_eigenvec(1);
axises.at(2) = solver.get_eigenvec(2);
calculated = true;
return;
}
Realvec AxisInertia::get_CoM()
{
double sum_mass(0e0);
Realvec sum_pos(0e0);
for(auto iter = system.begin(); iter != system.end(); ++iter)
{
sum_pos += iter->second * (iter->first);
sum_mass += iter->second;
}
return sum_pos / sum_mass;
}
}
#endif//COFFEE_MILL_AXIS_INERTIA
|
#ifndef COFFEE_MILL_AXIS_INERTIA
#define COFFEE_MILL_AXIS_INERTIA
#include "mathematics/LinearAlgebra.hpp"
#include <vector>
namespace coffeemill
{
class AxisInertia
{
public:
AxisInertia(): calculated(false){}
AxisInertia(const std::vector<std::pair<Realvec, double>>& data)
: calculated(true), system(data)
{
calculate();
}
AxisInertia(const std::vector<Realvec>& data);
~AxisInertia(){}
const Realvec get_axis(const int i);
void calculate();
Realvec get_CoM();
private:
bool calculated;
std::array<Realvec, 3> axises;
std::vector<std::pair<Realvec, double>> system;//(position, mass)
};
AxisInertia::AxisInertia(const std::vector<Realvec>& data)
: calculated(true), system(data.size())
{
auto sysiter = system.begin();
for(auto iter = data.begin(); iter != data.end(); ++iter)
{
*sysiter = std::make_pair(*iter, 1e0);
++sysiter;
}
calculate();
}
const Realvec AxisInertia::get_axis(const int i)
{
if(i < 0 || 2 < 0)
throw std::invalid_argument("out of range");
if(!calculated)
calculate();
return axises.at(i);
}
void AxisInertia::calculate()
{
Realvec center_of_mass(get_CoM());
if(length(center_of_mass) > 1e-12)
{
for(auto iter = system.begin(); iter != system.end(); ++iter)
{
iter->first -= center_of_mass;
}
}// zeroing
Matrix3 Inertia(0e0);
for(auto iter = system.begin(); iter != system.end(); ++iter)
{
Inertia(0,0) += iter->second * (iter->first[1] * iter->first[1] +
iter->first[2] * iter->first[2]);
Inertia(1,1) += iter->second * (iter->first[0] * iter->first[0] +
iter->first[2] * iter->first[2]);
Inertia(2,2) += iter->second * (iter->first[0] * iter->first[0] +
iter->first[1] * iter->first[1]);
Inertia(0,1) -= iter->second * iter->first[0] * iter->first[1];
Inertia(0,2) -= iter->second * iter->first[2] * iter->first[0];
Inertia(1,2) -= iter->second * iter->first[1] * iter->first[2];
}
Inertia(1,0) = Inertia(0,1);
Inertia(2,0) = Inertia(0,2);
Inertia(2,1) = Inertia(1,2);
JacobiSolver<3> solver(Inertia);
std::cout << "solved" << std::endl;
axises.at(0) = solver.get_eigenvec(0);
axises.at(1) = solver.get_eigenvec(1);
axises.at(2) = solver.get_eigenvec(2);
calculated = true;
return;
}
Realvec AxisInertia::get_CoM()
{
double sum_mass(0e0);
Realvec sum_pos(0e0);
for(auto iter = system.begin(); iter != system.end(); ++iter)
{
sum_pos += iter->second * (iter->first);
sum_mass += iter->second;
}
return sum_pos / sum_mass;
}
}
#endif//COFFEE_MILL_AXIS_INERTIA
|
enable AxisInertia to get vector<Realvec>
|
modify: enable AxisInertia to get vector<Realvec>
|
C++
|
mit
|
ToruNiina/Coffee-mill,ToruNiina/Coffee-mill
|
afa694feffdef47312c04080affb01803389e0b7
|
browser/permission_manager.cc
|
browser/permission_manager.cc
|
// Copyright (c) 2015 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-CHROMIUM file.
#include "browser/permission_manager.h"
#include "base/callback.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/permission_type.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
namespace brightray {
PermissionManager::PermissionManager() {
}
PermissionManager::~PermissionManager() {
}
int PermissionManager::RequestPermission(
content::PermissionType permission,
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
const base::Callback<void(content::PermissionStatus)>& callback) {
if (permission == content::PermissionType::MIDI_SYSEX) {
content::ChildProcessSecurityPolicy::GetInstance()->
GrantSendMidiSysExMessage(render_frame_host->GetProcess()->GetID());
}
callback.Run(content::PERMISSION_STATUS_GRANTED);
return kNoPendingOperation;
}
int PermissionManager::RequestPermissions(
const std::vector<content::PermissionType>& permissions,
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
const base::Callback<void(
const std::vector<content::PermissionStatus>&)>& callback) {
std::vector<content::PermissionStatus> permissionStatuses;
for (auto permission : permissions) {
if (permission == content::PermissionType::MIDI_SYSEX) {
content::ChildProcessSecurityPolicy::GetInstance()->
GrantSendMidiSysExMessage(render_frame_host->GetProcess()->GetID());
}
permissionStatuses.push_back(content::PERMISSION_STATUS_GRANTED);
}
callback.Run(permissionStatuses);
return kNoPendingOperation;
}
void PermissionManager::CancelPermissionRequest(int request_id) {
}
void PermissionManager::ResetPermission(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {
}
content::PermissionStatus PermissionManager::GetPermissionStatus(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {
return content::PERMISSION_STATUS_GRANTED;
}
void PermissionManager::RegisterPermissionUsage(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {
}
int PermissionManager::SubscribePermissionStatusChange(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin,
const base::Callback<void(content::PermissionStatus)>& callback) {
return -1;
}
void PermissionManager::UnsubscribePermissionStatusChange(int subscription_id) {
}
} // namespace brightray
|
// Copyright (c) 2015 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-CHROMIUM file.
#include "browser/permission_manager.h"
#include "base/callback.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/permission_type.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
namespace brightray {
PermissionManager::PermissionManager() {
}
PermissionManager::~PermissionManager() {
}
int PermissionManager::RequestPermission(
content::PermissionType permission,
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
const base::Callback<void(content::PermissionStatus)>& callback) {
if (permission == content::PermissionType::MIDI_SYSEX) {
content::ChildProcessSecurityPolicy::GetInstance()->
GrantSendMidiSysExMessage(render_frame_host->GetProcess()->GetID());
}
callback.Run(content::PermissionStatus::GRANTED);
return kNoPendingOperation;
}
int PermissionManager::RequestPermissions(
const std::vector<content::PermissionType>& permissions,
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
const base::Callback<void(
const std::vector<content::PermissionStatus>&)>& callback) {
std::vector<content::PermissionStatus> permissionStatuses;
for (auto permission : permissions) {
if (permission == content::PermissionType::MIDI_SYSEX) {
content::ChildProcessSecurityPolicy::GetInstance()->
GrantSendMidiSysExMessage(render_frame_host->GetProcess()->GetID());
}
permissionStatuses.push_back(content::PermissionStatus::GRANTED);
}
callback.Run(permissionStatuses);
return kNoPendingOperation;
}
void PermissionManager::CancelPermissionRequest(int request_id) {
}
void PermissionManager::ResetPermission(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {
}
content::PermissionStatus PermissionManager::GetPermissionStatus(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {
return content::PermissionStatus::GRANTED;
}
void PermissionManager::RegisterPermissionUsage(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin) {
}
int PermissionManager::SubscribePermissionStatusChange(
content::PermissionType permission,
const GURL& requesting_origin,
const GURL& embedding_origin,
const base::Callback<void(content::PermissionStatus)>& callback) {
return -1;
}
void PermissionManager::UnsubscribePermissionStatusChange(int subscription_id) {
}
} // namespace brightray
|
Rename PERMISSION_STATUS enum value
|
Rename PERMISSION_STATUS enum value
|
C++
|
mit
|
atom/brightray,atom/brightray,brave/brightray,brave/brightray
|
32bd676bb33105818e18759ccbb0a109ad29a5a5
|
src/arch/wasm/long-double.cpp
|
src/arch/wasm/long-double.cpp
|
#ifdef __wasm__
#include <type_traits>
#include <cstdint>
namespace {
struct Tetra
{
[[gnu::mode(TF)]] typedef float Real;
unsigned __int128 mantissa: 112;
unsigned int exp : 15;
unsigned int sign: 1;
Tetra(Real);
explicit operator Real() const;
explicit operator __int128() const;
explicit operator bool() const;
bool isnan() const;
};
Tetra::Tetra(Real real)
{
static_assert(sizeof(Tetra) == sizeof(Real), "Bug: [[gnu::mode(TF)]] float does not fit Tetra.");
__builtin_memcpy(this, &real, sizeof(Tetra));
}
Tetra::operator Real() const
{
Real result;
__builtin_memcpy(&result, this, sizeof(Tetra));
return result;
}
Tetra::operator __int128() const
{
__int128 result;
__builtin_memcpy(&result, this, sizeof(Tetra));
return result;
}
Tetra::operator bool() const
{
return exp || mantissa;
}
bool Tetra::isnan() const
{
return exp == 0x7fff && mantissa;
}
} // namespace
bool operator==(Tetra a, Tetra b)
{
return __int128(a) == __int128(b) && a.exp != 0x7fff || !(a || b);
}
extern "C" {
int __unordtf2(Tetra::Real a, Tetra::Real b)
{
return Tetra(a).isnan() || Tetra(b).isnan();
}
int __eqtf2(Tetra::Real a, Tetra::Real b)
{
return Tetra(a) == Tetra(b);
}
} // extern "C"
#endif // __wasm__
|
#ifdef __wasm__
#include <cstdint>
namespace {
struct Tetra
{
[[gnu::mode(TF)]] typedef float Real;
unsigned __int128 mantissa: 112;
unsigned int exp : 15;
unsigned int sign: 1;
Tetra(Real);
explicit operator Real() const;
explicit operator __int128() const;
explicit operator bool() const;
bool isnan() const;
};
Tetra::Tetra(Real real)
{
static_assert(sizeof(Tetra) == sizeof(Real), "Bug: [[gnu::mode(TF)]] float does not fit Tetra.");
__builtin_memcpy(this, &real, sizeof(Tetra));
}
Tetra::operator Real() const
{
Real result;
__builtin_memcpy(&result, this, sizeof(Tetra));
return result;
}
Tetra::operator __int128() const
{
__int128 result;
__builtin_memcpy(&result, this, sizeof(Tetra));
return result;
}
Tetra::operator bool() const
{
return exp || mantissa;
}
bool Tetra::isnan() const
{
return exp == 0x7fff && mantissa;
}
} // namespace
bool operator==(Tetra a, Tetra b)
{
return __int128(a) == __int128(b) && a.exp != 0x7fff || !(a || b);
}
extern "C" {
int __unordtf2(Tetra::Real a, Tetra::Real b)
{
return Tetra(a).isnan() || Tetra(b).isnan();
}
int __eqtf2(Tetra::Real a, Tetra::Real b)
{
return Tetra(a) == Tetra(b);
}
} // extern "C"
#endif // __wasm__
|
Remove #include <type_traits> because it is no longer tested if long double is quadruple precision
|
Remove #include <type_traits> because it is no longer tested if long double is quadruple precision
|
C++
|
mit
|
jdh8/metallic,jdh8/metallic,jdh8/metallic,jdh8/metallic,jdh8/metallic
|
226244508734c2408ad57d1188fd5513f315e653
|
radiosity.cpp
|
radiosity.cpp
|
#include "trace.h"
#include "lib/output.h"
#include "lib/image.h"
#include "lib/lambertian.h"
#include "lib/range.h"
#include "lib/runtime.h"
#include "lib/triangle.h"
#include "lib/stats.h"
#include "lib/xorshift.h"
#include <assimp/Importer.hpp> // C++ importer interface
#include <assimp/scene.h> // Output data structure
#include <assimp/postprocess.h> // Post processing flags
#include <docopt.h>
#include <ThreadPool.h>
#include <math.h>
#include <vector>
#include <map>
#include <iostream>
#include <unordered_set>
#include <chrono>
Color trace(const Vec& origin, const Vec& dir,
const Tree& triangles_tree, const std::vector<Light>& lights,
int depth, const Configuration& conf)
{
//xorshift64star<float> uniform{4};
Stats::instance().num_rays += 1;
if (depth > conf.max_depth) {
return {};
}
// intersection
float dist_to_triangle, s, t;
auto triangle_pt = triangles_tree.intersect(
aiRay(origin, dir), dist_to_triangle, s, t);
if (!triangle_pt) {
return conf.bg_color;
}
// simple raycast
const auto& triangle = *triangle_pt;
auto result = triangle.diffuse;
result.a = dist_to_triangle;
//Color result { uniform(), uniform(), uniform(), dist_to_triangle};
return result;
}
Triangles triangles_from_scene(const aiScene* scene) {
Triangles triangles;
for (auto node : make_range(
scene->mRootNode->mChildren, scene->mRootNode->mNumChildren))
{
if (node->mNumMeshes == 0) {
continue;
}
const auto& T = node->mTransformation;
const aiMatrix3x3 Tp(T); // trafo without translation
for (auto mesh_index : make_range(node->mMeshes, node->mNumMeshes)) {
const auto& mesh = *scene->mMeshes[mesh_index];
aiColor4D ambient, diffuse;
scene->mMaterials[mesh.mMaterialIndex]->Get(
AI_MATKEY_COLOR_AMBIENT, ambient);
scene->mMaterials[mesh.mMaterialIndex]->Get(
AI_MATKEY_COLOR_DIFFUSE, diffuse);
for (aiFace face : make_range(mesh.mFaces, mesh.mNumFaces)) {
assert(face.mNumIndices == 3);
triangles.push_back(Triangle{
// vertices
{{
T * mesh.mVertices[face.mIndices[0]],
T * mesh.mVertices[face.mIndices[1]],
T * mesh.mVertices[face.mIndices[2]]
}},
// normals
{{
Tp * mesh.mNormals[face.mIndices[0]],
Tp * mesh.mNormals[face.mIndices[1]],
Tp * mesh.mNormals[face.mIndices[2]]
}},
ambient,
diffuse
});
}
}
}
return triangles;
}
static const char USAGE[] =
R"(Usage: raytracer <filename> [options]
Options:
-w --width=<px> Width of the image [default: 640].
-a --aspect=<num> Aspect ratio of the image. If the model has
specified the aspect ratio, it will be
used. Otherwise default value is 1.
-d --max-depth=<int> Maximum recursion depth for raytracing
[default: 3].
--shadow=<float> Intensity of shadow [default: 0.5].
--background=<3x float> Background color [default: 0 0 0].
-p --pixel-samples=<int> Number of samples per pixel [default: 1].
-m --monte-carlo-samples=<int> Monto Carlo samples per ray [default: 8].
Used only in pathtracer.
-t --threads=<int> Number of threads [default: 1].
--inverse-gamma=<float> Inverse of gamma for gamma correction
[default: 0.454545].
--no-gamma-correction Disables gamma correction.
)";
int main(int argc, char const *argv[])
{
// parameters
std::map<std::string, docopt::value> args =
docopt::docopt(USAGE, {argv + 1, argv + argc}, true, "raytracer 0.2");
const Configuration conf { args["--max-depth"].asLong()
, std::stof(args["--shadow"].asString())
, args["--pixel-samples"].asLong()
, args["--monte-carlo-samples"].asLong()
, args["--threads"].asLong()
, args["--background"].asString()
, std::stof(args["--inverse-gamma"].asString())
, args["--no-gamma-correction"].asBool()
};
// import scene
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(
args["<filename>"].asString().c_str(),
aiProcess_CalcTangentSpace |
aiProcess_Triangulate |
aiProcess_JoinIdenticalVertices |
aiProcess_GenNormals |
aiProcess_SortByPType);
if (!scene) {
std::cout << importer.GetErrorString() << std::endl;
return 1;
}
// setup camera
assert(scene->mNumCameras == 1); // we can deal only with a single camera
auto& sceneCam = *scene->mCameras[0];
if (args["--aspect"]) {
sceneCam.mAspect = std::stof(args["--aspect"].asString());
assert(sceneCam.mAspect > 0);
} else if (sceneCam.mAspect == 0) {
sceneCam.mAspect = 1.f;
}
auto* camNode = scene->mRootNode->FindNode(sceneCam.mName);
assert(camNode != nullptr);
const Camera cam(camNode->mTransformation, sceneCam);
// setup light
// we can deal only with one single or no light at all
assert(scene->mNumLights == 0 || scene->mNumLights == 1);
std::vector<Light> lights;
if(scene->mNumLights == 1) {
auto& rawLight = *scene->mLights[0];
auto* lightNode = scene->mRootNode->FindNode(rawLight.mName);
assert(lightNode != nullptr);
const auto& LT = lightNode->mTransformation;
lights.push_back(
{ LT * aiVector3D()
, aiColor4D
{ rawLight.mColorDiffuse.r
, rawLight.mColorDiffuse.g
, rawLight.mColorDiffuse.b
, 1
}
});
}
// load triangles from the scene into a kd-tree
auto triangles = triangles_from_scene(scene);
Stats::instance().num_triangles = triangles.size();
Tree tree(std::move(triangles));
//
// Raytracer
//
int width = args["--width"].asLong();
assert(width > 0);
int height = width / cam.mAspect;
Image image(width, height);
{
Runtime rt(Stats::instance().runtime_ms);
std::cerr << "Rendering ";
ThreadPool pool(conf.num_threads);
std::vector<std::future<void>> tasks;
for (int y = 0; y < height; ++y) {
tasks.emplace_back(pool.enqueue([
&image, &cam, &tree, &lights, width, height, y, &conf]()
{
float dx, dy;
xorshift64star<float> gen(42);
for (int x = 0; x < width; ++x) {
for (int i = 0; i < conf.num_pixel_samples; ++i) {
dx = gen();
dy = gen();
auto cam_dir = cam.raster2cam(
aiVector2D(x + dx, y + dy), width, height);
Stats::instance().num_prim_rays += 1;
image(x, y) += trace(cam.mPosition, cam_dir, tree,
lights, 0, conf);
}
image(x, y) /=
static_cast<float>(conf.num_pixel_samples);
// gamma correction
if (conf.gamma_correction_enabled) {
image(x, y).r = powf(image(x, y).r, conf.inverse_gamma);
image(x, y).g = powf(image(x, y).g, conf.inverse_gamma);
image(x, y).b = powf(image(x, y).b, conf.inverse_gamma);
}
}
}));
}
long completed = 0;
for (auto& task: tasks) {
task.get();
completed += 1;
float progress = static_cast<float>(completed) / tasks.size();
int bar_width = progress * 20;
std::cerr
<< "\rRendering "
<< "[" << std::string(bar_width, '-')
<< std::string(20 - bar_width, ' ') << "] "
<< std::setfill(' ') << std::setw(6)
<< std::fixed << std::setprecision(2) << (progress * 100.0) << '%';
std::cerr.flush();
}
std::cerr << std::endl;
// Render feature lines after
// "Ray Tracing NPR-Style Feature Lines" by Choudhury and Parker.
std::cerr << "Drawing mesh lines ";
std::vector<std::future<void>> mesh_tasks;
float offset = 1.f;
std::vector<Vec2> offsets =
{ Vec2(0.f, 0.f)
, Vec2(offset, 0.f)
, Vec2(offset, offset)
, Vec2(0.f, offset)
, Vec2(0.f, offset / 2)
, Vec2(offset / 2, offset)
, Vec2(offset, offset / 2)
, Vec2(offset / 2, 0.f)
};
for (int y = 0; y < height; ++y) {
mesh_tasks.emplace_back(pool.enqueue([
&image, &offsets, &cam, &tree, &lights, width, height, y, &conf]()
{
for (int x = 0; x < width; ++x) {
float dist_to_triangle, s, t;
std::unordered_set<std::uintptr_t> triangle_ids;
// Shoot center ray.
auto cam_dir = cam.raster2cam(
aiVector2D(x + 0.5f, y + 0.5f), width, height);
auto center_id = reinterpret_cast<std::uintptr_t>(tree.intersect(
Ray(cam.mPosition, cam_dir), dist_to_triangle, s, t));
triangle_ids.insert(center_id);
// Sample disc rays around center.
// TODO: Sample disc with Poisson or similar.
for ( auto offset : offsets) {
cam_dir = cam.raster2cam(
aiVector2D(x + offset[0], y + offset[1]), width, height);
auto triangle_pt = reinterpret_cast<std::uintptr_t>(tree.intersect(
Ray(cam.mPosition, cam_dir), dist_to_triangle, s, t));
triangle_ids.insert(triangle_pt);
}
const float M_2 = 0.5f * offsets.size();
// All hit primitives except the one hit by center.
const float m = triangle_ids.size() - 1.f;
float e = 1.f - std::pow( std::abs(m - M_2) / M_2, 10 );
image(x, y) = image(x, y) * (1.f - e);
}
}));
}
completed = 0;
for (auto& task: mesh_tasks) {
task.get();
completed += 1;
float progress = static_cast<float>(completed) / mesh_tasks.size();
int bar_width = progress * 20;
std::cerr
<< "\rDrawing mesh lines "
<< "[" << std::string(bar_width, '-')
<< std::string(20 - bar_width, ' ') << "] "
<< std::setfill(' ') << std::setw(6)
<< std::fixed << std::setprecision(2) << (progress * 100.0) << '%';
std::cerr.flush();
}
std::cerr << std::endl;
}
// output stats
std::cerr << Stats::instance() << std::endl;
// output image
std::cout << image << std::endl;
return 0;
}
|
#include "trace.h"
#include "lib/output.h"
#include "lib/image.h"
#include "lib/lambertian.h"
#include "lib/range.h"
#include "lib/runtime.h"
#include "lib/triangle.h"
#include "lib/stats.h"
#include "lib/xorshift.h"
#include <assimp/Importer.hpp> // C++ importer interface
#include <assimp/scene.h> // Output data structure
#include <assimp/postprocess.h> // Post processing flags
#include <docopt.h>
#include <ThreadPool.h>
#include <math.h>
#include <vector>
#include <map>
#include <iostream>
#include <unordered_set>
#include <chrono>
Color trace(const Vec& origin, const Vec& dir,
const Tree& triangles_tree, const std::vector<Light>& lights,
int depth, const Configuration& conf)
{
//xorshift64star<float> uniform{4};
Stats::instance().num_rays += 1;
if (depth > conf.max_depth) {
return {};
}
// intersection
float dist_to_triangle, s, t;
auto triangle_pt = triangles_tree.intersect(
aiRay(origin, dir), dist_to_triangle, s, t);
if (!triangle_pt) {
return conf.bg_color;
}
// simple raycast
const auto& triangle = *triangle_pt;
auto result = triangle.diffuse;
result.a = dist_to_triangle;
//Color result { uniform(), uniform(), uniform(), dist_to_triangle};
return result;
}
Triangles triangles_from_scene(const aiScene* scene) {
Triangles triangles;
for (auto node : make_range(
scene->mRootNode->mChildren, scene->mRootNode->mNumChildren))
{
if (node->mNumMeshes == 0) {
continue;
}
const auto& T = node->mTransformation;
const aiMatrix3x3 Tp(T); // trafo without translation
for (auto mesh_index : make_range(node->mMeshes, node->mNumMeshes)) {
const auto& mesh = *scene->mMeshes[mesh_index];
aiColor4D ambient, diffuse;
scene->mMaterials[mesh.mMaterialIndex]->Get(
AI_MATKEY_COLOR_AMBIENT, ambient);
scene->mMaterials[mesh.mMaterialIndex]->Get(
AI_MATKEY_COLOR_DIFFUSE, diffuse);
for (aiFace face : make_range(mesh.mFaces, mesh.mNumFaces)) {
assert(face.mNumIndices == 3);
triangles.push_back(Triangle{
// vertices
{{
T * mesh.mVertices[face.mIndices[0]],
T * mesh.mVertices[face.mIndices[1]],
T * mesh.mVertices[face.mIndices[2]]
}},
// normals
{{
Tp * mesh.mNormals[face.mIndices[0]],
Tp * mesh.mNormals[face.mIndices[1]],
Tp * mesh.mNormals[face.mIndices[2]]
}},
ambient,
diffuse
});
}
}
}
return triangles;
}
static const char USAGE[] =
R"(Usage: raytracer <filename> [options]
Options:
-w --width=<px> Width of the image [default: 640].
-a --aspect=<num> Aspect ratio of the image. If the model has
specified the aspect ratio, it will be
used. Otherwise default value is 1.
-d --max-depth=<int> Maximum recursion depth for raytracing
[default: 3].
--shadow=<float> Intensity of shadow [default: 0.5].
--background=<3x float> Background color [default: 0 0 0].
-p --pixel-samples=<int> Number of samples per pixel [default: 1].
-m --monte-carlo-samples=<int> Monto Carlo samples per ray [default: 8].
Used only in pathtracer.
-t --threads=<int> Number of threads [default: 1].
--inverse-gamma=<float> Inverse of gamma for gamma correction
[default: 0.454545].
--no-gamma-correction Disables gamma correction.
)";
int main(int argc, char const *argv[])
{
// parameters
std::map<std::string, docopt::value> args =
docopt::docopt(USAGE, {argv + 1, argv + argc}, true, "raytracer 0.2");
const Configuration conf { args["--max-depth"].asLong()
, std::stof(args["--shadow"].asString())
, args["--pixel-samples"].asLong()
, args["--monte-carlo-samples"].asLong()
, args["--threads"].asLong()
, args["--background"].asString()
, std::stof(args["--inverse-gamma"].asString())
, args["--no-gamma-correction"].asBool()
};
// import scene
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(
args["<filename>"].asString().c_str(),
aiProcess_CalcTangentSpace |
aiProcess_Triangulate |
aiProcess_JoinIdenticalVertices |
aiProcess_GenNormals |
aiProcess_SortByPType);
if (!scene) {
std::cout << importer.GetErrorString() << std::endl;
return 1;
}
// setup camera
assert(scene->mNumCameras == 1); // we can deal only with a single camera
auto& sceneCam = *scene->mCameras[0];
if (args["--aspect"]) {
sceneCam.mAspect = std::stof(args["--aspect"].asString());
assert(sceneCam.mAspect > 0);
} else if (sceneCam.mAspect == 0) {
sceneCam.mAspect = 1.f;
}
auto* camNode = scene->mRootNode->FindNode(sceneCam.mName);
assert(camNode != nullptr);
const Camera cam(camNode->mTransformation, sceneCam);
// setup light
// we can deal only with one single or no light at all
assert(scene->mNumLights == 0 || scene->mNumLights == 1);
std::vector<Light> lights;
if(scene->mNumLights == 1) {
auto& rawLight = *scene->mLights[0];
auto* lightNode = scene->mRootNode->FindNode(rawLight.mName);
assert(lightNode != nullptr);
const auto& LT = lightNode->mTransformation;
lights.push_back(
{ LT * aiVector3D()
, aiColor4D
{ rawLight.mColorDiffuse.r
, rawLight.mColorDiffuse.g
, rawLight.mColorDiffuse.b
, 1
}
});
}
// load triangles from the scene into a kd-tree
auto triangles = triangles_from_scene(scene);
Stats::instance().num_triangles = triangles.size();
Tree tree(std::move(triangles));
//
// Raytracer
//
int width = args["--width"].asLong();
assert(width > 0);
int height = width / cam.mAspect;
Image image(width, height);
{
Runtime rt(Stats::instance().runtime_ms);
std::cerr << "Rendering ";
ThreadPool pool(conf.num_threads);
std::vector<std::future<void>> tasks;
for (int y = 0; y < height; ++y) {
tasks.emplace_back(pool.enqueue([
&image, &cam, &tree, &lights, width, height, y, &conf]()
{
float dx, dy;
xorshift64star<float> gen(42);
for (int x = 0; x < width; ++x) {
for (int i = 0; i < conf.num_pixel_samples; ++i) {
dx = gen();
dy = gen();
auto cam_dir = cam.raster2cam(
aiVector2D(x + dx, y + dy), width, height);
Stats::instance().num_prim_rays += 1;
image(x, y) += trace(cam.mPosition, cam_dir, tree,
lights, 0, conf);
}
image(x, y) /=
static_cast<float>(conf.num_pixel_samples);
// gamma correction
if (conf.gamma_correction_enabled) {
image(x, y).r = powf(image(x, y).r, conf.inverse_gamma);
image(x, y).g = powf(image(x, y).g, conf.inverse_gamma);
image(x, y).b = powf(image(x, y).b, conf.inverse_gamma);
}
}
}));
}
long completed = 0;
for (auto& task: tasks) {
task.get();
completed += 1;
float progress = static_cast<float>(completed) / tasks.size();
int bar_width = progress * 20;
std::cerr
<< "\rRendering "
<< "[" << std::string(bar_width, '-')
<< std::string(20 - bar_width, ' ') << "] "
<< std::setfill(' ') << std::setw(6)
<< std::fixed << std::setprecision(2) << (progress * 100.0) << '%';
std::cerr.flush();
}
std::cerr << std::endl;
// Render feature lines after
// "Ray Tracing NPR-Style Feature Lines" by Choudhury and Parker.
std::cerr << "Drawing mesh lines ";
std::vector<std::future<void>> mesh_tasks;
float offset = 1.f;
std::vector<Vec2> offsets =
{ Vec2(0.f, 0.f)
, Vec2(offset, 0.f)
, Vec2(offset, offset)
, Vec2(0.f, offset)
, Vec2(0.f, offset / 2)
, Vec2(offset / 2, offset)
, Vec2(offset, offset / 2)
, Vec2(offset / 2, 0.f)
};
for (int y = 0; y < height; ++y) {
mesh_tasks.emplace_back(pool.enqueue([
&image, &offsets, &cam, &tree, &lights, width, height, y, &conf]()
{
for (int x = 0; x < width; ++x) {
float dist_to_triangle, s, t;
std::unordered_set<std::uintptr_t> triangle_ids;
// Shoot center ray.
auto cam_dir = cam.raster2cam(
aiVector2D(x + 0.5f, y + 0.5f), width, height);
auto center_id = reinterpret_cast<std::uintptr_t>(tree.intersect(
Ray(cam.mPosition, cam_dir), dist_to_triangle, s, t));
triangle_ids.insert(center_id);
// Sample disc rays around center.
// TODO: Sample disc with Poisson or similar.
for ( auto offset : offsets) {
cam_dir = cam.raster2cam(
aiVector2D(x + offset[0], y + offset[1]), width, height);
auto triangle_pt = reinterpret_cast<std::uintptr_t>(tree.intersect(
Ray(cam.mPosition, cam_dir), dist_to_triangle, s, t));
triangle_ids.insert(triangle_pt);
}
const float M_2 = 0.5f * offsets.size();
// All hit primitives except the one hit by center.
const float m = triangle_ids.size() - 1.f;
float e = std::pow( std::abs(m - M_2) / M_2, 10 );
image(x, y) = image(x, y) * (e);
}
}));
}
completed = 0;
for (auto& task: mesh_tasks) {
task.get();
completed += 1;
float progress = static_cast<float>(completed) / mesh_tasks.size();
int bar_width = progress * 20;
std::cerr
<< "\rDrawing mesh lines "
<< "[" << std::string(bar_width, '-')
<< std::string(20 - bar_width, ' ') << "] "
<< std::setfill(' ') << std::setw(6)
<< std::fixed << std::setprecision(2) << (progress * 100.0) << '%';
std::cerr.flush();
}
std::cerr << std::endl;
}
// output stats
std::cerr << Stats::instance() << std::endl;
// output image
std::cout << image << std::endl;
return 0;
}
|
Simplify e method.
|
Simplify e method.
Former-commit-id: 392b44f6e081e9d214865ab33d53339c8d060654
|
C++
|
apache-2.0
|
turner-renderer/turner,turner-renderer/turner,blacklab/renderer,turner-renderer/turner,jeschkies/renderer,turner-renderer/turner,jeschkies/renderer
|
830281b9eeb7b939676d338c505a79fc6cf6582b
|
indexer/cell_coverer.hpp
|
indexer/cell_coverer.hpp
|
#pragma once
#include "cell_id.hpp"
#include "../std/queue.hpp"
#include "../std/vector.hpp"
inline bool IntersectsHoriz(CoordT x1, CoordT y1, CoordT x2, CoordT y2,
CoordT y, CoordT l, CoordT r)
{
CoordT d = (y1 - y) * (y2 - y);
if (d > 0) return false;
CoordT x = x1 + (x2 - x1) * (y - y1) / (y2 - y1);
if ((l - x) * (r - x) <= 0) return true; else return false;
}
inline bool IntersectsVert(CoordT x1, CoordT y1, CoordT x2, CoordT y2,
CoordT x, CoordT b, CoordT t)
{
CoordT d = (x1 - x) * (x2 - x);
if (d > 0) return false;
CoordT y = y1 + (y2 - y1) * (x - x1) / (x2 - x1);
if ((b - y) * (t - y) <= 0) return true; else return false;
}
template <typename BoundsT, typename CellIdT>
inline bool CellIntersects(vector<CoordPointT> const & polyLine, CellIdT id)
{
CoordT minX, minY, maxX, maxY;
CellIdConverter<BoundsT, CellIdT>::GetCellBounds(id, minX, minY, maxX, maxY);
CoordPointT minPoint = make_pair(minX, minY);
CoordPointT maxPoint = make_pair(maxX, maxY);
for (size_t i = 0; i < polyLine.size() - 1; ++i)
{
if (IntersectsHoriz(polyLine[i].first, polyLine[i].second,
polyLine[i + 1].first, polyLine[i + 1].second,
minPoint.second, minPoint.first, maxPoint.first)) return true;
if (IntersectsHoriz(polyLine[i].first, polyLine[i].second,
polyLine[i + 1].first, polyLine[i + 1].second,
maxPoint.second, minPoint.first, maxPoint.first)) return true;
if (IntersectsVert(polyLine[i].first, polyLine[i].second,
polyLine[i + 1].first, polyLine[i + 1].second,
minPoint.first, minPoint.second, maxPoint.second)) return true;
if (IntersectsVert(polyLine[i].first, polyLine[i].second,
polyLine[i + 1].first, polyLine[i + 1].second,
maxPoint.first, minPoint.second, maxPoint.second)) return true;
}
return false;
}
template <typename BoundsT, typename CellIdT>
inline void SplitCell(vector<CoordPointT> const & polyLine, queue<CellIdT> & cellQueue)
{
CellIdT id = cellQueue.front();
cellQueue.pop();
for (size_t i = 0; i < 4; ++i)
{
CellIdT child = id.Child(i);
if (CellIntersects<BoundsT>(polyLine, child))
{
cellQueue.push(child);
}
}
}
template <typename ItT>
inline bool FindBounds(ItT begin, ItT end,
CoordT & minX, CoordT & minY, CoordT & maxX, CoordT & maxY)
{
if (begin == end) return false;
minX = begin->first;
maxX = begin->first;
minY = begin->second;
maxY = begin->second;
for (ItT it = begin; it != end; ++it)
{
if (it->first < minX) minX = it->first;
if (it->first > maxX) maxX = it->first;
if (it->second < minY) minY = it->second;
if (it->second > maxY) maxY = it->second;
}
return true;
}
template <typename BoundsT, typename CellIdT>
inline CellIdT CoverPoint(CoordPointT const & point)
{
return CellIdConverter<BoundsT, CellIdT>::ToCellId(point.first, point.second);
}
template <typename BoundsT, typename CellIdT>
inline void CoverPolyLine(vector< CoordPointT > const & polyLine, size_t cellDepth,
vector<CellIdT> & cells)
{
CoordT minX = 0, minY = 0, maxX = 0, maxY = 0;
FindBounds(polyLine.begin(), polyLine.end(), minX, minY, maxX, maxY);
CellIdT commonCell =
CellIdConverter<BoundsT, CellIdT>::Cover2PointsWithCell(minX, minY, maxX, maxY);
queue<CellIdT> cellQueue;
cellQueue.push(commonCell);
while (cellQueue.front().Level() < static_cast<int>(cellDepth)) // cellQueue.size() < cells_count
{
SplitCell<BoundsT>(polyLine, cellQueue);
}
while (!cellQueue.empty())
{
cells.push_back(cellQueue.front());
cellQueue.pop();
}
}
template <typename BoundsT, typename CellIdT>
inline void SplitRectCell(CellIdT id,
CoordT minX, CoordT minY,
CoordT maxX, CoordT maxY,
vector<CellIdT> & result)
{
for (size_t i = 0; i < 4; ++i)
{
CellIdT child = id.Child(i);
CoordT minCellX, minCellY, maxCellX, maxCellY;
CellIdConverter<BoundsT, CellIdT>::GetCellBounds(child, minCellX, minCellY, maxCellX, maxCellY);
if (!((maxX < minCellX) || (minX > maxCellX) || (maxY < minCellY) || (minY > maxCellY)))
result.push_back(child);
}
}
template <typename BoundsT, typename CellIdT>
inline void CoverRect(CoordT minX, CoordT minY,
CoordT maxX, CoordT maxY,
size_t cells_count,
vector<CellIdT> & cells)
{
ASSERT_LESS(minX, maxX, ());
ASSERT_LESS(minY, maxY, ());
if (minX < BoundsT::minX) minX = BoundsT::minX;
if (minY < BoundsT::minY) minY = BoundsT::minY;
if (maxX > BoundsT::maxX) maxX = BoundsT::maxX;
if (maxY > BoundsT::maxY) maxY = BoundsT::maxY;
if (minX >= maxX || minY >= maxY)
return;
CellIdT commonCell =
CellIdConverter<BoundsT, CellIdT>::Cover2PointsWithCell(minX, minY, maxX, maxY);
vector<CellIdT> result;
queue<CellIdT> cellQueue;
cellQueue.push(commonCell);
while (!cellQueue.empty() && cellQueue.size() + result.size() < cells_count)
{
CellIdT id = cellQueue.front();
cellQueue.pop();
if (id.Level() == CellIdT::DEPTH_LEVELS - 1)
{
result.push_back(id);
break;
}
vector<CellIdT> children;
SplitRectCell<BoundsT>(id, minX, minY, maxX, maxY, children);
// Children shouldn't be empty, but if it is, ignore this cellid in release.
ASSERT(!children.empty(), (id, minX, minY, maxX, maxY));
if (children.empty())
{
result.push_back(id);
continue;
}
if (cellQueue.size() + result.size() + children.size() <= cells_count)
{
for (size_t i = 0; i < children.size(); ++i)
cellQueue.push(children[i]);
}
else
result.push_back(id);
}
for (; !cellQueue.empty(); cellQueue.pop())
result.push_back(cellQueue.front());
for (size_t i = 0; i < result.size(); ++i)
{
CellIdT id = result[i];
while (id.Level() < CellIdT::DEPTH_LEVELS - 1)
{
vector<CellIdT> children;
SplitRectCell<BoundsT>(id, minX, minY, maxX, maxY, children);
if (children.size() == 1)
id = children[0];
else
break;
}
result[i] = id;
}
ASSERT_LESS_OR_EQUAL(result.size(), cells_count, (minX, minY, maxX, maxY));
cells.insert(cells.end(), result.begin(), result.end());
}
/*
template <typename BoundsT, typename CellIdT>
inline void CoverPolygon(vector<CoordPointT> const & polyLine, size_t cellDepth,
vector<CellIdT> & cells)
{
CoverPolyLine<BoundsT>(polyLine, cellDepth, cells);
if (cells.size() < 8)
return;
CellIdT minX = CellX(cells[0]), minY = CellY(cells[0]),
maxX = CellX(cells[0]), maxY = CellY(cells[0]);
for (size_t i = 1; i < cells.size(); ++i)
{
CellIdT cellX = CellX(cells[i]);
CellIdT cellY = CellY(cells[i]);
if (cellX.m_V < minX.m_V) minX.m_V = cellX.m_V;
if (cellY.m_V < minY.m_V) minY.m_V = cellY.m_V;
if (cellX.m_V > maxX.m_V) maxX.m_V = cellX.m_V;
if (cellY.m_V > maxY.m_V) maxY.m_V = cellY.m_V;
}
vector< vector<bool> > covered;
covered.resize(static_cast<size_t>(maxY.m_V - minY.m_V + 3));
for (size_t i = 0; i < covered.size(); ++i)
{
covered[i].resize(static_cast<size_t>(maxX.m_V - minX.m_V + 3));
}
vector< vector<bool> > outer = covered;
for (size_t i = 0; i < cells.size(); ++i)
{
size_t offsetX = static_cast<size_t>(CellX(cells[i]).m_V - minX.m_V + 1);
size_t offsetY = static_cast<size_t>(CellY(cells[i]).m_V - minY.m_V + 1);
covered[offsetY][offsetX] = true;
}
queue< pair<size_t, size_t> > flood;
size_t outerY = outer.size();
size_t outerX = outer[0].size();
flood.push(make_pair(0, 0));
while (!flood.empty())
{
size_t i = flood.front().first;
size_t j = flood.front().second;
flood.pop();
outer[i][j] = true;
if ((j > 0) && (!outer[i][j - 1]) && (!covered[i][j - 1]))
flood.push(make_pair(i, j - 1));
if ((i > 0) && (!outer[i - 1][j]) && (!covered[i - 1][j]))
flood.push(make_pair(i - 1, j));
if ((j < outerX - 1) && (!outer[i][j + 1]) && (!covered[i][j + 1]))
flood.push(make_pair(i, j + 1));
if ((i < outerY - 1) && (!outer[i + 1][j]) && (!covered[i + 1][j]))
flood.push(make_pair(i + 1, j));
}
cells.clear();
for (size_t i = 0; i < outer.size(); ++i)
{
for (size_t j = 0; j < outer[i].size(); ++j)
{
if (!outer[i][j])
{
cells.push_back(CellFromCellXY(cellDepth, minX.m_V + j - 1, minY.m_V + i - 1));
}
}
}
}
*/
|
#pragma once
#include "cell_id.hpp"
#include "../std/queue.hpp"
#include "../std/vector.hpp"
inline bool IntersectsHoriz(CoordT x1, CoordT y1, CoordT x2, CoordT y2,
CoordT y, CoordT l, CoordT r)
{
CoordT d = (y1 - y) * (y2 - y);
if (d > 0) return false;
CoordT x = x1 + (x2 - x1) * (y - y1) / (y2 - y1);
if ((l - x) * (r - x) <= 0) return true; else return false;
}
inline bool IntersectsVert(CoordT x1, CoordT y1, CoordT x2, CoordT y2,
CoordT x, CoordT b, CoordT t)
{
CoordT d = (x1 - x) * (x2 - x);
if (d > 0) return false;
CoordT y = y1 + (y2 - y1) * (x - x1) / (x2 - x1);
if ((b - y) * (t - y) <= 0) return true; else return false;
}
template <typename BoundsT, typename CellIdT>
inline bool CellIntersects(vector<CoordPointT> const & polyLine, CellIdT id)
{
CoordT minX, minY, maxX, maxY;
CellIdConverter<BoundsT, CellIdT>::GetCellBounds(id, minX, minY, maxX, maxY);
CoordPointT minPoint = make_pair(minX, minY);
CoordPointT maxPoint = make_pair(maxX, maxY);
for (size_t i = 0; i < polyLine.size() - 1; ++i)
{
if (IntersectsHoriz(polyLine[i].first, polyLine[i].second,
polyLine[i + 1].first, polyLine[i + 1].second,
minPoint.second, minPoint.first, maxPoint.first)) return true;
if (IntersectsHoriz(polyLine[i].first, polyLine[i].second,
polyLine[i + 1].first, polyLine[i + 1].second,
maxPoint.second, minPoint.first, maxPoint.first)) return true;
if (IntersectsVert(polyLine[i].first, polyLine[i].second,
polyLine[i + 1].first, polyLine[i + 1].second,
minPoint.first, minPoint.second, maxPoint.second)) return true;
if (IntersectsVert(polyLine[i].first, polyLine[i].second,
polyLine[i + 1].first, polyLine[i + 1].second,
maxPoint.first, minPoint.second, maxPoint.second)) return true;
}
return false;
}
template <typename BoundsT, typename CellIdT>
inline void SplitCell(vector<CoordPointT> const & polyLine, queue<CellIdT> & cellQueue)
{
CellIdT id = cellQueue.front();
cellQueue.pop();
for (size_t i = 0; i < 4; ++i)
{
CellIdT child = id.Child(i);
if (CellIntersects<BoundsT>(polyLine, child))
{
cellQueue.push(child);
}
}
}
template <typename ItT>
inline bool FindBounds(ItT begin, ItT end,
CoordT & minX, CoordT & minY, CoordT & maxX, CoordT & maxY)
{
if (begin == end) return false;
minX = begin->first;
maxX = begin->first;
minY = begin->second;
maxY = begin->second;
for (ItT it = begin; it != end; ++it)
{
if (it->first < minX) minX = it->first;
if (it->first > maxX) maxX = it->first;
if (it->second < minY) minY = it->second;
if (it->second > maxY) maxY = it->second;
}
return true;
}
template <typename BoundsT, typename CellIdT>
inline CellIdT CoverPoint(CoordPointT const & point)
{
return CellIdConverter<BoundsT, CellIdT>::ToCellId(point.first, point.second);
}
template <typename BoundsT, typename CellIdT>
inline void CoverPolyLine(vector< CoordPointT > const & polyLine, size_t cellDepth,
vector<CellIdT> & cells)
{
CoordT minX = 0, minY = 0, maxX = 0, maxY = 0;
FindBounds(polyLine.begin(), polyLine.end(), minX, minY, maxX, maxY);
CellIdT commonCell =
CellIdConverter<BoundsT, CellIdT>::Cover2PointsWithCell(minX, minY, maxX, maxY);
queue<CellIdT> cellQueue;
cellQueue.push(commonCell);
while (cellQueue.front().Level() < static_cast<int>(cellDepth)) // cellQueue.size() < cells_count
{
SplitCell<BoundsT>(polyLine, cellQueue);
}
while (!cellQueue.empty())
{
cells.push_back(cellQueue.front());
cellQueue.pop();
}
}
template <typename BoundsT, typename CellIdT>
inline void SplitRectCell(CellIdT id,
CoordT minX, CoordT minY,
CoordT maxX, CoordT maxY,
vector<CellIdT> & result)
{
for (size_t i = 0; i < 4; ++i)
{
CellIdT child = id.Child(i);
CoordT minCellX, minCellY, maxCellX, maxCellY;
CellIdConverter<BoundsT, CellIdT>::GetCellBounds(child, minCellX, minCellY, maxCellX, maxCellY);
if (!((maxX < minCellX) || (minX > maxCellX) || (maxY < minCellY) || (minY > maxCellY)))
result.push_back(child);
}
}
template <typename BoundsT, typename CellIdT>
inline void CoverRect(CoordT minX, CoordT minY,
CoordT maxX, CoordT maxY,
size_t cells_count,
vector<CellIdT> & cells)
{
ASSERT_LESS(minX, maxX, ());
ASSERT_LESS(minY, maxY, ());
if (minX < BoundsT::minX) minX = BoundsT::minX;
if (minY < BoundsT::minY) minY = BoundsT::minY;
if (maxX > BoundsT::maxX) maxX = BoundsT::maxX;
if (maxY > BoundsT::maxY) maxY = BoundsT::maxY;
if (minX >= maxX || minY >= maxY)
return;
CellIdT commonCell =
CellIdConverter<BoundsT, CellIdT>::Cover2PointsWithCell(minX, minY, maxX, maxY);
vector<CellIdT> result;
queue<CellIdT> cellQueue;
cellQueue.push(commonCell);
while (!cellQueue.empty() && cellQueue.size() + result.size() < cells_count)
{
CellIdT id = cellQueue.front();
cellQueue.pop();
if (id.Level() == CellIdT::DEPTH_LEVELS - 1)
{
result.push_back(id);
break;
}
vector<CellIdT> children;
SplitRectCell<BoundsT>(id, minX, minY, maxX, maxY, children);
// Children shouldn't be empty, but if it is, ignore this cellid in release.
ASSERT(!children.empty(), (id, minX, minY, maxX, maxY));
if (children.empty())
{
result.push_back(id);
continue;
}
if (cellQueue.size() + result.size() + children.size() <= cells_count)
{
for (size_t i = 0; i < children.size(); ++i)
cellQueue.push(children[i]);
}
else
result.push_back(id);
}
for (; !cellQueue.empty(); cellQueue.pop())
result.push_back(cellQueue.front());
for (size_t i = 0; i < result.size(); ++i)
{
CellIdT id = result[i];
while (id.Level() < CellIdT::DEPTH_LEVELS - 1)
{
vector<CellIdT> children;
SplitRectCell<BoundsT>(id, minX, minY, maxX, maxY, children);
if (children.size() == 1)
id = children[0];
else
break;
}
result[i] = id;
}
ASSERT_LESS_OR_EQUAL(result.size(), cells_count, (minX, minY, maxX, maxY));
cells.insert(cells.end(), result.begin(), result.end());
}
|
Remove commented-out CoverPolygon().
|
Remove commented-out CoverPolygon().
|
C++
|
apache-2.0
|
augmify/omim,stangls/omim,darina/omim,programming086/omim,bykoianko/omim,wersoo/omim,Saicheg/omim,UdjinM6/omim,stangls/omim,Zverik/omim,Zverik/omim,goblinr/omim,darina/omim,dobriy-eeh/omim,UdjinM6/omim,felipebetancur/omim,albertshift/omim,VladiMihaylenko/omim,alexzatsepin/omim,ygorshenin/omim,programming086/omim,gardster/omim,milchakov/omim,lydonchandra/omim,vng/omim,Saicheg/omim,VladiMihaylenko/omim,sidorov-panda/omim,Komzpa/omim,Saicheg/omim,darina/omim,syershov/omim,vladon/omim,Endika/omim,wersoo/omim,wersoo/omim,trashkalmar/omim,victorbriz/omim,vasilenkomike/omim,rokuz/omim,matsprea/omim,AlexanderMatveenko/omim,dobriy-eeh/omim,albertshift/omim,darina/omim,igrechuhin/omim,yunikkk/omim,milchakov/omim,dkorolev/omim,mapsme/omim,bykoianko/omim,mpimenov/omim,dobriy-eeh/omim,bykoianko/omim,programming086/omim,yunikkk/omim,lydonchandra/omim,ygorshenin/omim,darina/omim,rokuz/omim,mapsme/omim,vasilenkomike/omim,victorbriz/omim,stangls/omim,Zverik/omim,matsprea/omim,guard163/omim,VladiMihaylenko/omim,dkorolev/omim,ygorshenin/omim,VladiMihaylenko/omim,dobriy-eeh/omim,Transtech/omim,UdjinM6/omim,Zverik/omim,ygorshenin/omim,felipebetancur/omim,lydonchandra/omim,bykoianko/omim,therearesomewhocallmetim/omim,alexzatsepin/omim,trashkalmar/omim,65apps/omim,mapsme/omim,Zverik/omim,vladon/omim,VladiMihaylenko/omim,programming086/omim,UdjinM6/omim,guard163/omim,albertshift/omim,guard163/omim,TimurTarasenko/omim,Volcanoscar/omim,mapsme/omim,krasin/omim,rokuz/omim,andrewshadura/omim,jam891/omim,Komzpa/omim,dkorolev/omim,edl00k/omim,therearesomewhocallmetim/omim,augmify/omim,rokuz/omim,guard163/omim,bykoianko/omim,trashkalmar/omim,dkorolev/omim,bykoianko/omim,mapsme/omim,vladon/omim,igrechuhin/omim,lydonchandra/omim,goblinr/omim,Zverik/omim,matsprea/omim,jam891/omim,trashkalmar/omim,mapsme/omim,felipebetancur/omim,Endika/omim,bykoianko/omim,vng/omim,goblinr/omim,VladiMihaylenko/omim,felipebetancur/omim,dobriy-eeh/omim,rokuz/omim,rokuz/omim,krasin/omim,wersoo/omim,krasin/omim,Transtech/omim,mgsergio/omim,programming086/omim,mgsergio/omim,65apps/omim,Komzpa/omim,Endika/omim,AlexanderMatveenko/omim,igrechuhin/omim,alexzatsepin/omim,ygorshenin/omim,albertshift/omim,dkorolev/omim,VladiMihaylenko/omim,bykoianko/omim,darina/omim,darina/omim,vng/omim,Volcanoscar/omim,Volcanoscar/omim,yunikkk/omim,Volcanoscar/omim,gardster/omim,65apps/omim,alexzatsepin/omim,albertshift/omim,programming086/omim,jam891/omim,vasilenkomike/omim,TimurTarasenko/omim,UdjinM6/omim,65apps/omim,wersoo/omim,milchakov/omim,syershov/omim,stangls/omim,victorbriz/omim,felipebetancur/omim,edl00k/omim,VladiMihaylenko/omim,rokuz/omim,65apps/omim,sidorov-panda/omim,simon247/omim,krasin/omim,yunikkk/omim,65apps/omim,programming086/omim,augmify/omim,goblinr/omim,Endika/omim,therearesomewhocallmetim/omim,krasin/omim,gardster/omim,andrewshadura/omim,AlexanderMatveenko/omim,TimurTarasenko/omim,syershov/omim,darina/omim,sidorov-panda/omim,vng/omim,milchakov/omim,wersoo/omim,alexzatsepin/omim,Transtech/omim,AlexanderMatveenko/omim,AlexanderMatveenko/omim,wersoo/omim,Transtech/omim,Transtech/omim,trashkalmar/omim,albertshift/omim,guard163/omim,mapsme/omim,alexzatsepin/omim,andrewshadura/omim,wersoo/omim,therearesomewhocallmetim/omim,krasin/omim,vng/omim,Saicheg/omim,Komzpa/omim,victorbriz/omim,edl00k/omim,edl00k/omim,mpimenov/omim,simon247/omim,goblinr/omim,Saicheg/omim,milchakov/omim,stangls/omim,syershov/omim,augmify/omim,rokuz/omim,mgsergio/omim,kw217/omim,syershov/omim,igrechuhin/omim,bykoianko/omim,alexzatsepin/omim,bykoianko/omim,edl00k/omim,Volcanoscar/omim,lydonchandra/omim,albertshift/omim,bykoianko/omim,vladon/omim,programming086/omim,gardster/omim,goblinr/omim,TimurTarasenko/omim,bykoianko/omim,Komzpa/omim,darina/omim,vng/omim,vng/omim,felipebetancur/omim,kw217/omim,albertshift/omim,milchakov/omim,stangls/omim,mgsergio/omim,Zverik/omim,Volcanoscar/omim,victorbriz/omim,therearesomewhocallmetim/omim,mpimenov/omim,yunikkk/omim,felipebetancur/omim,jam891/omim,augmify/omim,krasin/omim,mpimenov/omim,mpimenov/omim,dobriy-eeh/omim,mgsergio/omim,stangls/omim,therearesomewhocallmetim/omim,simon247/omim,vasilenkomike/omim,vladon/omim,kw217/omim,vasilenkomike/omim,vasilenkomike/omim,mgsergio/omim,igrechuhin/omim,Zverik/omim,kw217/omim,wersoo/omim,kw217/omim,65apps/omim,Saicheg/omim,vasilenkomike/omim,therearesomewhocallmetim/omim,VladiMihaylenko/omim,AlexanderMatveenko/omim,vasilenkomike/omim,AlexanderMatveenko/omim,alexzatsepin/omim,stangls/omim,mgsergio/omim,syershov/omim,felipebetancur/omim,mpimenov/omim,trashkalmar/omim,65apps/omim,alexzatsepin/omim,yunikkk/omim,igrechuhin/omim,matsprea/omim,Zverik/omim,VladiMihaylenko/omim,sidorov-panda/omim,syershov/omim,matsprea/omim,yunikkk/omim,simon247/omim,UdjinM6/omim,andrewshadura/omim,dobriy-eeh/omim,Komzpa/omim,milchakov/omim,ygorshenin/omim,Transtech/omim,guard163/omim,edl00k/omim,65apps/omim,rokuz/omim,Zverik/omim,augmify/omim,alexzatsepin/omim,Komzpa/omim,augmify/omim,Komzpa/omim,rokuz/omim,matsprea/omim,vladon/omim,TimurTarasenko/omim,simon247/omim,rokuz/omim,vasilenkomike/omim,lydonchandra/omim,dkorolev/omim,simon247/omim,UdjinM6/omim,victorbriz/omim,igrechuhin/omim,milchakov/omim,andrewshadura/omim,Volcanoscar/omim,igrechuhin/omim,yunikkk/omim,stangls/omim,edl00k/omim,kw217/omim,dobriy-eeh/omim,Zverik/omim,mgsergio/omim,victorbriz/omim,lydonchandra/omim,mapsme/omim,milchakov/omim,lydonchandra/omim,simon247/omim,milchakov/omim,ygorshenin/omim,yunikkk/omim,mpimenov/omim,augmify/omim,milchakov/omim,mpimenov/omim,krasin/omim,guard163/omim,mgsergio/omim,UdjinM6/omim,VladiMihaylenko/omim,alexzatsepin/omim,andrewshadura/omim,65apps/omim,trashkalmar/omim,Saicheg/omim,stangls/omim,goblinr/omim,therearesomewhocallmetim/omim,TimurTarasenko/omim,mpimenov/omim,victorbriz/omim,AlexanderMatveenko/omim,igrechuhin/omim,augmify/omim,UdjinM6/omim,jam891/omim,jam891/omim,Endika/omim,goblinr/omim,ygorshenin/omim,gardster/omim,mgsergio/omim,vladon/omim,vasilenkomike/omim,Transtech/omim,VladiMihaylenko/omim,sidorov-panda/omim,victorbriz/omim,Volcanoscar/omim,milchakov/omim,sidorov-panda/omim,syershov/omim,Transtech/omim,Transtech/omim,dkorolev/omim,igrechuhin/omim,mapsme/omim,yunikkk/omim,andrewshadura/omim,felipebetancur/omim,Volcanoscar/omim,vng/omim,kw217/omim,guard163/omim,Saicheg/omim,darina/omim,matsprea/omim,lydonchandra/omim,gardster/omim,stangls/omim,syershov/omim,andrewshadura/omim,albertshift/omim,AlexanderMatveenko/omim,jam891/omim,alexzatsepin/omim,sidorov-panda/omim,andrewshadura/omim,sidorov-panda/omim,albertshift/omim,dkorolev/omim,alexzatsepin/omim,TimurTarasenko/omim,edl00k/omim,guard163/omim,goblinr/omim,lydonchandra/omim,vladon/omim,Zverik/omim,mpimenov/omim,vladon/omim,simon247/omim,kw217/omim,dobriy-eeh/omim,victorbriz/omim,trashkalmar/omim,rokuz/omim,wersoo/omim,mpimenov/omim,trashkalmar/omim,goblinr/omim,gardster/omim,milchakov/omim,programming086/omim,syershov/omim,bykoianko/omim,edl00k/omim,gardster/omim,augmify/omim,trashkalmar/omim,gardster/omim,Endika/omim,VladiMihaylenko/omim,Endika/omim,UdjinM6/omim,matsprea/omim,Volcanoscar/omim,65apps/omim,vng/omim,Transtech/omim,mpimenov/omim,kw217/omim,goblinr/omim,vladon/omim,mgsergio/omim,matsprea/omim,Endika/omim,jam891/omim,ygorshenin/omim,ygorshenin/omim,therearesomewhocallmetim/omim,therearesomewhocallmetim/omim,ygorshenin/omim,mpimenov/omim,dobriy-eeh/omim,Endika/omim,trashkalmar/omim,Komzpa/omim,goblinr/omim,Endika/omim,mapsme/omim,gardster/omim,mgsergio/omim,ygorshenin/omim,mapsme/omim,trashkalmar/omim,dkorolev/omim,dobriy-eeh/omim,kw217/omim,rokuz/omim,syershov/omim,TimurTarasenko/omim,Saicheg/omim,andrewshadura/omim,syershov/omim,edl00k/omim,matsprea/omim,krasin/omim,programming086/omim,sidorov-panda/omim,darina/omim,yunikkk/omim,simon247/omim,jam891/omim,mapsme/omim,Saicheg/omim,krasin/omim,dkorolev/omim,felipebetancur/omim,TimurTarasenko/omim,vng/omim,simon247/omim,darina/omim,darina/omim,TimurTarasenko/omim,Transtech/omim,sidorov-panda/omim,guard163/omim,AlexanderMatveenko/omim,Transtech/omim,jam891/omim,mapsme/omim,syershov/omim,dobriy-eeh/omim,dobriy-eeh/omim,Zverik/omim,Komzpa/omim,goblinr/omim
|
df897d02b62ff9e43d062a695f9660aed3425183
|
indexer/indexer_main.cpp
|
indexer/indexer_main.cpp
|
//
// indexer_main.cpp
// Argos
//
// Created by Windoze on 12-7-5.
// Copyright (c) 2012 0d0a.com. All rights reserved.
//
#include <fstream>
#include <boost/program_options.hpp>
#include "index.h"
#include "parser.h"
using namespace std;
using namespace argos;
using namespace argos::common;
using namespace argos::index;
using namespace argos::parser;
namespace po = boost::program_options;
inline void mark(size_t sz)
{
if (sz % 100==0) {
if (sz % 1000==0) {
if (sz % 10000==0) {
cout << sz;
} else {
cout << (sz/1000 % 10);
}
}
cout << '.';
cout.flush();
}
}
Index *the_index=0;
void close_index();
bool init_index(const char *conf, const char *index_dir)
{
if (conf && conf[0] && index_dir && index_dir[0]) {
the_index=new Index(conf, index_dir, INDEX_CREATE);
if(!the_index->is_open())
{
close_index();
the_index=0;
}
}
return the_index;
}
bool add_document(const std::string &line, ExecutionContext &context)
{
if (!the_index) {
return false;
}
value_list_t vl;
const char *s=line.c_str();
size_t len=line.size();
if(!parse_value_list(s, len, vl, context))
return false;
for (value_list_t::const_iterator i=vl.begin(); i!=vl.end(); ++i) {
if (i->type_==VT_EMPTY) {
return false;
}
}
return is_valid(the_index->add_document(vl, context));
}
void close_index()
{
if (the_index) {
delete the_index;
}
}
bool add_documents(istream &is, size_t &line_count, size_t &error_count)
{
string line;
ExecutionContext *context=the_index->create_context();
//context->temp_pool=get_tl_mem_pool();
line_count=0;
error_count=0;
bool ret=true;
while (is)
{
line_count++;
if ((line_count-1)%1000==0) {
context->temp_pool->reset();
}
if (!context) {
cerr << "ERROR: Fail to create context when processing line:" << line_count << endl;
return false;
}
getline(is, line);
if (line.empty()) {
error_count++;
continue;
}
if(!add_document(line, *context))
{
error_count++;
cerr << "WARNING: Fail to add document at line:" << line_count+1 << endl;
continue;
}
mark(line_count-1);
}
if (context) {
delete context;
}
return ret;
}
bool build_index(const string &conf, const string &index_dir, const string &inp, size_t &line_count, size_t &error_count)
{
if (inp=="-") {
if (!init_index(conf.c_str(), index_dir.c_str())) {
return false;
}
bool ret=add_documents(cin, line_count, error_count);
close_index();
return ret;
} else {
ifstream is(inp.c_str());
if (!is) {
return false;
}
if (!init_index(conf.c_str(), index_dir.c_str())) {
return false;
}
bool ret=add_documents(is, line_count, error_count);
close_index();
return ret;
}
}
int main(int argc, const char * argv[])
{
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("config,c", po::value<string>(), "index config XML file")
("index-dir,d", po::value<string>(), "index directory")
("input-file,i", po::value<string>(), "input file")
;
po::positional_options_description p;
p.add("input-file", -1);
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
} catch (...) {
cout << "Invalid command line options\n";
cout << desc << "\n";
return 1;
}
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
string conf;
string index_dir;
string inp;
if (vm.count("config")) {
conf=vm["config"].as<string>();
} else {
conf="./config.xml";
}
int fd=open(conf.c_str(), O_RDONLY);
if (fd<0) {
cerr << "Cannot access config file.\n";
return 100;
}
close(fd);
if (vm.count("index-dir")) {
index_dir=vm["index-dir"].as<string>();
} else {
index_dir="./index.db";
}
if (vm.count("input-file")) {
inp=vm["input-file"].as<string>();
} else {
inp="-";
}
cout << "Building index at \"" << index_dir << "\"...\n";
size_t line_count=0;
size_t error_count=0;
try {
if(!build_index(conf, index_dir, inp, line_count, error_count))
{
cerr << "\nFailed\n";
return 100;
}
cout << "\nDone.\n";
cout << "Processed " << line_count << " lines, " << error_count << " lines with error\n";
return 0;
}
catch(...) {
cerr << "\nERROR: Uncaught exception.\n";
}
return 100;
}
|
//
// indexer_main.cpp
// Argos
//
// Created by Windoze on 12-7-5.
// Copyright (c) 2012 0d0a.com. All rights reserved.
//
#include <fstream>
#include <boost/program_options.hpp>
#include "index.h"
#include "parser.h"
using namespace std;
using namespace argos;
using namespace argos::common;
using namespace argos::index;
using namespace argos::parser;
namespace po = boost::program_options;
inline void mark(size_t sz)
{
if (sz % 100==0) {
if (sz % 1000==0) {
if (sz % 10000==0) {
cout << sz;
} else {
cout << (sz/1000 % 10);
}
}
cout << '.';
cout.flush();
}
}
Index *the_index=0;
void close_index();
bool init_index(const char *conf, const char *index_dir)
{
if (!(index_dir && index_dir[0])) {
return false;
}
if (conf && conf[0]) {
// Create a new index
the_index=new Index(conf, index_dir, INDEX_CREATE);
if(!the_index->is_open())
{
cerr << "Cannot create index at \"" << index_dir << "\"\n";
close_index();
the_index=0;
}
} else {
// Open existing index
the_index=new Index(index_dir);
if(!the_index->is_open())
{
cerr << "Cannot open index at \"" << index_dir << "\"\n";
close_index();
the_index=0;
}
}
return the_index;
}
bool add_document(const std::string &line, ExecutionContext &context)
{
if (!the_index) {
return false;
}
value_list_t vl;
const char *s=line.c_str();
size_t len=line.size();
if(!parse_value_list(s, len, vl, context))
return false;
for (value_list_t::const_iterator i=vl.begin(); i!=vl.end(); ++i) {
if (i->type_==VT_EMPTY) {
return false;
}
}
return is_valid(the_index->add_document(vl, context));
}
void close_index()
{
if (the_index) {
delete the_index;
}
}
bool add_documents(istream &is, size_t &line_count, size_t &error_count)
{
string line;
ExecutionContext *context=the_index->create_context();
//context->temp_pool=get_tl_mem_pool();
line_count=0;
error_count=0;
bool ret=true;
while (is)
{
line_count++;
if ((line_count-1)%1000==0) {
context->temp_pool->reset();
}
if (!context) {
cerr << "ERROR: Fail to create context when processing line:" << line_count << endl;
return false;
}
getline(is, line);
if (line.empty()) {
error_count++;
continue;
}
if(!add_document(line, *context))
{
error_count++;
cerr << "WARNING: Fail to add document at line:" << line_count+1 << endl;
continue;
}
mark(line_count-1);
}
if (context) {
delete context;
}
return ret;
}
bool build_index(const string &conf, const string &index_dir, const string &inp, size_t &line_count, size_t &error_count)
{
if (inp=="-") {
if (!init_index(conf.c_str(), index_dir.c_str())) {
return false;
}
bool ret=add_documents(cin, line_count, error_count);
close_index();
return ret;
} else {
ifstream is(inp.c_str());
if (!is) {
return false;
}
if (!init_index(conf.c_str(), index_dir.c_str())) {
return false;
}
bool ret=add_documents(is, line_count, error_count);
close_index();
return ret;
}
}
int main(int argc, const char * argv[])
{
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("config,c", po::value<string>(), "index config XML file")
("index-dir,d", po::value<string>(), "index directory")
("input-file,i", po::value<string>(), "input file")
;
po::positional_options_description p;
p.add("input-file", -1);
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
} catch (...) {
cout << "Invalid command line options\n";
cout << desc << "\n";
return 1;
}
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
string conf;
string index_dir;
string inp;
if (vm.count("config")) {
conf=vm["config"].as<string>();
}
if (vm.count("index-dir")) {
index_dir=vm["index-dir"].as<string>();
} else {
cerr << "\nIndex path must be specified.\n";
return 100;
}
if (vm.count("input-file")) {
inp=vm["input-file"].as<string>();
} else {
inp="-";
}
if (conf.empty()) {
cout << "Updating index at \"" << index_dir << "\"...\n";
} else {
cout << "Building index at \"" << index_dir << "\"...\n";
}
size_t line_count=0;
size_t error_count=0;
try {
if(!build_index(conf, index_dir, inp, line_count, error_count))
{
cerr << "\nFailed.\n";
return 100;
}
cout << "\nDone.\n";
cout << line_count << "lines processed, " << error_count << " lines with error\n";
return 0;
}
catch(exception &e) {
cerr << "\nERROR: " << e.what() << "\n";
}
catch(...) {
cerr << "\nERROR: Uncaught exception.\n";
}
return 100;
}
|
Allow indexer to update existing index
|
Allow indexer to update existing index
|
C++
|
bsd-2-clause
|
pombredanne/Argos,pombredanne/Argos,windoze/Argos,windoze/Argos,pombredanne/Argos
|
13432ebfb78b9c73f86dd06a1a5ec24c66c5edca
|
include/caffe/blob.hpp
|
include/caffe/blob.hpp
|
// Copyright 2014 BVLC and contributors.
#ifndef CAFFE_BLOB_HPP_
#define CAFFE_BLOB_HPP_
#include "caffe/common.hpp"
#include "caffe/syncedmem.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
template <typename Dtype>
class Blob {
public:
Blob()
: num_(0), channels_(0), height_(0), width_(0), count_(0), data_(),
diff_() {}
explicit Blob(const int num, const int channels, const int height,
const int width);
virtual ~Blob() {}
void Reshape(const int num, const int height,
const int width, const int channels);
inline int num() const { return num_; }
inline int channels() const { return channels_; }
inline int height() const { return height_; }
inline int width() const { return width_; }
inline int count() const {return count_; }
inline int offset(const int n, const int c = 0, const int h = 0,
const int w = 0) const {
CHECK_GE(n, 0);
CHECK_LE(n, num_);
CHECK_GE(channels_, 0);
CHECK_LE(c, channels_);
CHECK_GE(height_, 0);
CHECK_LE(h, height_);
CHECK_GE(width_, 0);
CHECK_LE(w, width_);
return ((n * channels_ + c) * height_ + h) * width_ + w;
}
// Copy from source. If copy_diff is false, we copy the data; if copy_diff
// is true, we copy the diff.
void CopyFrom(const Blob<Dtype>& source, bool copy_diff = false,
bool reshape = false);
inline Dtype data_at(const int n, const int c, const int h,
const int w) const {
return *(cpu_data() + offset(n, c, h, w));
}
inline Dtype diff_at(const int n, const int c, const int h,
const int w) const {
return *(cpu_diff() + offset(n, c, h, w));
}
const Dtype* cpu_data() const;
const Dtype* gpu_data() const;
const Dtype* cpu_diff() const;
const Dtype* gpu_diff() const;
Dtype* mutable_cpu_data();
Dtype* mutable_gpu_data();
Dtype* mutable_cpu_diff();
Dtype* mutable_gpu_diff();
void Update();
void FromProto(const BlobProto& proto);
void ToProto(BlobProto* proto, bool write_diff = false) const;
protected:
shared_ptr<SyncedMemory> data_;
shared_ptr<SyncedMemory> diff_;
int num_;
int channels_;
int height_;
int width_;
int count_;
DISABLE_COPY_AND_ASSIGN(Blob);
}; // class Blob
} // namespace caffe
#endif // CAFFE_BLOB_HPP_
|
// Copyright 2014 BVLC and contributors.
#ifndef CAFFE_BLOB_HPP_
#define CAFFE_BLOB_HPP_
#include "caffe/common.hpp"
#include "caffe/syncedmem.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
template <typename Dtype>
class Blob {
public:
Blob()
: num_(0), channels_(0), height_(0), width_(0), count_(0), data_(),
diff_() {}
explicit Blob(const int num, const int channels, const int height,
const int width);
virtual ~Blob() {}
void Reshape(const int num, const int channels, const int height,
const int width);
inline int num() const { return num_; }
inline int channels() const { return channels_; }
inline int height() const { return height_; }
inline int width() const { return width_; }
inline int count() const {return count_; }
inline int offset(const int n, const int c = 0, const int h = 0,
const int w = 0) const {
CHECK_GE(n, 0);
CHECK_LE(n, num_);
CHECK_GE(channels_, 0);
CHECK_LE(c, channels_);
CHECK_GE(height_, 0);
CHECK_LE(h, height_);
CHECK_GE(width_, 0);
CHECK_LE(w, width_);
return ((n * channels_ + c) * height_ + h) * width_ + w;
}
// Copy from source. If copy_diff is false, we copy the data; if copy_diff
// is true, we copy the diff.
void CopyFrom(const Blob<Dtype>& source, bool copy_diff = false,
bool reshape = false);
inline Dtype data_at(const int n, const int c, const int h,
const int w) const {
return *(cpu_data() + offset(n, c, h, w));
}
inline Dtype diff_at(const int n, const int c, const int h,
const int w) const {
return *(cpu_diff() + offset(n, c, h, w));
}
const Dtype* cpu_data() const;
const Dtype* gpu_data() const;
const Dtype* cpu_diff() const;
const Dtype* gpu_diff() const;
Dtype* mutable_cpu_data();
Dtype* mutable_gpu_data();
Dtype* mutable_cpu_diff();
Dtype* mutable_gpu_diff();
void Update();
void FromProto(const BlobProto& proto);
void ToProto(BlobProto* proto, bool write_diff = false) const;
protected:
shared_ptr<SyncedMemory> data_;
shared_ptr<SyncedMemory> diff_;
int num_;
int channels_;
int height_;
int width_;
int count_;
DISABLE_COPY_AND_ASSIGN(Blob);
}; // class Blob
} // namespace caffe
#endif // CAFFE_BLOB_HPP_
|
Fix parameter orders in declaration of Reshape
|
Fix parameter orders in declaration of Reshape
|
C++
|
bsd-2-clause
|
nicodjimenez/caffe,minghuam/caffe,gogartom/caffe-textmaps,gnina/gnina,tackgeun/caffe,suixudongi8/caffe,shuimulinxi/caffe,gogartom/caffe-textmaps,vibhav-vineet/caffe,tackgeun/caffe,dylansun/caffe,xidianwlc/caffe,MoskalenkoViktor/caffe,shiquanwang/caffe,dculibrk/boosted_pooling,dylansun/caffe,gnina/gnina,audtlr24/caffe,liuxianming/caffe_feedback,yikeliu/caffe-future,shiquanwang/caffe,MoskalenkoViktor/caffe,audtlr24/caffe,dculibrk/boosted_pooling,wangg12/caffe,vibhav-vineet/caffe,dculibrk/boosted_pooling,naeluh/caffe,yikeliu/caffe-future,longjon/caffe,flickr/caffe,flickr/caffe,shiquanwang/caffe,pcoving/caffe,xidianwlc/caffe,shuimulinxi/caffe,xidianwlc/caffe,liuxianming/caffe_feedback,wangg12/caffe,flickr/caffe,flickr/caffe,pcoving/caffe,Hilovaiserillis/caffe,vibhav-vineet/caffe,naeluh/caffe,suixudongi8/caffe,minghuam/caffe,MoskalenkoViktor/caffe,wangg12/caffe,yikeliu/caffe-future,Hilovaiserillis/caffe,orentadmor/caffe,niuzhiheng/caffe,orentadmor/caffe,flickr/caffe,pcoving/caffe,Hilovaiserillis/caffe,orentadmor/caffe,audtlr24/caffe,audtlr24/caffe,niuzhiheng/caffe,Hilovaiserillis/caffe,xidianwlc/caffe,minghuam/caffe,sichenucsd/caffe_si,niuzhiheng/caffe,tackgeun/caffe,shuimulinxi/caffe,CZCV/s-dilation-caffe,nicodjimenez/caffe,CZCV/s-dilation-caffe,nicodjimenez/caffe,gogartom/caffe-textmaps,gnina/gnina,longjon/caffe,liuxianming/caffe_feedback,dylansun/caffe,dylansun/caffe,suixudongi8/caffe,tackgeun/caffe,CZCV/s-dilation-caffe,dculibrk/boosted_pooling,liuxianming/caffe_feedback,dculibrk/boosted_pooling,shiquanwang/caffe,CZCV/s-dilation-caffe,CVML/sds_eccv2014,Hilovaiserillis/caffe,dylansun/caffe,naeluh/caffe,wangg12/caffe,naeluh/caffe,suixudongi8/caffe,audtlr24/caffe,longjon/caffe,orentadmor/caffe,naeluh/caffe,niuzhiheng/caffe,sichenucsd/caffe_si,gogartom/caffe-textmaps,vibhav-vineet/caffe,nicodjimenez/caffe,longjon/caffe,shuimulinxi/caffe,sichenucsd/caffe_si,MoskalenkoViktor/caffe,yikeliu/caffe-future,pcoving/caffe,liuxianming/caffe_feedback,pcoving/caffe,gnina/gnina,niuzhiheng/caffe,MoskalenkoViktor/caffe,shuimulinxi/caffe,bharath272/sds_eccv2014,gnina/gnina,minghuam/caffe,sichenucsd/caffe_si,gnina/gnina,nicodjimenez/caffe
|
aa0e449932f7a0db5b9146c1e747bd2cc527ab26
|
lexlib/LexerBase.cxx
|
lexlib/LexerBase.cxx
|
// Scintilla source code edit control
/** @file LexerSimple.cxx
** A simple lexer with no state.
**/
// Copyright 1998-2010 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "PropSetSimple.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "LexerModule.h"
#include "LexerBase.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
LexerBase::LexerBase() {
for (int wl = 0; wl < numWordLists; wl++)
keyWordLists[wl] = new WordList;
keyWordLists[numWordLists] = 0;
}
LexerBase::~LexerBase() {
for (int wl = 0; wl < numWordLists; wl++) {
delete keyWordLists[wl];
keyWordLists[wl] = 0;
}
keyWordLists[numWordLists] = 0;
}
void SCI_METHOD LexerBase::Release() {
delete this;
}
int SCI_METHOD LexerBase::Version() const {
return lvOriginal;
}
const char * SCI_METHOD LexerBase::PropertyNames() {
return "";
}
int SCI_METHOD LexerBase::PropertyType(const char *) {
return SC_TYPE_BOOLEAN;
}
const char * SCI_METHOD LexerBase::DescribeProperty(const char *) {
return "";
}
int SCI_METHOD LexerBase::PropertySet(const char *key, const char *val) {
const char *valOld = props.Get(key);
if (strcmp(val, valOld) != 0) {
props.Set(key, val);
return 0;
} else {
return -1;
}
}
const char * SCI_METHOD LexerBase::DescribeWordListSets() {
return "";
}
int SCI_METHOD LexerBase::WordListSet(int n, const char *wl) {
if (n < numWordLists) {
WordList wlNew;
wlNew.Set(wl);
if (*keyWordLists[n] != wlNew) {
keyWordLists[n]->Set(wl);
return 0;
}
}
return -1;
}
void * SCI_METHOD LexerBase::PrivateCall(int, void *) {
return 0;
}
|
// Scintilla source code edit control
/** @file LexerBase.cxx
** A simple lexer with no state.
**/
// Copyright 1998-2010 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "PropSetSimple.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "LexerModule.h"
#include "LexerBase.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
LexerBase::LexerBase() {
for (int wl = 0; wl < numWordLists; wl++)
keyWordLists[wl] = new WordList;
keyWordLists[numWordLists] = 0;
}
LexerBase::~LexerBase() {
for (int wl = 0; wl < numWordLists; wl++) {
delete keyWordLists[wl];
keyWordLists[wl] = 0;
}
keyWordLists[numWordLists] = 0;
}
void SCI_METHOD LexerBase::Release() {
delete this;
}
int SCI_METHOD LexerBase::Version() const {
return lvOriginal;
}
const char * SCI_METHOD LexerBase::PropertyNames() {
return "";
}
int SCI_METHOD LexerBase::PropertyType(const char *) {
return SC_TYPE_BOOLEAN;
}
const char * SCI_METHOD LexerBase::DescribeProperty(const char *) {
return "";
}
int SCI_METHOD LexerBase::PropertySet(const char *key, const char *val) {
const char *valOld = props.Get(key);
if (strcmp(val, valOld) != 0) {
props.Set(key, val);
return 0;
} else {
return -1;
}
}
const char * SCI_METHOD LexerBase::DescribeWordListSets() {
return "";
}
int SCI_METHOD LexerBase::WordListSet(int n, const char *wl) {
if (n < numWordLists) {
WordList wlNew;
wlNew.Set(wl);
if (*keyWordLists[n] != wlNew) {
keyWordLists[n]->Set(wl);
return 0;
}
}
return -1;
}
void * SCI_METHOD LexerBase::PrivateCall(int, void *) {
return 0;
}
|
Fix copy&paste error in comment.
|
Fix copy&paste error in comment.
|
C++
|
isc
|
windoze/scintilla,windoze/scintilla,windoze/scintilla,windoze/scintilla,windoze/scintilla,windoze/scintilla,windoze/scintilla,windoze/scintilla
|
450ed4da9043895b5257d813a9038aaec58fbb47
|
examples/wifi-echo/server/esp32/main/LEDWidget.cpp
|
examples/wifi-echo/server/esp32/main/LEDWidget.cpp
|
/*
*
* Copyright (c) 2018 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file LEDWidget.cpp
*
* Implements an LED Widget controller that is usually tied to a GPIO
* It also updates the display widget if it's enabled
*/
#include "LEDWidget.h"
#include "ScreenManager.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_timer.h"
#if CONFIG_HAVE_DISPLAY
// The Y position of the LED Status message on screen as a
// percentage of the screen's height.
#define LED_STATUS_POSITION 85
// Position the LED Indicator at the bottom right corner
#define LED_INDICATOR_X 92
#define LED_INDICATOR_Y 88
// The radius of the LED Indicator
#define LED_INDICATOR_R_PX 16
static const char * onMsg = "LIGHT: ON";
static const char * offMsg = "LIGHT: OFF";
#endif
extern const char * TAG;
void LEDWidget::Init(gpio_num_t gpioNum)
{
mLastChangeTimeUS = 0;
mBlinkOnTimeMS = 0;
mBlinkOffTimeMS = 0;
mGPIONum = gpioNum;
mVLED1 = -1;
mVLED2 = -1;
mState = false;
mError = false;
errorTimer = NULL;
if (gpioNum < GPIO_NUM_MAX)
{
gpio_set_direction(gpioNum, GPIO_MODE_OUTPUT);
}
}
void LEDWidget::Set(bool state)
{
mBlinkOnTimeMS = mBlinkOffTimeMS = 0;
DoSet(state);
}
void LEDWidget::Blink(uint32_t changeRateMS)
{
Blink(changeRateMS, changeRateMS);
}
void LEDWidget::Blink(uint32_t onTimeMS, uint32_t offTimeMS)
{
mBlinkOnTimeMS = onTimeMS;
mBlinkOffTimeMS = offTimeMS;
Animate();
}
void ClearErrorState(TimerHandle_t handle)
{
#if CONFIG_HAVE_DISPLAY
LEDWidget * pWidget = (LEDWidget *) pvTimerGetTimerID(handle);
pWidget->mError = false;
if (pWidget->mVLED2 != -1)
{
ScreenManager::SetVLED(pWidget->mVLED2, false);
}
#endif
}
void LEDWidget::BlinkOnError()
{
#if CONFIG_HAVE_DISPLAY
mError = true;
if (errorTimer != NULL)
{
xTimerDelete(errorTimer, 0);
}
errorTimer = xTimerCreate("ErrorTimer", pdMS_TO_TICKS(2000), false, this, ClearErrorState);
xTimerStart(errorTimer, 0);
if (mVLED2 != -1)
{
ScreenManager::SetVLED(mVLED2, true);
}
#endif
}
void LEDWidget::Animate()
{
if (mBlinkOnTimeMS != 0 && mBlinkOffTimeMS != 0)
{
int64_t nowUS = ::esp_timer_get_time();
int64_t stateDurUS = ((mState) ? mBlinkOnTimeMS : mBlinkOffTimeMS) * 1000LL;
int64_t nextChangeTimeUS = mLastChangeTimeUS + stateDurUS;
if (nowUS > nextChangeTimeUS)
{
DoSet(!mState);
mLastChangeTimeUS = nowUS;
}
}
}
void LEDWidget::DoSet(bool state)
{
bool stateChange = (mState != state);
mState = state;
if (mGPIONum < GPIO_NUM_MAX)
{
gpio_set_level(mGPIONum, (state) ? 1 : 0);
}
if (stateChange)
{
#if CONFIG_HAVE_DISPLAY
if (mVLED1 != -1)
{
ScreenManager::SetVLED(mVLED1, mState);
}
#endif
}
}
#if CONFIG_HAVE_DISPLAY
void LEDWidget::SetVLED(int id1, int id2)
{
mVLED1 = id1;
if (mVLED1 != -1)
{
ScreenManager::SetVLED(mVLED1, mState);
}
mVLED2 = id2;
if (mVLED2 != -1)
{
ScreenManager::SetVLED(mVLED2, mError);
}
}
#endif
|
/*
*
* Copyright (c) 2018 Nest Labs, Inc.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file LEDWidget.cpp
*
* Implements an LED Widget controller that is usually tied to a GPIO
* It also updates the display widget if it's enabled
*/
#include "LEDWidget.h"
#include "ScreenManager.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_timer.h"
void LEDWidget::Init(gpio_num_t gpioNum)
{
mLastChangeTimeUS = 0;
mBlinkOnTimeMS = 0;
mBlinkOffTimeMS = 0;
mGPIONum = gpioNum;
mVLED1 = -1;
mVLED2 = -1;
mState = false;
mError = false;
errorTimer = NULL;
if (gpioNum < GPIO_NUM_MAX)
{
gpio_set_direction(gpioNum, GPIO_MODE_OUTPUT);
}
}
void LEDWidget::Set(bool state)
{
mBlinkOnTimeMS = mBlinkOffTimeMS = 0;
DoSet(state);
}
void LEDWidget::Blink(uint32_t changeRateMS)
{
Blink(changeRateMS, changeRateMS);
}
void LEDWidget::Blink(uint32_t onTimeMS, uint32_t offTimeMS)
{
mBlinkOnTimeMS = onTimeMS;
mBlinkOffTimeMS = offTimeMS;
Animate();
}
void ClearErrorState(TimerHandle_t handle)
{
#if CONFIG_HAVE_DISPLAY
LEDWidget * pWidget = (LEDWidget *) pvTimerGetTimerID(handle);
pWidget->mError = false;
if (pWidget->mVLED2 != -1)
{
ScreenManager::SetVLED(pWidget->mVLED2, false);
}
#endif
}
void LEDWidget::BlinkOnError()
{
#if CONFIG_HAVE_DISPLAY
mError = true;
if (errorTimer != NULL)
{
xTimerDelete(errorTimer, 0);
}
errorTimer = xTimerCreate("ErrorTimer", pdMS_TO_TICKS(2000), false, this, ClearErrorState);
xTimerStart(errorTimer, 0);
if (mVLED2 != -1)
{
ScreenManager::SetVLED(mVLED2, true);
}
#endif
}
void LEDWidget::Animate()
{
if (mBlinkOnTimeMS != 0 && mBlinkOffTimeMS != 0)
{
int64_t nowUS = ::esp_timer_get_time();
int64_t stateDurUS = ((mState) ? mBlinkOnTimeMS : mBlinkOffTimeMS) * 1000LL;
int64_t nextChangeTimeUS = mLastChangeTimeUS + stateDurUS;
if (nowUS > nextChangeTimeUS)
{
DoSet(!mState);
mLastChangeTimeUS = nowUS;
}
}
}
void LEDWidget::DoSet(bool state)
{
bool stateChange = (mState != state);
mState = state;
if (mGPIONum < GPIO_NUM_MAX)
{
gpio_set_level(mGPIONum, (state) ? 1 : 0);
}
if (stateChange)
{
#if CONFIG_HAVE_DISPLAY
if (mVLED1 != -1)
{
ScreenManager::SetVLED(mVLED1, mState);
}
#endif
}
}
#if CONFIG_HAVE_DISPLAY
void LEDWidget::SetVLED(int id1, int id2)
{
mVLED1 = id1;
if (mVLED1 != -1)
{
ScreenManager::SetVLED(mVLED1, mState);
}
mVLED2 = id2;
if (mVLED2 != -1)
{
ScreenManager::SetVLED(mVLED2, mError);
}
}
#endif
|
Remove leftover code in LEDWidget.cpp (#1681)
|
Remove leftover code in LEDWidget.cpp (#1681)
|
C++
|
apache-2.0
|
nestlabs/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip,nestlabs/connectedhomeip,project-chip/connectedhomeip
|
0d9dbff776062f621ea981c15ef02d7087567d80
|
src/audio_io/winmm_output.cpp
|
src/audio_io/winmm_output.cpp
|
#include <audio_io/audio_io.hpp>
#include <audio_io/audio_io_private.hpp>
#include <functional>
#include <string>
#include <vector>
#include <memory>
#include <utility>
#include <mutex>
#include <map>
#include <string.h>
#include <algorithm>
#include <thread>
#include <chrono>
#include <windows.h>
#include <mmreg.h> //WAVEFORMATEXTENSIBLE
namespace audio_io {
namespace implementation {
WAVEFORMATEXTENSIBLE makeFormat(unsigned int channels, unsigned int sr, bool isExtended) {
//lookup table so we can easily pull out masks.
unsigned int chanmasks[] = {
0,
0,
SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT,
0,
0,
0,
SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT,
0,
SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT,
};
WAVEFORMATEXTENSIBLE format;
format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
format.Format.nSamplesPerSec = sr;
format.Format.wBitsPerSample = 16;
format.Format.cbSize = 22; //this comes directly from msdn, which gives no further explanation.
format.Samples.wValidBitsPerSample = 16;
format.Format.nAvgBytesPerSec = channels*2*sr;
format.Format.nBlockAlign = channels*2;
format.Format.nChannels = channels;
format.dwChannelMask = chanmasks[channels];
format.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
if(isExtended == false) {
format.Format.cbSize = 0;
format.Format.wFormatTag = WAVE_FORMAT_PCM;
}
return format;
}
class WinmmOutputDevice: public OutputDeviceImplementation {
public:
//channels is what user requested, maxChannels is what the device can support at most.
//maxChannels comes from the DeviceFactory subclass and is cached; thus the parameter here.
WinmmOutputDevice(std::function<void(float*, int)> getBuffer, unsigned int blockSize, unsigned int channels, unsigned int maxChannels, unsigned int mixAhead, UINT_PTR which, unsigned int sourceSr, unsigned int targetSr);
~WinmmOutputDevice();
virtual void stop() override;
void winmm_mixer();
HWAVEOUT winmm_handle;
HANDLE buffer_state_changed_event;
std::thread winmm_mixing_thread;
std::vector<WAVEHDR> winmm_headers;
std::vector<short*> audio_data;
std::atomic_flag winmm_mixing_flag;
};
WinmmOutputDevice::WinmmOutputDevice(std::function<void(float*, int)> getBuffer, unsigned int blockSize, unsigned int channels, unsigned int maxChannels, unsigned int mixAhead, UINT_PTR which, unsigned int sourceSr, unsigned int targetSr) {
WAVEFORMATEXTENSIBLE format = {0};
mixAhead += 1;
winmm_headers.resize(mixAhead);
audio_data.resize(mixAhead);
buffer_state_changed_event = CreateEvent(NULL, FALSE, FALSE, NULL);
//we try all the channels until we get a device, and then bale out if we've still failed.
unsigned int chancounts[] = {8, 6, 2};
MMRESULT res = 0;
winmm_handle = nullptr;
bool gotAudio = false;
unsigned int neededChannels = channels < 2 ? 2 : channels;
unsigned int inChannels = neededChannels, outChannels = 0;
for(unsigned int i = 0; i < 3; i++) {
if(chancounts[i] > neededChannels) continue;
if(chancounts[i] > maxChannels) continue;
format = makeFormat(chancounts[i], targetSr, true);
res = waveOutOpen(&winmm_handle, which, (WAVEFORMATEX*)&format, (DWORD)buffer_state_changed_event, NULL, CALLBACK_EVENT);
if(res == MMSYSERR_NOERROR) {
gotAudio = true;
outChannels = chancounts[i];
break;
}
}
if(gotAudio == false) { //we can still maybe get something by falling back to a last resort.
//we make this back into a waveformatex and request stereo.
format = makeFormat(2, targetSr, false);
res = waveOutOpen(&winmm_handle, which, (WAVEFORMATEX*)&format, (DWORD)buffer_state_changed_event, NULL, CALLBACK_EVENT);
//error checking needs to go here.
outChannels = 2;
}
init(getBuffer, blockSize, sourceSr, outChannels, targetSr, mixAhead);
for(unsigned int i = 0; i < audio_data.size(); i++) audio_data[i] = new short[output_buffer_size];
//we can go ahead and set up the headers.
for(unsigned int i = 0; i < winmm_headers.size(); i++) {
winmm_headers[i].lpData = (LPSTR)audio_data[i];
winmm_headers[i].dwBufferLength = sizeof(short)*blockSize*channels;
winmm_headers[i].dwFlags = WHDR_DONE;
}
winmm_mixing_flag.test_and_set();
winmm_mixing_thread = std::thread([this]() {winmm_mixer();});
start();
}
WinmmOutputDevice::~WinmmOutputDevice() {
stop();
}
void WinmmOutputDevice::stop() {
if(started) {
winmm_mixing_flag.clear();
winmm_mixing_thread.join();
}
OutputDeviceImplementation::stop();
}
void WinmmOutputDevice::winmm_mixer() {
float* workspace = new float[output_buffer_size];
while(winmm_mixing_flag.test_and_set()) {
while(1) {
short* nextBuffer = nullptr;
WAVEHDR* nextHeader = nullptr;
for(unsigned int i = 0; i < winmm_headers.size(); i++) {
if(winmm_headers[i].dwFlags & WHDR_DONE) {
nextBuffer = audio_data[i];
nextHeader = &winmm_headers[i];
break;
}
}
if(nextHeader == nullptr || nextBuffer == nullptr) break;
zeroOrNextBuffer(workspace);
waveOutUnprepareHeader(winmm_handle, nextHeader, sizeof(WAVEHDR));
for(unsigned int i = 0; i < output_buffer_size; i++) nextBuffer[i] = (short)(workspace[i]*32767);
nextHeader->dwFlags = 0;
nextHeader->dwBufferLength = sizeof(short)*output_buffer_size;
nextHeader->lpData = (LPSTR)nextBuffer;
waveOutPrepareHeader(winmm_handle, nextHeader, sizeof(WAVEHDR));
waveOutWrite(winmm_handle, nextHeader, sizeof(WAVEHDR));
}
WaitForSingleObject(buffer_state_changed_event, 5); //the timeout is to let us detect that we've been requested to die.
}
//we prepared these, we need to also kill them. If we don't, very very bad things happen.
for(auto i= winmm_headers.begin(); i != winmm_headers.end(); i++) {
auto *header = &*i;
while((header->dwFlags & WHDR_DONE) == 0) {
std::this_thread::yield();
}
waveOutUnprepareHeader(winmm_handle, header, sizeof(WAVEHDR));
}
waveOutClose(winmm_handle);
winmm_handle=nullptr;
}
class WinmmOutputDeviceFactory: public OutputDeviceFactoryImplementation {
public:
WinmmOutputDeviceFactory();
virtual std::vector<std::string> getOutputNames();
virtual std::vector<int> getOutputMaxChannels();
virtual std::shared_ptr<OutputDevice> createDevice(std::function<void(float*, int)> getBuffer, int index, unsigned int channels, unsigned int sr, unsigned int blockSize, unsigned int mixAhead);
virtual unsigned int getOutputCount();
virtual bool scan();
std::string getName();
private:
std::vector<std::string> names;
std::vector<int> max_channels;
std::vector<unsigned int> srs; //we need this, because these are not easy to query.
unsigned int mapper_max_channels = 2, mapper_sr = 44100;
};
WinmmOutputDeviceFactory::WinmmOutputDeviceFactory() {
}
std::vector<std::string> WinmmOutputDeviceFactory::getOutputNames() {
return names;
}
std::vector<int> WinmmOutputDeviceFactory::getOutputMaxChannels() {
return max_channels;
}
std::shared_ptr<OutputDevice> WinmmOutputDeviceFactory::createDevice(std::function<void(float*, int)> getBuffer, int index, unsigned int channels, unsigned int sr, unsigned int blockSize, unsigned int mixAhead) {
//first, we need to do sanity checks.
//error checking.
std::shared_ptr<OutputDeviceImplementation> device = std::make_shared<WinmmOutputDevice>(getBuffer, blockSize, channels, index != -1 ? max_channels[index] : mapper_max_channels, mixAhead, index == -1 ? WAVE_MAPPER : index, sr, index == -1 ? mapper_sr : srs[index]);
created_devices.push_back(device);
return device;
}
unsigned int WinmmOutputDeviceFactory::getOutputCount() {
return names.size();
}
std::string WinmmOutputDeviceFactory::getName() {
return "Winmm";
}
struct WinmmCapabilities {
unsigned int sr;
std::string name;
unsigned int channels;
};
WinmmCapabilities getWinmmCapabilities(UINT index) {
WAVEFORMATEXTENSIBLE format;
WAVEOUTCAPS caps;
waveOutGetDevCaps(index, &caps, sizeof(caps));
WinmmCapabilities retval;
retval.sr = 44100;
retval.channels = 2;
retval.name = std::string(caps.szPname);
unsigned int srs[] = {48000, 44100, 22050};
unsigned int srsCount = 3;
unsigned int channels[] = {8, 6, 2};
unsigned int channelsCount = 3;
for(unsigned int i = 0; i < channelsCount; i++) {
for(unsigned int j = 0; j < srsCount; j++) {
format = makeFormat(channels[i], srs[j], true);
auto res = waveOutOpen(NULL, index, (WAVEFORMATEX*)&format, NULL, NULL, WAVE_FORMAT_QUERY);
if(res == MMSYSERR_NOERROR) {
retval.sr = srs[j];
retval.channels = channels[i];
goto done;
}
}
}
done:
return retval;
}
bool WinmmOutputDeviceFactory::scan() {
std::vector<std::string> newNames;
std::vector<int> newMaxChannels;
std::vector<unsigned int> newSrs; //we need this, because these are not easy to query.
UINT devs = waveOutGetNumDevs();
WinmmCapabilities caps;
for(UINT i = 0; i < devs; i++) {
caps = getWinmmCapabilities(i);
//todo: unicode support
std::string name(caps.name);
//channels.
unsigned int channels = caps.channels;
unsigned int sr = caps.sr;
newMaxChannels.push_back(channels);
newNames.push_back(name);
newSrs.push_back(sr);
}
this->max_channels = newMaxChannels;
this->names = newNames;
this->srs = newSrs;
caps = getWinmmCapabilities(WAVE_MAPPER);
mapper_max_channels = caps.channels;
mapper_sr = caps.sr;
return true;
}
OutputDeviceFactory* createWinmmOutputDeviceFactory() {
WinmmOutputDeviceFactory* fact = new WinmmOutputDeviceFactory();
if(fact->scan() == false) {
delete fact;
return nullptr;
}
return fact;
}
} //end namespace implementation
} //end namespace audio_io
|
#include <audio_io/audio_io.hpp>
#include <audio_io/audio_io_private.hpp>
#include <functional>
#include <string>
#include <vector>
#include <memory>
#include <utility>
#include <mutex>
#include <map>
#include <string.h>
#include <algorithm>
#include <thread>
#include <chrono>
#include <windows.h>
#include <mmreg.h> //WAVEFORMATEXTENSIBLE
namespace audio_io {
namespace implementation {
WAVEFORMATEXTENSIBLE makeFormat(unsigned int channels, unsigned int sr, bool isExtended) {
//lookup table so we can easily pull out masks.
unsigned int chanmasks[] = {
0,
0,
SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT,
0,
0,
0,
SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT,
0,
SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT,
};
WAVEFORMATEXTENSIBLE format;
format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
format.Format.nSamplesPerSec = sr;
format.Format.wBitsPerSample = 16;
format.Format.cbSize = 22; //this comes directly from msdn, which gives no further explanation.
format.Samples.wValidBitsPerSample = 16;
format.Format.nAvgBytesPerSec = channels*2*sr;
format.Format.nBlockAlign = channels*2;
format.Format.nChannels = channels;
format.dwChannelMask = chanmasks[channels];
format.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
if(isExtended == false) {
format.Format.cbSize = 0;
format.Format.wFormatTag = WAVE_FORMAT_PCM;
}
return format;
}
class WinmmOutputDevice: public OutputDeviceImplementation {
public:
//channels is what user requested, maxChannels is what the device can support at most.
//maxChannels comes from the DeviceFactory subclass and is cached; thus the parameter here.
WinmmOutputDevice(std::function<void(float*, int)> getBuffer, unsigned int blockSize, unsigned int channels, unsigned int maxChannels, unsigned int mixAhead, UINT_PTR which, unsigned int sourceSr, unsigned int targetSr);
~WinmmOutputDevice();
virtual void stop() override;
void winmm_mixer();
HWAVEOUT winmm_handle;
HANDLE buffer_state_changed_event;
std::thread winmm_mixing_thread;
std::vector<WAVEHDR> winmm_headers;
std::vector<short*> audio_data;
std::atomic_flag winmm_mixing_flag;
};
WinmmOutputDevice::WinmmOutputDevice(std::function<void(float*, int)> getBuffer, unsigned int blockSize, unsigned int channels, unsigned int maxChannels, unsigned int mixAhead, UINT_PTR which, unsigned int sourceSr, unsigned int targetSr) {
WAVEFORMATEXTENSIBLE format = {0};
mixAhead += 1;
winmm_headers.resize(mixAhead);
audio_data.resize(mixAhead);
buffer_state_changed_event = CreateEvent(NULL, FALSE, FALSE, NULL);
//we try all the channels until we get a device, and then bale out if we've still failed.
unsigned int chancounts[] = {8, 6, 2};
MMRESULT res = 0;
winmm_handle = nullptr;
bool gotAudio = false;
unsigned int neededChannels = channels < 2 ? 2 : channels;
unsigned int inChannels = neededChannels, outChannels = 0;
for(unsigned int i = 0; i < 3; i++) {
if(chancounts[i] > neededChannels) continue;
if(chancounts[i] > maxChannels) continue;
format = makeFormat(chancounts[i], targetSr, true);
res = waveOutOpen(&winmm_handle, which, (WAVEFORMATEX*)&format, (DWORD)buffer_state_changed_event, NULL, CALLBACK_EVENT);
if(res == MMSYSERR_NOERROR) {
gotAudio = true;
outChannels = chancounts[i];
break;
}
}
if(gotAudio == false) { //we can still maybe get something by falling back to a last resort.
//we make this back into a waveformatex and request stereo.
format = makeFormat(2, targetSr, false);
res = waveOutOpen(&winmm_handle, which, (WAVEFORMATEX*)&format, (DWORD)buffer_state_changed_event, NULL, CALLBACK_EVENT);
//error checking needs to go here.
outChannels = 2;
}
init(getBuffer, blockSize, sourceSr, outChannels, targetSr, mixAhead);
for(unsigned int i = 0; i < audio_data.size(); i++) audio_data[i] = new short[output_buffer_size];
//we can go ahead and set up the headers.
for(unsigned int i = 0; i < winmm_headers.size(); i++) {
winmm_headers[i].lpData = (LPSTR)audio_data[i];
winmm_headers[i].dwBufferLength = sizeof(short)*blockSize*channels;
winmm_headers[i].dwFlags = WHDR_DONE;
}
winmm_mixing_flag.test_and_set();
winmm_mixing_thread = std::thread([this]() {winmm_mixer();});
start();
}
WinmmOutputDevice::~WinmmOutputDevice() {
stop();
}
void WinmmOutputDevice::stop() {
if(started) {
winmm_mixing_flag.clear();
winmm_mixing_thread.join();
}
OutputDeviceImplementation::stop();
}
void WinmmOutputDevice::winmm_mixer() {
float* workspace = new float[output_buffer_size];
while(winmm_mixing_flag.test_and_set()) {
while(1) {
short* nextBuffer = nullptr;
WAVEHDR* nextHeader = nullptr;
for(unsigned int i = 0; i < winmm_headers.size(); i++) {
if(winmm_headers[i].dwFlags & WHDR_DONE) {
nextBuffer = audio_data[i];
nextHeader = &winmm_headers[i];
break;
}
}
if(nextHeader == nullptr || nextBuffer == nullptr) break;
zeroOrNextBuffer(workspace);
waveOutUnprepareHeader(winmm_handle, nextHeader, sizeof(WAVEHDR));
for(unsigned int i = 0; i < output_buffer_size; i++) nextBuffer[i] = (short)(workspace[i]*32767);
nextHeader->dwFlags = 0;
nextHeader->dwBufferLength = sizeof(short)*output_buffer_size;
nextHeader->lpData = (LPSTR)nextBuffer;
waveOutPrepareHeader(winmm_handle, nextHeader, sizeof(WAVEHDR));
waveOutWrite(winmm_handle, nextHeader, sizeof(WAVEHDR));
}
WaitForSingleObject(buffer_state_changed_event, 5); //the timeout is to let us detect that we've been requested to die.
}
//we prepared these, we need to also kill them. If we don't, very very bad things happen.
//This call ends playback.
waveOutReset(winmm_handle);
for(auto i= winmm_headers.begin(); i != winmm_headers.end(); i++) {
auto *header = &*i;
while((header->dwFlags & WHDR_DONE) == 0) {
std::this_thread::yield();
}
waveOutUnprepareHeader(winmm_handle, header, sizeof(WAVEHDR));
}
waveOutClose(winmm_handle);
winmm_handle=nullptr;
}
class WinmmOutputDeviceFactory: public OutputDeviceFactoryImplementation {
public:
WinmmOutputDeviceFactory();
virtual std::vector<std::string> getOutputNames();
virtual std::vector<int> getOutputMaxChannels();
virtual std::shared_ptr<OutputDevice> createDevice(std::function<void(float*, int)> getBuffer, int index, unsigned int channels, unsigned int sr, unsigned int blockSize, unsigned int mixAhead);
virtual unsigned int getOutputCount();
virtual bool scan();
std::string getName();
private:
std::vector<std::string> names;
std::vector<int> max_channels;
std::vector<unsigned int> srs; //we need this, because these are not easy to query.
unsigned int mapper_max_channels = 2, mapper_sr = 44100;
};
WinmmOutputDeviceFactory::WinmmOutputDeviceFactory() {
}
std::vector<std::string> WinmmOutputDeviceFactory::getOutputNames() {
return names;
}
std::vector<int> WinmmOutputDeviceFactory::getOutputMaxChannels() {
return max_channels;
}
std::shared_ptr<OutputDevice> WinmmOutputDeviceFactory::createDevice(std::function<void(float*, int)> getBuffer, int index, unsigned int channels, unsigned int sr, unsigned int blockSize, unsigned int mixAhead) {
//first, we need to do sanity checks.
//error checking.
std::shared_ptr<OutputDeviceImplementation> device = std::make_shared<WinmmOutputDevice>(getBuffer, blockSize, channels, index != -1 ? max_channels[index] : mapper_max_channels, mixAhead, index == -1 ? WAVE_MAPPER : index, sr, index == -1 ? mapper_sr : srs[index]);
created_devices.push_back(device);
return device;
}
unsigned int WinmmOutputDeviceFactory::getOutputCount() {
return names.size();
}
std::string WinmmOutputDeviceFactory::getName() {
return "Winmm";
}
struct WinmmCapabilities {
unsigned int sr;
std::string name;
unsigned int channels;
};
WinmmCapabilities getWinmmCapabilities(UINT index) {
WAVEFORMATEXTENSIBLE format;
WAVEOUTCAPS caps;
waveOutGetDevCaps(index, &caps, sizeof(caps));
WinmmCapabilities retval;
retval.sr = 44100;
retval.channels = 2;
retval.name = std::string(caps.szPname);
unsigned int srs[] = {48000, 44100, 22050};
unsigned int srsCount = 3;
unsigned int channels[] = {8, 6, 2};
unsigned int channelsCount = 3;
for(unsigned int i = 0; i < channelsCount; i++) {
for(unsigned int j = 0; j < srsCount; j++) {
format = makeFormat(channels[i], srs[j], true);
auto res = waveOutOpen(NULL, index, (WAVEFORMATEX*)&format, NULL, NULL, WAVE_FORMAT_QUERY);
if(res == MMSYSERR_NOERROR) {
retval.sr = srs[j];
retval.channels = channels[i];
goto done;
}
}
}
done:
return retval;
}
bool WinmmOutputDeviceFactory::scan() {
std::vector<std::string> newNames;
std::vector<int> newMaxChannels;
std::vector<unsigned int> newSrs; //we need this, because these are not easy to query.
UINT devs = waveOutGetNumDevs();
WinmmCapabilities caps;
for(UINT i = 0; i < devs; i++) {
caps = getWinmmCapabilities(i);
//todo: unicode support
std::string name(caps.name);
//channels.
unsigned int channels = caps.channels;
unsigned int sr = caps.sr;
newMaxChannels.push_back(channels);
newNames.push_back(name);
newSrs.push_back(sr);
}
this->max_channels = newMaxChannels;
this->names = newNames;
this->srs = newSrs;
caps = getWinmmCapabilities(WAVE_MAPPER);
mapper_max_channels = caps.channels;
mapper_sr = caps.sr;
return true;
}
OutputDeviceFactory* createWinmmOutputDeviceFactory() {
WinmmOutputDeviceFactory* fact = new WinmmOutputDeviceFactory();
if(fact->scan() == false) {
delete fact;
return nullptr;
}
return fact;
}
} //end namespace implementation
} //end namespace audio_io
|
Insert a call to waveOutReset, making the thread shutdown happen faster.
|
Insert a call to waveOutReset, making the thread shutdown happen faster.
|
C++
|
unlicense
|
camlorn/audio_io,camlorn/audio_io,libaudioverse/audio_io,libaudioverse/audio_io
|
9ba68b2714e8ab9a6f3ed755096c95d5918e895d
|
lib/Basic/Module.cpp
|
lib/Basic/Module.cpp
|
//===--- Module.cpp - Describe a module -----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the Module class, which describes a module in the source
// code.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/Module.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
bool IsFramework, bool IsExplicit)
: Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent), Directory(),
Umbrella(), ASTFile(nullptr), IsMissingRequirement(false),
IsAvailable(true), IsFromModuleFile(false), IsFramework(IsFramework),
IsExplicit(IsExplicit), IsSystem(false), IsExternC(false),
IsInferred(false), InferSubmodules(false), InferExplicitSubmodules(false),
InferExportWildcard(false), ConfigMacrosExhaustive(false),
NameVisibility(Hidden) {
if (Parent) {
if (!Parent->isAvailable())
IsAvailable = false;
if (Parent->IsSystem)
IsSystem = true;
if (Parent->IsExternC)
IsExternC = true;
IsMissingRequirement = Parent->IsMissingRequirement;
Parent->SubModuleIndex[Name] = Parent->SubModules.size();
Parent->SubModules.push_back(this);
}
}
Module::~Module() {
for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
I != IEnd; ++I) {
delete *I;
}
}
/// \brief Determine whether a translation unit built using the current
/// language options has the given feature.
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
const TargetInfo &Target) {
return llvm::StringSwitch<bool>(Feature)
.Case("altivec", LangOpts.AltiVec)
.Case("blocks", LangOpts.Blocks)
.Case("cplusplus", LangOpts.CPlusPlus)
.Case("cplusplus11", LangOpts.CPlusPlus11)
.Case("objc", LangOpts.ObjC1)
.Case("objc_arc", LangOpts.ObjCAutoRefCount)
.Case("opencl", LangOpts.OpenCL)
.Case("tls", Target.isTLSSupported())
.Default(Target.hasFeature(Feature));
}
bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
Requirement &Req,
UnresolvedHeaderDirective &MissingHeader) const {
if (IsAvailable)
return true;
for (const Module *Current = this; Current; Current = Current->Parent) {
if (!Current->MissingHeaders.empty()) {
MissingHeader = Current->MissingHeaders.front();
return false;
}
for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
Current->Requirements[I].second) {
Req = Current->Requirements[I];
return false;
}
}
}
llvm_unreachable("could not find a reason why module is unavailable");
}
bool Module::isSubModuleOf(const Module *Other) const {
const Module *This = this;
do {
if (This == Other)
return true;
This = This->Parent;
} while (This);
return false;
}
const Module *Module::getTopLevelModule() const {
const Module *Result = this;
while (Result->Parent)
Result = Result->Parent;
return Result;
}
std::string Module::getFullModuleName() const {
SmallVector<StringRef, 2> Names;
// Build up the set of module names (from innermost to outermost).
for (const Module *M = this; M; M = M->Parent)
Names.push_back(M->Name);
std::string Result;
for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
IEnd = Names.rend();
I != IEnd; ++I) {
if (!Result.empty())
Result += '.';
Result += *I;
}
return Result;
}
const DirectoryEntry *Module::getUmbrellaDir() const {
if (const FileEntry *Header = getUmbrellaHeader())
return Header->getDir();
return Umbrella.dyn_cast<const DirectoryEntry *>();
}
ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
if (!TopHeaderNames.empty()) {
for (std::vector<std::string>::iterator
I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
if (const FileEntry *FE = FileMgr.getFile(*I))
TopHeaders.insert(FE);
}
TopHeaderNames.clear();
}
return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
}
void Module::addRequirement(StringRef Feature, bool RequiredState,
const LangOptions &LangOpts,
const TargetInfo &Target) {
Requirements.push_back(Requirement(Feature, RequiredState));
// If this feature is currently available, we're done.
if (hasFeature(Feature, LangOpts, Target) == RequiredState)
return;
markUnavailable(/*MissingRequirement*/true);
}
void Module::markUnavailable(bool MissingRequirement) {
if (!IsAvailable)
return;
SmallVector<Module *, 2> Stack;
Stack.push_back(this);
while (!Stack.empty()) {
Module *Current = Stack.back();
Stack.pop_back();
if (!Current->IsAvailable)
continue;
Current->IsAvailable = false;
Current->IsMissingRequirement |= MissingRequirement;
for (submodule_iterator Sub = Current->submodule_begin(),
SubEnd = Current->submodule_end();
Sub != SubEnd; ++Sub) {
if ((*Sub)->IsAvailable)
Stack.push_back(*Sub);
}
}
}
Module *Module::findSubmodule(StringRef Name) const {
llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
if (Pos == SubModuleIndex.end())
return nullptr;
return SubModules[Pos->getValue()];
}
static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
for (unsigned I = 0, N = Id.size(); I != N; ++I) {
if (I)
OS << ".";
OS << Id[I].first;
}
}
void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
// All non-explicit submodules are exported.
for (std::vector<Module *>::const_iterator I = SubModules.begin(),
E = SubModules.end();
I != E; ++I) {
Module *Mod = *I;
if (!Mod->IsExplicit)
Exported.push_back(Mod);
}
// Find re-exported modules by filtering the list of imported modules.
bool AnyWildcard = false;
bool UnrestrictedWildcard = false;
SmallVector<Module *, 4> WildcardRestrictions;
for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
Module *Mod = Exports[I].getPointer();
if (!Exports[I].getInt()) {
// Export a named module directly; no wildcards involved.
Exported.push_back(Mod);
continue;
}
// Wildcard export: export all of the imported modules that match
// the given pattern.
AnyWildcard = true;
if (UnrestrictedWildcard)
continue;
if (Module *Restriction = Exports[I].getPointer())
WildcardRestrictions.push_back(Restriction);
else {
WildcardRestrictions.clear();
UnrestrictedWildcard = true;
}
}
// If there were any wildcards, push any imported modules that were
// re-exported by the wildcard restriction.
if (!AnyWildcard)
return;
for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
Module *Mod = Imports[I];
bool Acceptable = UnrestrictedWildcard;
if (!Acceptable) {
// Check whether this module meets one of the restrictions.
for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
Module *Restriction = WildcardRestrictions[R];
if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
Acceptable = true;
break;
}
}
}
if (!Acceptable)
continue;
Exported.push_back(Mod);
}
}
void Module::buildVisibleModulesCache() const {
assert(VisibleModulesCache.empty() && "cache does not need building");
// This module is visible to itself.
VisibleModulesCache.insert(this);
// Every imported module is visible.
SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
while (!Stack.empty()) {
Module *CurrModule = Stack.pop_back_val();
// Every module transitively exported by an imported module is visible.
if (VisibleModulesCache.insert(CurrModule).second)
CurrModule->getExportedModules(Stack);
}
}
void Module::print(raw_ostream &OS, unsigned Indent) const {
OS.indent(Indent);
if (IsFramework)
OS << "framework ";
if (IsExplicit)
OS << "explicit ";
OS << "module " << Name;
if (IsSystem) {
OS.indent(Indent + 2);
OS << " [system]";
}
OS << " {\n";
if (!Requirements.empty()) {
OS.indent(Indent + 2);
OS << "requires ";
for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
if (I)
OS << ", ";
if (!Requirements[I].second)
OS << "!";
OS << Requirements[I].first;
}
OS << "\n";
}
if (const FileEntry *UmbrellaHeader = getUmbrellaHeader()) {
OS.indent(Indent + 2);
OS << "umbrella header \"";
OS.write_escaped(UmbrellaHeader->getName());
OS << "\"\n";
} else if (const DirectoryEntry *UmbrellaDir = getUmbrellaDir()) {
OS.indent(Indent + 2);
OS << "umbrella \"";
OS.write_escaped(UmbrellaDir->getName());
OS << "\"\n";
}
if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
OS.indent(Indent + 2);
OS << "config_macros ";
if (ConfigMacrosExhaustive)
OS << "[exhaustive]";
for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
if (I)
OS << ", ";
OS << ConfigMacros[I];
}
OS << "\n";
}
struct {
StringRef Prefix;
HeaderKind Kind;
} Kinds[] = {{"", HK_Normal},
{"textual ", HK_Textual},
{"private ", HK_Private},
{"private textual ", HK_PrivateTextual},
{"exclude ", HK_Excluded}};
for (auto &K : Kinds) {
for (auto &H : Headers[K.Kind]) {
OS.indent(Indent + 2);
OS << K.Prefix << "header \"";
OS.write_escaped(H.NameAsWritten);
OS << "\"\n";
}
}
for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
MI != MIEnd; ++MI)
// Print inferred subframework modules so that we don't need to re-infer
// them (requires expensive directory iteration + stat calls) when we build
// the module. Regular inferred submodules are OK, as we need to look at all
// those header files anyway.
if (!(*MI)->IsInferred || (*MI)->IsFramework)
(*MI)->print(OS, Indent + 2);
for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "export ";
if (Module *Restriction = Exports[I].getPointer()) {
OS << Restriction->getFullModuleName();
if (Exports[I].getInt())
OS << ".*";
} else {
OS << "*";
}
OS << "\n";
}
for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "export ";
printModuleId(OS, UnresolvedExports[I].Id);
if (UnresolvedExports[I].Wildcard) {
if (UnresolvedExports[I].Id.empty())
OS << "*";
else
OS << ".*";
}
OS << "\n";
}
for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "use ";
OS << DirectUses[I]->getFullModuleName();
OS << "\n";
}
for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "use ";
printModuleId(OS, UnresolvedDirectUses[I]);
OS << "\n";
}
for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "link ";
if (LinkLibraries[I].IsFramework)
OS << "framework ";
OS << "\"";
OS.write_escaped(LinkLibraries[I].Library);
OS << "\"";
}
for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "conflict ";
printModuleId(OS, UnresolvedConflicts[I].Id);
OS << ", \"";
OS.write_escaped(UnresolvedConflicts[I].Message);
OS << "\"\n";
}
for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "conflict ";
OS << Conflicts[I].Other->getFullModuleName();
OS << ", \"";
OS.write_escaped(Conflicts[I].Message);
OS << "\"\n";
}
if (InferSubmodules) {
OS.indent(Indent + 2);
if (InferExplicitSubmodules)
OS << "explicit ";
OS << "module * {\n";
if (InferExportWildcard) {
OS.indent(Indent + 4);
OS << "export *\n";
}
OS.indent(Indent + 2);
OS << "}\n";
}
OS.indent(Indent);
OS << "}\n";
}
void Module::dump() const {
print(llvm::errs());
}
|
//===--- Module.cpp - Describe a module -----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the Module class, which describes a module in the source
// code.
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/Module.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent,
bool IsFramework, bool IsExplicit)
: Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent), Directory(),
Umbrella(), ASTFile(nullptr), IsMissingRequirement(false),
IsAvailable(true), IsFromModuleFile(false), IsFramework(IsFramework),
IsExplicit(IsExplicit), IsSystem(false), IsExternC(false),
IsInferred(false), InferSubmodules(false), InferExplicitSubmodules(false),
InferExportWildcard(false), ConfigMacrosExhaustive(false),
NameVisibility(Hidden) {
if (Parent) {
if (!Parent->isAvailable())
IsAvailable = false;
if (Parent->IsSystem)
IsSystem = true;
if (Parent->IsExternC)
IsExternC = true;
IsMissingRequirement = Parent->IsMissingRequirement;
Parent->SubModuleIndex[Name] = Parent->SubModules.size();
Parent->SubModules.push_back(this);
}
}
Module::~Module() {
for (submodule_iterator I = submodule_begin(), IEnd = submodule_end();
I != IEnd; ++I) {
delete *I;
}
}
/// \brief Determine whether a translation unit built using the current
/// language options has the given feature.
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts,
const TargetInfo &Target) {
return llvm::StringSwitch<bool>(Feature)
.Case("altivec", LangOpts.AltiVec)
.Case("blocks", LangOpts.Blocks)
.Case("cplusplus", LangOpts.CPlusPlus)
.Case("cplusplus11", LangOpts.CPlusPlus11)
.Case("objc", LangOpts.ObjC1)
.Case("objc_arc", LangOpts.ObjCAutoRefCount)
.Case("opencl", LangOpts.OpenCL)
.Case("tls", Target.isTLSSupported())
.Default(Target.hasFeature(Feature));
}
bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target,
Requirement &Req,
UnresolvedHeaderDirective &MissingHeader) const {
if (IsAvailable)
return true;
for (const Module *Current = this; Current; Current = Current->Parent) {
if (!Current->MissingHeaders.empty()) {
MissingHeader = Current->MissingHeaders.front();
return false;
}
for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) {
if (hasFeature(Current->Requirements[I].first, LangOpts, Target) !=
Current->Requirements[I].second) {
Req = Current->Requirements[I];
return false;
}
}
}
llvm_unreachable("could not find a reason why module is unavailable");
}
bool Module::isSubModuleOf(const Module *Other) const {
const Module *This = this;
do {
if (This == Other)
return true;
This = This->Parent;
} while (This);
return false;
}
const Module *Module::getTopLevelModule() const {
const Module *Result = this;
while (Result->Parent)
Result = Result->Parent;
return Result;
}
std::string Module::getFullModuleName() const {
SmallVector<StringRef, 2> Names;
// Build up the set of module names (from innermost to outermost).
for (const Module *M = this; M; M = M->Parent)
Names.push_back(M->Name);
std::string Result;
for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(),
IEnd = Names.rend();
I != IEnd; ++I) {
if (!Result.empty())
Result += '.';
Result += *I;
}
return Result;
}
const DirectoryEntry *Module::getUmbrellaDir() const {
if (const FileEntry *Header = getUmbrellaHeader())
return Header->getDir();
return Umbrella.dyn_cast<const DirectoryEntry *>();
}
ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) {
if (!TopHeaderNames.empty()) {
for (std::vector<std::string>::iterator
I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) {
if (const FileEntry *FE = FileMgr.getFile(*I))
TopHeaders.insert(FE);
}
TopHeaderNames.clear();
}
return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end());
}
void Module::addRequirement(StringRef Feature, bool RequiredState,
const LangOptions &LangOpts,
const TargetInfo &Target) {
Requirements.push_back(Requirement(Feature, RequiredState));
// If this feature is currently available, we're done.
if (hasFeature(Feature, LangOpts, Target) == RequiredState)
return;
markUnavailable(/*MissingRequirement*/true);
}
void Module::markUnavailable(bool MissingRequirement) {
if (!IsAvailable)
return;
SmallVector<Module *, 2> Stack;
Stack.push_back(this);
while (!Stack.empty()) {
Module *Current = Stack.back();
Stack.pop_back();
if (!Current->IsAvailable)
continue;
Current->IsAvailable = false;
Current->IsMissingRequirement |= MissingRequirement;
for (submodule_iterator Sub = Current->submodule_begin(),
SubEnd = Current->submodule_end();
Sub != SubEnd; ++Sub) {
if ((*Sub)->IsAvailable)
Stack.push_back(*Sub);
}
}
}
Module *Module::findSubmodule(StringRef Name) const {
llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name);
if (Pos == SubModuleIndex.end())
return nullptr;
return SubModules[Pos->getValue()];
}
static void printModuleId(raw_ostream &OS, const ModuleId &Id) {
for (unsigned I = 0, N = Id.size(); I != N; ++I) {
if (I)
OS << ".";
OS << Id[I].first;
}
}
void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const {
// All non-explicit submodules are exported.
for (std::vector<Module *>::const_iterator I = SubModules.begin(),
E = SubModules.end();
I != E; ++I) {
Module *Mod = *I;
if (!Mod->IsExplicit)
Exported.push_back(Mod);
}
// Find re-exported modules by filtering the list of imported modules.
bool AnyWildcard = false;
bool UnrestrictedWildcard = false;
SmallVector<Module *, 4> WildcardRestrictions;
for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
Module *Mod = Exports[I].getPointer();
if (!Exports[I].getInt()) {
// Export a named module directly; no wildcards involved.
Exported.push_back(Mod);
continue;
}
// Wildcard export: export all of the imported modules that match
// the given pattern.
AnyWildcard = true;
if (UnrestrictedWildcard)
continue;
if (Module *Restriction = Exports[I].getPointer())
WildcardRestrictions.push_back(Restriction);
else {
WildcardRestrictions.clear();
UnrestrictedWildcard = true;
}
}
// If there were any wildcards, push any imported modules that were
// re-exported by the wildcard restriction.
if (!AnyWildcard)
return;
for (unsigned I = 0, N = Imports.size(); I != N; ++I) {
Module *Mod = Imports[I];
bool Acceptable = UnrestrictedWildcard;
if (!Acceptable) {
// Check whether this module meets one of the restrictions.
for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) {
Module *Restriction = WildcardRestrictions[R];
if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) {
Acceptable = true;
break;
}
}
}
if (!Acceptable)
continue;
Exported.push_back(Mod);
}
}
void Module::buildVisibleModulesCache() const {
assert(VisibleModulesCache.empty() && "cache does not need building");
// This module is visible to itself.
VisibleModulesCache.insert(this);
// Every imported module is visible.
SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end());
while (!Stack.empty()) {
Module *CurrModule = Stack.pop_back_val();
// Every module transitively exported by an imported module is visible.
if (VisibleModulesCache.insert(CurrModule).second)
CurrModule->getExportedModules(Stack);
}
}
void Module::print(raw_ostream &OS, unsigned Indent) const {
OS.indent(Indent);
if (IsFramework)
OS << "framework ";
if (IsExplicit)
OS << "explicit ";
OS << "module " << Name;
if (IsSystem || IsExternC) {
OS.indent(Indent + 2);
if (IsSystem)
OS << " [system]";
if (IsExternC)
OS << " [extern_c]";
}
OS << " {\n";
if (!Requirements.empty()) {
OS.indent(Indent + 2);
OS << "requires ";
for (unsigned I = 0, N = Requirements.size(); I != N; ++I) {
if (I)
OS << ", ";
if (!Requirements[I].second)
OS << "!";
OS << Requirements[I].first;
}
OS << "\n";
}
if (const FileEntry *UmbrellaHeader = getUmbrellaHeader()) {
OS.indent(Indent + 2);
OS << "umbrella header \"";
OS.write_escaped(UmbrellaHeader->getName());
OS << "\"\n";
} else if (const DirectoryEntry *UmbrellaDir = getUmbrellaDir()) {
OS.indent(Indent + 2);
OS << "umbrella \"";
OS.write_escaped(UmbrellaDir->getName());
OS << "\"\n";
}
if (!ConfigMacros.empty() || ConfigMacrosExhaustive) {
OS.indent(Indent + 2);
OS << "config_macros ";
if (ConfigMacrosExhaustive)
OS << "[exhaustive]";
for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) {
if (I)
OS << ", ";
OS << ConfigMacros[I];
}
OS << "\n";
}
struct {
StringRef Prefix;
HeaderKind Kind;
} Kinds[] = {{"", HK_Normal},
{"textual ", HK_Textual},
{"private ", HK_Private},
{"private textual ", HK_PrivateTextual},
{"exclude ", HK_Excluded}};
for (auto &K : Kinds) {
for (auto &H : Headers[K.Kind]) {
OS.indent(Indent + 2);
OS << K.Prefix << "header \"";
OS.write_escaped(H.NameAsWritten);
OS << "\"\n";
}
}
for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end();
MI != MIEnd; ++MI)
// Print inferred subframework modules so that we don't need to re-infer
// them (requires expensive directory iteration + stat calls) when we build
// the module. Regular inferred submodules are OK, as we need to look at all
// those header files anyway.
if (!(*MI)->IsInferred || (*MI)->IsFramework)
(*MI)->print(OS, Indent + 2);
for (unsigned I = 0, N = Exports.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "export ";
if (Module *Restriction = Exports[I].getPointer()) {
OS << Restriction->getFullModuleName();
if (Exports[I].getInt())
OS << ".*";
} else {
OS << "*";
}
OS << "\n";
}
for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "export ";
printModuleId(OS, UnresolvedExports[I].Id);
if (UnresolvedExports[I].Wildcard) {
if (UnresolvedExports[I].Id.empty())
OS << "*";
else
OS << ".*";
}
OS << "\n";
}
for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "use ";
OS << DirectUses[I]->getFullModuleName();
OS << "\n";
}
for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "use ";
printModuleId(OS, UnresolvedDirectUses[I]);
OS << "\n";
}
for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "link ";
if (LinkLibraries[I].IsFramework)
OS << "framework ";
OS << "\"";
OS.write_escaped(LinkLibraries[I].Library);
OS << "\"";
}
for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "conflict ";
printModuleId(OS, UnresolvedConflicts[I].Id);
OS << ", \"";
OS.write_escaped(UnresolvedConflicts[I].Message);
OS << "\"\n";
}
for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) {
OS.indent(Indent + 2);
OS << "conflict ";
OS << Conflicts[I].Other->getFullModuleName();
OS << ", \"";
OS.write_escaped(Conflicts[I].Message);
OS << "\"\n";
}
if (InferSubmodules) {
OS.indent(Indent + 2);
if (InferExplicitSubmodules)
OS << "explicit ";
OS << "module * {\n";
if (InferExportWildcard) {
OS.indent(Indent + 4);
OS << "export *\n";
}
OS.indent(Indent + 2);
OS << "}\n";
}
OS.indent(Indent);
OS << "}\n";
}
void Module::dump() const {
print(llvm::errs());
}
|
Handle [extern_c] attribute in module printer
|
Handle [extern_c] attribute in module printer
I'm not sure why we have OS.indent(Indent+2) for the system attribute,
but presumably we want the same behaviour for all attributes...
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@225802 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang
|
107dccc9772f2cb2e2a906d546f18280c611d76a
|
apps/qtViewer/ModelViewer.cpp
|
apps/qtViewer/ModelViewer.cpp
|
// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "ModelViewer.h"
#include "widgets/affineSpaceManipulator/HelperGeometry.h"
#include "sg/SceneGraph.h"
#include "sg/Renderer.h"
namespace ospray {
namespace viewer {
using std::cout;
using std::endl;
struct FPSCounter {
double fps;
double smooth_nom;
double smooth_den;
double frameStartTime;
FPSCounter()
{
smooth_nom = 0.;
smooth_den = 0.;
frameStartTime = 0.;
}
void startRender() { frameStartTime = ospray::getSysTime(); }
void doneRender() {
double seconds = ospray::getSysTime() - frameStartTime;
fps = 1./seconds;
smooth_nom = smooth_nom * 0.8 + seconds;
smooth_den = smooth_den * 0.8 + 1.;
}
double getSmoothFPS() const { return smooth_den / smooth_nom; }
double getFPS() const { return fps; }
};
FPSCounter fps;
OSPRayRenderWidget::OSPRayRenderWidget(Ref<sg::Renderer> renderer)
: QAffineSpaceManipulator(QAffineSpaceManipulator::INSPECT),
sgRenderer(renderer)
{
if (renderer->world) {
box3f worldBounds = renderer->world->getBounds();
if (!worldBounds.empty()) {
float moveSpeed = .25*length(worldBounds.size());
QAffineSpaceManipulator::setMoveSpeed(moveSpeed);
}
}
Ref<sg::PerspectiveCamera> camera = renderer->camera.cast<sg::PerspectiveCamera>();
if (camera) {
frame->sourcePoint = camera->getFrom();
frame->targetPoint = camera->getAt();
frame->upVector = camera->getUp();
frame->orientation.vz = normalize(camera->getUp());
frame->orientation.vy = normalize(camera->getAt() - camera->getFrom());
frame->orientation.vx = normalize(cross(frame->orientation.vy,frame->orientation.vz));
}
}
void OSPRayRenderWidget::setWorld(Ref<sg::World> world)
{
assert(sgRenderer);
sgRenderer->setWorld(world);
cout << "#ospQTV: world set, found "
<< sgRenderer->allNodes.size() << " nodes" << endl;
}
//! the QT callback that tells us that we have to redraw
void OSPRayRenderWidget::redraw()
{
if (!sgRenderer) return;
if (!sgRenderer->frameBuffer) return;
if (!sgRenderer->camera) return;
if (showFPS) {
static int frameID = 0;
if (frameID > 0) {
fps.doneRender();
printf("fps: %7.3f (smoothed: %7.3f)\n",fps.getFPS(),fps.getSmoothFPS());
}
fps.startRender();
++frameID;
}
sgRenderer->renderFrame();
vec2i size = sgRenderer->frameBuffer->getSize();
unsigned char *fbMem = sgRenderer->frameBuffer->map();
glDrawPixels(size.x, size.y, GL_RGBA, GL_UNSIGNED_BYTE, fbMem);
sgRenderer->frameBuffer->unmap(fbMem);
// accumulate, but only up to 32 frames
if (sgRenderer->accumID < 32)
update();
}
//! the QT callback that tells us that the image got resize
void OSPRayRenderWidget::resize(int width, int height)
{
sgRenderer->frameBuffer = new sg::FrameBuffer(vec2i(width,height));
sgRenderer->resetAccumulation();
Ref<sg::PerspectiveCamera> camera = sgRenderer->camera.cast<sg::PerspectiveCamera>();
camera->setAspect(width/float(height));
camera->commit();
}
//! update the ospray camera (ospCamera) from the widget camera (this->camera)
void OSPRayRenderWidget::updateOSPRayCamera()
{
if (!sgRenderer) return;
if (!sgRenderer->camera) return;
sgRenderer->resetAccumulation();
Ref<sg::PerspectiveCamera> camera = sgRenderer->camera.cast<sg::PerspectiveCamera>();
assert(camera);
const vec3f from = frame->sourcePoint;
const vec3f at = frame->targetPoint;
vec2i size = sgRenderer->frameBuffer->getSize();
camera->setFrom(from);
camera->setAt(at);
camera->setUp(frame->orientation.vz);
camera->setAspect(size.x/float(size.y));
camera->commit();
}
//! create the lower-side time step slider (for models that have
//! time steps; won't do anything for models that don't)
void ModelViewer::createTimeSlider()
{
}
//! create the widet on the side that'll host all the editing widgets
void ModelViewer::createEditorWidgetStack()
{
editorWidgetStack = new EditorWidgetStack;
editorWidgetDock = new QDockWidget(this);
editorWidgetDock->setWindowTitle("Editors");
editorWidgetDock->setWidget(editorWidgetStack);
editorWidgetDock->setFeatures(0);
addDockWidget(Qt::RightDockWidgetArea,editorWidgetDock);
}
void ModelViewer::createTransferFunctionEditor()
{
QWidget *xfEditorsPage = NULL;
// make a list of all transfer function nodes in the scene graph
std::vector<Ref<sg::TransferFunction> > xferFuncs;
for (int i=0;i<sgRenderer->uniqueNodes.size();i++) {
sg::TransferFunction *xf = dynamic_cast<sg::TransferFunction *>
(sgRenderer->uniqueNodes.object[i]->node.ptr);
if (xf) xferFuncs.push_back(xf);
}
std::cout << "#osp:qtv: found " << xferFuncs.size()
<< " transfer function nodes" << std::endl;
if (xferFuncs.empty()) {
xfEditorsPage = new QLabel("(no xfer fcts found)");
} else {
// -------------------------------------------------------
// found some transfer functions - create a stacked widget
// with an editor for each
// -------------------------------------------------------
xfEditorsPage = new QWidget;
QVBoxLayout *layout = new QVBoxLayout;
xfEditorsPage->setLayout(layout);
QStackedWidget *stackedWidget = new QStackedWidget;
QComboBox *pageComboBox = new QComboBox;
QObject::connect(pageComboBox, SIGNAL(activated(int)),
stackedWidget, SLOT(setCurrentIndex(int)));
layout->addWidget(pageComboBox);
layout->addWidget(stackedWidget);
// now, create widgets for all of them
for (int i=0;i<xferFuncs.size();i++) {
// take name from node, or create one
std::string name = xferFuncs[i]->name;
if (name == "") {
std::stringstream ss;
ss << "(unnamed xfr fct #" << i << ")";
name = ss.str();
}
// add combo box and stacked widget entries
pageComboBox->addItem(tr(name.c_str()));
// create a transfer function editor for this transfer function node
QOSPTransferFunctionEditor *xfEd
= new QOSPTransferFunctionEditor(xferFuncs[i]);
stackedWidget->addWidget(xfEd);
connect(xfEd, SIGNAL(transferFunctionChanged()),
this, SLOT(render()));
}
}
editorWidgetStack->addPage("Transfer Functions",xfEditorsPage);
}
void ModelViewer::createLightManipulator() {
QWidget *lmEditorsPage = new QWidget;
QVBoxLayout *layout = new QVBoxLayout;
lmEditorsPage->setLayout(layout);
QStackedWidget *stackedWidget = new QStackedWidget;
layout->addWidget(stackedWidget);
Ref<sg::PerspectiveCamera> camera = renderWidget->sgRenderer->camera.cast<sg::PerspectiveCamera>();
QLightManipulator *lManipulator = new QLightManipulator(sgRenderer, camera->getUp());
//stackedWidget->addWidget(lManipulator);
layout->addWidget(lManipulator);
editorWidgetStack->addPage("Light Editor", lManipulator);
connect(lManipulator, SIGNAL(lightsChanged()), this, SLOT(render()));
}
void ModelViewer::toggleUpAxis(int axis)
{
std::cout << "#osp:QTV: new upvector is " << renderWidget->getFrame()->upVector << std::endl;
}
void ModelViewer::keyPressEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_Escape: {
QApplication::quit();
} break;
case Qt::Key_C: {
// ------------------------------------------------------------------
// 'C':
// - Shift-C print current camera
// ------------------------------------------------------------------
if (event->modifiers() & Qt::ShiftModifier) {
// shift-f: switch to fly mode
std::cout << "Shift-C: Printing camera" << std::endl;
printCameraAction();
}
} break;
case Qt::Key_F: {
// ------------------------------------------------------------------
// 'F':
// - Shift-F enters fly mode
// - Ctrl-F toggles full-screen
// ------------------------------------------------------------------
if (event->modifiers() & Qt::ShiftModifier) {
// shift-f: switch to fly mode
std::cout << "Shift-F: Entering 'Fly' mode" << std::endl;
renderWidget->setInteractionMode(QAffineSpaceManipulator::FLY);
} else if (event->modifiers() & Qt::ControlModifier) {
// ctrl-f: switch to full-screen
std::cout << "Ctrl-F: Toggling full-screen mode" << std::endl;
setWindowState(windowState() ^ Qt::WindowFullScreen);
if (windowState() & Qt::WindowFullScreen){
toolBar->hide();
editorWidgetDock->hide();
} else {
toolBar->show();
editorWidgetDock->show();
}
}
} break;
case Qt::Key_I: {
// ------------------------------------------------------------------
// 'I':
// - Ctrl-I switches to inspect mode
// ------------------------------------------------------------------
if (event->modifiers() & Qt::ShiftModifier) {
// shift-f: switch to fly mode
std::cout << "Shift-I: Entering 'Inspect' mode" << std::endl;
renderWidget->setInteractionMode(QAffineSpaceManipulator::INSPECT);
}
} break;
case Qt::Key_Q: {
QApplication::quit();
} break;
case Qt::Key_R: {
if (event->modifiers() & Qt::ShiftModifier) {
// shift-f: switch to fly mode
std::cout << "Shift-R: Entering Free-'Rotation' mode (no up-vector)" << std::endl;
renderWidget->setInteractionMode(QAffineSpaceManipulator::FREE_ROTATION);
}
} break;
case Qt::Key_X: {
// ------------------------------------------------------------------
// 'X':
// - Ctrl-X switches to X-up/down for upvector
// ------------------------------------------------------------------
if (event->modifiers() & Qt::ShiftModifier) {
// shift-x: switch to X-up
std::cout << "Shift-X: switching to X-up/down upvector " << std::endl;
renderWidget->toggleUp(0);
}
} break;
// ------------------------------------------------------------------
// 'Y':
// - Ctrl-Y switches to Y-up/down for upvector
// ------------------------------------------------------------------
case Qt::Key_Y: {
if (event->modifiers() & Qt::ShiftModifier) {
// shift-x: switch to X-up
std::cout << "Shift-Y: switching to Y-up/down upvector " << std::endl;
renderWidget->toggleUp(1);
}
} break;
case Qt::Key_Z: {
// ------------------------------------------------------------------
// 'Z':
// - Ctrl-Z switches to Z-up/down for upvector
// ------------------------------------------------------------------
if (event->modifiers() & Qt::ShiftModifier) {
// shift-x: switch to X-up
std::cout << "Shift-Z: switching to Z-up/down upvector " << std::endl;
renderWidget->toggleUp(2);
}
} break;
default:
QMainWindow::keyPressEvent(event);
}
}
ModelViewer::ModelViewer(Ref<sg::Renderer> sgRenderer, bool fullscreen)
: editorWidgetStack(NULL),
transferFunctionEditor(NULL),
lightEditor(NULL),
toolBar(NULL),
sgRenderer(sgRenderer)
{
// resize to default window size
setWindowTitle(tr("OSPRay QT ModelViewer"));
resize(1024,768);
// create GUI elements
toolBar = addToolBar("toolbar");
QAction *printCameraAction = new QAction("Print Camera", this);
connect(printCameraAction, SIGNAL(triggered()), this, SLOT(printCameraAction()));
toolBar->addAction(printCameraAction);
QAction *screenShotAction = new QAction("Screenshot", this);
connect(screenShotAction, SIGNAL(triggered()), this, SLOT(screenShotAction()));
toolBar->addAction(screenShotAction);
renderWidget = new OSPRayRenderWidget(sgRenderer);
///renderWidget = new CheckeredSphereRotationEditor();
// renderWidget = new QCoordAxisFrameEditor(QAffineSpaceManipulator::FLY);
// renderWidget = new QCoordAxisFrameEditor(QAffineSpaceManipulator::INSPECT);
// renderWidget = new QCoordAxisFrameEditor(QAffineSpaceManipulator::FREE_ROTATION);
// renderWidget->setMoveSpeed(1.f);
connect(renderWidget,SIGNAL(affineSpaceChanged(QAffineSpaceManipulator *)),
this,SLOT(cameraChanged()));
setCentralWidget(renderWidget);
setFocusPolicy(Qt::StrongFocus);
createTimeSlider();
createEditorWidgetStack();
createLightManipulator();
createTransferFunctionEditor();
if (fullscreen) {
setWindowState(windowState() & Qt::WindowFullScreen);
toolBar->hide();
editorWidgetDock->hide();
}
}
void ModelViewer::setWorld(Ref<sg::World> world)
{
renderWidget->setWorld(world);
}
void ModelViewer::render() {
sgRenderer->resetAccumulation();
if (renderWidget) renderWidget->updateGL();
}
// this is a incoming signal that the render widget changed the camera
void ModelViewer::cameraChanged()
{
renderWidget->updateOSPRayCamera();
}
//! print the camera on the command line (triggered by toolbar/menu).
void ModelViewer::printCameraAction()
{
Ref<sg::PerspectiveCamera> camera = renderWidget->sgRenderer->camera.cast<sg::PerspectiveCamera>();
vec3f from = camera->getFrom();
vec3f up = camera->getUp();
vec3f at = camera->getAt();
std::cout << "#osp:qtv: camera is"
<< " -vp " << from.x << " " << from.y << " " << from.z
<< " -vi " << at.x << " " << at.y << " " << at.z
<< " -vu " << up.x << " " << up.y << " " << up.z
<< std::endl;
}
//! take a screen shot
void ModelViewer::screenShotAction()
{
vec2i size = sgRenderer->frameBuffer->getSize();
unsigned char *fbMem = sgRenderer->frameBuffer->map();
glDrawPixels(size.x, size.y, GL_RGBA, GL_UNSIGNED_BYTE, fbMem);
sgRenderer->frameBuffer->unmap(fbMem);
QImage fb = QImage(fbMem,size.x,size.y,QImage::Format_RGB32).rgbSwapped().mirrored();
const std::string fileName = "/tmp/ospQTV.screenshot.png";
fb.save(fileName.c_str());
std::cout << "screen shot saved in " << fileName << std::endl;
}
void ModelViewer::lightChanged()
{
}
}
}
|
// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "ModelViewer.h"
#include "widgets/affineSpaceManipulator/HelperGeometry.h"
#include "sg/SceneGraph.h"
#include "sg/Renderer.h"
namespace ospray {
namespace viewer {
using std::cout;
using std::endl;
struct FPSCounter {
double fps;
double smooth_nom;
double smooth_den;
double frameStartTime;
FPSCounter()
{
smooth_nom = 0.;
smooth_den = 0.;
frameStartTime = 0.;
}
void startRender() { frameStartTime = ospray::getSysTime(); }
void doneRender() {
double seconds = ospray::getSysTime() - frameStartTime;
fps = 1./seconds;
smooth_nom = smooth_nom * 0.8 + seconds;
smooth_den = smooth_den * 0.8 + 1.;
}
double getSmoothFPS() const { return smooth_den / smooth_nom; }
double getFPS() const { return fps; }
};
FPSCounter fps;
OSPRayRenderWidget::OSPRayRenderWidget(Ref<sg::Renderer> renderer)
: QAffineSpaceManipulator(QAffineSpaceManipulator::INSPECT),
sgRenderer(renderer)
{
if (renderer->world) {
box3f worldBounds = renderer->world->getBounds();
if (!worldBounds.empty()) {
float moveSpeed = .25*length(worldBounds.size());
QAffineSpaceManipulator::setMoveSpeed(moveSpeed);
}
}
Ref<sg::PerspectiveCamera> camera = renderer->camera.cast<sg::PerspectiveCamera>();
if (camera) {
frame->sourcePoint = camera->getFrom();
frame->targetPoint = camera->getAt();
frame->upVector = camera->getUp();
frame->orientation.vz = normalize(camera->getUp());
frame->orientation.vy = normalize(camera->getAt() - camera->getFrom());
frame->orientation.vx = normalize(cross(frame->orientation.vy,frame->orientation.vz));
}
}
void OSPRayRenderWidget::setWorld(Ref<sg::World> world)
{
assert(sgRenderer);
sgRenderer->setWorld(world);
cout << "#ospQTV: world set, found "
<< sgRenderer->allNodes.size() << " nodes" << endl;
}
//! the QT callback that tells us that we have to redraw
void OSPRayRenderWidget::redraw()
{
if (!sgRenderer) return;
if (!sgRenderer->frameBuffer) return;
if (!sgRenderer->camera) return;
if (showFPS) {
static int frameID = 0;
if (frameID > 0) {
fps.doneRender();
printf("fps: %7.3f (smoothed: %7.3f)\n",fps.getFPS(),fps.getSmoothFPS());
}
fps.startRender();
++frameID;
}
sgRenderer->renderFrame();
vec2i size = sgRenderer->frameBuffer->getSize();
unsigned char *fbMem = sgRenderer->frameBuffer->map();
glDrawPixels(size.x, size.y, GL_RGBA, GL_UNSIGNED_BYTE, fbMem);
sgRenderer->frameBuffer->unmap(fbMem);
// accumulate, but only up to 32 frames
if (sgRenderer->accumID < 32)
update();
}
//! the QT callback that tells us that the image got resize
void OSPRayRenderWidget::resize(int width, int height)
{
sgRenderer->frameBuffer = new sg::FrameBuffer(vec2i(width,height));
sgRenderer->resetAccumulation();
Ref<sg::PerspectiveCamera> camera = sgRenderer->camera.cast<sg::PerspectiveCamera>();
camera->setAspect(width/float(height));
camera->commit();
}
//! update the ospray camera (ospCamera) from the widget camera (this->camera)
void OSPRayRenderWidget::updateOSPRayCamera()
{
if (!sgRenderer) return;
if (!sgRenderer->camera) return;
sgRenderer->resetAccumulation();
Ref<sg::PerspectiveCamera> camera = sgRenderer->camera.cast<sg::PerspectiveCamera>();
assert(camera);
const vec3f from = frame->sourcePoint;
const vec3f at = frame->targetPoint;
vec2i size = sgRenderer->frameBuffer->getSize();
camera->setFrom(from);
camera->setAt(at);
camera->setUp(frame->orientation.vz);
camera->setAspect(size.x/float(size.y));
camera->commit();
}
//! create the lower-side time step slider (for models that have
//! time steps; won't do anything for models that don't)
void ModelViewer::createTimeSlider()
{
}
//! create the widet on the side that'll host all the editing widgets
void ModelViewer::createEditorWidgetStack()
{
editorWidgetStack = new EditorWidgetStack;
editorWidgetDock = new QDockWidget(this);
editorWidgetDock->setWindowTitle("Editors");
editorWidgetDock->setWidget(editorWidgetStack);
editorWidgetDock->setFeatures(0);
addDockWidget(Qt::RightDockWidgetArea,editorWidgetDock);
}
void ModelViewer::createTransferFunctionEditor()
{
QWidget *xfEditorsPage = NULL;
// make a list of all transfer function nodes in the scene graph
std::vector<Ref<sg::TransferFunction> > xferFuncs;
for (int i=0;i<sgRenderer->uniqueNodes.size();i++) {
sg::TransferFunction *xf = dynamic_cast<sg::TransferFunction *>
(sgRenderer->uniqueNodes.object[i]->node.ptr);
if (xf) xferFuncs.push_back(xf);
}
std::cout << "#osp:qtv: found " << xferFuncs.size()
<< " transfer function nodes" << std::endl;
if (xferFuncs.empty()) {
xfEditorsPage = new QLabel("(no xfer fcts found)");
} else {
// -------------------------------------------------------
// found some transfer functions - create a stacked widget
// with an editor for each
// -------------------------------------------------------
xfEditorsPage = new QWidget;
QVBoxLayout *layout = new QVBoxLayout;
xfEditorsPage->setLayout(layout);
QStackedWidget *stackedWidget = new QStackedWidget;
QComboBox *pageComboBox = new QComboBox;
QObject::connect(pageComboBox, SIGNAL(activated(int)),
stackedWidget, SLOT(setCurrentIndex(int)));
layout->addWidget(pageComboBox);
layout->addWidget(stackedWidget);
// now, create widgets for all of them
for (int i=0;i<xferFuncs.size();i++) {
// take name from node, or create one
std::string name = xferFuncs[i]->name;
if (name == "") {
std::stringstream ss;
ss << "(unnamed xfr fct #" << i << ")";
name = ss.str();
}
// add combo box and stacked widget entries
pageComboBox->addItem(tr(name.c_str()));
// create a transfer function editor for this transfer function node
QOSPTransferFunctionEditor *xfEd
= new QOSPTransferFunctionEditor(xferFuncs[i]);
stackedWidget->addWidget(xfEd);
connect(xfEd, SIGNAL(transferFunctionChanged()),
this, SLOT(render()));
}
}
editorWidgetStack->addPage("Transfer Functions",xfEditorsPage);
}
void ModelViewer::createLightManipulator() {
QWidget *lmEditorsPage = new QWidget;
QVBoxLayout *layout = new QVBoxLayout;
lmEditorsPage->setLayout(layout);
QStackedWidget *stackedWidget = new QStackedWidget;
layout->addWidget(stackedWidget);
Ref<sg::PerspectiveCamera> camera = renderWidget->sgRenderer->camera.cast<sg::PerspectiveCamera>();
QLightManipulator *lManipulator = new QLightManipulator(sgRenderer, camera->getUp());
//stackedWidget->addWidget(lManipulator);
layout->addWidget(lManipulator);
editorWidgetStack->addPage("Light Editor", lManipulator);
connect(lManipulator, SIGNAL(lightsChanged()), this, SLOT(render()));
}
void ModelViewer::toggleUpAxis(int axis)
{
std::cout << "#osp:QTV: new upvector is " << renderWidget->getFrame()->upVector << std::endl;
}
void ModelViewer::keyPressEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_Escape: {
QApplication::quit();
} break;
case Qt::Key_C: {
// ------------------------------------------------------------------
// 'C':
// - Shift-C print current camera
// ------------------------------------------------------------------
if (event->modifiers() & Qt::ShiftModifier) {
// shift-f: switch to fly mode
std::cout << "Shift-C: Printing camera" << std::endl;
printCameraAction();
}
} break;
case Qt::Key_F: {
// ------------------------------------------------------------------
// 'F':
// - Shift-F enters fly mode
// - Ctrl-F toggles full-screen
// ------------------------------------------------------------------
if (event->modifiers() & Qt::ShiftModifier) {
// shift-f: switch to fly mode
std::cout << "Shift-F: Entering 'Fly' mode" << std::endl;
renderWidget->setInteractionMode(QAffineSpaceManipulator::FLY);
} else if (event->modifiers() & Qt::ControlModifier) {
// ctrl-f: switch to full-screen
std::cout << "Ctrl-F: Toggling full-screen mode" << std::endl;
setWindowState(windowState() ^ Qt::WindowFullScreen);
if (windowState() & Qt::WindowFullScreen){
toolBar->hide();
editorWidgetDock->hide();
} else {
toolBar->show();
editorWidgetDock->show();
}
}
} break;
case Qt::Key_I: {
// ------------------------------------------------------------------
// 'I':
// - Ctrl-I switches to inspect mode
// ------------------------------------------------------------------
if (event->modifiers() & Qt::ShiftModifier) {
// shift-f: switch to fly mode
std::cout << "Shift-I: Entering 'Inspect' mode" << std::endl;
renderWidget->setInteractionMode(QAffineSpaceManipulator::INSPECT);
}
} break;
case Qt::Key_Q: {
QApplication::quit();
} break;
case Qt::Key_R: {
if (event->modifiers() & Qt::ShiftModifier) {
// shift-f: switch to fly mode
std::cout << "Shift-R: Entering Free-'Rotation' mode (no up-vector)" << std::endl;
renderWidget->setInteractionMode(QAffineSpaceManipulator::FREE_ROTATION);
}
} break;
case Qt::Key_X: {
// ------------------------------------------------------------------
// 'X':
// - Ctrl-X switches to X-up/down for upvector
// ------------------------------------------------------------------
if (event->modifiers() & Qt::ShiftModifier) {
// shift-x: switch to X-up
std::cout << "Shift-X: switching to X-up/down upvector " << std::endl;
renderWidget->toggleUp(0);
}
} break;
// ------------------------------------------------------------------
// 'Y':
// - Ctrl-Y switches to Y-up/down for upvector
// ------------------------------------------------------------------
case Qt::Key_Y: {
if (event->modifiers() & Qt::ShiftModifier) {
// shift-x: switch to X-up
std::cout << "Shift-Y: switching to Y-up/down upvector " << std::endl;
renderWidget->toggleUp(1);
}
} break;
case Qt::Key_Z: {
// ------------------------------------------------------------------
// 'Z':
// - Ctrl-Z switches to Z-up/down for upvector
// ------------------------------------------------------------------
if (event->modifiers() & Qt::ShiftModifier) {
// shift-x: switch to X-up
std::cout << "Shift-Z: switching to Z-up/down upvector " << std::endl;
renderWidget->toggleUp(2);
}
} break;
default:
QMainWindow::keyPressEvent(event);
}
}
ModelViewer::ModelViewer(Ref<sg::Renderer> sgRenderer, bool fullscreen)
: editorWidgetStack(NULL),
transferFunctionEditor(NULL),
lightEditor(NULL),
toolBar(NULL),
sgRenderer(sgRenderer)
{
// resize to default window size
setWindowTitle(tr("OSPRay QT ModelViewer"));
resize(1024,768);
// create GUI elements
toolBar = addToolBar("toolbar");
QAction *printCameraAction = new QAction("Print Camera", this);
connect(printCameraAction, SIGNAL(triggered()), this, SLOT(printCameraAction()));
toolBar->addAction(printCameraAction);
QAction *screenShotAction = new QAction("Screenshot", this);
connect(screenShotAction, SIGNAL(triggered()), this, SLOT(screenShotAction()));
toolBar->addAction(screenShotAction);
renderWidget = new OSPRayRenderWidget(sgRenderer);
///renderWidget = new CheckeredSphereRotationEditor();
// renderWidget = new QCoordAxisFrameEditor(QAffineSpaceManipulator::FLY);
// renderWidget = new QCoordAxisFrameEditor(QAffineSpaceManipulator::INSPECT);
// renderWidget = new QCoordAxisFrameEditor(QAffineSpaceManipulator::FREE_ROTATION);
// renderWidget->setMoveSpeed(1.f);
connect(renderWidget,SIGNAL(affineSpaceChanged(QAffineSpaceManipulator *)),
this,SLOT(cameraChanged()));
setCentralWidget(renderWidget);
setFocusPolicy(Qt::StrongFocus);
createTimeSlider();
createEditorWidgetStack();
createLightManipulator();
createTransferFunctionEditor();
if (fullscreen) {
setWindowState(windowState() | Qt::WindowFullScreen);
toolBar->hide();
editorWidgetDock->hide();
}
}
void ModelViewer::setWorld(Ref<sg::World> world)
{
renderWidget->setWorld(world);
}
void ModelViewer::render() {
sgRenderer->resetAccumulation();
if (renderWidget) renderWidget->updateGL();
}
// this is a incoming signal that the render widget changed the camera
void ModelViewer::cameraChanged()
{
renderWidget->updateOSPRayCamera();
}
//! print the camera on the command line (triggered by toolbar/menu).
void ModelViewer::printCameraAction()
{
Ref<sg::PerspectiveCamera> camera = renderWidget->sgRenderer->camera.cast<sg::PerspectiveCamera>();
vec3f from = camera->getFrom();
vec3f up = camera->getUp();
vec3f at = camera->getAt();
std::cout << "#osp:qtv: camera is"
<< " -vp " << from.x << " " << from.y << " " << from.z
<< " -vi " << at.x << " " << at.y << " " << at.z
<< " -vu " << up.x << " " << up.y << " " << up.z
<< std::endl;
}
//! take a screen shot
void ModelViewer::screenShotAction()
{
vec2i size = sgRenderer->frameBuffer->getSize();
unsigned char *fbMem = sgRenderer->frameBuffer->map();
glDrawPixels(size.x, size.y, GL_RGBA, GL_UNSIGNED_BYTE, fbMem);
sgRenderer->frameBuffer->unmap(fbMem);
QImage fb = QImage(fbMem,size.x,size.y,QImage::Format_RGB32).rgbSwapped().mirrored();
const std::string fileName = "/tmp/ospQTV.screenshot.png";
fb.save(fileName.c_str());
std::cout << "screen shot saved in " << fileName << std::endl;
}
void ModelViewer::lightChanged()
{
}
}
}
|
Fix initial fullscreen in qtViewer
|
Fix initial fullscreen in qtViewer
|
C++
|
apache-2.0
|
wilsonCernWq/ospray,wilsonCernWq/ospray,favreau/OSPRay,ospray/OSPRay,favreau/OSPRay,favreau/OSPRay,ospray/OSPRay,wilsonCernWq/ospray,MengjiaoH/ospray,Twinklebear/OSPRay,Twinklebear/OSPRay,favreau/OSPRay,MengjiaoH/ospray,ospray/OSPRay,Twinklebear/OSPRay,MengjiaoH/ospray,Twinklebear/OSPRay,MengjiaoH/ospray,MengjiaoH/ospray,ospray/OSPRay
|
6325406afa60d5d98a2c4e349fb92e994b33fbab
|
src/backend/MemoryManager.cpp
|
src/backend/MemoryManager.cpp
|
/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>
#include "MemoryManager.hpp"
#include "dispatch.hpp"
#include "err_common.hpp"
#include "util.hpp"
namespace common
{
MemoryManager::MemoryManager(int num_devices, unsigned MAX_BUFFERS, bool debug):
mem_step_size(1024),
max_buffers(MAX_BUFFERS),
memory(num_devices),
debug_mode(debug)
{
lock_guard_t lock(this->memory_mutex);
for (int n = 0; n < num_devices; n++) {
// Calling getMaxMemorySize() here calls the virtual function that returns 0
// Call it from outside the constructor.
memory[n].max_bytes = ONE_GB;
memory[n].total_bytes = 0;
memory[n].total_buffers = 0;
memory[n].lock_bytes = 0;
memory[n].lock_buffers = 0;
}
// Check for environment variables
std::string env_var;
// Debug mode
env_var = getEnvVar("AF_MEM_DEBUG");
if (!env_var.empty()) {
this->debug_mode = env_var[0] != '0';
}
if (this->debug_mode) mem_step_size = 1;
// Max Buffer count
env_var = getEnvVar("AF_MAX_BUFFERS");
if (!env_var.empty()) {
this->max_buffers = std::max(1, std::stoi(env_var));
}
}
void MemoryManager::setMaxMemorySize()
{
for (unsigned n = 0; n < memory.size(); n++) {
// Calls garbage collection when:
// total_bytes > memsize * 0.75 when memsize < 4GB
// total_bytes > memsize - 1 GB when memsize >= 4GB
// If memsize returned 0, then use 1GB
size_t memsize = this->getMaxMemorySize(n);
memory[n].max_bytes = memsize == 0 ? ONE_GB : std::max(memsize * 0.75, (double)(memsize - ONE_GB));
}
}
void MemoryManager::garbageCollect()
{
if (this->debug_mode) return;
lock_guard_t lock(this->memory_mutex);
memory_info& current = this->getCurrentMemoryInfo();
// Return if all buffers are locked
if (current.total_buffers == current.lock_buffers) return;
for (auto &kv : current.free_map) {
size_t num_ptrs = kv.second.size();
//Free memory by popping the last element
for (int n = num_ptrs-1; n >= 0; n--) {
this->nativeFree(kv.second[n]);
current.total_bytes -= kv.first;
current.total_buffers--;
kv.second.pop_back();
}
}
current.free_map.clear();
}
void MemoryManager::unlock(void *ptr, bool user_unlock)
{
lock_guard_t lock(this->memory_mutex);
memory_info& current = this->getCurrentMemoryInfo();
locked_iter iter = current.locked_map.find((void *)ptr);
// Pointer not found in locked map
if (iter == current.locked_map.end()) {
// Probably came from user, just free it
this->nativeFree(ptr);
return;
}
if (user_unlock) {
(iter->second).user_lock = false;
} else {
(iter->second).manager_lock = false;
}
// Return early if either one is locked
if ((iter->second).user_lock || (iter->second).manager_lock) return;
size_t bytes = iter->second.bytes;
current.lock_bytes -= iter->second.bytes;
current.lock_buffers--;
current.locked_map.erase(iter);
if (this->debug_mode) {
// Just free memory in debug mode
if ((iter->second).bytes > 0) {
this->nativeFree(iter->first);
current.total_buffers--;
current.total_bytes -= iter->second.bytes;
}
} else {
// In regular mode, move buffer to free map
free_iter fiter = current.free_map.find(bytes);
if (fiter != current.free_map.end()) {
// If found, push back
fiter->second.push_back(ptr);
} else {
// If not found, create new vector for this size
std::vector<void *> ptrs;
ptrs.push_back(ptr);
current.free_map[bytes] = ptrs;
}
}
}
void *MemoryManager::alloc(const size_t bytes, bool user_lock)
{
lock_guard_t lock(this->memory_mutex);
void *ptr = NULL;
size_t alloc_bytes = this->debug_mode ? bytes : (divup(bytes, mem_step_size) * mem_step_size);
if (bytes > 0) {
memory_info& current = this->getCurrentMemoryInfo();
// There is no memory cache in debug mode
if (!this->debug_mode) {
// FIXME: Add better checks for garbage collection
// Perhaps look at total memory available as a metric
if (current.lock_bytes >= current.max_bytes ||
current.total_buffers >= this->max_buffers) {
this->garbageCollect();
}
free_iter iter = current.free_map.find(alloc_bytes);
if (iter != current.free_map.end() && !iter->second.empty()) {
ptr = iter->second.back();
iter->second.pop_back();
}
}
// Only comes here if buffer size not found or in debug mode
if (ptr == NULL) {
// Perform garbage collection if memory can not be allocated
try {
ptr = this->nativeAlloc(alloc_bytes);
} catch (AfError &ex) {
// If out of memory, run garbage collect and try again
if (ex.getError() != AF_ERR_NO_MEM) throw;
this->garbageCollect();
ptr = this->nativeAlloc(alloc_bytes);
}
// Increment these two only when it succeeds to come here.
current.total_bytes += alloc_bytes;
current.total_buffers += 1;
}
locked_info info = {true, user_lock, alloc_bytes};
current.locked_map[ptr] = info;
current.lock_bytes += alloc_bytes;
current.lock_buffers++;
}
return ptr;
}
void MemoryManager::userLock(const void *ptr)
{
memory_info& current = this->getCurrentMemoryInfo();
lock_guard_t lock(this->memory_mutex);
locked_iter iter = current.locked_map.find(const_cast<void *>(ptr));
if (iter != current.locked_map.end()) {
iter->second.user_lock = true;
} else {
locked_info info = {false,
true,
100}; //This number is not relevant
current.locked_map[(void *)ptr] = info;
}
}
void MemoryManager::userUnlock(const void *ptr)
{
this->unlock(const_cast<void *>(ptr), true);
}
size_t MemoryManager::getMemStepSize()
{
lock_guard_t lock(this->memory_mutex);
return this->mem_step_size;
}
void MemoryManager::setMemStepSize(size_t new_step_size)
{
lock_guard_t lock(this->memory_mutex);
this->mem_step_size = new_step_size;
}
size_t MemoryManager::getMaxBytes()
{
lock_guard_t lock(this->memory_mutex);
return this->getCurrentMemoryInfo().max_bytes;
}
void MemoryManager::printInfo(const char *msg, const int device)
{
lock_guard_t lock(this->memory_mutex);
memory_info& current = this->getCurrentMemoryInfo();
std::cout << msg << std::endl;
static const std::string head("| POINTER | SIZE | AF LOCK | USER LOCK |");
static const std::string line(head.size(), '-');
std::cout << line << std::endl << head << std::endl << line << std::endl;
for(auto& kv : current.locked_map) {
std::string status_mngr("Yes");
std::string status_user("Unknown");
if(kv.second.user_lock) status_user = "Yes";
else status_user = " No";
std::string unit = "KB";
double size = (double)(kv.second.bytes) / 1024;
if(size >= 1024) {
size = size / 1024;
unit = "MB";
}
std::cout << " | " << std::right << std::setw(14) << kv.first << " "
<< " | " << std::setw(7) << std::setprecision(4) << size << " " << unit
<< " | " << std::setw(9) << status_mngr
<< " | " << std::setw(9) << status_user
<< " |" << std::endl;
}
for(auto &kv : current.free_map) {
std::string status_mngr("No");
std::string status_user("No");
std::string unit = "KB";
double size = (double)(kv.first) / 1024;
if(size >= 1024) {
size = size / 1024;
unit = "MB";
}
for (auto &ptr : kv.second) {
std::cout << " | " << std::right << std::setw(14) << ptr << " "
<< " | " << std::setw(7) << std::setprecision(4) << size << " " << unit
<< " | " << std::setw(9) << status_mngr
<< " | " << std::setw(9) << status_user
<< " |" << std::endl;
}
}
std::cout << line << std::endl;
}
void MemoryManager::bufferInfo(size_t *alloc_bytes, size_t *alloc_buffers,
size_t *lock_bytes, size_t *lock_buffers)
{
lock_guard_t lock(this->memory_mutex);
memory_info current = this->getCurrentMemoryInfo();
if (alloc_bytes ) *alloc_bytes = current.total_bytes;
if (alloc_buffers ) *alloc_buffers = current.total_buffers;
if (lock_bytes ) *lock_bytes = current.lock_bytes;
if (lock_buffers ) *lock_buffers = current.lock_buffers;
}
unsigned MemoryManager::getMaxBuffers()
{
return this->max_buffers;
}
}
|
/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>
#include "MemoryManager.hpp"
#include "dispatch.hpp"
#include "err_common.hpp"
#include "util.hpp"
namespace common
{
MemoryManager::MemoryManager(int num_devices, unsigned MAX_BUFFERS, bool debug):
mem_step_size(1024),
max_buffers(MAX_BUFFERS),
memory(num_devices),
debug_mode(debug)
{
lock_guard_t lock(this->memory_mutex);
for (int n = 0; n < num_devices; n++) {
// Calling getMaxMemorySize() here calls the virtual function that returns 0
// Call it from outside the constructor.
memory[n].max_bytes = ONE_GB;
memory[n].total_bytes = 0;
memory[n].total_buffers = 0;
memory[n].lock_bytes = 0;
memory[n].lock_buffers = 0;
}
// Check for environment variables
std::string env_var;
// Debug mode
env_var = getEnvVar("AF_MEM_DEBUG");
if (!env_var.empty()) {
this->debug_mode = env_var[0] != '0';
}
if (this->debug_mode) mem_step_size = 1;
// Max Buffer count
env_var = getEnvVar("AF_MAX_BUFFERS");
if (!env_var.empty()) {
this->max_buffers = std::max(1, std::stoi(env_var));
}
}
void MemoryManager::setMaxMemorySize()
{
for (unsigned n = 0; n < memory.size(); n++) {
// Calls garbage collection when:
// total_bytes > memsize * 0.75 when memsize < 4GB
// total_bytes > memsize - 1 GB when memsize >= 4GB
// If memsize returned 0, then use 1GB
size_t memsize = this->getMaxMemorySize(n);
memory[n].max_bytes = memsize == 0 ? ONE_GB : std::max(memsize * 0.75, (double)(memsize - ONE_GB));
}
}
void MemoryManager::garbageCollect()
{
if (this->debug_mode) return;
lock_guard_t lock(this->memory_mutex);
memory_info& current = this->getCurrentMemoryInfo();
// Return if all buffers are locked
if (current.total_buffers == current.lock_buffers) return;
for (auto &kv : current.free_map) {
size_t num_ptrs = kv.second.size();
//Free memory by popping the last element
for (int n = num_ptrs-1; n >= 0; n--) {
this->nativeFree(kv.second[n]);
current.total_bytes -= kv.first;
current.total_buffers--;
kv.second.pop_back();
}
}
current.free_map.clear();
}
void MemoryManager::unlock(void *ptr, bool user_unlock)
{
// Shortcut for empty arrays
if (!ptr) return;
lock_guard_t lock(this->memory_mutex);
memory_info& current = this->getCurrentMemoryInfo();
locked_iter iter = current.locked_map.find((void *)ptr);
// Pointer not found in locked map
if (iter == current.locked_map.end()) {
// Probably came from user, just free it
this->nativeFree(ptr);
return;
}
if (user_unlock) {
(iter->second).user_lock = false;
} else {
(iter->second).manager_lock = false;
}
// Return early if either one is locked
if ((iter->second).user_lock || (iter->second).manager_lock) return;
size_t bytes = iter->second.bytes;
current.lock_bytes -= iter->second.bytes;
current.lock_buffers--;
current.locked_map.erase(iter);
if (this->debug_mode) {
// Just free memory in debug mode
if ((iter->second).bytes > 0) {
this->nativeFree(iter->first);
current.total_buffers--;
current.total_bytes -= iter->second.bytes;
}
} else {
// In regular mode, move buffer to free map
free_iter fiter = current.free_map.find(bytes);
if (fiter != current.free_map.end()) {
// If found, push back
fiter->second.push_back(ptr);
} else {
// If not found, create new vector for this size
std::vector<void *> ptrs;
ptrs.push_back(ptr);
current.free_map[bytes] = ptrs;
}
}
}
void *MemoryManager::alloc(const size_t bytes, bool user_lock)
{
lock_guard_t lock(this->memory_mutex);
void *ptr = NULL;
size_t alloc_bytes = this->debug_mode ? bytes : (divup(bytes, mem_step_size) * mem_step_size);
if (bytes > 0) {
memory_info& current = this->getCurrentMemoryInfo();
// There is no memory cache in debug mode
if (!this->debug_mode) {
// FIXME: Add better checks for garbage collection
// Perhaps look at total memory available as a metric
if (current.lock_bytes >= current.max_bytes ||
current.total_buffers >= this->max_buffers) {
this->garbageCollect();
}
free_iter iter = current.free_map.find(alloc_bytes);
if (iter != current.free_map.end() && !iter->second.empty()) {
ptr = iter->second.back();
iter->second.pop_back();
}
}
// Only comes here if buffer size not found or in debug mode
if (ptr == NULL) {
// Perform garbage collection if memory can not be allocated
try {
ptr = this->nativeAlloc(alloc_bytes);
} catch (AfError &ex) {
// If out of memory, run garbage collect and try again
if (ex.getError() != AF_ERR_NO_MEM) throw;
this->garbageCollect();
ptr = this->nativeAlloc(alloc_bytes);
}
// Increment these two only when it succeeds to come here.
current.total_bytes += alloc_bytes;
current.total_buffers += 1;
}
locked_info info = {true, user_lock, alloc_bytes};
current.locked_map[ptr] = info;
current.lock_bytes += alloc_bytes;
current.lock_buffers++;
}
return ptr;
}
void MemoryManager::userLock(const void *ptr)
{
memory_info& current = this->getCurrentMemoryInfo();
lock_guard_t lock(this->memory_mutex);
locked_iter iter = current.locked_map.find(const_cast<void *>(ptr));
if (iter != current.locked_map.end()) {
iter->second.user_lock = true;
} else {
locked_info info = {false,
true,
100}; //This number is not relevant
current.locked_map[(void *)ptr] = info;
}
}
void MemoryManager::userUnlock(const void *ptr)
{
this->unlock(const_cast<void *>(ptr), true);
}
size_t MemoryManager::getMemStepSize()
{
lock_guard_t lock(this->memory_mutex);
return this->mem_step_size;
}
void MemoryManager::setMemStepSize(size_t new_step_size)
{
lock_guard_t lock(this->memory_mutex);
this->mem_step_size = new_step_size;
}
size_t MemoryManager::getMaxBytes()
{
lock_guard_t lock(this->memory_mutex);
return this->getCurrentMemoryInfo().max_bytes;
}
void MemoryManager::printInfo(const char *msg, const int device)
{
lock_guard_t lock(this->memory_mutex);
memory_info& current = this->getCurrentMemoryInfo();
std::cout << msg << std::endl;
static const std::string head("| POINTER | SIZE | AF LOCK | USER LOCK |");
static const std::string line(head.size(), '-');
std::cout << line << std::endl << head << std::endl << line << std::endl;
for(auto& kv : current.locked_map) {
std::string status_mngr("Yes");
std::string status_user("Unknown");
if(kv.second.user_lock) status_user = "Yes";
else status_user = " No";
std::string unit = "KB";
double size = (double)(kv.second.bytes) / 1024;
if(size >= 1024) {
size = size / 1024;
unit = "MB";
}
std::cout << " | " << std::right << std::setw(14) << kv.first << " "
<< " | " << std::setw(7) << std::setprecision(4) << size << " " << unit
<< " | " << std::setw(9) << status_mngr
<< " | " << std::setw(9) << status_user
<< " |" << std::endl;
}
for(auto &kv : current.free_map) {
std::string status_mngr("No");
std::string status_user("No");
std::string unit = "KB";
double size = (double)(kv.first) / 1024;
if(size >= 1024) {
size = size / 1024;
unit = "MB";
}
for (auto &ptr : kv.second) {
std::cout << " | " << std::right << std::setw(14) << ptr << " "
<< " | " << std::setw(7) << std::setprecision(4) << size << " " << unit
<< " | " << std::setw(9) << status_mngr
<< " | " << std::setw(9) << status_user
<< " |" << std::endl;
}
}
std::cout << line << std::endl;
}
void MemoryManager::bufferInfo(size_t *alloc_bytes, size_t *alloc_buffers,
size_t *lock_bytes, size_t *lock_buffers)
{
lock_guard_t lock(this->memory_mutex);
memory_info current = this->getCurrentMemoryInfo();
if (alloc_bytes ) *alloc_bytes = current.total_bytes;
if (alloc_buffers ) *alloc_buffers = current.total_buffers;
if (lock_bytes ) *lock_bytes = current.lock_bytes;
if (lock_buffers ) *lock_buffers = current.lock_buffers;
}
unsigned MemoryManager::getMaxBuffers()
{
return this->max_buffers;
}
}
|
Exit early when destructor is called on empty arrays.
|
Exit early when destructor is called on empty arrays.
This should speed things up when a lot of buffers are
present in the MemoryManager.
|
C++
|
bsd-3-clause
|
marbre/arrayfire,bkloppenborg/arrayfire,arrayfire/arrayfire,arrayfire/arrayfire,shehzan10/arrayfire,shehzan10/arrayfire,munnybearz/arrayfire,marbre/arrayfire,shehzan10/arrayfire,merlin-ext/arrayfire,victorv/arrayfire,umar456/arrayfire,victorv/arrayfire,marbre/arrayfire,ghisvail/arrayfire,arrayfire/arrayfire,ghisvail/arrayfire,munnybearz/arrayfire,ghisvail/arrayfire,merlin-ext/arrayfire,arrayfire/arrayfire,bkloppenborg/arrayfire,9prady9/arrayfire,bkloppenborg/arrayfire,umar456/arrayfire,munnybearz/arrayfire,umar456/arrayfire,shehzan10/arrayfire,bkloppenborg/arrayfire,9prady9/arrayfire,victorv/arrayfire,merlin-ext/arrayfire,umar456/arrayfire,victorv/arrayfire,9prady9/arrayfire,merlin-ext/arrayfire,marbre/arrayfire,ghisvail/arrayfire,9prady9/arrayfire
|
f21b8c360e66527911258828a86c280c842202f4
|
test.cpp
|
test.cpp
|
#include <string>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstream>
#include "json11.hpp"
#include <cassert>
#include <list>
#include <set>
#include <unordered_map>
using namespace json11;
using std::string;
// Check that Json has the properties we want.
#include <type_traits>
#define CHECK_TRAIT(x) static_assert(std::x::value, #x)
CHECK_TRAIT(is_nothrow_constructible<Json>);
CHECK_TRAIT(is_nothrow_default_constructible<Json>);
CHECK_TRAIT(is_copy_constructible<Json>);
CHECK_TRAIT(is_nothrow_move_constructible<Json>);
CHECK_TRAIT(is_copy_assignable<Json>);
CHECK_TRAIT(is_nothrow_move_assignable<Json>);
CHECK_TRAIT(is_nothrow_destructible<Json>);
void parse_from_stdin() {
string buf;
string line;
while (std::getline(std::cin, line)) {
buf += line + "\n";
}
string err;
auto json = Json::parse(buf, err);
if (!err.empty()) {
printf("Failed: %s\n", err.c_str());
} else {
printf("Result: %s\n", json.dump().c_str());
}
}
int main(int argc, char **argv) {
if (argc == 2 && argv[1] == string("--stdin")) {
parse_from_stdin();
return 0;
}
const string simple_test =
R"({"k1":"v1", "k2":42, "k3":["a",123,true,false,null]})";
string err;
auto json = Json::parse(simple_test, err);
std::cout << "k1: " << json["k1"].string_value() << "\n";
std::cout << "k3: " << json["k3"].dump() << "\n";
for (auto &k : json["k3"].array_items()) {
std::cout << " - " << k.dump() << "\n";
}
const string comment_test = R"({
// comment /* with nested comment */
"a": 1,
// comment
// continued
"b": "text",
/* multi
line
comment */
// and single-line comment
"c": [1, 2, 3]
})";
string err_comment;
auto json_comment = Json::parse(
comment_test, err_comment, /*detect_comments=*/ true);
if (!err_comment.empty()) {
printf("Failed: %s\n", err_comment.c_str());
} else {
printf("Result: %s\n", json_comment.dump().c_str());
}
std::list<int> l1 { 1, 2, 3 };
std::vector<int> l2 { 1, 2, 3 };
std::set<int> l3 { 1, 2, 3 };
assert(Json(l1) == Json(l2));
assert(Json(l2) == Json(l3));
std::map<string, string> m1 { { "k1", "v1" }, { "k2", "v2" } };
std::unordered_map<string, string> m2 { { "k1", "v1" }, { "k2", "v2" } };
assert(Json(m1) == Json(m2));
// Json literals
Json obj = Json::object({
{ "k1", "v1" },
{ "k2", 42.0 },
{ "k3", Json::array({ "a", 123.0, true, false, nullptr }) },
});
std::cout << "obj: " << obj.dump() << "\n";
assert(Json("a").number_value() == 0);
assert(Json("a").string_value() == "a");
assert(Json().number_value() == 0);
assert(obj == json);
assert(Json(42) == Json(42.0));
assert(Json(42) != Json(42.1));
const string unicode_escape_test =
R"([ "blah\ud83d\udca9blah\ud83dblah\udca9blah\u0000blah\u1234" ])";
const char utf8[] = "blah" "\xf0\x9f\x92\xa9" "blah" "\xed\xa0\xbd" "blah"
"\xed\xb2\xa9" "blah" "\0" "blah" "\xe1\x88\xb4";
Json uni = Json::parse(unicode_escape_test, err);
assert(uni[0].string_value().size() == (sizeof utf8) - 1);
assert(std::memcmp(uni[0].string_value().data(), utf8, sizeof utf8) == 0);
// Demonstrates the behavior change in Xcode 7 / Clang 3.7 described
// here: https://llvm.org/bugs/show_bug.cgi?id=23812
Json nested_array = Json::array { Json::array { 1, 2, 3 } };
assert(nested_array.is_array());
assert(nested_array.array_items().size() == 1);
assert(nested_array.array_items()[0].is_array());
assert(nested_array.array_items()[0].array_items().size() == 3);
Json my_json = Json::object {
{ "key1", "value1" },
{ "key2", false },
{ "key3", Json::array { 1, 2, 3 } },
};
std::string json_str = my_json.dump();
printf("%s\n", json_str.c_str());
class Point {
public:
int x;
int y;
Point (int x, int y) : x(x), y(y) {}
Json to_json() const { return Json::array { x, y }; }
};
std::vector<Point> points = { { 1, 2 }, { 10, 20 }, { 100, 200 } };
std::string points_json = Json(points).dump();
printf("%s\n", points_json.c_str());
}
|
#include <string>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstream>
#include "json11.hpp"
#include <cassert>
#include <list>
#include <set>
#include <unordered_map>
using namespace json11;
using std::string;
// Check that Json has the properties we want.
#include <type_traits>
#define CHECK_TRAIT(x) static_assert(std::x::value, #x)
CHECK_TRAIT(is_nothrow_constructible<Json>);
CHECK_TRAIT(is_nothrow_default_constructible<Json>);
CHECK_TRAIT(is_copy_constructible<Json>);
CHECK_TRAIT(is_nothrow_move_constructible<Json>);
CHECK_TRAIT(is_copy_assignable<Json>);
CHECK_TRAIT(is_nothrow_move_assignable<Json>);
CHECK_TRAIT(is_nothrow_destructible<Json>);
void parse_from_stdin() {
string buf;
string line;
while (std::getline(std::cin, line)) {
buf += line + "\n";
}
string err;
auto json = Json::parse(buf, err);
if (!err.empty()) {
printf("Failed: %s\n", err.c_str());
} else {
printf("Result: %s\n", json.dump().c_str());
}
}
int main(int argc, char **argv) {
if (argc == 2 && argv[1] == string("--stdin")) {
parse_from_stdin();
return 0;
}
const string simple_test =
R"({"k1":"v1", "k2":42, "k3":["a",123,true,false,null]})";
string err;
auto json = Json::parse(simple_test, err);
std::cout << "k1: " << json["k1"].string_value() << "\n";
std::cout << "k3: " << json["k3"].dump() << "\n";
for (auto &k : json["k3"].array_items()) {
std::cout << " - " << k.dump() << "\n";
}
const string comment_test = R"({
// comment /* with nested comment */
"a": 1,
// comment
// continued
"b": "text",
/* multi
line
comment */
// and single-line comment
"c": [1, 2, 3]
})";
string err_comment;
auto json_comment = Json::parse(
comment_test, err_comment, /*detect_comments=*/ true);
if (!err_comment.empty()) {
printf("Failed: %s\n", err_comment.c_str());
} else {
printf("Result: %s\n", json_comment.dump().c_str());
}
string failing_comment_test = R"({
/* bad comment
"a": 1,
})";
string err_failing_comment;
auto json_failing_comment = Json::parse(
failing_comment_test, err_failing_comment, /*detect_comments=*/ true);
if (!err_failing_comment.empty()) {
printf("Failed: %s\n", err_failing_comment.c_str());
} else {
printf("Result: %s\n", json_failing_comment.dump().c_str());
}
failing_comment_test = R"({
/ / bad comment
"a": 1,
})";
json_failing_comment = Json::parse(
failing_comment_test, err_failing_comment, /*detect_comments=*/ true);
if (!err_failing_comment.empty()) {
printf("Failed: %s\n", err_failing_comment.c_str());
} else {
printf("Result: %s\n", json_failing_comment.dump().c_str());
}
failing_comment_test = R"({
"a": 1,
}/)";
json_failing_comment = Json::parse(
failing_comment_test, err_failing_comment, /*detect_comments=*/ true);
if (!err_failing_comment.empty()) {
printf("Failed: %s\n", err_failing_comment.c_str());
} else {
printf("Result: %s\n", json_failing_comment.dump().c_str());
}
std::list<int> l1 { 1, 2, 3 };
std::vector<int> l2 { 1, 2, 3 };
std::set<int> l3 { 1, 2, 3 };
assert(Json(l1) == Json(l2));
assert(Json(l2) == Json(l3));
std::map<string, string> m1 { { "k1", "v1" }, { "k2", "v2" } };
std::unordered_map<string, string> m2 { { "k1", "v1" }, { "k2", "v2" } };
assert(Json(m1) == Json(m2));
// Json literals
Json obj = Json::object({
{ "k1", "v1" },
{ "k2", 42.0 },
{ "k3", Json::array({ "a", 123.0, true, false, nullptr }) },
});
std::cout << "obj: " << obj.dump() << "\n";
assert(Json("a").number_value() == 0);
assert(Json("a").string_value() == "a");
assert(Json().number_value() == 0);
assert(obj == json);
assert(Json(42) == Json(42.0));
assert(Json(42) != Json(42.1));
const string unicode_escape_test =
R"([ "blah\ud83d\udca9blah\ud83dblah\udca9blah\u0000blah\u1234" ])";
const char utf8[] = "blah" "\xf0\x9f\x92\xa9" "blah" "\xed\xa0\xbd" "blah"
"\xed\xb2\xa9" "blah" "\0" "blah" "\xe1\x88\xb4";
Json uni = Json::parse(unicode_escape_test, err);
assert(uni[0].string_value().size() == (sizeof utf8) - 1);
assert(std::memcmp(uni[0].string_value().data(), utf8, sizeof utf8) == 0);
// Demonstrates the behavior change in Xcode 7 / Clang 3.7 described
// here: https://llvm.org/bugs/show_bug.cgi?id=23812
Json nested_array = Json::array { Json::array { 1, 2, 3 } };
assert(nested_array.is_array());
assert(nested_array.array_items().size() == 1);
assert(nested_array.array_items()[0].is_array());
assert(nested_array.array_items()[0].array_items().size() == 3);
Json my_json = Json::object {
{ "key1", "value1" },
{ "key2", false },
{ "key3", Json::array { 1, 2, 3 } },
};
std::string json_str = my_json.dump();
printf("%s\n", json_str.c_str());
class Point {
public:
int x;
int y;
Point (int x, int y) : x(x), y(y) {}
Json to_json() const { return Json::array { x, y }; }
};
std::vector<Point> points = { { 1, 2 }, { 10, 20 }, { 100, 200 } };
std::string points_json = Json(points).dump();
printf("%s\n", points_json.c_str());
}
|
add malformed comment tests.
|
add malformed comment tests.
add 3 testes for:
- unended multi-line comment,
- malformed single-line comment,
- trailing slash
|
C++
|
mit
|
dropbox/json11,githubwoniu/json11,githubwoniu/json11
|
e05d7f238f7b4be025430c823a3e4a7064da3c99
|
Parser/spirit.cpp
|
Parser/spirit.cpp
|
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
///////////////////////////////////////////////////////////////////////////////
//
// A Calculator example demonstrating generation of AST. The AST,
// once created, is traversed, 1) To print its contents and
// 2) To evaluate the result.
//
// [ JDG April 28, 2008 ] For BoostCon 2008
// [ JDG February 18, 2011 ] Pure attributes. No semantic actions.
//
///////////////////////////////////////////////////////////////////////////////
#include "parserPrivate.h"
#define BOOST_SPIRIT_DEBUG
#define BOOST_SPIRIT_USE_PHOENIX_V3
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/foreach.hpp>
#include <boost/bind.hpp>
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phx = boost::phoenix;
typedef struct localMonome
{
std::string coefficientBegin;
std::string coefficientEnd;
uint x_exponent;
} internalMonome;
namespace client
{
///////////////////////////////////////////////////////////////////////////////
// The grammar
///////////////////////////////////////////////////////////////////////////////
template <typename Iterator>
struct calculator : qi::grammar<Iterator, internalMonome(), ascii::space_type>
{
calculator() : calculator::base_type(polynomial)
{
using qi::_val;
using qi::eps;
qi::char_type char_;
//This part is going to parse polynoms
x_term = char_("x") >> ((char_("^") >> qi::uint_[_val = qi::_1]) | eps[_val = 1]);
//Will parse a single component
variable = -char_("i")
>> ((char_("{") >> (+char_("a-zA-Z_0-9") - char_("}")) >> char_("}"))
| (+char_("0-9") >> -(char_(".") >> +char_("0-9"))))
>> -char_("i");
//Monome core
polynomial = eps[_val = internalMonome()]
>> (variable[phx::bind(&internalMonome::coefficientBegin, _val) = qi::_1]
| eps[phx::bind(&internalMonome::coefficientBegin, _val) = "1"])
>> (-char_("*") >> (x_term[phx::bind(&internalMonome::x_exponent, _val) = qi::_1]
| eps[phx::bind(&internalMonome::x_exponent, _val) = SPIRIT_DEFAULT_POWER_VALUE]))
>> (variable[phx::bind(&internalMonome::coefficientEnd, _val) = qi::_1]
| eps[phx::bind(&internalMonome::coefficientEnd, _val) = "1"]);
}
qi::rule<Iterator, internalMonome(), ascii::space_type> polynomial;
qi::rule<Iterator, uint(), ascii::space_type> x_term;
qi::rule<Iterator, std::string(), ascii::space_type> variable;
};
}
monome parseMonome(std::string str, bool & error)
{
client::calculator<std::string::const_iterator> calc;
boost::spirit::ascii::space_type space;
std::string::const_iterator begin = str.begin();
std::string::const_iterator end = str.end();
internalMonome internMonome;
monome output;
bool r = phrase_parse(begin, end, calc, space, internMonome);
if (r && begin == end)
{
error = false;
output.coef = combineComplexParser(getNumber(internMonome.coefficientBegin), getNumber(internMonome.coefficientEnd));
output.exponent = internMonome.x_exponent;
}
else
{
error = true;
std::string rest(begin, end);
#ifdef VERBOSE
std::cout << "Parsing failed, stopped at: \" " << rest << "\"" << " ~ full string: " << str << '\n';
#endif
}
return output;
}
|
#include "parserPrivate.h"
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phx = boost::phoenix;
typedef struct localMonome
{
std::string coefficientBegin;
std::string coefficientEnd;
uint x_exponent;
} internalMonome;
/*
* Parser grammar
*/
template <typename Iterator>
struct grammar : qi::grammar<Iterator, internalMonome(), ascii::space_type>
{
grammar() : grammar::base_type(polynomial)
{
using qi::_val;
using qi::eps;
qi::char_type char_;
//This part is going to parse polynoms
exponent = char_("x") >> ((char_("^") >> qi::uint_[_val = qi::_1]) | eps[_val = 1]);
//Will parse a single component
variable = -char_("i")
>> ((char_("{") >> (+char_("a-zA-Z_0-9") - char_("}")) >> char_("}"))
| (+char_("0-9") >> -(char_(".") >> +char_("0-9"))))
>> -char_("i");
//Monome core
polynomial = eps[_val = internalMonome()]
>> (variable[phx::bind(&internalMonome::coefficientBegin, _val) = qi::_1]
| eps[phx::bind(&internalMonome::coefficientBegin, _val) = "1"])
>> (-char_("*") >> (exponent[phx::bind(&internalMonome::x_exponent, _val) = qi::_1]
| eps[phx::bind(&internalMonome::x_exponent, _val) = SPIRIT_DEFAULT_POWER_VALUE]))
>> (variable[phx::bind(&internalMonome::coefficientEnd, _val) = qi::_1]
| eps[phx::bind(&internalMonome::coefficientEnd, _val) = "1"]);
}
qi::rule<Iterator, internalMonome(), ascii::space_type> polynomial;
qi::rule<Iterator, std::string(), ascii::space_type> variable;
qi::rule<Iterator, uint(), ascii::space_type> exponent;
};
/*
* Parser entrypoint
*/
monome parseMonome(std::string str, bool & error)
{
grammar<std::string::const_iterator> grammar;
boost::spirit::ascii::space_type space;
std::string::const_iterator begin = str.begin(), end = str.end();
internalMonome internMonome;
monome output;
//Actual parsing
bool success = phrase_parse(begin, end, grammar, space, internMonome);
if (success && begin == end)
{
output.coef = combineComplexParser(getNumber(internMonome.coefficientBegin), getNumber(internMonome.coefficientEnd));
output.exponent = internMonome.x_exponent;
}
else
{
error = true;
#ifdef VERBOSE
std::string rest(begin, end);
std::cout << "Parsing failed, stopped at: \" " << rest << "\"" << " ~ full string: " << str << '\n';
#endif
}
return output;
}
|
Clean up the few remaining parts from the original code, nothing from it remaining here anyway
|
Clean up the few remaining parts from the original code, nothing from it remaining here anyway
|
C++
|
bsd-3-clause
|
Taiki-San/Polybob,Taiki-San/Polybob
|
1ea6230c7d3e441ea8a2961bc1fcd107a79cfed8
|
ProcReadTimer.cpp
|
ProcReadTimer.cpp
|
#include <thread>
#include <future>
#include <algorithm>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "ProcFd.h"
#include "ProcNet.h"
#include "InodeIpHelper.h"
#include "ProcNetPublisher.h"
#include "Duration.h"
#include "ProcReadTimer.h"
using namespace std;
using namespace boost;
void procRead(const system::error_code &code, asio::deadline_timer *timer, const string &pid,
const vector<string>&previousSocketsInode);
bool newConnectionCreated(const vector<string>& currentSocketsInode, const vector<string>& previousSocketsInode);
ProcNetPublisher* procNetPublisher;
ProcReadTimer::ProcReadTimer() {
procNetPublisher = this;
}
void ProcReadTimer::start(string pid) {
thread procReadThread([](string processId) {
asio::io_service io;
asio::deadline_timer timer(io, posix_time::microseconds(0));
timer.async_wait(bind(procRead, asio::placeholders::error, &timer, processId, vector<string>({""})));
io.run();
}, pid);
procReadThread.detach();
}
void procRead(const system::error_code &code, asio::deadline_timer *timer, const string &pid,
const vector<string>&previousSocketsInode) {
Duration duration;
duration.start();
vector<string> socketsInode;
unordered_map<string, NetData> tcpInodeIp;
unordered_map<string, NetData> udpInodeIp;
unordered_map<string, NetData> tcp6InodeIp;
unordered_map<string, NetData> udp6InodeIp;
socketsInode = ProcFd(pid).getSocketInodeList();
if (newConnectionCreated(socketsInode, previousSocketsInode)) {
#pragma omp parallel sections
{
#pragma omp section
tcpInodeIp = ProcNet("tcp").getInodesIpMap();
#pragma omp section
udpInodeIp = ProcNet("udp").getInodesIpMap();
#pragma omp section
tcp6InodeIp = ProcNet("tcp6").getInodesIpMap();
#pragma omp section
udp6InodeIp = ProcNet("udp6").getInodesIpMap();
}
vector<NetData> tcpNetData;
vector<NetData> udpNetData;
vector<NetData> tcp6NetData;
vector<NetData> udp6NetData;
#pragma omp parallel sections
{
#pragma omp section
tcpNetData = InodeIpHelper::filterProccessIp(socketsInode, tcpInodeIp);
#pragma omp section
udpNetData = InodeIpHelper::filterProccessIp(socketsInode, udpInodeIp);
#pragma omp section
tcp6NetData = InodeIpHelper::filterProccessIp(socketsInode, tcp6InodeIp);
#pragma omp section
udp6NetData = InodeIpHelper::filterProccessIp(socketsInode, udp6InodeIp);
}
procNetPublisher->setNetData(tcpNetData, udpNetData, tcp6NetData, udp6NetData);
procNetPublisher->notifyObservers();
}
duration.end();
timer->expires_at(timer->expires_at() + posix_time::microseconds(500000 - duration.inMicroSeconds()));
timer->async_wait(bind(procRead, asio::placeholders::error, timer, pid, socketsInode));
}
bool newConnectionCreated(const vector<string>& currentSocketsInode, const vector<string>& previousSocketsInode) {
bool isNewConnectionCreated = false;
for (auto& previousInode: previousSocketsInode) {
auto iter = find(currentSocketsInode.begin(), currentSocketsInode.end(), previousInode);
if (iter == currentSocketsInode.end()) {
isNewConnectionCreated = true;
break;
}
}
return isNewConnectionCreated;
}
|
#include <thread>
#include <future>
#include <algorithm>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "ProcFd.h"
#include "ProcNet.h"
#include "InodeIpHelper.h"
#include "ProcNetPublisher.h"
#include "Duration.h"
#include "ProcReadTimer.h"
using namespace std;
using namespace boost;
void procRead(const system::error_code &code, asio::deadline_timer *timer, const string &pid,
const vector<string> previousSocketsInode);
ProcNetPublisher* procNetPublisher;
ProcReadTimer::ProcReadTimer() {
procNetPublisher = this;
}
void ProcReadTimer::start(string pid) {
thread procReadThread([](string processId) {
asio::io_service io;
asio::deadline_timer timer(io, posix_time::microseconds(0));
timer.async_wait(bind(procRead, asio::placeholders::error, &timer, processId, vector<string>({""})));
io.run();
}, pid);
procReadThread.detach();
}
void procRead(const system::error_code &code, asio::deadline_timer *timer, const string &pid,
const vector<string> previousSocketsInode) {
Duration duration;
duration.start();
vector<string> socketsInode;
unordered_map<string, NetData> tcpInodeIp;
unordered_map<string, NetData> udpInodeIp;
unordered_map<string, NetData> tcp6InodeIp;
unordered_map<string, NetData> udp6InodeIp;
socketsInode = ProcFd(pid).getSocketInodeList();
if (!equal(previousSocketsInode.begin(), previousSocketsInode.end(), socketsInode.begin())) {
#pragma omp parallel sections
{
#pragma omp section
tcpInodeIp = ProcNet("tcp").getInodesIpMap();
#pragma omp section
udpInodeIp = ProcNet("udp").getInodesIpMap();
#pragma omp section
tcp6InodeIp = ProcNet("tcp6").getInodesIpMap();
#pragma omp section
udp6InodeIp = ProcNet("udp6").getInodesIpMap();
}
vector<NetData> tcpNetData;
vector<NetData> udpNetData;
vector<NetData> tcp6NetData;
vector<NetData> udp6NetData;
#pragma omp parallel sections
{
#pragma omp section
tcpNetData = InodeIpHelper::filterProccessIp(socketsInode, tcpInodeIp);
#pragma omp section
udpNetData = InodeIpHelper::filterProccessIp(socketsInode, udpInodeIp);
#pragma omp section
tcp6NetData = InodeIpHelper::filterProccessIp(socketsInode, tcp6InodeIp);
#pragma omp section
udp6NetData = InodeIpHelper::filterProccessIp(socketsInode, udp6InodeIp);
}
procNetPublisher->setNetData(tcpNetData, udpNetData, tcp6NetData, udp6NetData);
procNetPublisher->notifyObservers();
}
duration.end();
timer->expires_at(timer->expires_at() + posix_time::microseconds(500000 - duration.inMicroSeconds()));
timer->async_wait(bind(procRead, asio::placeholders::error, timer, pid, socketsInode));
}
|
Use std::equal for comparing sockets inode vectors
|
Use std::equal for comparing sockets inode vectors
|
C++
|
mit
|
zulhilmizainuddin/nettomon,zulhilmizainuddin/nettomon,zulhilmizainuddin/nettomon,zulhilmizainuddin/nettomon
|
1113da43569d2cfc1ac3afbcd62e833da215989b
|
inc/fastuidraw/util/fastuidraw_memory.hpp
|
inc/fastuidraw/util/fastuidraw_memory.hpp
|
/*!
* \file fastuidraw_memory.hpp
* \brief file fastuidraw_memory.hpp
*
* Adapted from: WRATHNew.hpp and WRATHmemory.hpp of WRATH:
*
* Copyright 2013 by Nomovok Ltd.
* Contact: [email protected]
* 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/.
*
* \author Kevin Rogovin <[email protected]>
* \author Kevin Rogovin <[email protected]>
*
*/
#pragma once
/*!\addtogroup Utility
@{
*/
#include <stdlib.h>
#include <boost/checked_delete.hpp>
#include <fastuidraw/util/fastuidraw_memory_private.hpp>
/*!\def FASTUIDRAWnew
When DEBUG is defined, allocations with FASTUIDRAWnew are tracked and
at program exit a list of those objects not deleted by FASTUIDRAWdelete
are printed with the file and line number of the allocation. When DEBUG
is not defined, FASTUIDRAWnew maps to new.
*/
/*!\def FASTUIDRAWdelete
Use FASTUIDRAWdelete for objects allocated with FASTUIDRAWnew.
When DEBUG is not defined, maps to boost::checked_delete(p).
\param ptr address of object to delete, value must be a return
value of FASTUIDRAWnew
*/
/*!\def FASTUIDRAWdelete_array
Use FASTUIDRAWdelete_array for arrays of objects allocated with FASTUIDRAWnew.
When DEBUG is not defined, maps to boost::checked_array_delete().
\param ptr address of array of objects to delete, value must be a return
value of FASTUIDRAWnew
*/
/*!\def FASTUIDRAWmalloc
When DEBUG is defined, allocations with FASTUIDRAWmalloc are tracked and
at program exit a list of those objects not deleted by FASTUIDRAWfree
are printed with the file and line number of the allocation. When DEBUG
is not defined, maps to ::malloc.
*/
/*!\def FASTUIDRAWcalloc
When DEBUG is defined, allocations with FASTUIDRAWcalloc are tracked and
at program exit a list of those objects not deleted by FASTUIDRAWfree
are printed with the file and line number of the allocation. When DEBUG
is not defined, maps to ::malloc.
\param nmemb number of elements to allocate
\param size size of each element in bytes
*/
/*!\def FASTUIDRAWrealloc
When DEBUG is defined, allocations with FASTUIDRAWrealloc are tracked and
at program exit a list of those objects not deleted by FASTUIDRAWfree
are printed with the file and line number of the allocation. When DEBUG
is not defined, maps to ::realloc.
\param ptr pointer at whcih to rellocate
\param size new size
*/
/*!\def FASTUIDRAWfree
Use FASTUIDRAWfree for objects allocated with FASTUIDRAWmallo,
FASTUIDRAWrealloc and FASTUIDRAWcalloc. When DEBUG is not defined,
maps to ::free(p).
\param ptr address of object to free
*/
#ifdef DEBUG
#define FASTUIDRAWnew \
::new(__FILE__, __LINE__)
#define FASTUIDRAWdelete(ptr) \
do { \
fastuidraw::memory::object_deletion_message(ptr, __FILE__, __LINE__); \
boost::checked_delete(ptr); } while(0)
#define FASTUIDRAWdelete_array(ptr) \
do { \
fastuidraw::memory::object_deletion_message(ptr, __FILE__, __LINE__); \
boost::checked_array_delete(ptr); } while(0)
#define FASTUIDRAWmalloc(size) \
fastuidraw::memory::malloc_implement(size, __FILE__, __LINE__)
#define FASTUIDRAWcalloc(nmemb, size) \
fastuidraw::memory::calloc_implement(nmemb, size, __FILE__, __LINE__)
#define FASTUIDRAWrealloc(ptr, size) \
fastuidraw::memory::realloc_implement(ptr, size, __FILE__, __LINE__)
#define FASTUIDRAWfree(ptr) \
fastuidraw::memory::free_implement(ptr, __FILE__, __LINE__)
#else
#define FASTUIDRAWnew \
new
#define FASTUIDRAWdelete(ptr) \
do { boost::checked_delete(ptr); } while(0)
#define FASTUIDRAWdelete_array(ptr) \
do { boost::checked_array_delete(ptr); } while(0)
#define FASTUIDRAWmalloc(size) \
::malloc(size)
#define FASTUIDRAWcalloc(nmemb, size) \
::calloc(nmemb, size);
#define FASTUIDRAWrealloc(ptr, size) \
::realloc(ptr, size);
#define FASTUIDRAWfree(ptr) \
::free(ptr)
#endif
/*! @} */
|
/*!
* \file fastuidraw_memory.hpp
* \brief file fastuidraw_memory.hpp
*
* Adapted from: WRATHNew.hpp and WRATHmemory.hpp of WRATH:
*
* Copyright 2013 by Nomovok Ltd.
* Contact: [email protected]
* 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/.
*
* \author Kevin Rogovin <[email protected]>
* \author Kevin Rogovin <[email protected]>
*
*/
#pragma once
/*!\addtogroup Utility
@{
*/
#include <cstdlib>
#include <boost/checked_delete.hpp>
#include <fastuidraw/util/fastuidraw_memory_private.hpp>
/*!\def FASTUIDRAWnew
When DEBUG is defined, allocations with FASTUIDRAWnew are tracked and
at program exit a list of those objects not deleted by FASTUIDRAWdelete
are printed with the file and line number of the allocation. When DEBUG
is not defined, FASTUIDRAWnew maps to new.
*/
/*!\def FASTUIDRAWdelete
Use FASTUIDRAWdelete for objects allocated with FASTUIDRAWnew.
When DEBUG is not defined, maps to boost::checked_delete(p).
\param ptr address of object to delete, value must be a return
value of FASTUIDRAWnew
*/
/*!\def FASTUIDRAWdelete_array
Use FASTUIDRAWdelete_array for arrays of objects allocated with FASTUIDRAWnew.
When DEBUG is not defined, maps to boost::checked_array_delete().
\param ptr address of array of objects to delete, value must be a return
value of FASTUIDRAWnew
*/
/*!\def FASTUIDRAWmalloc
When DEBUG is defined, allocations with FASTUIDRAWmalloc are tracked and
at program exit a list of those objects not deleted by FASTUIDRAWfree
are printed with the file and line number of the allocation. When DEBUG
is not defined, maps to std::malloc.
*/
/*!\def FASTUIDRAWcalloc
When DEBUG is defined, allocations with FASTUIDRAWcalloc are tracked and
at program exit a list of those objects not deleted by FASTUIDRAWfree
are printed with the file and line number of the allocation. When DEBUG
is not defined, maps to std::calloc.
\param nmemb number of elements to allocate
\param size size of each element in bytes
*/
/*!\def FASTUIDRAWrealloc
When DEBUG is defined, allocations with FASTUIDRAWrealloc are tracked and
at program exit a list of those objects not deleted by FASTUIDRAWfree
are printed with the file and line number of the allocation. When DEBUG
is not defined, maps to std::realloc.
\param ptr pointer at whcih to rellocate
\param size new size
*/
/*!\def FASTUIDRAWfree
Use FASTUIDRAWfree for objects allocated with FASTUIDRAWmallo,
FASTUIDRAWrealloc and FASTUIDRAWcalloc. When DEBUG is not defined,
maps to std::free.
\param ptr address of object to free
*/
#ifdef DEBUG
#define FASTUIDRAWnew \
::new(__FILE__, __LINE__)
#define FASTUIDRAWdelete(ptr) \
do { \
fastuidraw::memory::object_deletion_message(ptr, __FILE__, __LINE__); \
boost::checked_delete(ptr); } while(0)
#define FASTUIDRAWdelete_array(ptr) \
do { \
fastuidraw::memory::object_deletion_message(ptr, __FILE__, __LINE__); \
boost::checked_array_delete(ptr); } while(0)
#define FASTUIDRAWmalloc(size) \
fastuidraw::memory::malloc_implement(size, __FILE__, __LINE__)
#define FASTUIDRAWcalloc(nmemb, size) \
fastuidraw::memory::calloc_implement(nmemb, size, __FILE__, __LINE__)
#define FASTUIDRAWrealloc(ptr, size) \
fastuidraw::memory::realloc_implement(ptr, size, __FILE__, __LINE__)
#define FASTUIDRAWfree(ptr) \
fastuidraw::memory::free_implement(ptr, __FILE__, __LINE__)
#else
#define FASTUIDRAWnew \
new
#define FASTUIDRAWdelete(ptr) \
do { boost::checked_delete(ptr); } while(0)
#define FASTUIDRAWdelete_array(ptr) \
do { boost::checked_array_delete(ptr); } while(0)
#define FASTUIDRAWmalloc(size) \
std::malloc(size)
#define FASTUIDRAWcalloc(nmemb, size) \
std::calloc(nmemb, size);
#define FASTUIDRAWrealloc(ptr, size) \
std::realloc(ptr, size);
#define FASTUIDRAWfree(ptr) \
std::free(ptr)
#endif
/*! @} */
|
use std:: instead of global :: for malloc, calloc, realloc and free and also note that in doxytags
|
fastuidraw/util: use std:: instead of global :: for malloc, calloc, realloc and free and also note that in doxytags
|
C++
|
mpl-2.0
|
01org/fastuidraw,01org/fastuidraw
|
68ce888781a163fdf52bd77e3707bcfbc9e49243
|
need-hug/cpp/Main.cpp
|
need-hug/cpp/Main.cpp
|
#include <need-hug-lib/hpp/NeedHugGame.hpp>
#include <need-hug-lib/hpp/ReturnCode/ReturnCodeConverter.hpp>
#include <iostream>
int main(int argc, char** argv)
{
using namespace NeedHug;
ReturnCode returnCode = ReturnCode::Continue;
while(returnCode == NeedHug::ReturnCode::Continue)
{
// When the code reaches here, nothing should be allocated any longer in order to avoid memoryleaks.
NeedHugGame needHugGame;
try
{
returnCode = needHugGame.Start();
}
catch(...)
{
std::cout << "Game crashed unexpectedly" << std::endl;
returnCode = ReturnCode::Unknown;
}
}
std::cout << "The game returned the following stopCode '" << ReturnCodeConverter().Convert(returnCode).info << "'." << std::endl;
int returnCodeValue = 1;
if(returnCode == ReturnCode::Stop)
{
returnCodeValue = 0;
}
return returnCodeValue;
}
|
#include <need-hug-lib/hpp/NeedHugGame.hpp>
#include <need-hug-lib/hpp/ReturnCode/ReturnCodeConverter.hpp>
#include <iostream>
int main(int argc, char** argv)
{
using namespace NeedHug;
ReturnCode returnCode = ReturnCode::Continue;
while (returnCode == NeedHug::ReturnCode::Continue)
{
// When the code reaches here, nothing should be allocated any longer in order to avoid memoryleaks.
NeedHugGame needHugGame;
try
{
returnCode = needHugGame.Start();
}
catch (...)
{
std::cout << "Game crashed unexpectedly" << std::endl;
returnCode = ReturnCode::Unknown;
}
}
std::cout << "The game returned the following stopCode '" << ReturnCodeConverter().Convert(returnCode).info << "'." << std::endl;
int returnCodeValue = 1;
if (returnCode == ReturnCode::Stop)
{
returnCodeValue = 0;
}
#ifdef _WIN32
std::getchar();
#endif
return returnCodeValue;
}
|
Add pause before exit on windows systems
|
Add pause before exit on windows systems
|
C++
|
mit
|
Poelsa/need-hug,Poelsa/need-hug
|
c62a65517c9ed14545a5a5223354af74aedce5fc
|
Include/COMInterface.inl
|
Include/COMInterface.inl
|
#pragma once
#include "COMInterface.hpp"
#include <cassert>
#include <utility>
#ifndef _WIN64
#error This files is meant to be included only in Windows builds.
#endif
using GUID = _GUID;
struct IUnknown
{
public:
virtual long QueryInterface(const GUID& interfaceID, void** object) = 0;
virtual unsigned long AddRef() = 0;
virtual unsigned long Release() = 0;
};
template <typename I>
struct RemoveIUnknown : public I
{
private:
virtual long QueryInterface(const GUID& interfaceID, void** object) = 0;
virtual unsigned long AddRef() = 0;
virtual unsigned long Release() = 0;
};
template <typename I>
COMInterface<I>::COMInterface() noexcept = default;
template <typename I>
COMInterface<I>::~COMInterface()
{
if (ptr)
release();
}
template <typename I>
COMInterface<I>::COMInterface(const COMInterface& other) noexcept
{
*this = other;
}
template <typename I>
COMInterface<I>& COMInterface<I>::operator=(const COMInterface& other) noexcept
{
if (this == &rhs)
return *this;
if (ptr)
release();
ptr = rhs.ptr;
if (ptr)
addRef();
return *this;
}
template <typename I>
COMInterface<I>::COMInterface(COMInterface&& other) noexcept
{
*this = std::move(other);
}
template <typename I>
COMInterface<I>& COMInterface<I>::operator=(COMInterface&& rhs) noexcept
{
if (this == &rhs)
return *this;
if (ptr)
release();
ptr = std::exchange(rhs.ptr, nullptr);
return *this;
}
template <typename I>
I** COMInterface<I>::getAddress() noexcept
{
return &ptr;
}
template <typename I>
I* const* COMInterface<I>::getAddress() const noexcept
{
return &ptr;
}
template <typename I>
template <typename U>
void COMInterface<I>::as(COMInterface<U>& other) noexcept
{
assert(ptr);
ptr->QueryInterface(other.getUUID(), reinterpret_cast<void**>(&other.ptr));
}
template <typename I>
template <typename U>
COMInterface<U> COMInterface<I>::as() noexcept
{
assert(ptr);
COMInterface<U> result;
as(result);
return result;
}
template <typename I>
auto* COMInterface<I>::operator->() noexcept
{
assert(ptr);
return reinterpret_cast<RemoveIUnknown*>(ptr);
}
template <typename I>
const auto* COMInterface<I>::operator->() const noexcept
{
assert(ptr);
return reinterpret_cast<RemoveIUnknown*>(ptr);
}
template <typename I>
auto& COMInterface<I>::operator*() noexcept
{
assert(ptr);
return *reinterpret_cast<RemoveIUnknown*>(ptr);
}
template <typename I>
const auto& COMInterface<I>::operator*() const noexcept
{
assert(ptr);
return *reinterpret_cast<RemoveIUnknown*>(ptr);
}
template <typename I>
void swap(COMInterface<I>& lhs, COMInterface<I>& rhs) noexcept
{
using std::swap;
swap(lhs.ptr, rhs.ptr);
}
template <typename I>
constexpr static auto COMInterface<I>::getUUID() noexcept
{
return __uuidof(I);
}
template <typename I>
void COMInterface<I>::addRef() noexcept
{
assert(ptr);
reinterpret_cast<IUnknown*>(ptr)->AddRef();
}
template <typename I>
void COMInterface<I>::release() noexcept
{
assert(ptr);
reinterpret_cast<IUnknown*>(ptr)->Release();
ptr = nullptr;
}
|
#pragma once
#include "COMInterface.hpp"
#include <cassert>
#include <utility>
#ifndef _WIN64
#error This files is meant to be included only in Windows builds.
#endif
using GUID = _GUID;
struct IUnknown
{
public:
virtual long QueryInterface(const GUID& interfaceID, void** object) = 0;
virtual unsigned long AddRef() = 0;
virtual unsigned long Release() = 0;
};
template <typename I>
struct RemoveIUnknown : public I
{
private:
virtual long QueryInterface(const GUID& interfaceID, void** object) = 0;
virtual unsigned long AddRef() = 0;
virtual unsigned long Release() = 0;
};
template <typename I>
COMInterface<I>::COMInterface() noexcept = default;
template <typename I>
COMInterface<I>::~COMInterface()
{
if (ptr)
release();
}
template <typename I>
COMInterface<I>::COMInterface(const COMInterface& other) noexcept
{
*this = other;
}
template <typename I>
COMInterface<I>& COMInterface<I>::operator=(const COMInterface& other) noexcept
{
if (this == &rhs)
return *this;
if (ptr)
release();
ptr = rhs.ptr;
if (ptr)
addRef();
return *this;
}
template <typename I>
COMInterface<I>::COMInterface(COMInterface&& other) noexcept
{
*this = std::move(other);
}
template <typename I>
COMInterface<I>& COMInterface<I>::operator=(COMInterface&& rhs) noexcept
{
if (this == &rhs)
return *this;
if (ptr)
release();
ptr = std::exchange(rhs.ptr, nullptr);
return *this;
}
template <typename I>
I** COMInterface<I>::getAddress() noexcept
{
return &ptr;
}
template <typename I>
I* const* COMInterface<I>::getAddress() const noexcept
{
return &ptr;
}
template <typename I>
template <typename U>
void COMInterface<I>::as(COMInterface<U>& other) noexcept
{
assert(ptr);
ptr->QueryInterface(other.getUUID(), reinterpret_cast<void**>(&other.ptr));
}
template <typename I>
template <typename U>
COMInterface<U> COMInterface<I>::as() noexcept
{
assert(ptr);
COMInterface<U> result;
as(result);
return result;
}
template <typename I>
auto* COMInterface<I>::operator->() noexcept
{
assert(ptr);
return reinterpret_cast<RemoveIUnknown*>(ptr);
}
template <typename I>
const auto* COMInterface<I>::operator->() const noexcept
{
assert(ptr);
return reinterpret_cast<RemoveIUnknown*>(ptr);
}
template <typename I>
auto& COMInterface<I>::operator*() noexcept
{
assert(ptr);
return *reinterpret_cast<RemoveIUnknown*>(ptr);
}
template <typename I>
const auto& COMInterface<I>::operator*() const noexcept
{
assert(ptr);
return *reinterpret_cast<RemoveIUnknown*>(ptr);
}
template <typename I>
void swap(COMInterface<I>& lhs, COMInterface<I>& rhs) noexcept
{
using std::swap;
swap(lhs.ptr, rhs.ptr);
}
template <typename I>
constexpr auto COMInterface<I>::getUUID() noexcept
{
return __uuidof(I);
}
template <typename I>
void COMInterface<I>::addRef() noexcept
{
assert(ptr);
reinterpret_cast<IUnknown*>(ptr)->AddRef();
}
template <typename I>
void COMInterface<I>::release() noexcept
{
assert(ptr);
reinterpret_cast<IUnknown*>(ptr)->Release();
ptr = nullptr;
}
|
Remove extraneous `static` keyword
|
Remove extraneous `static` keyword
|
C++
|
unlicense
|
GuildMasterInfinite/CPP-Utilities
|
739f18f67dc59e869a2a1ccf657e1487e151d896
|
include/visionaray/detail/pathtracing.inl
|
include/visionaray/detail/pathtracing.inl
|
// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include "../math/vector.h"
#include "../get_area.h"
#include "../get_surface.h"
#include "../result_record.h"
#include "../sampling.h"
#include "../spectrum.h"
#include "../surface_interaction.h"
#include "../traverse.h"
#ifdef __CUDACC__
#define CLOCK clock
#else
#define CLOCK clock64
#endif
namespace visionaray
{
namespace pathtracing
{
template <typename T>
VSNRAY_FUNC inline vector<4, T> over(vector<4, T> const& a, vector<4, T> const& b)
{
return a + (T(1.0) - a.w) * b;
}
template <typename Params>
struct kernel
{
Params params;
bool perf_debug = false;
template <typename Intersector, typename R, typename Generator>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(
Intersector& isect,
R ray,
Generator& gen
) const
{
uint64_t clock_begin = CLOCK();
using S = typename R::scalar_type;
using I = simd::int_type_t<S>;
using V = vector<3, S>;
using C = spectrum<S>;
simd::mask_type_t<S> active_rays = true;
simd::mask_type_t<S> last_specular = true;
C intensity(0.0);
C throughput(1.0);
result_record<S> result;
result.color = vector<4, S>(params.background.intensity(ray.dir), S(1.0));
for (unsigned bounce = 0; bounce < params.num_bounces; ++bounce)
{
auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
// Handle rays that just exited
auto exited = active_rays & !hit_rec.hit;
auto env = params.amb_light.intensity(ray.dir);
intensity += select(
exited,
from_rgb(env) * throughput,
C(0.0)
);
// Exit if no ray is active anymore
active_rays &= hit_rec.hit;
if (!any(active_rays))
{
break;
}
// Special handling for first bounce
if (bounce == 0)
{
result.hit = hit_rec.hit;
result.depth = hit_rec.t;
}
// Process the current bounce
V refl_dir(0.0);
V view_dir = -ray.dir;
hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t;
auto surf = get_surface(hit_rec, params);
S brdf_pdf(0.0);
// Remember the last type of surface interaction.
// If the last interaction was not diffuse, we have
// to include light from emissive surfaces.
I inter = 0;
auto src = surf.sample(view_dir, refl_dir, brdf_pdf, inter, gen);
auto zero_pdf = brdf_pdf <= S(0.0);
S light_pdf(0.0);
auto num_lights = params.lights.end - params.lights.begin;
if (num_lights > 0 && any(inter == surface_interaction::Emission))
{
auto A = get_area(params.prims.begin, hit_rec);
auto ld = length(hit_rec.isect_pos - ray.ori);
auto L = normalize(hit_rec.isect_pos - ray.ori);
auto n = surf.geometric_normal;
auto ldotln = abs(dot(-L, n));
auto solid_angle = (ldotln * A) / (ld * ld);
light_pdf = select(
inter == surface_interaction::Emission,
S(1.0) / solid_angle,
S(0.0)
);
}
S mis_weight = select(
bounce > 0 && num_lights > 0 && !last_specular,
power_heuristic(brdf_pdf, light_pdf / static_cast<float>(num_lights)),
S(1.0)
);
intensity += select(
active_rays && inter == surface_interaction::Emission,
mis_weight * throughput * src,
C(0.0)
);
active_rays &= inter != surface_interaction::Emission;
active_rays &= !zero_pdf;
auto n = surf.shading_normal;
#if 1
n = faceforward( n, view_dir, surf.geometric_normal );
#endif
if (num_lights > 0)
{
auto ls = sample_random_light(
params.lights.begin,
params.lights.end,
hit_rec.isect_pos,
gen
);
auto ld = ls.dist;
auto L = normalize(ls.dir);
auto ln = select(ls.delta_light, -L, ls.normal);
#if 1
ln = faceforward( ln, -L, ln );
#endif
auto ldotn = dot(L, n);
auto ldotln = abs(dot(-L, ln));
R shadow_ray(
hit_rec.isect_pos + L * S(params.epsilon), // origin
L, // direction
S(params.epsilon), // tmin
ld - S(params.epsilon) // tmax
);
auto lhr = any_hit(shadow_ray, params.prims.begin, params.prims.end, isect);
auto brdf_pdf = surf.pdf(view_dir, L, inter);
auto prob = max_element(throughput.samples());
brdf_pdf *= prob;
// TODO: inv_pi / dot(n, wi) factor only valid for plastic and matte
auto src = surf.shade(view_dir, L, ls.intensity) * constants::inv_pi<S>() / ldotn;
auto solid_angle = (ldotln * ls.area);
solid_angle = select(!ls.delta_light, solid_angle / (ld * ld), solid_angle);
auto light_pdf = S(1.0) / solid_angle;
S mis_weight = power_heuristic(light_pdf / static_cast<float>(num_lights), brdf_pdf);
intensity += select(
active_rays && !lhr.hit && ldotn > S(0.0) && ldotln > S(0.0),
mis_weight * throughput * src * (ldotn / light_pdf) * S(static_cast<float>(num_lights)),
C(0.0)
);
}
throughput *= src * (dot(n, refl_dir) / brdf_pdf);
throughput = select(zero_pdf, C(0.0), throughput);
if (bounce >= 2)
{
// Russian roulette
auto prob = max_element(throughput.samples());
auto terminate = gen.next() > prob;
active_rays &= !terminate;
throughput /= prob;
if (!any(active_rays))
{
break;
}
}
ray.ori = hit_rec.isect_pos + refl_dir * S(params.epsilon);
ray.dir = refl_dir;
last_specular = inter == surface_interaction::SpecularReflection ||
inter == surface_interaction::SpecularTransmission;
}
result.color = select( result.hit, to_rgba(intensity), result.color );
if (perf_debug)
{
uint64_t clock_end = CLOCK();
float heat_map_scale = 1.0f;
float t = (clock_end - clock_begin) * heat_map_scale;
result.color = over(vector<4, S>(vector<3, S>(temperature_to_rgb(t)), S(0.5)), result.color);
}
return result;
}
template <typename R, typename Generator>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(
R ray,
Generator& gen
) const
{
default_intersector ignore;
return (*this)(ignore, ray, gen);
}
};
} // pathtracing
} // visionaray
|
// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include "../math/vector.h"
#include "../get_area.h"
#include "../get_surface.h"
#include "../result_record.h"
#include "../sampling.h"
#include "../spectrum.h"
#include "../surface_interaction.h"
#include "../traverse.h"
#ifdef __CUDACC__
#define CLOCK clock
#else
#define CLOCK clock64
#endif
namespace visionaray
{
namespace pathtracing
{
template <typename T>
VSNRAY_FUNC inline vector<4, T> over(vector<4, T> const& a, vector<4, T> const& b)
{
return a + (T(1.0) - a.w) * b;
}
template <typename Params>
struct kernel
{
Params params;
float heat_map_scale = 1.0f;
bool perf_debug = false;
template <typename Intersector, typename R, typename Generator>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(
Intersector& isect,
R ray,
Generator& gen
) const
{
uint64_t clock_begin = CLOCK();
using S = typename R::scalar_type;
using I = simd::int_type_t<S>;
using V = vector<3, S>;
using C = spectrum<S>;
simd::mask_type_t<S> active_rays = true;
simd::mask_type_t<S> last_specular = true;
C intensity(0.0);
C throughput(1.0);
result_record<S> result;
result.color = vector<4, S>(params.background.intensity(ray.dir), S(1.0));
for (unsigned bounce = 0; bounce < params.num_bounces; ++bounce)
{
auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);
// Handle rays that just exited
auto exited = active_rays & !hit_rec.hit;
auto env = params.amb_light.intensity(ray.dir);
intensity += select(
exited,
from_rgb(env) * throughput,
C(0.0)
);
// Exit if no ray is active anymore
active_rays &= hit_rec.hit;
if (!any(active_rays))
{
break;
}
// Special handling for first bounce
if (bounce == 0)
{
result.hit = hit_rec.hit;
result.depth = hit_rec.t;
}
// Process the current bounce
V refl_dir(0.0);
V view_dir = -ray.dir;
hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t;
auto surf = get_surface(hit_rec, params);
S brdf_pdf(0.0);
// Remember the last type of surface interaction.
// If the last interaction was not diffuse, we have
// to include light from emissive surfaces.
I inter = 0;
auto src = surf.sample(view_dir, refl_dir, brdf_pdf, inter, gen);
auto zero_pdf = brdf_pdf <= S(0.0);
S light_pdf(0.0);
auto num_lights = params.lights.end - params.lights.begin;
if (num_lights > 0 && any(inter == surface_interaction::Emission))
{
auto A = get_area(params.prims.begin, hit_rec);
auto ld = length(hit_rec.isect_pos - ray.ori);
auto L = normalize(hit_rec.isect_pos - ray.ori);
auto n = surf.geometric_normal;
auto ldotln = abs(dot(-L, n));
auto solid_angle = (ldotln * A) / (ld * ld);
light_pdf = select(
inter == surface_interaction::Emission,
S(1.0) / solid_angle,
S(0.0)
);
}
S mis_weight = select(
bounce > 0 && num_lights > 0 && !last_specular,
power_heuristic(brdf_pdf, light_pdf / static_cast<float>(num_lights)),
S(1.0)
);
intensity += select(
active_rays && inter == surface_interaction::Emission,
mis_weight * throughput * src,
C(0.0)
);
active_rays &= inter != surface_interaction::Emission;
active_rays &= !zero_pdf;
auto n = surf.shading_normal;
#if 1
n = faceforward( n, view_dir, surf.geometric_normal );
#endif
if (num_lights > 0)
{
auto ls = sample_random_light(
params.lights.begin,
params.lights.end,
hit_rec.isect_pos,
gen
);
auto ld = ls.dist;
auto L = normalize(ls.dir);
auto ln = select(ls.delta_light, -L, ls.normal);
#if 1
ln = faceforward( ln, -L, ln );
#endif
auto ldotn = dot(L, n);
auto ldotln = abs(dot(-L, ln));
R shadow_ray(
hit_rec.isect_pos + L * S(params.epsilon), // origin
L, // direction
S(params.epsilon), // tmin
ld - S(params.epsilon) // tmax
);
auto lhr = any_hit(shadow_ray, params.prims.begin, params.prims.end, isect);
auto brdf_pdf = surf.pdf(view_dir, L, inter);
auto prob = max_element(throughput.samples());
brdf_pdf *= prob;
// TODO: inv_pi / dot(n, wi) factor only valid for plastic and matte
auto src = surf.shade(view_dir, L, ls.intensity) * constants::inv_pi<S>() / ldotn;
auto solid_angle = (ldotln * ls.area);
solid_angle = select(!ls.delta_light, solid_angle / (ld * ld), solid_angle);
auto light_pdf = S(1.0) / solid_angle;
S mis_weight = power_heuristic(light_pdf / static_cast<float>(num_lights), brdf_pdf);
intensity += select(
active_rays && !lhr.hit && ldotn > S(0.0) && ldotln > S(0.0),
mis_weight * throughput * src * (ldotn / light_pdf) * S(static_cast<float>(num_lights)),
C(0.0)
);
}
throughput *= src * (dot(n, refl_dir) / brdf_pdf);
throughput = select(zero_pdf, C(0.0), throughput);
if (bounce >= 2)
{
// Russian roulette
auto prob = max_element(throughput.samples());
auto terminate = gen.next() > prob;
active_rays &= !terminate;
throughput /= prob;
if (!any(active_rays))
{
break;
}
}
ray.ori = hit_rec.isect_pos + refl_dir * S(params.epsilon);
ray.dir = refl_dir;
last_specular = inter == surface_interaction::SpecularReflection ||
inter == surface_interaction::SpecularTransmission;
}
result.color = select( result.hit, to_rgba(intensity), result.color );
if (perf_debug)
{
uint64_t clock_end = CLOCK();
float t = (clock_end - clock_begin) * heat_map_scale;
result.color = over(vector<4, S>(vector<3, S>(temperature_to_rgb(t)), S(0.5)), result.color);
}
return result;
}
template <typename R, typename Generator>
VSNRAY_FUNC result_record<typename R::scalar_type> operator()(
R ray,
Generator& gen
) const
{
default_intersector ignore;
return (*this)(ignore, ray, gen);
}
};
} // pathtracing
} // visionaray
|
Set heatmap scale from outside
|
Set heatmap scale from outside
|
C++
|
mit
|
szellmann/visionaray,szellmann/visionaray
|
00c144ff48df1c2b7a00bb5e16f59aad5e31bbf5
|
WhisperHost.cpp
|
WhisperHost.cpp
|
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file WhisperHost.cpp
* @author Gav Wood <[email protected]>
* @date 2014
*/
#include "WhisperHost.h"
#include <libdevcore/CommonIO.h>
#include <libdevcore/Log.h>
#include <libp2p/All.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::shh;
#if defined(clogS)
#undef clogS
#endif
#define clogS(X) dev::LogOutputStream<X, true>(false) << "| " << std::setw(2) << session()->socketId() << "] "
WhisperHost::WhisperHost()
{
}
WhisperHost::~WhisperHost()
{
}
void WhisperHost::streamMessage(h256 _m, RLPStream& _s) const
{
UpgradableGuard l(x_messages);
if (m_messages.count(_m))
{
UpgradeGuard ll(l);
auto const& m = m_messages.at(_m);
cnote << "streamRLP: " << m.expiry() << m.ttl() << m.topic() << toHex(m.data());
m.streamRLP(_s);
}
}
void WhisperHost::inject(Envelope const& _m, WhisperPeer* _p)
{
cnote << this << ": inject: " << _m.expiry() << _m.ttl() << _m.topic() << toHex(_m.data());
if (_m.expiry() <= (unsigned)time(0))
return;
auto h = _m.sha3();
{
UpgradableGuard l(x_messages);
if (m_messages.count(h))
return;
UpgradeGuard ll(l);
m_messages[h] = _m;
m_expiryQueue.insert(make_pair(_m.expiry(), h));
}
// if (_p)
{
Guard l(m_filterLock);
for (auto const& f: m_filters)
if (f.second.filter.matches(_m))
noteChanged(h, f.first);
}
// TODO p2p: capability-based rating
for (auto i: peerSessions())
{
auto w = i.first->cap<WhisperPeer>().get();
if (w == _p)
w->addRating(1);
else
w->noteNewMessage(h, _m);
}
}
void WhisperHost::noteChanged(h256 _messageHash, h256 _filter)
{
for (auto& i: m_watches)
if (i.second.id == _filter)
{
cwatshh << "!!!" << i.first << i.second.id;
i.second.changes.push_back(_messageHash);
}
}
unsigned WhisperHost::installWatchOnId(h256 _h)
{
auto ret = m_watches.size() ? m_watches.rbegin()->first + 1 : 0;
m_watches[ret] = ClientWatch(_h);
cwatshh << "+++" << ret << _h;
return ret;
}
unsigned WhisperHost::installWatch(shh::FullTopic const& _ft)
{
Guard l(m_filterLock);
InstalledFilter f(_ft);
h256 h = f.filter.sha3();
if (!m_filters.count(h))
m_filters.insert(make_pair(h, f));
return installWatchOnId(h);
}
h256s WhisperHost::watchMessages(unsigned _watchId)
{
h256s ret;
auto wit = m_watches.find(_watchId);
if (wit == m_watches.end())
return ret;
TopicFilter f;
{
Guard l(m_filterLock);
auto fit = m_filters.find(wit->second.id);
if (fit == m_filters.end())
return ret;
f = fit->second.filter;
}
ReadGuard l(x_messages);
for (auto const& m: m_messages)
if (f.matches(m.second))
ret.push_back(m.first);
return ret;
}
void WhisperHost::uninstallWatch(unsigned _i)
{
cwatshh << "XXX" << _i;
Guard l(m_filterLock);
auto it = m_watches.find(_i);
if (it == m_watches.end())
return;
auto id = it->second.id;
m_watches.erase(it);
auto fit = m_filters.find(id);
if (fit != m_filters.end())
if (!--fit->second.refCount)
m_filters.erase(fit);
}
void WhisperHost::doWork()
{
for (auto& i: peerSessions())
i.first->cap<WhisperPeer>().get()->sendMessages();
cleanup();
}
void WhisperHost::cleanup()
{
// remove old messages.
// should be called every now and again.
unsigned now = (unsigned)time(0);
WriteGuard l(x_messages);
for (auto it = m_expiryQueue.begin(); it != m_expiryQueue.end() && it->first <= now; it = m_expiryQueue.erase(it))
m_messages.erase(it->second);
}
|
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file WhisperHost.cpp
* @author Gav Wood <[email protected]>
* @date 2014
*/
#include "WhisperHost.h"
#include <libdevcore/CommonIO.h>
#include <libdevcore/Log.h>
#include <libp2p/All.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::shh;
#if defined(clogS)
#undef clogS
#endif
#define clogS(X) dev::LogOutputStream<X, true>(false) << "| " << std::setw(2) << session()->socketId() << "] "
WhisperHost::WhisperHost()
{
}
WhisperHost::~WhisperHost()
{
}
void WhisperHost::streamMessage(h256 _m, RLPStream& _s) const
{
UpgradableGuard l(x_messages);
if (m_messages.count(_m))
{
UpgradeGuard ll(l);
auto const& m = m_messages.at(_m);
cnote << "streamRLP: " << m.expiry() << m.ttl() << m.topic() << toHex(m.data());
m.streamRLP(_s);
}
}
void WhisperHost::inject(Envelope const& _m, WhisperPeer* _p)
{
cnote << this << ": inject: " << _m.expiry() << _m.ttl() << _m.topic() << toHex(_m.data());
if (_m.expiry() <= (unsigned)time(0))
return;
auto h = _m.sha3();
{
UpgradableGuard l(x_messages);
if (m_messages.count(h))
return;
UpgradeGuard ll(l);
m_messages[h] = _m;
m_expiryQueue.insert(make_pair(_m.expiry(), h));
}
// if (_p)
{
Guard l(m_filterLock);
for (auto const& f: m_filters)
if (f.second.filter.matches(_m))
noteChanged(h, f.first);
}
// TODO p2p: capability-based rating
for (auto i: peerSessions())
{
auto w = i.first->cap<WhisperPeer>();
if (!!w && w.get() == _p)
w->addRating(1);
else if(!!w)
w->noteNewMessage(h, _m);
}
}
void WhisperHost::noteChanged(h256 _messageHash, h256 _filter)
{
for (auto& i: m_watches)
if (i.second.id == _filter)
{
cwatshh << "!!!" << i.first << i.second.id;
i.second.changes.push_back(_messageHash);
}
}
unsigned WhisperHost::installWatchOnId(h256 _h)
{
auto ret = m_watches.size() ? m_watches.rbegin()->first + 1 : 0;
m_watches[ret] = ClientWatch(_h);
cwatshh << "+++" << ret << _h;
return ret;
}
unsigned WhisperHost::installWatch(shh::FullTopic const& _ft)
{
Guard l(m_filterLock);
InstalledFilter f(_ft);
h256 h = f.filter.sha3();
if (!m_filters.count(h))
m_filters.insert(make_pair(h, f));
return installWatchOnId(h);
}
h256s WhisperHost::watchMessages(unsigned _watchId)
{
h256s ret;
auto wit = m_watches.find(_watchId);
if (wit == m_watches.end())
return ret;
TopicFilter f;
{
Guard l(m_filterLock);
auto fit = m_filters.find(wit->second.id);
if (fit == m_filters.end())
return ret;
f = fit->second.filter;
}
ReadGuard l(x_messages);
for (auto const& m: m_messages)
if (f.matches(m.second))
ret.push_back(m.first);
return ret;
}
void WhisperHost::uninstallWatch(unsigned _i)
{
cwatshh << "XXX" << _i;
Guard l(m_filterLock);
auto it = m_watches.find(_i);
if (it == m_watches.end())
return;
auto id = it->second.id;
m_watches.erase(it);
auto fit = m_filters.find(id);
if (fit != m_filters.end())
if (!--fit->second.refCount)
m_filters.erase(fit);
}
void WhisperHost::doWork()
{
for (auto& i: peerSessions())
if (auto w = i.first->cap<WhisperPeer>())
if (!!w)
i.first->cap<WhisperPeer>()->sendMessages();
cleanup();
}
void WhisperHost::cleanup()
{
// remove old messages.
// should be called every now and again.
unsigned now = (unsigned)time(0);
WriteGuard l(x_messages);
for (auto it = m_expiryQueue.begin(); it != m_expiryQueue.end() && it->first <= now; it = m_expiryQueue.erase(it))
m_messages.erase(it->second);
}
|
fix #1366
|
fix #1366
|
C++
|
mit
|
CJentzsch/webthree,gluk256/webthree,gluk256/webthree,LianaHus/webthree,LianaHus/webthree,CJentzsch/webthree
|
b1bb995e3f894717f9f636801ab707a0dca667ac
|
Rudder/Rudder.cpp
|
Rudder/Rudder.cpp
|
#include <Adafruit_HMC5883_U.h>
#include "Arduino.h"
#include "Calculations.h"
#include "Rudder.h"
#include "Boat.h"
using namespace std;
extern Adafruit_HMC5883_Unified rudderCompass;
int rudderAddr = 6;
float getCompass()
{
sensors_event_t event;
Calculations::tcaselect(rudderAddr);
rudderCompass.getEvent(&event);
float degs = Calculations::sensorToDegrees(event.magnetic.x, event.magnetic.y);
return degs;
}
Rudder::Rudder()
{
Serial.print("Rudder Initialized.");
}
float Rudder::turnTo(float angle, char side)
{
}
rudderPosition Rudder::getAngle(float boatHeading)
{
rudderPosition position;
float rudderHeading = getCompass();
position.angle = Calculations::degreesBetween(boatHeading,rudderHeading);
float rudderRads = Calculations::degreesToRadians(rudderHeading);
float boatRads = Calculations::degreesToRadians(boatHeading);
float direction = sin((boatRads - rudderRads));
if (direction > 0) {
position.direction = 'p';
} else {
position.direction = 's';
}
return position;
}
|
#include <Adafruit_HMC5883_U.h>
#include "Arduino.h"
#include "Calculations.h"
#include "Rudder.h"
#include "Boat.h"
using namespace std;
extern Adafruit_HMC5883_Unified rudderCompass;
int rudderAddr = 6;
float getCompass()
{
sensors_event_t event;
Calculations::tcaselect(rudderAddr);
rudderCompass.getEvent(&event);
float degs = Calculations::sensorToDegrees(event.magnetic.x, event.magnetic.y);
return degs;
}
Rudder::Rudder()
{
Serial.print("Rudder Initialized.");
}
float Rudder::turnTo(float angle, char side)
{
}
rudderPosition Rudder::getAngle(float boatHeading)
{
rudderPosition position;
float rudderHeading = getCompass();
position.angle = Calculations::degreesBetween(boatHeading,rudderHeading);
float rudderRads = Calculations::degreesToRadians(rudderHeading);
float boatRads = Calculations::degreesToRadians(boatHeading);
float direction = sin((boatRads - rudderRads));
if (direction > 0) {
position.direction = 's';
} else {
position.direction = 'p';
}
return position;
}
|
Fix starboard/port mixup
|
Fix starboard/port mixup
|
C++
|
mit
|
johngroves/SCOUT,johngroves/SCOUT
|
286f9250a666360811c67280247feafbecfb0b4b
|
c-cpp/09_queue/array_queue.hpp
|
c-cpp/09_queue/array_queue.hpp
|
/**
* Created by Liam Huang (Liam0205) on 2018/10/10.
*/
#ifndef QUEUE_ARRAY_QUEUE_HPP_
#define QUEUE_ARRAY_QUEUE_HPP_
template <typename T>
class ArrayQueue {
private:
T* items_ = nullptr;
size_t capacity_ = 0;
size_t head_ = 0;
size_t tail_ = 0;
public:
ArrayQueue() = delete;
ArrayQueue(size_t capacity) : capacity_(capacity) {
items_ = new T[capacity];
}
~ArrayQueue() {
if (nullptr != items_) {
delete[] items_;
items_ = nullptr;
}
}
ArrayQueue(const ArrayQueue& other) : capacity_(other.capacity_) {
items_ = new T[capacity_];
for (size_t i = other.head_; i != other.tail_; ++i) {
enqueue(other.items_[i]);
}
}
ArrayQueue& operator=(const ArrayQueue& rhs) {
delete[] items_;
head_ = 0;
tail_ = 0;
capacity_ = rhs.capacity_;
items_ = new T[capacity_];
for (size_t i = other.head_; i != other.tail_; ++i) {
enqueue(other.items_[i]);
}
return *this;
}
ArrayQueue(ArrayQueue&& other) : items_(other.items_),
capacity_(other.capacity_),
head_(other.head_),
tail_(other.tail_) {
other.items_ = nullptr;
other.capacity_ = 0;
other.head_ = 0;
other.tail_ = 0;
}
ArrayQueue& operator=(ArrayQueue&& rhs) {
delete[] items_;
items_ = rhs.items_;
capacity_ = rhs.capacity_;
head_ = rhs.head_;
tail_ = rhs.tail_;
rhs.items_ = nullptr;
rhs.capacity_ = 0;
rhs.head_ = 0;
rhs.tail_ = 0;
return *this;
}
public:
void enqueue(T item) {
if (capacity_ == tail_) {
throw "Push data into a full queue!";
}
items_[tail_++] = item;
}
T head() const {
if (head_ != tail_) {
return items_[head_];
} else {
throw "Fetch data from an empty queue!";
}
}
void dequeue() {
if (head_ != tail_) {
++head_;
} else {
throw "Pop data from an empty queue!";
}
}
public:
template <typename UnaryFunc>
void traverse(UnaryFunc do_traverse) {
for (size_t i = head_; i != tail_; ++i) {
do_traverse(items_[i]);
}
}
};
#endif // QUEUE_ARRAY_QUEUE_HPP_
|
/**
* Created by Liam Huang (Liam0205) on 2018/10/10.
*/
#ifndef QUEUE_ARRAY_QUEUE_HPP_
#define QUEUE_ARRAY_QUEUE_HPP_
template <typename T>
class ArrayQueue {
private:
T* items_ = nullptr;
size_t capacity_ = 0;
size_t head_ = 0;
size_t tail_ = 0;
public:
ArrayQueue() = delete;
ArrayQueue(size_t capacity) : capacity_(capacity) {
items_ = new T[capacity];
}
~ArrayQueue() {
if (nullptr != items_) {
delete[] items_;
items_ = nullptr;
}
}
ArrayQueue(const ArrayQueue& other) : capacity_(other.capacity_) {
items_ = new T[capacity_];
for (size_t i = other.head_; i != other.tail_; ++i) {
enqueue(other.items_[i]);
}
}
ArrayQueue& operator=(const ArrayQueue& rhs) {
delete[] items_;
head_ = 0;
tail_ = 0;
capacity_ = rhs.capacity_;
items_ = new T[capacity_];
for (size_t i = rhs.head_; i != rhs.tail_; ++i) {
enqueue(rhs.items_[i]);
}
return *this;
}
ArrayQueue(ArrayQueue&& other) : items_(other.items_),
capacity_(other.capacity_),
head_(other.head_),
tail_(other.tail_) {
other.items_ = nullptr;
other.capacity_ = 0;
other.head_ = 0;
other.tail_ = 0;
}
ArrayQueue& operator=(ArrayQueue&& rhs) {
delete[] items_;
items_ = rhs.items_;
capacity_ = rhs.capacity_;
head_ = rhs.head_;
tail_ = rhs.tail_;
rhs.items_ = nullptr;
rhs.capacity_ = 0;
rhs.head_ = 0;
rhs.tail_ = 0;
return *this;
}
public:
void enqueue(T item) {
if (capacity_ == tail_) {
throw "Push data into a full queue!";
}
items_[tail_++] = item;
}
T head() const {
if (head_ != tail_) {
return items_[head_];
} else {
throw "Fetch data from an empty queue!";
}
}
void dequeue() {
if (head_ != tail_) {
++head_;
} else {
throw "Pop data from an empty queue!";
}
}
public:
template <typename UnaryFunc>
void traverse(UnaryFunc do_traverse) {
for (size_t i = head_; i != tail_; ++i) {
do_traverse(items_[i]);
}
}
};
#endif // QUEUE_ARRAY_QUEUE_HPP_
|
fix typo [other -> rhs].
|
[09_queue] fix typo [other -> rhs].
|
C++
|
apache-2.0
|
wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo,wangzheng0822/algo
|
a8d13f91083a6e99fd20228a4d5866f43987b298
|
Code/GraphMol/FileParsers/MolFileWriter.cpp
|
Code/GraphMol/FileParsers/MolFileWriter.cpp
|
// $Id$
//
// Copyright (C) 2003-2006 Rational Discovery LLC
//
// @@ All Rights Reserved @@
//
#include "FileParsers.h"
#include "MolFileStereochem.h"
#include <RDGeneral/Invariant.h>
#include <GraphMol/RDKitQueries.h>
#include <fstream>
namespace RDKit{
//*************************************
//
// Every effort has been made to adhere to MDL's standard
// for mol files
//
//*************************************
std::string AtomGetMolFileSymbol(const Atom *atom){
PRECONDITION(atom,"");
std::string res;
if(atom->getAtomicNum()){
res=atom->getSymbol();
} else {
if(!atom->hasProp("dummyLabel")){
res = "*";
} else {
std::string symb;
atom->getProp("dummyLabel",symb);
if(symb=="*") res="*";
else if(symb=="X") res="R";
else if(symb=="Xa") res="R1";
else if(symb=="Xb") res="R2";
else if(symb=="Xc") res="R3";
else if(symb=="Xd") res="R4";
else if(symb=="Xf") res="R5";
else if(symb=="Xg") res="R6";
else if(symb=="Xh") res="R7";
else if(symb=="Xi") res="R8";
else if(symb=="Xj") res="R9";
else res=symb;
}
}
// pad the end with spaces
while(res.size()<3) res += " ";
return res;
}
std::string GetMolFileAtomLine(const Atom *atom, const Conformer *conf=0){
PRECONDITION(atom,"");
std::string res;
char tmpStr[256];
int massDiff,chg,stereoCare,hCount,totValence,rxnComponentType;
int rxnComponentNumber,atomMapNumber,inversionFlag,exactChangeFlag;
massDiff=0;
chg=0;
stereoCare=0;
hCount=0;
totValence=0;
rxnComponentType=0;
rxnComponentNumber=0;
atomMapNumber=0;
inversionFlag=0;
exactChangeFlag=0;
double atomMassDiff=atom->getMass()-PeriodicTable::getTable()->getAtomicWeight(atom->getAtomicNum());
massDiff = static_cast<int>(atomMassDiff+.1);
if(atom->getFormalCharge()!=0){
switch(atom->getFormalCharge()){
case 1: chg=3;break;
case 2: chg=2;break;
case 3: chg=1;break;
case -1: chg=5;break;
case -2: chg=6;break;
case -3: chg=7;break;
default: chg=0;
}
}
double x, y, z;
x = y = z = 0.0;
if (conf) {
const RDGeom::Point3D pos = conf->getAtomPos(atom->getIdx());
x = pos.x; y = pos.y; z = pos.z;
}
std::string symbol = AtomGetMolFileSymbol(atom);
sprintf(tmpStr,"% 10.4f% 10.4f% 10.4f %3s% 2d% 3d 0% 3d% 3d% 3d 0% 3d% 3d% 3d% 3d% 3d",
x,y,z,
symbol.c_str(),
massDiff,chg,hCount,stereoCare,totValence,rxnComponentType,
rxnComponentNumber,atomMapNumber,inversionFlag,exactChangeFlag
);
res += tmpStr;
return res;
};
std::string BondGetMolFileSymbol(const Bond *bond){
PRECONDITION(bond,"");
// FIX: should eventually recognize queries
std::string res;
if(bond->getIsAromatic()){
res = " 4";
} else {
switch(bond->getBondType()){
case Bond::SINGLE: res=" 1";break;
case Bond::DOUBLE: res=" 2";break;
case Bond::TRIPLE: res=" 3";break;
case Bond::AROMATIC: res=" 4";break;
}
}
return res;
//return res.c_str();
}
// only valid for single bonds
int BondGetDirCode(const Bond::BondDir dir){
int res=0;
switch(dir){
case Bond::NONE: res=0;break;
case Bond::BEGINWEDGE: res=1;break;
case Bond::BEGINDASH: res=6;break;
case Bond::UNKNOWN: res=4;break;
default:
break;
}
return res;
}
std::string GetMolFileBondLine(const Bond *bond, const INT_MAP_INT &wedgeBonds,
const Conformer *conf){
PRECONDITION(bond,"");
std::string res;
char tmpStr[256];
std::string symbol = BondGetMolFileSymbol(bond);
int dirCode=0;
Bond::BondDir dir=Bond::NONE;
bool reverse = false;
if(bond->getBondType()==Bond::SINGLE){
// single bond stereo chemistry
dir = DetermineBondWedgeState(bond, wedgeBonds, conf);
dirCode = BondGetDirCode(dir);
// if this bond needs to be wedged it is possible that this wedgin was determined
// by a chiral at the end of bond (instead of at the beginning. In this case we
// to reverse the bond begin and end atoms for the bond when we write the
// mol file
if ((dirCode == 1) || (dirCode == 6)) {
INT_MAP_INT_CI wbi = wedgeBonds.find(bond->getIdx());
if (wbi->second != bond->getBeginAtomIdx()) {
reverse = true;
}
}
} else if (bond->getBondType()==Bond::DOUBLE) { // && (bond->hasProp("_CIPCode"))) {
// double bond stereo chemistry -
// we will worry about it only if it is "any"
Bond::BondStereo stType = bond->getStereo();
if (stType == Bond::STEREOANY) { //"A") {
dirCode = 3; // can be either cis/trans
}
}
if (reverse) {
// switch the begin and end atoms on the bond line
sprintf(tmpStr,"% 3d% 3d%s % 2d",bond->getEndAtomIdx()+1,
bond->getBeginAtomIdx()+1,
symbol.c_str(),dirCode);
} else {
sprintf(tmpStr,"% 3d% 3d%s % 2d",bond->getBeginAtomIdx()+1,
bond->getEndAtomIdx()+1,
symbol.c_str(),dirCode);
}
res = tmpStr;
return res;
}
//------------------------------------------------
//
// gets a mol block as a string
//
//------------------------------------------------
std::string MolToMolBlock(const ROMol &mol,bool includeStereo, int confId){
// NOTE: kekulize the molecule before writing it out
// because of the way mol files handle aroamticity
ROMol tromol(mol);
RWMol &trwmol = static_cast<RWMol &>(tromol);
MolOps::Kekulize(trwmol);
if(includeStereo){
// assign "any" status to any stereo bond that are not
// marked with "E" or "Z" code - these bonds need to be explictly written
// out to the mol file
MolOps::findPotentialStereoBonds(trwmol);
// now assign stereo code if any have been specified by the directions on
// single bonds
MolOps::assignBondStereoCodes(trwmol);
}
const RWMol &tmol = const_cast<RWMol &>(trwmol);
std::string res;
char tmpStr[256];
int nAtoms,nBonds,nLists,chiralFlag,nsText,nRxnComponents;
int nReactants,nProducts,nIntermediates;
nAtoms = tmol.getNumAtoms();
nBonds = tmol.getNumBonds();
nLists = 0;
chiralFlag = 0;
nsText=0;
nRxnComponents=0;
nReactants=0;
nProducts=0;
nIntermediates=0;
if(tmol.hasProp("_Name")){
std::string name;
tmol.getProp("_Name",name);
res += name;
}
res += "\n";
// info
if(tmol.hasProp("MolFileInfo")){
std::string info;
tmol.getProp("MolFileInfo",info);
res += info;
}
res += "\n";
// comments
if(tmol.hasProp("MolFileComments")){
std::string info;
tmol.getProp("MolFileComments",info);
res += info;
}
res += "\n";
sprintf(tmpStr,"% 3d% 3d% 3d 0% 3d% 3d% 3d% 3d% 3d% 3d999 V2000\n",
nAtoms,nBonds,nLists,chiralFlag,nsText,nRxnComponents,
nReactants,nProducts,nIntermediates);
res += tmpStr;
const Conformer *conf;
if(confId<0 && tmol.getNumConformers()==0){
conf=0;
} else {
conf = &(tmol.getConformer(confId));
}
ROMol::ConstAtomIterator atomIt;
for(atomIt=tmol.beginAtoms();atomIt!=tmol.endAtoms();atomIt++){
res += GetMolFileAtomLine(*atomIt, conf);
res += "\n";
}
INT_MAP_INT wedgeBonds = pickBondsToWedge(tmol);
ROMol::ConstBondIterator bondIt;
for(bondIt=tmol.beginBonds();bondIt!=tmol.endBonds();bondIt++){
res += GetMolFileBondLine(*bondIt, wedgeBonds, conf);
res += "\n";
}
// FIX: aliases, atom lists, etc.
res += "M END\n";
return res;
}
//------------------------------------------------
//
// Dump a molecule to a file
//
//------------------------------------------------
void MolToMolFile(const ROMol &mol,std::string fName,bool includeStereo, int confId){
std::ofstream *outStream = new std::ofstream(fName.c_str());
CHECK_INVARIANT(outStream&&!outStream->bad(),"could not open output file");
std::string outString = MolToMolBlock(mol,includeStereo, confId);
*outStream << outString;
delete outStream;
}
}
|
// $Id$
//
// Copyright (C) 2003-2006 Rational Discovery LLC
//
// @@ All Rights Reserved @@
//
#include "FileParsers.h"
#include "MolFileStereochem.h"
#include <RDGeneral/Invariant.h>
#include <GraphMol/RDKitQueries.h>
#include <fstream>
namespace RDKit{
//*************************************
//
// Every effort has been made to adhere to MDL's standard
// for mol files
//
//*************************************
std::string AtomGetMolFileSymbol(const Atom *atom){
PRECONDITION(atom,"");
std::string res;
if(atom->getAtomicNum()){
res=atom->getSymbol();
} else {
if(!atom->hasProp("dummyLabel")){
res = "*";
} else {
std::string symb;
atom->getProp("dummyLabel",symb);
if(symb=="*") res="*";
else if(symb=="X") res="R";
else if(symb=="Xa") res="R1";
else if(symb=="Xb") res="R2";
else if(symb=="Xc") res="R3";
else if(symb=="Xd") res="R4";
else if(symb=="Xf") res="R5";
else if(symb=="Xg") res="R6";
else if(symb=="Xh") res="R7";
else if(symb=="Xi") res="R8";
else if(symb=="Xj") res="R9";
else res=symb;
}
}
// pad the end with spaces
while(res.size()<3) res += " ";
return res;
}
std::string GetMolFileAtomLine(const Atom *atom, const Conformer *conf=0){
PRECONDITION(atom,"");
std::string res;
char tmpStr[256];
int massDiff,chg,stereoCare,hCount,totValence,rxnComponentType;
int rxnComponentNumber,atomMapNumber,inversionFlag,exactChangeFlag;
massDiff=0;
chg=0;
stereoCare=0;
hCount=0;
totValence=0;
rxnComponentType=0;
rxnComponentNumber=0;
atomMapNumber=0;
inversionFlag=0;
exactChangeFlag=0;
double atomMassDiff=atom->getMass()-PeriodicTable::getTable()->getAtomicWeight(atom->getAtomicNum());
massDiff = static_cast<int>(atomMassDiff+.1);
if(atom->getFormalCharge()!=0){
switch(atom->getFormalCharge()){
case 1: chg=3;break;
case 2: chg=2;break;
case 3: chg=1;break;
case -1: chg=5;break;
case -2: chg=6;break;
case -3: chg=7;break;
default: chg=0;
}
}
double x, y, z;
x = y = z = 0.0;
if (conf) {
const RDGeom::Point3D pos = conf->getAtomPos(atom->getIdx());
x = pos.x; y = pos.y; z = pos.z;
}
std::string symbol = AtomGetMolFileSymbol(atom);
sprintf(tmpStr,"% 10.4f% 10.4f% 10.4f %3s% 2d% 3d 0% 3d% 3d% 3d 0% 3d% 3d% 3d% 3d% 3d",
x,y,z,
symbol.c_str(),
massDiff,chg,hCount,stereoCare,totValence,rxnComponentType,
rxnComponentNumber,atomMapNumber,inversionFlag,exactChangeFlag
);
res += tmpStr;
return res;
};
std::string BondGetMolFileSymbol(const Bond *bond){
PRECONDITION(bond,"");
// FIX: should eventually recognize queries
std::string res;
if(bond->getIsAromatic()){
res = " 4";
} else {
switch(bond->getBondType()){
case Bond::SINGLE: res=" 1";break;
case Bond::DOUBLE: res=" 2";break;
case Bond::TRIPLE: res=" 3";break;
case Bond::AROMATIC: res=" 4";break;
default: res=" 0";break;
}
}
return res;
//return res.c_str();
}
// only valid for single bonds
int BondGetDirCode(const Bond::BondDir dir){
int res=0;
switch(dir){
case Bond::NONE: res=0;break;
case Bond::BEGINWEDGE: res=1;break;
case Bond::BEGINDASH: res=6;break;
case Bond::UNKNOWN: res=4;break;
default:
break;
}
return res;
}
std::string GetMolFileBondLine(const Bond *bond, const INT_MAP_INT &wedgeBonds,
const Conformer *conf){
PRECONDITION(bond,"");
std::string res;
char tmpStr[256];
std::string symbol = BondGetMolFileSymbol(bond);
int dirCode=0;
Bond::BondDir dir=Bond::NONE;
bool reverse = false;
if(bond->getBondType()==Bond::SINGLE){
// single bond stereo chemistry
dir = DetermineBondWedgeState(bond, wedgeBonds, conf);
dirCode = BondGetDirCode(dir);
// if this bond needs to be wedged it is possible that this wedgin was determined
// by a chiral at the end of bond (instead of at the beginning. In this case we
// to reverse the bond begin and end atoms for the bond when we write the
// mol file
if ((dirCode == 1) || (dirCode == 6)) {
INT_MAP_INT_CI wbi = wedgeBonds.find(bond->getIdx());
if (wbi->second != bond->getBeginAtomIdx()) {
reverse = true;
}
}
} else if (bond->getBondType()==Bond::DOUBLE) { // && (bond->hasProp("_CIPCode"))) {
// double bond stereo chemistry -
// we will worry about it only if it is "any"
Bond::BondStereo stType = bond->getStereo();
if (stType == Bond::STEREOANY) { //"A") {
dirCode = 3; // can be either cis/trans
}
}
if (reverse) {
// switch the begin and end atoms on the bond line
sprintf(tmpStr,"% 3d% 3d%s % 2d",bond->getEndAtomIdx()+1,
bond->getBeginAtomIdx()+1,
symbol.c_str(),dirCode);
} else {
sprintf(tmpStr,"% 3d% 3d%s % 2d",bond->getBeginAtomIdx()+1,
bond->getEndAtomIdx()+1,
symbol.c_str(),dirCode);
}
res = tmpStr;
return res;
}
//------------------------------------------------
//
// gets a mol block as a string
//
//------------------------------------------------
std::string MolToMolBlock(const ROMol &mol,bool includeStereo, int confId){
// NOTE: kekulize the molecule before writing it out
// because of the way mol files handle aroamticity
ROMol tromol(mol);
RWMol &trwmol = static_cast<RWMol &>(tromol);
MolOps::Kekulize(trwmol);
if(includeStereo){
// assign "any" status to any stereo bond that are not
// marked with "E" or "Z" code - these bonds need to be explictly written
// out to the mol file
MolOps::findPotentialStereoBonds(trwmol);
// now assign stereo code if any have been specified by the directions on
// single bonds
MolOps::assignBondStereoCodes(trwmol);
}
const RWMol &tmol = const_cast<RWMol &>(trwmol);
std::string res;
char tmpStr[256];
int nAtoms,nBonds,nLists,chiralFlag,nsText,nRxnComponents;
int nReactants,nProducts,nIntermediates;
nAtoms = tmol.getNumAtoms();
nBonds = tmol.getNumBonds();
nLists = 0;
chiralFlag = 0;
nsText=0;
nRxnComponents=0;
nReactants=0;
nProducts=0;
nIntermediates=0;
if(tmol.hasProp("_Name")){
std::string name;
tmol.getProp("_Name",name);
res += name;
}
res += "\n";
// info
if(tmol.hasProp("MolFileInfo")){
std::string info;
tmol.getProp("MolFileInfo",info);
res += info;
}
res += "\n";
// comments
if(tmol.hasProp("MolFileComments")){
std::string info;
tmol.getProp("MolFileComments",info);
res += info;
}
res += "\n";
sprintf(tmpStr,"% 3d% 3d% 3d 0% 3d% 3d% 3d% 3d% 3d% 3d999 V2000\n",
nAtoms,nBonds,nLists,chiralFlag,nsText,nRxnComponents,
nReactants,nProducts,nIntermediates);
res += tmpStr;
const Conformer *conf;
if(confId<0 && tmol.getNumConformers()==0){
conf=0;
} else {
conf = &(tmol.getConformer(confId));
}
ROMol::ConstAtomIterator atomIt;
for(atomIt=tmol.beginAtoms();atomIt!=tmol.endAtoms();atomIt++){
res += GetMolFileAtomLine(*atomIt, conf);
res += "\n";
}
INT_MAP_INT wedgeBonds = pickBondsToWedge(tmol);
ROMol::ConstBondIterator bondIt;
for(bondIt=tmol.beginBonds();bondIt!=tmol.endBonds();bondIt++){
res += GetMolFileBondLine(*bondIt, wedgeBonds, conf);
res += "\n";
}
// FIX: aliases, atom lists, etc.
res += "M END\n";
return res;
}
//------------------------------------------------
//
// Dump a molecule to a file
//
//------------------------------------------------
void MolToMolFile(const ROMol &mol,std::string fName,bool includeStereo, int confId){
std::ofstream *outStream = new std::ofstream(fName.c_str());
CHECK_INVARIANT(outStream&&!outStream->bad(),"could not open output file");
std::string outString = MolToMolBlock(mol,includeStereo, confId);
*outStream << outString;
delete outStream;
}
}
|
remove a compiler warning
|
remove a compiler warning
git-svn-id: 931ab4487dc05a11552de95f7d42b8249ade56b7@463 a5045d30-4826-4484-9c7f-6e55a06ddc77
|
C++
|
bsd-3-clause
|
rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig,rdkit/rdkit-orig
|
6e48b504572b90ef42e569efc5c1f624ed010a11
|
protocols/libwebqq/src/impl/webqq_login.cpp
|
protocols/libwebqq/src/impl/webqq_login.cpp
|
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <regex>
#include <cstdint>
#include <iterator>
#include <algorithm>
#include <openssl/md5.h>
#include <openssl/rsa.h>
#include <openssl/engine.h>
#include "webqq_login.hpp"
namespace webqq {
namespace qqimpl {
namespace detail {
/**
* I hacked the javascript file named comm.js, which received from tencent
* server, and find that fuck tencent has changed encryption algorithm
* for password in webqq3 . The new algorithm is below(descripted with javascript):
* var M=C.p.value; // M is the qq password
* var I=hexchar2bin(md5(M)); // Make a md5 digest
* var H=md5(I+pt.uin); // Make md5 with I and uin(see below)
* var G=md5(H+C.verifycode.value.toUpperCase());
*
* @param pwd User's password
* @param vc Verify Code. e.g. "!M6C"
* @param salt A string like "\x00\x00\x00\x00\x54\xb3\x3c\x53", NB: it
* must contain 8 hexadecimal number, in this example, it equaled
* to "0x0,0x0,0x0,0x0,0x54,0xb3,0x3c,0x53"
*
* @return Encoded password
*/
namespace {
inline void md5(const unsigned char *input, size_t ilen, unsigned char output[16])
{
MD5(input, ilen, output);
}
/*
* Encode a buffer into base64 format
*/
int base64_encode(unsigned char *dst, size_t *dlen,
const unsigned char *src, size_t slen)
{
static const unsigned char base64_enc_map[64] =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/'
};
size_t i, n;
int C1, C2, C3;
unsigned char *p;
if (slen == 0)
{
*dlen = 0;
return(0);
}
n = (slen << 3) / 6;
switch ((slen << 3) - (n * 6))
{
case 2: n += 3; break;
case 4: n += 2; break;
default: break;
}
if (*dlen < n + 1)
{
*dlen = n + 1;
return(-1);
}
n = (slen / 3) * 3;
for (i = 0, p = dst; i < n; i += 3)
{
C1 = *src++;
C2 = *src++;
C3 = *src++;
*p++ = base64_enc_map[(C1 >> 2) & 0x3F];
*p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];
*p++ = base64_enc_map[(((C2 & 15) << 2) + (C3 >> 6)) & 0x3F];
*p++ = base64_enc_map[C3 & 0x3F];
}
if (i < slen)
{
C1 = *src++;
C2 = ((i + 1) < slen) ? *src++ : 0;
*p++ = base64_enc_map[(C1 >> 2) & 0x3F];
*p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];
if ((i + 1) < slen)
*p++ = base64_enc_map[((C2 & 15) << 2) & 0x3F];
else *p++ = '=';
*p++ = '=';
}
*dlen = p - dst;
*p = 0;
return(0);
}
static int to_binary(const char * hex_string, unsigned char * output)
{
size_t len = strlen(hex_string);
if (len < 2 || (len % 2) != 0) {
return -1;
}
auto _Hex = [](int ch) -> int {
if (ch >= '0' && ch <= '9')
return ch - '0';
else if (ch >= 'A' && ch <= 'F')
return (ch - 'A' + 10);
else if (ch >= 'a' && ch <= 'f')
return (ch - 'a' + 10);
return (int)(-1);
};
for (size_t i = 0; i < len;) {
*output = _Hex(hex_string[i++]);
*output <<= 4;
*output |= _Hex(hex_string[i++]);
*output++;
}
return 0;
}
static void tea_encrypt_block(uint32_t plain[2], uint32_t key[4], uint32_t cipher[2])
{
auto _bswap = [](uint32_t x) -> uint32_t {
return (((x) >> 24) | (((x) >> 8) & 0xff00) | (((x) << 8) & 0xff0000) | ((x) << 24));
};
uint32_t delta = 0x9E3779B9, sum = 0;
uint32_t left = _bswap(plain[0]), right = _bswap(plain[1]);
uint32_t a = _bswap(key[0]), b = _bswap(key[1]), c = _bswap(key[2]), d = _bswap(key[3]);
int count = 16;
while (count--) {
sum += delta;
left += ((right << 4) + a) ^ (right + sum) ^ ((right >> 5) + b);
right += ((left << 4) + c) ^ (left + sum) ^ ((left >> 5) + d);
}
cipher[0] = _bswap(left);
cipher[1] = _bswap(right);
}
static int tea_encrypt(const unsigned char * input, size_t sz, unsigned char * key, unsigned char * cipher, size_t * outlen)
{
size_t bytes_pad;
size_t len;
unsigned char * plain = NULL;
int isHead = 1;
uint64_t pre_cipher = 0;
uint64_t * plain_ptr = NULL, *cipher_ptr = NULL;
bytes_pad = (sz + 10) % 8;
if (bytes_pad != 0){
bytes_pad = 8 - bytes_pad;
}
len = sz + 10 + bytes_pad;
if (!cipher || (*outlen < len)) {
*outlen = len;
return -1;
}
plain = (unsigned char *)malloc(len);
memset(plain, 0, len);
srand((unsigned int)time(NULL));
plain[0] = (rand() & 0xF8) | bytes_pad;
for (size_t i = 1; i <= (bytes_pad + 2); i++) {
plain[i] = rand() & 0xFF;
}
memcpy(&plain[bytes_pad + 3], input, sz);
plain_ptr = (uint64_t *)plain;
cipher_ptr = (uint64_t *)cipher;
for (size_t i = 0; i < len / 8; i++) {
uint64_t tmp;
if (isHead) {
plain_ptr[i] ^= 0; //
isHead = 0;
}
else {
plain_ptr[i] ^= cipher_ptr[i - 1];
}
tea_encrypt_block((uint32_t *)&plain_ptr[i], (uint32_t*)key, (uint32_t *)&tmp);
cipher_ptr[i] = tmp ^ pre_cipher;
pre_cipher = plain_ptr[i];
}
*outlen = len;
free(plain);
return 0;
}
static void tx_rsa_encrypt(const unsigned char * input, size_t sz, unsigned char output[128])
{
static const char N[] = "F20CE00BAE5361F8FA3AE9CEFA495362FF7DA1BA628F64A347F0A8C012BF0B254A30CD92ABFFE7A6EE0DC424CB6166F8819EFA5BCCB20EDFB4AD02E412CCF579B1CA711D55B8B0B3AEB60153D5E0693A2A86F3167D7847A0CB8B00004716A9095D9BADC977CBB804DBDCBA6029A9710869A453F27DFDDF83C016D928B3CBF4C7";
static const char E[] = "3";
RSA * rsa;
BIGNUM * bn, *be;
rsa = RSA_new();
bn = BN_new();
be = BN_new();
BN_hex2bn(&bn, N);
BN_hex2bn(&be, E);
rsa->n = bn;
rsa->e = be;
RSA_public_encrypt(sz, input, output, rsa, RSA_PKCS1_PADDING);
//BN_free(bn);
//BN_free(be);
RSA_free(rsa);
//rsa_context rsa;
//const char * pers = "rsa_encrypt";
//entropy_context entropy;
//ctr_drbg_context ctr_drbg;
//entropy_init(&entropy);
//ctr_drbg_init(&ctr_drbg, entropy_func, &entropy, (unsigned char*)pers, strlen(pers));
//rsa_init(&rsa, RSA_PKCS_V15, 0);
//mpi_read_string(&rsa.N, 16, N);
//mpi_read_string(&rsa.E, 16, E);
//rsa.len = (mpi_msb(&rsa.N) + 7) >> 3;
//rsa_pkcs1_encrypt(&rsa, ctr_drbg_random, &ctr_drbg, RSA_PUBLIC, sz,input, output);
//rsa_free(&rsa);
//ctr_drbg_free(&ctr_drbg);
//entropy_free(&entropy);
}
std::string tx_password_encrypt(const std::string& pwd, const std::string& captcha, const std::string& salt)
{
unsigned char md5_pwd[16] = { 0 };
unsigned char key_md5[16];
unsigned char key[24] = { 0 };
unsigned char cipher[512] = { 0 };
size_t sz = sizeof(cipher); //
char b64code[1024] = { 0 };
size_t b64_sz = sizeof(b64code);
struct
{
unsigned short len_rsa_md5_pwd;
unsigned char rsa_md5_pwd[128];
unsigned char salt[8]; //
unsigned short len_captcha; //4
char captcha[4];
} plain = { 0 };
plain.len_rsa_md5_pwd = 0x8000; // 128
plain.len_captcha = 0x0400; //4 验证码长度
memcpy(plain.captcha, captcha.c_str(), 4);
md5((unsigned char*)pwd.c_str(), pwd.length(), md5_pwd);
tx_rsa_encrypt(md5_pwd, 16, plain.rsa_md5_pwd);
//
to_binary(salt.c_str(), plain.salt);
memcpy(key, md5_pwd, 16);
memcpy(&key[16], plain.salt, 8);
md5(key, 24, key_md5);
//plain_hex = "0080" + to_hex_string(rsa_md5_pwd, 128) + salt + "0004" + to_hex_string((unsigned char *)vcode.c_str(),vcode.length());
tea_encrypt((unsigned char *)&plain, sizeof(plain), key_md5, cipher, &sz);
base64_encode((unsigned char*)b64code, &b64_sz, cipher, sz);
std::transform(b64code, b64code + b64_sz, b64code, [](int ch) ->int { if (ch == '/') return '-'; else if (ch == '+') return '*'; else if (ch == '=') return '_'; else return ch; });
return b64code;
}
}
std::string webqq_password_encode(const std::string& pwd, const std::string& vc, const std::string& salt)
{
return tx_password_encrypt(pwd, vc, boost::replace_all_copy(salt, "\\x", ""));
}
}
}
}
|
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <regex>
#include <cstdint>
#include <iterator>
#include <algorithm>
#include <openssl/md5.h>
#include <openssl/rsa.h>
#include "webqq_login.hpp"
namespace webqq {
namespace qqimpl {
namespace detail {
/**
* I hacked the javascript file named comm.js, which received from tencent
* server, and find that fuck tencent has changed encryption algorithm
* for password in webqq3 . The new algorithm is below(descripted with javascript):
* var M=C.p.value; // M is the qq password
* var I=hexchar2bin(md5(M)); // Make a md5 digest
* var H=md5(I+pt.uin); // Make md5 with I and uin(see below)
* var G=md5(H+C.verifycode.value.toUpperCase());
*
* @param pwd User's password
* @param vc Verify Code. e.g. "!M6C"
* @param salt A string like "\x00\x00\x00\x00\x54\xb3\x3c\x53", NB: it
* must contain 8 hexadecimal number, in this example, it equaled
* to "0x0,0x0,0x0,0x0,0x54,0xb3,0x3c,0x53"
*
* @return Encoded password
*/
namespace {
inline void md5(const unsigned char *input, size_t ilen, unsigned char output[16])
{
MD5(input, ilen, output);
}
/*
* Encode a buffer into base64 format
*/
int base64_encode(unsigned char *dst, size_t *dlen,
const unsigned char *src, size_t slen)
{
static const unsigned char base64_enc_map[64] =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/'
};
size_t i, n;
int C1, C2, C3;
unsigned char *p;
if (slen == 0)
{
*dlen = 0;
return(0);
}
n = (slen << 3) / 6;
switch ((slen << 3) - (n * 6))
{
case 2: n += 3; break;
case 4: n += 2; break;
default: break;
}
if (*dlen < n + 1)
{
*dlen = n + 1;
return(-1);
}
n = (slen / 3) * 3;
for (i = 0, p = dst; i < n; i += 3)
{
C1 = *src++;
C2 = *src++;
C3 = *src++;
*p++ = base64_enc_map[(C1 >> 2) & 0x3F];
*p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];
*p++ = base64_enc_map[(((C2 & 15) << 2) + (C3 >> 6)) & 0x3F];
*p++ = base64_enc_map[C3 & 0x3F];
}
if (i < slen)
{
C1 = *src++;
C2 = ((i + 1) < slen) ? *src++ : 0;
*p++ = base64_enc_map[(C1 >> 2) & 0x3F];
*p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];
if ((i + 1) < slen)
*p++ = base64_enc_map[((C2 & 15) << 2) & 0x3F];
else *p++ = '=';
*p++ = '=';
}
*dlen = p - dst;
*p = 0;
return(0);
}
static int to_binary(const char * hex_string, unsigned char * output)
{
size_t len = strlen(hex_string);
if (len < 2 || (len % 2) != 0) {
return -1;
}
auto _Hex = [](int ch) -> int {
if (ch >= '0' && ch <= '9')
return ch - '0';
else if (ch >= 'A' && ch <= 'F')
return (ch - 'A' + 10);
else if (ch >= 'a' && ch <= 'f')
return (ch - 'a' + 10);
return (int)(-1);
};
for (size_t i = 0; i < len;) {
*output = _Hex(hex_string[i++]);
*output <<= 4;
*output |= _Hex(hex_string[i++]);
*output++;
}
return 0;
}
static void tea_encrypt_block(uint32_t plain[2], uint32_t key[4], uint32_t cipher[2])
{
auto _bswap = [](uint32_t x) -> uint32_t {
return (((x) >> 24) | (((x) >> 8) & 0xff00) | (((x) << 8) & 0xff0000) | ((x) << 24));
};
uint32_t delta = 0x9E3779B9, sum = 0;
uint32_t left = _bswap(plain[0]), right = _bswap(plain[1]);
uint32_t a = _bswap(key[0]), b = _bswap(key[1]), c = _bswap(key[2]), d = _bswap(key[3]);
int count = 16;
while (count--) {
sum += delta;
left += ((right << 4) + a) ^ (right + sum) ^ ((right >> 5) + b);
right += ((left << 4) + c) ^ (left + sum) ^ ((left >> 5) + d);
}
cipher[0] = _bswap(left);
cipher[1] = _bswap(right);
}
static int tea_encrypt(const unsigned char * input, size_t sz, unsigned char * key, unsigned char * cipher, size_t * outlen)
{
size_t bytes_pad;
size_t len;
unsigned char * plain = NULL;
int isHead = 1;
uint64_t pre_cipher = 0;
uint64_t * plain_ptr = NULL, *cipher_ptr = NULL;
bytes_pad = (sz + 10) % 8;
if (bytes_pad != 0){
bytes_pad = 8 - bytes_pad;
}
len = sz + 10 + bytes_pad;
if (!cipher || (*outlen < len)) {
*outlen = len;
return -1;
}
plain = (unsigned char *)malloc(len);
memset(plain, 0, len);
srand((unsigned int)time(NULL));
plain[0] = (rand() & 0xF8) | bytes_pad;
for (size_t i = 1; i <= (bytes_pad + 2); i++) {
plain[i] = rand() & 0xFF;
}
memcpy(&plain[bytes_pad + 3], input, sz);
plain_ptr = (uint64_t *)plain;
cipher_ptr = (uint64_t *)cipher;
for (size_t i = 0; i < len / 8; i++) {
uint64_t tmp;
if (isHead) {
plain_ptr[i] ^= 0; //
isHead = 0;
}
else {
plain_ptr[i] ^= cipher_ptr[i - 1];
}
tea_encrypt_block((uint32_t *)&plain_ptr[i], (uint32_t*)key, (uint32_t *)&tmp);
cipher_ptr[i] = tmp ^ pre_cipher;
pre_cipher = plain_ptr[i];
}
*outlen = len;
free(plain);
return 0;
}
static void tx_rsa_encrypt(const unsigned char * input, size_t sz, unsigned char output[128])
{
static const char N[] = "F20CE00BAE5361F8FA3AE9CEFA495362FF7DA1BA628F64A347F0A8C012BF0B254A30CD92ABFFE7A6EE0DC424CB6166F8819EFA5BCCB20EDFB4AD02E412CCF579B1CA711D55B8B0B3AEB60153D5E0693A2A86F3167D7847A0CB8B00004716A9095D9BADC977CBB804DBDCBA6029A9710869A453F27DFDDF83C016D928B3CBF4C7";
static const char E[] = "3";
RSA * rsa;
BIGNUM * bn, *be;
rsa = RSA_new();
bn = BN_new();
be = BN_new();
BN_hex2bn(&bn, N);
BN_hex2bn(&be, E);
rsa->n = bn;
rsa->e = be;
RSA_public_encrypt(sz, input, output, rsa, RSA_PKCS1_PADDING);
//BN_free(bn);
//BN_free(be);
RSA_free(rsa);
//rsa_context rsa;
//const char * pers = "rsa_encrypt";
//entropy_context entropy;
//ctr_drbg_context ctr_drbg;
//entropy_init(&entropy);
//ctr_drbg_init(&ctr_drbg, entropy_func, &entropy, (unsigned char*)pers, strlen(pers));
//rsa_init(&rsa, RSA_PKCS_V15, 0);
//mpi_read_string(&rsa.N, 16, N);
//mpi_read_string(&rsa.E, 16, E);
//rsa.len = (mpi_msb(&rsa.N) + 7) >> 3;
//rsa_pkcs1_encrypt(&rsa, ctr_drbg_random, &ctr_drbg, RSA_PUBLIC, sz,input, output);
//rsa_free(&rsa);
//ctr_drbg_free(&ctr_drbg);
//entropy_free(&entropy);
}
std::string tx_password_encrypt(const std::string& pwd, const std::string& captcha, const std::string& salt)
{
unsigned char md5_pwd[16] = { 0 };
unsigned char key_md5[16];
unsigned char key[24] = { 0 };
unsigned char cipher[512] = { 0 };
size_t sz = sizeof(cipher); //
char b64code[1024] = { 0 };
size_t b64_sz = sizeof(b64code);
struct
{
unsigned short len_rsa_md5_pwd;
unsigned char rsa_md5_pwd[128];
unsigned char salt[8]; //
unsigned short len_captcha; //4
char captcha[4];
} plain = { 0 };
plain.len_rsa_md5_pwd = 0x8000; // 128
plain.len_captcha = 0x0400; //4 验证码长度
memcpy(plain.captcha, captcha.c_str(), 4);
md5((unsigned char*)pwd.c_str(), pwd.length(), md5_pwd);
tx_rsa_encrypt(md5_pwd, 16, plain.rsa_md5_pwd);
//
to_binary(salt.c_str(), plain.salt);
memcpy(key, md5_pwd, 16);
memcpy(&key[16], plain.salt, 8);
md5(key, 24, key_md5);
//plain_hex = "0080" + to_hex_string(rsa_md5_pwd, 128) + salt + "0004" + to_hex_string((unsigned char *)vcode.c_str(),vcode.length());
tea_encrypt((unsigned char *)&plain, sizeof(plain), key_md5, cipher, &sz);
base64_encode((unsigned char*)b64code, &b64_sz, cipher, sz);
std::transform(b64code, b64code + b64_sz, b64code, [](int ch) ->int { if (ch == '/') return '-'; else if (ch == '+') return '*'; else if (ch == '=') return '_'; else return ch; });
return b64code;
}
}
std::string webqq_password_encode(const std::string& pwd, const std::string& vc, const std::string& salt)
{
return tx_password_encrypt(pwd, vc, boost::replace_all_copy(salt, "\\x", ""));
}
}
}
}
|
fix for engine.h
|
fix for engine.h
|
C++
|
agpl-3.0
|
avplayer/avbot,upsoft/avbot,upsoft/avbot,upsoft/avbot,upsoft/avbot,stone-jin/avbot,stone-jin/avbot,avplayer/avbot,stone-jin/avbot,upsoft/avbot,avplayer/avbot,avplayer/avbot,stone-jin/avbot,stone-jin/avbot,avplayer/avbot
|
4fc016d1d38849030d46864f298c6a8f1f4da6ad
|
Core/DataStructures/mitkPropertyManager.cpp
|
Core/DataStructures/mitkPropertyManager.cpp
|
#include "mitkPropertyManager.h"
#include "mitkBoolProperty.h"
mitk::PropertyManager::PropertyManager() {
std::cout << "ctor PropertyManager" << std::endl;
m_DefaultPropertyNameSet.insert(std::string("visible"));
}
const mitk::PropertyManager::PropertyNameSet& mitk::PropertyManager::GetDefaultPropertyNames() {
static mitk::PropertyManager propManager;
return propManager.m_DefaultPropertyNameSet;
};
mitk::BaseProperty::Pointer mitk::PropertyManager::CreateDefaultProperty(std::string name) {
mitk::BaseProperty::Pointer newProperty(NULL);
if ( name == "visible" ) {
newProperty = new mitk::BoolProperty(true);
} else {
std::cout << "Warning: non-existing default property requested: "
<< name << std::endl;
}
return newProperty;
};
|
#include "mitkPropertyManager.h"
#include "mitkProperties.h"
mitk::PropertyManager::PropertyManager() {
std::cout << "ctor PropertyManager" << std::endl;
m_DefaultPropertyNameSet.insert(std::string("visible"));
}
const mitk::PropertyManager::PropertyNameSet& mitk::PropertyManager::GetDefaultPropertyNames() {
static mitk::PropertyManager propManager;
return propManager.m_DefaultPropertyNameSet;
};
mitk::BaseProperty::Pointer mitk::PropertyManager::CreateDefaultProperty(std::string name) {
mitk::BaseProperty::Pointer newProperty(NULL);
if ( name == "visible" ) {
newProperty = new mitk::BoolProperty(true);
} else {
std::cout << "Warning: non-existing default property requested: "
<< name << std::endl;
}
return newProperty;
};
|
fix mitkBoolProperty
|
fix mitkBoolProperty
|
C++
|
bsd-3-clause
|
lsanzdiaz/MITK-BiiG,fmilano/mitk,lsanzdiaz/MITK-BiiG,danielknorr/MITK,fmilano/mitk,fmilano/mitk,RabadanLab/MITKats,iwegner/MITK,rfloca/MITK,MITK/MITK,nocnokneo/MITK,NifTK/MITK,NifTK/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,RabadanLab/MITKats,MITK/MITK,iwegner/MITK,nocnokneo/MITK,danielknorr/MITK,nocnokneo/MITK,rfloca/MITK,iwegner/MITK,RabadanLab/MITKats,danielknorr/MITK,MITK/MITK,fmilano/mitk,nocnokneo/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,RabadanLab/MITKats,MITK/MITK,rfloca/MITK,iwegner/MITK,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,rfloca/MITK,fmilano/mitk,danielknorr/MITK,rfloca/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,NifTK/MITK,MITK/MITK,fmilano/mitk,RabadanLab/MITKats,nocnokneo/MITK,NifTK/MITK,danielknorr/MITK,iwegner/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,fmilano/mitk,rfloca/MITK,nocnokneo/MITK,rfloca/MITK,iwegner/MITK,nocnokneo/MITK
|
703f126af719266709ae9d832ce16812b5dc7193
|
src/camera/ofStableCam.cpp
|
src/camera/ofStableCam.cpp
|
#include "ofStableCam.h"
#include "ofMath.h"
#include "ofUtils.h"
// #include <iostream>
// when an ofStableCam is moving due to momentum, this keeps it
// from moving forever by assuming small values are zero.
float minDifference = 0.1e-5f;
// this is the default on windows os
unsigned long doubleclickTime = 200;
//----------------------------------------
ofStableCam::ofStableCam() : up(0, 0, 1){
lastTap = 0;
lastDistance = 0;
drag = 0.9f;
sensitivityRot = 1.0f;//when 1 moving the mouse from one side to the other of the arcball (min(viewport.width, viewport.height)) will rotate 180degrees. when .5, 90 degrees.
sensitivityXY = .5f;
sensitivityZ= .7f;
bDistanceSet = false;
bMouseInputEnabled = false;
bDoRotate = false;
bApplyInertia =false;
bDoTranslate = false;
bInsideArcball = true;
bValidClick = false;
bEnableMouseMiddleButton = true;
bAutoDistance = true;
doTranslationKey = 'm';
reset();
enableMouseInput();
}
//----------------------------------------
ofStableCam::~ofStableCam(){
disableMouseInput();
}
//----------------------------------------
void ofStableCam::update(ofEventArgs & args){
if(!bDistanceSet && bAutoDistance){
setDistance(getImagePlaneDistance(viewport), true);
}
if(bMouseInputEnabled){
rotationFactor = sensitivityRot * 180 / min(viewport.width, viewport.height);
if (bMouseInputEnabled) {
updateMouse();
}
if (bDoRotate) {
updateRotation();
}else if (bDoTranslate) {
updateTranslation();
}
}
}
//----------------------------------------
void ofStableCam::begin(ofRectangle viewport){
fixUp();
this->viewport = viewport;
ofCamera::begin(viewport);
}
//----------------------------------------
void ofStableCam::reset(){
target.resetTransform();
/*
target.setPosition(0,0, 0);
lookAt(target);
resetTransform();
setPosition(0, 0, lastDistance);
*/
xRot = 0;
yRot = 0;
zRot = 0;
moveX = 0;
moveY = 0;
moveZ = 0;
enableMouseMiddleButton();
setDistance(13.0f);
setNearClip(0.1f);
setUp(ofVec3f(0.0f, 0.0f, 1.0f));
setPosition(0, -10.0f, 3.0f);
setTarget(ofVec3f(0.0f, 0.0f, 0.0f));
}
/**
* Fix the camera to have ${up} as up vector all the time
*/
void ofStableCam::fixUp(){
// do not fix while translating as there is no rotation change => no change for up
// if(ofGetMousePressed(OF_MOUSE_BUTTON_MIDDLE)) return;
// reset up direction unless we're perpendicular to it
float angleZUp = getUpDir().dot(up);
if(angleZUp > 1e-4f){
ofVec3f camPos = getPosition();
// ofVec3f trgPos = getTarget().getPosition();
lookAt(getTarget(), up);
setPosition(camPos);
//setTarget(trgPos);
}
}
//----------------------------------------
void ofStableCam::setTarget(const ofVec3f& targetPoint){
target.setPosition(targetPoint);
lookAt(target);
}
//----------------------------------------
void ofStableCam::setTarget(ofNode& targetNode){
target = targetNode;
lookAt(target);
}
//----------------------------------------
ofNode& ofStableCam::getTarget(){
return target;
}
//----------------------------------------
void ofStableCam::setUp(const ofVec3f& u){
up = u;
}
//----------------------------------------
const ofVec3f& ofStableCam::getUp() const{
return up;
}
//----------------------------------------
void ofStableCam::setDistance(float distance){
setDistance(distance, true);
}
//----------------------------------------
void ofStableCam::setDistance(float distance, bool save){//should this be the distance from the camera to the target?
if (distance > 0.0f){
if(save){
this->lastDistance = distance;
}
setPosition(target.getPosition() + (distance * getZAxis()));
bDistanceSet = true;
}
}
//----------------------------------------
float ofStableCam::getDistance() const {
return target.getPosition().distance(getPosition());
}
//----------------------------------------
void ofStableCam::setAutoDistance(bool bAutoDistance){
this->bAutoDistance = bAutoDistance;
if (bAutoDistance) {
bDistanceSet = false;
}
}
//----------------------------------------
void ofStableCam::setDrag(float drag){
this->drag = drag;
}
//----------------------------------------
float ofStableCam::getDrag() const {
return drag;
}
//----------------------------------------
void ofStableCam::setTranslationKey(char key){
doTranslationKey = key;
}
//----------------------------------------
char ofStableCam::getTranslationKey(){
return doTranslationKey;
}
//----------------------------------------
void ofStableCam::enableMouseInput(){
if(!bMouseInputEnabled){
bMouseInputEnabled = true;
// ofRegisterMouseEvents(this);
ofAddListener(ofEvents().update , this, &ofStableCam::update);
}
}
//----------------------------------------
void ofStableCam::disableMouseInput(){
if(bMouseInputEnabled){
bMouseInputEnabled = false;
//ofUnregisterMouseEvents(this);
ofRemoveListener(ofEvents().update, this, &ofStableCam::update);
}
}
//----------------------------------------
bool ofStableCam::getMouseInputEnabled(){
return bMouseInputEnabled;
}
//----------------------------------------
void ofStableCam::enableMouseMiddleButton(){
bEnableMouseMiddleButton = true;
}
//----------------------------------------
void ofStableCam::disableMouseMiddleButton(){
bEnableMouseMiddleButton = false;
}
//----------------------------------------
bool ofStableCam::getMouseMiddleButtonEnabled(){
return bEnableMouseMiddleButton;
}
//----------------------------------------
void ofStableCam::updateTranslation(){
if (bApplyInertia) {
moveX *= drag;
moveY *= drag;
moveZ *= drag;
if (ABS(moveX) <= minDifference && ABS(moveY) <= minDifference && ABS(moveZ) <= minDifference) {
bApplyInertia = false;
bDoTranslate = false;
}
}
ofVec3f delta = (getXAxis() * moveX) + (getYAxis() * moveY) + (getZAxis() * moveZ);
// stable movement => move both position and target
target.move(delta);
move(delta);
}
//----------------------------------------
void ofStableCam::updateRotation(){
if (bApplyInertia) {
xRot *=drag;
yRot *=drag;
zRot *=drag;
if (ABS(xRot) <= minDifference && ABS(yRot) <= minDifference && ABS(zRot) <= minDifference) {
bApplyInertia = false;
bDoRotate = false;
}
}
curRot = ofQuaternion(xRot, ofCamera::getXAxis(), yRot, ofCamera::getYAxis(), zRot, ofCamera::getZAxis());
setPosition((ofCamera::getGlobalPosition()-target.getGlobalPosition())*curRot +target.getGlobalPosition());
rotate(curRot);
}
//----------------------------------------
void ofStableCam::updateMouse(){
mouse = ofVec2f(ofGetMouseX(), ofGetMouseY());
if(viewport.inside(mouse.x, mouse.y) && !bValidClick && ofGetMousePressed()){
unsigned long curTap = ofGetElapsedTimeMillis();
if(lastTap != 0 && curTap - lastTap < doubleclickTime){
reset();
}
if ((bEnableMouseMiddleButton && ofGetMousePressed(OF_MOUSE_BUTTON_MIDDLE)) || ofGetKeyPressed(doTranslationKey) || ofGetMousePressed(OF_MOUSE_BUTTON_RIGHT)){
bDoTranslate = true;
bDoRotate = false;
bApplyInertia = false;
}else if (ofGetMousePressed(OF_MOUSE_BUTTON_LEFT)) {
bDoTranslate = false;
bDoRotate = true;
bApplyInertia = false;
if(ofVec2f(mouse.x - viewport.x - (viewport.width/2), mouse.y - viewport.y - (viewport.height/2)).length() < min(viewport.width/2, viewport.height/2)){
bInsideArcball = true;
}else {
bInsideArcball = false;
}
}
lastTap = curTap;
//lastMouse = ofVec2f(ofGetPreviousMouseX(),ofGetPreviousMouseY()); //this was causing the camera to have a tiny "random" rotation when clicked.
lastMouse = mouse;
bValidClick = true;
bApplyInertia = false;
}
if (bValidClick) {
if (!ofGetMousePressed()) {
bApplyInertia = true;
bValidClick = false;
}else {
int vFlip;
if(isVFlipped()){
vFlip = -1;
}else{
vFlip = 1;
}
mouseVel = mouse - lastMouse;
if (bDoTranslate) {
moveX = 0;
moveY = 0;
moveZ = 0;
if (ofGetMousePressed(OF_MOUSE_BUTTON_RIGHT)) {
moveZ = mouseVel.y * sensitivityZ * (getDistance() + FLT_EPSILON)/ viewport.height;
}else {
moveX = -mouseVel.x * sensitivityXY * (getDistance() + FLT_EPSILON)/viewport.width;
moveY = vFlip * mouseVel.y * sensitivityXY * (getDistance() + FLT_EPSILON)/viewport.height;
}
}else {
xRot = 0;
yRot = 0;
zRot = 0;
if (bInsideArcball) {
xRot = vFlip * -mouseVel.y * rotationFactor;
yRot = -mouseVel.x * rotationFactor;
}else {
ofVec2f center(viewport.width/2, viewport.height/2);
zRot = - vFlip * ofVec2f(mouse.x - viewport.x - center.x, mouse.y - viewport.y - center.y).angle(lastMouse - ofVec2f(viewport.x, viewport.y) - center);
}
}
lastMouse = mouse;
}
}
}
|
#include "ofStableCam.h"
#include "ofMath.h"
#include "ofUtils.h"
// #include <iostream>
// when an ofStableCam is moving due to momentum, this keeps it
// from moving forever by assuming small values are zero.
float minDifference = 0.1e-5f;
// this is the default on windows os
unsigned long doubleclickTime = 200;
//----------------------------------------
ofStableCam::ofStableCam() : up(0, 0, 1){
lastTap = 0;
lastDistance = 0;
drag = 0.9f;
sensitivityRot = 1.0f;//when 1 moving the mouse from one side to the other of the arcball (min(viewport.width, viewport.height)) will rotate 180degrees. when .5, 90 degrees.
sensitivityXY = .5f;
sensitivityZ= .7f;
bDistanceSet = false;
bMouseInputEnabled = false;
bDoRotate = false;
bApplyInertia =false;
bDoTranslate = false;
bInsideArcball = true;
bValidClick = false;
bEnableMouseMiddleButton = true;
bAutoDistance = true;
doTranslationKey = 'm';
reset();
enableMouseInput();
}
//----------------------------------------
ofStableCam::~ofStableCam(){
disableMouseInput();
}
//----------------------------------------
void ofStableCam::update(ofEventArgs & args){
if(!bDistanceSet && bAutoDistance){
setDistance(getImagePlaneDistance(viewport), true);
}
if(bMouseInputEnabled){
rotationFactor = sensitivityRot * 180 / min(viewport.width, viewport.height);
if (bMouseInputEnabled) {
updateMouse();
}
if (bDoRotate) {
updateRotation();
}else if (bDoTranslate) {
updateTranslation();
}
}
}
//----------------------------------------
void ofStableCam::begin(ofRectangle viewport){
fixUp();
this->viewport = viewport;
ofCamera::begin(viewport);
}
//----------------------------------------
void ofStableCam::reset(){
target.resetTransform();
/*
target.setPosition(0,0, 0);
lookAt(target);
resetTransform();
setPosition(0, 0, lastDistance);
*/
xRot = 0;
yRot = 0;
zRot = 0;
moveX = 0;
moveY = 0;
moveZ = 0;
enableMouseMiddleButton();
setDistance(13.0f);
setNearClip(0.1f);
setUp(ofVec3f(0.0f, 0.0f, 1.0f));
setPosition(0, -10.0f, 3.0f);
setTarget(ofVec3f(0.0f, 0.0f, 0.0f));
}
/**
* Fix the camera to have ${up} as up vector all the time
*/
void ofStableCam::fixUp(){
// do not fix while translating as there is no rotation change => no change for up
// if(ofGetMousePressed(OF_MOUSE_BUTTON_MIDDLE)) return;
// reset up direction unless we're perpendicular to it
float angleZUp = getUpDir().dot(up);
if(angleZUp > 1e-4f){
ofVec3f camPos = getPosition();
// ofVec3f trgPos = getTarget().getPosition();
lookAt(getTarget(), up);
setPosition(camPos);
//setTarget(trgPos);
}
}
//----------------------------------------
void ofStableCam::setTarget(const ofVec3f& targetPoint){
target.setPosition(targetPoint);
lookAt(target);
}
//----------------------------------------
void ofStableCam::setTarget(ofNode& targetNode){
target = targetNode;
lookAt(target);
}
//----------------------------------------
ofNode& ofStableCam::getTarget(){
return target;
}
//----------------------------------------
void ofStableCam::setUp(const ofVec3f& u){
up = u;
}
//----------------------------------------
const ofVec3f& ofStableCam::getUp() const{
return up;
}
//----------------------------------------
void ofStableCam::setDistance(float distance){
setDistance(distance, true);
}
//----------------------------------------
void ofStableCam::setDistance(float distance, bool save){//should this be the distance from the camera to the target?
if (distance > 0.0f){
if(save){
this->lastDistance = distance;
}
setPosition(target.getPosition() + (distance * getZAxis()));
bDistanceSet = true;
}
}
//----------------------------------------
float ofStableCam::getDistance() const {
return target.getPosition().distance(getPosition());
}
//----------------------------------------
void ofStableCam::setAutoDistance(bool bAutoDistance){
this->bAutoDistance = bAutoDistance;
if (bAutoDistance) {
bDistanceSet = false;
}
}
//----------------------------------------
void ofStableCam::setDrag(float drag){
this->drag = drag;
}
//----------------------------------------
float ofStableCam::getDrag() const {
return drag;
}
//----------------------------------------
void ofStableCam::setTranslationKey(char key){
doTranslationKey = key;
}
//----------------------------------------
char ofStableCam::getTranslationKey(){
return doTranslationKey;
}
//----------------------------------------
void ofStableCam::enableMouseInput(){
if(!bMouseInputEnabled){
bMouseInputEnabled = true;
// ofRegisterMouseEvents(this);
ofAddListener(ofEvents().update , this, &ofStableCam::update);
}
}
//----------------------------------------
void ofStableCam::disableMouseInput(){
if(bMouseInputEnabled){
bMouseInputEnabled = false;
//ofUnregisterMouseEvents(this);
ofRemoveListener(ofEvents().update, this, &ofStableCam::update);
}
}
//----------------------------------------
bool ofStableCam::getMouseInputEnabled(){
return bMouseInputEnabled;
}
//----------------------------------------
void ofStableCam::enableMouseMiddleButton(){
bEnableMouseMiddleButton = true;
}
//----------------------------------------
void ofStableCam::disableMouseMiddleButton(){
bEnableMouseMiddleButton = false;
}
//----------------------------------------
bool ofStableCam::getMouseMiddleButtonEnabled(){
return bEnableMouseMiddleButton;
}
//----------------------------------------
void ofStableCam::updateTranslation(){
if (bApplyInertia) {
moveX *= drag;
moveY *= drag;
moveZ *= drag;
if (ABS(moveX) <= minDifference && ABS(moveY) <= minDifference && ABS(moveZ) <= minDifference) {
bApplyInertia = false;
bDoTranslate = false;
}
}
ofVec3f deltaXY = getXAxis() * moveX + getYAxis() * moveY;
ofVec3f deltaZ = getZAxis() * moveZ;
// stable movement => move both position and target
target.move(deltaXY);
move(deltaXY + deltaZ);
}
//----------------------------------------
void ofStableCam::updateRotation(){
if (bApplyInertia) {
xRot *=drag;
yRot *=drag;
zRot *=drag;
if (ABS(xRot) <= minDifference && ABS(yRot) <= minDifference && ABS(zRot) <= minDifference) {
bApplyInertia = false;
bDoRotate = false;
}
}
curRot = ofQuaternion(xRot, ofCamera::getXAxis(), yRot, ofCamera::getYAxis(), zRot, ofCamera::getZAxis());
setPosition((ofCamera::getGlobalPosition()-target.getGlobalPosition())*curRot +target.getGlobalPosition());
rotate(curRot);
}
//----------------------------------------
void ofStableCam::updateMouse(){
mouse = ofVec2f(ofGetMouseX(), ofGetMouseY());
if(viewport.inside(mouse.x, mouse.y) && !bValidClick && ofGetMousePressed()){
unsigned long curTap = ofGetElapsedTimeMillis();
if(lastTap != 0 && curTap - lastTap < doubleclickTime){
reset();
}
if ((bEnableMouseMiddleButton && ofGetMousePressed(OF_MOUSE_BUTTON_MIDDLE)) || ofGetKeyPressed(doTranslationKey) || ofGetMousePressed(OF_MOUSE_BUTTON_RIGHT)){
bDoTranslate = true;
bDoRotate = false;
bApplyInertia = false;
}else if (ofGetMousePressed(OF_MOUSE_BUTTON_LEFT)) {
bDoTranslate = false;
bDoRotate = true;
bApplyInertia = false;
if(ofVec2f(mouse.x - viewport.x - (viewport.width/2), mouse.y - viewport.y - (viewport.height/2)).length() < min(viewport.width/2, viewport.height/2)){
bInsideArcball = true;
}else {
bInsideArcball = false;
}
}
lastTap = curTap;
//lastMouse = ofVec2f(ofGetPreviousMouseX(),ofGetPreviousMouseY()); //this was causing the camera to have a tiny "random" rotation when clicked.
lastMouse = mouse;
bValidClick = true;
bApplyInertia = false;
}
if (bValidClick) {
if (!ofGetMousePressed()) {
bApplyInertia = true;
bValidClick = false;
}else {
int vFlip;
if(isVFlipped()){
vFlip = -1;
}else{
vFlip = 1;
}
mouseVel = mouse - lastMouse;
if (bDoTranslate) {
moveX = 0;
moveY = 0;
moveZ = 0;
if (ofGetMousePressed(OF_MOUSE_BUTTON_RIGHT)) {
moveZ = mouseVel.y * sensitivityZ * (getDistance() + FLT_EPSILON)/ viewport.height;
}else {
moveX = -mouseVel.x * sensitivityXY * (getDistance() + FLT_EPSILON)/viewport.width;
moveY = vFlip * mouseVel.y * sensitivityXY * (getDistance() + FLT_EPSILON)/viewport.height;
}
}else {
xRot = 0;
yRot = 0;
zRot = 0;
if (bInsideArcball) {
xRot = vFlip * -mouseVel.y * rotationFactor;
yRot = -mouseVel.x * rotationFactor;
}else {
ofVec2f center(viewport.width/2, viewport.height/2);
zRot = - vFlip * ofVec2f(mouse.x - viewport.x - center.x, mouse.y - viewport.y - center.y).angle(lastMouse - ofVec2f(viewport.x, viewport.y) - center);
}
}
lastMouse = mouse;
}
}
}
|
Fix z-axis movement update (should only impact camera, not target)
|
Fix z-axis movement update (should only impact camera, not target)
|
C++
|
mpl-2.0
|
xionluhnis/risepath
|
6b96cf68f1e243779d51d2217b2c746c862894fe
|
src/chemkit/pluginmanager.cpp
|
src/chemkit/pluginmanager.cpp
|
/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <[email protected]>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** 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 chemkit project 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 "pluginmanager.h"
#include <map>
#include <cstdlib>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include "plugin.h"
#include "foreach.h"
#include "dynamiclibrary.h"
namespace chemkit {
// === PluginManagerPrivate ================================================ //
class PluginManagerPrivate
{
public:
std::vector<Plugin *> plugins;
std::string errorString;
bool defaultPluginsLoaded;
std::map<std::string, std::map<std::string, PluginManager::Function> > pluginClasses;
};
// === PluginManager ======================================================= //
/// \class PluginManager pluginmanager.h chemkit/pluginmanager.h
/// \ingroup chemkit
/// \brief The PluginManager class manages the loading and unloading
/// of plugins.
///
/// \see Plugin
// --- Construction and Destruction ---------------------------------------- //
PluginManager::PluginManager()
: d(new PluginManagerPrivate)
{
d->defaultPluginsLoaded = false;
}
PluginManager::~PluginManager()
{
foreach(Plugin *plugin, d->plugins){
delete plugin;
}
delete d;
}
// --- Properties ---------------------------------------------------------- //
/// Returns the plugin with \p name. Returns \c 0 if no plugin with
// \p name is loaded.
Plugin* PluginManager::plugin(const std::string &name) const
{
foreach(Plugin *plugin, d->plugins){
if(plugin->name() == name){
return plugin;
}
}
return 0;
}
/// Returns a list of all the loaded plugins.
const std::vector<Plugin *>& PluginManager::plugins() const
{
return d->plugins;
}
/// Returns the number of loaded plugins.
int PluginManager::pluginCount() const
{
return d->plugins.size();
}
// --- Plugin Loading ------------------------------------------------------ //
/// Loads a plugin from \p fileName. Returns \c false if an error
/// occurs.
bool PluginManager::loadPlugin(const std::string &fileName)
{
DynamicLibrary *library = new DynamicLibrary;
library->setFileName(fileName);
bool ok = library->open();
if(!ok){
std::cerr << "PluginManager: Error: Failed to load plugin: (" << fileName << "):"
<< library->errorString() << std::endl;
return false;
}
typedef Plugin* (*InitFunction)();
InitFunction initFunction = reinterpret_cast<InitFunction>(library->resolve("chemkit_plugin_init"));
if(!initFunction){
std::cerr << "PluginManager: Error: Failed to load plugin: (" << fileName << "):"
<< "Plugin contains no init() function." << std::endl;
return false;
}
Plugin *plugin = initFunction();
if(!plugin){
std::cerr << "PluginManager: Error: Failed to load plugin: (" << fileName << "):"
<< "Calling the plugin's init() function failed." << std::endl;
return false;
}
plugin->setLibrary(library);
d->plugins.push_back(plugin);
return true;
}
/// Loads all plugins from \p directory.
void PluginManager::loadPlugins(const std::string &directory)
{
boost::filesystem::path dir(directory);
if(!boost::filesystem::exists(dir)){
return;
}
for(boost::filesystem::directory_iterator iter(dir); iter != boost::filesystem::directory_iterator(); ++iter){
std::string fileName = boost::filesystem::path(iter->path().filename()).string();
if(DynamicLibrary::isLibrary(fileName)){
loadPlugin(iter->path().string());
}
}
}
void PluginManager::loadDefaultPlugins()
{
if(d->defaultPluginsLoaded){
return;
}
// list of directories to load plugins from
std::vector<std::string> directories;
// add default plugin directory
#if defined(CHEMKIT_OS_LINUX)
directories.push_back(CHEMKIT_INSTALL_PREFIX "/share/chemkit/plugins/");
#endif
// add directory from the CHEMKIT_PLUGIN_PATH environment variable
const char *path = getenv("CHEMKIT_PLUGIN_PATH");
if(path){
directories.push_back(path);
}
// load plugins from each directory
foreach(const std::string &directory, directories){
loadPlugins(directory);
}
d->defaultPluginsLoaded = true;
}
/// Unloads the plugin.
bool PluginManager::unloadPlugin(Plugin *plugin)
{
if(!plugin){
return false;
}
d->plugins.erase(std::remove(d->plugins.begin(), d->plugins.end(), plugin));
delete plugin->library();
delete plugin;
return true;
}
/// Unloads the plugin with \p name.
bool PluginManager::unloadPlugin(const std::string &name)
{
return unloadPlugin(plugin((name)));
}
// --- Error Handling ------------------------------------------------------ //
void PluginManager::setErrorString(const std::string &errorString)
{
d->errorString = errorString;
}
/// Returns a string describing the last error that occured.
std::string PluginManager::errorString() const
{
return d->errorString;
}
// --- Static Methods ------------------------------------------------------ //
/// Returns the instance of the plugin manager.
PluginManager* PluginManager::instance()
{
static PluginManager singleton;
return &singleton;
}
// --- Internal Methods ---------------------------------------------------- //
/// Registers a new plugin function for \p className and
/// \p pluginName.
bool PluginManager::registerPluginClass(const std::string &className, const std::string &pluginName, Function function)
{
std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
// use lower case plugin name
std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);
// prevent overwriting of previously registered plugins
if(classPlugins.find(lowerCasePluginName) != classPlugins.end()){
return false;
}
// add plugin class
classPlugins[lowerCasePluginName] = function;
return true;
}
/// Unregisters a plugin function for \p className and \p pluginName.
bool PluginManager::unregisterPluginClass(const std::string &className, const std::string &pluginName)
{
std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
// use lower case plugin name
std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);
// remove plugin class
return classPlugins.erase(lowerCasePluginName) > 0;
}
/// Returns a vector of strings containing the names of registered
/// plugins for \p className.
std::vector<std::string> PluginManager::pluginClassNames(const std::string &className) const
{
// ensure default plugins are loaded
const_cast<PluginManager *>(this)->loadDefaultPlugins();
const std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
std::vector<std::string> names;
for(std::map<std::string, Function>::const_iterator i = classPlugins.begin(); i != classPlugins.end(); ++i){
names.push_back(i->first);
}
return names;
}
/// Returns the registered function for the given \p className and \p pluginName.
PluginManager::Function PluginManager::pluginClassFunction(const std::string &className, const std::string &pluginName) const
{
// ensure default plugins are loaded
const_cast<PluginManager *>(this)->loadDefaultPlugins();
// use lower case plugin name
std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);
const std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
std::map<std::string, Function>::const_iterator location = classPlugins.find(lowerCasePluginName);
if(location == classPlugins.end()){
return 0;
}
return location->second;
}
} // end chemkit namespace
|
/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <[email protected]>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** 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 chemkit project 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 "pluginmanager.h"
#include <map>
#include <cstdlib>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include "plugin.h"
#include "foreach.h"
#include "dynamiclibrary.h"
namespace chemkit {
// === PluginManagerPrivate ================================================ //
class PluginManagerPrivate
{
public:
std::vector<Plugin *> plugins;
std::string errorString;
bool defaultPluginsLoaded;
std::map<std::string, std::map<std::string, PluginManager::Function> > pluginClasses;
};
// === PluginManager ======================================================= //
/// \class PluginManager pluginmanager.h chemkit/pluginmanager.h
/// \ingroup chemkit
/// \brief The PluginManager class manages the loading and unloading
/// of plugins.
///
/// \see Plugin
// --- Construction and Destruction ---------------------------------------- //
PluginManager::PluginManager()
: d(new PluginManagerPrivate)
{
d->defaultPluginsLoaded = false;
}
PluginManager::~PluginManager()
{
foreach(Plugin *plugin, d->plugins){
DynamicLibrary *library = plugin->library();
delete plugin;
delete library;
}
delete d;
}
// --- Properties ---------------------------------------------------------- //
/// Returns the plugin with \p name. Returns \c 0 if no plugin with
// \p name is loaded.
Plugin* PluginManager::plugin(const std::string &name) const
{
foreach(Plugin *plugin, d->plugins){
if(plugin->name() == name){
return plugin;
}
}
return 0;
}
/// Returns a list of all the loaded plugins.
const std::vector<Plugin *>& PluginManager::plugins() const
{
return d->plugins;
}
/// Returns the number of loaded plugins.
int PluginManager::pluginCount() const
{
return d->plugins.size();
}
// --- Plugin Loading ------------------------------------------------------ //
/// Loads a plugin from \p fileName. Returns \c false if an error
/// occurs.
bool PluginManager::loadPlugin(const std::string &fileName)
{
DynamicLibrary *library = new DynamicLibrary;
library->setFileName(fileName);
bool ok = library->open();
if(!ok){
std::cerr << "PluginManager: Error: Failed to load plugin: (" << fileName << "):"
<< library->errorString() << std::endl;
return false;
}
typedef Plugin* (*InitFunction)();
InitFunction initFunction = reinterpret_cast<InitFunction>(library->resolve("chemkit_plugin_init"));
if(!initFunction){
std::cerr << "PluginManager: Error: Failed to load plugin: (" << fileName << "):"
<< "Plugin contains no init() function." << std::endl;
return false;
}
Plugin *plugin = initFunction();
if(!plugin){
std::cerr << "PluginManager: Error: Failed to load plugin: (" << fileName << "):"
<< "Calling the plugin's init() function failed." << std::endl;
return false;
}
plugin->setLibrary(library);
d->plugins.push_back(plugin);
return true;
}
/// Loads all plugins from \p directory.
void PluginManager::loadPlugins(const std::string &directory)
{
boost::filesystem::path dir(directory);
if(!boost::filesystem::exists(dir)){
return;
}
for(boost::filesystem::directory_iterator iter(dir); iter != boost::filesystem::directory_iterator(); ++iter){
std::string fileName = boost::filesystem::path(iter->path().filename()).string();
if(DynamicLibrary::isLibrary(fileName)){
loadPlugin(iter->path().string());
}
}
}
void PluginManager::loadDefaultPlugins()
{
if(d->defaultPluginsLoaded){
return;
}
// list of directories to load plugins from
std::vector<std::string> directories;
// add default plugin directory
#if defined(CHEMKIT_OS_LINUX)
directories.push_back(CHEMKIT_INSTALL_PREFIX "/share/chemkit/plugins/");
#endif
// add directory from the CHEMKIT_PLUGIN_PATH environment variable
const char *path = getenv("CHEMKIT_PLUGIN_PATH");
if(path){
directories.push_back(path);
}
// load plugins from each directory
foreach(const std::string &directory, directories){
loadPlugins(directory);
}
d->defaultPluginsLoaded = true;
}
/// Unloads the plugin.
bool PluginManager::unloadPlugin(Plugin *plugin)
{
if(!plugin){
return false;
}
d->plugins.erase(std::remove(d->plugins.begin(), d->plugins.end(), plugin));
DynamicLibrary *library = plugin->library();
delete plugin;
delete library;
return true;
}
/// Unloads the plugin with \p name.
bool PluginManager::unloadPlugin(const std::string &name)
{
return unloadPlugin(plugin((name)));
}
// --- Error Handling ------------------------------------------------------ //
void PluginManager::setErrorString(const std::string &errorString)
{
d->errorString = errorString;
}
/// Returns a string describing the last error that occured.
std::string PluginManager::errorString() const
{
return d->errorString;
}
// --- Static Methods ------------------------------------------------------ //
/// Returns the instance of the plugin manager.
PluginManager* PluginManager::instance()
{
static PluginManager singleton;
return &singleton;
}
// --- Internal Methods ---------------------------------------------------- //
/// Registers a new plugin function for \p className and
/// \p pluginName.
bool PluginManager::registerPluginClass(const std::string &className, const std::string &pluginName, Function function)
{
std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
// use lower case plugin name
std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);
// prevent overwriting of previously registered plugins
if(classPlugins.find(lowerCasePluginName) != classPlugins.end()){
return false;
}
// add plugin class
classPlugins[lowerCasePluginName] = function;
return true;
}
/// Unregisters a plugin function for \p className and \p pluginName.
bool PluginManager::unregisterPluginClass(const std::string &className, const std::string &pluginName)
{
std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
// use lower case plugin name
std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);
// remove plugin class
return classPlugins.erase(lowerCasePluginName) > 0;
}
/// Returns a vector of strings containing the names of registered
/// plugins for \p className.
std::vector<std::string> PluginManager::pluginClassNames(const std::string &className) const
{
// ensure default plugins are loaded
const_cast<PluginManager *>(this)->loadDefaultPlugins();
const std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
std::vector<std::string> names;
for(std::map<std::string, Function>::const_iterator i = classPlugins.begin(); i != classPlugins.end(); ++i){
names.push_back(i->first);
}
return names;
}
/// Returns the registered function for the given \p className and \p pluginName.
PluginManager::Function PluginManager::pluginClassFunction(const std::string &className, const std::string &pluginName) const
{
// ensure default plugins are loaded
const_cast<PluginManager *>(this)->loadDefaultPlugins();
// use lower case plugin name
std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);
const std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
std::map<std::string, Function>::const_iterator location = classPlugins.find(lowerCasePluginName);
if(location == classPlugins.end()){
return 0;
}
return location->second;
}
} // end chemkit namespace
|
Fix memory leak in PluginManager
|
Fix memory leak in PluginManager
This fixes a memory leak in the PluginManager class when
removing and deleting plugins. Previously the dynamic library
for the plugin wasn't being closed and deleted.
|
C++
|
bsd-3-clause
|
kylelutz/chemkit,kylelutz/chemkit,kylelutz/chemkit,kylelutz/chemkit
|
510ba4eda4e221a7514eea84398eacb1e6bae0ea
|
xs/src/libslic3r/IO.cpp
|
xs/src/libslic3r/IO.cpp
|
#include "IO.hpp"
#include <stdexcept>
#include <fstream>
#include <functional>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/nowide/fstream.hpp>
#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"
namespace Slic3r { namespace IO {
const std::map<ExportFormat,std::string> extensions{
{STL, "stl"},
{OBJ, "obj"},
{POV, "pov"},
{AMF, "amf"},
{TMF, "3mf"},
{SVG, "svg"},
{Gcode, "gcode"},
};
const std::map<ExportFormat,bool(*)(const Model&,std::string)> write_model{
{STL, &STL::write},
{OBJ, &OBJ::write},
{POV, &POV::write},
{AMF, &AMF::write},
{TMF, &TMF::write},
};
bool
STL::read(std::string input_file, TriangleMesh* mesh)
{
// TODO: check that file exists
try {
mesh->ReadSTLFile(input_file);
mesh->check_topology();
} catch (...) {
throw std::runtime_error("Error while reading STL file");
}
return true;
}
bool
STL::read(std::string input_file, Model* model)
{
TriangleMesh mesh;
if (!STL::read(input_file, &mesh)) return false;
if (mesh.facets_count() == 0)
throw std::runtime_error("This STL file couldn't be read because it's empty.");
ModelObject* object = model->add_object();
object->name = boost::filesystem::path(input_file).filename().string();
object->input_file = input_file;
ModelVolume* volume = object->add_volume(mesh);
volume->name = object->name;
return true;
}
bool
STL::write(const Model &model, std::string output_file, bool binary)
{
TriangleMesh mesh = model.mesh();
return STL::write(mesh, output_file, binary);
}
bool
STL::write(const TriangleMesh &mesh, std::string output_file, bool binary)
{
if (binary) {
mesh.write_binary(output_file);
} else {
mesh.write_ascii(output_file);
}
return true;
}
bool
OBJ::read(std::string input_file, TriangleMesh* mesh)
{
Model model;
OBJ::read(input_file, &model);
*mesh = model.mesh();
return true;
}
bool
OBJ::read(std::string input_file, Model* model)
{
// TODO: encode file name
// TODO: check that file exists
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string err;
boost::nowide::ifstream ifs(input_file);
bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, &ifs);
if (!err.empty()) { // `err` may contain warning message.
std::cerr << err << std::endl;
}
if (!ret)
throw std::runtime_error("Error while reading OBJ file");
ModelObject* object = model->add_object();
object->name = boost::filesystem::path(input_file).filename().string();
object->input_file = input_file;
// Loop over shapes and add a volume for each one.
for (std::vector<tinyobj::shape_t>::const_iterator shape = shapes.begin();
shape != shapes.end(); ++shape) {
Pointf3s points;
std::vector<Point3> facets;
// Read vertices.
assert((attrib.vertices.size() % 3) == 0);
for (size_t v = 0; v < attrib.vertices.size(); v += 3) {
points.push_back(Pointf3(
attrib.vertices[v],
attrib.vertices[v+1],
attrib.vertices[v+2]
));
}
// Loop over facets of the current shape.
for (size_t f = 0; f < shape->mesh.num_face_vertices.size(); ++f) {
// tiny_obj_loader should triangulate any facet with more than 3 vertices
assert((shape->mesh.num_face_vertices[f] % 3) == 0);
facets.push_back(Point3(
shape->mesh.indices[f*3+0].vertex_index,
shape->mesh.indices[f*3+1].vertex_index,
shape->mesh.indices[f*3+2].vertex_index
));
}
TriangleMesh mesh(points, facets);
mesh.check_topology();
ModelVolume* volume = object->add_volume(mesh);
volume->name = object->name;
}
return true;
}
bool
OBJ::write(const Model& model, std::string output_file)
{
TriangleMesh mesh = model.mesh();
return OBJ::write(mesh, output_file);
}
bool
OBJ::write(const TriangleMesh& mesh, std::string output_file)
{
mesh.WriteOBJFile(output_file);
return true;
}
bool
POV::write(const Model &model, std::string output_file)
{
TriangleMesh mesh{ model.mesh() };
return POV::write(mesh, output_file);
}
bool
POV::write(const TriangleMesh& mesh, std::string output_file)
{
using namespace std;
boost::nowide::ofstream pov;
pov.open(output_file.c_str(), ios::out | ios::trunc);
for (int i = 0; i < mesh.stl.stats.number_of_facets; ++i) {
const stl_facet &f = mesh.stl.facet_start[i];
pov << "triangle { ";
pov << "<" << f.vertex[0].x << "," << f.vertex[0].y << "," << f.vertex[0].z << ">,";
pov << "<" << f.vertex[1].x << "," << f.vertex[1].y << "," << f.vertex[1].z << ">,";
pov << "<" << f.vertex[2].x << "," << f.vertex[2].y << "," << f.vertex[2].z << ">";
pov << " }" << endl;
}
pov.close();
return true;
}
} }
|
#include "IO.hpp"
#include <stdexcept>
#include <fstream>
#include <functional>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/nowide/fstream.hpp>
#define TINYOBJLOADER_IMPLEMENTATION
#include "tiny_obj_loader.h"
namespace Slic3r { namespace IO {
const std::map<ExportFormat,std::string> extensions{
{STL, "stl"},
{OBJ, "obj"},
{POV, "pov"},
{AMF, "amf"},
{TMF, "3mf"},
{SVG, "svg"},
{Gcode, "gcode"},
};
const std::map<ExportFormat,bool(*)(const Model&,std::string)> write_model{
{STL, &STL::write},
{OBJ, &OBJ::write},
{POV, &POV::write},
{AMF, &AMF::write},
{TMF, &TMF::write},
};
bool
STL::read(std::string input_file, TriangleMesh* mesh)
{
// TODO: check that file exists
try {
mesh->ReadSTLFile(input_file);
mesh->check_topology();
} catch (...) {
throw std::runtime_error("Error while reading STL file");
}
return true;
}
bool
STL::read(std::string input_file, Model* model)
{
TriangleMesh mesh;
if (!STL::read(input_file, &mesh)) return false;
if (mesh.facets_count() == 0)
throw std::runtime_error("This STL file couldn't be read because it's empty.");
ModelObject* object = model->add_object();
object->name = boost::filesystem::path(input_file).filename().string();
object->input_file = input_file;
ModelVolume* volume = object->add_volume(mesh);
volume->name = object->name;
return true;
}
bool
STL::write(const Model &model, std::string output_file, bool binary)
{
TriangleMesh mesh = model.mesh();
return STL::write(mesh, output_file, binary);
}
bool
STL::write(const TriangleMesh &mesh, std::string output_file, bool binary)
{
if (binary) {
mesh.write_binary(output_file);
} else {
mesh.write_ascii(output_file);
}
return true;
}
bool
OBJ::read(std::string input_file, TriangleMesh* mesh)
{
Model model;
OBJ::read(input_file, &model);
*mesh = model.mesh();
return true;
}
bool
OBJ::read(std::string input_file, Model* model)
{
// TODO: encode file name
// TODO: check that file exists
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string err;
boost::nowide::ifstream ifs(input_file);
bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &err, &ifs);
if (!err.empty()) { // `err` may contain warning message.
std::cerr << err << std::endl;
}
if (!ret)
throw std::runtime_error("Error while reading OBJ file");
ModelObject* object = model->add_object();
object->name = boost::filesystem::path(input_file).filename().string();
object->input_file = input_file;
// Loop over shapes and add a volume for each one.
for (std::vector<tinyobj::shape_t>::const_iterator shape = shapes.begin();
shape != shapes.end(); ++shape) {
Pointf3s points;
std::vector<Point3> facets;
// Read vertices.
assert((attrib.vertices.size() % 3) == 0);
for (size_t v = 0; v < attrib.vertices.size(); v += 3) {
points.push_back(Pointf3(
attrib.vertices[v],
attrib.vertices[v+1],
attrib.vertices[v+2]
));
}
// Loop over facets of the current shape.
for (size_t f = 0; f < shape->mesh.num_face_vertices.size(); ++f) {
// tiny_obj_loader should triangulate any facet with more than 3 vertices
assert((shape->mesh.num_face_vertices[f] % 3) == 0);
facets.push_back(Point3(
shape->mesh.indices[f*3+0].vertex_index,
shape->mesh.indices[f*3+1].vertex_index,
shape->mesh.indices[f*3+2].vertex_index
));
}
TriangleMesh mesh(points, facets);
mesh.check_topology();
ModelVolume* volume = object->add_volume(mesh);
volume->name = object->name;
}
return true;
}
bool
OBJ::write(const Model& model, std::string output_file)
{
TriangleMesh mesh = model.mesh();
// pre-emptively repair because object write can break
// output
mesh.repair();
return OBJ::write(mesh, output_file);
}
bool
OBJ::write(const TriangleMesh& mesh, std::string output_file)
{
mesh.WriteOBJFile(output_file);
return true;
}
bool
POV::write(const Model &model, std::string output_file)
{
TriangleMesh mesh{ model.mesh() };
return POV::write(mesh, output_file);
}
bool
POV::write(const TriangleMesh& mesh, std::string output_file)
{
using namespace std;
boost::nowide::ofstream pov;
pov.open(output_file.c_str(), ios::out | ios::trunc);
for (int i = 0; i < mesh.stl.stats.number_of_facets; ++i) {
const stl_facet &f = mesh.stl.facet_start[i];
pov << "triangle { ";
pov << "<" << f.vertex[0].x << "," << f.vertex[0].y << "," << f.vertex[0].z << ">,";
pov << "<" << f.vertex[1].x << "," << f.vertex[1].y << "," << f.vertex[1].z << ">,";
pov << "<" << f.vertex[2].x << "," << f.vertex[2].y << "," << f.vertex[2].z << ">";
pov << " }" << endl;
}
pov.close();
return true;
}
} }
|
Call repair() before trying to export object (because it tries to generate shared vertices and that method is apparently fragile).
|
Call repair() before trying to export object (because it tries to generate shared vertices and that method is apparently fragile).
|
C++
|
agpl-3.0
|
alexrj/Slic3r,alexrj/Slic3r,curieos/Slic3r,pieis2pi/Slic3r,pieis2pi/Slic3r,pieis2pi/Slic3r,pieis2pi/Slic3r,pieis2pi/Slic3r,alexrj/Slic3r,curieos/Slic3r,alexrj/Slic3r,alexrj/Slic3r,curieos/Slic3r,pieis2pi/Slic3r,curieos/Slic3r,curieos/Slic3r,alexrj/Slic3r,curieos/Slic3r
|
100bd9f9d683094ef9e9939cfb786045d10018fd
|
src/common/mprpc/rpc_util.hpp
|
src/common/mprpc/rpc_util.hpp
|
// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 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 version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef JUBATUS_COMMON_RPC_UTIL_HPP_
#define JUBATUS_COMMON_RPC_UTIL_HPP_
#include <string>
#include <utility>
#include <jubatus/msgpack/rpc/client.h>
#include <pficommon/data/serialization.h>
#include <msgpack.hpp>
#include "rpc_server.hpp"
namespace jubatus {
typedef std::pair<std::string, int> connection_info;
template<typename T, typename E = std::string>
struct result {
bool success;
T retval;
E error;
static result<T, E> ok(const T& t) {
result<T, E> r;
r.success = true;
r.retval = t;
return r;
}
static result<T, E> fail(const E& e) {
result<T, E> r;
r.success = false;
r.error = e;
return r;
}
MSGPACK_DEFINE(success, retval, error);
template<class Archiver>
void serialize(Archiver& ar) {
ar & MEMBER(success) & MEMBER(retval) & MEMBER(error);
}
};
#define JUBATUS_MPRPC_PROC(name, ret_type, param_list) \
namespace _server_impl { \
class name : public virtual jubatus::common::mprpc::rpc_server { \
public: \
name() : rpc_server(0) { } \
void set_##name(const pfi::lang::function< ret_type param_list> &f) { \
rpc_server::add< ret_type param_list>(#name, f); \
} \
}; \
} \
\
namespace _client_impl { \
class name : public virtual msgpack::rpc::client { \
public: \
name(): msgpack::rpc::client("", 0) { } \
\
template<typename A0> \
ret_type call_##name(A0 a0) { \
return call(#name, a0).template get<ret_type>(); \
} \
template<typename A0, typename A1> \
ret_type call_##name(A0 a0, A1 a1) { \
return call(#name, a0, a1).template get<ret_type>(); \
} \
template<typename A0, typename A1, typename A2> \
ret_type call_##name(A0 a0, A1 a1, A2 a2) { \
return call(#name, a0, a1, a2).template get<ret_type>(); \
} \
template<typename A0, typename A1, typename A2, typename A3> \
ret_type call_##name(A0 a0, A1 a1, A2 a2, A3 a3) { \
return call(#name, a0, a1, a2, a3).template get<ret_type>(); \
} \
}; \
}
#define JUBATUS_MPRPC_GEN(ver, base, ...) \
namespace _server_impl { \
struct base##_server : __VA_ARGS__ { \
public: \
base##_server(double timeout_sec) \
: jubatus::common::mprpc::rpc_server(timeout_sec) { } \
void __listen__(uint16_t port) { \
jubatus::common::mprpc::rpc_server::listen(port); \
} \
void __start__(int nthreads, bool no_hang = false) { \
jubatus::common::mprpc::rpc_server::start(nthreads, no_hang); \
} \
void __join__() { \
jubatus::common::mprpc::rpc_server::join(); \
} \
void __stop__() { \
jubatus::common::mprpc::rpc_server::stop(); \
} \
void __close__() { \
jubatus::common::mprpc::rpc_server::close(); \
} \
}; \
} \
typedef _server_impl::base##_server base##_server; \
\
namespace _client_impl { \
struct base##_client : __VA_ARGS__ { \
public: \
base##_client( \
const std::string& host, \
uint16_t port, \
double timeout_sec) \
: msgpack::rpc::client(host, port) { \
set_timeout(timeout_sec); \
} \
}; \
} \
typedef _client_impl::base##_client base##_client;
} // namespace jubatus
#endif // JUBATUS_COMMON_RPC_UTIL_HPP_
|
// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 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 version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef JUBATUS_COMMON_MPRPC_RPC_UTIL_HPP_
#define JUBATUS_COMMON_MPRPC_RPC_UTIL_HPP_
#include <string>
#include <utility>
#include <jubatus/msgpack/rpc/client.h>
#include <pficommon/data/serialization.h>
#include <msgpack.hpp>
#include "rpc_server.hpp"
namespace jubatus {
typedef std::pair<std::string, int> connection_info;
template<typename T, typename E = std::string>
struct result {
bool success;
T retval;
E error;
static result<T, E> ok(const T& t) {
result<T, E> r;
r.success = true;
r.retval = t;
return r;
}
static result<T, E> fail(const E& e) {
result<T, E> r;
r.success = false;
r.error = e;
return r;
}
MSGPACK_DEFINE(success, retval, error);
template<class Archiver>
void serialize(Archiver& ar) {
ar & MEMBER(success) & MEMBER(retval) & MEMBER(error);
}
};
#define JUBATUS_MPRPC_PROC(name, ret_type, param_list) \
namespace _server_impl { \
class name : public virtual jubatus::common::mprpc::rpc_server { \
public: \
name() : rpc_server(0) { } \
void set_##name(const pfi::lang::function< ret_type param_list> &f) { \
rpc_server::add< ret_type param_list>(#name, f); \
} \
}; \
} \
\
namespace _client_impl { \
class name : public virtual msgpack::rpc::client { \
public: \
name(): msgpack::rpc::client("", 0) { } \
\
template<typename A0> \
ret_type call_##name(A0 a0) { \
return call(#name, a0).template get<ret_type>(); \
} \
template<typename A0, typename A1> \
ret_type call_##name(A0 a0, A1 a1) { \
return call(#name, a0, a1).template get<ret_type>(); \
} \
template<typename A0, typename A1, typename A2> \
ret_type call_##name(A0 a0, A1 a1, A2 a2) { \
return call(#name, a0, a1, a2).template get<ret_type>(); \
} \
template<typename A0, typename A1, typename A2, typename A3> \
ret_type call_##name(A0 a0, A1 a1, A2 a2, A3 a3) { \
return call(#name, a0, a1, a2, a3).template get<ret_type>(); \
} \
}; \
}
#define JUBATUS_MPRPC_GEN(ver, base, ...) \
namespace _server_impl { \
struct base##_server : __VA_ARGS__ { \
public: \
base##_server(double timeout_sec) \
: jubatus::common::mprpc::rpc_server(timeout_sec) { } \
void __listen__(uint16_t port) { \
jubatus::common::mprpc::rpc_server::listen(port); \
} \
void __start__(int nthreads, bool no_hang = false) { \
jubatus::common::mprpc::rpc_server::start(nthreads, no_hang); \
} \
void __join__() { \
jubatus::common::mprpc::rpc_server::join(); \
} \
void __stop__() { \
jubatus::common::mprpc::rpc_server::stop(); \
} \
void __close__() { \
jubatus::common::mprpc::rpc_server::close(); \
} \
}; \
} \
typedef _server_impl::base##_server base##_server; \
\
namespace _client_impl { \
struct base##_client : __VA_ARGS__ { \
public: \
base##_client( \
const std::string& host, \
uint16_t port, \
double timeout_sec) \
: msgpack::rpc::client(host, port) { \
set_timeout(timeout_sec); \
} \
}; \
} \
typedef _client_impl::base##_client base##_client;
} // namespace jubatus
#endif // JUBATUS_COMMON_MPRPC_RPC_UTIL_HPP_
|
Fix rpc_util include guard naming
|
Fix rpc_util include guard naming
|
C++
|
lgpl-2.1
|
rimms/jubatus_core,Asuka52/jubatus,kmaehashi/jubatus,mathn/jubatus,jubatus/jubatus,kmaehashi/jubatus_core,gintenlabo/jubatus,kumagi/jubatus_core,rimms/jubatus,jubatus/jubatus,elkingtonmcb/jubatus,mathn/jubatus,gintenlabo/jubatus,roselleebarle04/jubatus,roselleebarle04/jubatus,kmaehashi/jubatus_core,kmaehashi/jubatus_core,elkingtonmcb/jubatus,kumagi/jubatus_core,gintenlabo/jubatus_core,jubatus/jubatus,kumagi/jubatus_core,gintenlabo/jubatus_core,rimms/jubatus,Asuka52/jubatus,gintenlabo/jubatus_core,rimms/jubatus_core,kmaehashi/jubatus,kumagi/jubatus_core,kmaehashi/jubatus_core,gintenlabo/jubatus_core,rimms/jubatus_core,rimms/jubatus_core
|
28befb4c534a428f2612475571f567dafa10a512
|
src/compat/glibcxx_compat.cpp
|
src/compat/glibcxx_compat.cpp
|
#include <cstddef>
#include <istream>
#include <stdexcept>
#include <typeinfo>
#ifndef _GLIBCXX_USE_NOEXCEPT
#define _GLIBCXX_USE_NOEXCEPT throw()
#endif
namespace std {
const char* bad_exception::what() const throw()
{
return "std::bad_exception";
}
const char* bad_cast::what() const throw()
{
return "std::bad_cast";
}
const char* bad_alloc::what() const throw()
{
return "std::bad_alloc";
}
namespace __detail
{
struct _List_node_base
{
void _M_hook(std::__detail::_List_node_base* const __position) throw () __attribute__((used))
{
_M_next = __position;
_M_prev = __position->_M_prev;
__position->_M_prev->_M_next = this;
__position->_M_prev = this;
}
void _M_unhook() __attribute__((used))
{
_List_node_base* const __next_node = _M_next;
_List_node_base* const __prev_node = _M_prev;
__prev_node->_M_next = __next_node;
__next_node->_M_prev = __prev_node;
}
_List_node_base* _M_next;
_List_node_base* _M_prev;
};
} // namespace detail
template ostream& ostream::_M_insert(bool);
template ostream& ostream::_M_insert(long);
template ostream& ostream::_M_insert(double);
template ostream& ostream::_M_insert(unsigned long);
template ostream& ostream::_M_insert(const void*);
template ostream& __ostream_insert(ostream&, const char*, streamsize);
template istream& istream::_M_extract(long&);
template istream& istream::_M_extract(unsigned short&);
out_of_range::~out_of_range() _GLIBCXX_USE_NOEXCEPT { }
// Used with permission.
// See: https://github.com/madlib/madlib/commit/c3db418c0d34d6813608f2137fef1012ce03043d
void
ctype<char>::_M_widen_init() const {
char __tmp[sizeof(_M_widen)];
for (unsigned __i = 0; __i < sizeof(_M_widen); ++__i)
__tmp[__i] = __i;
do_widen(__tmp, __tmp + sizeof(__tmp), _M_widen);
_M_widen_ok = 1;
// Set _M_widen_ok to 2 if memcpy can't be used.
for (unsigned __i = 0; __i < sizeof(_M_widen); ++__i)
if (__tmp[__i] != _M_widen[__i]) {
_M_widen_ok = 2;
break;
}
}
}// namespace std
|
#include <cstddef>
#include <istream>
#include <stdexcept>
#include <typeinfo>
#ifndef _GLIBCXX_USE_NOEXCEPT
#define _GLIBCXX_USE_NOEXCEPT throw()
#endif
namespace std {
const char* bad_exception::what() const throw()
{
return "std::bad_exception";
}
const char* bad_cast::what() const throw()
{
return "std::bad_cast";
}
const char* bad_alloc::what() const throw()
{
return "std::bad_alloc";
}
namespace __detail
{
struct _List_node_base
{
void _M_hook(std::__detail::_List_node_base* const __position) throw () __attribute__((used))
{
_M_next = __position;
_M_prev = __position->_M_prev;
__position->_M_prev->_M_next = this;
__position->_M_prev = this;
}
void _M_unhook() __attribute__((used))
{
_List_node_base* const __next_node = _M_next;
_List_node_base* const __prev_node = _M_prev;
__prev_node->_M_next = __next_node;
__next_node->_M_prev = __prev_node;
}
_List_node_base* _M_next;
_List_node_base* _M_prev;
};
} // namespace detail
template ostream& ostream::_M_insert(bool);
template ostream& ostream::_M_insert(long);
template ostream& ostream::_M_insert(double);
template ostream& ostream::_M_insert(unsigned long);
template ostream& ostream::_M_insert(const void*);
template ostream& __ostream_insert(ostream&, const char*, streamsize);
template istream& istream::_M_extract(long&);
template istream& istream::_M_extract(unsigned short&);
out_of_range::~out_of_range() _GLIBCXX_USE_NOEXCEPT { }
// Used with permission.
// See: https://github.com/madlib/madlib/commit/c3db418c0d34d6813608f2137fef1012ce03043d
void
ctype<char>::_M_widen_init() const {
char __tmp[sizeof(_M_widen)];
for (unsigned __i = 0; __i < sizeof(_M_widen); ++__i)
__tmp[__i] = __i;
do_widen(__tmp, __tmp + sizeof(__tmp), _M_widen);
_M_widen_ok = 1;
// Set _M_widen_ok to 2 if memcpy can't be used.
for (unsigned __i = 0; __i < sizeof(_M_widen); ++__i)
if (__tmp[__i] != _M_widen[__i]) {
_M_widen_ok = 2;
break;
}
}
void __throw_out_of_range_fmt(const char*, ...) __attribute__((__noreturn__));
void __throw_out_of_range_fmt(const char* err, ...)
{
// Safe and over-simplified version. Ignore the format and print it as-is.
__throw_out_of_range(err);
}
}// namespace std
|
add symbol for upcoming gcc 4.9's libstdc++
|
build: add symbol for upcoming gcc 4.9's libstdc++
|
C++
|
mit
|
brishtiteveja/sherlockcoin,jarymoth/dogecoin,Exceltior/dogecoin,brishtiteveja/sherlockcoin,haisee/dogecoin,brishtiteveja/sherlockcoin,marklai9999/Taiwancoin,koharjidan/dogecoin,Domer85/dogecoin,coinkeeper/2015-06-22_18-37_dogecoin,langerhans/dogecoin,coinkeeper/2015-06-22_18-37_dogecoin,langerhans/dogecoin,koharjidan/dogecoin,Domer85/dogecoin,coinwarp/dogecoin,Exceltior/dogecoin,haisee/dogecoin,jarymoth/dogecoin,haisee/dogecoin,Domer85/dogecoin,koharjidan/dogecoin,koharjidan/dogecoin,marklai9999/Taiwancoin,koharjidan/dogecoin,coinkeeper/2015-06-22_18-37_dogecoin,brishtiteveja/sherlockcoin,coinwarp/dogecoin,coinwarp/dogecoin,coinkeeper/2015-06-22_18-37_dogecoin,coinwarp/dogecoin,coinwarp/dogecoin,langerhans/dogecoin,coinkeeper/2015-06-22_18-37_dogecoin,langerhans/dogecoin,haisee/dogecoin,jarymoth/dogecoin,jarymoth/dogecoin,haisee/dogecoin,marklai9999/Taiwancoin,Exceltior/dogecoin,langerhans/dogecoin,jarymoth/dogecoin,brishtiteveja/sherlockcoin,Exceltior/dogecoin,marklai9999/Taiwancoin,Domer85/dogecoin,koharjidan/dogecoin,Exceltior/dogecoin,langerhans/dogecoin
|
3c34cf9bc0c6c471ab1d6a446716f7fe5aa25735
|
xchainer/dtype_test.cc
|
xchainer/dtype_test.cc
|
#include "xchainer/dtype.h"
#include <gtest/gtest.h>
#include <type_traits>
namespace xchainer {
namespace {
// Check if DtypeToType and TypeToDtype are inverses of each other.
template <Dtype dtype>
constexpr bool kDtypeMappingTest = dtype == TypeToDtype<DtypeToType<dtype>>;
static_assert(kDtypeMappingTest<Dtype::kBool>, "bool");
static_assert(kDtypeMappingTest<Dtype::kInt8>, "int8");
static_assert(kDtypeMappingTest<Dtype::kInt16>, "int16");
static_assert(kDtypeMappingTest<Dtype::kInt32>, "int32");
static_assert(kDtypeMappingTest<Dtype::kInt64>, "int64");
static_assert(kDtypeMappingTest<Dtype::kUInt8>, "uint8");
static_assert(kDtypeMappingTest<Dtype::kFloat32>, "float32");
static_assert(kDtypeMappingTest<Dtype::kFloat64>, "float64");
// Check if GetCharCode and CharToDtype are inverses of each other.
template <Dtype dtype>
constexpr bool kDtypeCharMappingTest = dtype == CharToDtype<GetCharCode(dtype)>;
static_assert(kDtypeCharMappingTest<Dtype::kBool>, "bool");
static_assert(kDtypeCharMappingTest<Dtype::kInt8>, "int8");
static_assert(kDtypeCharMappingTest<Dtype::kInt16>, "int16");
static_assert(kDtypeCharMappingTest<Dtype::kInt32>, "int32");
static_assert(kDtypeCharMappingTest<Dtype::kInt64>, "int64");
static_assert(kDtypeCharMappingTest<Dtype::kUInt8>, "uint8");
static_assert(kDtypeCharMappingTest<Dtype::kFloat32>, "float32");
static_assert(kDtypeCharMappingTest<Dtype::kFloat64>, "float64");
// Check if the element size is correct.
template <typename T>
constexpr bool kGetElementSizeTest = GetElementSize(TypeToDtype<T>) == sizeof(T);
static_assert(kGetElementSizeTest<bool>, "bool");
static_assert(kGetElementSizeTest<int8_t>, "int8");
static_assert(kGetElementSizeTest<int16_t>, "int16");
static_assert(kGetElementSizeTest<int32_t>, "int32");
static_assert(kGetElementSizeTest<int64_t>, "int64");
static_assert(kGetElementSizeTest<uint8_t>, "uint8");
static_assert(kGetElementSizeTest<float>, "float32");
static_assert(kGetElementSizeTest<double>, "float64");
// Check if char* GetDtypeName and GetDtype(std::string) are inverses of each other.
TEST(DtypeTest, GetDtype_GetDtypeName) {
ASSERT_EQ(Dtype::kBool, GetDtype(GetDtypeName(Dtype::kBool)));
ASSERT_EQ(Dtype::kInt8, GetDtype(GetDtypeName(Dtype::kInt8)));
ASSERT_EQ(Dtype::kInt16, GetDtype(GetDtypeName(Dtype::kInt16)));
ASSERT_EQ(Dtype::kInt32, GetDtype(GetDtypeName(Dtype::kInt32)));
ASSERT_EQ(Dtype::kInt64, GetDtype(GetDtypeName(Dtype::kInt64)));
ASSERT_EQ(Dtype::kUInt8, GetDtype(GetDtypeName(Dtype::kUInt8)));
ASSERT_EQ(Dtype::kFloat32, GetDtype(GetDtypeName(Dtype::kFloat32)));
ASSERT_EQ(Dtype::kFloat64, GetDtype(GetDtypeName(Dtype::kFloat64)));
ASSERT_THROW(GetDtype("wrong"), DtypeError);
}
// Check if char GetCharCode and GetDtype(std::string) are inverses of each other.
TEST(DtypeTest, GetDtype_GetCharCode) {
ASSERT_EQ(Dtype::kBool, GetDtype({GetCharCode(Dtype::kBool)}));
ASSERT_EQ(Dtype::kInt8, GetDtype({GetCharCode(Dtype::kInt8)}));
ASSERT_EQ(Dtype::kInt16, GetDtype({GetCharCode(Dtype::kInt16)}));
ASSERT_EQ(Dtype::kInt32, GetDtype({GetCharCode(Dtype::kInt32)}));
ASSERT_EQ(Dtype::kInt64, GetDtype({GetCharCode(Dtype::kInt64)}));
ASSERT_EQ(Dtype::kUInt8, GetDtype({GetCharCode(Dtype::kUInt8)}));
ASSERT_EQ(Dtype::kFloat32, GetDtype({GetCharCode(Dtype::kFloat32)}));
ASSERT_EQ(Dtype::kFloat64, GetDtype({GetCharCode(Dtype::kFloat64)}));
}
TEST(DtypeTest, CheckEqual) {
ASSERT_NO_THROW(CheckEqual(Dtype::kInt8, Dtype::kInt8));
ASSERT_THROW(CheckEqual(Dtype::kInt8, Dtype::kUInt8), DtypeError);
}
} // namespace
} // namespace xchainer
|
#include "xchainer/dtype.h"
#include <type_traits>
#include <gtest/gtest.h>
namespace xchainer {
namespace {
// Check if DtypeToType and TypeToDtype are inverses of each other.
template <Dtype dtype>
constexpr bool kDtypeMappingTest = dtype == TypeToDtype<DtypeToType<dtype>>;
static_assert(kDtypeMappingTest<Dtype::kBool>, "bool");
static_assert(kDtypeMappingTest<Dtype::kInt8>, "int8");
static_assert(kDtypeMappingTest<Dtype::kInt16>, "int16");
static_assert(kDtypeMappingTest<Dtype::kInt32>, "int32");
static_assert(kDtypeMappingTest<Dtype::kInt64>, "int64");
static_assert(kDtypeMappingTest<Dtype::kUInt8>, "uint8");
static_assert(kDtypeMappingTest<Dtype::kFloat32>, "float32");
static_assert(kDtypeMappingTest<Dtype::kFloat64>, "float64");
// Check if GetCharCode and CharToDtype are inverses of each other.
template <Dtype dtype>
constexpr bool kDtypeCharMappingTest = dtype == CharToDtype<GetCharCode(dtype)>;
static_assert(kDtypeCharMappingTest<Dtype::kBool>, "bool");
static_assert(kDtypeCharMappingTest<Dtype::kInt8>, "int8");
static_assert(kDtypeCharMappingTest<Dtype::kInt16>, "int16");
static_assert(kDtypeCharMappingTest<Dtype::kInt32>, "int32");
static_assert(kDtypeCharMappingTest<Dtype::kInt64>, "int64");
static_assert(kDtypeCharMappingTest<Dtype::kUInt8>, "uint8");
static_assert(kDtypeCharMappingTest<Dtype::kFloat32>, "float32");
static_assert(kDtypeCharMappingTest<Dtype::kFloat64>, "float64");
// Check if the element size is correct.
template <typename T>
constexpr bool kGetElementSizeTest = GetElementSize(TypeToDtype<T>) == sizeof(T);
static_assert(kGetElementSizeTest<bool>, "bool");
static_assert(kGetElementSizeTest<int8_t>, "int8");
static_assert(kGetElementSizeTest<int16_t>, "int16");
static_assert(kGetElementSizeTest<int32_t>, "int32");
static_assert(kGetElementSizeTest<int64_t>, "int64");
static_assert(kGetElementSizeTest<uint8_t>, "uint8");
static_assert(kGetElementSizeTest<float>, "float32");
static_assert(kGetElementSizeTest<double>, "float64");
// Check if char* GetDtypeName and GetDtype(std::string) are inverses of each other.
TEST(DtypeTest, GetDtype_GetDtypeName) {
ASSERT_EQ(Dtype::kBool, GetDtype(GetDtypeName(Dtype::kBool)));
ASSERT_EQ(Dtype::kInt8, GetDtype(GetDtypeName(Dtype::kInt8)));
ASSERT_EQ(Dtype::kInt16, GetDtype(GetDtypeName(Dtype::kInt16)));
ASSERT_EQ(Dtype::kInt32, GetDtype(GetDtypeName(Dtype::kInt32)));
ASSERT_EQ(Dtype::kInt64, GetDtype(GetDtypeName(Dtype::kInt64)));
ASSERT_EQ(Dtype::kUInt8, GetDtype(GetDtypeName(Dtype::kUInt8)));
ASSERT_EQ(Dtype::kFloat32, GetDtype(GetDtypeName(Dtype::kFloat32)));
ASSERT_EQ(Dtype::kFloat64, GetDtype(GetDtypeName(Dtype::kFloat64)));
ASSERT_THROW(GetDtype("wrong"), DtypeError);
}
// Check if char GetCharCode and GetDtype(std::string) are inverses of each other.
TEST(DtypeTest, GetDtype_GetCharCode) {
ASSERT_EQ(Dtype::kBool, GetDtype({GetCharCode(Dtype::kBool)}));
ASSERT_EQ(Dtype::kInt8, GetDtype({GetCharCode(Dtype::kInt8)}));
ASSERT_EQ(Dtype::kInt16, GetDtype({GetCharCode(Dtype::kInt16)}));
ASSERT_EQ(Dtype::kInt32, GetDtype({GetCharCode(Dtype::kInt32)}));
ASSERT_EQ(Dtype::kInt64, GetDtype({GetCharCode(Dtype::kInt64)}));
ASSERT_EQ(Dtype::kUInt8, GetDtype({GetCharCode(Dtype::kUInt8)}));
ASSERT_EQ(Dtype::kFloat32, GetDtype({GetCharCode(Dtype::kFloat32)}));
ASSERT_EQ(Dtype::kFloat64, GetDtype({GetCharCode(Dtype::kFloat64)}));
}
TEST(DtypeTest, CheckEqual) {
ASSERT_NO_THROW(CheckEqual(Dtype::kInt8, Dtype::kInt8));
ASSERT_THROW(CheckEqual(Dtype::kInt8, Dtype::kUInt8), DtypeError);
}
} // namespace
} // namespace xchainer
|
fix order of includes to follow google style guide
|
fix order of includes to follow google style guide
|
C++
|
mit
|
ktnyt/chainer,niboshi/chainer,niboshi/chainer,wkentaro/chainer,niboshi/chainer,chainer/chainer,chainer/chainer,chainer/chainer,chainer/chainer,jnishi/chainer,jnishi/chainer,ktnyt/chainer,pfnet/chainer,jnishi/chainer,okuta/chainer,keisuke-umezawa/chainer,jnishi/chainer,hvy/chainer,hvy/chainer,hvy/chainer,keisuke-umezawa/chainer,wkentaro/chainer,niboshi/chainer,okuta/chainer,ktnyt/chainer,okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,ktnyt/chainer,wkentaro/chainer,hvy/chainer,keisuke-umezawa/chainer,okuta/chainer,tkerola/chainer
|
7a6365a65caf450f18bf8671b158e85a0a6d436d
|
lib/Target/AVR/AVRInstrumentFunctions.cpp
|
lib/Target/AVR/AVRInstrumentFunctions.cpp
|
//===-- AVRInstrumentFunctions.cpp - Insert instrumentation for testing ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass takes a function and inserts calls to hook functions which are
// told the name, arguments, and results of function calls.
//
// The hooks can do anything with the information given. It is possible to
// send the data through a serial connection in order to runs tests on
// bare metal.
//
//===----------------------------------------------------------------------===//
#include "AVR.h"
#include <llvm/IR/Function.h>
#include <llvm/IR/Module.h>
using namespace llvm;
#define AVR_INSTRUMENT_FUNCTIONS_NAME "AVR function instrumentation pass"
namespace {
// External symbols that we emit calls to.
namespace symbols {
#define SYMBOL_PREFIX "avr_instrumentation"
const StringRef PREFIX = SYMBOL_PREFIX;
// void (i16 argCount);
const StringRef BEGIN_FUNCTION_SIGNATURE = SYMBOL_PREFIX "_begin_signature";
// void(i16 argCount);
const StringRef END_FUNCTION_SIGNATURE = SYMBOL_PREFIX "_end_signature";
#undef SYMBOL_PREFIX
}
class AVRInstrumentFunctions : public FunctionPass {
public:
static char ID;
AVRInstrumentFunctions() : FunctionPass(ID) {
initializeAVRInstrumentFunctionsPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
StringRef getPassName() const override { return AVR_INSTRUMENT_FUNCTIONS_NAME; }
};
char AVRInstrumentFunctions::ID = 0;
/// Creates a pointer to a string.
static Value *CreateStringPtr(BasicBlock &BB, StringRef Str) {
LLVMContext &Ctx = BB.getContext();
IntegerType *I8 = Type::getInt8Ty(Ctx);
Constant *ConstantStr = ConstantDataArray::getString(Ctx, Str);
GlobalVariable *GlobalStr = new GlobalVariable(*BB.getParent()->getParent(),
ConstantStr->getType(),
true, /* is a constant */
GlobalValue::PrivateLinkage,
ConstantStr);
return GetElementPtrInst::CreateInBounds(GlobalStr,
{ConstantInt::get(I8, 0), ConstantInt::get(I8, 0)}, "", &BB);
}
/// Builds a call to one of the signature begin/end hooks.
static void BuildSignatureCall(StringRef SymName, BasicBlock &BB, Function &F) {
LLVMContext &Ctx = F.getContext();
IntegerType *I16 = Type::getInt16Ty(Ctx);
FunctionType *FnType = FunctionType::get(Type::getVoidTy(Ctx),
{Type::getInt8PtrTy(Ctx), I16}, false);
Constant *Fn = F.getParent()->getOrInsertFunction(SymName, FnType);
Value *FunctionName = CreateStringPtr(BB, F.getName());
Value *Args[] = {FunctionName,
ConstantInt::get(I16, F.getArgumentList().size())};
CallInst::Create(Fn, Args, "", &BB);
}
/// Builds instructions to call into an external function to
/// notify about a function signature beginning.
static void BuildBeginSignature(BasicBlock &BB, Function &F) {
return BuildSignatureCall(symbols::BEGIN_FUNCTION_SIGNATURE, BB, F);
}
/// Builds instructions to call into an external function to
/// notify about a function signature ending.
static void BuildEndSignature(BasicBlock &BB, Function &F) {
return BuildSignatureCall(symbols::END_FUNCTION_SIGNATURE, BB, F);
}
/// Get the name of the external symbol that we need to call
/// to notify about this argument.
static std::string GetArgumentSymbolName(Argument &Arg) {
Type *Ty = Arg.getType();
if (auto *IntTy = dyn_cast<IntegerType>(Ty)) {
return (symbols::PREFIX + "_argument_i" + std::to_string(IntTy->getBitWidth())).str();
}
llvm_unreachable("unknown argument type");
}
/// Builds a call to one of the argument hooks.
static void BuildArgument(BasicBlock &BB, Argument &Arg) {
Function &F = *Arg.getParent();
LLVMContext &Ctx = F.getContext();
FunctionType *FnType = FunctionType::get(Type::getVoidTy(Ctx),
{Type::getInt8PtrTy(Ctx), Arg.getType()}, false);
Constant *Fn = F.getParent()->getOrInsertFunction(
GetArgumentSymbolName(Arg), FnType);
Value *ArgName = CreateStringPtr(BB, Arg.getName());
Value *Args[] = {ArgName, &Arg};
CallInst::Create(Fn, Args, "", &BB);
}
/// Builds a call to all of the function signature hooks.
static void BuildSignature(BasicBlock &BB, Function &F) {
BuildBeginSignature(BB, F);
for (Argument &Arg : F.args()) { BuildArgument(BB, Arg); }
BuildEndSignature(BB, F);
}
/// Builds the instrumentation entry block.
static void BuildEntryBlock(Function &F) {
BasicBlock &EntryBlock = F.getEntryBlock();
// Create a new basic block at the start of the existing entry block.
BasicBlock *BB = BasicBlock::Create(F.getContext(),
"instrumentation_entry",
&F, &EntryBlock);
BuildSignature(*BB, F);
// Jump to the actual entry block.
BranchInst::Create(&EntryBlock, BB);
}
static std::string GetReturnSymbolName(Value &Val) {
Type *Ty = Val.getType();
if (auto *IntTy = dyn_cast<IntegerType>(Ty)) {
return (symbols::PREFIX + "_result_u" + std::to_string(IntTy->getBitWidth())).str();
}
llvm_unreachable("unknown return type");
}
static void BuildExitHook(Instruction &I) {
Function &F = *I.getParent()->getParent();
LLVMContext &Ctx = F.getContext();
if (auto *Ret = dyn_cast<ReturnInst>(&I)) {
Value *RetVal = Ret->getReturnValue();
assert(RetVal && "should only be instrumenting functions with return values");
FunctionType *FnType = FunctionType::get(Type::getVoidTy(Ctx),
{RetVal->getType()}, false);
Constant *Fn = F.getParent()->getOrInsertFunction(
GetReturnSymbolName(*RetVal), FnType);
// Call the result hook just before the return.
CallInst::Create(Fn, {RetVal}, "", &I);
}
}
/// Runs return hooks before all returns in a function.
static void BuildExitHooks(Function &F) {
for (BasicBlock &BB : F) {
auto BBI = BB.begin(), E = BB.end();
while (BBI != E) {
auto NBBI = std::next(BBI);
BuildExitHook(*BBI);
// Modified |= expandMI(BB, MBBI);
BBI = NBBI;
}
}
}
static bool ShouldInstrument(Function &F) {
// No point reporting results if there are none.
return !F.getReturnType()->isVoidTy();
}
bool AVRInstrumentFunctions::runOnFunction(Function &F) {
if (ShouldInstrument(F)) {
BuildEntryBlock(F);
BuildExitHooks(F);
}
return true;
}
} // end of anonymous namespace
INITIALIZE_PASS(AVRInstrumentFunctions, "avr-instrument-functions",
AVR_INSTRUMENT_FUNCTIONS_NAME, false, false)
namespace llvm {
FunctionPass *createAVRInstrumentFunctionsPass() { return new AVRInstrumentFunctions(); }
} // end of namespace llvm
|
//===-- AVRInstrumentFunctions.cpp - Insert instrumentation for testing ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass takes a function and inserts calls to hook functions which are
// told the name, arguments, and results of function calls.
//
// The hooks can do anything with the information given. It is possible to
// send the data through a serial connection in order to runs tests on
// bare metal.
//
//===----------------------------------------------------------------------===//
#include "AVR.h"
#include <llvm/IR/Function.h>
#include <llvm/IR/Module.h>
using namespace llvm;
#define AVR_INSTRUMENT_FUNCTIONS_NAME "AVR function instrumentation pass"
namespace {
// External symbols that we emit calls to.
namespace symbols {
#define SYMBOL_PREFIX "avr_instrumentation"
const StringRef PREFIX = SYMBOL_PREFIX;
// void (i16 argCount);
const StringRef BEGIN_FUNCTION_SIGNATURE = SYMBOL_PREFIX "_begin_signature";
// void(i16 argCount);
const StringRef END_FUNCTION_SIGNATURE = SYMBOL_PREFIX "_end_signature";
#undef SYMBOL_PREFIX
}
class AVRInstrumentFunctions : public FunctionPass {
public:
static char ID;
AVRInstrumentFunctions() : FunctionPass(ID) {
initializeAVRInstrumentFunctionsPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override;
StringRef getPassName() const override { return AVR_INSTRUMENT_FUNCTIONS_NAME; }
};
char AVRInstrumentFunctions::ID = 0;
/// Creates a pointer to a string.
static Value *CreateStringPtr(BasicBlock &BB, StringRef Str) {
LLVMContext &Ctx = BB.getContext();
IntegerType *I8 = Type::getInt8Ty(Ctx);
Constant *ConstantStr = ConstantDataArray::getString(Ctx, Str);
GlobalVariable *GlobalStr = new GlobalVariable(*BB.getParent()->getParent(),
ConstantStr->getType(),
true, /* is a constant */
GlobalValue::PrivateLinkage,
ConstantStr);
return GetElementPtrInst::CreateInBounds(GlobalStr,
{ConstantInt::get(I8, 0), ConstantInt::get(I8, 0)}, "", &BB);
}
/// Builds a call to one of the signature begin/end hooks.
static void BuildSignatureCall(StringRef SymName, BasicBlock &BB, Function &F) {
LLVMContext &Ctx = F.getContext();
IntegerType *I16 = Type::getInt16Ty(Ctx);
FunctionType *FnType = FunctionType::get(Type::getVoidTy(Ctx),
{Type::getInt8PtrTy(Ctx), I16}, false);
Constant *Fn = F.getParent()->getOrInsertFunction(SymName, FnType);
Value *FunctionName = CreateStringPtr(BB, F.getName());
Value *Args[] = {FunctionName,
ConstantInt::get(I16, F.getArgumentList().size())};
CallInst::Create(Fn, Args, "", &BB);
}
/// Builds instructions to call into an external function to
/// notify about a function signature beginning.
static void BuildBeginSignature(BasicBlock &BB, Function &F) {
return BuildSignatureCall(symbols::BEGIN_FUNCTION_SIGNATURE, BB, F);
}
/// Builds instructions to call into an external function to
/// notify about a function signature ending.
static void BuildEndSignature(BasicBlock &BB, Function &F) {
return BuildSignatureCall(symbols::END_FUNCTION_SIGNATURE, BB, F);
}
/// Get the name of the external symbol that we need to call
/// to notify about this argument.
static std::string GetArgumentSymbolName(Argument &Arg) {
Type *Ty = Arg.getType();
if (auto *IntTy = dyn_cast<IntegerType>(Ty)) {
return (symbols::PREFIX + "_argument_i" + std::to_string(IntTy->getBitWidth())).str();
}
llvm_unreachable("unknown argument type");
}
/// Builds a call to one of the argument hooks.
static void BuildArgument(BasicBlock &BB, Argument &Arg) {
Function &F = *Arg.getParent();
LLVMContext &Ctx = F.getContext();
Type *I8 = Type::getInt8Ty(Ctx);
FunctionType *FnType = FunctionType::get(Type::getVoidTy(Ctx),
{Type::getInt8PtrTy(Ctx), I8, Arg.getType()}, false);
Constant *Fn = F.getParent()->getOrInsertFunction(
GetArgumentSymbolName(Arg), FnType);
Value *ArgName = CreateStringPtr(BB, Arg.getName());
Value *Args[] = {ArgName, ConstantInt::get(I8, Arg.getArgNo()), &Arg};
CallInst::Create(Fn, Args, "", &BB);
}
/// Builds a call to all of the function signature hooks.
static void BuildSignature(BasicBlock &BB, Function &F) {
BuildBeginSignature(BB, F);
for (Argument &Arg : F.args()) { BuildArgument(BB, Arg); }
BuildEndSignature(BB, F);
}
/// Builds the instrumentation entry block.
static void BuildEntryBlock(Function &F) {
BasicBlock &EntryBlock = F.getEntryBlock();
// Create a new basic block at the start of the existing entry block.
BasicBlock *BB = BasicBlock::Create(F.getContext(),
"instrumentation_entry",
&F, &EntryBlock);
BuildSignature(*BB, F);
// Jump to the actual entry block.
BranchInst::Create(&EntryBlock, BB);
}
static std::string GetReturnSymbolName(Value &Val) {
Type *Ty = Val.getType();
if (auto *IntTy = dyn_cast<IntegerType>(Ty)) {
return (symbols::PREFIX + "_result_u" + std::to_string(IntTy->getBitWidth())).str();
}
llvm_unreachable("unknown return type");
}
static void BuildExitHook(Instruction &I) {
Function &F = *I.getParent()->getParent();
LLVMContext &Ctx = F.getContext();
if (auto *Ret = dyn_cast<ReturnInst>(&I)) {
Value *RetVal = Ret->getReturnValue();
assert(RetVal && "should only be instrumenting functions with return values");
FunctionType *FnType = FunctionType::get(Type::getVoidTy(Ctx),
{RetVal->getType()}, false);
Constant *Fn = F.getParent()->getOrInsertFunction(
GetReturnSymbolName(*RetVal), FnType);
// Call the result hook just before the return.
CallInst::Create(Fn, {RetVal}, "", &I);
}
}
/// Runs return hooks before all returns in a function.
static void BuildExitHooks(Function &F) {
for (BasicBlock &BB : F) {
auto BBI = BB.begin(), E = BB.end();
while (BBI != E) {
auto NBBI = std::next(BBI);
BuildExitHook(*BBI);
// Modified |= expandMI(BB, MBBI);
BBI = NBBI;
}
}
}
static bool ShouldInstrument(Function &F) {
// No point reporting results if there are none.
return !F.getReturnType()->isVoidTy();
}
bool AVRInstrumentFunctions::runOnFunction(Function &F) {
if (ShouldInstrument(F)) {
BuildEntryBlock(F);
BuildExitHooks(F);
}
return true;
}
} // end of anonymous namespace
INITIALIZE_PASS(AVRInstrumentFunctions, "avr-instrument-functions",
AVR_INSTRUMENT_FUNCTIONS_NAME, false, false)
namespace llvm {
FunctionPass *createAVRInstrumentFunctionsPass() { return new AVRInstrumentFunctions(); }
} // end of namespace llvm
|
Add argument indices to the instrumention hook functions
|
[AVR] Add argument indices to the instrumention hook functions
This allows the instrumention hook functions to do better
pretty-printing.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@289793 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm
|
0b6c8e597fe75739361f80b94a6355c60a2a503f
|
sawbuck/image_util/disassembler_unittest.cc
|
sawbuck/image_util/disassembler_unittest.cc
|
// Copyright 2011 Google 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.
//
// Implementation of disassembler.
#include "sawbuck/image_util/disassembler.h"
#include "base/scoped_ptr.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <vector>
using testing::_;
using testing::Invoke;
using testing::SetArgumentPointee;
extern "C" {
// functions and labels exposed from our .asm test stub.
extern int assembly_func();
extern int internal_label();
extern int assembly_func_end();
extern int assembly_switch();
extern int case_0();
extern int case_1();
extern int case_default();
extern int jump_table();
extern int lookup_table();
extern int assembly_switch_end();
// Functions invoked or referred by the .asm test stub.
int func1() {
return 1;
}
int func2() {
return 2;
}
int func3() {
return 3;
}
int func4() {
return 4;
}
} // extern "C"
namespace image_util {
class DisassemblerTest: public testing::Test {
public:
virtual void SetUp() {
on_instruction_.reset(NewCallback(this, &DisassemblerTest::OnInstruction));
}
MOCK_METHOD3(OnInstruction, void(const Disassembler&, const _DInst&, bool*));
static AbsoluteAddress AddressOf(const void* ptr) {
return AbsoluteAddress(reinterpret_cast<size_t>(ptr));
}
static const uint8* PointerTo(const void* ptr) {
return reinterpret_cast<const uint8*>(ptr);
}
void RecordFunctionEncounter(const Disassembler& disasm,
const _DInst& inst,
bool* continue_walk) {
switch (META_GET_FC(inst.meta)) {
case FC_CALL:
case FC_BRANCH:
ASSERT_EQ(O_PC, inst.ops[0].type);
if (inst.ops[0].size == 8) {
ASSERT_EQ(2, inst.size);
} else {
ASSERT_EQ(32, inst.ops[0].size);
ASSERT_EQ(5, inst.size);
functions_.push_back(
AbsoluteAddress(
static_cast<size_t>(inst.addr + inst.size + inst.imm.addr)));
}
break;
default:
break;
}
}
protected:
std::vector<AbsoluteAddress> functions_;
scoped_ptr<Disassembler::InstructionCallback> on_instruction_;
};
TEST_F(DisassemblerTest, Terminate) {
Disassembler disasm(PointerTo(&assembly_func),
PointerTo(&assembly_func_end) - PointerTo(&assembly_func),
AddressOf(&assembly_func),
on_instruction_.get());
ASSERT_TRUE(disasm.Unvisited(AddressOf(&assembly_func)));
// Terminate the walk on first visit.
EXPECT_CALL(*this, OnInstruction(_, _, _))
.WillRepeatedly(SetArgumentPointee<2>(false));
ASSERT_EQ(Disassembler::kWalkTerminated, disasm.Walk());
}
TEST_F(DisassemblerTest, DisassemblePartial) {
Disassembler disasm(PointerTo(&assembly_func),
PointerTo(&assembly_func_end) - PointerTo(&assembly_func),
AddressOf(&assembly_func),
on_instruction_.get());
ASSERT_TRUE(disasm.Unvisited(AddressOf(&assembly_func)));
// We should hit 6 instructions.
EXPECT_CALL(*this, OnInstruction(_, _, _)).Times(6);
ASSERT_EQ(Disassembler::kWalkSuccess, disasm.Walk());
// We should have disassembled everything save one call to func3 and
// the jump/lookup tables.
ASSERT_EQ(PointerTo(&assembly_func_end) - PointerTo(&assembly_func) - 5,
disasm.disassembled_bytes());
}
TEST_F(DisassemblerTest, DisassembleFull) {
Disassembler disasm(PointerTo(&assembly_func),
PointerTo(&assembly_func_end) - PointerTo(&assembly_func),
AddressOf(&assembly_func),
on_instruction_.get());
ASSERT_TRUE(disasm.Unvisited(AddressOf(&assembly_func)));
// Mark the internal label as well.
ASSERT_TRUE(disasm.Unvisited(AddressOf(&internal_label)));
// We should hit 7 instructions.
EXPECT_CALL(*this, OnInstruction(_, _, _)).Times(7);
ASSERT_EQ(Disassembler::kWalkSuccess, disasm.Walk());
// We should have disassembled everything.
ASSERT_EQ(PointerTo(&assembly_func_end) - PointerTo(&assembly_func),
disasm.disassembled_bytes());
}
TEST_F(DisassemblerTest, EnounterFunctions) {
Disassembler disasm(PointerTo(&assembly_func),
PointerTo(&assembly_func_end) - PointerTo(&assembly_func),
AddressOf(&assembly_func),
on_instruction_.get());
ASSERT_TRUE(disasm.Unvisited(AddressOf(&assembly_func)));
// Mark the internal label as well.
ASSERT_TRUE(disasm.Unvisited(AddressOf(&internal_label)));
// Record the functions we encounter along the way.
EXPECT_CALL(*this, OnInstruction(_, _, _))
.WillRepeatedly(Invoke(this,
&DisassemblerTest::RecordFunctionEncounter));
ASSERT_EQ(Disassembler::kWalkSuccess, disasm.Walk());
std::vector<AbsoluteAddress> expected;
expected.push_back(AddressOf(func1));
expected.push_back(AddressOf(func2));
expected.push_back(AddressOf(func3));
expected.push_back(AddressOf(func4));
EXPECT_THAT(functions_, testing::ContainerEq(expected));
}
TEST_F(DisassemblerTest, IdentifiesData) {
Disassembler disasm(
PointerTo(&assembly_switch),
PointerTo(&assembly_switch_end) - PointerTo(&assembly_switch),
AddressOf(&assembly_switch), on_instruction_.get());
// Mark the entry and the cases we jump to as
ASSERT_TRUE(disasm.Unvisited(AddressOf(&assembly_switch)));
ASSERT_TRUE(disasm.Unvisited(AddressOf(&case_0)));
ASSERT_TRUE(disasm.Unvisited(AddressOf(&case_1)));
ASSERT_TRUE(disasm.Unvisited(AddressOf(&case_default)));
// We expect to hit all the instructions in the function.
EXPECT_CALL(*this, OnInstruction(_, _, _))
.Times(10);
// We expect an incomplete walk from this.
ASSERT_EQ(Disassembler::kWalkIncomplete, disasm.Walk());
std::set<AbsoluteAddress> expected;
expected.insert(AddressOf(&jump_table));
expected.insert(AddressOf(&lookup_table));
EXPECT_THAT(disasm.data_locations(), testing::ContainerEq(expected));
}
} // namespace image_util
|
// Copyright 2011 Google 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.
//
// Implementation of disassembler.
#include "sawbuck/image_util/disassembler.h"
#include "base/scoped_ptr.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <vector>
using testing::_;
using testing::Invoke;
using testing::SetArgumentPointee;
extern "C" {
// functions and labels exposed from our .asm test stub.
extern int assembly_func();
extern int internal_label();
extern int assembly_func_end();
extern int assembly_switch();
extern int case_0();
extern int case_1();
extern int case_default();
extern int jump_table();
extern int lookup_table();
extern int assembly_switch_end();
// Functions invoked or referred by the .asm test stub.
int func1() {
return 1;
}
int func2() {
return 2;
}
int func3() {
return 3;
}
int func4() {
return 4;
}
} // extern "C"
namespace image_util {
class DisassemblerTest: public testing::Test {
public:
virtual void SetUp() {
on_instruction_.reset(NewCallback(this, &DisassemblerTest::OnInstruction));
}
MOCK_METHOD3(OnInstruction, void(const Disassembler&, const _DInst&, bool*));
static AbsoluteAddress AddressOf(const void* ptr) {
return AbsoluteAddress(reinterpret_cast<size_t>(ptr));
}
static const uint8* PointerTo(const void* ptr) {
return reinterpret_cast<const uint8*>(ptr);
}
void RecordFunctionEncounter(const Disassembler& disasm,
const _DInst& inst,
bool* continue_walk) {
switch (META_GET_FC(inst.meta)) {
case FC_CALL:
case FC_BRANCH:
ASSERT_EQ(O_PC, inst.ops[0].type);
if (inst.ops[0].size == 8) {
ASSERT_EQ(2, inst.size);
} else {
ASSERT_EQ(32, inst.ops[0].size);
ASSERT_EQ(5, inst.size);
functions_.push_back(
AbsoluteAddress(
static_cast<size_t>(inst.addr + inst.size + inst.imm.addr)));
}
break;
default:
break;
}
}
protected:
std::vector<AbsoluteAddress> functions_;
scoped_ptr<Disassembler::InstructionCallback> on_instruction_;
};
TEST_F(DisassemblerTest, Terminate) {
Disassembler disasm(PointerTo(&assembly_func),
PointerTo(&assembly_func_end) - PointerTo(&assembly_func),
AddressOf(&assembly_func),
on_instruction_.get());
ASSERT_TRUE(disasm.Unvisited(AddressOf(&assembly_func)));
// Terminate the walk on first visit.
EXPECT_CALL(*this, OnInstruction(_, _, _))
.WillRepeatedly(SetArgumentPointee<2>(false));
ASSERT_EQ(Disassembler::kWalkTerminated, disasm.Walk());
}
TEST_F(DisassemblerTest, DisassemblePartial) {
Disassembler disasm(PointerTo(&assembly_func),
PointerTo(&assembly_func_end) - PointerTo(&assembly_func),
AddressOf(&assembly_func),
on_instruction_.get());
ASSERT_TRUE(disasm.Unvisited(AddressOf(&assembly_func)));
// We should hit 6 instructions.
EXPECT_CALL(*this, OnInstruction(_, _, _)).Times(6);
ASSERT_EQ(Disassembler::kWalkSuccess, disasm.Walk());
// We should have disassembled everything save one call to func3 and
// the jump/lookup tables.
ASSERT_EQ(PointerTo(&assembly_func_end) - PointerTo(&assembly_func) - 5,
disasm.disassembled_bytes());
}
TEST_F(DisassemblerTest, DisassembleFull) {
Disassembler disasm(PointerTo(&assembly_func),
PointerTo(&assembly_func_end) - PointerTo(&assembly_func),
AddressOf(&assembly_func),
on_instruction_.get());
ASSERT_TRUE(disasm.Unvisited(AddressOf(&assembly_func)));
// Mark the internal label as well.
ASSERT_TRUE(disasm.Unvisited(AddressOf(&internal_label)));
// We should hit 7 instructions.
EXPECT_CALL(*this, OnInstruction(_, _, _)).Times(7);
ASSERT_EQ(Disassembler::kWalkSuccess, disasm.Walk());
// We should have disassembled everything.
ASSERT_EQ(PointerTo(&assembly_func_end) - PointerTo(&assembly_func),
disasm.disassembled_bytes());
}
TEST_F(DisassemblerTest, EnounterFunctions) {
Disassembler disasm(PointerTo(&assembly_func),
PointerTo(&assembly_func_end) - PointerTo(&assembly_func),
AddressOf(&assembly_func),
on_instruction_.get());
ASSERT_TRUE(disasm.Unvisited(AddressOf(&assembly_func)));
// Mark the internal label as well.
ASSERT_TRUE(disasm.Unvisited(AddressOf(&internal_label)));
// Record the functions we encounter along the way.
EXPECT_CALL(*this, OnInstruction(_, _, _))
.WillRepeatedly(Invoke(this,
&DisassemblerTest::RecordFunctionEncounter));
ASSERT_EQ(Disassembler::kWalkSuccess, disasm.Walk());
std::vector<AbsoluteAddress> expected;
expected.push_back(AddressOf(func1));
expected.push_back(AddressOf(func2));
expected.push_back(AddressOf(func3));
expected.push_back(AddressOf(func4));
EXPECT_THAT(functions_, testing::ContainerEq(expected));
}
TEST_F(DisassemblerTest, IdentifiesData) {
Disassembler disasm(
PointerTo(&assembly_switch),
PointerTo(&assembly_switch_end) - PointerTo(&assembly_switch),
AddressOf(&assembly_switch), on_instruction_.get());
// Mark the entry and the cases we jump to as
ASSERT_TRUE(disasm.Unvisited(AddressOf(&assembly_switch)));
ASSERT_TRUE(disasm.Unvisited(AddressOf(&case_0)));
ASSERT_TRUE(disasm.Unvisited(AddressOf(&case_1)));
ASSERT_TRUE(disasm.Unvisited(AddressOf(&case_default)));
// We expect to hit all the instructions in the function.
EXPECT_CALL(*this, OnInstruction(_, _, _))
.Times(9);
// We expect an incomplete walk from this.
ASSERT_EQ(Disassembler::kWalkIncomplete, disasm.Walk());
std::set<AbsoluteAddress> expected;
expected.insert(AddressOf(&jump_table));
expected.insert(AddressOf(&lookup_table));
EXPECT_THAT(disasm.data_locations(), testing::ContainerEq(expected));
}
} // namespace image_util
|
Fix an error I forgot to add to the previous CL.
|
Fix an error I forgot to add to the previous CL.
BUG=None
TEST=None
Review URL: http://codereview.appspot.com/3972042
git-svn-id: db59699583a60be9a535cd09cdc9132301867226@150 15e8cca8-e42c-11de-a347-f34a4f72eb7d
|
C++
|
apache-2.0
|
ericmckean/syzygy,pombreda/syzygy,ericmckean/syzygy,supriyantomaftuh/syzygy,ericmckean/syzygy,pombreda/syzygy,sebmarchand/syzygy,ericmckean/syzygy,sebmarchand/syzygy,wangming28/syzygy,wangming28/syzygy,pombreda/syzygy,google/syzygy,google/syzygy,google/syzygy,sebmarchand/syzygy,supriyantomaftuh/syzygy,sebmarchand/syzygy,sebmarchand/syzygy,ericmckean/syzygy,pombreda/syzygy,google/syzygy,pombreda/syzygy,wangming28/syzygy,wangming28/syzygy,supriyantomaftuh/syzygy,Eloston/syzygy,Eloston/syzygy,supriyantomaftuh/syzygy
|
49f201214055c8eaffa3eef91b87c4997afadc45
|
lib/Transforms/IPO/FunctionResolution.cpp
|
lib/Transforms/IPO/FunctionResolution.cpp
|
//===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
//
// Loop over the functions that are in the module and look for functions that
// have the same name. More often than not, there will be things like:
//
// declare void %foo(...)
// void %foo(int, int) { ... }
//
// because of the way things are declared in C. If this is the case, patch
// things up.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Module.h"
#include "llvm/SymbolTable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Pass.h"
#include "llvm/iOther.h"
#include "llvm/Constants.h"
#include "llvm/Assembly/Writer.h" // FIXME: remove when varargs implemented
#include "Support/Statistic.h"
#include <algorithm>
namespace {
Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
struct FunctionResolvingPass : public Pass {
bool run(Module &M);
};
RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
}
Pass *createFunctionResolvingPass() {
return new FunctionResolvingPass();
}
// ConvertCallTo - Convert a call to a varargs function with no arg types
// specified to a concrete nonvarargs function.
//
static void ConvertCallTo(CallInst *CI, Function *Dest) {
const FunctionType::ParamTypes &ParamTys =
Dest->getFunctionType()->getParamTypes();
BasicBlock *BB = CI->getParent();
// Keep an iterator to where we want to insert cast instructions if the
// argument types don't agree.
//
BasicBlock::iterator BBI = CI;
if (CI->getNumOperands()-1 != ParamTys.size()) {
std::cerr << "WARNING: Call arguments do not match expected number of"
<< " parameters.\n";
std::cerr << "WARNING: In function '"
<< CI->getParent()->getParent()->getName() << "': call: " << *CI;
std::cerr << "Function resolved to: ";
WriteAsOperand(std::cerr, Dest);
std::cerr << "\n";
}
std::vector<Value*> Params;
// Convert all of the call arguments over... inserting cast instructions if
// the types are not compatible.
for (unsigned i = 1; i <= ParamTys.size(); ++i) {
Value *V = CI->getOperand(i);
if (V->getType() != ParamTys[i-1]) // Must insert a cast...
V = new CastInst(V, ParamTys[i-1], "argcast", BBI);
Params.push_back(V);
}
// Replace the old call instruction with a new call instruction that calls
// the real function.
//
Instruction *NewCall = new CallInst(Dest, Params, "", BBI);
// Remove the old call instruction from the program...
BB->getInstList().remove(BBI);
// Transfer the name over...
if (NewCall->getType() != Type::VoidTy)
NewCall->setName(CI->getName());
// Replace uses of the old instruction with the appropriate values...
//
if (NewCall->getType() == CI->getType()) {
CI->replaceAllUsesWith(NewCall);
NewCall->setName(CI->getName());
} else if (NewCall->getType() == Type::VoidTy) {
// Resolved function does not return a value but the prototype does. This
// often occurs because undefined functions default to returning integers.
// Just replace uses of the call (which are broken anyway) with dummy
// values.
CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
} else if (CI->getType() == Type::VoidTy) {
// If we are gaining a new return value, we don't have to do anything
// special here, because it will automatically be ignored.
} else {
// Insert a cast instruction to convert the return value of the function
// into it's new type. Of course we only need to do this if the return
// value of the function is actually USED.
//
if (!CI->use_empty()) {
// Insert the new cast instruction...
CastInst *NewCast = new CastInst(NewCall, CI->getType(),
NewCall->getName(), BBI);
CI->replaceAllUsesWith(NewCast);
}
}
// The old instruction is no longer needed, destroy it!
delete CI;
}
static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
Function *Concrete) {
bool Changed = false;
for (unsigned i = 0; i != Globals.size(); ++i)
if (Globals[i] != Concrete) {
Function *Old = cast<Function>(Globals[i]);
const FunctionType *OldMT = Old->getFunctionType();
const FunctionType *ConcreteMT = Concrete->getFunctionType();
assert(OldMT->getParamTypes().size() <=
ConcreteMT->getParamTypes().size() &&
"Concrete type must have more specified parameters!");
// Check to make sure that if there are specified types, that they
// match...
//
for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
std::cerr << "funcresolve: Function [" << Old->getName()
<< "]: Parameter types conflict for: '" << OldMT
<< "' and '" << ConcreteMT << "'\n";
return Changed;
}
// Attempt to convert all of the uses of the old function to the
// concrete form of the function. If there is a use of the fn that
// we don't understand here we punt to avoid making a bad
// transformation.
//
// At this point, we know that the return values are the same for
// our two functions and that the Old function has no varargs fns
// specified. In otherwords it's just <retty> (...)
//
for (unsigned i = 0; i < Old->use_size(); ) {
User *U = *(Old->use_begin()+i);
if (CastInst *CI = dyn_cast<CastInst>(U)) {
// Convert casts directly
assert(CI->getOperand(0) == Old);
CI->setOperand(0, Concrete);
Changed = true;
++NumResolved;
} else if (CallInst *CI = dyn_cast<CallInst>(U)) {
// Can only fix up calls TO the argument, not args passed in.
if (CI->getCalledValue() == Old) {
ConvertCallTo(CI, Concrete);
Changed = true;
++NumResolved;
} else {
std::cerr << "Couldn't cleanup this function call, must be an"
<< " argument or something!" << CI;
++i;
}
} else {
std::cerr << "Cannot convert use of function: " << U << "\n";
++i;
}
}
}
return Changed;
}
static bool ResolveGlobalVariables(Module &M,
std::vector<GlobalValue*> &Globals,
GlobalVariable *Concrete) {
bool Changed = false;
assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
"Concrete version should be an array type!");
// Get the type of the things that may be resolved to us...
const Type *AETy =
cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();
std::vector<Constant*> Args;
Args.push_back(Constant::getNullValue(Type::LongTy));
Args.push_back(Constant::getNullValue(Type::LongTy));
ConstantExpr *Replacement =
ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);
for (unsigned i = 0; i != Globals.size(); ++i)
if (Globals[i] != Concrete) {
GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
if (Old->getType()->getElementType() != AETy) {
std::cerr << "WARNING: Two global variables exist with the same name "
<< "that cannot be resolved!\n";
return false;
}
// In this case, Old is a pointer to T, Concrete is a pointer to array of
// T. Because of this, replace all uses of Old with a constantexpr
// getelementptr that returns the address of the first element of the
// array.
//
Old->replaceAllUsesWith(Replacement);
// Since there are no uses of Old anymore, remove it from the module.
M.getGlobalList().erase(Old);
++NumGlobals;
Changed = true;
}
return Changed;
}
static bool ProcessGlobalsWithSameName(Module &M,
std::vector<GlobalValue*> &Globals) {
assert(!Globals.empty() && "Globals list shouldn't be empty here!");
bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
bool Changed = false;
GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
"Should either be function or gvar!");
for (unsigned i = 0; i != Globals.size(); ) {
if (isa<Function>(Globals[i]) != isFunction) {
std::cerr << "WARNING: Found function and global variable with the "
<< "same name: '" << Globals[i]->getName() << "'.\n";
return false; // Don't know how to handle this, bail out!
}
if (isFunction) {
// For functions, we look to merge functions definitions of "int (...)"
// to 'int (int)' or 'int ()' or whatever else is not completely generic.
//
Function *F = cast<Function>(Globals[i]);
if (!F->isExternal()) {
if (Concrete && !Concrete->isExternal())
return false; // Found two different functions types. Can't choose!
Concrete = Globals[i];
} else if (Concrete) {
if (Concrete->isExternal()) // If we have multiple external symbols...x
if (F->getFunctionType()->getNumParams() >
cast<Function>(Concrete)->getFunctionType()->getNumParams())
Concrete = F; // We are more concrete than "Concrete"!
} else {
Concrete = F;
}
++i;
} else {
// For global variables, we have to merge C definitions int A[][4] with
// int[6][4]
GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
if (Concrete == 0) {
if (isa<ArrayType>(GV->getType()->getElementType()))
Concrete = GV;
} else { // Must have different types... one is an array of the other?
const ArrayType *AT =
dyn_cast<ArrayType>(GV->getType()->getElementType());
// If GV is an array of Concrete, then GV is the array.
if (AT && AT->getElementType() == Concrete->getType()->getElementType())
Concrete = GV;
else {
// Concrete must be an array type, check to see if the element type of
// concrete is already GV.
AT = cast<ArrayType>(Concrete->getType()->getElementType());
if (AT->getElementType() != GV->getType()->getElementType())
Concrete = 0; // Don't know how to handle it!
}
}
++i;
}
}
if (Globals.size() > 1) { // Found a multiply defined global...
// We should find exactly one concrete function definition, which is
// probably the implementation. Change all of the function definitions and
// uses to use it instead.
//
if (!Concrete) {
std::cerr << "WARNING: Found function types that are not compatible:\n";
for (unsigned i = 0; i < Globals.size(); ++i) {
std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
<< Globals[i]->getName() << "\n";
}
std::cerr << " No linkage of globals named '" << Globals[0]->getName()
<< "' performed!\n";
return Changed;
}
if (isFunction)
return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));
else
return Changed | ResolveGlobalVariables(M, Globals,
cast<GlobalVariable>(Concrete));
}
return Changed;
}
bool FunctionResolvingPass::run(Module &M) {
SymbolTable &ST = M.getSymbolTable();
std::map<std::string, std::vector<GlobalValue*> > Globals;
// Loop over the entries in the symbol table. If an entry is a func pointer,
// then add it to the Functions map. We do a two pass algorithm here to avoid
// problems with iterators getting invalidated if we did a one pass scheme.
//
for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
SymbolTable::VarMap &Plane = I->second;
for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
PI != PE; ++PI) {
GlobalValue *GV = cast<GlobalValue>(PI->second);
assert(PI->first == GV->getName() &&
"Global name and symbol table do not agree!");
if (GV->hasExternalLinkage()) // Only resolve decls to external fns
Globals[PI->first].push_back(GV);
}
}
bool Changed = false;
// Now we have a list of all functions with a particular name. If there is
// more than one entry in a list, merge the functions together.
//
for (std::map<std::string, std::vector<GlobalValue*> >::iterator
I = Globals.begin(), E = Globals.end(); I != E; ++I)
Changed |= ProcessGlobalsWithSameName(M, I->second);
// Now loop over all of the globals, checking to see if any are trivially
// dead. If so, remove them now.
for (Module::iterator I = M.begin(), E = M.end(); I != E; )
if (I->isExternal() && I->use_empty()) {
Function *F = I;
++I;
M.getFunctionList().erase(F);
++NumResolved;
Changed = true;
} else {
++I;
}
for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
if (I->isExternal() && I->use_empty()) {
GlobalVariable *GV = I;
++I;
M.getGlobalList().erase(GV);
++NumGlobals;
Changed = true;
} else {
++I;
}
return Changed;
}
|
//===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
//
// Loop over the functions that are in the module and look for functions that
// have the same name. More often than not, there will be things like:
//
// declare void %foo(...)
// void %foo(int, int) { ... }
//
// because of the way things are declared in C. If this is the case, patch
// things up.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO.h"
#include "llvm/Module.h"
#include "llvm/SymbolTable.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Pass.h"
#include "llvm/iOther.h"
#include "llvm/Constants.h"
#include "llvm/Assembly/Writer.h" // FIXME: remove when varargs implemented
#include "Support/Statistic.h"
#include <algorithm>
namespace {
Statistic<>NumResolved("funcresolve", "Number of varargs functions resolved");
Statistic<> NumGlobals("funcresolve", "Number of global variables resolved");
struct FunctionResolvingPass : public Pass {
bool run(Module &M);
};
RegisterOpt<FunctionResolvingPass> X("funcresolve", "Resolve Functions");
}
Pass *createFunctionResolvingPass() {
return new FunctionResolvingPass();
}
// ConvertCallTo - Convert a call to a varargs function with no arg types
// specified to a concrete nonvarargs function.
//
static void ConvertCallTo(CallInst *CI, Function *Dest) {
const FunctionType::ParamTypes &ParamTys =
Dest->getFunctionType()->getParamTypes();
BasicBlock *BB = CI->getParent();
// Keep an iterator to where we want to insert cast instructions if the
// argument types don't agree.
//
BasicBlock::iterator BBI = CI;
unsigned NumArgsToCopy = CI->getNumOperands()-1;
if (CI->getNumOperands()-1 != ParamTys.size() &&
!(CI->getNumOperands()-1 > ParamTys.size() &&
Dest->getFunctionType()->isVarArg())) {
std::cerr << "WARNING: Call arguments do not match expected number of"
<< " parameters.\n";
std::cerr << "WARNING: In function '"
<< CI->getParent()->getParent()->getName() << "': call: " << *CI;
std::cerr << "Function resolved to: ";
WriteAsOperand(std::cerr, Dest);
std::cerr << "\n";
}
std::vector<Value*> Params;
// Convert all of the call arguments over... inserting cast instructions if
// the types are not compatible.
for (unsigned i = 1; i <= NumArgsToCopy; ++i) {
Value *V = CI->getOperand(i);
if (i-1 < ParamTys.size() && V->getType() != ParamTys[i-1]) {
// Must insert a cast...
V = new CastInst(V, ParamTys[i-1], "argcast", BBI);
}
Params.push_back(V);
}
// Replace the old call instruction with a new call instruction that calls
// the real function.
//
Instruction *NewCall = new CallInst(Dest, Params, "", BBI);
// Remove the old call instruction from the program...
BB->getInstList().remove(BBI);
// Transfer the name over...
if (NewCall->getType() != Type::VoidTy)
NewCall->setName(CI->getName());
// Replace uses of the old instruction with the appropriate values...
//
if (NewCall->getType() == CI->getType()) {
CI->replaceAllUsesWith(NewCall);
NewCall->setName(CI->getName());
} else if (NewCall->getType() == Type::VoidTy) {
// Resolved function does not return a value but the prototype does. This
// often occurs because undefined functions default to returning integers.
// Just replace uses of the call (which are broken anyway) with dummy
// values.
CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
} else if (CI->getType() == Type::VoidTy) {
// If we are gaining a new return value, we don't have to do anything
// special here, because it will automatically be ignored.
} else {
// Insert a cast instruction to convert the return value of the function
// into it's new type. Of course we only need to do this if the return
// value of the function is actually USED.
//
if (!CI->use_empty()) {
// Insert the new cast instruction...
CastInst *NewCast = new CastInst(NewCall, CI->getType(),
NewCall->getName(), BBI);
CI->replaceAllUsesWith(NewCast);
}
}
// The old instruction is no longer needed, destroy it!
delete CI;
}
static bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,
Function *Concrete) {
bool Changed = false;
for (unsigned i = 0; i != Globals.size(); ++i)
if (Globals[i] != Concrete) {
Function *Old = cast<Function>(Globals[i]);
const FunctionType *OldMT = Old->getFunctionType();
const FunctionType *ConcreteMT = Concrete->getFunctionType();
assert(OldMT->getParamTypes().size() <=
ConcreteMT->getParamTypes().size() &&
"Concrete type must have more specified parameters!");
// Check to make sure that if there are specified types, that they
// match...
//
for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)
if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {
std::cerr << "funcresolve: Function [" << Old->getName()
<< "]: Parameter types conflict for: '" << OldMT
<< "' and '" << ConcreteMT << "'\n";
return Changed;
}
// Attempt to convert all of the uses of the old function to the
// concrete form of the function. If there is a use of the fn that
// we don't understand here we punt to avoid making a bad
// transformation.
//
// At this point, we know that the return values are the same for
// our two functions and that the Old function has no varargs fns
// specified. In otherwords it's just <retty> (...)
//
for (unsigned i = 0; i < Old->use_size(); ) {
User *U = *(Old->use_begin()+i);
if (CastInst *CI = dyn_cast<CastInst>(U)) {
// Convert casts directly
assert(CI->getOperand(0) == Old);
CI->setOperand(0, Concrete);
Changed = true;
++NumResolved;
} else if (CallInst *CI = dyn_cast<CallInst>(U)) {
// Can only fix up calls TO the argument, not args passed in.
if (CI->getCalledValue() == Old) {
ConvertCallTo(CI, Concrete);
Changed = true;
++NumResolved;
} else {
std::cerr << "Couldn't cleanup this function call, must be an"
<< " argument or something!" << CI;
++i;
}
} else {
std::cerr << "Cannot convert use of function: " << U << "\n";
++i;
}
}
}
return Changed;
}
static bool ResolveGlobalVariables(Module &M,
std::vector<GlobalValue*> &Globals,
GlobalVariable *Concrete) {
bool Changed = false;
assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&
"Concrete version should be an array type!");
// Get the type of the things that may be resolved to us...
const Type *AETy =
cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();
std::vector<Constant*> Args;
Args.push_back(Constant::getNullValue(Type::LongTy));
Args.push_back(Constant::getNullValue(Type::LongTy));
ConstantExpr *Replacement =
ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);
for (unsigned i = 0; i != Globals.size(); ++i)
if (Globals[i] != Concrete) {
GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);
if (Old->getType()->getElementType() != AETy) {
std::cerr << "WARNING: Two global variables exist with the same name "
<< "that cannot be resolved!\n";
return false;
}
// In this case, Old is a pointer to T, Concrete is a pointer to array of
// T. Because of this, replace all uses of Old with a constantexpr
// getelementptr that returns the address of the first element of the
// array.
//
Old->replaceAllUsesWith(Replacement);
// Since there are no uses of Old anymore, remove it from the module.
M.getGlobalList().erase(Old);
++NumGlobals;
Changed = true;
}
return Changed;
}
static bool ProcessGlobalsWithSameName(Module &M,
std::vector<GlobalValue*> &Globals) {
assert(!Globals.empty() && "Globals list shouldn't be empty here!");
bool isFunction = isa<Function>(Globals[0]); // Is this group all functions?
bool Changed = false;
GlobalValue *Concrete = 0; // The most concrete implementation to resolve to
assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&
"Should either be function or gvar!");
for (unsigned i = 0; i != Globals.size(); ) {
if (isa<Function>(Globals[i]) != isFunction) {
std::cerr << "WARNING: Found function and global variable with the "
<< "same name: '" << Globals[i]->getName() << "'.\n";
return false; // Don't know how to handle this, bail out!
}
if (isFunction) {
// For functions, we look to merge functions definitions of "int (...)"
// to 'int (int)' or 'int ()' or whatever else is not completely generic.
//
Function *F = cast<Function>(Globals[i]);
if (!F->isExternal()) {
if (Concrete && !Concrete->isExternal())
return false; // Found two different functions types. Can't choose!
Concrete = Globals[i];
} else if (Concrete) {
if (Concrete->isExternal()) // If we have multiple external symbols...x
if (F->getFunctionType()->getNumParams() >
cast<Function>(Concrete)->getFunctionType()->getNumParams())
Concrete = F; // We are more concrete than "Concrete"!
} else {
Concrete = F;
}
++i;
} else {
// For global variables, we have to merge C definitions int A[][4] with
// int[6][4]
GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);
if (Concrete == 0) {
if (isa<ArrayType>(GV->getType()->getElementType()))
Concrete = GV;
} else { // Must have different types... one is an array of the other?
const ArrayType *AT =
dyn_cast<ArrayType>(GV->getType()->getElementType());
// If GV is an array of Concrete, then GV is the array.
if (AT && AT->getElementType() == Concrete->getType()->getElementType())
Concrete = GV;
else {
// Concrete must be an array type, check to see if the element type of
// concrete is already GV.
AT = cast<ArrayType>(Concrete->getType()->getElementType());
if (AT->getElementType() != GV->getType()->getElementType())
Concrete = 0; // Don't know how to handle it!
}
}
++i;
}
}
if (Globals.size() > 1) { // Found a multiply defined global...
// We should find exactly one concrete function definition, which is
// probably the implementation. Change all of the function definitions and
// uses to use it instead.
//
if (!Concrete) {
std::cerr << "WARNING: Found function types that are not compatible:\n";
for (unsigned i = 0; i < Globals.size(); ++i) {
std::cerr << "\t" << Globals[i]->getType()->getDescription() << " %"
<< Globals[i]->getName() << "\n";
}
std::cerr << " No linkage of globals named '" << Globals[0]->getName()
<< "' performed!\n";
return Changed;
}
if (isFunction)
return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));
else
return Changed | ResolveGlobalVariables(M, Globals,
cast<GlobalVariable>(Concrete));
}
return Changed;
}
bool FunctionResolvingPass::run(Module &M) {
SymbolTable &ST = M.getSymbolTable();
std::map<std::string, std::vector<GlobalValue*> > Globals;
// Loop over the entries in the symbol table. If an entry is a func pointer,
// then add it to the Functions map. We do a two pass algorithm here to avoid
// problems with iterators getting invalidated if we did a one pass scheme.
//
for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)
if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {
SymbolTable::VarMap &Plane = I->second;
for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();
PI != PE; ++PI) {
GlobalValue *GV = cast<GlobalValue>(PI->second);
assert(PI->first == GV->getName() &&
"Global name and symbol table do not agree!");
if (GV->hasExternalLinkage()) // Only resolve decls to external fns
Globals[PI->first].push_back(GV);
}
}
bool Changed = false;
// Now we have a list of all functions with a particular name. If there is
// more than one entry in a list, merge the functions together.
//
for (std::map<std::string, std::vector<GlobalValue*> >::iterator
I = Globals.begin(), E = Globals.end(); I != E; ++I)
Changed |= ProcessGlobalsWithSameName(M, I->second);
// Now loop over all of the globals, checking to see if any are trivially
// dead. If so, remove them now.
for (Module::iterator I = M.begin(), E = M.end(); I != E; )
if (I->isExternal() && I->use_empty()) {
Function *F = I;
++I;
M.getFunctionList().erase(F);
++NumResolved;
Changed = true;
} else {
++I;
}
for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )
if (I->isExternal() && I->use_empty()) {
GlobalVariable *GV = I;
++I;
M.getGlobalList().erase(GV);
++NumGlobals;
Changed = true;
} else {
++I;
}
return Changed;
}
|
Fix a bug resolving sprintf(...) to sprintf(char*, char*, ...)
|
Fix a bug resolving sprintf(...) to sprintf(char*, char*, ...)
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@5446 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm
|
d802f7e29067a33c2e9db841d5b8052ef474d856
|
lib/Transforms/Utils/LowerAllocations.cpp
|
lib/Transforms/Utils/LowerAllocations.cpp
|
//===- LowerAllocations.cpp - Reduce malloc & free insts to calls ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The LowerAllocations transformation is a target-dependent tranformation
// because it depends on the size of data types and alignment constraints.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "lowerallocs"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Constants.h"
#include "llvm/LLVMContext.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/Compiler.h"
using namespace llvm;
STATISTIC(NumLowered, "Number of allocations lowered");
namespace {
/// LowerAllocations - Turn malloc and free instructions into %malloc and
/// %free calls.
///
class VISIBILITY_HIDDEN LowerAllocations : public BasicBlockPass {
Constant *MallocFunc; // Functions in the module we are processing
Constant *FreeFunc; // Initialized by doInitialization
bool LowerMallocArgToInteger;
public:
static char ID; // Pass ID, replacement for typeid
explicit LowerAllocations(bool LowerToInt = false)
: BasicBlockPass(&ID), MallocFunc(0), FreeFunc(0),
LowerMallocArgToInteger(LowerToInt) {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetData>();
AU.setPreservesCFG();
// This is a cluster of orthogonal Transforms:
AU.addPreserved<UnifyFunctionExitNodes>();
AU.addPreservedID(PromoteMemoryToRegisterID);
AU.addPreservedID(LowerSwitchID);
AU.addPreservedID(LowerInvokePassID);
}
/// doPassInitialization - For the lower allocations pass, this ensures that
/// a module contains a declaration for a malloc and a free function.
///
bool doInitialization(Module &M);
virtual bool doInitialization(Function &F) {
return doInitialization(*F.getParent());
}
/// runOnBasicBlock - This method does the actual work of converting
/// instructions over, assuming that the pass has already been initialized.
///
bool runOnBasicBlock(BasicBlock &BB);
};
}
char LowerAllocations::ID = 0;
static RegisterPass<LowerAllocations>
X("lowerallocs", "Lower allocations from instructions to calls");
// Publically exposed interface to pass...
const PassInfo *const llvm::LowerAllocationsID = &X;
// createLowerAllocationsPass - Interface to this file...
Pass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
return new LowerAllocations(LowerMallocArgToInteger);
}
// doInitialization - For the lower allocations pass, this ensures that a
// module contains a declaration for a malloc and a free function.
//
// This function is always successful.
//
bool LowerAllocations::doInitialization(Module &M) {
const Type *BPTy = PointerType::getUnqual(Type::getInt8Ty(M.getContext()));
// Prototype malloc as "char* malloc(...)", because we don't know in
// doInitialization whether size_t is int or long.
FunctionType *FT = FunctionType::get(BPTy, true);
MallocFunc = M.getOrInsertFunction("malloc", FT);
FreeFunc = M.getOrInsertFunction("free" , Type::getVoidTy(M.getContext()),
BPTy, (Type *)0);
return true;
}
// runOnBasicBlock - This method does the actual work of converting
// instructions over, assuming that the pass has already been initialized.
//
bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
bool Changed = false;
assert(MallocFunc && FreeFunc && "Pass not initialized!");
BasicBlock::InstListType &BBIL = BB.getInstList();
const TargetData &TD = getAnalysis<TargetData>();
const Type *IntPtrTy = TD.getIntPtrType(BB.getContext());
// Loop over all of the instructions, looking for malloc or free instructions
for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
const Type *AllocTy = MI->getType()->getElementType();
// malloc(type) becomes i8 *malloc(size)
Value *MallocArg;
if (LowerMallocArgToInteger)
MallocArg = ConstantInt::get(Type::getInt64Ty(BB.getContext()),
TD.getTypeAllocSize(AllocTy));
else
MallocArg = ConstantExpr::getSizeOf(AllocTy);
MallocArg =
ConstantExpr::getTruncOrBitCast(cast<Constant>(MallocArg),
IntPtrTy);
if (MI->isArrayAllocation()) {
if (isa<ConstantInt>(MallocArg) &&
cast<ConstantInt>(MallocArg)->isOne()) {
MallocArg = MI->getOperand(0); // Operand * 1 = Operand
} else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
CO =
ConstantExpr::getIntegerCast(CO, IntPtrTy, false /*ZExt*/);
MallocArg = ConstantExpr::getMul(CO,
cast<Constant>(MallocArg));
} else {
Value *Scale = MI->getOperand(0);
if (Scale->getType() != IntPtrTy)
Scale = CastInst::CreateIntegerCast(Scale, IntPtrTy, false /*ZExt*/,
"", I);
// Multiply it by the array size if necessary...
MallocArg = BinaryOperator::Create(Instruction::Mul, Scale,
MallocArg, "", I);
}
}
// Create the call to Malloc.
CallInst *MCall = CallInst::Create(MallocFunc, MallocArg, "", I);
MCall->setTailCall();
// Create a cast instruction to convert to the right type...
Value *MCast;
if (MCall->getType() != Type::getVoidTy(BB.getContext()))
MCast = new BitCastInst(MCall, MI->getType(), "", I);
else
MCast = Constant::getNullValue(MI->getType());
// Replace all uses of the old malloc inst with the cast inst
MI->replaceAllUsesWith(MCast);
I = --BBIL.erase(I); // remove and delete the malloc instr...
Changed = true;
++NumLowered;
} else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
Value *PtrCast =
new BitCastInst(FI->getOperand(0),
PointerType::getUnqual(Type::getInt8Ty(BB.getContext())), "", I);
// Insert a call to the free function...
CallInst::Create(FreeFunc, PtrCast, "", I)->setTailCall();
// Delete the old free instruction
I = --BBIL.erase(I);
Changed = true;
++NumLowered;
}
}
return Changed;
}
|
//===- LowerAllocations.cpp - Reduce malloc & free insts to calls ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The LowerAllocations transformation is a target-dependent tranformation
// because it depends on the size of data types and alignment constraints.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "lowerallocs"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Constants.h"
#include "llvm/LLVMContext.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/Compiler.h"
using namespace llvm;
STATISTIC(NumLowered, "Number of allocations lowered");
namespace {
/// LowerAllocations - Turn malloc and free instructions into @malloc and
/// @free calls.
///
class VISIBILITY_HIDDEN LowerAllocations : public BasicBlockPass {
Constant *MallocFunc; // Functions in the module we are processing
Constant *FreeFunc; // Initialized by doInitialization
bool LowerMallocArgToInteger;
public:
static char ID; // Pass ID, replacement for typeid
explicit LowerAllocations(bool LowerToInt = false)
: BasicBlockPass(&ID), MallocFunc(0), FreeFunc(0),
LowerMallocArgToInteger(LowerToInt) {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetData>();
AU.setPreservesCFG();
// This is a cluster of orthogonal Transforms:
AU.addPreserved<UnifyFunctionExitNodes>();
AU.addPreservedID(PromoteMemoryToRegisterID);
AU.addPreservedID(LowerSwitchID);
AU.addPreservedID(LowerInvokePassID);
}
/// doPassInitialization - For the lower allocations pass, this ensures that
/// a module contains a declaration for a malloc and a free function.
///
bool doInitialization(Module &M);
virtual bool doInitialization(Function &F) {
return doInitialization(*F.getParent());
}
/// runOnBasicBlock - This method does the actual work of converting
/// instructions over, assuming that the pass has already been initialized.
///
bool runOnBasicBlock(BasicBlock &BB);
};
}
char LowerAllocations::ID = 0;
static RegisterPass<LowerAllocations>
X("lowerallocs", "Lower allocations from instructions to calls");
// Publically exposed interface to pass...
const PassInfo *const llvm::LowerAllocationsID = &X;
// createLowerAllocationsPass - Interface to this file...
Pass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
return new LowerAllocations(LowerMallocArgToInteger);
}
// doInitialization - For the lower allocations pass, this ensures that a
// module contains a declaration for a malloc and a free function.
//
// This function is always successful.
//
bool LowerAllocations::doInitialization(Module &M) {
const Type *BPTy = PointerType::getUnqual(Type::getInt8Ty(M.getContext()));
// Prototype malloc as "char* malloc(...)", because we don't know in
// doInitialization whether size_t is int or long.
FunctionType *FT = FunctionType::get(BPTy, true);
MallocFunc = M.getOrInsertFunction("malloc", FT);
FreeFunc = M.getOrInsertFunction("free" , Type::getVoidTy(M.getContext()),
BPTy, (Type *)0);
return true;
}
// runOnBasicBlock - This method does the actual work of converting
// instructions over, assuming that the pass has already been initialized.
//
bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
bool Changed = false;
assert(MallocFunc && FreeFunc && "Pass not initialized!");
BasicBlock::InstListType &BBIL = BB.getInstList();
const TargetData &TD = getAnalysis<TargetData>();
const Type *IntPtrTy = TD.getIntPtrType(BB.getContext());
// Loop over all of the instructions, looking for malloc or free instructions
for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
const Type *AllocTy = MI->getType()->getElementType();
// malloc(type) becomes i8 *malloc(size)
Value *MallocArg;
if (LowerMallocArgToInteger)
MallocArg = ConstantInt::get(Type::getInt64Ty(BB.getContext()),
TD.getTypeAllocSize(AllocTy));
else
MallocArg = ConstantExpr::getSizeOf(AllocTy);
MallocArg =
ConstantExpr::getTruncOrBitCast(cast<Constant>(MallocArg),
IntPtrTy);
if (MI->isArrayAllocation()) {
if (isa<ConstantInt>(MallocArg) &&
cast<ConstantInt>(MallocArg)->isOne()) {
MallocArg = MI->getOperand(0); // Operand * 1 = Operand
} else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
CO =
ConstantExpr::getIntegerCast(CO, IntPtrTy, false /*ZExt*/);
MallocArg = ConstantExpr::getMul(CO,
cast<Constant>(MallocArg));
} else {
Value *Scale = MI->getOperand(0);
if (Scale->getType() != IntPtrTy)
Scale = CastInst::CreateIntegerCast(Scale, IntPtrTy, false /*ZExt*/,
"", I);
// Multiply it by the array size if necessary...
MallocArg = BinaryOperator::Create(Instruction::Mul, Scale,
MallocArg, "", I);
}
}
// Create the call to Malloc.
CallInst *MCall = CallInst::Create(MallocFunc, MallocArg, "", I);
MCall->setTailCall();
// Create a cast instruction to convert to the right type...
Value *MCast;
if (MCall->getType() != Type::getVoidTy(BB.getContext()))
MCast = new BitCastInst(MCall, MI->getType(), "", I);
else
MCast = Constant::getNullValue(MI->getType());
// Replace all uses of the old malloc inst with the cast inst
MI->replaceAllUsesWith(MCast);
I = --BBIL.erase(I); // remove and delete the malloc instr...
Changed = true;
++NumLowered;
} else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
Value *PtrCast =
new BitCastInst(FI->getOperand(0),
PointerType::getUnqual(Type::getInt8Ty(BB.getContext())), "", I);
// Insert a call to the free function...
CallInst::Create(FreeFunc, PtrCast, "", I)->setTailCall();
// Delete the old free instruction
I = --BBIL.erase(I);
Changed = true;
++NumLowered;
}
}
return Changed;
}
|
Update comments to new-style syntax.
|
Update comments to new-style syntax.
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@79263 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm
|
de1e73c6f2af5b9561c9a90b13db986d76cc06dd
|
lib/models/embed.cpp
|
lib/models/embed.cpp
|
#include <models/embed.hpp>
#include <vector>
#include <models/entity.hpp>
#include <models/embed_author.hpp>
#include <models/embed_field.hpp>
#include <models/embed_footer.hpp>
#include <models/embed_image.hpp>
#include <models/embed_video.hpp>
#include <models/embed_thumbnail.hpp>
#include <models/embed_provider.hpp>
namespace disccord
{
namespace models
{
embed::embed()
: title(""), type("rich"), description(), url(), //default to rich embed, and default color (should enum)
timestamp(), color(0), footer(),image(),thumbnail(),
video(),provider(),author(),fields()
{ }
embed::~embed()
{ }
void embed::decode(web::json::value json)
{
title = json.at("title").as_string();
type = json.at("type").as_string();
color = json.at("color").as_integer();
#define get_field(var, conv) \
if (json.has_field(#var)) { \
auto field = json.at(#var); \
if (!field.is_null()) { \
var = decltype(var)(field.conv()); \
} else { \
var = decltype(var)::no_value(); \
} \
} else { \
var = decltype(var)(); \
}
#define get_composite_field(var, type) \
if (json.has_field(#var)) { \
auto field = json.at(#var); \
if (!field.is_null()) { \
type val; \
val.decode(field); \
var = decltype(var)(val); \
} else { \
var = decltype(var)::no_value(); \
} \
} else { \
var = decltype(var)(); \
}
get_field(description, as_string);
get_field(url, as_string);
get_field(timestamp, as_string);
get_composite_field(footer, embed_footer);
get_composite_field(image, embed_image);
get_composite_field(thumbnail, embed_thumbnail);
get_composite_field(video, embed_video);
get_composite_field(provider, embed_provider);
get_composite_field(author, embed_author);
if (json.has_field("fields"))
{
auto _fields_array = json.at("fields").as_array();
std::vector<embed_field> fields_array(_fields_array.size());
std::transform(_fields_array.begin(), _fields_array.end(), fields_array.begin(),
[](web::json::value _field){
embed_field field;
field.decode(_field);
return field;
});
}
#undef get_field
#undef get_composite_field
}
void embed::encode_to(std::unordered_map<std::string, web::json::value> &info)
{
info["title"] = web::json::value(get_title());
info["type"] = web::json::value(get_type());
info["color"] = web::json::value(get_color());
if (get_description().is_specified())
info["description"] = get_description();
if (get_url().is_specified())
info["url"] = get_url();
if (get_timestamp().is_specified())
info["timestamp"] = get_timestamp();
if (get_footer().is_specified())
info["footer"] = get_footer().get_value().encode();
if (get_image().is_specified())
info["image"] = get_footer().get_value().encode();
if (get_thumbnail().is_specified())
info["thumbnail"] = get_thumbnail().get_value().encode();
if (get_video().is_specified())
info["video"] = get_video().get_value().encode();
if (get_provider().is_specified())
info["provider"] = get_provider().get_value().encode();
if (get_fields().is_specified())
{
auto _fields = get_fields().get_value();
std::vector<web::json::value> field_array(_fields.size());
std::transform(_fields.begin(), _fields.end(), field_array.begin(),
[](embed_field field){
return field.encode();
});
info["fields"] = web::json::value::array(field_array);
}
if (get_author().is_specified())
info["author"] = get_author().get_value().encode();
}
std::string embed::get_title()
{
return title;
}
std::string embed::get_type()
{
return type;
}
util::optional<std::string> embed::get_description()
{
return description;
}
util::optional<std::string> embed::get_url()
{
return url;
}
util::optional<std::string> embed::get_timestamp()
{
return timestamp;
}
int embed::get_color()
{
return color;
}
util::optional<embed_footer> embed::get_footer()
{
return footer;
}
util::optional<embed_image> embed::get_image()
{
return image;
}
util::optional<embed_thumbnail> embed::get_thumbnail()
{
return thumbnail;
}
util::optional<embed_video> embed::get_video()
{
return video;
}
util::optional<embed_provider> embed::get_provider()
{
return provider;
}
util::optional<embed_author> embed::get_author()
{
return author;
}
util::optional<std::vector<embed_field>> embed::get_fields()
{
return fields;
}
}
}
|
#include <models/embed.hpp>
#include <vector>
#include <models/entity.hpp>
#include <models/embed_author.hpp>
#include <models/embed_field.hpp>
#include <models/embed_footer.hpp>
#include <models/embed_image.hpp>
#include <models/embed_video.hpp>
#include <models/embed_thumbnail.hpp>
#include <models/embed_provider.hpp>
namespace disccord
{
namespace models
{
embed::embed()
: title(""), type("rich"), description(), url(), //default to rich embed, and default color (should enum)
timestamp(), color(0), footer(),image(),thumbnail(),
video(),provider(),author(),fields()
{ }
embed::~embed()
{ }
void embed::decode(web::json::value json)
{
title = json.at("title").as_string();
type = json.at("type").as_string();
color = json.at("color").as_integer();
#define get_field(var, conv) \
if (json.has_field(#var)) { \
auto field = json.at(#var); \
if (!field.is_null()) { \
var = decltype(var)(field.conv()); \
} else { \
var = decltype(var)::no_value(); \
} \
} else { \
var = decltype(var)(); \
}
#define get_composite_field(var, type) \
if (json.has_field(#var)) { \
auto field = json.at(#var); \
if (!field.is_null()) { \
type val; \
val.decode(field); \
var = decltype(var)(val); \
} else { \
var = decltype(var)::no_value(); \
} \
} else { \
var = decltype(var)(); \
}
get_field(description, as_string);
get_field(url, as_string);
get_field(timestamp, as_string);
get_composite_field(footer, embed_footer);
get_composite_field(image, embed_image);
get_composite_field(thumbnail, embed_thumbnail);
get_composite_field(video, embed_video);
get_composite_field(provider, embed_provider);
get_composite_field(author, embed_author);
if (json.has_field("fields"))
{
auto _fields_array = json.at("fields").as_array();
std::vector<embed_field> fields_array(_fields_array.size());
std::transform(_fields_array.begin(), _fields_array.end(), fields_array.begin(),
[](web::json::value _field){
embed_field field;
field.decode(_field);
return field;
});
fields = fields_array;
}
#undef get_field
#undef get_composite_field
}
void embed::encode_to(std::unordered_map<std::string, web::json::value> &info)
{
info["title"] = web::json::value(get_title());
info["type"] = web::json::value(get_type());
info["color"] = web::json::value(get_color());
if (get_description().is_specified())
info["description"] = get_description();
if (get_url().is_specified())
info["url"] = get_url();
if (get_timestamp().is_specified())
info["timestamp"] = get_timestamp();
if (get_footer().is_specified())
info["footer"] = get_footer().get_value().encode();
if (get_image().is_specified())
info["image"] = get_footer().get_value().encode();
if (get_thumbnail().is_specified())
info["thumbnail"] = get_thumbnail().get_value().encode();
if (get_video().is_specified())
info["video"] = get_video().get_value().encode();
if (get_provider().is_specified())
info["provider"] = get_provider().get_value().encode();
if (get_fields().is_specified())
{
auto _fields = get_fields().get_value();
std::vector<web::json::value> field_array(_fields.size());
std::transform(_fields.begin(), _fields.end(), field_array.begin(),
[](embed_field field){
return field.encode();
});
info["fields"] = web::json::value::array(field_array);
}
if (get_author().is_specified())
info["author"] = get_author().get_value().encode();
}
std::string embed::get_title()
{
return title;
}
std::string embed::get_type()
{
return type;
}
util::optional<std::string> embed::get_description()
{
return description;
}
util::optional<std::string> embed::get_url()
{
return url;
}
util::optional<std::string> embed::get_timestamp()
{
return timestamp;
}
int embed::get_color()
{
return color;
}
util::optional<embed_footer> embed::get_footer()
{
return footer;
}
util::optional<embed_image> embed::get_image()
{
return image;
}
util::optional<embed_thumbnail> embed::get_thumbnail()
{
return thumbnail;
}
util::optional<embed_video> embed::get_video()
{
return video;
}
util::optional<embed_provider> embed::get_provider()
{
return provider;
}
util::optional<embed_author> embed::get_author()
{
return author;
}
util::optional<std::vector<embed_field>> embed::get_fields()
{
return fields;
}
}
}
|
Fix missing assignment in embed model
|
Fix missing assignment in embed model
|
C++
|
mit
|
FiniteReality/disccord,FiniteReality/disccord
|
b2f3e2cf100088a9635692683322531d38157298
|
src/firstpersoncontrol.cpp
|
src/firstpersoncontrol.cpp
|
#include "firstpersoncontrol.hpp"
#include "input.hpp"
#include "spatial.hpp"
gst::FirstPersonControl::FirstPersonControl()
: FirstPersonControl(false, 2.8f, 5.0f)
{
}
gst::FirstPersonControl::FirstPersonControl(bool freelook, float rotation_speed, float movement_speed)
: freelook(freelook),
rotation_speed(rotation_speed),
movement_speed(movement_speed),
yaw_angle(0.0f),
pitch_angle(0.0f)
{
}
void gst::FirstPersonControl::update(float dt, Input const & input, Spatial & spatial)
{
rotate(dt, input, spatial);
move(dt, input, spatial);
}
void gst::FirstPersonControl::rotate(float dt, Input const & input, Spatial & spatial)
{
const glm::vec2 mouse_movement(
-input.position_delta().x,
-input.position_delta().y
);
const float speed = rotation_speed * dt;
// -90 <= pitch <= 90
pitch_angle += mouse_movement.y * speed;
pitch_angle = glm::clamp(pitch_angle, -90.0f, 90.0f);
glm::quat pitch = glm::angleAxis(pitch_angle, X_UNIT);
// -360 <= yaw <= 360
yaw_angle += mouse_movement.x * speed;
if (yaw_angle < -360.0f) {
yaw_angle += 360.0f;
} else if (yaw_angle > 360.0f) {
yaw_angle -= 360.0f;
}
glm::quat yaw = glm::angleAxis(yaw_angle, Y_UNIT);
spatial.orientation = glm::normalize(yaw * pitch);
}
void gst::FirstPersonControl::move(float dt, Input const & input, Spatial & spatial)
{
const float speed = movement_speed * dt;
glm::vec3 displacement(0.0f);
if (input.down(Key::W) || input.down(Key::UP)) {
displacement.z--;;
}
if (input.down(Key::S) || input.down(Key::DOWN)) {
displacement.z++;
}
if (input.down(Key::A) || input.down(Key::LEFT)) {
displacement.x--;
}
if (input.down(Key::D) || input.down(Key::RIGHT)) {
displacement.x++;
}
if (input.down(Key::Q)) {
displacement.y--;
}
if (input.down(Key::R)) {
displacement.y++;
}
if (displacement != glm::vec3(0.0f)) {
displacement = glm::normalize(displacement);
if (freelook) {
spatial.translate(speed, displacement);
} else {
// limit translation to the xz-plane
glm::quat yaw = spatial.orientation;
yaw.x = 0.0f;
yaw.z = 0.0f;
yaw = glm::normalize(yaw);
spatial.position += yaw * (displacement * speed);
}
}
}
|
#include "firstpersoncontrol.hpp"
#include "input.hpp"
#include "spatial.hpp"
gst::FirstPersonControl::FirstPersonControl()
: FirstPersonControl(false, 2.8f, 5.0f)
{
}
gst::FirstPersonControl::FirstPersonControl(bool freelook, float rotation_speed, float movement_speed)
: freelook(freelook),
rotation_speed(rotation_speed),
movement_speed(movement_speed),
yaw_angle(0.0f),
pitch_angle(0.0f)
{
}
void gst::FirstPersonControl::update(float dt, Input const & input, Spatial & spatial)
{
rotate(dt, input, spatial);
move(dt, input, spatial);
}
void gst::FirstPersonControl::rotate(float dt, Input const & input, Spatial & spatial)
{
const glm::vec2 mouse_movement(
-input.position_delta().x,
-input.position_delta().y
);
const float speed = rotation_speed * dt;
// -90 <= pitch <= 90
pitch_angle += mouse_movement.y * speed;
pitch_angle = glm::clamp(pitch_angle, -90.0f, 90.0f);
glm::quat pitch = glm::angleAxis(pitch_angle, X_UNIT);
// -360 <= yaw <= 360
yaw_angle += mouse_movement.x * speed;
if (yaw_angle < -360.0f) {
yaw_angle += 360.0f;
} else if (yaw_angle > 360.0f) {
yaw_angle -= 360.0f;
}
glm::quat yaw = glm::angleAxis(yaw_angle, Y_UNIT);
spatial.orientation = glm::normalize(yaw * pitch);
}
void gst::FirstPersonControl::move(float dt, Input const & input, Spatial & spatial)
{
const float speed = movement_speed * dt;
glm::vec3 displacement(0.0f);
if (input.down(Key::W) || input.down(Key::UP)) {
displacement.z--;;
}
if (input.down(Key::S) || input.down(Key::DOWN)) {
displacement.z++;
}
if (input.down(Key::A) || input.down(Key::LEFT)) {
displacement.x--;
}
if (input.down(Key::D) || input.down(Key::RIGHT)) {
displacement.x++;
}
if (input.down(Key::Q)) {
displacement.y--;
}
if (input.down(Key::R)) {
displacement.y++;
}
if (displacement != glm::vec3(0.0f)) {
displacement = glm::normalize(displacement);
if (freelook) {
// translate y on the world y-axis and not the object y-axis, this
// is the expected behaviour of the "traditional" freelook controls
spatial.position.y += speed * displacement.y;
displacement.y = 0.0f;
spatial.translate(speed, displacement);
} else {
// limit translation to the xz-plane
glm::quat yaw = spatial.orientation;
yaw.x = 0.0f;
yaw.z = 0.0f;
yaw = glm::normalize(yaw);
spatial.position += yaw * (displacement * speed);
}
}
}
|
change behaviour for translating on the y-axis in first-person controls freelook mode
|
change behaviour for translating on the y-axis in first-person controls freelook mode
|
C++
|
mit
|
mharrys/gust,mharrys/gust,mharrys/gust
|
e5f6f89663a3c92fef762a59bb346bc13436c793
|
src/hdf5/DataArrayHDF5.cpp
|
src/hdf5/DataArrayHDF5.cpp
|
// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/util/util.hpp>
#include <nix/hdf5/DataArrayHDF5.hpp>
#include <nix/hdf5/DataSetHDF5.hpp>
#include <nix/hdf5/DimensionHDF5.hpp>
using namespace std;
using namespace nix::base;
namespace nix {
namespace hdf5 {
DataArrayHDF5::DataArrayHDF5(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block, const Group &group)
: EntityWithSourcesHDF5(file, block, group) {
dimension_group = this->group().openOptGroup("dimensions");
}
DataArrayHDF5::DataArrayHDF5(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const Group &group,
const string &id, const string &type, const string &name)
: DataArrayHDF5(file, block, group, id, type, name, util::getTime()) {
}
DataArrayHDF5::DataArrayHDF5(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const Group &group,
const string &id, const string &type, const string &name, time_t time)
: EntityWithSourcesHDF5(file, block, group, id, type, name, time) {
dimension_group = this->group().openOptGroup("dimensions");
}
//--------------------------------------------------
// Element getters and setters
//--------------------------------------------------
boost::optional<std::string> DataArrayHDF5::label() const {
boost::optional<std::string> ret;
string value;
bool have_attr = group().getAttr("label", value);
if (have_attr) {
ret = value;
}
return ret;
}
void DataArrayHDF5::label(const string &label) {
if (label.empty()) {
throw EmptyString("label");
}
else {
group().setAttr("label", label);
forceUpdatedAt();
}
}
void DataArrayHDF5::label(const none_t t) {
if (group().hasAttr("label")) {
group().removeAttr("label");
}
forceUpdatedAt();
}
boost::optional<std::string> DataArrayHDF5::unit() const {
boost::optional<std::string> ret;
string value;
bool have_attr = group().getAttr("unit", value);
if (have_attr) {
ret = value;
}
return ret;
}
void DataArrayHDF5::unit(const string &unit) {
if (unit.empty()) {
throw EmptyString("unit");
}
else {
group().setAttr("unit", unit);
forceUpdatedAt();
}
}
void DataArrayHDF5::unit(const none_t t) {
if (group().hasAttr("unit")) {
group().removeAttr("unit");
}
forceUpdatedAt();
}
// TODO use defaults
boost::optional<double> DataArrayHDF5::expansionOrigin() const {
boost::optional<double> ret;
double expansion_origin;
bool have_attr = group().getAttr("expansion_origin", expansion_origin);
if (have_attr) {
ret = expansion_origin;
}
return ret;
}
void DataArrayHDF5::expansionOrigin(double expansion_origin) {
group().setAttr("expansion_origin", expansion_origin);
forceUpdatedAt();
}
void DataArrayHDF5::expansionOrigin(const none_t t) {
if (group().hasAttr("expansion_origin")) {
group().removeAttr("expansion_origin");
}
forceUpdatedAt();
}
// TODO use defaults
vector<double> DataArrayHDF5::polynomCoefficients() const {
vector<double> polynom_coefficients;
if (group().hasData("polynom_coefficients")) {
DataSet ds = group().openData("polynom_coefficients");
ds.read(polynom_coefficients, true);
}
return polynom_coefficients;
}
void DataArrayHDF5::polynomCoefficients(const vector<double> &coefficients) {
DataSet ds;
if (group().hasData("polynom_coefficients")) {
ds = group().openData("polynom_coefficients");
ds.setExtent({coefficients.size()});
} else {
ds = DataSet::create(group().h5Group(), "polynom_coefficients", coefficients);
}
ds.write(coefficients);
forceUpdatedAt();
}
void DataArrayHDF5::polynomCoefficients(const none_t t) {
if (group().hasData("polynom_coefficients")) {
group().removeData("polynom_coefficients");
}
forceUpdatedAt();
}
//--------------------------------------------------
// Methods concerning dimensions
//--------------------------------------------------
size_t DataArrayHDF5::dimensionCount() const {
boost::optional<Group> g = dimension_group();
return g ? g->objectCount() : size_t(0);
}
shared_ptr<IDimension> DataArrayHDF5::getDimension(size_t index) const {
shared_ptr<IDimension> dim;
boost::optional<Group> g = dimension_group();
if (g) {
string str_id = util::numToStr(index);
if (g->hasGroup(str_id)) {
Group group = g->openGroup(str_id, false);
dim = openDimensionHDF5(group, index);
}
}
return dim;
}
std::shared_ptr<base::ISetDimension> DataArrayHDF5::createSetDimension(size_t index) {
Group g = createDimensionGroup(index);
return make_shared<SetDimensionHDF5>(g, index);
}
std::shared_ptr<base::IRangeDimension> DataArrayHDF5::createRangeDimension(size_t index, const std::vector<double> &ticks) {
Group g = createDimensionGroup(index);
return make_shared<RangeDimensionHDF5>(g, index, ticks);
}
std::shared_ptr<base::ISampledDimension> DataArrayHDF5::createSampledDimension(size_t index, double sampling_interval) {
Group g = createDimensionGroup(index);
return make_shared<SampledDimensionHDF5>(g, index, sampling_interval);
}
Group DataArrayHDF5::createDimensionGroup(size_t index) {
boost::optional<Group> g = dimension_group(true);
size_t dim_max = dimensionCount() + 1;
if (index > dim_max || index <= 0)
throw new runtime_error("Invalid dimension index: has to be 0 < index <= " + util::numToStr(dim_max));
string str_id = util::numToStr(index);
if (g->hasGroup(str_id)) {
g->removeGroup(str_id);
}
return g->openGroup(str_id, true);
}
bool DataArrayHDF5::deleteDimension(size_t index) {
bool deleted = false;
size_t dim_count = dimensionCount();
string str_id = util::numToStr(index);
boost::optional<Group> g = dimension_group();
if (g) {
if (g->hasGroup(str_id)) {
g->removeGroup(str_id);
deleted = true;
}
if (deleted && index < dim_count) {
for (size_t old_id = index + 1; old_id <= dim_count; old_id++) {
string str_old_id = util::numToStr(old_id);
string str_new_id = util::numToStr(old_id - 1);
g->renameGroup(str_old_id, str_new_id);
}
}
}
return deleted;
}
//--------------------------------------------------
// Other methods and functions
//--------------------------------------------------
DataArrayHDF5::~DataArrayHDF5() {
}
void DataArrayHDF5::createData(DataType dtype, const NDSize &size) {
if (group().hasData("data")) {
throw new std::runtime_error("DataArray alread exists"); //TODO: FIXME, better exception
}
DataSet::create(group().h5Group(), "data", dtype, size);
DataSet ds = group().openData("data");
}
bool DataArrayHDF5::hasData() const {
return group().hasData("data");
}
void DataArrayHDF5::write(DataType dtype, const void *data, const NDSize &count, const NDSize &offset) {
DataSet ds;
if (!group().hasData("data")) {
ds = DataSet::create(group().h5Group(), "data", dtype, count);
} else {
ds = group().openData("data");
}
if (offset.size()) {
Selection fileSel = ds.createSelection();
fileSel.select(count, offset);
Selection memSel(DataSpace::create(count, false));
ds.write(dtype, data, fileSel, memSel);
} else {
ds.write(dtype, count, data);
}
}
void DataArrayHDF5::read(DataType dtype, void *data, const NDSize &count, const NDSize &offset) const {
if (!group().hasData("data")) {
return;
}
DataSet ds = group().openData("data");
if (offset.size()) {
Selection fileSel = ds.createSelection();
// if count.size() == 0, i.e. we want to read a scalar,
// we have to supply something that fileSel can make sense of
fileSel.select(count ? count : NDSize(offset.size(), 1), offset);
Selection memSel(DataSpace::create(count, false));
ds.read(dtype, data, fileSel, memSel);
} else {
ds.read(dtype, count, data);
}
}
NDSize DataArrayHDF5::dataExtent(void) const {
if (!group().hasData("data")) {
return NDSize{};
}
DataSet ds = group().openData("data");
return ds.size();
}
void DataArrayHDF5::dataExtent(const NDSize &extent) {
if (!group().hasData("data")) {
throw runtime_error("Data field not found in DataArray!");
}
DataSet ds = group().openData("data");
ds.setExtent(extent);
}
DataType DataArrayHDF5::dataType(void) const {
if (!group().hasData("data")) {
return DataType::Nothing;
}
DataSet ds = group().openData("data");
return ds.dataType();
}
} // ns nix::hdf5
} // ns nix
|
// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/util/util.hpp>
#include <nix/hdf5/DataArrayHDF5.hpp>
#include <nix/hdf5/DataSetHDF5.hpp>
#include <nix/hdf5/DimensionHDF5.hpp>
using namespace std;
using namespace nix::base;
namespace nix {
namespace hdf5 {
DataArrayHDF5::DataArrayHDF5(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block, const Group &group)
: EntityWithSourcesHDF5(file, block, group) {
dimension_group = this->group().openOptGroup("dimensions");
}
DataArrayHDF5::DataArrayHDF5(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const Group &group,
const string &id, const string &type, const string &name)
: DataArrayHDF5(file, block, group, id, type, name, util::getTime()) {
}
DataArrayHDF5::DataArrayHDF5(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const Group &group,
const string &id, const string &type, const string &name, time_t time)
: EntityWithSourcesHDF5(file, block, group, id, type, name, time) {
dimension_group = this->group().openOptGroup("dimensions");
}
//--------------------------------------------------
// Element getters and setters
//--------------------------------------------------
boost::optional<std::string> DataArrayHDF5::label() const {
boost::optional<std::string> ret;
string value;
bool have_attr = group().getAttr("label", value);
if (have_attr) {
ret = value;
}
return ret;
}
void DataArrayHDF5::label(const string &label) {
if (label.empty()) {
throw EmptyString("label");
}
else {
group().setAttr("label", label);
forceUpdatedAt();
}
}
void DataArrayHDF5::label(const none_t t) {
if (group().hasAttr("label")) {
group().removeAttr("label");
}
forceUpdatedAt();
}
boost::optional<std::string> DataArrayHDF5::unit() const {
boost::optional<std::string> ret;
string value;
bool have_attr = group().getAttr("unit", value);
if (have_attr) {
ret = value;
}
return ret;
}
void DataArrayHDF5::unit(const string &unit) {
if (unit.empty()) {
throw EmptyString("unit");
}
else {
group().setAttr("unit", unit);
forceUpdatedAt();
}
}
void DataArrayHDF5::unit(const none_t t) {
if (group().hasAttr("unit")) {
group().removeAttr("unit");
}
forceUpdatedAt();
}
// TODO use defaults
boost::optional<double> DataArrayHDF5::expansionOrigin() const {
boost::optional<double> ret;
double expansion_origin;
bool have_attr = group().getAttr("expansion_origin", expansion_origin);
if (have_attr) {
ret = expansion_origin;
}
return ret;
}
void DataArrayHDF5::expansionOrigin(double expansion_origin) {
group().setAttr("expansion_origin", expansion_origin);
forceUpdatedAt();
}
void DataArrayHDF5::expansionOrigin(const none_t t) {
if (group().hasAttr("expansion_origin")) {
group().removeAttr("expansion_origin");
}
forceUpdatedAt();
}
// TODO use defaults
vector<double> DataArrayHDF5::polynomCoefficients() const {
vector<double> polynom_coefficients;
if (group().hasData("polynom_coefficients")) {
DataSet ds = group().openData("polynom_coefficients");
ds.read(polynom_coefficients, true);
}
return polynom_coefficients;
}
void DataArrayHDF5::polynomCoefficients(const vector<double> &coefficients) {
DataSet ds;
if (group().hasData("polynom_coefficients")) {
ds = group().openData("polynom_coefficients");
ds.setExtent({coefficients.size()});
} else {
ds = DataSet::create(group().h5Group(), "polynom_coefficients", DataType::Double, {coefficients.size()});
}
ds.write(coefficients);
forceUpdatedAt();
}
void DataArrayHDF5::polynomCoefficients(const none_t t) {
if (group().hasData("polynom_coefficients")) {
group().removeData("polynom_coefficients");
}
forceUpdatedAt();
}
//--------------------------------------------------
// Methods concerning dimensions
//--------------------------------------------------
size_t DataArrayHDF5::dimensionCount() const {
boost::optional<Group> g = dimension_group();
return g ? g->objectCount() : size_t(0);
}
shared_ptr<IDimension> DataArrayHDF5::getDimension(size_t index) const {
shared_ptr<IDimension> dim;
boost::optional<Group> g = dimension_group();
if (g) {
string str_id = util::numToStr(index);
if (g->hasGroup(str_id)) {
Group group = g->openGroup(str_id, false);
dim = openDimensionHDF5(group, index);
}
}
return dim;
}
std::shared_ptr<base::ISetDimension> DataArrayHDF5::createSetDimension(size_t index) {
Group g = createDimensionGroup(index);
return make_shared<SetDimensionHDF5>(g, index);
}
std::shared_ptr<base::IRangeDimension> DataArrayHDF5::createRangeDimension(size_t index, const std::vector<double> &ticks) {
Group g = createDimensionGroup(index);
return make_shared<RangeDimensionHDF5>(g, index, ticks);
}
std::shared_ptr<base::ISampledDimension> DataArrayHDF5::createSampledDimension(size_t index, double sampling_interval) {
Group g = createDimensionGroup(index);
return make_shared<SampledDimensionHDF5>(g, index, sampling_interval);
}
Group DataArrayHDF5::createDimensionGroup(size_t index) {
boost::optional<Group> g = dimension_group(true);
size_t dim_max = dimensionCount() + 1;
if (index > dim_max || index <= 0)
throw new runtime_error("Invalid dimension index: has to be 0 < index <= " + util::numToStr(dim_max));
string str_id = util::numToStr(index);
if (g->hasGroup(str_id)) {
g->removeGroup(str_id);
}
return g->openGroup(str_id, true);
}
bool DataArrayHDF5::deleteDimension(size_t index) {
bool deleted = false;
size_t dim_count = dimensionCount();
string str_id = util::numToStr(index);
boost::optional<Group> g = dimension_group();
if (g) {
if (g->hasGroup(str_id)) {
g->removeGroup(str_id);
deleted = true;
}
if (deleted && index < dim_count) {
for (size_t old_id = index + 1; old_id <= dim_count; old_id++) {
string str_old_id = util::numToStr(old_id);
string str_new_id = util::numToStr(old_id - 1);
g->renameGroup(str_old_id, str_new_id);
}
}
}
return deleted;
}
//--------------------------------------------------
// Other methods and functions
//--------------------------------------------------
DataArrayHDF5::~DataArrayHDF5() {
}
void DataArrayHDF5::createData(DataType dtype, const NDSize &size) {
if (group().hasData("data")) {
throw new std::runtime_error("DataArray alread exists"); //TODO: FIXME, better exception
}
DataSet::create(group().h5Group(), "data", dtype, size);
DataSet ds = group().openData("data");
}
bool DataArrayHDF5::hasData() const {
return group().hasData("data");
}
void DataArrayHDF5::write(DataType dtype, const void *data, const NDSize &count, const NDSize &offset) {
DataSet ds;
if (!group().hasData("data")) {
ds = DataSet::create(group().h5Group(), "data", dtype, count);
} else {
ds = group().openData("data");
}
if (offset.size()) {
Selection fileSel = ds.createSelection();
fileSel.select(count, offset);
Selection memSel(DataSpace::create(count, false));
ds.write(dtype, data, fileSel, memSel);
} else {
ds.write(dtype, count, data);
}
}
void DataArrayHDF5::read(DataType dtype, void *data, const NDSize &count, const NDSize &offset) const {
if (!group().hasData("data")) {
return;
}
DataSet ds = group().openData("data");
if (offset.size()) {
Selection fileSel = ds.createSelection();
// if count.size() == 0, i.e. we want to read a scalar,
// we have to supply something that fileSel can make sense of
fileSel.select(count ? count : NDSize(offset.size(), 1), offset);
Selection memSel(DataSpace::create(count, false));
ds.read(dtype, data, fileSel, memSel);
} else {
ds.read(dtype, count, data);
}
}
NDSize DataArrayHDF5::dataExtent(void) const {
if (!group().hasData("data")) {
return NDSize{};
}
DataSet ds = group().openData("data");
return ds.size();
}
void DataArrayHDF5::dataExtent(const NDSize &extent) {
if (!group().hasData("data")) {
throw runtime_error("Data field not found in DataArray!");
}
DataSet ds = group().openData("data");
ds.setExtent(extent);
}
DataType DataArrayHDF5::dataType(void) const {
if (!group().hasData("data")) {
return DataType::Nothing;
}
DataSet ds = group().openData("data");
return ds.dataType();
}
} // ns nix::hdf5
} // ns nix
|
use non-templt. DataSet::create
|
DA::polyCoeff: use non-templt. DataSet::create
|
C++
|
bsd-3-clause
|
stoewer/nix
|
9df07c30ae1343725a06fb28dd46eb2b0d12e50a
|
src/include/miopen/env.hpp
|
src/include/miopen/env.hpp
|
#ifndef GUARD_MIOPEN_ENV_HPP
#define GUARD_MIOPEN_ENV_HPP
#include <cstdlib>
#include <cstring>
namespace miopen {
/// \todo Rework: Case-insensitive string compare, ODR, (?) move to .cpp
// Declare a cached environment variable
#define MIOPEN_DECLARE_ENV_VAR(x) struct x { static const char* value() { return #x; }};
/*
* Returns false if a feature-controlling environment variable is defined
* and set to something which disables a feature.
*/
inline bool IsEnvvarValueDisabled(const char* name)
{
const auto value_env_p = std::getenv(name);
return value_env_p != nullptr &&
( std::strcmp(value_env_p, "disable") == 0
|| std::strcmp(value_env_p, "disabled") == 0
|| std::strcmp(value_env_p, "0") == 0
|| std::strcmp(value_env_p, "no") == 0
|| std::strcmp(value_env_p, "false") == 0 );
}
inline bool IsEnvvarValueEnabled(const char* name)
{
const auto value_env_p = std::getenv(name);
return value_env_p != nullptr &&
( std::strcmp(value_env_p, "enable") == 0
|| std::strcmp(value_env_p, "enabled") == 0
|| std::strcmp(value_env_p, "1") == 0
|| std::strcmp(value_env_p, "yes") == 0
|| std::strcmp(value_env_p, "true") == 0 );
}
template<class T>
inline const char * GetStringEnv(T)
{
static const char * result = std::getenv(T::value());
return result;
}
template<class T>
inline bool IsEnabled(T)
{
static const bool result = miopen::IsEnvvarValueEnabled(T::value());
return result;
}
template<class T>
inline bool IsDisabled(T)
{
static const bool result = miopen::IsEnvvarValueDisabled(T::value());
return result;
}
} // namespace miopen
#endif
|
#ifndef GUARD_MIOPEN_ENV_HPP
#define GUARD_MIOPEN_ENV_HPP
#include <cstdlib>
#include <cstring>
#include <vector>
#include <string>
namespace miopen {
/// \todo Rework: Case-insensitive string compare, ODR, (?) move to .cpp
// Declare a cached environment variable
#define MIOPEN_DECLARE_ENV_VAR(x) struct x { static const char* value() { return #x; }};
/*
* Returns false if a feature-controlling environment variable is defined
* and set to something which disables a feature.
*/
inline bool IsEnvvarValueDisabled(const char* name)
{
const auto value_env_p = std::getenv(name);
return value_env_p != nullptr &&
( std::strcmp(value_env_p, "disable") == 0
|| std::strcmp(value_env_p, "disabled") == 0
|| std::strcmp(value_env_p, "0") == 0
|| std::strcmp(value_env_p, "no") == 0
|| std::strcmp(value_env_p, "false") == 0 );
}
inline bool IsEnvvarValueEnabled(const char* name)
{
const auto value_env_p = std::getenv(name);
return value_env_p != nullptr &&
( std::strcmp(value_env_p, "enable") == 0
|| std::strcmp(value_env_p, "enabled") == 0
|| std::strcmp(value_env_p, "1") == 0
|| std::strcmp(value_env_p, "yes") == 0
|| std::strcmp(value_env_p, "true") == 0 );
}
inline std::vector<std::string> GetEnv(const char * name)
{
auto p = std::getenv(name);
if (p == nullptr) return {};
else return {{p}};
}
template<class T>
inline const char * GetStringEnv(T)
{
static const std::vector<std::string> result = GetEnv(T::value());
if (result.empty()) return nullptr;
else return result.front().c_str();
}
template<class T>
inline bool IsEnabled(T)
{
static const bool result = miopen::IsEnvvarValueEnabled(T::value());
return result;
}
template<class T>
inline bool IsDisabled(T)
{
static const bool result = miopen::IsEnvvarValueDisabled(T::value());
return result;
}
} // namespace miopen
#endif
|
Store env variables as string
|
Store env variables as string
|
C++
|
mit
|
ROCmSoftwarePlatform/MIOpen,ROCmSoftwarePlatform/MIOpen,ROCmSoftwarePlatform/MIOpen,ROCmSoftwarePlatform/MIOpen,ROCmSoftwarePlatform/MIOpen
|
be5f94f90a740bfc93506d40c47fcdc56c7dbdb9
|
src/input/sdl/joystick.cpp
|
src/input/sdl/joystick.cpp
|
#ifdef USE_SDL
#include <SDL.h>
#include "joystick.h"
void SDLJoystick::poll(){
/* TODO */
}
JoystickInput SDLJoystick::readAll(){
/* TODO */
JoystickInput ok;
return ok;
}
SDLJoystick::~SDLJoystick(){
if (joystick){
SDL_JoystickClose(joystick);
}
}
SDLJoystick::SDLJoystick():
joystick(NULL){
if (SDL_NumJoysticks() > 0){
joystick = SDL_JoystickOpen(0);
}
}
#endif
|
#ifdef USE_SDL
#include <SDL.h>
#include "joystick.h"
void SDLJoystick::poll(){
/* TODO */
}
static bool read_button(SDL_Joystick * joystick, int button){
return SDL_JoystickGetButton(joystick, button);
}
JoystickInput SDLJoystick::readAll(){
JoystickInput input;
if (joystick){
int buttons = SDL_JoystickNumButtons(joystick);
switch (buttons > 4 ? 4 : buttons){
case 4: input.button4 = read_button(joystick, 3);
case 3: input.button3 = read_button(joystick, 2);
case 2: input.button2 = read_button(joystick, 1);
case 1: input.button1 = read_button(joystick, 0);
case 0: {
break;
}
}
}
int axis = SDL_JoystickNumAxes(joystick);
if (axis > 0){
int position = SDL_JoystickGetAxis(joystick, 0);
if (position < 0){
input.left = true;
} else if (position > 0){
input.right = true;
}
}
if (axis > 1){
int position = SDL_JoystickGetAxis(joystick, 1);
if (position < 0){
input.up = true;
} else if (position > 0){
input.down = true;
}
}
return input;
}
SDLJoystick::~SDLJoystick(){
if (joystick){
SDL_JoystickClose(joystick);
}
}
SDLJoystick::SDLJoystick():
joystick(NULL){
if (SDL_NumJoysticks() > 0){
joystick = SDL_JoystickOpen(0);
}
}
#endif
|
read buttons/axis in sdl joystick
|
read buttons/axis in sdl joystick
git-svn-id: 39e099a8ed5324aded674b764a67f7a08796d9a7@4171 662fdd30-d327-0410-a531-f549c87e1e9e
|
C++
|
bsd-3-clause
|
boyjimeking/paintown,boyjimeking/paintown,boyjimeking/paintown,boyjimeking/paintown,boyjimeking/paintown,Sevalecan/paintown,Sevalecan/paintown,Sevalecan/paintown,Sevalecan/paintown,boyjimeking/paintown,boyjimeking/paintown,Sevalecan/paintown,Sevalecan/paintown,boyjimeking/paintown,Sevalecan/paintown,Sevalecan/paintown
|
4101c6142203aa80f7b6abb6349e13e82e39dc1c
|
src/io/ByteOrderValues.cpp
|
src/io/ByteOrderValues.cpp
|
/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2005-2006 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: io/ByteOrderValues.java rev. 1.3 (JTS-1.10)
*
**********************************************************************/
#include <geos/io/ByteOrderValues.h>
#include <geos/platform.h>
#include <geos/util.h>
#include <cstring>
#include <cassert>
namespace geos {
namespace io { // geos.io
int
ByteOrderValues::getInt(const unsigned char *buf, int byteOrder)
{
if ( byteOrder == ENDIAN_BIG )
{
return ((int) (buf[0]&0xff) <<24) |
((int) (buf[1]&0xff) <<16) |
((int) (buf[2]&0xff) <<8) |
((int) (buf[3]&0xff) );
}
else // ENDIAN_LITTLE
{
assert(byteOrder == ENDIAN_LITTLE);
return ((int) (buf[3]&0xff) <<24) |
((int) (buf[2]&0xff) <<16) |
((int) (buf[1]&0xff) <<8) |
((int) (buf[0]&0xff) );
}
}
void
ByteOrderValues::putInt(int intValue, unsigned char *buf, int byteOrder)
{
if ( byteOrder == ENDIAN_BIG )
{
buf[0] = (unsigned char)(intValue >> 24);
buf[1] = (unsigned char)(intValue >> 16);
buf[2] = (unsigned char)(intValue >> 8);
buf[3] = (unsigned char) intValue;
}
else // ENDIAN_LITTLE
{
assert(byteOrder == ENDIAN_LITTLE);
buf[3] = (unsigned char)(intValue >> 24);
buf[2] = (unsigned char)(intValue >> 16);
buf[1] = (unsigned char)(intValue >> 8);
buf[0] = (unsigned char) intValue;
}
}
int64
ByteOrderValues::getLong(const unsigned char *buf, int byteOrder)
{
if ( byteOrder == ENDIAN_BIG )
{
return
(int64) (buf[0]) << 56
| (int64) (buf[1] & 0xff) << 48
| (int64) (buf[2] & 0xff) << 40
| (int64) (buf[3] & 0xff) << 32
| (int64) (buf[4] & 0xff) << 24
| (int64) (buf[5] & 0xff) << 16
| (int64) (buf[6] & 0xff) << 8
| (int64) (buf[7] & 0xff);
}
else // ENDIAN_LITTLE
{
assert(byteOrder == ENDIAN_LITTLE);
return
(int64) (buf[7]) << 56
| (int64) (buf[6] & 0xff) << 48
| (int64) (buf[5] & 0xff) << 40
| (int64) (buf[4] & 0xff) << 32
| (int64) (buf[3] & 0xff) << 24
| (int64) (buf[2] & 0xff) << 16
| (int64) (buf[1] & 0xff) << 8
| (int64) (buf[0] & 0xff);
}
}
void
ByteOrderValues::putLong(int64 longValue, unsigned char *buf, int byteOrder)
{
if ( byteOrder == ENDIAN_BIG )
{
buf[0] = (unsigned char)(longValue >> 56);
buf[1] = (unsigned char)(longValue >> 48);
buf[2] = (unsigned char)(longValue >> 40);
buf[3] = (unsigned char)(longValue >> 32);
buf[4] = (unsigned char)(longValue >> 24);
buf[5] = (unsigned char)(longValue >> 16);
buf[6] = (unsigned char)(longValue >> 8);
buf[7] = (unsigned char) longValue;
}
else // ENDIAN_LITTLE
{
assert(byteOrder == ENDIAN_LITTLE);
buf[0] = (unsigned char) longValue;
buf[1] = (unsigned char)(longValue >> 8);
buf[2] = (unsigned char)(longValue >> 16);
buf[3] = (unsigned char)(longValue >> 24);
buf[4] = (unsigned char)(longValue >> 32);
buf[5] = (unsigned char)(longValue >> 40);
buf[6] = (unsigned char)(longValue >> 48);
buf[7] = (unsigned char)(longValue >> 56);
}
}
double
ByteOrderValues::getDouble(const unsigned char *buf, int byteOrder)
{
int64 longValue = getLong(buf, byteOrder);
double ret;
std::memcpy(&ret, &longValue, sizeof(double));
return ret;
}
void
ByteOrderValues::putDouble(double doubleValue, unsigned char *buf, int byteOrder)
{
int64 longValue;
std::memcpy(&longValue, &doubleValue, sizeof(double));
#if DEBUG_BYTEORDER_VALUES
cout<<"ByteOrderValues::putDouble("<<doubleValue<<
", order:"<<byteOrder
<<") = "<<hex;
for (int i=0; i<8; i++)
cout<<"["<<(int)buf[i]<<"]";
cout<<dec<<endl;
#endif
putLong(longValue, buf, byteOrder);
}
} // namespace geos.io
} // namespace geos
|
/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2005-2006 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: io/ByteOrderValues.java rev. 1.3 (JTS-1.10)
*
**********************************************************************/
#include <geos/io/ByteOrderValues.h>
#include <geos/platform.h>
#include <geos/util.h>
#include <cstring>
#include <cassert>
#if DEBUG_BYTEORDER_VALUES
#include <ios>
#include <iostream>
#endif
namespace geos {
namespace io { // geos.io
int
ByteOrderValues::getInt(const unsigned char *buf, int byteOrder)
{
if ( byteOrder == ENDIAN_BIG )
{
return ((int) (buf[0]&0xff) <<24) |
((int) (buf[1]&0xff) <<16) |
((int) (buf[2]&0xff) <<8) |
((int) (buf[3]&0xff) );
}
else // ENDIAN_LITTLE
{
assert(byteOrder == ENDIAN_LITTLE);
return ((int) (buf[3]&0xff) <<24) |
((int) (buf[2]&0xff) <<16) |
((int) (buf[1]&0xff) <<8) |
((int) (buf[0]&0xff) );
}
}
void
ByteOrderValues::putInt(int intValue, unsigned char *buf, int byteOrder)
{
if ( byteOrder == ENDIAN_BIG )
{
buf[0] = (unsigned char)(intValue >> 24);
buf[1] = (unsigned char)(intValue >> 16);
buf[2] = (unsigned char)(intValue >> 8);
buf[3] = (unsigned char) intValue;
}
else // ENDIAN_LITTLE
{
assert(byteOrder == ENDIAN_LITTLE);
buf[3] = (unsigned char)(intValue >> 24);
buf[2] = (unsigned char)(intValue >> 16);
buf[1] = (unsigned char)(intValue >> 8);
buf[0] = (unsigned char) intValue;
}
}
int64
ByteOrderValues::getLong(const unsigned char *buf, int byteOrder)
{
if ( byteOrder == ENDIAN_BIG )
{
return
(int64) (buf[0]) << 56
| (int64) (buf[1] & 0xff) << 48
| (int64) (buf[2] & 0xff) << 40
| (int64) (buf[3] & 0xff) << 32
| (int64) (buf[4] & 0xff) << 24
| (int64) (buf[5] & 0xff) << 16
| (int64) (buf[6] & 0xff) << 8
| (int64) (buf[7] & 0xff);
}
else // ENDIAN_LITTLE
{
assert(byteOrder == ENDIAN_LITTLE);
return
(int64) (buf[7]) << 56
| (int64) (buf[6] & 0xff) << 48
| (int64) (buf[5] & 0xff) << 40
| (int64) (buf[4] & 0xff) << 32
| (int64) (buf[3] & 0xff) << 24
| (int64) (buf[2] & 0xff) << 16
| (int64) (buf[1] & 0xff) << 8
| (int64) (buf[0] & 0xff);
}
}
void
ByteOrderValues::putLong(int64 longValue, unsigned char *buf, int byteOrder)
{
if ( byteOrder == ENDIAN_BIG )
{
buf[0] = (unsigned char)(longValue >> 56);
buf[1] = (unsigned char)(longValue >> 48);
buf[2] = (unsigned char)(longValue >> 40);
buf[3] = (unsigned char)(longValue >> 32);
buf[4] = (unsigned char)(longValue >> 24);
buf[5] = (unsigned char)(longValue >> 16);
buf[6] = (unsigned char)(longValue >> 8);
buf[7] = (unsigned char) longValue;
}
else // ENDIAN_LITTLE
{
assert(byteOrder == ENDIAN_LITTLE);
buf[0] = (unsigned char) longValue;
buf[1] = (unsigned char)(longValue >> 8);
buf[2] = (unsigned char)(longValue >> 16);
buf[3] = (unsigned char)(longValue >> 24);
buf[4] = (unsigned char)(longValue >> 32);
buf[5] = (unsigned char)(longValue >> 40);
buf[6] = (unsigned char)(longValue >> 48);
buf[7] = (unsigned char)(longValue >> 56);
}
}
double
ByteOrderValues::getDouble(const unsigned char *buf, int byteOrder)
{
int64 longValue = getLong(buf, byteOrder);
double ret;
std::memcpy(&ret, &longValue, sizeof(double));
return ret;
}
void
ByteOrderValues::putDouble(double doubleValue, unsigned char *buf, int byteOrder)
{
int64 longValue;
std::memcpy(&longValue, &doubleValue, sizeof(double));
#if DEBUG_BYTEORDER_VALUES
std::cout<<"ByteOrderValues::putDouble("<<doubleValue<<
", order:"<<byteOrder
<<") = "<<std::hex;
for (int i=0; i<8; i++)
std::cout<<"["<<(int)buf[i]<<"]";
std::cout<<std::dec<<std::endl;
#endif
putLong(longValue, buf, byteOrder);
}
} // namespace geos.io
} // namespace geos
|
Fix building with DEBUG_BYTEORDER_VALUES=1 in ByteOrderValues.cpp
|
Fix building with DEBUG_BYTEORDER_VALUES=1 in ByteOrderValues.cpp
Add missing includes and missing std::
Fixes #863
|
C++
|
lgpl-2.1
|
mwtoews/libgeos,mwtoews/libgeos,libgeos/libgeos,libgeos/libgeos,mwtoews/libgeos,libgeos/libgeos,mwtoews/libgeos,mwtoews/libgeos,mwtoews/libgeos,libgeos/libgeos,mwtoews/libgeos,libgeos/libgeos
|
708ceec1d9ed10dc4b83cf10680420a16124700a
|
src/libmettle/cmd_line.cpp
|
src/libmettle/cmd_line.cpp
|
#include <mettle/driver/cmd_line.hpp>
#include <cassert>
#include <cstdint>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <boost/program_options.hpp>
#include <mettle/driver/log/brief.hpp>
#include <mettle/driver/log/verbose.hpp>
#include <mettle/detail/string_algorithm.hpp>
#ifndef _WIN32
# include <unistd.h>
#else
# include <io.h>
#endif
namespace mettle {
boost::program_options::options_description
make_generic_options(generic_options &opts) {
using namespace boost::program_options;
options_description desc("Generic options");
desc.add_options()
("help,h", value(&opts.show_help)->zero_tokens(), "show help")
;
return desc;
}
boost::program_options::options_description
make_driver_options(driver_options &opts) {
using namespace boost::program_options;
options_description desc("Driver options");
desc.add_options()
("timeout,t", value(&opts.timeout)->value_name("TIME"), "timeout in ms")
("test,T", value(&opts.filters.by_name)->value_name("REGEX"),
"regex matching names of tests to run")
("attr,a", value(&opts.filters.by_attr)->value_name("ATTR"),
"attributes of tests to run")
;
return desc;
}
// MSVC doesn't understand [[noreturn]], so just ignore the warning here.
#if defined(_MSC_VER) && !defined(__clang__)
# pragma warning(push)
# pragma warning(disable:4715)
#endif
bool color_enabled(color_option opt, int fd) {
switch(opt) {
case color_option::never:
return false;
case color_option::automatic:
#ifndef _WIN32
return isatty(fd);
#else
return _isatty(fd);
#endif
case color_option::always:
return true;
default:
assert(false && "unexpected value");
}
}
#if defined(_MSC_VER) && !defined(__clang__)
# pragma warning(pop)
#endif
boost::program_options::options_description
make_output_options(output_options &opts, const logger_factory &factory) {
using namespace boost::program_options;
std::ostringstream ss;
ss << "set output format (one of: " << detail::joined(factory, [](auto &&i) {
return i.first;
}) << "; default: " << opts.output << ")";
options_description desc("Output options");
desc.add_options()
("output,o", value(&opts.output)->value_name("FORMAT"), ss.str().c_str())
("color,c", value(&opts.color)->value_name("WHEN")
->implicit_value(color_option::always, "always"),
"show colored output (one of: never, auto, always; default: auto)")
("runs,n", value(&opts.runs)->value_name("N"), "number of test runs")
("show-terminal", value(&opts.show_terminal)->zero_tokens(),
"show terminal output for each test")
("show-time", value(&opts.show_time)->zero_tokens(),
"show the duration for each test")
;
return desc;
}
boost::program_options::option_description *
has_option(const boost::program_options::options_description &options,
const boost::program_options::variables_map &args) {
for(const auto &i : options.options()) {
if(args.count(i->long_name()))
return i.get();
}
return nullptr;
}
logger_factory make_logger_factory() {
logger_factory f;
f.add("silent", [](indenting_ostream &, const output_options &) {
return std::unique_ptr<log::file_logger>();
});
f.add("brief", [](indenting_ostream &out, const output_options &) {
return std::make_unique<log::brief>(out);
});
f.add("verbose", [](indenting_ostream &out, const output_options &args) {
return std::make_unique<log::verbose>(
out, args.runs, args.show_time, args.show_terminal
);
});
return f;
}
attr_filter parse_attr(const std::string &value) {
enum parse_state {
ITEM_START,
NAME_START,
NAME,
VALUE_START,
VALUE
};
attr_filter result;
bool negated;
parse_state state = ITEM_START;
std::string::const_iterator i = value.begin(), start, name_start, name_end;
do {
switch(state) {
case ITEM_START:
if(i == value.end()) {
throw std::invalid_argument("unexpected end of string");
}
else if(*i == '!') {
negated = true;
state = NAME_START;
break;
}
negated = false;
case NAME_START:
if(i == value.end())
throw std::invalid_argument("unexpected end of string");
else if(*i == ',' || *i == '=')
throw std::invalid_argument("expected attribute name");
start = i;
state = NAME;
break;
case NAME:
if(i == value.end() || *i == ',') {
auto item = has_attr(std::string(start, i));
result.insert(negated ? !std::move(item) : std::move(item));
state = ITEM_START;
}
else if(*i == '=') {
name_start = start;
name_end = i;
state = VALUE_START;
}
break;
case VALUE_START:
start = i;
state = VALUE;
case VALUE:
if(i == value.end() || *i == ',') {
auto item = has_attr(
std::string(name_start, name_end),
std::string(start, i)
);
result.insert(negated ? !std::move(item) : std::move(item));
state = ITEM_START;
}
break;
default:
assert(false && "invalid parse state");
}
} while(i++ != value.end());
assert(state == ITEM_START);
return result;
}
void validate(boost::any &v, const std::vector<std::string> &values,
color_option*, int) {
using namespace boost::program_options;
validators::check_first_occurrence(v);
const std::string &val = validators::get_single_string(values);
if(val == "never")
v = color_option::never;
else if(val == "auto")
v = color_option::automatic;
else if(val == "always")
v = color_option::always;
else
boost::throw_exception(invalid_option_value(val));
}
void validate(boost::any &v, const std::vector<std::string> &values,
attr_filter_set*, int) {
using namespace boost::program_options;
if(v.empty())
v = attr_filter_set();
attr_filter_set *filters = boost::any_cast<attr_filter_set>(&v);
assert(filters != nullptr);
for(const auto &i : values) {
try {
filters->insert(parse_attr(i));
}
catch(...) {
boost::throw_exception(invalid_option_value(i));
}
}
}
void validate(boost::any &v, const std::vector<std::string> &values,
name_filter_set*, int) {
using namespace boost::program_options;
if(v.empty())
v = name_filter_set();
name_filter_set *filters = boost::any_cast<name_filter_set>(&v);
assert(filters != nullptr);
for(const auto &i : values) {
try {
filters->insert(std::regex(i));
}
catch(...) {
boost::throw_exception(invalid_option_value(i));
}
}
}
} // namespace mettle
namespace boost {
void validate(boost::any &v, const std::vector<std::string> &values,
std::chrono::milliseconds*, int) {
using namespace boost::program_options;
validators::check_first_occurrence(v);
const std::string &val = validators::get_single_string(values);
try {
v = std::chrono::milliseconds(boost::lexical_cast<std::size_t>(val));
}
catch(...) {
boost::throw_exception(invalid_option_value(val));
}
}
#ifdef _WIN32
void validate(boost::any &v, const std::vector<std::string> &values,
HANDLE*, int) {
using namespace boost::program_options;
validators::check_first_occurrence(v);
const std::string &val = validators::get_single_string(values);
try {
HANDLE h;
std::istringstream is(val);
is >> h;
v = h;
}
catch (...) {
boost::throw_exception(invalid_option_value(val));
}
}
#endif
} // namespace boost
|
#include <mettle/driver/cmd_line.hpp>
#include <cassert>
#include <cstdint>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <boost/program_options.hpp>
#include <mettle/driver/log/brief.hpp>
#include <mettle/driver/log/verbose.hpp>
#include <mettle/detail/string_algorithm.hpp>
#ifndef _WIN32
# include <unistd.h>
#else
# include <io.h>
#endif
namespace mettle {
boost::program_options::options_description
make_generic_options(generic_options &opts) {
using namespace boost::program_options;
options_description desc("Generic options");
desc.add_options()
("help,h", value(&opts.show_help)->zero_tokens(), "show help")
;
return desc;
}
boost::program_options::options_description
make_driver_options(driver_options &opts) {
using namespace boost::program_options;
options_description desc("Driver options");
desc.add_options()
("timeout,t", value(&opts.timeout)->value_name("TIME"), "timeout in ms")
("test,T", value(&opts.filters.by_name)->value_name("REGEX"),
"regex matching names of tests to run")
("attr,a", value(&opts.filters.by_attr)->value_name("ATTR"),
"attributes of tests to run")
;
return desc;
}
// MSVC doesn't understand [[noreturn]], so just ignore the warning here.
#if defined(_MSC_VER) && !defined(__clang__)
# pragma warning(push)
# pragma warning(disable:4715)
#endif
bool color_enabled(color_option opt, int fd) {
switch(opt) {
case color_option::never:
return false;
case color_option::automatic:
#ifndef _WIN32
return isatty(fd);
#else
return _isatty(fd);
#endif
case color_option::always:
return true;
default:
assert(false && "unexpected value");
}
}
#if defined(_MSC_VER) && !defined(__clang__)
# pragma warning(pop)
#endif
boost::program_options::options_description
make_output_options(output_options &opts, const logger_factory &factory) {
using namespace boost::program_options;
std::ostringstream ss;
ss << "set output format (one of: " << detail::joined(factory, [](auto &&i) {
return i.first;
}) << "; default: " << opts.output << ")";
options_description desc("Output options");
desc.add_options()
("output,o", value(&opts.output)->value_name("FORMAT"), ss.str().c_str())
("color", value(&opts.color)->value_name("WHEN"),
"show colored output (one of: never, auto, always; default: auto)")
(",c", value(&opts.color)->zero_tokens()
->implicit_value(color_option::always, "always"),
"show colored output (equivalent to `--color=always`)")
("runs,n", value(&opts.runs)->value_name("N"), "number of test runs")
("show-terminal", value(&opts.show_terminal)->zero_tokens(),
"show terminal output for each test")
("show-time", value(&opts.show_time)->zero_tokens(),
"show the duration for each test")
;
return desc;
}
boost::program_options::option_description *
has_option(const boost::program_options::options_description &options,
const boost::program_options::variables_map &args) {
for(const auto &i : options.options()) {
if(args.count(i->long_name()))
return i.get();
}
return nullptr;
}
logger_factory make_logger_factory() {
logger_factory f;
f.add("silent", [](indenting_ostream &, const output_options &) {
return std::unique_ptr<log::file_logger>();
});
f.add("brief", [](indenting_ostream &out, const output_options &) {
return std::make_unique<log::brief>(out);
});
f.add("verbose", [](indenting_ostream &out, const output_options &args) {
return std::make_unique<log::verbose>(
out, args.runs, args.show_time, args.show_terminal
);
});
return f;
}
attr_filter parse_attr(const std::string &value) {
enum parse_state {
ITEM_START,
NAME_START,
NAME,
VALUE_START,
VALUE
};
attr_filter result;
bool negated;
parse_state state = ITEM_START;
std::string::const_iterator i = value.begin(), start, name_start, name_end;
do {
switch(state) {
case ITEM_START:
if(i == value.end()) {
throw std::invalid_argument("unexpected end of string");
}
else if(*i == '!') {
negated = true;
state = NAME_START;
break;
}
negated = false;
case NAME_START:
if(i == value.end())
throw std::invalid_argument("unexpected end of string");
else if(*i == ',' || *i == '=')
throw std::invalid_argument("expected attribute name");
start = i;
state = NAME;
break;
case NAME:
if(i == value.end() || *i == ',') {
auto item = has_attr(std::string(start, i));
result.insert(negated ? !std::move(item) : std::move(item));
state = ITEM_START;
}
else if(*i == '=') {
name_start = start;
name_end = i;
state = VALUE_START;
}
break;
case VALUE_START:
start = i;
state = VALUE;
case VALUE:
if(i == value.end() || *i == ',') {
auto item = has_attr(
std::string(name_start, name_end),
std::string(start, i)
);
result.insert(negated ? !std::move(item) : std::move(item));
state = ITEM_START;
}
break;
default:
assert(false && "invalid parse state");
}
} while(i++ != value.end());
assert(state == ITEM_START);
return result;
}
void validate(boost::any &v, const std::vector<std::string> &values,
color_option*, int) {
using namespace boost::program_options;
validators::check_first_occurrence(v);
const std::string &val = validators::get_single_string(values);
if(val == "never")
v = color_option::never;
else if(val == "auto")
v = color_option::automatic;
else if(val == "always")
v = color_option::always;
else
boost::throw_exception(invalid_option_value(val));
}
void validate(boost::any &v, const std::vector<std::string> &values,
attr_filter_set*, int) {
using namespace boost::program_options;
if(v.empty())
v = attr_filter_set();
attr_filter_set *filters = boost::any_cast<attr_filter_set>(&v);
assert(filters != nullptr);
for(const auto &i : values) {
try {
filters->insert(parse_attr(i));
}
catch(...) {
boost::throw_exception(invalid_option_value(i));
}
}
}
void validate(boost::any &v, const std::vector<std::string> &values,
name_filter_set*, int) {
using namespace boost::program_options;
if(v.empty())
v = name_filter_set();
name_filter_set *filters = boost::any_cast<name_filter_set>(&v);
assert(filters != nullptr);
for(const auto &i : values) {
try {
filters->insert(std::regex(i));
}
catch(...) {
boost::throw_exception(invalid_option_value(i));
}
}
}
} // namespace mettle
namespace boost {
void validate(boost::any &v, const std::vector<std::string> &values,
std::chrono::milliseconds*, int) {
using namespace boost::program_options;
validators::check_first_occurrence(v);
const std::string &val = validators::get_single_string(values);
try {
v = std::chrono::milliseconds(boost::lexical_cast<std::size_t>(val));
}
catch(...) {
boost::throw_exception(invalid_option_value(val));
}
}
#ifdef _WIN32
void validate(boost::any &v, const std::vector<std::string> &values,
HANDLE*, int) {
using namespace boost::program_options;
validators::check_first_occurrence(v);
const std::string &val = validators::get_single_string(values);
try {
HANDLE h;
std::istringstream is(val);
is >> h;
v = h;
}
catch (...) {
boost::throw_exception(invalid_option_value(val));
}
}
#endif
} // namespace boost
|
Simplify -c argument (now equivalent to --color=always)
|
Simplify -c argument (now equivalent to --color=always)
|
C++
|
bsd-3-clause
|
jimporter/mettle,jimporter/mettle
|
bfb60d9409b66fe444b5b9bb321810317247e396
|
libcard/src/deck.cpp
|
libcard/src/deck.cpp
|
#include <card/deck.hpp>
#include <algorithm>
namespace cg {
Deck::Deck(std::string&& name) : m_name(name), m_cards() {}
void Deck::shuffle() {
std::shuffle(m_cards.begin(), m_cards.end(),
std::mt19937{std::random_device{}()});
}
}
|
#include <card/deck.hpp>
#include <algorithm>
#include <random>
namespace cg {
Deck::Deck(std::string&& name) : m_name(name), m_cards() {}
void Deck::shuffle() {
std::shuffle(m_cards.begin(), m_cards.end(),
std::mt19937{std::random_device{}()});
}
}
|
Fix compilation
|
Fix compilation
|
C++
|
apache-2.0
|
Mizux/cardgame
|
1b0acc309ff2b5135b313308fb1ce276a8c95097
|
libcpu/interface.cpp
|
libcpu/interface.cpp
|
/*
* libcpu: interface.cpp
*
* This is the interface to the client.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/TargetSelect.h"
/* project global headers */
#include "libcpu.h"
#include "libcpu_llvm.h"
#include "tag.h"
#include "translate_all.h"
#include "translate_singlestep.h"
#include "translate_singlestep_bb.h"
#include "function.h"
#include "optimize.h"
#include "stat.h"
/* architecture descriptors */
extern arch_func_t arch_func_6502;
extern arch_func_t arch_func_m68k;
extern arch_func_t arch_func_mips;
extern arch_func_t arch_func_m88k;
extern arch_func_t arch_func_arm;
extern arch_func_t arch_func_8086;
extern arch_func_t arch_func_fapra;
#define IS_LITTLE_ENDIAN(cpu) (((cpu)->info.common_flags & CPU_FLAG_ENDIAN_MASK) == CPU_FLAG_ENDIAN_LITTLE)
static inline bool
is_valid_gpr_size(size_t size)
{
switch (size) {
case 0: case 1: case 8: case 16: case 32: case 64:
return true;
default:
return false;
}
}
static inline bool
is_valid_fpr_size(size_t size)
{
switch (size) {
case 0: case 32: case 64: case 80: case 128:
return true;
default:
return false;
}
}
static inline bool
is_valid_vr_size(size_t size)
{
switch (size) {
case 0: case 64: case 128:
return true;
default:
return false;
}
}
//////////////////////////////////////////////////////////////////////
// cpu_t
//////////////////////////////////////////////////////////////////////
cpu_t *
cpu_new(cpu_arch_t arch, uint32_t flags, uint32_t arch_flags)
{
cpu_t *cpu;
llvm::InitializeNativeTarget();
cpu = new cpu_t;
assert(cpu != NULL);
memset(&cpu->info, 0, sizeof(cpu->info));
memset(&cpu->rf, 0, sizeof(cpu->rf));
cpu->info.type = arch;
cpu->info.name = "noname";
cpu->info.common_flags = flags;
cpu->info.arch_flags = arch_flags;
switch (arch) {
case CPU_ARCH_6502:
cpu->f = arch_func_6502;
break;
case CPU_ARCH_M68K:
cpu->f = arch_func_m68k;
break;
case CPU_ARCH_MIPS:
cpu->f = arch_func_mips;
break;
case CPU_ARCH_M88K:
cpu->f = arch_func_m88k;
break;
case CPU_ARCH_ARM:
cpu->f = arch_func_arm;
break;
case CPU_ARCH_8086:
cpu->f = arch_func_8086;
break;
case CPU_ARCH_FAPRA:
cpu->f = arch_func_fapra;
break;
default:
printf("illegal arch: %d\n", arch);
exit(1);
}
cpu->code_start = 0;
cpu->code_end = 0;
cpu->code_entry = 0;
cpu->tag = NULL;
uint32_t i;
for (i = 0; i < sizeof(cpu->func)/sizeof(*cpu->func); i++)
cpu->func[i] = NULL;
for (i = 0; i < sizeof(cpu->fp)/sizeof(*cpu->fp); i++)
cpu->fp[i] = NULL;
cpu->functions = 0;
cpu->flags_codegen = CPU_CODEGEN_OPTIMIZE;
cpu->flags_debug = CPU_DEBUG_NONE;
cpu->flags_hint = CPU_HINT_NONE;
cpu->flags = 0;
// init the frontend
cpu->f.init(cpu, &cpu->info, &cpu->rf);
assert(is_valid_gpr_size(cpu->info.register_size[CPU_REG_GPR]) &&
"the specified GPR size is not guaranteed to work");
assert(is_valid_fpr_size(cpu->info.register_size[CPU_REG_FPR]) &&
"the specified FPR size is not guaranteed to work");
assert(is_valid_vr_size(cpu->info.register_size[CPU_REG_VR]) &&
"the specified VR size is not guaranteed to work");
assert(is_valid_gpr_size(cpu->info.register_size[CPU_REG_XR]) &&
"the specified XR size is not guaranteed to work");
uint32_t count = cpu->info.register_count[CPU_REG_GPR];
if (count != 0) {
cpu->ptr_gpr = (Value **)calloc(count, sizeof(Value *));
cpu->in_ptr_gpr = (Value **)calloc(count, sizeof(Value *));
} else {
cpu->ptr_gpr = NULL;
cpu->in_ptr_gpr = NULL;
}
count = cpu->info.register_count[CPU_REG_XR];
if (count != 0) {
cpu->ptr_xr = (Value **)calloc(count, sizeof(Value *));
cpu->in_ptr_xr = (Value **)calloc(count, sizeof(Value *));
} else {
cpu->ptr_xr = NULL;
cpu->in_ptr_xr = NULL;
}
count = cpu->info.register_count[CPU_REG_FPR];
if (count != 0) {
cpu->ptr_fpr = (Value **)calloc(count, sizeof(Value *));
cpu->in_ptr_fpr = (Value **)calloc(count, sizeof(Value *));
} else {
cpu->ptr_fpr = NULL;
cpu->in_ptr_fpr = NULL;
}
if (cpu->info.psr_size != 0) {
cpu->ptr_FLAG = (Value **)calloc(cpu->info.flags_count,
sizeof(Value*));
assert(cpu->ptr_FLAG != NULL);
}
// init LLVM
cpu->mod = new Module(cpu->info.name, _CTX());
assert(cpu->mod != NULL);
cpu->exec_engine = ExecutionEngine::create(cpu->mod);
assert(cpu->exec_engine != NULL);
// check if FP80 and FP128 are supported by this architecture.
// XXX there is a better way to do this?
std::string data_layout = cpu->exec_engine->getDataLayout().getStringRepresentation();
if (data_layout.find("f80") != std::string::npos) {
LOG("INFO: FP80 supported.\n");
cpu->flags |= CPU_FLAG_FP80;
}
if (data_layout.find("f128") != std::string::npos) {
LOG("INFO: FP128 supported.\n");
cpu->flags |= CPU_FLAG_FP128;
}
// check if we need to swap guest memory.
if (cpu->exec_engine->getDataLayout().isLittleEndian()
^ IS_LITTLE_ENDIAN(cpu))
cpu->flags |= CPU_FLAG_SWAPMEM;
cpu->timer_total[TIMER_TAG] = 0;
cpu->timer_total[TIMER_FE] = 0;
cpu->timer_total[TIMER_BE] = 0;
cpu->timer_total[TIMER_RUN] = 0;
return cpu;
}
void
cpu_free(cpu_t *cpu)
{
if (cpu->f.done != NULL)
cpu->f.done(cpu);
if (cpu->exec_engine != NULL) {
if (cpu->cur_func != NULL) {
cpu->exec_engine->freeMachineCodeForFunction(cpu->cur_func);
cpu->cur_func->eraseFromParent();
}
delete cpu->exec_engine;
}
if (cpu->ptr_FLAG != NULL)
free(cpu->ptr_FLAG);
if (cpu->in_ptr_fpr != NULL)
free(cpu->in_ptr_fpr);
if (cpu->ptr_fpr != NULL)
free(cpu->ptr_fpr);
if (cpu->in_ptr_xr != NULL)
free(cpu->in_ptr_xr);
if (cpu->ptr_xr != NULL)
free(cpu->ptr_xr);
if (cpu->in_ptr_gpr != NULL)
free(cpu->in_ptr_gpr);
if (cpu->ptr_gpr != NULL)
free(cpu->ptr_gpr);
delete cpu;
}
void
cpu_set_ram(cpu_t*cpu, uint8_t *r)
{
cpu->RAM = r;
}
void
cpu_set_flags_codegen(cpu_t *cpu, uint32_t f)
{
cpu->flags_codegen = f;
}
void
cpu_set_flags_debug(cpu_t *cpu, uint32_t f)
{
cpu->flags_debug = f;
}
void
cpu_set_flags_hint(cpu_t *cpu, uint32_t f)
{
cpu->flags_hint = f;
}
void
cpu_tag(cpu_t *cpu, addr_t pc)
{
update_timing(cpu, TIMER_TAG, true);
tag_start(cpu, pc);
update_timing(cpu, TIMER_TAG, false);
}
static void
cpu_translate_function(cpu_t *cpu)
{
BasicBlock *bb_ret, *bb_trap, *label_entry, *bb_start;
/* create function and fill it with std basic blocks */
cpu->cur_func = cpu_create_function(cpu, "jitmain", &bb_ret, &bb_trap, &label_entry);
cpu->func[cpu->functions] = cpu->cur_func;
/* TRANSLATE! */
update_timing(cpu, TIMER_FE, true);
if (cpu->flags_debug & CPU_DEBUG_SINGLESTEP) {
bb_start = cpu_translate_singlestep(cpu, bb_ret, bb_trap);
} else if (cpu->flags_debug & CPU_DEBUG_SINGLESTEP_BB) {
bb_start = cpu_translate_singlestep_bb(cpu, bb_ret, bb_trap);
} else {
bb_start = cpu_translate_all(cpu, bb_ret, bb_trap);
}
update_timing(cpu, TIMER_FE, false);
/* finish entry basicblock */
BranchInst::Create(bb_start, label_entry);
/* make sure everything is OK */
verifyFunction(*cpu->cur_func, PrintMessageAction);
if (cpu->flags_debug & CPU_DEBUG_PRINT_IR)
cpu->mod->dump();
if (cpu->flags_codegen & CPU_CODEGEN_OPTIMIZE) {
LOG("*** Optimizing...");
optimize(cpu);
LOG("done.\n");
if (cpu->flags_debug & CPU_DEBUG_PRINT_IR_OPTIMIZED)
cpu->mod->dump();
}
LOG("*** Translating...");
update_timing(cpu, TIMER_BE, true);
cpu->fp[cpu->functions] = cpu->exec_engine->getPointerToFunction(cpu->cur_func);
update_timing(cpu, TIMER_BE, false);
LOG("done.\n");
cpu->functions++;
}
/* forces ahead of time translation (e.g. for benchmarking the run) */
void
cpu_translate(cpu_t *cpu)
{
/* on demand translation */
if (cpu->tags_dirty)
cpu_translate_function(cpu);
cpu->tags_dirty = false;
}
typedef int (*fp_t)(uint8_t *RAM, void *grf, void *frf, debug_function_t fp);
#ifdef __GNUC__
void __attribute__((noinline))
breakpoint() {
asm("nop");
}
#else
void breakpoint() {}
#endif
int
cpu_run(cpu_t *cpu, debug_function_t debug_function)
{
addr_t pc = 0, orig_pc = 0;
uint32_t i;
int ret;
bool success;
bool do_translate = true;
/* try to find the entry in all functions */
while(true) {
if (do_translate) {
cpu_translate(cpu);
pc = cpu->f.get_pc(cpu, cpu->rf.grf);
}
orig_pc = pc;
success = false;
for (i = 0; i < cpu->functions; i++) {
fp_t FP = (fp_t)cpu->fp[i];
update_timing(cpu, TIMER_RUN, true);
breakpoint();
ret = FP(cpu->RAM, cpu->rf.grf, cpu->rf.frf, debug_function);
update_timing(cpu, TIMER_RUN, false);
pc = cpu->f.get_pc(cpu, cpu->rf.grf);
if (ret != JIT_RETURN_FUNCNOTFOUND)
return ret;
if (!is_inside_code_area(cpu, pc))
return ret;
if (pc != orig_pc) {
success = true;
break;
}
}
if (!success) {
LOG("{%" PRIx64 "}", pc);
cpu_tag(cpu, pc);
do_translate = true;
}
}
}
//printf("%d\n", __LINE__);
void
cpu_flush(cpu_t *cpu)
{
cpu->exec_engine->freeMachineCodeForFunction(cpu->cur_func);
cpu->cur_func->eraseFromParent();
cpu->functions = 0;
// reset bb caching mapping
cpu->func_bb.clear();
// delete cpu->mod;
// cpu->mod = NULL;
}
void
cpu_print_statistics(cpu_t *cpu)
{
printf("tag = %8" PRId64 "\n", cpu->timer_total[TIMER_TAG]);
printf("fe = %8" PRId64 "\n", cpu->timer_total[TIMER_FE]);
printf("be = %8" PRId64 "\n", cpu->timer_total[TIMER_BE]);
printf("run = %8" PRId64 "\n", cpu->timer_total[TIMER_RUN]);
}
//printf("%s:%d\n", __func__, __LINE__);
|
/*
* libcpu: interface.cpp
*
* This is the interface to the client.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/TargetSelect.h"
/* project global headers */
#include "libcpu.h"
#include "libcpu_llvm.h"
#include "tag.h"
#include "translate_all.h"
#include "translate_singlestep.h"
#include "translate_singlestep_bb.h"
#include "function.h"
#include "optimize.h"
#include "stat.h"
/* architecture descriptors */
extern arch_func_t arch_func_6502;
extern arch_func_t arch_func_m68k;
extern arch_func_t arch_func_mips;
extern arch_func_t arch_func_m88k;
extern arch_func_t arch_func_arm;
extern arch_func_t arch_func_8086;
extern arch_func_t arch_func_fapra;
#define IS_LITTLE_ENDIAN(cpu) (((cpu)->info.common_flags & CPU_FLAG_ENDIAN_MASK) == CPU_FLAG_ENDIAN_LITTLE)
static inline bool
is_valid_gpr_size(size_t size)
{
switch (size) {
case 0: case 1: case 8: case 16: case 32: case 64:
return true;
default:
return false;
}
}
static inline bool
is_valid_fpr_size(size_t size)
{
switch (size) {
case 0: case 32: case 64: case 80: case 128:
return true;
default:
return false;
}
}
static inline bool
is_valid_vr_size(size_t size)
{
switch (size) {
case 0: case 64: case 128:
return true;
default:
return false;
}
}
//////////////////////////////////////////////////////////////////////
// cpu_t
//////////////////////////////////////////////////////////////////////
cpu_t *
cpu_new(cpu_arch_t arch, uint32_t flags, uint32_t arch_flags)
{
cpu_t *cpu;
llvm::InitializeNativeTarget();
cpu = new cpu_t;
assert(cpu != NULL);
memset(&cpu->info, 0, sizeof(cpu->info));
memset(&cpu->rf, 0, sizeof(cpu->rf));
cpu->info.type = arch;
cpu->info.name = "noname";
cpu->info.common_flags = flags;
cpu->info.arch_flags = arch_flags;
switch (arch) {
case CPU_ARCH_6502:
cpu->f = arch_func_6502;
break;
case CPU_ARCH_M68K:
cpu->f = arch_func_m68k;
break;
case CPU_ARCH_MIPS:
cpu->f = arch_func_mips;
break;
case CPU_ARCH_M88K:
cpu->f = arch_func_m88k;
break;
case CPU_ARCH_ARM:
cpu->f = arch_func_arm;
break;
case CPU_ARCH_8086:
cpu->f = arch_func_8086;
break;
case CPU_ARCH_FAPRA:
cpu->f = arch_func_fapra;
break;
default:
printf("illegal arch: %d\n", arch);
exit(1);
}
cpu->code_start = 0;
cpu->code_end = 0;
cpu->code_entry = 0;
cpu->tag = NULL;
uint32_t i;
for (i = 0; i < sizeof(cpu->func)/sizeof(*cpu->func); i++)
cpu->func[i] = NULL;
for (i = 0; i < sizeof(cpu->fp)/sizeof(*cpu->fp); i++)
cpu->fp[i] = NULL;
cpu->functions = 0;
cpu->flags_codegen = CPU_CODEGEN_OPTIMIZE;
cpu->flags_debug = CPU_DEBUG_NONE;
cpu->flags_hint = CPU_HINT_NONE;
cpu->flags = 0;
// init the frontend
cpu->f.init(cpu, &cpu->info, &cpu->rf);
assert(is_valid_gpr_size(cpu->info.register_size[CPU_REG_GPR]) &&
"the specified GPR size is not guaranteed to work");
assert(is_valid_fpr_size(cpu->info.register_size[CPU_REG_FPR]) &&
"the specified FPR size is not guaranteed to work");
assert(is_valid_vr_size(cpu->info.register_size[CPU_REG_VR]) &&
"the specified VR size is not guaranteed to work");
assert(is_valid_gpr_size(cpu->info.register_size[CPU_REG_XR]) &&
"the specified XR size is not guaranteed to work");
uint32_t count = cpu->info.register_count[CPU_REG_GPR];
if (count != 0) {
cpu->ptr_gpr = (Value **)calloc(count, sizeof(Value *));
cpu->in_ptr_gpr = (Value **)calloc(count, sizeof(Value *));
} else {
cpu->ptr_gpr = NULL;
cpu->in_ptr_gpr = NULL;
}
count = cpu->info.register_count[CPU_REG_XR];
if (count != 0) {
cpu->ptr_xr = (Value **)calloc(count, sizeof(Value *));
cpu->in_ptr_xr = (Value **)calloc(count, sizeof(Value *));
} else {
cpu->ptr_xr = NULL;
cpu->in_ptr_xr = NULL;
}
count = cpu->info.register_count[CPU_REG_FPR];
if (count != 0) {
cpu->ptr_fpr = (Value **)calloc(count, sizeof(Value *));
cpu->in_ptr_fpr = (Value **)calloc(count, sizeof(Value *));
} else {
cpu->ptr_fpr = NULL;
cpu->in_ptr_fpr = NULL;
}
if (cpu->info.psr_size != 0) {
cpu->ptr_FLAG = (Value **)calloc(cpu->info.flags_count,
sizeof(Value*));
assert(cpu->ptr_FLAG != NULL);
}
// init LLVM
cpu->mod = new Module(cpu->info.name, _CTX());
assert(cpu->mod != NULL);
cpu->exec_engine = ExecutionEngine::create(cpu->mod);
assert(cpu->exec_engine != NULL);
// check if FP80 and FP128 are supported by this architecture.
// XXX there is a better way to do this?
std::string data_layout = cpu->exec_engine->getDataLayout().getStringRepresentation();
if (data_layout.find("f80") != std::string::npos) {
LOG("INFO: FP80 supported.\n");
cpu->flags |= CPU_FLAG_FP80;
}
if (data_layout.find("f128") != std::string::npos) {
LOG("INFO: FP128 supported.\n");
cpu->flags |= CPU_FLAG_FP128;
}
// check if we need to swap guest memory.
if (cpu->exec_engine->getDataLayout().isLittleEndian()
^ IS_LITTLE_ENDIAN(cpu))
cpu->flags |= CPU_FLAG_SWAPMEM;
cpu->timer_total[TIMER_TAG] = 0;
cpu->timer_total[TIMER_FE] = 0;
cpu->timer_total[TIMER_BE] = 0;
cpu->timer_total[TIMER_RUN] = 0;
return cpu;
}
void
cpu_free(cpu_t *cpu)
{
if (cpu->f.done != NULL)
cpu->f.done(cpu);
if (cpu->exec_engine != NULL) {
if (cpu->cur_func != NULL) {
cpu->exec_engine->freeMachineCodeForFunction(cpu->cur_func);
cpu->cur_func->eraseFromParent();
}
delete cpu->exec_engine;
}
if (cpu->ptr_FLAG != NULL)
free(cpu->ptr_FLAG);
if (cpu->in_ptr_fpr != NULL)
free(cpu->in_ptr_fpr);
if (cpu->ptr_fpr != NULL)
free(cpu->ptr_fpr);
if (cpu->in_ptr_xr != NULL)
free(cpu->in_ptr_xr);
if (cpu->ptr_xr != NULL)
free(cpu->ptr_xr);
if (cpu->in_ptr_gpr != NULL)
free(cpu->in_ptr_gpr);
if (cpu->ptr_gpr != NULL)
free(cpu->ptr_gpr);
delete cpu;
}
void
cpu_set_ram(cpu_t*cpu, uint8_t *r)
{
cpu->RAM = r;
}
void
cpu_set_flags_codegen(cpu_t *cpu, uint32_t f)
{
cpu->flags_codegen = f;
}
void
cpu_set_flags_debug(cpu_t *cpu, uint32_t f)
{
cpu->flags_debug = f;
}
void
cpu_set_flags_hint(cpu_t *cpu, uint32_t f)
{
cpu->flags_hint = f;
}
void
cpu_tag(cpu_t *cpu, addr_t pc)
{
update_timing(cpu, TIMER_TAG, true);
tag_start(cpu, pc);
update_timing(cpu, TIMER_TAG, false);
}
static void
cpu_translate_function(cpu_t *cpu)
{
BasicBlock *bb_ret, *bb_trap, *label_entry, *bb_start;
/* create function and fill it with std basic blocks */
cpu->cur_func = cpu_create_function(cpu, "jitmain", &bb_ret, &bb_trap, &label_entry);
cpu->func[cpu->functions] = cpu->cur_func;
/* TRANSLATE! */
update_timing(cpu, TIMER_FE, true);
if (cpu->flags_debug & CPU_DEBUG_SINGLESTEP) {
bb_start = cpu_translate_singlestep(cpu, bb_ret, bb_trap);
} else if (cpu->flags_debug & CPU_DEBUG_SINGLESTEP_BB) {
bb_start = cpu_translate_singlestep_bb(cpu, bb_ret, bb_trap);
} else {
bb_start = cpu_translate_all(cpu, bb_ret, bb_trap);
}
update_timing(cpu, TIMER_FE, false);
/* finish entry basicblock */
BranchInst::Create(bb_start, label_entry);
/* make sure everything is OK */
verifyFunction(*cpu->cur_func, PrintMessageAction);
#if 0
if (cpu->flags_debug & CPU_DEBUG_PRINT_IR)
cpu->mod->dump();
#endif
if (cpu->flags_codegen & CPU_CODEGEN_OPTIMIZE) {
LOG("*** Optimizing...");
optimize(cpu);
LOG("done.\n");
#if 0
if (cpu->flags_debug & CPU_DEBUG_PRINT_IR_OPTIMIZED)
cpu->mod->dump();
#endif
}
LOG("*** Translating...");
update_timing(cpu, TIMER_BE, true);
cpu->fp[cpu->functions] = cpu->exec_engine->getPointerToFunction(cpu->cur_func);
update_timing(cpu, TIMER_BE, false);
LOG("done.\n");
cpu->functions++;
}
/* forces ahead of time translation (e.g. for benchmarking the run) */
void
cpu_translate(cpu_t *cpu)
{
/* on demand translation */
if (cpu->tags_dirty)
cpu_translate_function(cpu);
cpu->tags_dirty = false;
}
typedef int (*fp_t)(uint8_t *RAM, void *grf, void *frf, debug_function_t fp);
#ifdef __GNUC__
void __attribute__((noinline))
breakpoint() {
asm("nop");
}
#else
void breakpoint() {}
#endif
int
cpu_run(cpu_t *cpu, debug_function_t debug_function)
{
addr_t pc = 0, orig_pc = 0;
uint32_t i;
int ret;
bool success;
bool do_translate = true;
/* try to find the entry in all functions */
while(true) {
if (do_translate) {
cpu_translate(cpu);
pc = cpu->f.get_pc(cpu, cpu->rf.grf);
}
orig_pc = pc;
success = false;
for (i = 0; i < cpu->functions; i++) {
fp_t FP = (fp_t)cpu->fp[i];
update_timing(cpu, TIMER_RUN, true);
breakpoint();
ret = FP(cpu->RAM, cpu->rf.grf, cpu->rf.frf, debug_function);
update_timing(cpu, TIMER_RUN, false);
pc = cpu->f.get_pc(cpu, cpu->rf.grf);
if (ret != JIT_RETURN_FUNCNOTFOUND)
return ret;
if (!is_inside_code_area(cpu, pc))
return ret;
if (pc != orig_pc) {
success = true;
break;
}
}
if (!success) {
LOG("{%" PRIx64 "}", pc);
cpu_tag(cpu, pc);
do_translate = true;
}
}
}
//printf("%d\n", __LINE__);
void
cpu_flush(cpu_t *cpu)
{
cpu->exec_engine->freeMachineCodeForFunction(cpu->cur_func);
cpu->cur_func->eraseFromParent();
cpu->functions = 0;
// reset bb caching mapping
cpu->func_bb.clear();
// delete cpu->mod;
// cpu->mod = NULL;
}
void
cpu_print_statistics(cpu_t *cpu)
{
printf("tag = %8" PRId64 "\n", cpu->timer_total[TIMER_TAG]);
printf("fe = %8" PRId64 "\n", cpu->timer_total[TIMER_FE]);
printf("be = %8" PRId64 "\n", cpu->timer_total[TIMER_BE]);
printf("run = %8" PRId64 "\n", cpu->timer_total[TIMER_RUN]);
}
//printf("%s:%d\n", __func__, __LINE__);
|
Kill calls to llvm::Module::dump()
|
llvm: Kill calls to llvm::Module::dump()
Linker says no:
/usr/bin/ld: ../../libcpu/libcpu.so: undefined reference to `llvm::Module::dump() const'
|
C++
|
bsd-2-clause
|
libcpu/libcpu,libcpu/libcpu,libcpu/libcpu,libcpu/libcpu
|
5f0e5044473e14a914104f3c2c949af0adacbc05
|
src/ngx_rewrite_options.cc
|
src/ngx_rewrite_options.cc
|
/*
* Copyright 2012 Google 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.
*/
// Author: [email protected] (Jeff Kaufman)
extern "C" {
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
}
#include "ngx_rewrite_options.h"
#include "ngx_pagespeed.h"
#include "net/instaweb/public/version.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/util/public/timer.h"
namespace net_instaweb {
const char NgxRewriteOptions::kClassName[] = "NgxRewriteOptions";
RewriteOptions::Properties* NgxRewriteOptions::ngx_properties_ = NULL;
NgxRewriteOptions::NgxRewriteOptions() {
Init();
}
void NgxRewriteOptions::Init() {
DCHECK(ngx_properties_ != NULL)
<< "Call NgxRewriteOptions::Initialize() before construction";
InitializeOptions(ngx_properties_);
}
void NgxRewriteOptions::AddProperties() {
// TODO(jefftk): All these caching-related properties could move to an
// OriginRewriteOptions.
add_ngx_option("", &NgxRewriteOptions::file_cache_path_, "nfcp",
RewriteOptions::kFileCachePath);
add_ngx_option(Timer::kHourMs,
&NgxRewriteOptions::file_cache_clean_interval_ms_,
"nfcci", RewriteOptions::kFileCacheCleanIntervalMs);
add_ngx_option(100 * 1024, // 100MB
&NgxRewriteOptions::file_cache_clean_size_kb_, "nfc",
RewriteOptions::kFileCacheCleanSizeKb);
add_ngx_option(500000,
&NgxRewriteOptions::file_cache_clean_inode_limit_, "nfcl",
RewriteOptions::kFileCacheCleanInodeLimit);
add_ngx_option(16384, //16MB
&NgxRewriteOptions::lru_cache_byte_limit_, "nlcb",
RewriteOptions::kLruCacheByteLimit);
add_ngx_option(1024, // 1MB
&NgxRewriteOptions::lru_cache_kb_per_process_, "nlcp",
RewriteOptions::kLruCacheKbPerProcess);
add_ngx_option("", &NgxRewriteOptions::memcached_servers_, "ams",
RewriteOptions::kMemcachedServers);
add_ngx_option(1, &NgxRewriteOptions::memcached_threads_, "amt",
RewriteOptions::kMemcachedThreads);
add_ngx_option(false, &NgxRewriteOptions::use_shared_mem_locking_, "ausml",
RewriteOptions::kUseSharedMemLocking);
add_ngx_option("", &NgxRewriteOptions::fetcher_proxy_, "afp",
RewriteOptions::kFetcherProxy);
MergeSubclassProperties(ngx_properties_);
NgxRewriteOptions config;
config.InitializeSignaturesAndDefaults();
}
void NgxRewriteOptions::InitializeSignaturesAndDefaults() {
// Calls to foo_.DoNotUseForSignatureComputation() would go here.
// Set default header value.
set_default_x_header_value(kModPagespeedVersion);
}
void NgxRewriteOptions::Initialize() {
if (Properties::Initialize(&ngx_properties_)) {
RewriteOptions::Initialize();
AddProperties();
}
}
void NgxRewriteOptions::Terminate() {
if (Properties::Terminate(&ngx_properties_)) {
RewriteOptions::Terminate();
}
}
bool NgxRewriteOptions::IsDirective(StringPiece config_directive,
StringPiece compare_directive) {
return StringCaseEqual(config_directive, compare_directive);
}
RewriteOptions::OptionSettingResult NgxRewriteOptions::ParseAndSetOptions0(
StringPiece directive, GoogleString* msg, MessageHandler* handler) {
if (IsDirective(directive, "on")) {
set_enabled(true);
} else if (IsDirective(directive, "off")) {
set_enabled(false);
} else {
return RewriteOptions::kOptionNameUnknown;
}
return RewriteOptions::kOptionOk;
}
RewriteOptions::OptionSettingResult NgxRewriteOptions::ParseAndSetOptions1(
StringPiece directive, StringPiece arg,
GoogleString* msg, MessageHandler* handler) {
// FileCachePath needs error checking.
if (IsDirective(directive, "FileCachePath")) {
if (!StringCaseStartsWith(arg, "/")) {
*msg = "must start with a slash";
return RewriteOptions::kOptionValueInvalid;
} else {
set_file_cache_path(arg.as_string());
}
}
RewriteOptions::OptionSettingResult result =
SetOptionFromName(directive, arg.as_string(), msg);
if (result != RewriteOptions::kOptionNameUnknown) {
return result;
}
if (IsDirective(directive, "Allow")) {
Allow(arg);
} else if (IsDirective(directive, "DangerPermitFetchFromUnknownHosts")) {
// TODO(jefftk): port this.
*msg = "not supported";
return RewriteOptions::kOptionValueInvalid;
} else if (IsDirective(directive, "DisableFilters")) {
bool ok = DisableFiltersByCommaSeparatedList(arg, handler);
if (!ok) {
*msg = "Failed to disable some filters.";
return RewriteOptions::kOptionValueInvalid;
}
} else if (IsDirective(directive, "Disallow")) {
Disallow(arg);
} else if (IsDirective(directive, "Domain")) {
domain_lawyer()->AddDomain(arg, handler);
} else if (IsDirective(directive, "EnableFilters")) {
bool ok = EnableFiltersByCommaSeparatedList(arg, handler);
if (!ok) {
*msg = "Failed to enable some filters.";
return RewriteOptions::kOptionValueInvalid;
}
} else if (IsDirective(directive, "FetchWithGzip")) {
// TODO(jefftk): port this.
*msg = "not supported";
return RewriteOptions::kOptionValueInvalid;
} else if (IsDirective(directive, "ForceCaching")) {
// TODO(jefftk): port this.
*msg = "not supported";
return RewriteOptions::kOptionValueInvalid;
} else if (IsDirective(directive, "ExperimentVariable")) {
int slot;
bool ok = StringToInt(arg.as_string().c_str(), &slot);
if (!ok || slot < 1 || slot > 5) {
*msg = "must be an integer between 1 and 5";
return RewriteOptions::kOptionValueInvalid;
}
set_furious_ga_slot(slot);
} else if (IsDirective(directive, "ExperimentSpec")) {
bool ok = AddFuriousSpec(arg, handler);
if (!ok) {
*msg = "not a valid experiment spec";
return RewriteOptions::kOptionValueInvalid;
}
} else if (IsDirective(directive, "RetainComment")) {
RetainComment(arg);
} else if (IsDirective(directive, "BlockingRewriteKey")) {
set_blocking_rewrite_key(arg);
} else {
return RewriteOptions::kOptionNameUnknown;
}
return RewriteOptions::kOptionOk;
}
RewriteOptions::OptionSettingResult NgxRewriteOptions::ParseAndSetOptions2(
StringPiece directive, StringPiece arg1, StringPiece arg2,
GoogleString* msg, MessageHandler* handler) {
if (IsDirective(directive, "MapRewriteDomain")) {
domain_lawyer()->AddRewriteDomainMapping(arg1, arg2, handler);
} else if (IsDirective(directive, "MapOriginDomain")) {
domain_lawyer()->AddOriginDomainMapping(arg1, arg2, handler);
} else if (IsDirective(directive, "ShardDomain")) {
domain_lawyer()->AddShard(arg1, arg2, handler);
} else if (IsDirective(directive, "CustomFetchHeader")) {
AddCustomFetchHeader(arg1, arg2);
} else {
return RewriteOptions::kOptionNameUnknown;
}
return RewriteOptions::kOptionOk;
}
RewriteOptions::OptionSettingResult NgxRewriteOptions::ParseAndSetOptions3(
StringPiece directive, StringPiece arg1, StringPiece arg2, StringPiece arg3,
GoogleString* msg, MessageHandler* handler) {
if (IsDirective(directive, "UrlValuedAttribute")) {
semantic_type::Category category;
bool ok = semantic_type::ParseCategory(arg3, &category);
if (!ok) {
*msg = "Invalid resource category";
return RewriteOptions::kOptionValueInvalid;
}
AddUrlValuedAttribute(arg1, arg2, category);
} else if (IsDirective(directive, "Library")) {
int64 bytes;
bool ok = StringToInt64(arg1.as_string().c_str(), &bytes);
if (!ok || bytes < 0) {
*msg = "Size must be a positive 64-bit integer";
return RewriteOptions::kOptionValueInvalid;
}
ok = RegisterLibrary(bytes, arg2, arg3);
if (!ok) {
*msg = "Format is size md5 url; bad md5 or URL";
return RewriteOptions::kOptionValueInvalid;
}
} else {
return RewriteOptions::kOptionNameUnknown;
}
return RewriteOptions::kOptionOk;
}
// Very similar to apache/mod_instaweb::ParseDirective.
// TODO(jefftk): Move argument parsing to OriginRewriteOptions.
const char*
NgxRewriteOptions::ParseAndSetOptions(
StringPiece* args, int n_args, ngx_pool_t* pool, MessageHandler* handler) {
CHECK(n_args >= 1);
int i;
fprintf(stderr, "Setting option from (");
for (i = 0 ; i < n_args ; i++) {
fprintf(stderr, "%s\"%s\"",
i == 0 ? "" : ", ",
args[i].as_string().c_str());
}
fprintf(stderr, ")\n");
StringPiece directive = args[0];
// Remove initial "ModPagespeed" if there is one.
StringPiece mod_pagespeed("ModPagespeed");
if (StringCaseStartsWith(directive, mod_pagespeed)) {
directive.remove_prefix(mod_pagespeed.size());
}
GoogleString msg;
OptionSettingResult result;
if (n_args == 1) {
result = ParseAndSetOptions0(directive, &msg, handler);
} else if (n_args == 2) {
result = ParseAndSetOptions1(directive, args[1], &msg, handler);
} else if (n_args == 3) {
result = ParseAndSetOptions2(directive, args[1], args[2], &msg, handler);
} else if (n_args == 4) {
result = ParseAndSetOptions3(
directive, args[1], args[2], args[3], &msg, handler);
} else {
return "unknown option";
}
switch (result) {
case RewriteOptions::kOptionOk:
return NGX_CONF_OK;
case RewriteOptions::kOptionNameUnknown:
return "unknown option";
case RewriteOptions::kOptionValueInvalid: {
GoogleString full_directive = "\"";
for (int i = 0 ; i < n_args ; i++) {
StrAppend(&full_directive, i == 0 ? "" : " ", args[i]);
}
StrAppend(&full_directive, "\": ", msg);
char* s = ngx_psol::string_piece_to_pool_string(pool, full_directive);
if (s == NULL) {
return "failed to allocate memory";
}
return s;
}
}
CHECK(false);
return NULL;
}
NgxRewriteOptions* NgxRewriteOptions::Clone() const {
NgxRewriteOptions* options = new NgxRewriteOptions();
options->Merge(*this);
return options;
}
const NgxRewriteOptions* NgxRewriteOptions::DynamicCast(
const RewriteOptions* instance) {
return (instance == NULL ||
instance->class_name() != NgxRewriteOptions::kClassName
? NULL
: static_cast<const NgxRewriteOptions*>(instance));
}
NgxRewriteOptions* NgxRewriteOptions::DynamicCast(RewriteOptions* instance) {
return (instance == NULL ||
instance->class_name() != NgxRewriteOptions::kClassName
? NULL
: static_cast<NgxRewriteOptions*>(instance));
}
const char* NgxRewriteOptions::class_name() const {
return NgxRewriteOptions::kClassName;
}
} // namespace net_instaweb
|
/*
* Copyright 2012 Google 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.
*/
// Author: [email protected] (Jeff Kaufman)
extern "C" {
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
}
#include "ngx_rewrite_options.h"
#include "ngx_pagespeed.h"
#include "net/instaweb/public/version.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/util/public/timer.h"
namespace net_instaweb {
const char NgxRewriteOptions::kClassName[] = "NgxRewriteOptions";
RewriteOptions::Properties* NgxRewriteOptions::ngx_properties_ = NULL;
NgxRewriteOptions::NgxRewriteOptions() {
Init();
}
void NgxRewriteOptions::Init() {
DCHECK(ngx_properties_ != NULL)
<< "Call NgxRewriteOptions::Initialize() before construction";
InitializeOptions(ngx_properties_);
}
void NgxRewriteOptions::AddProperties() {
// TODO(jefftk): All these caching-related properties could move to an
// OriginRewriteOptions.
add_ngx_option("", &NgxRewriteOptions::file_cache_path_, "nfcp",
RewriteOptions::kFileCachePath);
add_ngx_option(Timer::kHourMs,
&NgxRewriteOptions::file_cache_clean_interval_ms_,
"nfcci", RewriteOptions::kFileCacheCleanIntervalMs);
add_ngx_option(100 * 1024, // 100MB
&NgxRewriteOptions::file_cache_clean_size_kb_, "nfc",
RewriteOptions::kFileCacheCleanSizeKb);
add_ngx_option(500000,
&NgxRewriteOptions::file_cache_clean_inode_limit_, "nfcl",
RewriteOptions::kFileCacheCleanInodeLimit);
add_ngx_option(16384, //16MB
&NgxRewriteOptions::lru_cache_byte_limit_, "nlcb",
RewriteOptions::kLruCacheByteLimit);
add_ngx_option(1024, // 1MB
&NgxRewriteOptions::lru_cache_kb_per_process_, "nlcp",
RewriteOptions::kLruCacheKbPerProcess);
add_ngx_option("", &NgxRewriteOptions::memcached_servers_, "ams",
RewriteOptions::kMemcachedServers);
add_ngx_option(1, &NgxRewriteOptions::memcached_threads_, "amt",
RewriteOptions::kMemcachedThreads);
add_ngx_option(false, &NgxRewriteOptions::use_shared_mem_locking_, "ausml",
RewriteOptions::kUseSharedMemLocking);
add_ngx_option("", &NgxRewriteOptions::fetcher_proxy_, "afp",
RewriteOptions::kFetcherProxy);
MergeSubclassProperties(ngx_properties_);
NgxRewriteOptions config;
config.InitializeSignaturesAndDefaults();
}
void NgxRewriteOptions::InitializeSignaturesAndDefaults() {
// Calls to foo_.DoNotUseForSignatureComputation() would go here.
// Set default header value.
set_default_x_header_value(kModPagespeedVersion);
}
void NgxRewriteOptions::Initialize() {
if (Properties::Initialize(&ngx_properties_)) {
RewriteOptions::Initialize();
AddProperties();
}
}
void NgxRewriteOptions::Terminate() {
if (Properties::Terminate(&ngx_properties_)) {
RewriteOptions::Terminate();
}
}
bool NgxRewriteOptions::IsDirective(StringPiece config_directive,
StringPiece compare_directive) {
return StringCaseEqual(config_directive, compare_directive);
}
RewriteOptions::OptionSettingResult NgxRewriteOptions::ParseAndSetOptions0(
StringPiece directive, GoogleString* msg, MessageHandler* handler) {
if (IsDirective(directive, "on")) {
set_enabled(true);
} else if (IsDirective(directive, "off")) {
set_enabled(false);
} else {
return RewriteOptions::kOptionNameUnknown;
}
return RewriteOptions::kOptionOk;
}
RewriteOptions::OptionSettingResult NgxRewriteOptions::ParseAndSetOptions1(
StringPiece directive, StringPiece arg,
GoogleString* msg, MessageHandler* handler) {
// FileCachePath needs error checking.
if (IsDirective(directive, "FileCachePath")) {
if (!StringCaseStartsWith(arg, "/")) {
*msg = "must start with a slash";
return RewriteOptions::kOptionValueInvalid;
} else {
set_file_cache_path(arg.as_string());
}
}
RewriteOptions::OptionSettingResult result =
SetOptionFromName(directive, arg.as_string(), msg);
if (result != RewriteOptions::kOptionNameUnknown) {
return result;
}
if (IsDirective(directive, "Allow")) {
Allow(arg);
} else if (IsDirective(directive, "DangerPermitFetchFromUnknownHosts")) {
// TODO(jefftk): port this.
*msg = "not supported";
return RewriteOptions::kOptionValueInvalid;
} else if (IsDirective(directive, "DisableFilters")) {
bool ok = DisableFiltersByCommaSeparatedList(arg, handler);
if (!ok) {
*msg = "Failed to disable some filters.";
return RewriteOptions::kOptionValueInvalid;
}
} else if (IsDirective(directive, "Disallow")) {
Disallow(arg);
} else if (IsDirective(directive, "Domain")) {
domain_lawyer()->AddDomain(arg, handler);
} else if (IsDirective(directive, "EnableFilters")) {
bool ok = EnableFiltersByCommaSeparatedList(arg, handler);
if (!ok) {
*msg = "Failed to enable some filters.";
return RewriteOptions::kOptionValueInvalid;
}
} else if (IsDirective(directive, "FetchWithGzip")) {
// TODO(jefftk): port this.
*msg = "not supported";
return RewriteOptions::kOptionValueInvalid;
} else if (IsDirective(directive, "ForceCaching")) {
// TODO(jefftk): port this.
*msg = "not supported";
return RewriteOptions::kOptionValueInvalid;
} else if (IsDirective(directive, "ExperimentVariable")) {
int slot;
bool ok = StringToInt(arg.as_string().c_str(), &slot);
if (!ok || slot < 1 || slot > 5) {
*msg = "must be an integer between 1 and 5";
return RewriteOptions::kOptionValueInvalid;
}
set_furious_ga_slot(slot);
} else if (IsDirective(directive, "ExperimentSpec")) {
bool ok = AddFuriousSpec(arg, handler);
if (!ok) {
*msg = "not a valid experiment spec";
return RewriteOptions::kOptionValueInvalid;
}
} else if (IsDirective(directive, "RetainComment")) {
RetainComment(arg);
} else if (IsDirective(directive, "BlockingRewriteKey")) {
set_blocking_rewrite_key(arg);
} else {
return RewriteOptions::kOptionNameUnknown;
}
return RewriteOptions::kOptionOk;
}
RewriteOptions::OptionSettingResult NgxRewriteOptions::ParseAndSetOptions2(
StringPiece directive, StringPiece arg1, StringPiece arg2,
GoogleString* msg, MessageHandler* handler) {
if (IsDirective(directive, "MapRewriteDomain")) {
domain_lawyer()->AddRewriteDomainMapping(arg1, arg2, handler);
} else if (IsDirective(directive, "MapOriginDomain")) {
domain_lawyer()->AddOriginDomainMapping(arg1, arg2, handler);
} else if (IsDirective(directive, "MapProxyDomain")) {
domain_lawyer()->AddProxyDomainMapping(arg1, arg2, handler);
} else if (IsDirective(directive, "ShardDomain")) {
domain_lawyer()->AddShard(arg1, arg2, handler);
} else if (IsDirective(directive, "CustomFetchHeader")) {
AddCustomFetchHeader(arg1, arg2);
} else {
return RewriteOptions::kOptionNameUnknown;
}
return RewriteOptions::kOptionOk;
}
RewriteOptions::OptionSettingResult NgxRewriteOptions::ParseAndSetOptions3(
StringPiece directive, StringPiece arg1, StringPiece arg2, StringPiece arg3,
GoogleString* msg, MessageHandler* handler) {
if (IsDirective(directive, "UrlValuedAttribute")) {
semantic_type::Category category;
bool ok = semantic_type::ParseCategory(arg3, &category);
if (!ok) {
*msg = "Invalid resource category";
return RewriteOptions::kOptionValueInvalid;
}
AddUrlValuedAttribute(arg1, arg2, category);
} else if (IsDirective(directive, "Library")) {
int64 bytes;
bool ok = StringToInt64(arg1.as_string().c_str(), &bytes);
if (!ok || bytes < 0) {
*msg = "Size must be a positive 64-bit integer";
return RewriteOptions::kOptionValueInvalid;
}
ok = RegisterLibrary(bytes, arg2, arg3);
if (!ok) {
*msg = "Format is size md5 url; bad md5 or URL";
return RewriteOptions::kOptionValueInvalid;
}
} else {
return RewriteOptions::kOptionNameUnknown;
}
return RewriteOptions::kOptionOk;
}
// Very similar to apache/mod_instaweb::ParseDirective.
// TODO(jefftk): Move argument parsing to OriginRewriteOptions.
const char*
NgxRewriteOptions::ParseAndSetOptions(
StringPiece* args, int n_args, ngx_pool_t* pool, MessageHandler* handler) {
CHECK(n_args >= 1);
int i;
fprintf(stderr, "Setting option from (");
for (i = 0 ; i < n_args ; i++) {
fprintf(stderr, "%s\"%s\"",
i == 0 ? "" : ", ",
args[i].as_string().c_str());
}
fprintf(stderr, ")\n");
StringPiece directive = args[0];
// Remove initial "ModPagespeed" if there is one.
StringPiece mod_pagespeed("ModPagespeed");
if (StringCaseStartsWith(directive, mod_pagespeed)) {
directive.remove_prefix(mod_pagespeed.size());
}
GoogleString msg;
OptionSettingResult result;
if (n_args == 1) {
result = ParseAndSetOptions0(directive, &msg, handler);
} else if (n_args == 2) {
result = ParseAndSetOptions1(directive, args[1], &msg, handler);
} else if (n_args == 3) {
result = ParseAndSetOptions2(directive, args[1], args[2], &msg, handler);
} else if (n_args == 4) {
result = ParseAndSetOptions3(
directive, args[1], args[2], args[3], &msg, handler);
} else {
return "unknown option";
}
switch (result) {
case RewriteOptions::kOptionOk:
return NGX_CONF_OK;
case RewriteOptions::kOptionNameUnknown:
return "unknown option";
case RewriteOptions::kOptionValueInvalid: {
GoogleString full_directive = "\"";
for (int i = 0 ; i < n_args ; i++) {
StrAppend(&full_directive, i == 0 ? "" : " ", args[i]);
}
StrAppend(&full_directive, "\": ", msg);
char* s = ngx_psol::string_piece_to_pool_string(pool, full_directive);
if (s == NULL) {
return "failed to allocate memory";
}
return s;
}
}
CHECK(false);
return NULL;
}
NgxRewriteOptions* NgxRewriteOptions::Clone() const {
NgxRewriteOptions* options = new NgxRewriteOptions();
options->Merge(*this);
return options;
}
const NgxRewriteOptions* NgxRewriteOptions::DynamicCast(
const RewriteOptions* instance) {
return (instance == NULL ||
instance->class_name() != NgxRewriteOptions::kClassName
? NULL
: static_cast<const NgxRewriteOptions*>(instance));
}
NgxRewriteOptions* NgxRewriteOptions::DynamicCast(RewriteOptions* instance) {
return (instance == NULL ||
instance->class_name() != NgxRewriteOptions::kClassName
? NULL
: static_cast<NgxRewriteOptions*>(instance));
}
const char* NgxRewriteOptions::class_name() const {
return NgxRewriteOptions::kClassName;
}
} // namespace net_instaweb
|
support mapProxyDomain
|
options: support mapProxyDomain
|
C++
|
apache-2.0
|
pagespeed/ngx_pagespeed,digideskio/ngx_pagespeed,wanrui/ngx_pagespeed,pagespeed/ngx_pagespeed,wanrui/ngx_pagespeed,digideskio/ngx_pagespeed,0x0mar/ngx_pagespeed,0x0mar/ngx_pagespeed
|
c24915fa465a733bc3e304d527978b61065ad70c
|
Server/src/ServerPub.cpp
|
Server/src/ServerPub.cpp
|
#include "ServerPub.hpp"
#include "Protocol.hpp"
#include "DataBuffer.hpp"
namespace RhIO {
ServerPub::ServerPub(std::string endpoint) :
_context(1),
_socket(_context, ZMQ_PUB),
_isWritingTo1(true),
_queue1Bool(),
_queue1Int(),
_queue1Float(),
_queue1Str(),
_queue1Stream(),
_queue1Frame(),
_queue2Bool(),
_queue2Int(),
_queue2Float(),
_queue2Str(),
_queue2Stream(),
_queue2Frame(),
_mutexQueueBool(),
_mutexQueueInt(),
_mutexQueueFloat(),
_mutexQueueStr(),
_mutexQueueStream(),
_mutexQueueFrame()
{
if (endpoint == "") {
std::stringstream ss;
ss << "tcp://*:" << ServersPortBase;
endpoint = ss.str();
}
// Limiting the water mark to 10 to avoid stacking messages or frames and
// product a delay
//FIXME too low warter mark value breaks Leph openGL 3d viewer
int water_mark = 10;
zmq_setsockopt(_socket, ZMQ_SNDHWM, &water_mark, sizeof(int));
_socket.bind(endpoint.c_str());
}
void ServerPub::publishBool(const std::string& name,
bool val, int64_t timestamp)
{
std::lock_guard<std::mutex> lock(_mutexQueueBool);
if (_isWritingTo1) {
_queue1Bool.push_back({name, val, timestamp});
} else {
_queue2Bool.push_back({name, val, timestamp});
}
}
void ServerPub::publishInt(const std::string& name,
int64_t val, int64_t timestamp)
{
std::lock_guard<std::mutex> lock(_mutexQueueInt);
if (_isWritingTo1) {
_queue1Int.push_back({name, val, timestamp});
} else {
_queue2Int.push_back({name, val, timestamp});
}
}
void ServerPub::publishFloat(const std::string& name,
double val, int64_t timestamp)
{
std::lock_guard<std::mutex> lock(_mutexQueueFloat);
if (_isWritingTo1) {
_queue1Float.push_back({name, val, timestamp});
} else {
_queue2Float.push_back({name, val, timestamp});
}
}
void ServerPub::publishStr(const std::string& name,
const std::string& val, int64_t timestamp)
{
std::lock_guard<std::mutex> lock(_mutexQueueStr);
if (_isWritingTo1) {
_queue1Str.push_back({name, val, timestamp});
} else {
_queue2Str.push_back({name, val, timestamp});
}
}
void ServerPub::publishStream(const std::string& name,
const std::string& val, int64_t timestamp)
{
std::lock_guard<std::mutex> lock(_mutexQueueStream);
if (_isWritingTo1) {
_queue1Stream.push_back({name, val, timestamp});
} else {
_queue2Stream.push_back({name, val, timestamp});
}
}
void ServerPub::publishFrame(const std::string& name,
size_t width, size_t height,
unsigned char* data, size_t size,
int64_t timestamp)
{
//Directly allocate message data
std::lock_guard<std::mutex> lock(_mutexQueueFrame);
if (_isWritingTo1) {
_queue1Frame.clear();
_queue1Frame.push_back(zmq::message_t(
sizeof(MsgType)
+ sizeof(int64_t)
+ name.length()
+ 4*sizeof(int64_t)
+ size
));
DataBuffer pub(_queue1Frame.back().data(), _queue1Frame.back().size());
pub.writeType(MsgStreamFrame);
pub.writeStr(name);
pub.writeInt(timestamp);
pub.writeInt((uint64_t)width);
pub.writeInt((uint64_t)height);
pub.writeData(data, size);
} else {
_queue2Frame.clear();
_queue2Frame.push_back(zmq::message_t(
sizeof(MsgType)
+ sizeof(int64_t)
+ name.length()
+ 4*sizeof(int64_t)
+ size
));
DataBuffer pub(_queue2Frame.back().data(), _queue2Frame.back().size());
pub.writeType(MsgStreamFrame);
pub.writeStr(name);
pub.writeInt(timestamp);
pub.writeInt((uint64_t)width);
pub.writeInt((uint64_t)height);
pub.writeData(data, size);
}
}
void ServerPub::sendToClient()
{
//Swap double buffer
//Later network communication is lock-free
swapBuffer();
//Reference on full value buffer to be send
std::list<PubValBool>& queueBool =
(_isWritingTo1) ? _queue2Bool : _queue1Bool;
std::list<PubValInt>& queueInt =
(_isWritingTo1) ? _queue2Int : _queue1Int;
std::list<PubValFloat>& queueFloat =
(_isWritingTo1) ? _queue2Float : _queue1Float;
std::list<PubValStr>& queueStr =
(_isWritingTo1) ? _queue2Str : _queue1Str;
std::list<PubValStr>& queueStream =
(_isWritingTo1) ? _queue2Stream : _queue1Stream;
std::list<zmq::message_t>& queueFrame =
(_isWritingTo1) ? _queue2Frame : _queue1Frame;
//Sending values Bool
while (!queueBool.empty()) {
//Allocate message data
zmq::message_t packet(
sizeof(MsgType) + sizeof(int64_t)
+ queueBool.front().name.length()
+ sizeof(int64_t) + sizeof(uint8_t));
DataBuffer pub(packet.data(), packet.size());
pub.writeType(MsgStreamBool);
pub.writeStr(queueBool.front().name);
pub.writeInt(queueBool.front().timestamp);
pub.writeBool(queueBool.front().value);
//Send packet
_socket.send(packet);
//Pop value
queueBool.pop_front();
}
//Sending values Int
while (!queueInt.empty()) {
//Allocate message data
zmq::message_t packet(
sizeof(MsgType) + sizeof(int64_t)
+ queueInt.front().name.length()
+ sizeof(int64_t) + sizeof(int64_t));
DataBuffer pub(packet.data(), packet.size());
pub.writeType(MsgStreamInt);
pub.writeStr(queueInt.front().name);
pub.writeInt(queueInt.front().timestamp);
pub.writeInt(queueInt.front().value);
//Send packet
_socket.send(packet);
//Pop value
queueInt.pop_front();
}
//Sending values Float
while (!queueFloat.empty()) {
//Allocate message data
zmq::message_t packet(
sizeof(MsgType) + sizeof(int64_t)
+ queueFloat.front().name.length()
+ sizeof(int64_t) + sizeof(double));
DataBuffer pub(packet.data(), packet.size());
pub.writeType(MsgStreamFloat);
pub.writeStr(queueFloat.front().name);
pub.writeInt(queueFloat.front().timestamp);
pub.writeFloat(queueFloat.front().value);
//Send packet
_socket.send(packet);
//Pop value
queueFloat.pop_front();
}
//Sending values Str
while (!queueStr.empty()) {
//Allocate message data
zmq::message_t packet(
sizeof(MsgType) + sizeof(int64_t)
+ queueStr.front().name.length()
+ sizeof(int64_t) + sizeof(int64_t)
+ queueStr.front().value.length());
DataBuffer pub(packet.data(), packet.size());
pub.writeType(MsgStreamStr);
pub.writeStr(queueStr.front().name);
pub.writeInt(queueStr.front().timestamp);
pub.writeStr(queueStr.front().value);
//Send packet
_socket.send(packet);
//Pop value
queueStr.pop_front();
}
//Sending values Stream
while (!queueStream.empty()) {
//Allocate message data
zmq::message_t packet(
sizeof(MsgType) + sizeof(int64_t)
+ queueStream.front().name.length()
+ sizeof(int64_t) + sizeof(int64_t)
+ queueStream.front().value.length());
DataBuffer pub(packet.data(), packet.size());
pub.writeType(MsgStreamStream);
pub.writeStr(queueStream.front().name);
pub.writeInt(queueStream.front().timestamp);
pub.writeStr(queueStream.front().value);
//Send packet
_socket.send(packet);
//Pop value
queueStream.pop_front();
}
//Sending values Frame
while (!queueFrame.empty()) {
//Send packet
_socket.send(queueFrame.front());
//Pop value
queueFrame.pop_front();
}
}
void ServerPub::swapBuffer()
{
//Lock all publisher buffer for all types
std::lock_guard<std::mutex> lockBool(_mutexQueueBool);
std::lock_guard<std::mutex> lockInt(_mutexQueueInt);
std::lock_guard<std::mutex> lockFloat(_mutexQueueFloat);
std::lock_guard<std::mutex> lockStr(_mutexQueueStr);
std::lock_guard<std::mutex> lockStream(_mutexQueueStream);
std::lock_guard<std::mutex> lockFrame(_mutexQueueFrame);
//Swap buffer
_isWritingTo1 = !_isWritingTo1;
}
}
|
#include "ServerPub.hpp"
#include "Protocol.hpp"
#include "DataBuffer.hpp"
#ifdef VISION_COMPONENT
#define WATERMARK 10
#else
#define WATERMARK 0
#endif
namespace RhIO {
ServerPub::ServerPub(std::string endpoint) :
_context(1),
_socket(_context, ZMQ_PUB),
_isWritingTo1(true),
_queue1Bool(),
_queue1Int(),
_queue1Float(),
_queue1Str(),
_queue1Stream(),
_queue1Frame(),
_queue2Bool(),
_queue2Int(),
_queue2Float(),
_queue2Str(),
_queue2Stream(),
_queue2Frame(),
_mutexQueueBool(),
_mutexQueueInt(),
_mutexQueueFloat(),
_mutexQueueStr(),
_mutexQueueStream(),
_mutexQueueFrame()
{
if (endpoint == "") {
std::stringstream ss;
ss << "tcp://*:" << ServersPortBase;
endpoint = ss.str();
}
// Limiting the water mark to 10 to avoid stacking messages or frames and
// product a delay
//FIXME too low warter mark value breaks Leph openGL 3d viewer
int water_mark = WATERMARK;
zmq_setsockopt(_socket, ZMQ_SNDHWM, &water_mark, sizeof(int));
_socket.bind(endpoint.c_str());
}
void ServerPub::publishBool(const std::string& name,
bool val, int64_t timestamp)
{
std::lock_guard<std::mutex> lock(_mutexQueueBool);
if (_isWritingTo1) {
_queue1Bool.push_back({name, val, timestamp});
} else {
_queue2Bool.push_back({name, val, timestamp});
}
}
void ServerPub::publishInt(const std::string& name,
int64_t val, int64_t timestamp)
{
std::lock_guard<std::mutex> lock(_mutexQueueInt);
if (_isWritingTo1) {
_queue1Int.push_back({name, val, timestamp});
} else {
_queue2Int.push_back({name, val, timestamp});
}
}
void ServerPub::publishFloat(const std::string& name,
double val, int64_t timestamp)
{
std::lock_guard<std::mutex> lock(_mutexQueueFloat);
if (_isWritingTo1) {
_queue1Float.push_back({name, val, timestamp});
} else {
_queue2Float.push_back({name, val, timestamp});
}
}
void ServerPub::publishStr(const std::string& name,
const std::string& val, int64_t timestamp)
{
std::lock_guard<std::mutex> lock(_mutexQueueStr);
if (_isWritingTo1) {
_queue1Str.push_back({name, val, timestamp});
} else {
_queue2Str.push_back({name, val, timestamp});
}
}
void ServerPub::publishStream(const std::string& name,
const std::string& val, int64_t timestamp)
{
std::lock_guard<std::mutex> lock(_mutexQueueStream);
if (_isWritingTo1) {
_queue1Stream.push_back({name, val, timestamp});
} else {
_queue2Stream.push_back({name, val, timestamp});
}
}
void ServerPub::publishFrame(const std::string& name,
size_t width, size_t height,
unsigned char* data, size_t size,
int64_t timestamp)
{
//Directly allocate message data
std::lock_guard<std::mutex> lock(_mutexQueueFrame);
if (_isWritingTo1) {
_queue1Frame.clear();
_queue1Frame.push_back(zmq::message_t(
sizeof(MsgType)
+ sizeof(int64_t)
+ name.length()
+ 4*sizeof(int64_t)
+ size
));
DataBuffer pub(_queue1Frame.back().data(), _queue1Frame.back().size());
pub.writeType(MsgStreamFrame);
pub.writeStr(name);
pub.writeInt(timestamp);
pub.writeInt((uint64_t)width);
pub.writeInt((uint64_t)height);
pub.writeData(data, size);
} else {
_queue2Frame.clear();
_queue2Frame.push_back(zmq::message_t(
sizeof(MsgType)
+ sizeof(int64_t)
+ name.length()
+ 4*sizeof(int64_t)
+ size
));
DataBuffer pub(_queue2Frame.back().data(), _queue2Frame.back().size());
pub.writeType(MsgStreamFrame);
pub.writeStr(name);
pub.writeInt(timestamp);
pub.writeInt((uint64_t)width);
pub.writeInt((uint64_t)height);
pub.writeData(data, size);
}
}
void ServerPub::sendToClient()
{
//Swap double buffer
//Later network communication is lock-free
swapBuffer();
//Reference on full value buffer to be send
std::list<PubValBool>& queueBool =
(_isWritingTo1) ? _queue2Bool : _queue1Bool;
std::list<PubValInt>& queueInt =
(_isWritingTo1) ? _queue2Int : _queue1Int;
std::list<PubValFloat>& queueFloat =
(_isWritingTo1) ? _queue2Float : _queue1Float;
std::list<PubValStr>& queueStr =
(_isWritingTo1) ? _queue2Str : _queue1Str;
std::list<PubValStr>& queueStream =
(_isWritingTo1) ? _queue2Stream : _queue1Stream;
std::list<zmq::message_t>& queueFrame =
(_isWritingTo1) ? _queue2Frame : _queue1Frame;
//Sending values Bool
while (!queueBool.empty()) {
//Allocate message data
zmq::message_t packet(
sizeof(MsgType) + sizeof(int64_t)
+ queueBool.front().name.length()
+ sizeof(int64_t) + sizeof(uint8_t));
DataBuffer pub(packet.data(), packet.size());
pub.writeType(MsgStreamBool);
pub.writeStr(queueBool.front().name);
pub.writeInt(queueBool.front().timestamp);
pub.writeBool(queueBool.front().value);
//Send packet
_socket.send(packet);
//Pop value
queueBool.pop_front();
}
//Sending values Int
while (!queueInt.empty()) {
//Allocate message data
zmq::message_t packet(
sizeof(MsgType) + sizeof(int64_t)
+ queueInt.front().name.length()
+ sizeof(int64_t) + sizeof(int64_t));
DataBuffer pub(packet.data(), packet.size());
pub.writeType(MsgStreamInt);
pub.writeStr(queueInt.front().name);
pub.writeInt(queueInt.front().timestamp);
pub.writeInt(queueInt.front().value);
//Send packet
_socket.send(packet);
//Pop value
queueInt.pop_front();
}
//Sending values Float
while (!queueFloat.empty()) {
//Allocate message data
zmq::message_t packet(
sizeof(MsgType) + sizeof(int64_t)
+ queueFloat.front().name.length()
+ sizeof(int64_t) + sizeof(double));
DataBuffer pub(packet.data(), packet.size());
pub.writeType(MsgStreamFloat);
pub.writeStr(queueFloat.front().name);
pub.writeInt(queueFloat.front().timestamp);
pub.writeFloat(queueFloat.front().value);
//Send packet
_socket.send(packet);
//Pop value
queueFloat.pop_front();
}
//Sending values Str
while (!queueStr.empty()) {
//Allocate message data
zmq::message_t packet(
sizeof(MsgType) + sizeof(int64_t)
+ queueStr.front().name.length()
+ sizeof(int64_t) + sizeof(int64_t)
+ queueStr.front().value.length());
DataBuffer pub(packet.data(), packet.size());
pub.writeType(MsgStreamStr);
pub.writeStr(queueStr.front().name);
pub.writeInt(queueStr.front().timestamp);
pub.writeStr(queueStr.front().value);
//Send packet
_socket.send(packet);
//Pop value
queueStr.pop_front();
}
//Sending values Stream
while (!queueStream.empty()) {
//Allocate message data
zmq::message_t packet(
sizeof(MsgType) + sizeof(int64_t)
+ queueStream.front().name.length()
+ sizeof(int64_t) + sizeof(int64_t)
+ queueStream.front().value.length());
DataBuffer pub(packet.data(), packet.size());
pub.writeType(MsgStreamStream);
pub.writeStr(queueStream.front().name);
pub.writeInt(queueStream.front().timestamp);
pub.writeStr(queueStream.front().value);
//Send packet
_socket.send(packet);
//Pop value
queueStream.pop_front();
}
//Sending values Frame
while (!queueFrame.empty()) {
//Send packet
_socket.send(queueFrame.front());
//Pop value
queueFrame.pop_front();
}
}
void ServerPub::swapBuffer()
{
//Lock all publisher buffer for all types
std::lock_guard<std::mutex> lockBool(_mutexQueueBool);
std::lock_guard<std::mutex> lockInt(_mutexQueueInt);
std::lock_guard<std::mutex> lockFloat(_mutexQueueFloat);
std::lock_guard<std::mutex> lockStr(_mutexQueueStr);
std::lock_guard<std::mutex> lockStream(_mutexQueueStream);
std::lock_guard<std::mutex> lockFrame(_mutexQueueFrame);
//Swap buffer
_isWritingTo1 = !_isWritingTo1;
}
}
|
disable watermark if novision
|
disable watermark if novision
|
C++
|
mit
|
Rhoban/RhIO
|
a6d4af14696316009e63a8108d16d1fcb5646cf3
|
json.cpp
|
json.cpp
|
/** Copyright (c) 2013, Sean Kasun */
#include <QFile>
#include <QtCore>
#include "./json.h"
enum Token {
TokenNULL,
TokenTRUE,
TokenFALSE,
TokenString,
TokenNumber,
TokenObject,
TokenArray,
TokenObjectClose,
TokenArrayClose,
TokenKeySeparator,
TokenValueSeparator
};
class JSONHelper {
public:
explicit JSONHelper(QString data) : data(data) {
pos = 0;
len = data.length();
}
~JSONHelper() {}
Token nextToken() {
while (pos < len && data.at(pos).isSpace())
pos++;
if (pos == len)
throw JSONParseException("Unexpected EOF", location());
QChar c = data.at(pos++);
if (c.isLetter()) { // keyword like NULL,TRUE or FALSE
int start = pos - 1;
while (pos < len && data.at(pos).isLetter())
pos++;
QStringRef ref = data.midRef(start, pos - start);
if (ref.compare(QString("null"), Qt::CaseInsensitive) == 0)
return TokenNULL;
if (ref.compare(QString("true"), Qt::CaseInsensitive) == 0)
return TokenTRUE;
if (ref.compare(QString("false"), Qt::CaseInsensitive) == 0)
return TokenFALSE;
throw JSONParseException("Unquoted string", location());
}
if (c.isDigit() || c == '-') { // double or hex
pos--;
return TokenNumber;
}
switch (c.unicode()) {
case '"': return TokenString;
case '{': return TokenObject;
case '}': return TokenObjectClose;
case '[': return TokenArray;
case ']': return TokenArrayClose;
case ':': return TokenKeySeparator;
case ',': return TokenValueSeparator;
default:
throw JSONParseException(QString("Unexpected character: %1").arg(c),
location());
}
}
QString readString() {
QString r;
while (pos < len && data.at(pos) != '"') {
if (data.at(pos) == '\\') {
pos++;
if (pos == len)
throw JSONParseException("Unexpected EOF", location());
switch (data.at(pos++).unicode()) {
case '"': r += '"'; break;
case '\\': r += '\\'; break;
case '/': r += '/'; break;
case 'b': r += '\b'; break;
case 'f': r += '\f'; break;
case 'n': r += '\n'; break;
case 'r': r += '\r'; break;
case 't': r += '\t'; break;
case 'u': { // hex
int num = 0;
for (int i = 0; i < 4; i++) {
if (pos == len)
throw JSONParseException("Unexpected EOF", location());
num <<= 4;
char c = data.at(pos++).unicode();
if (c >= '0' && c <= '9')
num |= c - '0';
else if (c >= 'a' && c <= 'f')
num |= c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
num |= c - 'A' + 10;
else
throw JSONParseException("Invalid hex code", location());
}
r += QChar(num);
}
break;
default:
throw JSONParseException("Unknown escape sequence", location());
}
} else {
r += data.at(pos++);
}
}
pos++;
return r;
}
double readDouble() {
double sign = 1.0;
if (data.at(pos) == '-') {
sign = -1.0;
pos++;
} else if (data.at(pos) == '+') {
pos++;
}
double value = 0.0;
while (pos < len && data.at(pos).isDigit()) {
value *= 10.0;
value += data.at(pos++).unicode() - '0';
}
if (pos == len)
throw JSONParseException("Unexpected EOF", location());
if (data.at(pos) == '.') {
double pow10 = 10.0;
pos++;
while (pos < len && data.at(pos).isDigit()) {
value += (data.at(pos++).unicode() - '0') / pow10;
pow10 *= 10.0;
}
}
if (pos == len)
throw JSONParseException("Unexpected EOF", location());
double scale = 1.0;
bool frac = false;
if (data.at(pos) == 'e' || data.at(pos) == 'E') {
pos++;
if (pos == len)
throw JSONParseException("Unexpected EOF", location());
if (data.at(pos) == '-') {
frac = true;
pos++;
} else if (data.at(pos) == '+') {
pos++;
}
unsigned int expon = 0;
while (pos < len && data.at(pos).isDigit()) {
expon *= 10.0;
expon += data.at(pos++).unicode() - '0';
}
if (expon > 308)
expon = 308;
while (expon >= 50) {
scale *= 1E50;
expon -= 50;
}
while (expon >= 8) {
scale *= 1E8;
expon -= 8;
}
while (expon > 0) {
scale *= 10.0;
expon -= 1;
}
}
return sign * (frac ? (value / scale) : (value * scale));
}
QString location() {
int line = 1;
int col = 0;
int cpos = pos;
bool doneCol = false;
while (cpos >= 0) {
if (data.at(cpos) == '\n') {
doneCol = true;
line++;
}
if (!doneCol) col++;
cpos--;
}
return QString("Line: %1, Offset: %2").arg(line).arg(col);
}
private:
int pos, len;
QString data;
};
JSONData *JSON::parse(const QString data) {
JSONHelper reader(data);
Token type = reader.nextToken();
switch (type) {
case TokenObject: // hash
return new JSONObject(reader);
case TokenArray: // array
return new JSONArray(reader);
default:
throw JSONParseException("Doesn't start with object or array",
reader.location());
break;
}
return NULL;
}
static JSONData Null;
JSONData::JSONData() {
}
JSONData::~JSONData() {
}
bool JSONData::has(const QString) {
return false;
}
JSONData *JSONData::at(const QString) {
return &Null;
}
JSONData *JSONData::at(int /* idx */) {
return &Null;
}
int JSONData::length() {
return 0;
}
QString JSONData::asString() {
return "";
}
double JSONData::asNumber() {
return 0.0;
}
bool JSONData::asBool() {
return false;
}
JSONBool::JSONBool(bool val) {
data = val;
}
bool JSONBool::asBool() {
return data;
}
JSONString::JSONString(QString val) {
data = val;
}
QString JSONString::asString() {
return data;
}
JSONNumber::JSONNumber(double val) {
data = val;
}
double JSONNumber::asNumber() {
return data;
}
JSONObject::JSONObject(JSONHelper &reader) {
while (true) {
Token type = reader.nextToken();
if (type == TokenObjectClose)
break;
if (type != TokenString)
throw JSONParseException("Expected quoted string", reader.location());
QString key = reader.readString();
if (key.length() == 0)
throw JSONParseException("Empty object key", reader.location());
if (reader.nextToken() != TokenKeySeparator)
throw JSONParseException("Expected ':'", reader.location());
JSONData *value;
switch (reader.nextToken()) {
case TokenNULL: value = NULL; break;
case TokenTRUE: value = new JSONBool(true); break;
case TokenFALSE: value = new JSONBool(false); break;
case TokenString: value = new JSONString(reader.readString()); break;
case TokenNumber: value = new JSONNumber(reader.readDouble()); break;
case TokenObject: value = new JSONObject(reader); break;
case TokenArray: value = new JSONArray(reader); break;
default: throw JSONParseException("Expected value", reader.location());
}
children[key] = value;
type = reader.nextToken(); // comma or end
if (type == TokenObjectClose)
break;
if (type != TokenValueSeparator)
throw JSONParseException("Expected ',' or '}'", reader.location());
}
}
JSONObject::~JSONObject() {
for (auto i = children.constBegin(); i != children.constEnd(); i++)
delete i.value();
}
bool JSONObject::has(QString key) {
return children.contains(key);
}
JSONData *JSONObject::at(QString key) {
if (children.contains(key))
return children[key];
return &Null;
}
JSONArray::JSONArray(JSONHelper &reader) {
while (true) {
Token type = reader.nextToken();
if (type == TokenArrayClose)
break;
JSONData *value;
switch (type) {
case TokenNULL: value = NULL; break;
case TokenTRUE: value = new JSONBool(true); break;
case TokenFALSE: value = new JSONBool(false); break;
case TokenString: value = new JSONString(reader.readString()); break;
case TokenNumber: value = new JSONNumber(reader.readDouble()); break;
case TokenObject: value = new JSONObject(reader); break;
case TokenArray: value = new JSONArray(reader); break;
default: throw JSONParseException("Expected Value", reader.location());
}
data.append(value);
type = reader.nextToken(); // comma or end
if (type == TokenArrayClose)
break;
if (type != TokenValueSeparator)
throw JSONParseException("Expected ',' or ']'", reader.location());
}
}
JSONArray::~JSONArray() {
for (auto i = data.constBegin(); i != data.constEnd(); i++)
delete *i;
}
int JSONArray::length() {
return data.length();
}
JSONData *JSONArray::at(int index) {
if (index < data.length())
return data[index];
return &Null;
}
|
/** Copyright (c) 2013, Sean Kasun */
#include <QFile>
#include <QtCore>
#include "./json.h"
enum Token {
TokenNULL,
TokenTRUE,
TokenFALSE,
TokenString,
TokenNumber,
TokenObject,
TokenArray,
TokenObjectClose,
TokenArrayClose,
TokenKeySeparator,
TokenValueSeparator
};
class JSONHelper {
public:
explicit JSONHelper(QString data) : data(data) {
pos = 0;
len = data.length();
}
~JSONHelper() {}
Token nextToken() {
while (pos < len && data.at(pos).isSpace())
pos++;
if (pos == len)
throw JSONParseException("Unexpected EOF", location());
QChar c = data.at(pos++);
if (c.isLetter()) { // keyword like NULL,TRUE or FALSE
int start = pos - 1;
while (pos < len && data.at(pos).isLetter())
pos++;
QStringRef ref = data.midRef(start, pos - start);
if (ref.compare(QString("null"), Qt::CaseInsensitive) == 0)
return TokenNULL;
if (ref.compare(QString("true"), Qt::CaseInsensitive) == 0)
return TokenTRUE;
if (ref.compare(QString("false"), Qt::CaseInsensitive) == 0)
return TokenFALSE;
throw JSONParseException("Unquoted string", location());
}
if (c.isDigit() || c == '-') { // double or hex
pos--;
return TokenNumber;
}
switch (c.unicode()) {
case '"': return TokenString;
case '{': return TokenObject;
case '}': return TokenObjectClose;
case '[': return TokenArray;
case ']': return TokenArrayClose;
case ':': return TokenKeySeparator;
case ',': return TokenValueSeparator;
default:
throw JSONParseException(QString("Unexpected character: %1").arg(c),
location());
}
}
QString readString() {
QString r;
while (pos < len && data.at(pos) != '"') {
if (data.at(pos) == '\\') {
pos++;
if (pos == len)
throw JSONParseException("Unexpected EOF", location());
switch (data.at(pos++).unicode()) {
case '"': r += '"'; break;
case '\\': r += '\\'; break;
case '/': r += '/'; break;
case 'b': r += '\b'; break;
case 'f': r += '\f'; break;
case 'n': r += '\n'; break;
case 'r': r += '\r'; break;
case 't': r += '\t'; break;
case 'u': { // hex
int num = 0;
for (int i = 0; i < 4; i++) {
if (pos == len)
throw JSONParseException("Unexpected EOF", location());
num <<= 4;
char c = data.at(pos++).unicode();
if (c >= '0' && c <= '9')
num |= c - '0';
else if (c >= 'a' && c <= 'f')
num |= c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
num |= c - 'A' + 10;
else
throw JSONParseException("Invalid hex code", location());
}
r += QChar(num);
}
break;
default:
throw JSONParseException("Unknown escape sequence", location());
}
} else {
r += data.at(pos++);
}
}
pos++;
return r;
}
double readDouble() {
double sign = 1.0;
if (data.at(pos) == '-') {
sign = -1.0;
pos++;
} else if (data.at(pos) == '+') {
pos++;
}
double value = 0.0;
while (pos < len && data.at(pos).isDigit()) {
value *= 10.0;
value += data.at(pos++).unicode() - '0';
}
if (pos == len)
throw JSONParseException("Unexpected EOF", location());
if (data.at(pos) == '.') {
double pow10 = 10.0;
pos++;
while (pos < len && data.at(pos).isDigit()) {
value += (data.at(pos++).unicode() - '0') / pow10;
pow10 *= 10.0;
}
}
if (pos == len)
throw JSONParseException("Unexpected EOF", location());
double scale = 1.0;
bool frac = false;
if (data.at(pos) == 'e' || data.at(pos) == 'E') {
pos++;
if (pos == len)
throw JSONParseException("Unexpected EOF", location());
if (data.at(pos) == '-') {
frac = true;
pos++;
} else if (data.at(pos) == '+') {
pos++;
}
unsigned int expon = 0;
while (pos < len && data.at(pos).isDigit()) {
expon *= 10.0;
expon += data.at(pos++).unicode() - '0';
}
if (expon > 308)
expon = 308;
while (expon >= 50) {
scale *= 1E50;
expon -= 50;
}
while (expon >= 8) {
scale *= 1E8;
expon -= 8;
}
while (expon > 0) {
scale *= 10.0;
expon -= 1;
}
}
return sign * (frac ? (value / scale) : (value * scale));
}
QString location() {
int line = 1;
int col = 0;
if (len > 0)
{
int cpos = pos;
bool doneCol = false;
while (cpos >= 0) {
if (data.at(cpos) == '\n') {
doneCol = true;
line++;
}
if (!doneCol) col++;
cpos--;
}
}
return QString("Line: %1, Offset: %2").arg(line).arg(col);
}
private:
int pos, len;
QString data;
};
JSONData *JSON::parse(const QString data) {
JSONHelper reader(data);
Token type = reader.nextToken();
switch (type) {
case TokenObject: // hash
return new JSONObject(reader);
case TokenArray: // array
return new JSONArray(reader);
default:
throw JSONParseException("Doesn't start with object or array",
reader.location());
break;
}
return NULL;
}
static JSONData Null;
JSONData::JSONData() {
}
JSONData::~JSONData() {
}
bool JSONData::has(const QString) {
return false;
}
JSONData *JSONData::at(const QString) {
return &Null;
}
JSONData *JSONData::at(int /* idx */) {
return &Null;
}
int JSONData::length() {
return 0;
}
QString JSONData::asString() {
return "";
}
double JSONData::asNumber() {
return 0.0;
}
bool JSONData::asBool() {
return false;
}
JSONBool::JSONBool(bool val) {
data = val;
}
bool JSONBool::asBool() {
return data;
}
JSONString::JSONString(QString val) {
data = val;
}
QString JSONString::asString() {
return data;
}
JSONNumber::JSONNumber(double val) {
data = val;
}
double JSONNumber::asNumber() {
return data;
}
JSONObject::JSONObject(JSONHelper &reader) {
while (true) {
Token type = reader.nextToken();
if (type == TokenObjectClose)
break;
if (type != TokenString)
throw JSONParseException("Expected quoted string", reader.location());
QString key = reader.readString();
if (key.length() == 0)
throw JSONParseException("Empty object key", reader.location());
if (reader.nextToken() != TokenKeySeparator)
throw JSONParseException("Expected ':'", reader.location());
JSONData *value;
switch (reader.nextToken()) {
case TokenNULL: value = NULL; break;
case TokenTRUE: value = new JSONBool(true); break;
case TokenFALSE: value = new JSONBool(false); break;
case TokenString: value = new JSONString(reader.readString()); break;
case TokenNumber: value = new JSONNumber(reader.readDouble()); break;
case TokenObject: value = new JSONObject(reader); break;
case TokenArray: value = new JSONArray(reader); break;
default: throw JSONParseException("Expected value", reader.location());
}
children[key] = value;
type = reader.nextToken(); // comma or end
if (type == TokenObjectClose)
break;
if (type != TokenValueSeparator)
throw JSONParseException("Expected ',' or '}'", reader.location());
}
}
JSONObject::~JSONObject() {
for (auto i = children.constBegin(); i != children.constEnd(); i++)
delete i.value();
}
bool JSONObject::has(QString key) {
return children.contains(key);
}
JSONData *JSONObject::at(QString key) {
if (children.contains(key))
return children[key];
return &Null;
}
JSONArray::JSONArray(JSONHelper &reader) {
while (true) {
Token type = reader.nextToken();
if (type == TokenArrayClose)
break;
JSONData *value;
switch (type) {
case TokenNULL: value = NULL; break;
case TokenTRUE: value = new JSONBool(true); break;
case TokenFALSE: value = new JSONBool(false); break;
case TokenString: value = new JSONString(reader.readString()); break;
case TokenNumber: value = new JSONNumber(reader.readDouble()); break;
case TokenObject: value = new JSONObject(reader); break;
case TokenArray: value = new JSONArray(reader); break;
default: throw JSONParseException("Expected Value", reader.location());
}
data.append(value);
type = reader.nextToken(); // comma or end
if (type == TokenArrayClose)
break;
if (type != TokenValueSeparator)
throw JSONParseException("Expected ',' or ']'", reader.location());
}
}
JSONArray::~JSONArray() {
for (auto i = data.constBegin(); i != data.constEnd(); i++)
delete *i;
}
int JSONArray::length() {
return data.length();
}
JSONData *JSONArray::at(int index) {
if (index < data.length())
return data[index];
return &Null;
}
|
fix access out of boundary when json file is completely empty
|
fix access out of boundary when json file is completely empty
|
C++
|
bsd-2-clause
|
mrkite/minutor,EtlamGit/minutor,EtlamGit/minutor,EtlamGit/minutor,EtlamGit/minutor,mrkite/minutor,EtlamGit/minutor,mrkite/minutor,mrkite/minutor,mrkite/minutor
|
4a79f77b2ed88dc8f0a58a237413552a0f7306f7
|
konbu.hh
|
konbu.hh
|
/* You can use one of the both BSD 3-Clause License or GNU Lesser General Public License 3.0 for this source. */
/* BSD 3-Clause License:
* Copyright (c) 2013 - 2021, kazunobu watatsu.
* 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 or other materials provided with the distribution.
* Neither 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.
*/
#if !defined(_LINEAR_OPT_)
using std::cerr;
using std::flush;
template <typename T> SimpleVector<T> inner(const SimpleMatrix<T>& A, const SimpleVector<T>& bl, const SimpleVector<T>& bu) {
#if defined(_FLOAT_BITS_)
static const auto epsilon(T(1) >> int64_t(mybits - 1));
#else
static const auto epsilon(std::numeric_limits<T>::epsilon());
#endif
assert(A.rows() == bl.size() && A.rows() == bu.size() &&
0 < A.cols() && 0 < A.rows());
// cout << A << endl << b << endl << c.transpose() << endl;
cerr << " (" << A.rows() << ", " << A.cols() << ")";
// bu - bb == A, bl - bb == - A <=> bu - bl == 2 A
const auto bb(bu - (bu - bl) / T(2));
const auto upper(bu - bb);
SimpleMatrix<T> AA(A.rows() * 2 - 1, A.cols() + 1);
SimpleVector<T> one(AA.rows());
std::vector<std::pair<T, int> > equal;
equal.reserve(A.rows());
for(int i = 0; i < A.rows(); i ++) {
for(int j = 0; j < A.cols(); j ++)
AA(i, j) = A(i, j);
AA(i, A.cols()) = - bb[i];
if(upper[i] == T(0)) {
const auto n2(AA.row(i).dot(AA.row(i)));
if(n2 != T(0)) {
equal.emplace_back(std::make_pair(T(0), i));
AA.row(i) /= sqrt(n2);
}
} else {
AA.row(i) /= upper[i];
AA(i, A.cols()) -= - T(1);
}
one[i] = T(1);
assert(isfinite(AA.row(i).dot(AA.row(i))));
if(A.rows() - 1 <= i) break;
AA.row(i + A.rows()) = - AA.row(i);
one[i + A.rows()] = T(1);
}
SimpleMatrix<T> Pt(AA.cols(), AA.rows());
for(int i = 0; i < Pt.rows(); i ++)
for(int j = 0; j < Pt.cols(); j ++)
Pt(i, j) = T(0);
int ii(0);
for(int i = 0; i < AA.cols() && ii < AA.cols(); i ++) {
const auto Atrowi(AA.col(i));
const auto work(Atrowi - Pt.projectionPt(Atrowi));
const auto n2(work.dot(work));
if(n2 <= epsilon) continue;
Pt.row(ii ++) = work / sqrt(n2);
}
int j(0);
for( ; ii < AA.cols(); ii ++) {
for( ; j < AA.rows(); j ++) {
SimpleVector<T> ek(AA.rows());
for(int k = 0; k < AA.rows(); k ++)
ek[k] = j == k ? T(1) : T(0);
ek -= Pt.projectionPt(ek);
const auto n2(ek.dot(ek));
if(n2 <= epsilon) continue;
Pt.row(ii) = ek / sqrt(n2);
break;
}
}
assert(Pt.rows() <= ii);
cerr << "Q" << flush;
const auto R(Pt * AA);
cerr << "R" << flush;
const auto on(Pt.projectionPt(- one));
std::vector<std::pair<T, int> > fidx;
fidx.reserve(on.size());
for(int i = 0; i < on.size(); i ++)
if(T(0) < on[i])
fidx.emplace_back(std::make_pair(on[i], i));
std::sort(fidx.begin(), fidx.end());
{
std::vector<std::pair<T, int> > work;
work.reserve(equal.size() + fidx.size());
for(int i = 0; i < equal.size(); i ++)
work.emplace_back(std::move(equal[i]));
for(int i = 0; i < fidx.size(); i ++)
work.emplace_back(std::move(fidx[i]));
fidx = std::move(work);
// N.B. there's a little possibility on {0, 1} problem.
}
// worst case O(mn^2) over all in this function,
// we can make this function better case it's O(n^3) but not now.
for(int n_fixed = 0, idx = 0; n_fixed < Pt.rows() - 1 && idx < fidx.size(); n_fixed ++, idx ++) {
const auto& iidx(fidx[idx].second);
const auto orth(Pt.col(iidx));
const auto norm2orth(orth.dot(orth));
// XXX error:
if(norm2orth <= epsilon) {
n_fixed --;
continue;
}
#if defined(_OPENMP)
#pragma omp parallel for schedule(static, 1)
#endif
for(int j = 0; j < Pt.cols(); j ++)
Pt.setCol(j, Pt.col(j) - orth * (Pt.col(j).dot(orth) + T(n_fixed ? 0 : 1)) / norm2orth);
}
cerr << "G" << flush;
#if defined(_WITHOUT_EIGEN_)
auto rvec(- R.solve(Pt * one));
#else
auto rvec(- R.inverse() * (Pt * one));
#endif
cerr << "I" << flush;
SimpleVector<T> rrvec(rvec.size() - 1);
// | [A, - bb == - upper] [x t] | <= epsilon 1.
for(int i = 0; i < rrvec.size(); i ++)
rrvec[i] = rvec[i] / rvec[rvec.size() - 1];
return rrvec;
}
#define _LINEAR_OPT_
#endif
|
/* You can use one of the both BSD 3-Clause License or GNU Lesser General Public License 3.0 for this source. */
/* BSD 3-Clause License:
* Copyright (c) 2013 - 2021, kazunobu watatsu.
* 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 or other materials provided with the distribution.
* Neither 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.
*/
#if !defined(_LINEAR_OPT_)
using std::cerr;
using std::flush;
template <typename T> SimpleVector<T> inner(const SimpleMatrix<T>& A, const SimpleVector<T>& bl, const SimpleVector<T>& bu) {
#if defined(_FLOAT_BITS_)
static const auto epsilon(T(1) >> int64_t(mybits - 1));
#else
static const auto epsilon(std::numeric_limits<T>::epsilon());
#endif
assert(A.rows() == bl.size() && A.rows() == bu.size() &&
0 < A.cols() && 0 < A.rows());
// cout << A << endl << b << endl << c.transpose() << endl;
cerr << " (" << A.rows() << ", " << A.cols() << ")";
// bu - bb == A, bl - bb == - A <=> bu - bl == 2 A
const auto bb(bu - (bu - bl) / T(2));
const auto upper(bu - bb);
SimpleMatrix<T> AA(A.rows() * 2 - 1, A.cols() + 1);
SimpleVector<T> one(AA.rows());
std::vector<std::pair<T, int> > equal;
equal.reserve(A.rows());
for(int i = 0; i < A.rows(); i ++) {
for(int j = 0; j < A.cols(); j ++)
AA(i, j) = A(i, j);
AA(i, A.cols()) = - bb[i];
if(upper[i] == T(0)) {
const auto n2(AA.row(i).dot(AA.row(i)));
if(n2 != T(0)) {
equal.emplace_back(std::make_pair(T(0), i));
AA.row(i) /= sqrt(n2);
}
} else {
AA.row(i) /= upper[i];
AA(i, A.cols()) -= - T(1);
}
one[i] = T(1);
assert(isfinite(AA.row(i).dot(AA.row(i))));
if(A.rows() - 1 <= i) break;
AA.row(i + A.rows()) = - AA.row(i);
one[i + A.rows()] = T(1);
}
SimpleMatrix<T> Pt(AA.cols(), AA.rows());
for(int i = 0; i < Pt.rows(); i ++)
for(int j = 0; j < Pt.cols(); j ++)
Pt(i, j) = T(0);
int ii(0);
for(int i = 0; i < AA.cols() && ii < AA.cols(); i ++) {
const auto Atrowi(AA.col(i));
const auto work(Atrowi - Pt.projectionPt(Atrowi));
const auto n2(work.dot(work));
if(n2 <= epsilon) continue;
Pt.row(ii ++) = work / sqrt(n2);
}
for(int j = 0; j < Pt.cols() && ii < Pt.rows(); j ++) {
SimpleVector<T> ek(Pt.cols());
for(int k = 0; k < Pt.cols(); k ++)
ek[k] = j == k ? T(1) : T(0);
ek -= Pt.projectionPt(ek);
const auto n2(ek.dot(ek));
if(n2 <= epsilon) continue;
Pt.row(ii ++) = ek / sqrt(n2);
}
assert(Pt.rows() <= ii);
cerr << "Q" << flush;
const auto R(Pt * AA);
cerr << "R" << flush;
const auto on(Pt.projectionPt(- one));
std::vector<std::pair<T, int> > fidx;
fidx.reserve(on.size());
for(int i = 0; i < on.size(); i ++)
if(T(0) < on[i])
fidx.emplace_back(std::make_pair(on[i], i));
std::sort(fidx.begin(), fidx.end());
{
std::vector<std::pair<T, int> > work;
work.reserve(equal.size() + fidx.size());
for(int i = 0; i < equal.size(); i ++)
work.emplace_back(std::move(equal[i]));
for(int i = 0; i < fidx.size(); i ++)
work.emplace_back(std::move(fidx[i]));
fidx = std::move(work);
// N.B. there's a little possibility on {0, 1} problem.
}
// worst case O(mn^2) over all in this function,
// we can make this function better case it's O(n^3) but not now.
for(int n_fixed = 0, idx = 0; n_fixed < Pt.rows() - 1 && idx < fidx.size(); n_fixed ++, idx ++) {
const auto& iidx(fidx[idx].second);
const auto orth(Pt.col(iidx));
const auto norm2orth(orth.dot(orth));
// XXX error:
if(norm2orth <= epsilon) {
n_fixed --;
continue;
}
#if defined(_OPENMP)
#pragma omp parallel for schedule(static, 1)
#endif
for(int j = 0; j < Pt.cols(); j ++)
Pt.setCol(j, Pt.col(j) - orth * (Pt.col(j).dot(orth) + T(n_fixed ? 0 : 1)) / norm2orth);
}
cerr << "G" << flush;
#if defined(_WITHOUT_EIGEN_)
auto rvec(- R.solve(Pt * one));
#else
auto rvec(- R.inverse() * (Pt * one));
#endif
cerr << "I" << flush;
SimpleVector<T> rrvec(rvec.size() - 1);
// | [A, - bb == - upper] [x t] | <= epsilon 1.
for(int i = 0; i < rrvec.size(); i ++)
rrvec[i] = rvec[i] / rvec[rvec.size() - 1];
return rrvec;
}
#define _LINEAR_OPT_
#endif
|
fix qr.
|
fix qr.
|
C++
|
bsd-3-clause
|
bitsofcotton/conv_check
|
d8d4ae3a785b586d0719be541294f0f5ec8aa2f1
|
main.cpp
|
main.cpp
|
ae4761e1-4b02-11e5-8184-28cfe9171a43
|
ae52d0fd-4b02-11e5-ac8d-28cfe9171a43
|
Put the thingie in the thingie
|
Put the thingie in the thingie
|
C++
|
apache-2.0
|
haosdent/jcgroup,haosdent/jcgroup
|
9ffb27beaa0c18aa1224d073bd9ecf69297b4c02
|
main.cpp
|
main.cpp
|
#include <string>
#include "pongobj.h"
#include "pongstring.h"
#include "sysio.h"
#include "pongproperties.h"
#include "pongtrigger.h"
#include "mainautomation.h"
using pong::PString;
using pong::PRect;
using pong::PKProperty;
using pong::PGProperty;
using pong::PGTrigger;
using pong::sys::SOut;
using pong::sys::SInInitial;
using pong::sys::SCurrent;
int main(void)
{
SOut sout;
SInInitial sin;
SCurrent scurrent;
int keyinput;
int terminal_length = sout.GetLength();
int terminal_width = sout.GetWidth();
PRect boundary_up = PRect(3, 1, terminal_length-4, 1, PColor(PColor::DEFAULT));
PRect boundary_down = PRect(3, terminal_width, terminal_length-4, 1, PColor(PColor::DEFAULT));
PRect boundary_left = PRect(2, 2, 1, terminal_width-2, PColor(PColor::DEFAULT));
PRect boundary_right = PRect(terminal_length-1, 2, 1, terminal_width-2, PColor(PColor::DEFAULT));
PRect boundary_court = PRect(3, 2, terminal_length-4, terminal_width-2, PColor(PColor::DEFAULT));
PRect lcursor = PRect(2, terminal_width/2-2, 1, 8, PColor(PColor::DEFAULT));
PRect rcursor = PRect(terminal_length-1, terminal_width/2-2, 1, 8, PColor(PColor::DEFAULT));
PRect ball = PRect(terminal_length/2, terminal_width/2, 1, 1, PColor(PColor::DEFAULT));
int ball_lr = -1;
int ball_ud = 1;
bool signal_terminate = false;
PGTrigger gmode_event = PGTrigger::LOBBY;
PGTrigger gmode_stage = PGTrigger::NONE;
while (signal_terminate != true)
{
sin >> keyinput;
if (gmode_event == PGTrigger(PGTrigger::LOBBY))
{
for (; gmode_stage != PGTrigger(PGTrigger::LOBBY); gmode_stage.Set(PGTrigger::LOBBY))
{
sout.Clear();
boundary_up.SetColor(PColor(PColor::BLUE));
boundary_down.SetColor(PColor(PColor::BLUE));
sout << boundary_up << boundary_down;
sout << PString("Pipong - Classic Table Tennis Game", PColor(PColor::CYAN), Point(terminal_length/2-16, terminal_width/2-2));
sout << PString("Press 's' to start game", PColor(PColor::DEFAULT), Point(terminal_length/2-13, terminal_width/2));
sout << PString("Press 'q' to exit the game", PColor(PColor::DEFAULT), Point(terminal_length/2-13, terminal_width/2+1));
}
if (keyinput == PKProperty::PSTART)
gmode_event.Set(PGTrigger::INGAME);
else if (keyinput == PKProperty::PEXIT)
signal_terminate = true;
}
else if (gmode_event == PGTrigger(PGTrigger::INGAME))
{
for (; gmode_stage != PGTrigger(PGTrigger::INGAME); gmode_stage.Set(PGTrigger::INGAME))
{
sout.Clear();
boundary_up.SetColor(PColor(PColor::CYAN));
boundary_down.SetColor(PColor(PColor::CYAN));
lcursor.SetSypos(terminal_width/2-4);
rcursor.SetSypos(terminal_width/2-4);
ball.SetSxpos(terminal_length/2);
ball.SetSypos(terminal_width/2);
sout << boundary_up << boundary_down << lcursor << rcursor << ball;
}
if (keyinput == PKProperty::PEXIT)
gmode_event.Set(PGTrigger::LOBBY);
else if (keyinput == PKProperty::PP1UP)
{
MainAM::PRectMove(sout, lcursor, 0, -1, boundary_left);
}
else if (keyinput == PKProperty::PP1DOWN)
{
MainAM::PRectMove(sout, lcursor, 0, 1, boundary_left);
}
else if (keyinput == PKProperty::PP2UP)
{
MainAM::PRectMove(sout, rcursor, 0, -1, boundary_right);
}
else if (keyinput == PKProperty::PP2DOWN)
{
MainAM::PRectMove(sout, rcursor, 0, 1, boundary_right);
}
if (scurrent.TimeTick(PGProperty::PBALLFREQ))
{
MainAM::PRectMove(sout, ball, ball_lr, ball_ud, boundary_court);
}
if ((ball.GetSpoint()).GetXpos() <= (boundary_left.GetSpoint()).GetXpos())
gmode_event.Set(PGTrigger::LOBBY);
}
scurrent.DelayMsec(PGProperty::PCYCLEDELAY);
}
return 0;
}
|
#include <string>
#include "pongobj.h"
#include "pongstring.h"
#include "sysio.h"
#include "pongproperties.h"
#include "pongtrigger.h"
#include "mainautomation.h"
using pong::PString;
using pong::PRect;
using pong::PKProperty;
using pong::PGProperty;
using pong::PGTrigger;
using pong::sys::SOut;
using pong::sys::SInInitial;
using pong::sys::SCurrent;
int main(void)
{
// System Object
SOut sout;
SInInitial sin;
SCurrent scurrent;
int keyinput;
// System Setting
int terminal_length = sout.GetLength();
int terminal_width = sout.GetWidth();
// Game Object
PRect boundary_up = PRect(3, 1, terminal_length-4, 1, PColor(PColor::DEFAULT));
PRect boundary_down = PRect(3, terminal_width, terminal_length-4, 1, PColor(PColor::DEFAULT));
PRect boundary_left = PRect(2, 2, 1, terminal_width-2, PColor(PColor::DEFAULT));
PRect boundary_right = PRect(terminal_length-1, 2, 1, terminal_width-2, PColor(PColor::DEFAULT));
PRect boundary_court = PRect(3, 2, terminal_length-4, terminal_width-2, PColor(PColor::DEFAULT));
PRect lcursor = PRect(2, terminal_width/2-2, 1, 8, PColor(PColor::DEFAULT));
PRect rcursor = PRect(terminal_length-1, terminal_width/2-2, 1, 8, PColor(PColor::DEFAULT));
PRect ball = PRect(terminal_length/2, terminal_width/2, 1, 1, PColor(PColor::DEFAULT));
// Game Setting
int ball_lr = -1;
int ball_ud = 1;
bool signal_terminate = false;
PGTrigger gmode_event = PGTrigger::LOBBY;
PGTrigger gmode_stage = PGTrigger::NONE;
// Game Logic
while (signal_terminate != true)
{
sin >> keyinput;
if (gmode_event == PGTrigger(PGTrigger::LOBBY))
{
for (; gmode_stage != PGTrigger(PGTrigger::LOBBY); gmode_stage.Set(PGTrigger::LOBBY))
{
sout.Clear();
boundary_up.SetColor(PColor(PColor::BLUE));
boundary_down.SetColor(PColor(PColor::BLUE));
sout << boundary_up << boundary_down;
sout << PString("Pipong - Classic Table Tennis Game", PColor(PColor::CYAN), Point(terminal_length/2-16, terminal_width/2-2));
sout << PString("Press 's' to start game", PColor(PColor::DEFAULT), Point(terminal_length/2-13, terminal_width/2));
sout << PString("Press 'q' to exit the game", PColor(PColor::DEFAULT), Point(terminal_length/2-13, terminal_width/2+1));
}
if (keyinput == PKProperty::PSTART)
gmode_event.Set(PGTrigger::INGAME);
else if (keyinput == PKProperty::PEXIT)
signal_terminate = true;
}
else if (gmode_event == PGTrigger(PGTrigger::INGAME))
{
for (; gmode_stage != PGTrigger(PGTrigger::INGAME); gmode_stage.Set(PGTrigger::INGAME))
{
sout.Clear();
boundary_up.SetColor(PColor(PColor::CYAN));
boundary_down.SetColor(PColor(PColor::CYAN));
lcursor.SetSypos(terminal_width/2-4);
rcursor.SetSypos(terminal_width/2-4);
ball.SetSxpos(terminal_length/2);
ball.SetSypos(terminal_width/2);
sout << boundary_up << boundary_down << lcursor << rcursor << ball;
}
if (keyinput == PKProperty::PEXIT)
gmode_event.Set(PGTrigger::LOBBY);
else if (keyinput == PKProperty::PP1UP)
{
MainAM::PRectMove(sout, lcursor, 0, -1, boundary_left);
}
else if (keyinput == PKProperty::PP1DOWN)
{
MainAM::PRectMove(sout, lcursor, 0, 1, boundary_left);
}
else if (keyinput == PKProperty::PP2UP)
{
MainAM::PRectMove(sout, rcursor, 0, -1, boundary_right);
}
else if (keyinput == PKProperty::PP2DOWN)
{
MainAM::PRectMove(sout, rcursor, 0, 1, boundary_right);
}
if (scurrent.TimeTick(PGProperty::PBALLFREQ))
{
MainAM::PRectMove(sout, ball, ball_lr, ball_ud, boundary_court);
}
if ((ball.GetSpoint()).GetXpos() <= (boundary_left.GetSpoint()).GetXpos())
gmode_event.Set(PGTrigger::LOBBY);
}
scurrent.DelayMsec(PGProperty::PCYCLEDELAY);
}
return 0;
}
|
Rearrange objects
|
Rearrange objects
|
C++
|
mit
|
pauis/pipong
|
747e3c4b3de6436c562066aa9cbade322765926d
|
main.cpp
|
main.cpp
|
//
// main.cpp
//
// Basic BST class implementation with insert, search, remove, recursive inorder print,
// and iterative inorder print.
//
// Created by Christopher Gleeson on 12/21/15.
// Copyright © 2015 Christopher Gleeson. All rights reserved.
//
#include <iostream>
#include <stack>
#include <cassert>
struct leaf {
int value;
struct leaf * left;
struct leaf * right;
};
class BST {
private:
struct leaf *root;
void destroy_tree(struct leaf *lf){
if(lf == NULL){
return;
}
destroy_tree(lf->left);
destroy_tree(lf->right);
delete lf;
}
struct leaf * find_parent(struct leaf *child, struct leaf * current){
if(current == NULL){
return NULL;
}else if(current->left == child || current->right == child){
return current;
}else if(child->value < current->value){
return find_parent(child, current->left);
}else if(child->value > current->value){
return find_parent(child, current->right);
}
return NULL;
}
void insert_hlpr(int key, struct leaf *lf){
if(key < lf->value){
if(lf->left == NULL){
lf->left = new struct leaf;
lf->left->value = key;
lf->left->left = NULL;
lf->left->right = NULL;
std::cout << "Inserting " << key << " into tree.\n";
}else{
insert_hlpr(key, lf->left);
}
}else if(key > lf->value){
if(lf->right == NULL){
lf->right = new struct leaf;
lf->right->value = key;
lf->right->left = NULL;
lf->right->right = NULL;
std::cout << "Inserting " << key << " into tree.\n";
}else{
insert_hlpr(key, lf->right);
}
}else{
//key is already in the tree, do nothing
}
}
struct leaf * search_hlpr(int key, struct leaf * lf){
if(lf == NULL){
return lf;
}else if(key == lf->value){
return lf;
}else if(key < lf->value){
return search_hlpr(key, lf->left);
}else if(key > lf->value){
return search_hlpr(key, lf->right);
}
return NULL;
}
void remove_hlpr(struct leaf *lf){
//this function takes a node to be removed that is in the tree
//cases: 1. node has no children, just remove the node.
//2. node has one child, copy the value of child to node and delete child.
//3. node has two children: copy inorder predecessor into node, call delete
//on the inorder predecessor, which will then hit case 1 or 2.
//case 1
if(lf->left == NULL && lf->right == NULL){
//must set the parent's pointer to lf to null before we delete
struct leaf *parent = find_parent(lf, root);
if(lf->value < parent->value){
parent->left = NULL;
}else{
parent->right = NULL;
}
delete lf;
return;
}
//case 2
if(lf->left == NULL && lf->right != NULL){
lf->value = lf->right->value;
remove_hlpr(lf->right);
return;
}
if(lf->left != NULL && lf->right == NULL){
lf->value = lf->left->value;
remove_hlpr(lf->left);
return;
}
//case 3
if(lf->left != NULL && lf->right != NULL){
struct leaf *iop = inorder_pred_hlpr(lf);
if(iop!=NULL){
lf->value = iop->value;
remove_hlpr(iop);
return;
}else{
//this should not be necessary, but its good to handle this case
std::cerr << "Critical error in node deletion! Abort!\n";
assert(iop != NULL);
}
}
}
struct leaf * inorder_pred_hlpr(struct leaf *lf){
//to find the inorder predecessor we look to the left child
//then traverse as far right as possible. when we can no
//longer traverse right, we are at the IOP.
struct leaf *iop = NULL;
if(lf->left == NULL){
return iop;
}else{
iop = lf->left;
}
while(iop->right != NULL){
iop = iop->right;
}
return iop;
}
void print_inorder_hlpr(struct leaf *lf){
if(lf == NULL) return;
print_inorder_hlpr(lf->left);
std::cout << lf->value << "\n";
print_inorder_hlpr(lf->right);
}
void print_it_inorder_hlpr(){
if(root == NULL) {
std::cout << "Tree is empty!\n";
return;
}
std::stack <struct leaf *> myStack;
struct leaf *current = root;
//Inorder iterative traversal algorithm:
//0. set current to root.
//1. while stack is not empty OR current != NULL
//2. if current != NULL push it onto the stack and set current = current->left
//3. then, pop the stack, print the value and set
//current to the the right child of the popped element
//4. continue this loop until the stack is empty.
while(!myStack.empty() || current != NULL){
if(current != NULL){
myStack.push(current);
current = current->left;
continue;
}
struct leaf *popped = myStack.top();
std::cout << popped->value << "\n";
current = popped->right;
myStack.pop();
}
}
public:
BST();
~BST();
void insert(int key);
bool search(int key);
void remove(int key);
void print_tree_inorder();
void print_tree_it_inorder();
void inorder_predecessor(int key); //for testing only
void locate_parent(int key); //for testing only
};
BST::BST(){
root = NULL;
}
BST::~BST(){
destroy_tree(root);
}
void BST::insert(int key){
if(root != NULL){
insert_hlpr(key, root);
return;
}
root = new struct leaf;
root->left = NULL;
root->right = NULL;
root->value = key;
std::cout << "Inserting " << key << " into tree.\n";
}
bool BST::search(int key){
//search for key in the tree and return a
//pointer to the node containing the key,
//else return a NULL pointer
if(root == NULL){
return false;
}else{
struct leaf *found = search_hlpr(key, root);
if(found != NULL){
return true;
}else{
return false;
}
}
}
void BST::remove(int key){
if(!search(key)){
std::cout << "Key not in tree, no removal possible.\n";
}else{
struct leaf *rem = search_hlpr(key, root);
std::cout << "Value to remove is " << rem->value << "\n";
remove_hlpr(rem);
}
}
void BST::print_tree_inorder(){
if(root == NULL){
std::cout << "Tree is empty!\n";
}else{
print_inorder_hlpr(root);
}
}
void BST::print_tree_it_inorder(){
if(root == NULL){
std::cout << "Tree is empty!\n";
}else{
print_it_inorder_hlpr();
}
}
void BST::inorder_predecessor(int key){
struct leaf *found = search_hlpr(key, root);
struct leaf *iop = inorder_pred_hlpr(found);
if(iop == NULL){
std::cout << "There is no inorder predecessor for key of " << key << "\n";
return;
}else{
std::cout << "Value of inorder predecessor for key of " << key << " is " << iop->value << "\n";
return;
}
}
void BST::locate_parent(int key){
struct leaf * par = NULL;
struct leaf * child = search_hlpr(key, root);
if(child != NULL){
par = find_parent(child, root);
}
if(par != NULL){
std::cout << "Found parent of node with value " << child->value << ", parent has value " << par->value << "\n";
}
}
int main(int argc, const char * argv[]){
//create a tree object
BST *myTree = new BST;
//print the empty tree
myTree->print_tree_inorder();
//add some elements
myTree->insert(8);
myTree->insert(4);
myTree->insert(2);
myTree->insert(-1);
myTree->insert(12);
myTree->insert(14);
myTree->insert(-16);
myTree->insert(3);
myTree->insert(5);
myTree->insert(10);
//print the tree recursively
std::cout << "Print of tree, inorder, recursive:\n";
myTree->print_tree_inorder();
//print the tree iteratively
std::cout << "Print of tree, inorder, iterative:\n";
myTree->print_tree_it_inorder();
//search for a node
std::cout << "Searching for node with value 4, expect success.\n";
int skey = 4;
bool result = myTree->search(skey);
if(!result){
std::cout << "Searched for key of " << skey << ", key NOT found!\n";
}else{
std::cout << "Found key of " << skey << " successfully!\n";
}
std::cout << "Searching for node with value 13, expect failure.\n";
skey = 13;
result = myTree->search(skey);
if(!result){
std::cout << "Searched for key of " << skey << ", key NOT found!\n";
}else{
std::cout << "Found key of " << skey << " successfully!\n";
}
//test inorder predecessor
std::cout << "Testing checks for inorder predecessor, 8,4,2,12 expect pass, 14 expect fail.\n";
myTree->inorder_predecessor(8);
myTree->inorder_predecessor(4);
myTree->inorder_predecessor(2);
myTree->inorder_predecessor(12);
myTree->inorder_predecessor(14);
//test find parent
std::cout << "Testing find parent for node with value 4, expect to find parent with value 8.\n";
myTree->locate_parent(4);
//test deletion
std::cout << "Testing node deletion of node with value 14, expect success.\n";
myTree->remove(14);
myTree->print_tree_inorder();
delete myTree;
return 0;
}
|
//
// main.cpp
// C++ClassBST
//
// Basic BST class implementation with insert, search, remove, recursive inorder print,
// and iterative inorder print.
//
// The data type of value in the leaf struct is templateized.
//
// Created by Christopher Gleeson on 12/21/15.
// Copyright © 2015 Christopher Gleeson. All rights reserved.
//
#include <iostream>
#include <stack>
#include <cassert>
template <typename T>
struct leaf {
T value;
struct leaf<T> * left;
struct leaf<T> * right;
};
template <typename T>
class BST {
private:
struct leaf<T> *root;
void destroy_tree(struct leaf<T> *lf){
if(lf == NULL){
return;
}
destroy_tree(lf->left);
destroy_tree(lf->right);
delete lf;
}
struct leaf<T> * find_parent(struct leaf<T> *child, struct leaf<T> * current){
if(current == NULL){
return NULL;
}else if(current->left == child || current->right == child){
return current;
}else if(child->value < current->value){
return find_parent(child, current->left);
}else if(child->value > current->value){
return find_parent(child, current->right);
}
return NULL;
}
void insert_hlpr(T key, struct leaf<T> *lf){
if(key < lf->value){
if(lf->left == NULL){
lf->left = new struct leaf<T>;
lf->left->value = key;
lf->left->left = NULL;
lf->left->right = NULL;
std::cout << "Inserting " << key << " into tree.\n";
}else{
insert_hlpr(key, lf->left);
}
}else if(key > lf->value){
if(lf->right == NULL){
lf->right = new struct leaf<T>;
lf->right->value = key;
lf->right->left = NULL;
lf->right->right = NULL;
std::cout << "Inserting " << key << " into tree.\n";
}else{
insert_hlpr(key, lf->right);
}
}else{
//key is already in the tree, do nothing
}
}
struct leaf<T> * search_hlpr(T key, struct leaf<T> * lf){
if(lf == NULL){
return lf;
}else if(key == lf->value){
return lf;
}else if(key < lf->value){
return search_hlpr(key, lf->left);
}else if(key > lf->value){
return search_hlpr(key, lf->right);
}
return NULL;
}
void remove_hlpr(struct leaf<T> *lf){
//this function takes a node to be removed that is in the tree
//cases: 1. node has no children, just remove the node.
//2. node has one child, copy the value of child to node and delete child.
//3. node has two children: copy inorder predecessor into node, call delete
//on the inorder predecessor, which will then hit case 1 or 2.
//case 1
if(lf->left == NULL && lf->right == NULL){
//must set the parent's pointer to lf to null before we delete
struct leaf<T> *parent = find_parent(lf, root);
if(lf->value < parent->value){
parent->left = NULL;
}else{
parent->right = NULL;
}
delete lf;
return;
}
//case 2
if(lf->left == NULL && lf->right != NULL){
lf->value = lf->right->value;
remove_hlpr(lf->right);
return;
}
if(lf->left != NULL && lf->right == NULL){
lf->value = lf->left->value;
remove_hlpr(lf->left);
return;
}
//case 3
if(lf->left != NULL && lf->right != NULL){
struct leaf<T> *iop = inorder_pred_hlpr(lf);
if(iop!=NULL){
lf->value = iop->value;
remove_hlpr(iop);
return;
}else{
//this should not be necessary, but its good to handle this case
std::cerr << "Critical error in node deletion! Abort!\n";
assert(iop != NULL);
}
}
}
struct leaf<T> * inorder_pred_hlpr(struct leaf<T> *lf){
//to find the inorder predecessor we look to the left child
//then traverse as far right as possible. when we can no
//longer traverse right, we are at the IOP.
struct leaf<T> *iop = NULL;
if(lf->left == NULL){
return iop;
}else{
iop = lf->left;
}
while(iop->right != NULL){
iop = iop->right;
}
return iop;
}
void print_inorder_hlpr(struct leaf<T> *lf){
if(lf == NULL) return;
print_inorder_hlpr(lf->left);
std::cout << lf->value << "\n";
print_inorder_hlpr(lf->right);
}
void print_it_inorder_hlpr(){
if(root == NULL) {
std::cout << "Tree is empty!\n";
return;
}
std::stack <struct leaf<T> *> myStack;
struct leaf<T> *current = root;
//Inorder iterative traversal algorithm:
//0. set current to root.
//1. while stack is not empty OR current != NULL
//2. if current != NULL push it onto the stack and set current = current->left
//3. then, pop the stack, print the value and set
//current to the the right child of the popped element
//4. continue this loop until the stack is empty.
while(!myStack.empty() || current != NULL){
if(current != NULL){
myStack.push(current);
current = current->left;
continue;
}
struct leaf<T> *popped = myStack.top();
std::cout << popped->value << "\n";
current = popped->right;
myStack.pop();
}
}
public:
BST();
~BST();
void insert(T key);
bool search(T key);
void remove(T key);
void print_tree_inorder();
void print_tree_it_inorder();
void inorder_predecessor(T key); //for testing only
void locate_parent(T key); //for testing only
};
template <typename T>
BST<T>::BST(){
root = NULL;
}
template <typename T>
BST<T>::~BST(){
destroy_tree(root);
}
template <typename T>
void BST<T>::insert(T key){
if(root != NULL){
insert_hlpr(key, root);
return;
}
root = new struct leaf<T>;
root->left = NULL;
root->right = NULL;
root->value = key;
std::cout << "Inserting " << key << " into tree.\n";
}
template <typename T>
bool BST<T>::search(T key){
//search for key in the tree and return a
//pointer to the node containing the key,
//else return a NULL pointer
if(root == NULL){
return false;
}else{
struct leaf<T> *found = search_hlpr(key, root);
if(found != NULL){
return true;
}else{
return false;
}
}
}
template <typename T>
void BST<T>::remove(T key){
if(!search(key)){
std::cout << "Key not in tree, no removal possible.\n";
}else{
struct leaf<T> *rem = search_hlpr(key, root);
std::cout << "Value to remove is " << rem->value << "\n";
remove_hlpr(rem);
}
}
template <typename T>
void BST<T>::print_tree_inorder(){
if(root == NULL){
std::cout << "Tree is empty!\n";
}else{
print_inorder_hlpr(root);
}
}
template <typename T>
void BST<T>::print_tree_it_inorder(){
if(root == NULL){
std::cout << "Tree is empty!\n";
}else{
print_it_inorder_hlpr();
}
}
template <typename T>
void BST<T>::inorder_predecessor(T key){
struct leaf<T> *found = search_hlpr(key, root);
struct leaf<T> *iop = inorder_pred_hlpr(found);
if(iop == NULL){
std::cout << "There is no inorder predecessor for key of " << key << "\n";
return;
}else{
std::cout << "Value of inorder predecessor for key of " << key << " is " << iop->value << "\n";
return;
}
}
template <typename T>
void BST<T>::locate_parent(T key){
struct leaf<T> * par = NULL;
struct leaf<T> * child = search_hlpr(key, root);
if(child != NULL){
par = find_parent(child, root);
}
if(par != NULL){
std::cout << "Found parent of node with value " << child->value << ", parent has value " << par->value << "\n";
}
}
int main(int argc, const char * argv[]){
//create a tree object
BST<int> *myTree = new BST<int>;
//print the empty tree
myTree->print_tree_inorder();
//add some elements
myTree->insert(8);
myTree->insert(4);
myTree->insert(2);
myTree->insert(-1);
myTree->insert(12);
myTree->insert(14);
myTree->insert(-16);
myTree->insert(3);
myTree->insert(5);
myTree->insert(10);
//print the tree recursively
std::cout << "Print of tree, inorder, recursive:\n";
myTree->print_tree_inorder();
//print the tree iteratively
std::cout << "Print of tree, inorder, iterative:\n";
myTree->print_tree_it_inorder();
//search for a node
std::cout << "Searching for node with value 4, expect success.\n";
int skey = 4;
bool result = myTree->search(skey);
if(!result){
std::cout << "Searched for key of " << skey << ", key NOT found!\n";
}else{
std::cout << "Found key of " << skey << " successfully!\n";
}
std::cout << "Searching for node with value 13, expect failure.\n";
skey = 13;
result = myTree->search(skey);
if(!result){
std::cout << "Searched for key of " << skey << ", key NOT found!\n";
}else{
std::cout << "Found key of " << skey << " successfully!\n";
}
//test inorder predecessor
std::cout << "Testing checks for inorder predecessor, 8,4,2,12 expect pass, 14 expect fail.\n";
myTree->inorder_predecessor(8);
myTree->inorder_predecessor(4);
myTree->inorder_predecessor(2);
myTree->inorder_predecessor(12);
myTree->inorder_predecessor(14);
//test find parent
std::cout << "Testing find parent for node with value 4, expect to find parent with value 8.\n";
myTree->locate_parent(4);
//test deletion
std::cout << "Testing node deletion of node with value 14, expect success.\n";
myTree->remove(14);
myTree->print_tree_inorder();
delete myTree;
return 0;
}
|
Update to main.cpp
|
Update to main.cpp
Refactored the struct/class definitions to use a template type for the value data type, class can now be used for any numeric data type (int, float, etc...)
|
C++
|
mit
|
randomInteger/CPlusPlus-BST
|
d2e8613aa89cfe64fc23271165789f37551ab088
|
main.cpp
|
main.cpp
|
#include <iostream>
#include <vector>
#include "GrappaContext.hpp"
#include <time.h>
#include <iomanip>
using std::cout;
struct int_container {
int64_t a;
int64_t b;
};
struct double_container {
double a;
double b;
};
int add(const int& a, const int& b) {
return a + b;
}
int main(int argc, char *argv[]) {
auto gc = new GrappaContext(argc, argv);
gc->run([] {
for (int i = 0; i < 3; i++) {
time_t t0;
time(&t0);
auto sum = RDD<int64_t>::range(1000000000)->sum();
time_t t1;
time(&t1);
double seconds = difftime(t1, t0);
cout << "Loop: " << i << endl;
cout << "Time: " << std::fixed << std::setprecision(3) << seconds << endl;
}
//vector<int> coll_data(100);
//for (int i = 0; i < 100; i++) {
//coll_data[i] = i;
//}
//auto collection_rdd = new ParallelCollectionRDD<int>(coll_data);
//int sum = collection_rdd->fold(0, [](const int& a, const int& b) -> int {return a + b;});
//cout << "Sum: " << sum << endl;
//cout << "ParallelCollectionRDD\n";
//vector <int_container> data;
//for (int i = 0; i < 20; i++) {
//int_container v;
//v.a = 2 * i;
//v.b = i;
//data.push_back(v);
//}
//auto pcoll = new ParallelCollectionRDD<int_container>(data);
//auto mpcoll = pcoll->map([](int_container a) -> double_container {
//double_container v;
//v.a = 2.5;
//v.b = 1.5;
//return v;
//});
//for (auto e: mpcoll->collect()) {
//cout << "a: " << e.a << " b: " << e.b << endl;
//}
});
gc->stop();
return 0;
}
|
#include <iostream>
#include <vector>
#include "GrappaContext.hpp"
#include <time.h>
#include <iomanip>
using std::cout;
struct int_container {
int64_t a;
int64_t b;
};
struct double_container {
double a;
double b;
};
int add(const int& a, const int& b) {
return a + b;
}
int main(int argc, char *argv[]) {
auto gc = new GrappaContext(argc, argv);
gc->run([] {
struct timeval t0, t1;
for (int i = 0; i < 3; i++) {
gettimeofday(&t0, NULL);
auto sum = RDD<int64_t>::range(1000000000)->sum();
gettimeofday(&t1, NULL);
cout << "Loop: " << i << endl;
cout << "Seconds: " << t1.tv_sec - t0.tv_sec << endl;
cout << "Milliseconds: " << (t1.tv_usec - t1.tv_usec) / 1000 << endl;
}
//vector<int> coll_data(100);
//for (int i = 0; i < 100; i++) {
//coll_data[i] = i;
//}
//auto collection_rdd = new ParallelCollectionRDD<int>(coll_data);
//int sum = collection_rdd->fold(0, [](const int& a, const int& b) -> int {return a + b;});
//cout << "Sum: " << sum << endl;
//cout << "ParallelCollectionRDD\n";
//vector <int_container> data;
//for (int i = 0; i < 20; i++) {
//int_container v;
//v.a = 2 * i;
//v.b = i;
//data.push_back(v);
//}
//auto pcoll = new ParallelCollectionRDD<int_container>(data);
//auto mpcoll = pcoll->map([](int_container a) -> double_container {
//double_container v;
//v.a = 2.5;
//v.b = 1.5;
//return v;
//});
//for (auto e: mpcoll->collect()) {
//cout << "a: " << e.a << " b: " << e.b << endl;
//}
});
gc->stop();
return 0;
}
|
Print milliseconds in addition to seconds
|
Print milliseconds in addition to seconds
|
C++
|
bsd-3-clause
|
EntilZha/GrappaRDD
|
8e66392e790384a4a09f6a0ed1257fbc76f94899
|
main.cpp
|
main.cpp
|
#include<iostream>
using namespace std;
void main()
{
cout<<"Hello world github 2016-11-24."<<endl;
}
|
#include<iostream>
using namespace std;
void main()
{
cout<<"Hello world github in 2016-11-24."<<endl;
int n;
cin>>n;
return;
}
|
Update main.cpp
|
Update main.cpp
add and modify some line text
|
C++
|
apache-2.0
|
zhangqingzhi/HelloWorld
|
23a70ad4ff24de5a1e2f2e350683f7e075f80c8f
|
main.cpp
|
main.cpp
|
#include <iostream>
#include <unistd.h>
#include <time.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include "tile.h"
#include "loader.h"
struct s_window_state {
int width;
int height;
} window_state;
double latitude = 50.356718;
double longitude = 7.599485;
bool left_mouse_down = false;
bool right_mouse_down = false;
bool middle_mouse_down = false;
double angle(int p1x, int p1y, int p2x, int p2y) {
float xDiff = p2x - p1x;
float yDiff = p2y - p1y;
return -atan2(yDiff, xDiff) * (180 / M_PI);
}
double _angle1 = 0.0;
double start_angle1 = 0.0;
double _angle2 = 0.0;
double start_angle2 = 0.0;
#define SIZE (150.0)
#define TILE_SIZE_LAT_16 (0.00350434d/2)
#define TILE_SIZE_LON_16 (0.00549316d/2)
#define Y_16 (0.000012)
#define X_16 (0.000019)
/**
* @brief poll for events
* @return true, if the program should end
*/
bool poll() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
return false;
case SDL_KEYUP:
if (event.key.keysym.sym == SDLK_ESCAPE) {
return false;
}
break;
case SDL_MOUSEMOTION:
if (left_mouse_down) {
_angle1 = angle(event.motion.x, event.motion.y, (window_state.width / 2), (window_state.height / 2)) - start_angle1;
}
if (right_mouse_down) {
_angle2 = std::max((window_state.height / 2) - event.motion.y, 0) * 70 / (window_state.height / 2);
}
if (middle_mouse_down) {
long double _cos = std::cos(_angle1 * M_PI / 180);
long double _sin = std::sin(_angle1 * M_PI / 180);
latitude += event.motion.yrel * Y_16 * _cos + event.motion.xrel * X_16 * _sin;
longitude -= event.motion.xrel * X_16 * _cos - event.motion.yrel * Y_16 * _sin;
}
break;
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == 1) {
left_mouse_down = true;
start_angle1 = angle(event.button.x, event.button.y, (window_state.width / 2), (window_state.height / 2)) - _angle1;
} else if (event.button.button == 3) {
right_mouse_down = true;
start_angle2 = angle(event.button.x, event.button.y, (window_state.width / 2), (window_state.height / 2)) - _angle2;
} else if (event.button.button == 2) {
middle_mouse_down = true;
}
break;
case SDL_MOUSEBUTTONUP:
if (event.button.button == 1) {
left_mouse_down = false;
} else if (event.button.button == 3) {
right_mouse_down = false;
} else if (event.button.button == 2) {
middle_mouse_down = false;
}
break;
default:
break;
}
}
return true;
}
void render(int zoom, double latitude, double longitude) {
Tile* center_tile = TileFactory::instance()->get_tile(zoom, latitude, longitude);
// Clear with black
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-(window_state.width / 2), (window_state.width / 2), (window_state.height / 2), -(window_state.height / 2), -1000, 1000);
// Render the slippy map parts
glEnable(GL_TEXTURE_2D);
glRotated(_angle2, 1.0, 0.0, 0.0);
glRotated(_angle1, 0.0, 0.0, -1.0);
int top = -6;
int left = -6;
int bottom = 6;
int right = 6;
// Top left coordinate of the current tile
double tile_latitude = tiley2lat(center_tile->y, zoom);
double tile_longitude = tilex2long(center_tile->x, zoom);
double lat_diff = (SIZE/2) + ((latitude - tile_latitude) * SIZE / TILE_SIZE_LAT_16);
double lon_diff = (SIZE/2) + ((tile_longitude - longitude) * SIZE / TILE_SIZE_LON_16);
//std::cout.precision(10);
//std::cout << "Lat: " << latitude << " vs " << tile_latitude << " -> offset " << lat_diff << "px" << std::endl;
//std::cout << "Lon: " << longitude << " vs " << tile_longitude << " -> offset " << lon_diff << "px" << std::endl;
glPushMatrix();
glTranslated(lon_diff, lat_diff, 0);
Tile* current = center_tile->get(left, top);
for (int y = top; y < bottom; y++) {
for (int x = left; x < right; x++) {
if (current->texid == 0) {
Loader::instance()->open_image(*current);
}
glPushMatrix();
glTranslated(x*SIZE*2, y*SIZE*2, 0);
glBindTexture(GL_TEXTURE_2D, current->texid);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 1.0); glVertex3f(-SIZE, SIZE, 0);
glTexCoord2f(1.0, 1.0); glVertex3f(SIZE, SIZE, 0);
glTexCoord2f(1.0, 0.0); glVertex3f(SIZE, -SIZE, 0);
glTexCoord2f(0.0, 0.0); glVertex3f(-SIZE, -SIZE, 0);
glEnd();
glPopMatrix();
current = current->get_west();
}
current = current->get(-(std::abs(left) + std::abs(right)), 1);
}
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glColor3d(1.0, 0.5, 0.0);
glBegin(GL_TRIANGLES);
glVertex3f(-10, 15, 1);
glVertex3f( 10, 15, 1);
glVertex3f( 0, -10, 1);
glEnd();
glColor3d(1.0, 1.0, 1.0);
}
int main(int argc, char **argv) {
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cerr << "Could not initialize SDL video: " << SDL_GetError() << std::endl;
return 1;
}
// Create an OpenGL window
SDL_Window* window = SDL_CreateWindow("slippymap3d", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1024, 768, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
SDL_GetWindowSize(window, &window_state.width, &window_state.height);
SDL_GLContext context = SDL_GL_CreateContext(window);
// Load the file matching the given coordinates
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
long base_time = spec.tv_sec * 1000 + round(spec.tv_nsec / 1.0e6);
int frames = 0;
while(true) {
if (!poll()) {
break;
}
frames++;
clock_gettime(CLOCK_REALTIME, &spec);
long time_in_mill = spec.tv_sec * 1000 + round(spec.tv_nsec / 1.0e6);
if ((time_in_mill - base_time) > 1000.0) {
std::cout << frames * 1000.0 / (time_in_mill - base_time) << " fps" << std::endl;
base_time = time_in_mill;
frames=0;
}
render(16, latitude, longitude);
SDL_GL_SwapWindow(window);
}
SDL_GL_DeleteContext(context);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
|
#include <iostream>
#include <unistd.h>
#include <time.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include "tile.h"
#include "loader.h"
struct s_window_state {
int width;
int height;
} window_state;
double latitude = 50.356718;
double longitude = 7.599485;
bool left_mouse_down = false;
bool right_mouse_down = false;
bool middle_mouse_down = false;
double angle(int p1x, int p1y, int p2x, int p2y) {
float xDiff = p2x - p1x;
float yDiff = p2y - p1y;
return -atan2(yDiff, xDiff) * (180 / M_PI);
}
double _angle1 = 0.0;
double start_angle1 = 0.0;
double _angle2 = 0.0;
double start_angle2 = 0.0;
#define MAX_TILT (65)
#define SIZE (150.0)
#define TILE_SIZE_LAT_16 (0.00350434d/2)
#define TILE_SIZE_LON_16 (0.00549316d/2)
#define Y_16 (0.000012)
#define X_16 (0.000019)
/**
* @brief poll for events
* @return true, if the program should end
*/
bool poll() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
return false;
case SDL_KEYUP:
if (event.key.keysym.sym == SDLK_ESCAPE) {
return false;
}
break;
case SDL_MOUSEMOTION:
if (left_mouse_down) {
_angle1 = angle(event.motion.x, event.motion.y, (window_state.width / 2), (window_state.height / 2)) - start_angle1;
}
if (right_mouse_down) {
_angle2 = std::max((window_state.height / 2) - event.motion.y, 0) * MAX_TILT / (window_state.height / 2);
}
if (middle_mouse_down) {
long double _cos = std::cos(_angle1 * M_PI / 180);
long double _sin = std::sin(_angle1 * M_PI / 180);
latitude += event.motion.yrel * Y_16 * _cos + event.motion.xrel * X_16 * _sin;
longitude -= event.motion.xrel * X_16 * _cos - event.motion.yrel * Y_16 * _sin;
}
break;
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == 1) {
left_mouse_down = true;
start_angle1 = angle(event.button.x, event.button.y, (window_state.width / 2), (window_state.height / 2)) - _angle1;
} else if (event.button.button == 3) {
right_mouse_down = true;
start_angle2 = angle(event.button.x, event.button.y, (window_state.width / 2), (window_state.height / 2)) - _angle2;
} else if (event.button.button == 2) {
middle_mouse_down = true;
}
break;
case SDL_MOUSEBUTTONUP:
if (event.button.button == 1) {
left_mouse_down = false;
} else if (event.button.button == 3) {
right_mouse_down = false;
} else if (event.button.button == 2) {
middle_mouse_down = false;
}
break;
default:
break;
}
}
return true;
}
void render(int zoom, double latitude, double longitude) {
Tile* center_tile = TileFactory::instance()->get_tile(zoom, latitude, longitude);
// Clear with black
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-(window_state.width / 2), (window_state.width / 2), (window_state.height / 2), -(window_state.height / 2), -1000, 1000);
// Render the slippy map parts
glEnable(GL_TEXTURE_2D);
glRotated(_angle2, 1.0, 0.0, 0.0);
glRotated(_angle1, 0.0, 0.0, -1.0);
int top = -6;
int left = -6;
int bottom = 6;
int right = 6;
// Top left coordinate of the current tile
double tile_latitude = tiley2lat(center_tile->y, zoom);
double tile_longitude = tilex2long(center_tile->x, zoom);
double lat_diff = (SIZE/2) + ((latitude - tile_latitude) * SIZE / TILE_SIZE_LAT_16);
double lon_diff = (SIZE/2) + ((tile_longitude - longitude) * SIZE / TILE_SIZE_LON_16);
//std::cout.precision(10);
//std::cout << "Lat: " << latitude << " vs " << tile_latitude << " -> offset " << lat_diff << "px" << std::endl;
//std::cout << "Lon: " << longitude << " vs " << tile_longitude << " -> offset " << lon_diff << "px" << std::endl;
glPushMatrix();
glTranslated(lon_diff, lat_diff, 0);
Tile* current = center_tile->get(left, top);
for (int y = top; y < bottom; y++) {
for (int x = left; x < right; x++) {
if (current->texid == 0) {
Loader::instance()->open_image(*current);
}
glPushMatrix();
glTranslated(x*SIZE*2, y*SIZE*2, 0);
glBindTexture(GL_TEXTURE_2D, current->texid);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 1.0); glVertex3f(-SIZE, SIZE, 0);
glTexCoord2f(1.0, 1.0); glVertex3f(SIZE, SIZE, 0);
glTexCoord2f(1.0, 0.0); glVertex3f(SIZE, -SIZE, 0);
glTexCoord2f(0.0, 0.0); glVertex3f(-SIZE, -SIZE, 0);
glEnd();
glPopMatrix();
current = current->get_west();
}
current = current->get(-(std::abs(left) + std::abs(right)), 1);
}
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glColor3d(1.0, 0.5, 0.0);
glBegin(GL_TRIANGLES);
glVertex3f(-10, 15, 1);
glVertex3f( 10, 15, 1);
glVertex3f( 0, -10, 1);
glEnd();
glColor3d(1.0, 1.0, 1.0);
}
int main(int argc, char **argv) {
// Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
std::cerr << "Could not initialize SDL video: " << SDL_GetError() << std::endl;
return 1;
}
// Create an OpenGL window
SDL_Window* window = SDL_CreateWindow("slippymap3d", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1024, 768, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
SDL_GetWindowSize(window, &window_state.width, &window_state.height);
SDL_GLContext context = SDL_GL_CreateContext(window);
// Load the file matching the given coordinates
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
long base_time = spec.tv_sec * 1000 + round(spec.tv_nsec / 1.0e6);
int frames = 0;
while(true) {
if (!poll()) {
break;
}
frames++;
clock_gettime(CLOCK_REALTIME, &spec);
long time_in_mill = spec.tv_sec * 1000 + round(spec.tv_nsec / 1.0e6);
if ((time_in_mill - base_time) > 1000.0) {
std::cout << frames * 1000.0 / (time_in_mill - base_time) << " fps" << std::endl;
base_time = time_in_mill;
frames=0;
}
render(16, latitude, longitude);
SDL_GL_SwapWindow(window);
}
SDL_GL_DeleteContext(context);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
|
Switch from a hardcoded constant to a define
|
Switch from a hardcoded constant to a define
Improves the understandibility. Also switch to 65° because it looks better.
|
C++
|
mit
|
egore/slippymap3d,egore/slippymap3d
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.