text stringlengths 54 60.6k |
|---|
<commit_before>//
// Copyright 2012 Francisco Jerez
//
// 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 "api/util.hpp"
#include "core/queue.hpp"
using namespace clover;
CLOVER_API cl_command_queue
clCreateCommandQueue(cl_context d_ctx, cl_device_id d_dev,
cl_command_queue_properties props,
cl_int *r_errcode) try {
auto &ctx = obj(d_ctx);
auto &dev = obj(d_dev);
if (!count(dev, ctx.devices()))
throw error(CL_INVALID_DEVICE);
if (props & ~(CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE |
CL_QUEUE_PROFILING_ENABLE))
throw error(CL_INVALID_VALUE);
ret_error(r_errcode, CL_SUCCESS);
return new command_queue(ctx, dev, props);
} catch (error &e) {
ret_error(r_errcode, e);
return NULL;
}
CLOVER_API cl_int
clRetainCommandQueue(cl_command_queue d_q) try {
obj(d_q).retain();
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clReleaseCommandQueue(cl_command_queue d_q) try {
if (obj(d_q).release())
delete pobj(d_q);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clGetCommandQueueInfo(cl_command_queue d_q, cl_command_queue_info param,
size_t size, void *r_buf, size_t *r_size) try {
property_buffer buf { r_buf, size, r_size };
auto &q = obj(d_q);
switch (param) {
case CL_QUEUE_CONTEXT:
buf.as_scalar<cl_context>() = desc(q.context());
break;
case CL_QUEUE_DEVICE:
buf.as_scalar<cl_device_id>() = desc(q.device());
break;
case CL_QUEUE_REFERENCE_COUNT:
buf.as_scalar<cl_uint>() = q.ref_count();
break;
case CL_QUEUE_PROPERTIES:
buf.as_scalar<cl_command_queue_properties>() = q.properties();
break;
default:
throw error(CL_INVALID_VALUE);
}
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clFlush(cl_command_queue d_q) try {
obj(d_q).flush();
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
<commit_msg>clover: Flush the command queue in clReleaseCommandQueue()<commit_after>//
// Copyright 2012 Francisco Jerez
//
// 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 "api/util.hpp"
#include "core/queue.hpp"
using namespace clover;
CLOVER_API cl_command_queue
clCreateCommandQueue(cl_context d_ctx, cl_device_id d_dev,
cl_command_queue_properties props,
cl_int *r_errcode) try {
auto &ctx = obj(d_ctx);
auto &dev = obj(d_dev);
if (!count(dev, ctx.devices()))
throw error(CL_INVALID_DEVICE);
if (props & ~(CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE |
CL_QUEUE_PROFILING_ENABLE))
throw error(CL_INVALID_VALUE);
ret_error(r_errcode, CL_SUCCESS);
return new command_queue(ctx, dev, props);
} catch (error &e) {
ret_error(r_errcode, e);
return NULL;
}
CLOVER_API cl_int
clRetainCommandQueue(cl_command_queue d_q) try {
obj(d_q).retain();
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clReleaseCommandQueue(cl_command_queue d_q) try {
auto &q = obj(d_q);
q.flush();
if (q.release())
delete pobj(d_q);
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clGetCommandQueueInfo(cl_command_queue d_q, cl_command_queue_info param,
size_t size, void *r_buf, size_t *r_size) try {
property_buffer buf { r_buf, size, r_size };
auto &q = obj(d_q);
switch (param) {
case CL_QUEUE_CONTEXT:
buf.as_scalar<cl_context>() = desc(q.context());
break;
case CL_QUEUE_DEVICE:
buf.as_scalar<cl_device_id>() = desc(q.device());
break;
case CL_QUEUE_REFERENCE_COUNT:
buf.as_scalar<cl_uint>() = q.ref_count();
break;
case CL_QUEUE_PROPERTIES:
buf.as_scalar<cl_command_queue_properties>() = q.properties();
break;
default:
throw error(CL_INVALID_VALUE);
}
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
CLOVER_API cl_int
clFlush(cl_command_queue d_q) try {
obj(d_q).flush();
return CL_SUCCESS;
} catch (error &e) {
return e.get();
}
<|endoftext|> |
<commit_before>#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <openssl/rand.h>
#include <openssl/err.h>
using namespace v8;
using namespace node;
static const char *hexencode = "0123456789abcdef";
static const int hexdecode[] =
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-2,-2,-1,-1,-2,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
};
static inline int check_byte(uint8_t b) {
if (b >= 0x80) return -1;
return hexdecode[b];
}
Handle<Value> RandBytes(const Arguments &args) {
HandleScope scope;
if (!Buffer::HasInstance(args[0])) {
return ThrowException(Exception::TypeError(String::New(
"First argument must be a Buffer")));
}
Local<Object> buf = args[0]->ToObject();
char *data = Buffer::Data(buf);
size_t length = Buffer::Length(buf);
if (!RAND_bytes((unsigned char*)data, length)) {
unsigned long code = ERR_get_error();
return ThrowException(Exception::Error(String::New(
ERR_error_string(code, NULL))));
}
return scope.Close(Integer::NewFromUnsigned(length));
}
Handle<Value> BufToHex(const Arguments &args) {
HandleScope scope;
if (!Buffer::HasInstance(args[0])) {
return ThrowException(Exception::TypeError(String::New(
"First argument must be a Buffer")));
}
Local<Object> buf = args[0]->ToObject();
char *data = Buffer::Data(buf);
size_t length = Buffer::Length(buf);
int out_len = length * 2;
char *out = new char[out_len];
int i;
for (i=0; i<length; i++) {
out[2*i] = hexencode[(data[i] & 0xf0) >> 4];
out[2*i + 1] = hexencode[ data[i] & 0x0f ];
}
Local<String> retval = String::New(out, out_len);
delete [] out;
return scope.Close(retval);
}
Handle<Value> HexToBuf(const Arguments &args) {
HandleScope scope;
if (!args[0]->IsString()) {
return ThrowException(Exception::TypeError(String::New(
"First argument must be a String")));
}
if (!Buffer::HasInstance(args[1])) {
return ThrowException(Exception::TypeError(String::New(
"Second argument must be a Buffer")));
}
Local<String> str = args[0]->ToString();
Local<Object> buf = args[1]->ToObject();
String::Utf8Value v(str);
char *data = *v;
size_t length = v.length();
int out_len = length >> 1;
char *out = Buffer::Data(buf);
size_t buf_len = Buffer::Length(buf);
int to_write = out_len;
if (length & 1) {
char b = check_byte(data[0]);
if (b < 0) {
return ThrowException(Exception::TypeError(String::New(
"Invalid hex string")));
}
*out++ = b;
data++;
to_write++;
}
if (to_write > buf_len) {
return ThrowException(Exception::Error(String::New(
"Buffer too small")));
}
int i;
for (i=0; i<out_len; i++) {
char l = check_byte(data[2*i]);
char r = check_byte(data[2*i + 1]);
if (l < 0 || r < 0) {
return ThrowException(Exception::TypeError(String::New(
"Invalid hex string")));
}
*out++ = (l << 4) | r;
}
return scope.Close(Integer::NewFromUnsigned(to_write));
}
extern "C"
void init(Handle<Object> target) {
HandleScope scope;
target->Set(String::NewSymbol("randomBytes"),
FunctionTemplate::New(RandBytes)->GetFunction());
target->Set(String::NewSymbol("bufToHex"),
FunctionTemplate::New(BufToHex)->GetFunction());
target->Set(String::NewSymbol("hexToBuf"),
FunctionTemplate::New(HexToBuf)->GetFunction());
}<commit_msg>handle -1 response<commit_after>#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <openssl/rand.h>
#include <openssl/err.h>
using namespace v8;
using namespace node;
static const char *hexencode = "0123456789abcdef";
static const int hexdecode[] =
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-2,-2,-1,-1,-2,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1
,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1
};
static inline int check_byte(uint8_t b) {
if (b >= 0x80) return -1;
return hexdecode[b];
}
Handle<Value> RandBytes(const Arguments &args) {
HandleScope scope;
if (!Buffer::HasInstance(args[0])) {
return ThrowException(Exception::TypeError(String::New(
"First argument must be a Buffer")));
}
Local<Object> buf = args[0]->ToObject();
char *data = Buffer::Data(buf);
size_t length = Buffer::Length(buf);
switch (RAND_bytes((unsigned char*) data, length)) {
case -1:
return ThrowException(Exception::Error(String::New(
"Current RAND method does not support this operation")));
case 0:
unsigned long code = ERR_get_error();
return ThrowException(Exception::Error(String::New(
ERR_error_string(code, NULL))));
}
return scope.Close(Integer::NewFromUnsigned(length));
}
Handle<Value> BufToHex(const Arguments &args) {
HandleScope scope;
if (!Buffer::HasInstance(args[0])) {
return ThrowException(Exception::TypeError(String::New(
"First argument must be a Buffer")));
}
Local<Object> buf = args[0]->ToObject();
char *data = Buffer::Data(buf);
size_t length = Buffer::Length(buf);
int out_len = length * 2;
char *out = new char[out_len];
int i;
for (i=0; i<length; i++) {
out[2*i] = hexencode[(data[i] & 0xf0) >> 4];
out[2*i + 1] = hexencode[ data[i] & 0x0f ];
}
Local<String> retval = String::New(out, out_len);
delete [] out;
return scope.Close(retval);
}
Handle<Value> HexToBuf(const Arguments &args) {
HandleScope scope;
if (!args[0]->IsString()) {
return ThrowException(Exception::TypeError(String::New(
"First argument must be a String")));
}
if (!Buffer::HasInstance(args[1])) {
return ThrowException(Exception::TypeError(String::New(
"Second argument must be a Buffer")));
}
Local<String> str = args[0]->ToString();
Local<Object> buf = args[1]->ToObject();
String::Utf8Value v(str);
char *data = *v;
size_t length = v.length();
int out_len = length >> 1;
char *out = Buffer::Data(buf);
size_t buf_len = Buffer::Length(buf);
int to_write = out_len;
if (length & 1) {
char b = check_byte(data[0]);
if (b < 0) {
return ThrowException(Exception::TypeError(String::New(
"Invalid hex string")));
}
*out++ = b;
data++;
to_write++;
}
if (to_write > buf_len) {
return ThrowException(Exception::Error(String::New(
"Buffer too small")));
}
int i;
for (i=0; i<out_len; i++) {
char l = check_byte(data[2*i]);
char r = check_byte(data[2*i + 1]);
if (l < 0 || r < 0) {
return ThrowException(Exception::TypeError(String::New(
"Invalid hex string")));
}
*out++ = (l << 4) | r;
}
return scope.Close(Integer::NewFromUnsigned(to_write));
}
extern "C"
void init(Handle<Object> target) {
HandleScope scope;
target->Set(String::NewSymbol("randomBytes"),
FunctionTemplate::New(RandBytes)->GetFunction());
target->Set(String::NewSymbol("bufToHex"),
FunctionTemplate::New(BufToHex)->GetFunction());
target->Set(String::NewSymbol("hexToBuf"),
FunctionTemplate::New(HexToBuf)->GetFunction());
}<|endoftext|> |
<commit_before>#include "bitmap.h"
#include "except.h"
Bitmap::Bitmap(std::string filepath)
: _filepath(filepath)
, _data(nullptr)
, _width(0)
, _height(0)
{
FILE * fptr = fopen(_filepath.c_str(), "rb");
if (fptr == nullptr)
throw FileError();
uint8_t bmp_header[54];
fread(bmp_header, sizeof(uint8_t), 54, fptr);
_width = *(int *)&bmp_header[18];
_height = *(int *)&bmp_header[22];
size_t num_bytes = 3 * _width * _height;
_data = new uint8_t[num_bytes];
fread(_data, sizeof(uint8_t), num_bytes, fptr);
fclose(fptr);
}
Bitmap::~Bitmap()
{
// TODO
}
uint8_t * const Bitmap::get_data() const
{
// TODO
return nullptr;
}
size_t Bitmap::get_width() const
{
// TODO
return 0;
}
size_t Bitmap::get_height() const
{
// TODO
return 0;
}
std::string Bitmap::save() const
{
// TODO
return "";
}
<commit_msg>Issue #14: implemented destructor<commit_after>#include "bitmap.h"
#include "except.h"
Bitmap::Bitmap(std::string filepath)
: _filepath(filepath)
, _data(nullptr)
, _width(0)
, _height(0)
{
FILE * fptr = fopen(_filepath.c_str(), "rb");
if (fptr == nullptr)
throw FileError();
uint8_t bmp_header[54];
fread(bmp_header, sizeof(uint8_t), 54, fptr);
_width = *(int *)&bmp_header[18];
_height = *(int *)&bmp_header[22];
size_t num_bytes = 3 * _width * _height;
_data = new uint8_t[num_bytes];
fread(_data, sizeof(uint8_t), num_bytes, fptr);
fclose(fptr);
}
Bitmap::~Bitmap()
{
save();
if (_data != nullptr)
delete [] _data;
}
uint8_t * const Bitmap::get_data() const
{
// TODO
return nullptr;
}
size_t Bitmap::get_width() const
{
// TODO
return 0;
}
size_t Bitmap::get_height() const
{
// TODO
return 0;
}
std::string Bitmap::save() const
{
// TODO
return "";
}
<|endoftext|> |
<commit_before>#include "ioHandler.h"
#include <exception>
void writer_helper(ReadBase *r, std::shared_ptr<OutputWriter> pe, std::shared_ptr<OutputWriter> se, bool stranded, Counter &c) {
PairedEndRead *per = dynamic_cast<PairedEndRead*>(r);
if (per) {
if (!(per->non_const_read_one()).getDiscard() && !(per->non_const_read_two()).getDiscard()) {
++c["PE_Out"];
per->setStats(c);
pe->write(*per);
} else if (!(per->non_const_read_one()).getDiscard()) { //if stranded RC
++c["SE_Out"];
++c["R1_Discarded"];
per->setStats(c);
se->write_read((per->get_read_one()), false);
} else if (!(per->non_const_read_two()).getDiscard()) { // Will never be RC
++c["SE_Out"];
++c["R2_Discarded"];
per->setStats(c);
se->write_read((per->get_read_two()), stranded);
} else {
++c["R1_Discarded"];
++c["R2_Discarded"];
per->setStats(c);
}
} else {
SingleEndRead *ser = dynamic_cast<SingleEndRead*>(r);
if (!ser) {
throw std::runtime_error("Unknow read found");
}
if (! (ser->non_const_read_one()).getDiscard() ) {
++c["SE_Out"];
ser->setStats(c);
se->write(*ser);
} else {
++c["SE_Discarded"];
ser->setStats(c);
}
}
}
void skip_lr(std::istream *input) {
while(input and input->good() and (input->peek() == '\n' || input->peek() == '\r')) {
input->get();
}
}
int check_open_r(const std::string& filename) {
bf::path p(filename);
if (!bf::exists(p)) {
throw std::runtime_error("File " + filename + " was not found.");
}
if (p.extension() == ".gz") {
return fileno(popen(("gunzip -c " + filename).c_str(), "r"));
} else {
return fileno(fopen(filename.c_str(), "r"));
}
}
int check_exists(const std::string& filename, bool force, bool gzip, bool std_out) {
if (std_out) {
return fileno(stdout);
}
bf::path p(filename);
if (force || !bf::exists(p)) {
if (gzip) {
return fileno(popen(("gzip > " + filename + ".gz").c_str(), "w"));
} else {
return fileno(fopen(filename.c_str(), "w"));
}
} else {
throw std::runtime_error("File " + filename + " all ready exists. Please use -F or delete it\n");
}
}
Read InputFastq::load_read(std::istream *input) {
while(std::getline(*input, id) && id.size() < 1) {
}
if (id.size() < 1) {
throw std::runtime_error("invalid id line empty");
}
if (id[0] != '@') {
throw std::runtime_error("id line did not begin with @");
}
std::getline(*input, seq);
if (seq.size() < 1) {
throw std::runtime_error("invalid seq line empty");
}
std::getline(*input, id2);
if (id2.size() < 1) {
throw std::runtime_error("invalid id2 line empty");
}
if (id2[0] != '+') {
throw std::runtime_error("invalid id2 line did not begin with +");
}
std::getline(*input, qual);
if (qual.size() != seq.size()) {
throw std::runtime_error("qual string not the same length as sequence");
}
// ignore extra lines at end of file
while(input->good() and (input->peek() == '\n' || input->peek() == '\r')) {
input->get();
}
return Read(seq, qual, id.substr(1));
}
//Overrides load_read for tab delimited reads
std::vector<Read> TabReadImpl::load_read(std::istream *input) {
std::vector <Read> reads(1);
while(std::getline(*input, tabLine) && tabLine.size() < 1) {
}
std::vector <std::string> parsedRead;
boost::split(parsedRead, tabLine, boost::is_any_of("\t"));
if (parsedRead.size() != 3 && parsedRead.size() != 5) {
throw std::runtime_error("There are not either 3 or 5 elements within a tab delimited file line");
}
if (parsedRead[1].size() != parsedRead[2].size()) {
throw std::runtime_error("sequence and qualities are not the same length 1");
}
reads[0] = Read(parsedRead[1], parsedRead[2], parsedRead[0]);
if (parsedRead.size() != 3) {
if (parsedRead[3].size() != parsedRead[4].size()) {
throw std::runtime_error("sequence and qualities are not the same length 2");
}
reads.push_back(Read(parsedRead[3], parsedRead[4], parsedRead[0]));
}
// ignore extra lines at end of file
while(input->good() and (input->peek() == '\n' || input->peek() == '\r')) {
input->get();
}
return reads;
}
template <>
bool InputReader<SingleEndRead, SingleEndReadFastqImpl>::has_next() {
// ignore extra lines at end of file
skip_lr(input);
return (input and input->good());
};
template <>
InputReader<SingleEndRead, SingleEndReadFastqImpl>::value_type InputReader<SingleEndRead, SingleEndReadFastqImpl>::next() {
return InputReader<SingleEndRead, SingleEndReadFastqImpl>::value_type(new SingleEndRead(load_read(input)));
}
template <>
InputReader<PairedEndRead, PairedEndReadFastqImpl>::value_type InputReader<PairedEndRead, PairedEndReadFastqImpl>::next() {
Read r1 = load_read(in1);
Read r2 = load_read(in2);
return InputReader<PairedEndRead, PairedEndReadFastqImpl>::value_type(new PairedEndRead(r1, r2));
}
template <>
bool InputReader<PairedEndRead, PairedEndReadFastqImpl>::has_next() {
// ignore extra lines at end of file
skip_lr(in1);
skip_lr(in2);
return (in1 and in1->good() and in2 and in2->good());
};
template<>
InputReader<PairedEndRead, InterReadImpl>::value_type InputReader<PairedEndRead, InterReadImpl>::next() {
Read r1 = load_read(in1);
Read r2;
try {
r2 = load_read(in1);
} catch (const std::exception&) {
throw std::runtime_error("odd number of sequences in interleaved file");
}
return InputReader<PairedEndRead, InterReadImpl>::value_type(new PairedEndRead(r1, r2));
}
template<>
bool InputReader<PairedEndRead, InterReadImpl>::has_next() {
skip_lr(in1);
return(in1 && in1->good());
}
template <>
InputReader<ReadBase, TabReadImpl>::value_type InputReader<ReadBase, TabReadImpl>::next() {
std::vector<Read> rs = load_read(in1);
if (rs.size() == 1) {
return InputReader<SingleEndRead, TabReadImpl>::value_type(new SingleEndRead(rs[0]));
}
return InputReader<PairedEndRead, TabReadImpl>::value_type(new PairedEndRead(rs[0], rs[1]));
}
template <>
bool InputReader<ReadBase, TabReadImpl>::has_next() {
// ignore extra lines at end of file
skip_lr(in1);
return (in1 and in1->good());
}
<commit_msg>Fixed Read Discard logic<commit_after>#include "ioHandler.h"
#include <exception>
void writer_helper(ReadBase *r, std::shared_ptr<OutputWriter> pe, std::shared_ptr<OutputWriter> se, bool stranded, Counter &c) {
PairedEndRead *per = dynamic_cast<PairedEndRead*>(r);
if (per) {
if (!(per->non_const_read_one()).getDiscard() && !(per->non_const_read_two()).getDiscard()) {
++c["PE_Out"];
per->setStats(c);
pe->write(*per);
} else if (!(per->non_const_read_one()).getDiscard()) { //if stranded RC
++c["SE_Out"];
++c["R2_Discarded"];
per->setStats(c);
se->write_read((per->get_read_one()), false);
} else if (!(per->non_const_read_two()).getDiscard()) { // Will never be RC
++c["SE_Out"];
++c["R1_Discarded"];
per->setStats(c);
se->write_read((per->get_read_two()), stranded);
} else {
++c["R1_Discarded"];
++c["R2_Discarded"];
per->setStats(c);
}
} else {
SingleEndRead *ser = dynamic_cast<SingleEndRead*>(r);
if (!ser) {
throw std::runtime_error("Unknow read found");
}
if (! (ser->non_const_read_one()).getDiscard() ) {
++c["SE_Out"];
ser->setStats(c);
se->write(*ser);
} else {
++c["SE_Discarded"];
ser->setStats(c);
}
}
}
void skip_lr(std::istream *input) {
while(input and input->good() and (input->peek() == '\n' || input->peek() == '\r')) {
input->get();
}
}
int check_open_r(const std::string& filename) {
bf::path p(filename);
if (!bf::exists(p)) {
throw std::runtime_error("File " + filename + " was not found.");
}
if (p.extension() == ".gz") {
return fileno(popen(("gunzip -c " + filename).c_str(), "r"));
} else {
return fileno(fopen(filename.c_str(), "r"));
}
}
int check_exists(const std::string& filename, bool force, bool gzip, bool std_out) {
if (std_out) {
return fileno(stdout);
}
bf::path p(filename);
if (force || !bf::exists(p)) {
if (gzip) {
return fileno(popen(("gzip > " + filename + ".gz").c_str(), "w"));
} else {
return fileno(fopen(filename.c_str(), "w"));
}
} else {
throw std::runtime_error("File " + filename + " all ready exists. Please use -F or delete it\n");
}
}
Read InputFastq::load_read(std::istream *input) {
while(std::getline(*input, id) && id.size() < 1) {
}
if (id.size() < 1) {
throw std::runtime_error("invalid id line empty");
}
if (id[0] != '@') {
throw std::runtime_error("id line did not begin with @");
}
std::getline(*input, seq);
if (seq.size() < 1) {
throw std::runtime_error("invalid seq line empty");
}
std::getline(*input, id2);
if (id2.size() < 1) {
throw std::runtime_error("invalid id2 line empty");
}
if (id2[0] != '+') {
throw std::runtime_error("invalid id2 line did not begin with +");
}
std::getline(*input, qual);
if (qual.size() != seq.size()) {
throw std::runtime_error("qual string not the same length as sequence");
}
// ignore extra lines at end of file
while(input->good() and (input->peek() == '\n' || input->peek() == '\r')) {
input->get();
}
return Read(seq, qual, id.substr(1));
}
//Overrides load_read for tab delimited reads
std::vector<Read> TabReadImpl::load_read(std::istream *input) {
std::vector <Read> reads(1);
while(std::getline(*input, tabLine) && tabLine.size() < 1) {
}
std::vector <std::string> parsedRead;
boost::split(parsedRead, tabLine, boost::is_any_of("\t"));
if (parsedRead.size() != 3 && parsedRead.size() != 5) {
throw std::runtime_error("There are not either 3 or 5 elements within a tab delimited file line");
}
if (parsedRead[1].size() != parsedRead[2].size()) {
throw std::runtime_error("sequence and qualities are not the same length 1");
}
reads[0] = Read(parsedRead[1], parsedRead[2], parsedRead[0]);
if (parsedRead.size() != 3) {
if (parsedRead[3].size() != parsedRead[4].size()) {
throw std::runtime_error("sequence and qualities are not the same length 2");
}
reads.push_back(Read(parsedRead[3], parsedRead[4], parsedRead[0]));
}
// ignore extra lines at end of file
while(input->good() and (input->peek() == '\n' || input->peek() == '\r')) {
input->get();
}
return reads;
}
template <>
bool InputReader<SingleEndRead, SingleEndReadFastqImpl>::has_next() {
// ignore extra lines at end of file
skip_lr(input);
return (input and input->good());
};
template <>
InputReader<SingleEndRead, SingleEndReadFastqImpl>::value_type InputReader<SingleEndRead, SingleEndReadFastqImpl>::next() {
return InputReader<SingleEndRead, SingleEndReadFastqImpl>::value_type(new SingleEndRead(load_read(input)));
}
template <>
InputReader<PairedEndRead, PairedEndReadFastqImpl>::value_type InputReader<PairedEndRead, PairedEndReadFastqImpl>::next() {
Read r1 = load_read(in1);
Read r2 = load_read(in2);
return InputReader<PairedEndRead, PairedEndReadFastqImpl>::value_type(new PairedEndRead(r1, r2));
}
template <>
bool InputReader<PairedEndRead, PairedEndReadFastqImpl>::has_next() {
// ignore extra lines at end of file
skip_lr(in1);
skip_lr(in2);
return (in1 and in1->good() and in2 and in2->good());
};
template<>
InputReader<PairedEndRead, InterReadImpl>::value_type InputReader<PairedEndRead, InterReadImpl>::next() {
Read r1 = load_read(in1);
Read r2;
try {
r2 = load_read(in1);
} catch (const std::exception&) {
throw std::runtime_error("odd number of sequences in interleaved file");
}
return InputReader<PairedEndRead, InterReadImpl>::value_type(new PairedEndRead(r1, r2));
}
template<>
bool InputReader<PairedEndRead, InterReadImpl>::has_next() {
skip_lr(in1);
return(in1 && in1->good());
}
template <>
InputReader<ReadBase, TabReadImpl>::value_type InputReader<ReadBase, TabReadImpl>::next() {
std::vector<Read> rs = load_read(in1);
if (rs.size() == 1) {
return InputReader<SingleEndRead, TabReadImpl>::value_type(new SingleEndRead(rs[0]));
}
return InputReader<PairedEndRead, TabReadImpl>::value_type(new PairedEndRead(rs[0], rs[1]));
}
template <>
bool InputReader<ReadBase, TabReadImpl>::has_next() {
// ignore extra lines at end of file
skip_lr(in1);
return (in1 and in1->good());
}
<|endoftext|> |
<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef GUARD_MIOPEN_LEGACY_EXHAUSTIVE_SEARCH_HPP
#define GUARD_MIOPEN_LEGACY_EXHAUSTIVE_SEARCH_HPP
#include "miopen/config.h"
#include "miopen/solver.hpp"
namespace miopen {
namespace solver {
class LegacyPerformanceConfig : public PerformanceConfig
{
public:
int grp_tile1 = 0;
int grp_tile0 = 0;
int in_tile1 = 0;
int in_tile0 = 0;
int out_pix_tile1 = 0;
int out_pix_tile0 = 0;
int n_out_pix_tiles = 0;
int n_in_data_tiles = 0;
int n_stacks = 0;
void CopyTo(ConvSolution& iud) const;
void Serialize(std::ostream& stream) const override;
bool Deserialize(const std::string& from) override;
#if MIOPEN_PERFDB_CONV_LEGACY_SUPPORT
bool LegacyDeserialize(const std::string& from) override;
#endif
};
} // namespace solver
} // namespace miopen
#endif
<commit_msg>Perf Db: clang-format<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef GUARD_MIOPEN_LEGACY_EXHAUSTIVE_SEARCH_HPP
#define GUARD_MIOPEN_LEGACY_EXHAUSTIVE_SEARCH_HPP
#include "miopen/config.h"
#include "miopen/solver.hpp"
namespace miopen {
namespace solver {
class LegacyPerformanceConfig : public PerformanceConfig
{
public:
int grp_tile1 = 0;
int grp_tile0 = 0;
int in_tile1 = 0;
int in_tile0 = 0;
int out_pix_tile1 = 0;
int out_pix_tile0 = 0;
int n_out_pix_tiles = 0;
int n_in_data_tiles = 0;
int n_stacks = 0;
void CopyTo(ConvSolution& iud) const;
void Serialize(std::ostream& stream) const override;
bool Deserialize(const std::string& from) override;
#if MIOPEN_PERFDB_CONV_LEGACY_SUPPORT
bool LegacyDeserialize(const std::string& from) override;
#endif
};
} // namespace solver
} // namespace miopen
#endif
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/include/usr/secureboot/secure_reasoncodes.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2013,2017 */
/* [+] 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 */
#ifndef __SECUREBOOT_REASONCODES_H
#define __SECUREBOOT_REASONCODES_H
#include <hbotcompid.H>
namespace SECUREBOOT
{
enum SECUREModuleId
{
MOD_SECURE_INVALID = 0x00,
MOD_SECURE_BLINDPURGE = 0x01,
MOD_SECURE_ROM_INIT = 0x02,
MOD_SECURE_ROM_VERIFY = 0x03,
MOD_SECURE_ROM_CLEANUP = 0x04,
MOD_SECURE_ROM_SHA512 = 0x05,
MOD_SECURE_READ_REG = 0x06,
MOD_SECURE_WRITE_REG = 0x07,
MOD_SECURE_SETTINGS_INIT = 0x08,
MOD_SECURE_VERIFY_COMPONENT = 0x09,
MOD_SECURE_CONT_HDR_PARSE = 0x0A,
MOD_SECURE_CONT_HDR_CPY_INC = 0x0B,
MOD_SECURE_CONT_VALIDATE = 0x0C,
MOD_SECURE_SET_SBE_SECURE_MODE = 0x0D,
MOD_SECURE_GET_ALL_SEC_REGS = 0x0E,
MOD_SECURE_LOAD_HEADER = 0x0F,
};
enum SECUREReasonCode
{
RC_PURGEOP_PENDING = SECURE_COMP_ID | 0x01,
RC_PURGEOP_FAIL_COMPLETE = SECURE_COMP_ID | 0x02,
RC_DEV_MAP_FAIL = SECURE_COMP_ID | 0x03,
RC_PAGE_ALLOC_FAIL = SECURE_COMP_ID | 0x04,
RC_SET_PERMISSION_FAIL_EXE = SECURE_COMP_ID | 0x05,
RC_SET_PERMISSION_FAIL_WRITE = SECURE_COMP_ID | 0x06,
RC_ROM_VERIFY = SECURE_COMP_ID | 0x07,
RC_ROM_SHA512 = SECURE_COMP_ID | 0x08,
RC_SECURE_BAD_TARGET = SECURE_COMP_ID | 0x09,
RC_SECURE_BOOT_DISABLED = SECURE_COMP_ID | 0x0A,
RC_SECROM_INVALID = SECURE_COMP_ID | 0x0B,
RC_CONT_HDR_NO_SPACE = SECURE_COMP_ID | 0x0C,
RC_CONT_HDR_INVALID = SECURE_COMP_ID | 0x0D,
RC_SBE_INVALID_SEC_MODE = SECURE_COMP_ID | 0x0E,
RC_DEVICE_WRITE_ERR = SECURE_COMP_ID | 0x0F,
RC_PROC_NOT_SCOMABLE = SECURE_COMP_ID | 0x10,
RC_DEVICE_READ_ERR = SECURE_COMP_ID | 0x11,
RC_INVALID_BASE_HEADER = SECURE_COMP_ID | 0x12,
// Reason codes 0xA0 - 0xEF reserved for trustedboot_reasoncodes.H
};
enum UserDetailsTypes
{
// Version(s)
SECURE_UDT_VERSION_1 = 0x1,
// Formats/User Detail Sections
SECURE_UDT_NO_FORMAT = 0x0,
SECURE_UDT_SYSTEM_HW_KEY_HASH = 0x1,
SECURE_UDT_TARGET_HW_KEY_HASH = 0x2,
SECURE_UDT_SECURITY_SETTINGS = 0x3,
};
}
#endif
<commit_msg>Secure Boot: Flag ROM verify reason code as terminating RC<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/include/usr/secureboot/secure_reasoncodes.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2013,2018 */
/* [+] 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 */
#ifndef __SECUREBOOT_REASONCODES_H
#define __SECUREBOOT_REASONCODES_H
#include <hbotcompid.H>
namespace SECUREBOOT
{
enum SECUREModuleId
{
MOD_SECURE_INVALID = 0x00,
MOD_SECURE_BLINDPURGE = 0x01,
MOD_SECURE_ROM_INIT = 0x02,
MOD_SECURE_ROM_VERIFY = 0x03,
MOD_SECURE_ROM_CLEANUP = 0x04,
MOD_SECURE_ROM_SHA512 = 0x05,
MOD_SECURE_READ_REG = 0x06,
MOD_SECURE_WRITE_REG = 0x07,
MOD_SECURE_SETTINGS_INIT = 0x08,
MOD_SECURE_VERIFY_COMPONENT = 0x09,
MOD_SECURE_CONT_HDR_PARSE = 0x0A,
MOD_SECURE_CONT_HDR_CPY_INC = 0x0B,
MOD_SECURE_CONT_VALIDATE = 0x0C,
MOD_SECURE_SET_SBE_SECURE_MODE = 0x0D,
MOD_SECURE_GET_ALL_SEC_REGS = 0x0E,
MOD_SECURE_LOAD_HEADER = 0x0F,
};
enum SECUREReasonCode
{
RC_PURGEOP_PENDING = SECURE_COMP_ID | 0x01,
RC_PURGEOP_FAIL_COMPLETE = SECURE_COMP_ID | 0x02,
RC_DEV_MAP_FAIL = SECURE_COMP_ID | 0x03,
RC_PAGE_ALLOC_FAIL = SECURE_COMP_ID | 0x04,
RC_SET_PERMISSION_FAIL_EXE = SECURE_COMP_ID | 0x05,
RC_SET_PERMISSION_FAIL_WRITE = SECURE_COMP_ID | 0x06,
//termination_rc
RC_ROM_VERIFY = SECURE_COMP_ID | 0x07,
RC_ROM_SHA512 = SECURE_COMP_ID | 0x08,
RC_SECURE_BAD_TARGET = SECURE_COMP_ID | 0x09,
RC_SECURE_BOOT_DISABLED = SECURE_COMP_ID | 0x0A,
RC_SECROM_INVALID = SECURE_COMP_ID | 0x0B,
RC_CONT_HDR_NO_SPACE = SECURE_COMP_ID | 0x0C,
RC_CONT_HDR_INVALID = SECURE_COMP_ID | 0x0D,
RC_SBE_INVALID_SEC_MODE = SECURE_COMP_ID | 0x0E,
RC_DEVICE_WRITE_ERR = SECURE_COMP_ID | 0x0F,
RC_PROC_NOT_SCOMABLE = SECURE_COMP_ID | 0x10,
RC_DEVICE_READ_ERR = SECURE_COMP_ID | 0x11,
RC_INVALID_BASE_HEADER = SECURE_COMP_ID | 0x12,
// Reason codes 0xA0 - 0xEF reserved for trustedboot_reasoncodes.H
};
enum UserDetailsTypes
{
// Version(s)
SECURE_UDT_VERSION_1 = 0x1,
// Formats/User Detail Sections
SECURE_UDT_NO_FORMAT = 0x0,
SECURE_UDT_SYSTEM_HW_KEY_HASH = 0x1,
SECURE_UDT_TARGET_HW_KEY_HASH = 0x2,
SECURE_UDT_SECURITY_SETTINGS = 0x3,
};
}
#endif
<|endoftext|> |
<commit_before>#pragma XOD evaluate_on_pin disable
#pragma XOD evaluate_on_pin enable input_UPD
node {
bool received = false;
TimeMs startTime = 0;
void evaluate(Context ctx) {
auto inet = getValue<input_INET>(ctx);
emitValue<output_INETU0027>(ctx, inet);
auto t = getValue<input_T>(ctx);
if (isInputDirty<input_UPD>(ctx)) {
startTime = transactionTime();
setImmediate();
return;
}
if (isTimedOut(ctx)) {
bool shouldWait = startTime + (t * 1000) > transactionTime();
if (shouldWait && inet->isConnected()) {
// No incoming data, but we're still waiting for data
if (!inet->isReceiving()) {
setImmediate();
return;
}
// Receiving data
received = true;
setImmediate();
emitValue<output_Y>(ctx, 1);
return;
} else {
// No more incoming data
if (received && !inet->isReceiving()) {
received = false;
emitValue<output_END>(ctx, 1);
return;
}
// Timeout error
raiseError(ctx);
return;
}
}
}
}
<commit_msg>fix(stdlib): fix `xod/debug/is-receiving` implementation<commit_after>#pragma XOD evaluate_on_pin disable
#pragma XOD evaluate_on_pin enable input_UPD
node {
bool received = false;
TimeMs startTime = 0;
bool isWaiting = false;
void evaluate(Context ctx) {
auto inet = getValue<input_INET>(ctx);
emitValue<output_INETU0027>(ctx, inet);
auto t = getValue<input_T>(ctx);
if (isInputDirty<input_UPD>(ctx)) {
startTime = transactionTime();
setImmediate();
isWaiting = true;
}
if (isWaiting) {
bool shouldWait = startTime + (t * 1000) > transactionTime();
if (shouldWait && inet->isConnected()) {
// No incoming data, but we're still waiting for data
if (!inet->isReceiving()) {
setImmediate();
return;
}
// Receiving data
received = true;
startTime = transactionTime();
setImmediate();
emitValue<output_Y>(ctx, 1);
} else {
isWaiting = false;
// No more incoming data
if (received && !inet->isReceiving()) {
received = false;
emitValue<output_END>(ctx, 1);
return;
}
// Timeout error
raiseError(ctx);
}
}
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* Copyright 2009-2015 Juan Francisco Crespo Galán
*
* 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 "fx/PlaybackManager.h"
#include "fx/VolumeSound.h"
#include <stdexcept>
AUD_NAMESPACE_BEGIN
PlaybackManager::PlaybackManager(std::shared_ptr<IDevice> device) :
m_device(device), m_currentKey(0)
{
}
unsigned int PlaybackManager::addCategory(std::shared_ptr<PlaybackCategory> category)
{
m_categories[m_currentKey] = category;
unsigned int k = m_currentKey;
m_currentKey++;
return k;
}
std::shared_ptr<IHandle> PlaybackManager::play(std::shared_ptr<ISound> sound, unsigned int catKey)
{
std::shared_ptr<PlaybackCategory> category;
try
{
category = m_categories.at(catKey);
}
catch(std::out_of_range& oor)
{
category = std::make_shared<PlaybackCategory>(m_device);
m_categories[catKey] = category;
m_currentKey = catKey + 1;
}
return category->play(sound);
}
bool PlaybackManager::resume(unsigned int catKey)
{
try
{
m_categories.at(catKey)->resume();
return true;
}
catch(std::out_of_range& oor)
{
return false;
}
}
bool PlaybackManager::pause(unsigned int catKey)
{
try
{
m_categories.at(catKey)->pause();
return true;
}
catch(std::out_of_range& oor)
{
return false;
}
}
float PlaybackManager::getVolume(unsigned int catKey)
{
try
{
return m_categories.at(catKey)->getVolume();
}
catch(std::out_of_range& oor)
{
return -1.0;
}
}
bool PlaybackManager::setVolume(float volume, unsigned int catKey)
{
try
{
m_categories.at(catKey)->setVolume(volume);
return true;
}
catch(std::out_of_range& oor)
{
return false;
}
}
bool PlaybackManager::stop(unsigned int catKey)
{
try
{
m_categories.at(catKey)->stop();
return true;
}
catch(std::out_of_range& oor)
{
return false;
}
}
void PlaybackManager::clean()
{
for(auto cat : m_categories)
cat.second->cleanHandles();
}
bool PlaybackManager::clean(unsigned int catKey)
{
try
{
m_categories.at(catKey)->cleanHandles();
return true;
}
catch(std::out_of_range& oor)
{
return false;
}
}
AUD_NAMESPACE_END
<commit_msg>Performance optimization. Exceptions are no longer used for flow control in the PlaybackManager class.<commit_after>/*******************************************************************************
* Copyright 2009-2015 Juan Francisco Crespo Galán
*
* 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 "fx/PlaybackManager.h"
#include "fx/VolumeSound.h"
#include <stdexcept>
AUD_NAMESPACE_BEGIN
PlaybackManager::PlaybackManager(std::shared_ptr<IDevice> device) :
m_device(device), m_currentKey(0)
{
}
unsigned int PlaybackManager::addCategory(std::shared_ptr<PlaybackCategory> category)
{
m_categories[m_currentKey] = category;
unsigned int k = m_currentKey;
m_currentKey++;
return k;
}
std::shared_ptr<IHandle> PlaybackManager::play(std::shared_ptr<ISound> sound, unsigned int catKey)
{
auto iter = m_categories.find(catKey);
std::shared_ptr<PlaybackCategory> category;
if(iter != m_categories.end())
{
category = iter->second;
}
else
{
category = std::make_shared<PlaybackCategory>(m_device);
m_categories[catKey] = category;
m_currentKey = catKey + 1;
}
return category->play(sound);
}
bool PlaybackManager::resume(unsigned int catKey)
{
auto iter = m_categories.find(catKey);
if(iter != m_categories.end())
{
iter->second->resume();
return true;
}
else
{
return false;
}
}
bool PlaybackManager::pause(unsigned int catKey)
{
auto iter = m_categories.find(catKey);
if(iter != m_categories.end())
{
iter->second->pause();
return true;
}
else
{
return false;
}
}
float PlaybackManager::getVolume(unsigned int catKey)
{
auto iter = m_categories.find(catKey);
if(iter != m_categories.end())
{
return iter->second->getVolume();
}
else
{
return -1.0;
}
}
bool PlaybackManager::setVolume(float volume, unsigned int catKey)
{
auto iter = m_categories.find(catKey);
if(iter != m_categories.end())
{
iter->second->setVolume(volume);
return true;
}
else
{
return false;
}
}
bool PlaybackManager::stop(unsigned int catKey)
{
auto iter = m_categories.find(catKey);
if(iter != m_categories.end())
{
iter->second->stop();
return true;
}
else
{
return false;
}
}
void PlaybackManager::clean()
{
for(auto cat : m_categories)
cat.second->cleanHandles();
}
bool PlaybackManager::clean(unsigned int catKey)
{
auto iter = m_categories.find(catKey);
if(iter != m_categories.end())
{
iter->second->cleanHandles();
return true;
}
else
{
return false;
}
}
AUD_NAMESPACE_END
<|endoftext|> |
<commit_before>#ifndef GARBAGECOLLECTOR_HPP_
#define GARBAGECOLLECTOR_HPP_
#include "CL/OpenCL.hpp"
#include <set>
namespace oul {
class GarbageCollector {
public:
void addMemoryObject(cl::Memory *);
void deleteMemoryObject(cl::Memory *);
void deleteAllMemoryObjects();
private:
std::set<cl::Memory *> memoryObjects;
};
}
#endif /* GARBAGECOLLECTOR_HPP_ */
<commit_msg>added some comments to the GC object<commit_after>#ifndef GARBAGECOLLECTOR_HPP_
#define GARBAGECOLLECTOR_HPP_
#include "CL/OpenCL.hpp"
#include <set>
namespace oul {
/**
* The purpose of the garbage collector object is to allow the explicit deletion
* of OpenCL memory objects such as buffers and images. This is useful when you
* want to delete an OpenCL memory object at a specific location in your code
* instead of waiting for the object to reach the end of its scope.
*/
class GarbageCollector {
public:
void addMemoryObject(cl::Memory *);
void deleteMemoryObject(cl::Memory *);
void deleteAllMemoryObjects();
private:
std::set<cl::Memory *> memoryObjects;
};
}
#endif /* GARBAGECOLLECTOR_HPP_ */
<|endoftext|> |
<commit_before>#include <sstream>
#include <istream>
#include <iostream>
#include <algorithm>
#include <cstring>
#include "builtin.hh"
#include "zs_error.hh"
#include "number.hh"
#include "procedure.hh"
#include "lisp_ptr.hh"
#include "eval.hh"
#include "builtin_util.hh"
#include "reader.hh"
#include "printer.hh"
#include "vm.hh"
#include "port.hh"
#include "builtin_boolean.hh"
#include "builtin_char.hh"
#include "builtin_cons.hh"
#include "builtin_equal.hh"
#include "builtin_extra.hh"
#include "builtin_numeric.hh"
#include "builtin_port.hh"
#include "builtin_procedure.hh"
#include "builtin_string.hh"
#include "builtin_symbol.hh"
#include "builtin_syntax.hh"
#include "builtin_vector.hh"
using namespace std;
using namespace Procedure;
namespace {
static const char null_env_symname[] = "null-env-value";
static const char r5rs_env_symname[] = "r5rs-env-value";
static const char interaction_env_symname[] = "interaction-env-value";
static
Lisp_ptr env_pick_2(const char* name){
ZsArgs args{1};
auto num = args[0].get<Number*>();
if(!num){
throw builtin_type_check_failed(name, Ptr_tag::number, args[0]);
}
if(num->type() != Number::Type::integer){
throw zs_error("native func: %s: passed number is not exact integer\n", name);
}
auto ver = num->get<Number::integer_type>();
if(ver != 5l){
throw zs_error("native func: %s: passed number is not 5 (supplied %ld)\n",
name, ver);
}
return vm.frame()->find(intern(vm.symtable(), name));
}
Lisp_ptr env_r5rs(){
return env_pick_2(r5rs_env_symname);
}
Lisp_ptr env_null(){
return env_pick_2(null_env_symname);
}
Lisp_ptr env_interactive(){
ZsArgs args{0};
return vm.frame()->find(intern(vm.symtable(), interaction_env_symname));
}
Lisp_ptr eval_func(){
ZsArgs args{2};
auto env = args[1].get<Env*>();
if(!env){
throw builtin_type_check_failed("eval", Ptr_tag::env, args[1]);
}
auto oldenv = vm.frame();
vm.set_frame(env);
vm.return_value = {oldenv, vm_op_leave_frame, args[0]};
return {};
}
Lisp_ptr load_func(){
ZsArgs args{1};
auto str = args[0].get<String*>();
if(!str){
throw builtin_type_check_failed("load", Ptr_tag::string, args[0]);
}
stringstream f(*str, ios_base::in);
if(!f){
throw zs_error("load error: failed at opening file\n");
}
load(&f);
return Lisp_ptr{true};
}
} //namespace
static const BuiltinFunc builtin_syntax_funcs[] = {
#include "builtin_equal.defs.hh"
#include "builtin_syntax.defs.hh"
};
static const BuiltinFunc builtin_funcs[] = {
{"eval", {
eval_func,
{2, 2, Passing::eval, Returning::code, MoveReturnValue::f}}},
{"scheme-report-environment", {
env_r5rs,
{1}}},
{"null-environment", {
env_null,
{1}}},
{"interaction-environment", {
env_interactive,
{0}}},
{"load", {
load_func,
{1}}},
#include "builtin_boolean.defs.hh"
#include "builtin_char.defs.hh"
#include "builtin_cons.defs.hh"
#include "builtin_numeric.defs.hh"
#include "builtin_port.defs.hh"
#include "builtin_procedure.defs.hh"
#include "builtin_string.defs.hh"
#include "builtin_symbol.defs.hh"
#include "builtin_vector.defs.hh"
};
static const char* builtin_strs[] = {
#include "builtin_cons.strs.hh"
#include "builtin_procedure.strs.hh"
#include "builtin_port.strs.hh"
};
static const BuiltinFunc builtin_extra_funcs[] = {
#include "builtin_extra.defs.hh"
};
static const char* builtin_extra_strs[] = {
#include "builtin_extra.strs.hh"
};
void install_builtin(){
static constexpr auto install_builtin_native = [](const BuiltinFunc& bf){
vm.frame()->local_set(intern(vm.symtable(), bf.name), {&bf.func});
};
static constexpr auto install_builtin_string = [](const char* s){
stringstream ss({s}, ios_base::in);
load(&ss);
};
static constexpr auto install_builtin_symbol = [](const char* name, Lisp_ptr value){
vm.frame()->local_set(intern(vm.symtable(), name), value);
};
// null-environment
for_each(std::begin(builtin_syntax_funcs), std::end(builtin_syntax_funcs),
install_builtin_native);
install_builtin_symbol(null_env_symname, vm.frame());
// r5rs-environment
vm.set_frame(vm.frame()->push());
for_each(std::begin(builtin_funcs), std::end(builtin_funcs),
install_builtin_native);
for_each(std::begin(builtin_strs), std::end(builtin_strs),
install_builtin_string);
install_builtin_symbol(CURRENT_INPUT_PORT_SYMNAME, &std::cin);
install_builtin_symbol(CURRENT_OUTPUT_PORT_SYMNAME, &std::cout);
install_builtin_symbol(r5rs_env_symname, vm.frame());
// interaction-environment
vm.set_frame(vm.frame()->push());
for_each(std::begin(builtin_extra_funcs), std::end(builtin_extra_funcs),
install_builtin_native);
for_each(std::begin(builtin_extra_strs), std::end(builtin_extra_strs),
install_builtin_string);
install_builtin_symbol(interaction_env_symname, vm.frame());
}
const Procedure::NProcedure* find_builtin_nproc(const char* name){
const auto find_func
= [name](const BuiltinFunc& bf){ return strcmp(name, bf.name) == 0; };
auto i = find_if(begin(builtin_syntax_funcs), end(builtin_syntax_funcs), find_func);
if(i != end(builtin_syntax_funcs)) return &(i->func);
i = find_if(begin(builtin_funcs), end(builtin_funcs), find_func);
if(i != end(builtin_funcs)) return &(i->func);
i = find_if(begin(builtin_extra_funcs), end(builtin_extra_funcs), find_func);
if(i != end(builtin_extra_funcs)) return &(i->func);
return nullptr;
}
void load(InputPort* p){
while(1){
auto form = read(*p);
if(!form){
if(!*p){
// cerr << "load error: failed at reading a form. abandoned.\n";
}
break;
}
vm.code.push_back(form);
eval();
if(!vm.return_value_1()){
cerr << "load error: failed at evaluating a form. skipped.\n";
cerr << "\tform: \n";
print(cerr, form);
continue;
}
}
}
<commit_msg>null-environment excludes eq funcs<commit_after>#include <sstream>
#include <istream>
#include <iostream>
#include <algorithm>
#include <cstring>
#include "builtin.hh"
#include "zs_error.hh"
#include "number.hh"
#include "procedure.hh"
#include "lisp_ptr.hh"
#include "eval.hh"
#include "builtin_util.hh"
#include "reader.hh"
#include "printer.hh"
#include "vm.hh"
#include "port.hh"
#include "builtin_boolean.hh"
#include "builtin_char.hh"
#include "builtin_cons.hh"
#include "builtin_equal.hh"
#include "builtin_extra.hh"
#include "builtin_numeric.hh"
#include "builtin_port.hh"
#include "builtin_procedure.hh"
#include "builtin_string.hh"
#include "builtin_symbol.hh"
#include "builtin_syntax.hh"
#include "builtin_vector.hh"
using namespace std;
using namespace Procedure;
namespace {
static const char null_env_symname[] = "null-env-value";
static const char r5rs_env_symname[] = "r5rs-env-value";
static const char interaction_env_symname[] = "interaction-env-value";
static
Lisp_ptr env_pick_2(const char* name){
ZsArgs args{1};
auto num = args[0].get<Number*>();
if(!num){
throw builtin_type_check_failed(name, Ptr_tag::number, args[0]);
}
if(num->type() != Number::Type::integer){
throw zs_error("native func: %s: passed number is not exact integer\n", name);
}
auto ver = num->get<Number::integer_type>();
if(ver != 5l){
throw zs_error("native func: %s: passed number is not 5 (supplied %ld)\n",
name, ver);
}
return vm.frame()->find(intern(vm.symtable(), name));
}
Lisp_ptr env_r5rs(){
return env_pick_2(r5rs_env_symname);
}
Lisp_ptr env_null(){
return env_pick_2(null_env_symname);
}
Lisp_ptr env_interactive(){
ZsArgs args{0};
return vm.frame()->find(intern(vm.symtable(), interaction_env_symname));
}
Lisp_ptr eval_func(){
ZsArgs args{2};
auto env = args[1].get<Env*>();
if(!env){
throw builtin_type_check_failed("eval", Ptr_tag::env, args[1]);
}
auto oldenv = vm.frame();
vm.set_frame(env);
vm.return_value = {oldenv, vm_op_leave_frame, args[0]};
return {};
}
Lisp_ptr load_func(){
ZsArgs args{1};
auto str = args[0].get<String*>();
if(!str){
throw builtin_type_check_failed("load", Ptr_tag::string, args[0]);
}
stringstream f(*str, ios_base::in);
if(!f){
throw zs_error("load error: failed at opening file\n");
}
load(&f);
return Lisp_ptr{true};
}
} //namespace
static const BuiltinFunc builtin_syntax_funcs[] = {
#include "builtin_syntax.defs.hh"
};
static const BuiltinFunc builtin_funcs[] = {
{"eval", {
eval_func,
{2, 2, Passing::eval, Returning::code, MoveReturnValue::f}}},
{"scheme-report-environment", {
env_r5rs,
{1}}},
{"null-environment", {
env_null,
{1}}},
{"interaction-environment", {
env_interactive,
{0}}},
{"load", {
load_func,
{1}}},
#include "builtin_boolean.defs.hh"
#include "builtin_char.defs.hh"
#include "builtin_cons.defs.hh"
#include "builtin_equal.defs.hh"
#include "builtin_numeric.defs.hh"
#include "builtin_port.defs.hh"
#include "builtin_procedure.defs.hh"
#include "builtin_string.defs.hh"
#include "builtin_symbol.defs.hh"
#include "builtin_vector.defs.hh"
};
static const char* builtin_strs[] = {
#include "builtin_cons.strs.hh"
#include "builtin_procedure.strs.hh"
#include "builtin_port.strs.hh"
};
static const BuiltinFunc builtin_extra_funcs[] = {
#include "builtin_extra.defs.hh"
};
static const char* builtin_extra_strs[] = {
#include "builtin_extra.strs.hh"
};
void install_builtin(){
static constexpr auto install_builtin_native = [](const BuiltinFunc& bf){
vm.frame()->local_set(intern(vm.symtable(), bf.name), {&bf.func});
};
static constexpr auto install_builtin_string = [](const char* s){
stringstream ss({s}, ios_base::in);
load(&ss);
};
static constexpr auto install_builtin_symbol = [](const char* name, Lisp_ptr value){
vm.frame()->local_set(intern(vm.symtable(), name), value);
};
// null-environment
for_each(std::begin(builtin_syntax_funcs), std::end(builtin_syntax_funcs),
install_builtin_native);
install_builtin_symbol(null_env_symname, vm.frame());
// r5rs-environment
vm.set_frame(vm.frame()->push());
for_each(std::begin(builtin_funcs), std::end(builtin_funcs),
install_builtin_native);
for_each(std::begin(builtin_strs), std::end(builtin_strs),
install_builtin_string);
install_builtin_symbol(CURRENT_INPUT_PORT_SYMNAME, &std::cin);
install_builtin_symbol(CURRENT_OUTPUT_PORT_SYMNAME, &std::cout);
install_builtin_symbol(r5rs_env_symname, vm.frame());
// interaction-environment
vm.set_frame(vm.frame()->push());
for_each(std::begin(builtin_extra_funcs), std::end(builtin_extra_funcs),
install_builtin_native);
for_each(std::begin(builtin_extra_strs), std::end(builtin_extra_strs),
install_builtin_string);
install_builtin_symbol(interaction_env_symname, vm.frame());
}
const Procedure::NProcedure* find_builtin_nproc(const char* name){
const auto find_func
= [name](const BuiltinFunc& bf){ return strcmp(name, bf.name) == 0; };
auto i = find_if(begin(builtin_syntax_funcs), end(builtin_syntax_funcs), find_func);
if(i != end(builtin_syntax_funcs)) return &(i->func);
i = find_if(begin(builtin_funcs), end(builtin_funcs), find_func);
if(i != end(builtin_funcs)) return &(i->func);
i = find_if(begin(builtin_extra_funcs), end(builtin_extra_funcs), find_func);
if(i != end(builtin_extra_funcs)) return &(i->func);
return nullptr;
}
void load(InputPort* p){
while(1){
auto form = read(*p);
if(!form){
if(!*p){
// cerr << "load error: failed at reading a form. abandoned.\n";
}
break;
}
vm.code.push_back(form);
eval();
if(!vm.return_value_1()){
cerr << "load error: failed at evaluating a form. skipped.\n";
cerr << "\tform: \n";
print(cerr, form);
continue;
}
}
}
<|endoftext|> |
<commit_before>#include "./camera.h"
#include <Eigen/Geometry>
#include <math.h>
Camera::Camera()
: position(0, 0, -1.0f), direction(0, 0, 1), up(0, 1, 0), radius(4.0f),
azimuth(-M_PI / 2.0f), declination(0)
{
projection = createProjection(M_PI / 2.0f, 16.0f / 9.0f, 0.1f, 100.0f);
}
Camera::~Camera()
{
}
Eigen::Matrix4f Camera::createProjection(float fov, float aspectRatio,
float nearPlane, float farPlane)
{
double tanHalfFovy = tan(fov / 2.0);
Eigen::Matrix4f result = Eigen::Matrix4f::Zero();
result(0, 0) = 1.0 / (aspectRatio * tanHalfFovy);
result(1, 1) = 1.0 / (tanHalfFovy);
result(2, 2) = -(farPlane + nearPlane) / (farPlane - nearPlane);
result(3, 2) = -1.0;
result(2, 3) = -(2.0 * farPlane * nearPlane) / (farPlane - nearPlane);
return result;
}
void Camera::moveForward(float distance)
{
position += distance * direction;
}
void Camera::moveBackward(float distance)
{
position -= distance * direction;
}
void Camera::strafeLeft(float distance)
{
auto right = direction.cross(up);
position -= distance * right;
}
void Camera::strafeRight(float distance)
{
auto right = direction.cross(up);
position += distance * right;
}
void Camera::changeAzimuth(float deltaAngle)
{
azimuth += deltaAngle;
update();
}
void Camera::changeDeclination(float deltaAngle)
{
declination += deltaAngle;
update();
}
void Camera::changeRadius(float deltaRadius)
{
radius += deltaRadius;
update();
}
void Camera::update()
{
radius = position.norm();
position = Eigen::Vector3f(cos(azimuth) * cos(declination), sin(declination),
sin(azimuth) * cos(declination)) *
radius;
direction = -position.normalized();
float upDeclination = declination - M_PI / 2.0f;
up = -Eigen::Vector3f(cos(azimuth) * cos(upDeclination), sin(upDeclination),
sin(azimuth) * cos(upDeclination)).normalized();
}
Eigen::Matrix4f Camera::getViewMatrix()
{
auto n = direction.normalized();
auto u = up.cross(n).normalized();
auto v = n.cross(u);
auto e = position;
view << u.x(), u.y(), u.z(), u.dot(e),
v.x(), v.y(), v.z(), v.dot(e),
n.x(), n.y(), n.z(), n.dot(e),
0, 0, 0, 1;
return view;
}
Eigen::Matrix4f Camera::getProjectionMatrix()
{
return projection;
}
Eigen::Vector3f Camera::getPosition()
{
return position;
}
<commit_msg>Implement Camera::changeRadius.<commit_after>#include "./camera.h"
#include <Eigen/Geometry>
#include <math.h>
Camera::Camera()
: position(0, 0, -1.0f), direction(0, 0, 1), up(0, 1, 0), radius(1.0f),
azimuth(-M_PI / 2.0f), declination(0)
{
projection = createProjection(M_PI / 2.0f, 16.0f / 9.0f, 0.1f, 100.0f);
}
Camera::~Camera()
{
}
Eigen::Matrix4f Camera::createProjection(float fov, float aspectRatio,
float nearPlane, float farPlane)
{
double tanHalfFovy = tan(fov / 2.0);
Eigen::Matrix4f result = Eigen::Matrix4f::Zero();
result(0, 0) = 1.0 / (aspectRatio * tanHalfFovy);
result(1, 1) = 1.0 / (tanHalfFovy);
result(2, 2) = -(farPlane + nearPlane) / (farPlane - nearPlane);
result(3, 2) = -1.0;
result(2, 3) = -(2.0 * farPlane * nearPlane) / (farPlane - nearPlane);
return result;
}
void Camera::moveForward(float distance)
{
position += distance * direction;
}
void Camera::moveBackward(float distance)
{
position -= distance * direction;
}
void Camera::strafeLeft(float distance)
{
auto right = direction.cross(up);
position -= distance * right;
}
void Camera::strafeRight(float distance)
{
auto right = direction.cross(up);
position += distance * right;
}
void Camera::changeAzimuth(float deltaAngle)
{
azimuth += deltaAngle;
update();
}
void Camera::changeDeclination(float deltaAngle)
{
declination += deltaAngle;
update();
}
void Camera::changeRadius(float deltaRadius)
{
radius += deltaRadius;
position = position.normalized() * radius;
update();
}
void Camera::update()
{
radius = position.norm();
position = Eigen::Vector3f(cos(azimuth) * cos(declination), sin(declination),
sin(azimuth) * cos(declination)) *
radius;
direction = -position.normalized();
float upDeclination = declination - M_PI / 2.0f;
up = -Eigen::Vector3f(cos(azimuth) * cos(upDeclination), sin(upDeclination),
sin(azimuth) * cos(upDeclination)).normalized();
}
Eigen::Matrix4f Camera::getViewMatrix()
{
auto n = direction.normalized();
auto u = up.cross(n).normalized();
auto v = n.cross(u);
auto e = position;
view << u.x(), u.y(), u.z(), u.dot(e),
v.x(), v.y(), v.z(), v.dot(e),
n.x(), n.y(), n.z(), n.dot(e),
0, 0, 0, 1;
return view;
}
Eigen::Matrix4f Camera::getProjectionMatrix()
{
return projection;
}
Eigen::Vector3f Camera::getPosition()
{
return position;
}
<|endoftext|> |
<commit_before>// Authors: see AUTHORS.md at project root.
// CopyPolicy: released under the terms of the LGPLv2.1, see LICENSE at project root.
// URL: https://github.com/asrob-uc3m/robotDevastation
#include "YarpNetworkManager.hpp"
#include <sstream>
#include <cstring> // strcmp()
#include <yarp/os/Network.h>
#include <ColorDebug.hpp>
#include "Vocabs.hpp"
//-- Initialize static members
rd::YarpNetworkManager * rd::YarpNetworkManager::uniqueInstance = NULL;
const std::string rd::YarpNetworkManager::id = "YARP";
const int rd::YarpNetworkManager::KEEPALIVE_RATE_MS = 1000;
bool rd::YarpNetworkManager::RegisterManager()
{
if (uniqueInstance == NULL)
{
uniqueInstance = new YarpNetworkManager();
}
return Register( uniqueInstance, id);
}
rd::YarpNetworkManager::YarpNetworkManager() : RateThread(KEEPALIVE_RATE_MS)
{
started = false;
}
void rd::YarpNetworkManager::run()
{
keepAlive();
}
rd::YarpNetworkManager::~YarpNetworkManager()
{
uniqueInstance = NULL;
}
bool rd::YarpNetworkManager::start()
{
if (player.getId() == -1)
{
CD_ERROR("NetworkManager not initialized, player id not set\n");
return false;
}
if (started)
{
CD_ERROR("NetworkManager already started\n");
return false;
}
yarp::os::Network::initMinimum();
if ( ! yarp::os::Network::checkNetwork() )
{
CD_INFO_NO_HEADER("Checking for yarp network... ");
CD_ERROR_NO_HEADER("[fail]\n");
CD_INFO_NO_HEADER("Found no yarp network to connect to rdServer (try running \"yarpserver &\"), bye!\n");
return false;
}
//-- Open the rpcClient port with this player's id
std::ostringstream rpc_str;
rpc_str << "/robotDevastation/";
rpc_str << player.getId();
rpc_str << "/rdServer/rpc:c";
if( ! rpcClient.open( rpc_str.str() ) )
{
CD_ERROR("Could not open '%s'. Bye!\n",rpc_str.str().c_str());
return false;
}
//-- Open the callback port with this player's id
std::ostringstream callback_str;
callback_str << "/robotDevastation/";
callback_str << player.getId();
callback_str << "/rdServer/info:i";
if( ! callbackPort.open( callback_str.str() ) )
{
CD_ERROR("Could not open '%s'. Bye!\n",callback_str.str().c_str());
return false;
}
//-- Connect robotDevastation RpcClient to rdServer RpcServer
std::string rdServerRpcS("/rdServer/rpc:s");
if( ! yarp::os::Network::connect( rpc_str.str() , rdServerRpcS ) )
{
CD_INFO_NO_HEADER("Checking for rdServer ports... ");
CD_ERROR_NO_HEADER("[fail]\n");
CD_INFO_NO_HEADER("Could not connect to rdServer '%s' port (try running \"rdServer &\"), bye!\n",rdServerRpcS.c_str());
return false;
}
//-- Connect from rdServer info to robotDevastation callbackPort
std::string rdServerInfoO("/rdServer/info:o");
if ( ! yarp::os::Network::connect( rdServerInfoO, callback_str.str() ))
{
CD_INFO_NO_HEADER("Checking for rdServer ports... ");
CD_ERROR_NO_HEADER("[fail]\n");
CD_INFO_NO_HEADER("Could not connect from rdServer '%s' port (try running \"rdServer &\"), bye!\n",rdServerInfoO.c_str());
return false;
}
CD_INFO_NO_HEADER("Checking for rdServer ports... ");
CD_SUCCESS_NO_HEADER("[ok]\n");
callbackPort.useCallback(*this);
RateThread::start();
started = true;
return true;
}
void rd::YarpNetworkManager::onRead(yarp::os::Bottle &b)
{
//CD_INFO("Got %s\n", b.toString().c_str());
if ((b.get(0).asString() == "players")||(b.get(0).asVocab() == VOCAB_RD_PLAYERS)) { // players //
//CD_INFO("Number of players: %d\n",b.size()-1); // -1 because of vocab.
std::vector< Player > players;
for (int i = 1; i < b.size(); i++)
{
Player rdPlayer(b.get(i).asList()->get(0).asInt(),
b.get(i).asList()->get(1).asString().c_str(),
b.get(i).asList()->get(2).asInt(),
b.get(i).asList()->get(3).asInt(),
b.get(i).asList()->get(4).asInt(),
b.get(i).asList()->get(5).asInt()
);
players.push_back(rdPlayer);
}
//-- Notify listeners
for (std::vector<NetworkEventListener *>::iterator it = listeners.begin(); it != listeners.end(); ++it)
{
(*it)->onDataArrived(players);
}
}
else
{
CD_ERROR("What?\n");
}
}
bool rd::YarpNetworkManager::stop()
{
if (!started)
{
CD_ERROR("Already stopped\n");
return false;
}
RateThread::askToStop();
rpcClient.close();
callbackPort.disableCallback();
callbackPort.interrupt();
callbackPort.close();
yarp::os::NetworkBase::finiMinimum();
started = false;
return true;
}
bool rd::YarpNetworkManager::isStopped() const
{
return !started;
}
bool rd::YarpNetworkManager::configure(const std::string & parameter, const Player & value)
{
if (parameter.compare("player") == 0)
{
player = value;
return true;
}
return NetworkManager::configure(parameter, value);
}
bool rd::YarpNetworkManager::sendPlayerHit(const Player & player, int damage)
{
if (!started)
{
CD_ERROR("NetworkManager has not been started\n");
return false;
}
//-- Send a message to the server with the player Id and the damage done:
yarp::os::Bottle msg_player_hit, response;
msg_player_hit.addVocab(VOCAB_RD_HIT);
msg_player_hit.addInt(player.getId());
msg_player_hit.addInt(damage);
rpcClient.write(msg_player_hit,response);
CD_INFO("rdServer response from hit: %s\n",response.toString().c_str());
//-- Check response
if (std::strcmp(response.toString().c_str(), "[ok]") == 0)
return true;
else
return false;
}
bool rd::YarpNetworkManager::login()
{
if (!started)
{
CD_WARNING("NetworkManager has not been started\n");
if(!start())
{
CD_ERROR("NetworkManager could not be started for player %d\n", player.getId() );
return false;
}
}
//-- Start network system
std::stringstream ss;
ss << player.getId();
//-- Send login message
yarp::os::Bottle msgRdPlayer,res;
msgRdPlayer.addVocab(VOCAB_RD_LOGIN);
msgRdPlayer.addInt(player.getId());
msgRdPlayer.addString(player.getName().c_str());
msgRdPlayer.addInt(player.getTeamId());
rpcClient.write(msgRdPlayer,res);
CD_INFO("rdServer response from login: %s\n",res.toString().c_str());
//-- Check response
if (std::strcmp(res.toString().c_str(), "[ok]") == 0)
return true;
else
return false;
}
bool rd::YarpNetworkManager::logout()
{
if (!started)
{
CD_ERROR("NetworkManager has not been started\n");
return false;
}
CD_INFO("Logout...\n");
yarp::os::Bottle msgRdPlayer,res;
msgRdPlayer.addVocab(VOCAB_RD_LOGOUT);
msgRdPlayer.addInt(player.getId());
rpcClient.write(msgRdPlayer,res);
CD_INFO("rdServer response from logout: %s\n",res.toString().c_str());
//-- Check response
if (std::strcmp(res.toString().c_str(), "[ok]") == 0)
{
CD_SUCCESS("Logout ok\n");
return true;
}
else
{
CD_ERROR("Logout failed\n");
return false;
}
}
bool rd::YarpNetworkManager::keepAlive()
{
if (!started)
{
CD_ERROR("NetworkManager has not been started\n");
return false;
}
CD_INFO("Keep alive...\n");
yarp::os::Bottle msgRdPlayer,res;
msgRdPlayer.addVocab(VOCAB_RD_KEEPALIVE);
msgRdPlayer.addInt(player.getId());
rpcClient.write(msgRdPlayer,res);
//-- Check response
if (std::strcmp(res.toString().c_str(), "[ok]") == 0)
{
return true;
}
else
{
CD_ERROR("Keep alive failed\n");
return false;
}
}
<commit_msg>astyle<commit_after>// Authors: see AUTHORS.md at project root.
// CopyPolicy: released under the terms of the LGPLv2.1, see LICENSE at project root.
// URL: https://github.com/asrob-uc3m/robotDevastation
#include "YarpNetworkManager.hpp"
#include <sstream>
#include <cstring> // strcmp()
#include <yarp/os/Network.h>
#include <ColorDebug.hpp>
#include "Vocabs.hpp"
//-- Initialize static members
rd::YarpNetworkManager * rd::YarpNetworkManager::uniqueInstance = NULL;
const std::string rd::YarpNetworkManager::id = "YARP";
const int rd::YarpNetworkManager::KEEPALIVE_RATE_MS = 1000;
bool rd::YarpNetworkManager::RegisterManager()
{
if (uniqueInstance == NULL)
{
uniqueInstance = new YarpNetworkManager();
}
return Register( uniqueInstance, id);
}
rd::YarpNetworkManager::YarpNetworkManager() : RateThread(KEEPALIVE_RATE_MS)
{
started = false;
}
void rd::YarpNetworkManager::run()
{
keepAlive();
}
rd::YarpNetworkManager::~YarpNetworkManager()
{
uniqueInstance = NULL;
}
bool rd::YarpNetworkManager::start()
{
if (player.getId() == -1)
{
CD_ERROR("NetworkManager not initialized, player id not set\n");
return false;
}
if (started)
{
CD_ERROR("NetworkManager already started\n");
return false;
}
yarp::os::Network::initMinimum();
if ( ! yarp::os::Network::checkNetwork() )
{
CD_INFO_NO_HEADER("Checking for yarp network... ");
CD_ERROR_NO_HEADER("[fail]\n");
CD_INFO_NO_HEADER("Found no yarp network to connect to rdServer (try running \"yarpserver &\"), bye!\n");
return false;
}
//-- Open the rpcClient port with this player's id
std::ostringstream rpc_str;
rpc_str << "/robotDevastation/";
rpc_str << player.getId();
rpc_str << "/rdServer/rpc:c";
if( ! rpcClient.open( rpc_str.str() ) )
{
CD_ERROR("Could not open '%s'. Bye!\n",rpc_str.str().c_str());
return false;
}
//-- Open the callback port with this player's id
std::ostringstream callback_str;
callback_str << "/robotDevastation/";
callback_str << player.getId();
callback_str << "/rdServer/info:i";
if( ! callbackPort.open( callback_str.str() ) )
{
CD_ERROR("Could not open '%s'. Bye!\n",callback_str.str().c_str());
return false;
}
//-- Connect robotDevastation RpcClient to rdServer RpcServer
std::string rdServerRpcS("/rdServer/rpc:s");
if( ! yarp::os::Network::connect( rpc_str.str() , rdServerRpcS ) )
{
CD_INFO_NO_HEADER("Checking for rdServer ports... ");
CD_ERROR_NO_HEADER("[fail]\n");
CD_INFO_NO_HEADER("Could not connect to rdServer '%s' port (try running \"rdServer &\"), bye!\n",rdServerRpcS.c_str());
return false;
}
//-- Connect from rdServer info to robotDevastation callbackPort
std::string rdServerInfoO("/rdServer/info:o");
if ( ! yarp::os::Network::connect( rdServerInfoO, callback_str.str() ))
{
CD_INFO_NO_HEADER("Checking for rdServer ports... ");
CD_ERROR_NO_HEADER("[fail]\n");
CD_INFO_NO_HEADER("Could not connect from rdServer '%s' port (try running \"rdServer &\"), bye!\n",rdServerInfoO.c_str());
return false;
}
CD_INFO_NO_HEADER("Checking for rdServer ports... ");
CD_SUCCESS_NO_HEADER("[ok]\n");
callbackPort.useCallback(*this);
RateThread::start();
started = true;
return true;
}
void rd::YarpNetworkManager::onRead(yarp::os::Bottle &b)
{
//CD_INFO("Got %s\n", b.toString().c_str());
if ((b.get(0).asString() == "players")||(b.get(0).asVocab() == VOCAB_RD_PLAYERS)) { // players //
//CD_INFO("Number of players: %d\n",b.size()-1); // -1 because of vocab.
std::vector< Player > players;
for (int i = 1; i < b.size(); i++)
{
Player rdPlayer(b.get(i).asList()->get(0).asInt(),
b.get(i).asList()->get(1).asString().c_str(),
b.get(i).asList()->get(2).asInt(),
b.get(i).asList()->get(3).asInt(),
b.get(i).asList()->get(4).asInt(),
b.get(i).asList()->get(5).asInt()
);
players.push_back(rdPlayer);
}
//-- Notify listeners
for (std::vector<NetworkEventListener *>::iterator it = listeners.begin(); it != listeners.end(); ++it)
{
(*it)->onDataArrived(players);
}
}
else
{
CD_ERROR("What?\n");
}
}
bool rd::YarpNetworkManager::stop()
{
if (!started)
{
CD_ERROR("Already stopped\n");
return false;
}
RateThread::askToStop();
rpcClient.close();
callbackPort.disableCallback();
callbackPort.interrupt();
callbackPort.close();
yarp::os::NetworkBase::finiMinimum();
started = false;
return true;
}
bool rd::YarpNetworkManager::isStopped() const
{
return !started;
}
bool rd::YarpNetworkManager::configure(const std::string & parameter, const Player & value)
{
if (parameter.compare("player") == 0)
{
player = value;
return true;
}
return NetworkManager::configure(parameter, value);
}
bool rd::YarpNetworkManager::sendPlayerHit(const Player & player, int damage)
{
if (!started)
{
CD_ERROR("NetworkManager has not been started\n");
return false;
}
//-- Send a message to the server with the player Id and the damage done:
yarp::os::Bottle msg_player_hit, response;
msg_player_hit.addVocab(VOCAB_RD_HIT);
msg_player_hit.addInt(player.getId());
msg_player_hit.addInt(damage);
rpcClient.write(msg_player_hit,response);
CD_INFO("rdServer response from hit: %s\n",response.toString().c_str());
//-- Check response
if (std::strcmp(response.toString().c_str(), "[ok]") == 0)
return true;
else
return false;
}
bool rd::YarpNetworkManager::login()
{
if (!started)
{
CD_WARNING("NetworkManager has not been started\n");
if( ! start() )
{
CD_ERROR("NetworkManager could not be started for player %d\n", player.getId() );
return false;
}
}
//-- Start network system
std::stringstream ss;
ss << player.getId();
//-- Send login message
yarp::os::Bottle msgRdPlayer,res;
msgRdPlayer.addVocab(VOCAB_RD_LOGIN);
msgRdPlayer.addInt(player.getId());
msgRdPlayer.addString(player.getName().c_str());
msgRdPlayer.addInt(player.getTeamId());
rpcClient.write(msgRdPlayer,res);
CD_INFO("rdServer response from login: %s\n",res.toString().c_str());
//-- Check response
if (std::strcmp(res.toString().c_str(), "[ok]") == 0)
return true;
else
return false;
}
bool rd::YarpNetworkManager::logout()
{
if (!started)
{
CD_ERROR("NetworkManager has not been started\n");
return false;
}
CD_INFO("Logout...\n");
yarp::os::Bottle msgRdPlayer,res;
msgRdPlayer.addVocab(VOCAB_RD_LOGOUT);
msgRdPlayer.addInt(player.getId());
rpcClient.write(msgRdPlayer,res);
CD_INFO("rdServer response from logout: %s\n",res.toString().c_str());
//-- Check response
if (std::strcmp(res.toString().c_str(), "[ok]") == 0)
{
CD_SUCCESS("Logout ok\n");
return true;
}
else
{
CD_ERROR("Logout failed\n");
return false;
}
}
bool rd::YarpNetworkManager::keepAlive()
{
if (!started)
{
CD_ERROR("NetworkManager has not been started\n");
return false;
}
CD_INFO("Keep alive...\n");
yarp::os::Bottle msgRdPlayer,res;
msgRdPlayer.addVocab(VOCAB_RD_KEEPALIVE);
msgRdPlayer.addInt(player.getId());
rpcClient.write(msgRdPlayer,res);
//-- Check response
if (std::strcmp(res.toString().c_str(), "[ok]") == 0)
{
return true;
}
else
{
CD_ERROR("Keep alive failed\n");
return false;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) 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.
*/
/**
* \file opt_dead_code.cpp
*
* Eliminates dead assignments and variable declarations from the code.
*/
#include "ir.h"
#include "ir_visitor.h"
#include "ir_variable_refcount.h"
#include "glsl_types.h"
#include "main/hash_table.h"
static bool debug = false;
/**
* Do a dead code pass over instructions and everything that instructions
* references.
*
* Note that this will remove assignments to globals, so it is not suitable
* for usage on an unlinked instruction stream.
*/
bool
do_dead_code(exec_list *instructions, bool uniform_locations_assigned)
{
ir_variable_refcount_visitor v;
bool progress = false;
v.run(instructions);
struct hash_entry *e;
hash_table_foreach(v.ht, e) {
ir_variable_refcount_entry *entry = (ir_variable_refcount_entry *)e->data;
/* Since each assignment is a reference, the refereneced count must be
* greater than or equal to the assignment count. If they are equal,
* then all of the references are assignments, and the variable is
* dead.
*
* Note that if the variable is neither assigned nor referenced, both
* counts will be zero and will be caught by the equality test.
*/
assert(entry->referenced_count >= entry->assigned_count);
if (debug) {
printf("%s@%p: %d refs, %d assigns, %sdeclared in our scope\n",
entry->var->name, (void *) entry->var,
entry->referenced_count, entry->assigned_count,
entry->declaration ? "" : "not ");
}
if ((entry->referenced_count > entry->assigned_count)
|| !entry->declaration)
continue;
if (entry->assign) {
/* Remove a single dead assignment to the variable we found.
* Don't do so if it's a shader or function output, though.
*/
if (entry->var->mode != ir_var_function_out &&
entry->var->mode != ir_var_function_inout &&
entry->var->mode != ir_var_shader_out) {
entry->assign->remove();
progress = true;
if (debug) {
printf("Removed assignment to %s@%p\n",
entry->var->name, (void *) entry->var);
}
}
} else {
/* If there are no assignments or references to the variable left,
* then we can remove its declaration.
*/
/* uniform initializers are precious, and could get used by another
* stage. Also, once uniform locations have been assigned, the
* declaration cannot be deleted.
*
* Also, GL_ARB_uniform_buffer_object says that std140
* uniforms will not be eliminated. Since we always do
* std140, just don't eliminate uniforms in UBOs.
*/
if (entry->var->mode == ir_var_uniform &&
(uniform_locations_assigned ||
entry->var->constant_value ||
entry->var->is_in_uniform_block()))
continue;
entry->var->remove();
progress = true;
if (debug) {
printf("Removed declaration of %s@%p\n",
entry->var->name, (void *) entry->var);
}
}
}
return progress;
}
/**
* Does a dead code pass on the functions present in the instruction stream.
*
* This is suitable for use while the program is not linked, as it will
* ignore variable declarations (and the assignments to them) for variables
* with global scope.
*/
bool
do_dead_code_unlinked(exec_list *instructions)
{
bool progress = false;
foreach_iter(exec_list_iterator, iter, *instructions) {
ir_instruction *ir = (ir_instruction *)iter.get();
ir_function *f = ir->as_function();
if (f) {
foreach_iter(exec_list_iterator, sigiter, *f) {
ir_function_signature *sig =
(ir_function_signature *) sigiter.get();
/* The setting of the uniform_locations_assigned flag here is
* irrelevent. If there is a uniform declaration encountered
* inside the body of the function, something has already gone
* terribly, terribly wrong.
*/
if (do_dead_code(&sig->body, false))
progress = true;
}
}
}
return progress;
}
<commit_msg>glsl: Allow elimination of uniform block members<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) 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.
*/
/**
* \file opt_dead_code.cpp
*
* Eliminates dead assignments and variable declarations from the code.
*/
#include "ir.h"
#include "ir_visitor.h"
#include "ir_variable_refcount.h"
#include "glsl_types.h"
#include "main/hash_table.h"
static bool debug = false;
/**
* Do a dead code pass over instructions and everything that instructions
* references.
*
* Note that this will remove assignments to globals, so it is not suitable
* for usage on an unlinked instruction stream.
*/
bool
do_dead_code(exec_list *instructions, bool uniform_locations_assigned)
{
ir_variable_refcount_visitor v;
bool progress = false;
v.run(instructions);
struct hash_entry *e;
hash_table_foreach(v.ht, e) {
ir_variable_refcount_entry *entry = (ir_variable_refcount_entry *)e->data;
/* Since each assignment is a reference, the refereneced count must be
* greater than or equal to the assignment count. If they are equal,
* then all of the references are assignments, and the variable is
* dead.
*
* Note that if the variable is neither assigned nor referenced, both
* counts will be zero and will be caught by the equality test.
*/
assert(entry->referenced_count >= entry->assigned_count);
if (debug) {
printf("%s@%p: %d refs, %d assigns, %sdeclared in our scope\n",
entry->var->name, (void *) entry->var,
entry->referenced_count, entry->assigned_count,
entry->declaration ? "" : "not ");
}
if ((entry->referenced_count > entry->assigned_count)
|| !entry->declaration)
continue;
if (entry->assign) {
/* Remove a single dead assignment to the variable we found.
* Don't do so if it's a shader or function output, though.
*/
if (entry->var->mode != ir_var_function_out &&
entry->var->mode != ir_var_function_inout &&
entry->var->mode != ir_var_shader_out) {
entry->assign->remove();
progress = true;
if (debug) {
printf("Removed assignment to %s@%p\n",
entry->var->name, (void *) entry->var);
}
}
} else {
/* If there are no assignments or references to the variable left,
* then we can remove its declaration.
*/
/* uniform initializers are precious, and could get used by another
* stage. Also, once uniform locations have been assigned, the
* declaration cannot be deleted.
*/
if (entry->var->mode == ir_var_uniform &&
(uniform_locations_assigned ||
entry->var->constant_value))
continue;
entry->var->remove();
progress = true;
if (debug) {
printf("Removed declaration of %s@%p\n",
entry->var->name, (void *) entry->var);
}
}
}
return progress;
}
/**
* Does a dead code pass on the functions present in the instruction stream.
*
* This is suitable for use while the program is not linked, as it will
* ignore variable declarations (and the assignments to them) for variables
* with global scope.
*/
bool
do_dead_code_unlinked(exec_list *instructions)
{
bool progress = false;
foreach_iter(exec_list_iterator, iter, *instructions) {
ir_instruction *ir = (ir_instruction *)iter.get();
ir_function *f = ir->as_function();
if (f) {
foreach_iter(exec_list_iterator, sigiter, *f) {
ir_function_signature *sig =
(ir_function_signature *) sigiter.get();
/* The setting of the uniform_locations_assigned flag here is
* irrelevent. If there is a uniform declaration encountered
* inside the body of the function, something has already gone
* terribly, terribly wrong.
*/
if (do_dead_code(&sig->body, false))
progress = true;
}
}
}
return progress;
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2012-2014 Danny Y., Rapptz
// 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 GEARS_STRING_HPP
#define GEARS_STRING_HPP
#include "string/case.hpp"
#include "string/predicate.hpp"
#include "string/literals.hpp"
#include "string/replace.hpp"
#include "string/trim.hpp"
#include "string/transforms.hpp"
#include "string/builder.hpp"
#endif // GEARS_STRING_HPP
<commit_msg>Begin documentation of string module<commit_after>// The MIT License (MIT)
// Copyright (c) 2012-2014 Danny Y., Rapptz
// 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 GEARS_STRING_HPP
#define GEARS_STRING_HPP
#include "string/case.hpp"
#include "string/predicate.hpp"
#include "string/literals.hpp"
#include "string/replace.hpp"
#include "string/trim.hpp"
#include "string/transforms.hpp"
#include "string/builder.hpp"
/**
* @defgroup string String module
* @brief Provides string algorithms
* @details This module provides string algorithms to help
* with the lack of high level algorithms with `std::string`.
* All the functions do not modify the string in-place and instead
* return a new string.
*
* Under the `<gears/string/literals.hpp>` header there is a
* user defined literal `_s` to help construct a string easier.
* It's provided for all `basic_string` types, e.g. `std::wstring`,
* `std::string`, etc.
*
* @code
* using namespace gears::string::literals; // required
* auto str = "hello world"_s; // decltype(str) is std::string
* @endcode
*/
#endif // GEARS_STRING_HPP
<|endoftext|> |
<commit_before>/*
* This file is part of the CitizenFX project - http://citizen.re/
*
* See LICENSE and MENTIONS in the root of the source tree for information
* regarding licensing.
*/
#include "Hooking.Patterns.h"
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <algorithm>
#include "string_view.hpp"
#if PATTERNS_USE_HINTS
#include <map>
#endif
#if PATTERNS_USE_HINTS
// from boost someplace
template <std::uint64_t FnvPrime, std::uint64_t OffsetBasis>
struct basic_fnv_1
{
std::uint64_t operator()(libcxx_strviewclone::string_view text) const
{
std::uint64_t hash = OffsetBasis;
for (auto it : text)
{
hash *= FnvPrime;
hash ^= it;
}
return hash;
}
};
const std::uint64_t fnv_prime = 1099511628211u;
const std::uint64_t fnv_offset_basis = 14695981039346656037u;
typedef basic_fnv_1<fnv_prime, fnv_offset_basis> fnv_1;
#endif
namespace hook
{
ptrdiff_t baseAddressDifference;
// sets the base to the process main base
void set_base()
{
set_base((uintptr_t)GetModuleHandle(nullptr));
}
#if PATTERNS_USE_HINTS
static std::multimap<uint64_t, uintptr_t> g_hints;
#endif
static void TransformPattern(libcxx_strviewclone::string_view pattern, std::string& data, std::string& mask)
{
uint8_t tempDigit = 0;
bool tempFlag = false;
auto tol = [] (char ch) -> uint8_t
{
if (ch >= 'A' && ch <= 'F') return uint8_t(ch - 'A' + 10);
if (ch >= 'a' && ch <= 'f') return uint8_t(ch - 'a' + 10);
return uint8_t(ch - '0');
};
for (auto ch : pattern)
{
if (ch == ' ')
{
continue;
}
else if (ch == '?')
{
data.push_back(0);
mask.push_back('?');
}
else if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))
{
uint8_t thisDigit = tol(ch);
if (!tempFlag)
{
tempDigit = thisDigit << 4;
tempFlag = true;
}
else
{
tempDigit |= thisDigit;
tempFlag = false;
data.push_back(tempDigit);
mask.push_back('x');
}
}
}
}
class executable_meta
{
private:
uintptr_t m_begin;
uintptr_t m_end;
public:
template<typename TReturn, typename TOffset>
TReturn* getRVA(TOffset rva)
{
return (TReturn*)(m_begin + rva);
}
explicit executable_meta(void* module)
: m_begin((uintptr_t)module), m_end(0)
{
static auto getSection = [](const PIMAGE_NT_HEADERS nt_headers, unsigned section) -> PIMAGE_SECTION_HEADER
{
return reinterpret_cast<PIMAGE_SECTION_HEADER>(
(UCHAR*)nt_headers->OptionalHeader.DataDirectory +
nt_headers->OptionalHeader.NumberOfRvaAndSizes * sizeof(IMAGE_DATA_DIRECTORY) +
section * sizeof(IMAGE_SECTION_HEADER));
};
PIMAGE_DOS_HEADER dosHeader = getRVA<IMAGE_DOS_HEADER>(0);
PIMAGE_NT_HEADERS ntHeader = getRVA<IMAGE_NT_HEADERS>(dosHeader->e_lfanew);
for (int i = 0; i < ntHeader->FileHeader.NumberOfSections; i++)
{
auto sec = getSection(ntHeader, i);
auto secSize = sec->SizeOfRawData != 0 ? sec->SizeOfRawData : sec->Misc.VirtualSize;
if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE)
m_end = m_begin + sec->VirtualAddress + secSize;
if ((i == ntHeader->FileHeader.NumberOfSections - 1) && m_end == 0)
m_end = m_begin + sec->PointerToRawData + secSize;
}
}
executable_meta(uintptr_t begin, uintptr_t end)
: m_begin(begin), m_end(end)
{
}
inline uintptr_t begin() const { return m_begin; }
inline uintptr_t end() const { return m_end; }
};
void pattern::Initialize(const char* pattern, size_t length)
{
// get the hash for the base pattern
#if PATTERNS_USE_HINTS
m_hash = fnv_1()(libcxx_strviewclone::string_view(pattern, length));
#endif
// transform the base pattern from IDA format to canonical format
TransformPattern(libcxx_strviewclone::string_view(pattern, length), m_bytes, m_mask);
m_size = m_mask.size();
#if PATTERNS_USE_HINTS
// if there's hints, try those first
if (m_module == GetModuleHandle(nullptr))
{
auto range = g_hints.equal_range(m_hash);
if (range.first != range.second)
{
std::for_each(range.first, range.second, [&] (const std::pair<uint64_t, uintptr_t>& hint)
{
ConsiderMatch(hint.second);
});
// if the hints succeeded, we don't need to do anything more
if (!m_matches.empty())
{
m_matched = true;
return;
}
}
}
#endif
}
void pattern::EnsureMatches(uint32_t maxCount)
{
if (m_matched)
{
return;
}
// scan the executable for code
executable_meta executable = m_rangeStart != 0 && m_rangeEnd != 0 ? executable_meta(m_rangeStart, m_rangeEnd) : executable_meta(m_module);
auto matchSuccess = [&] (uintptr_t address)
{
#if PATTERNS_USE_HINTS
g_hints.emplace(m_hash, address);
#else
(void)address;
#endif
return (m_matches.size() == maxCount);
};
const uint8_t* pattern = reinterpret_cast<const uint8_t*>(m_bytes.c_str());
const char* mask = m_mask.c_str();
size_t lastWild = m_mask.find_last_of('?');
ptrdiff_t Last[256];
std::fill(std::begin(Last), std::end(Last), lastWild == std::string::npos ? -1 : static_cast<ptrdiff_t>(lastWild) );
for ( ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(m_size); ++i )
{
if ( Last[ pattern[i] ] < i )
{
Last[ pattern[i] ] = i;
}
}
for (uintptr_t i = executable.begin(), end = executable.end() - m_size; i <= end;)
{
uint8_t* ptr = reinterpret_cast<uint8_t*>(i);
ptrdiff_t j = m_size - 1;
while((j >= 0) && (mask[j] == '?' || pattern[j] == ptr[j])) j--;
if(j < 0)
{
m_matches.emplace_back(ptr);
if (matchSuccess(i))
{
break;
}
i++;
}
else i += std::max(1, j - Last[ ptr[j] ]);
}
m_matched = true;
}
bool pattern::ConsiderMatch(uintptr_t offset)
{
const char* pattern = m_bytes.c_str();
const char* mask = m_mask.c_str();
char* ptr = reinterpret_cast<char*>(offset);
for (size_t i = 0; i < m_size; i++)
{
if (mask[i] == '?')
{
continue;
}
if (pattern[i] != ptr[i])
{
return false;
}
}
m_matches.emplace_back(ptr);
return true;
}
#if PATTERNS_USE_HINTS
void pattern::hint(uint64_t hash, uintptr_t address)
{
auto range = g_hints.equal_range(hash);
for (auto it = range.first; it != range.second; it++)
{
if (it->second == address)
{
return;
}
}
g_hints.emplace(hash, address);
}
#endif
}<commit_msg>mp steam exe crash fix<commit_after>/*
* This file is part of the CitizenFX project - http://citizen.re/
*
* See LICENSE and MENTIONS in the root of the source tree for information
* regarding licensing.
*/
#include "Hooking.Patterns.h"
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <algorithm>
#include "string_view.hpp"
#if PATTERNS_USE_HINTS
#include <map>
#endif
#if PATTERNS_USE_HINTS
// from boost someplace
template <std::uint64_t FnvPrime, std::uint64_t OffsetBasis>
struct basic_fnv_1
{
std::uint64_t operator()(libcxx_strviewclone::string_view text) const
{
std::uint64_t hash = OffsetBasis;
for (auto it : text)
{
hash *= FnvPrime;
hash ^= it;
}
return hash;
}
};
const std::uint64_t fnv_prime = 1099511628211u;
const std::uint64_t fnv_offset_basis = 14695981039346656037u;
typedef basic_fnv_1<fnv_prime, fnv_offset_basis> fnv_1;
#endif
namespace hook
{
ptrdiff_t baseAddressDifference;
// sets the base to the process main base
void set_base()
{
set_base((uintptr_t)GetModuleHandle(nullptr));
}
#if PATTERNS_USE_HINTS
static std::multimap<uint64_t, uintptr_t> g_hints;
#endif
static void TransformPattern(libcxx_strviewclone::string_view pattern, std::string& data, std::string& mask)
{
uint8_t tempDigit = 0;
bool tempFlag = false;
auto tol = [] (char ch) -> uint8_t
{
if (ch >= 'A' && ch <= 'F') return uint8_t(ch - 'A' + 10);
if (ch >= 'a' && ch <= 'f') return uint8_t(ch - 'a' + 10);
return uint8_t(ch - '0');
};
for (auto ch : pattern)
{
if (ch == ' ')
{
continue;
}
else if (ch == '?')
{
data.push_back(0);
mask.push_back('?');
}
else if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))
{
uint8_t thisDigit = tol(ch);
if (!tempFlag)
{
tempDigit = thisDigit << 4;
tempFlag = true;
}
else
{
tempDigit |= thisDigit;
tempFlag = false;
data.push_back(tempDigit);
mask.push_back('x');
}
}
}
}
class executable_meta
{
private:
uintptr_t m_begin;
uintptr_t m_end;
public:
template<typename TReturn, typename TOffset>
TReturn* getRVA(TOffset rva)
{
return (TReturn*)(m_begin + rva);
}
explicit executable_meta(void* module)
: m_begin((uintptr_t)module), m_end(0)
{
static auto getSection = [](const PIMAGE_NT_HEADERS nt_headers, unsigned section) -> PIMAGE_SECTION_HEADER
{
return reinterpret_cast<PIMAGE_SECTION_HEADER>(
(UCHAR*)nt_headers->OptionalHeader.DataDirectory +
nt_headers->OptionalHeader.NumberOfRvaAndSizes * sizeof(IMAGE_DATA_DIRECTORY) +
section * sizeof(IMAGE_SECTION_HEADER));
};
PIMAGE_DOS_HEADER dosHeader = getRVA<IMAGE_DOS_HEADER>(0);
PIMAGE_NT_HEADERS ntHeader = getRVA<IMAGE_NT_HEADERS>(dosHeader->e_lfanew);
for (int i = 0; i < ntHeader->FileHeader.NumberOfSections; i++)
{
auto sec = getSection(ntHeader, i);
auto secSize = sec->SizeOfRawData != 0 ? sec->SizeOfRawData : sec->Misc.VirtualSize;
if (sec->Characteristics & IMAGE_SCN_MEM_EXECUTE)
m_end = m_begin + sec->VirtualAddress + secSize;
if ((i == ntHeader->FileHeader.NumberOfSections - 1) && m_end == 0)
m_end = m_begin + sec->PointerToRawData + secSize;
}
}
executable_meta(uintptr_t begin, uintptr_t end)
: m_begin(begin), m_end(end)
{
}
inline uintptr_t begin() const { return m_begin; }
inline uintptr_t end() const { return m_end; }
};
void pattern::Initialize(const char* pattern, size_t length)
{
// get the hash for the base pattern
#if PATTERNS_USE_HINTS
m_hash = fnv_1()(libcxx_strviewclone::string_view(pattern, length));
#endif
// transform the base pattern from IDA format to canonical format
TransformPattern(libcxx_strviewclone::string_view(pattern, length), m_bytes, m_mask);
m_size = m_mask.size();
#if PATTERNS_USE_HINTS
// if there's hints, try those first
if (m_module == GetModuleHandle(nullptr))
{
auto range = g_hints.equal_range(m_hash);
if (range.first != range.second)
{
std::for_each(range.first, range.second, [&] (const std::pair<uint64_t, uintptr_t>& hint)
{
ConsiderMatch(hint.second);
});
// if the hints succeeded, we don't need to do anything more
if (!m_matches.empty())
{
m_matched = true;
return;
}
}
}
#endif
}
void pattern::EnsureMatches(uint32_t maxCount)
{
if (m_matched)
{
return;
}
// scan the executable for code
executable_meta executable = m_rangeStart != 0 && m_rangeEnd != 0 ? executable_meta(m_rangeStart, m_rangeEnd) : executable_meta(m_module);
auto matchSuccess = [&] (uintptr_t address)
{
#if PATTERNS_USE_HINTS
g_hints.emplace(m_hash, address);
#else
(void)address;
#endif
return (m_matches.size() == maxCount);
};
const uint8_t* pattern = reinterpret_cast<const uint8_t*>(m_bytes.c_str());
const char* mask = m_mask.c_str();
size_t lastWild = m_mask.find_last_of('?');
ptrdiff_t Last[256];
std::fill(std::begin(Last), std::end(Last), lastWild == std::string::npos ? -1 : static_cast<ptrdiff_t>(lastWild) );
for ( ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(m_size); ++i )
{
if ( Last[ pattern[i] ] < i )
{
Last[ pattern[i] ] = i;
}
}
__try
{
for (uintptr_t i = executable.begin(), end = executable.end() - m_size; i <= end;)
{
uint8_t* ptr = reinterpret_cast<uint8_t*>(i);
ptrdiff_t j = m_size - 1;
while ((j >= 0) && (mask[j] == '?' || pattern[j] == ptr[j])) j--;
if (j < 0)
{
m_matches.emplace_back(ptr);
if (matchSuccess(i))
{
break;
}
i++;
}
else i += std::max(1, j - Last[ptr[j]]);
}
}
__except ((GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION) ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{ }
m_matched = true;
}
bool pattern::ConsiderMatch(uintptr_t offset)
{
const char* pattern = m_bytes.c_str();
const char* mask = m_mask.c_str();
char* ptr = reinterpret_cast<char*>(offset);
for (size_t i = 0; i < m_size; i++)
{
if (mask[i] == '?')
{
continue;
}
if (pattern[i] != ptr[i])
{
return false;
}
}
m_matches.emplace_back(ptr);
return true;
}
#if PATTERNS_USE_HINTS
void pattern::hint(uint64_t hash, uintptr_t address)
{
auto range = g_hints.equal_range(hash);
for (auto it = range.first; it != range.second; it++)
{
if (it->second == address)
{
return;
}
}
g_hints.emplace(hash, address);
}
#endif
}<|endoftext|> |
<commit_before>#include "analyser_hls.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <mist/config.h>
#include <mist/defines.h>
#include <mist/http_parser.h>
#include <mist/timing.h>
#include <string.h>
#include <sys/sysinfo.h>
void AnalyserHLS::init(Util::Config &conf){
Analyser::init(conf);
JSON::Value opt;
opt["long"] = "reconstruct";
opt["short"] = "R";
opt["arg"] = "string";
opt["default"] = "";
opt["help"] = "Reconstruct TS file from HLS to the given filename";
conf.addOption("reconstruct", opt);
opt.null();
}
void AnalyserHLS::getParts(const std::string &body){
std::stringstream data(body);
std::string line;
uint64_t no = 0;
float durat = 0;
refreshAt = Util::bootSecs() + 10;
while (data.good()){
std::getline(data, line);
if (line.size() && *line.rbegin() == '\r'){line.resize(line.size() - 1);}
if (!line.size()){continue;}
if (line[0] != '#'){
if (line.find("m3u") != std::string::npos){
root = root.link(line);
INFO_MSG("Found a sub-playlist, re-targeting %s", root.getUrl().c_str());
refreshAt = Util::bootSecs();
return;
}
if (!parsedPart || no > parsedPart){
HTTP::URL newURL = root.link(line);
INFO_MSG("Discovered: %s", newURL.getUrl().c_str());
parts.push_back(HLSPart(newURL, no, durat));
}
++no;
}else{
if (line.substr(0, 8) == "#EXTINF:"){durat = atof(line.c_str() + 8) * 1000;}
if (line.substr(0, 22) == "#EXT-X-MEDIA-SEQUENCE:"){no = atoll(line.c_str() + 22);}
if (line.substr(0, 14) == "#EXT-X-ENDLIST"){refreshAt = 0;}
if (line.substr(0, 22) == "#EXT-X-TARGETDURATION:" && refreshAt){
refreshAt = Util::bootSecs() + atoll(line.c_str() + 22) / 2;
}
}
}
}
/// Returns true if we either still have parts to download, or are still refreshing the playlist.
bool AnalyserHLS::isOpen(){
return (*isActive) && (parts.size() || refreshAt);
}
void AnalyserHLS::stop(){
parts.clear();
refreshAt = 0;
}
bool AnalyserHLS::open(const std::string &url){
root = HTTP::URL(url);
if (root.protocol != "http"){
FAIL_MSG("Only http protocol is supported (%s not supported)", root.protocol.c_str());
return false;
}
return true;
}
AnalyserHLS::AnalyserHLS(Util::Config &conf) : Analyser(conf){
if (conf.getString("reconstruct") != ""){
reconstruct.open(conf.getString("reconstruct").c_str());
if (reconstruct.good()){
WARN_MSG("Will reconstruct to %s", conf.getString("reconstruct").c_str());
}
}
hlsTime = 0;
parsedPart = 0;
refreshAt = Util::bootSecs();
}
/// Downloads the given URL into 'H', returns true on success.
/// Makes at most 5 attempts, and will wait no longer than 5 seconds without receiving data.
bool AnalyserHLS::download(const HTTP::URL &link){
if (!link.host.size()){return false;}
INFO_MSG("Retrieving %s", link.getUrl().c_str());
unsigned int loop = 6; // max 5 attempts
while (--loop){// loop while we are unsuccessful
H.Clean();
// Reconnect if needed
if (!conn || link.host != connectedHost || link.getPort() != connectedPort){
conn.close();
connectedHost = link.host;
connectedPort = link.getPort();
conn = Socket::Connection(connectedHost, connectedPort, true);
}
H.url = "/" + link.path;
if (link.port.size()){
H.SetHeader("Host", link.host + ":" + link.port);
}else{
H.SetHeader("Host", link.host);
}
H.SendRequest(conn);
H.Clean();
uint64_t reqTime = Util::bootSecs();
while (conn && Util::bootSecs() < reqTime + 5){
// No data? Wait for a second or so.
if (!conn.spool()){
Util::sleep(1000);
continue;
}
// Data! Check if we can parse it...
if (H.Read(conn)){
return true; // Success!
}
// reset the 5 second timeout
reqTime = Util::bootSecs();
}
if (conn){
FAIL_MSG("Timeout while retrieving %s", link.getUrl().c_str());
return false;
}
Util::sleep(500); // wait a bit before retrying
}
FAIL_MSG("Could not retrieve %s", link.getUrl().c_str());
return false;
}
bool AnalyserHLS::parsePacket(){
while (isOpen()){
// If needed, refresh the playlist
if (refreshAt && Util::bootSecs() >= refreshAt){
if (download(root)){
getParts(H.body);
}else{
FAIL_MSG("Could not refresh playlist!");
return false;
}
}
// If there are parts to download, get one.
if (parts.size()){
HLSPart part = *parts.begin();
parts.pop_front();
if (!download(part.uri)){return false;}
if (H.GetHeader("Content-Length") != ""){
if (H.body.size() != atoi(H.GetHeader("Content-Length").c_str())){
FAIL_MSG("Expected %s bytes of data, but only received %lu.",
H.GetHeader("Content-Length").c_str(), H.body.size());
return false;
}
}
if (H.body.size() % 188){
FAIL_MSG("Expected a multiple of 188 bytes, received %d bytes", H.body.size());
return false;
}
parsedPart = part.no;
hlsTime += part.dur;
mediaTime = (uint64_t)hlsTime;
if (reconstruct.good()){reconstruct << H.body;}
H.Clean();
return true;
}
// Hm. I guess we had no parts to get.
if (refreshAt && refreshAt > Util::bootSecs()){
// We're getting a live stream. Let's wait and check again.
uint32_t sleepSecs = (refreshAt - Util::bootSecs());
INFO_MSG("Sleeping for %lu seconds", sleepSecs);
Util::sleep(sleepSecs * 1000);
}
//The non-live case is already handled in isOpen()
}
return false;
}
<commit_msg>Why was this even in here?<commit_after>#include "analyser_hls.h"
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <mist/config.h>
#include <mist/defines.h>
#include <mist/http_parser.h>
#include <mist/timing.h>
#include <string.h>
void AnalyserHLS::init(Util::Config &conf){
Analyser::init(conf);
JSON::Value opt;
opt["long"] = "reconstruct";
opt["short"] = "R";
opt["arg"] = "string";
opt["default"] = "";
opt["help"] = "Reconstruct TS file from HLS to the given filename";
conf.addOption("reconstruct", opt);
opt.null();
}
void AnalyserHLS::getParts(const std::string &body){
std::stringstream data(body);
std::string line;
uint64_t no = 0;
float durat = 0;
refreshAt = Util::bootSecs() + 10;
while (data.good()){
std::getline(data, line);
if (line.size() && *line.rbegin() == '\r'){line.resize(line.size() - 1);}
if (!line.size()){continue;}
if (line[0] != '#'){
if (line.find("m3u") != std::string::npos){
root = root.link(line);
INFO_MSG("Found a sub-playlist, re-targeting %s", root.getUrl().c_str());
refreshAt = Util::bootSecs();
return;
}
if (!parsedPart || no > parsedPart){
HTTP::URL newURL = root.link(line);
INFO_MSG("Discovered: %s", newURL.getUrl().c_str());
parts.push_back(HLSPart(newURL, no, durat));
}
++no;
}else{
if (line.substr(0, 8) == "#EXTINF:"){durat = atof(line.c_str() + 8) * 1000;}
if (line.substr(0, 22) == "#EXT-X-MEDIA-SEQUENCE:"){no = atoll(line.c_str() + 22);}
if (line.substr(0, 14) == "#EXT-X-ENDLIST"){refreshAt = 0;}
if (line.substr(0, 22) == "#EXT-X-TARGETDURATION:" && refreshAt){
refreshAt = Util::bootSecs() + atoll(line.c_str() + 22) / 2;
}
}
}
}
/// Returns true if we either still have parts to download, or are still refreshing the playlist.
bool AnalyserHLS::isOpen(){
return (*isActive) && (parts.size() || refreshAt);
}
void AnalyserHLS::stop(){
parts.clear();
refreshAt = 0;
}
bool AnalyserHLS::open(const std::string &url){
root = HTTP::URL(url);
if (root.protocol != "http"){
FAIL_MSG("Only http protocol is supported (%s not supported)", root.protocol.c_str());
return false;
}
return true;
}
AnalyserHLS::AnalyserHLS(Util::Config &conf) : Analyser(conf){
if (conf.getString("reconstruct") != ""){
reconstruct.open(conf.getString("reconstruct").c_str());
if (reconstruct.good()){
WARN_MSG("Will reconstruct to %s", conf.getString("reconstruct").c_str());
}
}
hlsTime = 0;
parsedPart = 0;
refreshAt = Util::bootSecs();
}
/// Downloads the given URL into 'H', returns true on success.
/// Makes at most 5 attempts, and will wait no longer than 5 seconds without receiving data.
bool AnalyserHLS::download(const HTTP::URL &link){
if (!link.host.size()){return false;}
INFO_MSG("Retrieving %s", link.getUrl().c_str());
unsigned int loop = 6; // max 5 attempts
while (--loop){// loop while we are unsuccessful
H.Clean();
// Reconnect if needed
if (!conn || link.host != connectedHost || link.getPort() != connectedPort){
conn.close();
connectedHost = link.host;
connectedPort = link.getPort();
conn = Socket::Connection(connectedHost, connectedPort, true);
}
H.url = "/" + link.path;
if (link.port.size()){
H.SetHeader("Host", link.host + ":" + link.port);
}else{
H.SetHeader("Host", link.host);
}
H.SendRequest(conn);
H.Clean();
uint64_t reqTime = Util::bootSecs();
while (conn && Util::bootSecs() < reqTime + 5){
// No data? Wait for a second or so.
if (!conn.spool()){
Util::sleep(1000);
continue;
}
// Data! Check if we can parse it...
if (H.Read(conn)){
return true; // Success!
}
// reset the 5 second timeout
reqTime = Util::bootSecs();
}
if (conn){
FAIL_MSG("Timeout while retrieving %s", link.getUrl().c_str());
return false;
}
Util::sleep(500); // wait a bit before retrying
}
FAIL_MSG("Could not retrieve %s", link.getUrl().c_str());
return false;
}
bool AnalyserHLS::parsePacket(){
while (isOpen()){
// If needed, refresh the playlist
if (refreshAt && Util::bootSecs() >= refreshAt){
if (download(root)){
getParts(H.body);
}else{
FAIL_MSG("Could not refresh playlist!");
return false;
}
}
// If there are parts to download, get one.
if (parts.size()){
HLSPart part = *parts.begin();
parts.pop_front();
if (!download(part.uri)){return false;}
if (H.GetHeader("Content-Length") != ""){
if (H.body.size() != atoi(H.GetHeader("Content-Length").c_str())){
FAIL_MSG("Expected %s bytes of data, but only received %lu.",
H.GetHeader("Content-Length").c_str(), H.body.size());
return false;
}
}
if (H.body.size() % 188){
FAIL_MSG("Expected a multiple of 188 bytes, received %d bytes", H.body.size());
return false;
}
parsedPart = part.no;
hlsTime += part.dur;
mediaTime = (uint64_t)hlsTime;
if (reconstruct.good()){reconstruct << H.body;}
H.Clean();
return true;
}
// Hm. I guess we had no parts to get.
if (refreshAt && refreshAt > Util::bootSecs()){
// We're getting a live stream. Let's wait and check again.
uint32_t sleepSecs = (refreshAt - Util::bootSecs());
INFO_MSG("Sleeping for %lu seconds", sleepSecs);
Util::sleep(sleepSecs * 1000);
}
//The non-live case is already handled in isOpen()
}
return false;
}
<|endoftext|> |
<commit_before>#pragma once
// Project specific
#include <Doremi/Core/Include/EntityComponent/Constants.hpp>
using namespace std;
// where we store the actual components/data
template <class T> class StorageShelf
{
public:
static StorageShelf<T>* GetInstance();
T* mItems;
T* GetPointerToArray() { return mItems; }
private:
StorageShelf();
~StorageShelf();
};
template <class T> StorageShelf<T>* StorageShelf<T>::GetInstance()
{
static StorageShelf<T> storageShelf;
return &storageShelf;
}
template <class T> StorageShelf<T>::StorageShelf() { mItems = new T[MAX_NUM_ENTITIES](); }
template <class T> StorageShelf<T>::~StorageShelf() { delete[] mItems; }
// This is the magic about singletons
// Find the right shelf for the needed component
template <class T> static T* GetComponent(EntityID pEntityID)
{
StorageShelf<T>* tNeededShelf = tNeededShelf->GetInstance();
return &tNeededShelf->mItems[pEntityID];
}
/**
Fist paremeter is from, second parameter is to
*/
template <class T, class U> static void CloneShelf()
{
if(sizeof(T) != sizeof(U))
{
std::runtime_error("Attempting to memcpy two different sized shelfs!");
}
// Get Pointers
StorageShelf<T>* tFirstShelf = tFirstShelf->GetInstance();
StorageShelf<U>* tSecondShelf = tSecondShelf->GetInstance();
// Memcpy
// TODO could take parameter of how many entities we have active
memcpy(tSecondShelf->mItems, tFirstShelf->mItems, sizeof(T) * MAX_NUM_ENTITIES);
}
<commit_msg>Pointer is now nullptr in constructor<commit_after>#pragma once
// Project specific
#include <Doremi/Core/Include/EntityComponent/Constants.hpp>
using namespace std;
// where we store the actual components/data
template <class T> class StorageShelf
{
public:
static StorageShelf<T>* GetInstance();
T* mItems;
T* GetPointerToArray() { return mItems; }
private:
StorageShelf();
~StorageShelf();
};
template <class T> StorageShelf<T>* StorageShelf<T>::GetInstance()
{
static StorageShelf<T> storageShelf;
return &storageShelf;
}
template <class T> StorageShelf<T>::StorageShelf() : mItems(nullptr) { mItems = new T[MAX_NUM_ENTITIES](); }
template <class T> StorageShelf<T>::~StorageShelf() { delete[] mItems; }
// This is the magic about singletons
// Find the right shelf for the needed component
template <class T> static T* GetComponent(EntityID pEntityID)
{
StorageShelf<T>* tNeededShelf = tNeededShelf->GetInstance();
return &tNeededShelf->mItems[pEntityID];
}
/**
Fist paremeter is from, second parameter is to
*/
template <class T, class U> static void CloneShelf()
{
if(sizeof(T) != sizeof(U))
{
std::runtime_error("Attempting to memcpy two different sized shelfs!");
}
// Get Pointers
StorageShelf<T>* tFirstShelf = tFirstShelf->GetInstance();
StorageShelf<U>* tSecondShelf = tSecondShelf->GetInstance();
// Memcpy
// TODO could take parameter of how many entities we have active
memcpy(tSecondShelf->mItems, tFirstShelf->mItems, sizeof(T) * MAX_NUM_ENTITIES);
}
<|endoftext|> |
<commit_before>#include <occa/core/device.hpp>
#include <occa/io/output.hpp>
#include <occa/modes.hpp>
namespace occa {
strToModeMap& modeMap() {
static strToModeMap modeMap_;
return modeMap_;
}
void registerMode(mode_v* mode) {
modeMap()[mode->name()] = mode;
}
bool modeIsEnabled(const std::string &mode) {
return (modeMap().find(mode) != modeMap().end());
}
mode_v* getMode(const occa::properties &props) {
std::string mode = props["mode"];
const bool noMode = !mode.size();
if (noMode || !modeIsEnabled(mode)) {
if (noMode) {
io::stderr << "No OCCA mode given, defaulting to [Serial] mode\n";
} else {
io::stderr << "[" << mode << "] mode is not enabled, defaulting to [Serial] mode\n";
}
mode = "Serial";
}
return modeMap()[mode];
}
modeDevice_t* newModeDevice(const occa::properties &props) {
return getMode(props)->newDevice(props);
}
modeInfo_v::modeInfo_v() {}
styling::section& modeInfo_v::getDescription() {
static styling::section section;
return section;
}
std::string& mode_v::name() {
return modeName;
}
}
<commit_msg>Assert chosen mode exists (#282)<commit_after>#include <occa/core/device.hpp>
#include <occa/io/output.hpp>
#include <occa/modes.hpp>
namespace occa {
strToModeMap& modeMap() {
static strToModeMap modeMap_;
return modeMap_;
}
void registerMode(mode_v* mode) {
modeMap()[mode->name()] = mode;
}
bool modeIsEnabled(const std::string &mode) {
return (modeMap().find(mode) != modeMap().end());
}
mode_v* getMode(const occa::properties &props) {
std::string mode = props["mode"];
OCCA_ERROR("No OCCA mode given", mode.size() > 0);
OCCA_ERROR("[" << mode << "] mode is not enabled", modeIsEnabled(mode));
return modeMap()[mode];
}
modeDevice_t* newModeDevice(const occa::properties &props) {
return getMode(props)->newDevice(props);
}
modeInfo_v::modeInfo_v() {}
styling::section& modeInfo_v::getDescription() {
static styling::section section;
return section;
}
std::string& mode_v::name() {
return modeName;
}
}
<|endoftext|> |
<commit_before>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//!
//! @file ludcmp.cc
//! @author <??>
//! @date 2010-11-29
//!
//! @brief Contains a functions to solve eq.systems
//!
//!
//! Finds solution to set of linear equations A x = b by LU decomposition.
//!
//! Chapter 2, Programs 3-5, Fig. 2.8-2.10
//! Gerald/Wheatley, APPLIED NUMERICAL ANALYSIS (fourth edition)
//! Addison-Wesley, 1989
//! http://www.johnloomis.org/ece538/notes/Matrix/ludcmp.html
//!
//$Id$
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include "ComponentSystem.h"
#include "ComponentUtilities/matrix.h"
#include "ComponentUtilities/ludcmp.h"
#include "CoreUtilities/HopsanCoreMessageHandler.h"
using namespace hopsan;
//! finds LU decomposition of Matrix
/*!
* The function ludcmp computes the lower L and upper U triangular
* matrices equivalent to the A Matrix, such that L U = A. These
* matrices are returned in the space of A, in compact form.
* The U Matrix has ones on its diagonal. Partial pivoting is used
* to give maximum valued elements on the diagonal of L. The order of
* the rows after pivoting is returned in the integer vector "order".
* This should be used to reorder the right-hand-side vectors before
* solving the system A x = b.
*
*
* \param a - n by n Matrix of coefficients
* \param order - integer vector holding row order after pivoting.
*
*/
bool hopsan::ludcmp(Matrix &a, int order[])
{
int i, j, k, n, nm1;
double sum, diag;
n = a.rows();
//assert(a.cols()==n);
/* establish initial ordering in order vector */
for (i=0; i<n; i++) order[i] = i;
/* do pivoting for first column and check for singularity */
if (pivot(a,order,0)) return false;
diag = 1.0/a[0][0];
for (i=1; i<n; i++) a[0][i] *= diag;
/*
* Now complete the computing of L and U elements.
* The general plan is to compute a column of L's, then
* call pivot to interchange rows, and then compute
* a row of U's.
*/
nm1 = n - 1;
for (j=1; j<nm1; j++) {
/* column of L's */
for (i=j; i<n; i++) {
sum = 0.0;
for (k=0; k<j; k++) sum += a[i][k]*a[k][j];
a[i][j] -= sum;
}
/* pivot, and check for singularity */
if(!pivot(a,order,j)) return false;
/* row of U's */
diag = 1.0/a[j][j];
for (k=j+1; k<n; k++) {
sum = 0.0;
for (i=0; i<j; i++) sum += a[j][i]*a[i][k];
a[j][k] = (a[j][k]-sum)*diag;
}
}
/* still need to get last element in L Matrix */
sum = 0.0;
for (k=0; k<nm1; k++) sum += a[nm1][k]*a[k][nm1];
a[nm1][nm1] -= sum;
return true;
}
//! Find pivot element
/*!
* The function pivot finds the largest element for a pivot in "jcol"
* of Matrix "a", performs interchanges of the appropriate
* rows in "a", and also interchanges the corresponding elements in
* the order vector.
*
*
* \param a - n by n Matrix of coefficients
* \param order - integer vector to hold row ordering
* \param jcol - column of "a" being searched for pivot element
*
*/
bool hopsan::pivot(Matrix &a, int order[], int jcol)
{
int i, ipvt,n;
double big, anext;
n = a.rows();
/*
* Find biggest element on or below diagonal.
* This will be the pivot row.
*/
ipvt = jcol;
big = fabs(a[ipvt][ipvt]);
for (i = ipvt+1; i<n; i++) {
anext = fabs(a[i][jcol]);
if (anext>big) {
big = anext;
ipvt = i;
}
}
if(fabs(big) < TINY)
{
return false;
}
//assert(fabs(big)>TINY); // otherwise Matrix is singular
/*
* Interchange pivot row (ipvt) with current row (jcol).
*/
if (ipvt==jcol) return 0;
a.swaprows(jcol,ipvt);
i = order[jcol];
order[jcol] = order[ipvt];
order[ipvt] = i;
return true;
}
//! This function is used to find the solution to a system of equations,
/*! A x = b, after LU decomposition of A has been found.
* Within this routine, the elements of b are rearranged in the same way
* that the rows of a were interchanged, using the order vector.
* The solution is returned inamespace hopsan {n x.
*
*
* \param a - the LU decomposition of the original coefficient Matrix.
* \param b - the vector of right-hand sides
* \param x - the solution vector
* \param order - integer array of row order as arranged during pivoting
*
*/
void hopsan::solvlu(const Matrix &a, const Vec &b, Vec &x, const int order[])
{
int i,j,n;
double sum;
n = a.rows();
/* rearrange the elements of the b vector. x is used to hold them. */
for (i=0; i<n; i++) {
j = order[i];
x[i] = b[j];
}
/* do forward substitution, replacing x vector. */
x[0] /= a[0][0];
for (i=1; i<n; i++) {
sum = 0.0;
for (j=0; j<i; j++) sum += a[i][j]*x[j];
x[i] = (x[i]-sum)/a[i][i];
}
/* now get the solution vector, x[n-1] is already done */
for (i=n-2; i>=0; i--) {
sum = 0.0;
for (j=i+1; j<n; j++) sum += a[i][j] * x[j];
x[i] -= sum;
}
}
<commit_msg>Fixed ludcmp int to bool conversion bugs<commit_after>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//!
//! @file ludcmp.cc
//! @author <??>
//! @date 2010-11-29
//!
//! @brief Contains a functions to solve eq.systems
//!
//!
//! Finds solution to set of linear equations A x = b by LU decomposition.
//!
//! Chapter 2, Programs 3-5, Fig. 2.8-2.10
//! Gerald/Wheatley, APPLIED NUMERICAL ANALYSIS (fourth edition)
//! Addison-Wesley, 1989
//! http://www.johnloomis.org/ece538/notes/Matrix/ludcmp.html
//!
//$Id$
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include "ComponentSystem.h"
#include "ComponentUtilities/matrix.h"
#include "ComponentUtilities/ludcmp.h"
#include "CoreUtilities/HopsanCoreMessageHandler.h"
using namespace hopsan;
//! finds LU decomposition of Matrix
/*!
* The function ludcmp computes the lower L and upper U triangular
* matrices equivalent to the A Matrix, such that L U = A. These
* matrices are returned in the space of A, in compact form.
* The U Matrix has ones on its diagonal. Partial pivoting is used
* to give maximum valued elements on the diagonal of L. The order of
* the rows after pivoting is returned in the integer vector "order".
* This should be used to reorder the right-hand-side vectors before
* solving the system A x = b.
*
*
* \param a - n by n Matrix of coefficients
* \param order - integer vector holding row order after pivoting.
*
*/
bool hopsan::ludcmp(Matrix &a, int order[])
{
int i, j, k, n, nm1;
double sum, diag;
n = a.rows();
//assert(a.cols()==n);
/* establish initial ordering in order vector */
for (i=0; i<n; i++) order[i] = i;
/* do pivoting for first column and check for singularity */
if (!pivot(a,order,0)) return false;
diag = 1.0/a[0][0];
for (i=1; i<n; i++) a[0][i] *= diag;
/*
* Now complete the computing of L and U elements.
* The general plan is to compute a column of L's, then
* call pivot to interchange rows, and then compute
* a row of U's.
*/
nm1 = n - 1;
for (j=1; j<nm1; j++) {
/* column of L's */
for (i=j; i<n; i++) {
sum = 0.0;
for (k=0; k<j; k++) sum += a[i][k]*a[k][j];
a[i][j] -= sum;
}
/* pivot, and check for singularity */
if(!pivot(a,order,j)) return false;
/* row of U's */
diag = 1.0/a[j][j];
for (k=j+1; k<n; k++) {
sum = 0.0;
for (i=0; i<j; i++) sum += a[j][i]*a[i][k];
a[j][k] = (a[j][k]-sum)*diag;
}
}
/* still need to get last element in L Matrix */
sum = 0.0;
for (k=0; k<nm1; k++) sum += a[nm1][k]*a[k][nm1];
a[nm1][nm1] -= sum;
return true;
}
//! Find pivot element
/*!
* The function pivot finds the largest element for a pivot in "jcol"
* of Matrix "a", performs interchanges of the appropriate
* rows in "a", and also interchanges the corresponding elements in
* the order vector.
*
*
* \param a - n by n Matrix of coefficients
* \param order - integer vector to hold row ordering
* \param jcol - column of "a" being searched for pivot element
*
*/
bool hopsan::pivot(Matrix &a, int order[], int jcol)
{
int i, ipvt,n;
double big, anext;
n = a.rows();
/*
* Find biggest element on or below diagonal.
* This will be the pivot row.
*/
ipvt = jcol;
big = fabs(a[ipvt][ipvt]);
for (i = ipvt+1; i<n; i++) {
anext = fabs(a[i][jcol]);
if (anext>big) {
big = anext;
ipvt = i;
}
}
if(fabs(big) < TINY)
{
return false;
}
//assert(fabs(big)>TINY); // otherwise Matrix is singular
/*
* Interchange pivot row (ipvt) with current row (jcol).
*/
if (ipvt==jcol) return true;
a.swaprows(jcol,ipvt);
i = order[jcol];
order[jcol] = order[ipvt];
order[ipvt] = i;
return true;
}
//! This function is used to find the solution to a system of equations,
/*! A x = b, after LU decomposition of A has been found.
* Within this routine, the elements of b are rearranged in the same way
* that the rows of a were interchanged, using the order vector.
* The solution is returned inamespace hopsan {n x.
*
*
* \param a - the LU decomposition of the original coefficient Matrix.
* \param b - the vector of right-hand sides
* \param x - the solution vector
* \param order - integer array of row order as arranged during pivoting
*
*/
void hopsan::solvlu(const Matrix &a, const Vec &b, Vec &x, const int order[])
{
int i,j,n;
double sum;
n = a.rows();
/* rearrange the elements of the b vector. x is used to hold them. */
for (i=0; i<n; i++) {
j = order[i];
x[i] = b[j];
}
/* do forward substitution, replacing x vector. */
x[0] /= a[0][0];
for (i=1; i<n; i++) {
sum = 0.0;
for (j=0; j<i; j++) sum += a[i][j]*x[j];
x[i] = (x[i]-sum)/a[i][i];
}
/* now get the solution vector, x[n-1] is already done */
for (i=n-2; i>=0; i--) {
sum = 0.0;
for (j=i+1; j<n; j++) sum += a[i][j] * x[j];
x[i] -= sum;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 Google
* 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: Gabe Black
*/
#ifndef __ARCH_GENERIC_MEMHELPERS_HH__
#define __ARCH_GENERIC_MEMHELPERS_HH__
#include "base/types.hh"
#include "sim/byteswap.hh"
#include "sim/fault_fwd.hh"
#include "sim/insttracer.hh"
/// Read from memory in timing mode.
template <class XC, class MemT>
Fault
readMemTiming(XC *xc, Trace::InstRecord *traceData, Addr addr,
MemT &mem, unsigned flags)
{
return xc->readMem(addr, (uint8_t *)&mem, sizeof(MemT), flags);
}
/// Extract the data returned from a timing mode read.
template <class MemT>
void
getMem(PacketPtr pkt, MemT &mem, Trace::InstRecord *traceData)
{
mem = pkt->get<MemT>();
if (traceData)
traceData->setData(mem);
}
/// Read from memory in atomic mode.
template <class XC, class MemT>
Fault
readMemAtomic(XC *xc, Trace::InstRecord *traceData, Addr addr, MemT &mem,
unsigned flags)
{
memset(&mem, 0, sizeof(mem));
Fault fault = readMemTiming(xc, traceData, addr, mem, flags);
if (fault == NoFault) {
mem = TheISA::gtoh(mem);
if (traceData)
traceData->setData(mem);
}
return fault;
}
/// Write to memory in timing mode.
template <class XC, class MemT>
Fault
writeMemTiming(XC *xc, Trace::InstRecord *traceData, MemT mem, Addr addr,
unsigned flags, uint64_t *res)
{
if (traceData) {
traceData->setData(mem);
}
mem = TheISA::htog(mem);
return xc->writeMem((uint8_t *)&mem, sizeof(MemT), addr, flags, res);
}
/// Write to memory in atomic mode.
template <class XC, class MemT>
Fault
writeMemAtomic(XC *xc, Trace::InstRecord *traceData, const MemT &mem,
Addr addr, unsigned flags, uint64_t *res)
{
Fault fault = writeMemTiming(xc, traceData, mem, addr, flags, res);
if (fault == NoFault && res != NULL) {
*res = TheISA::gtoh((MemT)*res);
}
return fault;
}
#endif
<commit_msg>mem: Remove explict cast from memhelper.<commit_after>/*
* Copyright (c) 2013 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2011 Google
* 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: Gabe Black
*/
#ifndef __ARCH_GENERIC_MEMHELPERS_HH__
#define __ARCH_GENERIC_MEMHELPERS_HH__
#include "base/types.hh"
#include "mem/request.hh"
#include "sim/byteswap.hh"
#include "sim/fault_fwd.hh"
#include "sim/insttracer.hh"
/// Read from memory in timing mode.
template <class XC, class MemT>
Fault
readMemTiming(XC *xc, Trace::InstRecord *traceData, Addr addr,
MemT &mem, unsigned flags)
{
return xc->readMem(addr, (uint8_t *)&mem, sizeof(MemT), flags);
}
/// Extract the data returned from a timing mode read.
template <class MemT>
void
getMem(PacketPtr pkt, MemT &mem, Trace::InstRecord *traceData)
{
mem = pkt->get<MemT>();
if (traceData)
traceData->setData(mem);
}
/// Read from memory in atomic mode.
template <class XC, class MemT>
Fault
readMemAtomic(XC *xc, Trace::InstRecord *traceData, Addr addr, MemT &mem,
unsigned flags)
{
memset(&mem, 0, sizeof(mem));
Fault fault = readMemTiming(xc, traceData, addr, mem, flags);
if (fault == NoFault) {
mem = TheISA::gtoh(mem);
if (traceData)
traceData->setData(mem);
}
return fault;
}
/// Write to memory in timing mode.
template <class XC, class MemT>
Fault
writeMemTiming(XC *xc, Trace::InstRecord *traceData, MemT mem, Addr addr,
unsigned flags, uint64_t *res)
{
if (traceData) {
traceData->setData(mem);
}
mem = TheISA::htog(mem);
return xc->writeMem((uint8_t *)&mem, sizeof(MemT), addr, flags, res);
}
/// Write to memory in atomic mode.
template <class XC, class MemT>
Fault
writeMemAtomic(XC *xc, Trace::InstRecord *traceData, const MemT &mem,
Addr addr, unsigned flags, uint64_t *res)
{
Fault fault = writeMemTiming(xc, traceData, mem, addr, flags, res);
if (fault == NoFault && res != NULL) {
if (flags & Request::MEM_SWAP || flags & Request::MEM_SWAP_COND)
*res = TheISA::gtoh((MemT)*res);
else
*res = TheISA::gtoh(*res);
}
return fault;
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2017 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.
*/
#include "font_skia.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkFont.h"
#include <minikin/MinikinFont.h>
namespace txt {
namespace {
hb_blob_t* GetTable(hb_face_t* face, hb_tag_t tag, void* context) {
SkTypeface* typeface = reinterpret_cast<SkTypeface*>(context);
sk_sp<SkData> data = typeface->copyTableData(tag);
if (!data) {
return nullptr;
}
SkData* rawData = data.release();
return hb_blob_create(reinterpret_cast<char*>(rawData->writable_data()),
rawData->size(), HB_MEMORY_MODE_WRITABLE, rawData,
[](void* ctx) { ((SkData*)ctx)->unref(); });
}
} // namespace
FontSkia::FontSkia(sk_sp<SkTypeface> typeface)
: MinikinFont(typeface->uniqueID()), typeface_(std::move(typeface)) {}
FontSkia::~FontSkia() = default;
static void FontSkia_SetSkiaFont(sk_sp<SkTypeface> typeface,
SkFont* skFont,
const minikin::MinikinPaint& paint) {
skFont->setTypeface(std::move(typeface));
// TODO: set more paint parameters from Minikin
skFont->setSize(paint.size);
}
float FontSkia::GetHorizontalAdvance(uint32_t glyph_id,
const minikin::MinikinPaint& paint) const {
SkFont skFont;
uint16_t glyph16 = glyph_id;
SkScalar skWidth;
FontSkia_SetSkiaFont(typeface_, &skFont, paint);
skFont.getWidths(&glyph16, 1, &skWidth);
return skWidth;
}
void FontSkia::GetBounds(minikin::MinikinRect* bounds,
uint32_t glyph_id,
const minikin::MinikinPaint& paint) const {
SkFont skFont;
uint16_t glyph16 = glyph_id;
SkRect skBounds;
FontSkia_SetSkiaFont(typeface_, &skFont, paint);
skFont.getWidths(&glyph16, 1, NULL, &skBounds);
bounds->mLeft = skBounds.fLeft;
bounds->mTop = skBounds.fTop;
bounds->mRight = skBounds.fRight;
bounds->mBottom = skBounds.fBottom;
}
hb_face_t* FontSkia::CreateHarfBuzzFace() const {
return hb_face_create_for_tables(GetTable, typeface_.get(), 0);
}
const std::vector<minikin::FontVariation>& FontSkia::GetAxes() const {
return variations_;
}
const sk_sp<SkTypeface>& FontSkia::GetSkTypeface() const {
return typeface_;
}
} // namespace txt
<commit_msg>Revert "Started taking advantage of Skia's new copyTableData to avoid (#10154)" (#12263)<commit_after>/*
* Copyright 2017 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.
*/
#include "font_skia.h"
#include "third_party/skia/include/core/SkFont.h"
#include <minikin/MinikinFont.h>
namespace txt {
namespace {
hb_blob_t* GetTable(hb_face_t* face, hb_tag_t tag, void* context) {
SkTypeface* typeface = reinterpret_cast<SkTypeface*>(context);
const size_t table_size = typeface->getTableSize(tag);
if (table_size == 0)
return nullptr;
void* buffer = malloc(table_size);
if (buffer == nullptr)
return nullptr;
size_t actual_size = typeface->getTableData(tag, 0, table_size, buffer);
if (table_size != actual_size) {
free(buffer);
return nullptr;
}
return hb_blob_create(reinterpret_cast<char*>(buffer), table_size,
HB_MEMORY_MODE_WRITABLE, buffer, free);
}
} // namespace
FontSkia::FontSkia(sk_sp<SkTypeface> typeface)
: MinikinFont(typeface->uniqueID()), typeface_(std::move(typeface)) {}
FontSkia::~FontSkia() = default;
static void FontSkia_SetSkiaFont(sk_sp<SkTypeface> typeface,
SkFont* skFont,
const minikin::MinikinPaint& paint) {
skFont->setTypeface(std::move(typeface));
// TODO: set more paint parameters from Minikin
skFont->setSize(paint.size);
}
float FontSkia::GetHorizontalAdvance(uint32_t glyph_id,
const minikin::MinikinPaint& paint) const {
SkFont skFont;
uint16_t glyph16 = glyph_id;
SkScalar skWidth;
FontSkia_SetSkiaFont(typeface_, &skFont, paint);
skFont.getWidths(&glyph16, 1, &skWidth);
return skWidth;
}
void FontSkia::GetBounds(minikin::MinikinRect* bounds,
uint32_t glyph_id,
const minikin::MinikinPaint& paint) const {
SkFont skFont;
uint16_t glyph16 = glyph_id;
SkRect skBounds;
FontSkia_SetSkiaFont(typeface_, &skFont, paint);
skFont.getWidths(&glyph16, 1, NULL, &skBounds);
bounds->mLeft = skBounds.fLeft;
bounds->mTop = skBounds.fTop;
bounds->mRight = skBounds.fRight;
bounds->mBottom = skBounds.fBottom;
}
hb_face_t* FontSkia::CreateHarfBuzzFace() const {
return hb_face_create_for_tables(GetTable, typeface_.get(), 0);
}
const std::vector<minikin::FontVariation>& FontSkia::GetAxes() const {
return variations_;
}
const sk_sp<SkTypeface>& FontSkia::GetSkTypeface() const {
return typeface_;
}
} // namespace txt
<|endoftext|> |
<commit_before>#include <iostream>
#include <complex>
#include <cmath>
#include "../sequence.h"
#include "../parallel.h"
#include "../run.h"
#include <thread>
#include <vector>
#include <gtest/gtest.h>
class SequenceTest : testing::Test { };
TEST(SequenceTest, Test1)
{
struct control_flow
{
bool code;
operator bool() const
{
return code;
}
};
control_flow flow = {true};
auto task = asyncply::sequence(flow,
[](control_flow flow) {
std::cout << "code 1" << std::endl;
return flow;
},
[](control_flow flow) {
std::cout << "code 2" << std::endl;
return flow;
},
[](control_flow flow) {
std::cout << "code 3" << std::endl;
flow.code = false;
return flow;
},
[](control_flow flow) {
std::cout << "code 4" << std::endl;
return flow;
}
);
flow = task->get();
ASSERT_FALSE(flow.code);
}
<commit_msg>Update test_sequence.cpp<commit_after>#include <iostream>
#include <complex>
#include <cmath>
#include <thread>
#include <vector>
#include <asyncply/sequence.h>
#include <asyncply/parallel.h>
#include <asyncply/run.h>
#include <gtest/gtest.h>
class SequenceTest : testing::Test { };
TEST(SequenceTest, Test1)
{
struct control_flow
{
bool code;
operator bool() const
{
return code;
}
};
control_flow flow = {true};
auto task = asyncply::sequence(flow,
[](control_flow flow) {
std::cout << "code 1" << std::endl;
return flow;
},
[](control_flow flow) {
std::cout << "code 2" << std::endl;
return flow;
},
[](control_flow flow) {
std::cout << "code 3" << std::endl;
flow.code = false;
return flow;
},
[](control_flow flow) {
std::cout << "code 4" << std::endl;
return flow;
}
);
flow = task->get();
ASSERT_FALSE(flow.code);
}
<|endoftext|> |
<commit_before>#include "core/filesystem.h"
#include "catch.hpp"
#define GTEST(X) TEST(filesystem, X)
class AlwaysExist : public FileSystemReadRoot
{
public:
std::shared_ptr<MemoryChunk>
ReadFile(const std::string& path) override
{
// alloc some garbage
return MemoryChunk::Alloc(32);
}
std::string
Describe() override
{
return "";
}
std::vector<ListedFile>
ListFiles(const Path& path) override
{
std::vector<ListedFile> ret;
return ret;
}
};
class NeverExist : public FileSystemReadRoot
{
public:
std::shared_ptr<MemoryChunk>
ReadFile(const std::string& path) override
{
return MemoryChunk::Null();
}
std::string
Describe() override
{
return "";
}
std::vector<ListedFile>
ListFiles(const Path& path) override
{
std::vector<ListedFile> ret;
return ret;
}
};
TEST_CASE("vfs-test_basic", "[vfs]")
{
SECTION("always")
{
FileSystem always;
always.AddReadRoot(std::make_shared<AlwaysExist>());
REQUIRE(always.ReadFile("dog") != nullptr);
}
SECTION("never")
{
FileSystem never;
never.AddReadRoot(std::make_shared<NeverExist>());
REQUIRE(never.ReadFile("dog") == nullptr);
}
}
TEST_CASE("vfs-test_catalog_with_null", "[vfs]")
{
FileSystem fs;
auto catalog = FileSystemRootCatalog::AddRoot(&fs);
catalog->RegisterFileString("dog", "happy");
std::string content;
SECTION("can read stored file")
{
REQUIRE(fs.ReadFileToString("dog", &content));
REQUIRE(content == "happy");
}
SECTION("error when trying to read missing file")
{
REQUIRE_FALSE(fs.ReadFileToString("cat", &content));
}
}
// todo: add test with overriding files from different roots
<commit_msg> fixed unit test build error<commit_after>#include "core/filesystem.h"
#include "catch.hpp"
#define GTEST(X) TEST(filesystem, X)
class AlwaysExist : public FileSystemReadRoot
{
public:
std::shared_ptr<MemoryChunk>
ReadFile(const std::string& path) override
{
// alloc some garbage
return MemoryChunk::Alloc(32);
}
std::string
Describe() override
{
return "";
}
FileList
ListFiles(const Path& path) override
{
FileList ret;
return ret;
}
};
class NeverExist : public FileSystemReadRoot
{
public:
std::shared_ptr<MemoryChunk>
ReadFile(const std::string& path) override
{
return MemoryChunk::Null();
}
std::string
Describe() override
{
return "";
}
FileList
ListFiles(const Path& path) override
{
FileList ret;
return ret;
}
};
TEST_CASE("vfs-test_basic", "[vfs]")
{
SECTION("always")
{
FileSystem always;
always.AddReadRoot(std::make_shared<AlwaysExist>());
REQUIRE(always.ReadFile("dog") != nullptr);
}
SECTION("never")
{
FileSystem never;
never.AddReadRoot(std::make_shared<NeverExist>());
REQUIRE(never.ReadFile("dog") == nullptr);
}
}
TEST_CASE("vfs-test_catalog_with_null", "[vfs]")
{
FileSystem fs;
auto catalog = FileSystemRootCatalog::AddRoot(&fs);
catalog->RegisterFileString("dog", "happy");
std::string content;
SECTION("can read stored file")
{
REQUIRE(fs.ReadFileToString("dog", &content));
REQUIRE(content == "happy");
}
SECTION("error when trying to read missing file")
{
REQUIRE_FALSE(fs.ReadFileToString("cat", &content));
}
}
// todo: add test with overriding files from different roots
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) [2016] [BTC.COM]
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 <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <err.h>
#include <errno.h>
#include <unistd.h>
#include <iostream>
#include <boost/interprocess/sync/file_lock.hpp>
#include <glog/logging.h>
#include <libconfig.h++>
#include "ShareConvertor.hpp"
#include "ShareDiffChanger.hpp"
#include "SharePrinter.hpp"
using namespace std;
using namespace libconfig;
// kafka repeater
KafkaRepeater *gKafkaRepeater = nullptr;
void handler(int sig) {
if (gKafkaRepeater) {
gKafkaRepeater->stop();
}
}
void usage() {
fprintf(stderr, "Usage:\n\tkafka_repeater -c \"kafka_repeater.cfg\" -l \"log_kafka_repeater\"\n");
}
template<typename S, typename V>
void readFromSetting(const S &setting,
const string &key,
V &value,
bool optional = false)
{
if (!setting.lookupValue(key, value) && !optional) {
LOG(FATAL) << "config section missing key: " << key;
}
}
int main(int argc, char **argv) {
char *optLogDir = NULL;
char *optConf = NULL;
int c;
if (argc <= 1) {
usage();
return 1;
}
while ((c = getopt(argc, argv, "c:l:h")) != -1) {
switch (c) {
case 'c':
optConf = optarg;
break;
case 'l':
optLogDir = optarg;
break;
case 'h': default:
usage();
exit(0);
}
}
// Initialize Google's logging library.
google::InitGoogleLogging(argv[0]);
if (optLogDir == NULL || strcmp(optLogDir, "stderr") == 0) {
FLAGS_logtostderr = 1;
} else {
FLAGS_log_dir = string(optLogDir);
}
// Log messages at a level >= this flag are automatically sent to
// stderr in addition to log files.
FLAGS_stderrthreshold = 3; // 3: FATAL
FLAGS_max_log_size = 100; // max log file size 100 MB
FLAGS_logbuflevel = -1; // don't buffer logs
FLAGS_stop_logging_if_full_disk = true;
// Read the file. If there is an error, report it and exit.
libconfig::Config cfg;
try
{
cfg.readFile(optConf);
} catch(const FileIOException &fioex) {
std::cerr << "I/O error while reading file." << std::endl;
return(EXIT_FAILURE);
} catch(const ParseException &pex) {
std::cerr << "Parse error at " << pex.getFile() << ":" << pex.getLine()
<< " - " << pex.getError() << std::endl;
return(EXIT_FAILURE);
}
// lock cfg file:
// you can't run more than one process with the same config file
/*boost::interprocess::file_lock pidFileLock(optConf);
if (pidFileLock.try_lock() == false) {
LOG(FATAL) << "lock cfg file fail";
return(EXIT_FAILURE);
}*/
signal(SIGTERM, handler);
signal(SIGINT, handler);
try {
bool enableShareConvBtcV2ToV1 = false;
bool enableShareDiffChangerBtcV1 = false;
bool enableShareDiffChangerBtcV2ToV1 = false;
bool enableSharePrinterBtcV1 = false;
int repeatedNumberDisplayInterval = 10;
readFromSetting(cfg, "share_convertor.bitcoin_v2_to_v1", enableShareConvBtcV2ToV1, true);
readFromSetting(cfg, "share_diff_changer.bitcoin_v1", enableShareDiffChangerBtcV1, true);
readFromSetting(cfg, "share_diff_changer.bitcoin_v2_to_v1", enableShareDiffChangerBtcV2ToV1, true);
readFromSetting(cfg, "share_printer.bitcoin_v1", enableSharePrinterBtcV1, true);
readFromSetting(cfg, "log.repeated_number_display_interval", repeatedNumberDisplayInterval, true);
if (enableShareConvBtcV2ToV1) {
gKafkaRepeater = new ShareConvertorBitcoinV2ToV1(
cfg.lookup("kafka.in_brokers"), cfg.lookup("kafka.in_topic"), cfg.lookup("kafka.in_group_id"),
cfg.lookup("kafka.out_brokers"), cfg.lookup("kafka.out_topic")
);
}
else if (enableShareDiffChangerBtcV1) {
gKafkaRepeater = new ShareDiffChangerBitcoinV1(
cfg.lookup("kafka.in_brokers"), cfg.lookup("kafka.in_topic"), cfg.lookup("kafka.in_group_id"),
cfg.lookup("kafka.out_brokers"), cfg.lookup("kafka.out_topic")
);
int jobTimeOffset = 30;
readFromSetting(cfg, "share_diff_changer.job_time_offset", jobTimeOffset, true);
if (!dynamic_cast<ShareDiffChangerBitcoinV1*>(gKafkaRepeater)->initStratumJobConsumer(
cfg.lookup("share_diff_changer.job_brokers"), cfg.lookup("share_diff_changer.job_topic"),
cfg.lookup("share_diff_changer.job_group_id"), jobTimeOffset
)) {
LOG(FATAL) << "kafka repeater init failed";
return 1;
}
}
else if (enableShareDiffChangerBtcV2ToV1) {
gKafkaRepeater = new ShareDiffChangerBitcoinV2ToV1(
cfg.lookup("kafka.in_brokers"), cfg.lookup("kafka.in_topic"), cfg.lookup("kafka.in_group_id"),
cfg.lookup("kafka.out_brokers"), cfg.lookup("kafka.out_topic")
);
int jobTimeOffset = 30;
readFromSetting(cfg, "share_diff_changer.job_time_offset", jobTimeOffset, true);
if (!dynamic_cast<ShareDiffChangerBitcoinV2ToV1*>(gKafkaRepeater)->initStratumJobConsumer(
cfg.lookup("share_diff_changer.job_brokers"), cfg.lookup("share_diff_changer.job_topic"),
cfg.lookup("share_diff_changer.job_group_id"), jobTimeOffset
)) {
LOG(FATAL) << "kafka repeater init failed";
return 1;
}
}
else if (enableSharePrinterBtcV1) {
gKafkaRepeater = new SharePrinterBitcoinV1(
cfg.lookup("kafka.in_brokers"), cfg.lookup("kafka.in_topic"), cfg.lookup("kafka.in_group_id"),
cfg.lookup("kafka.out_brokers"), cfg.lookup("kafka.out_topic")
);
}
else {
LOG(INFO) << "no repeater enabled";
return 0;
}
if (!gKafkaRepeater->init()) {
LOG(FATAL) << "kafka repeater init failed";
return 1;
}
gKafkaRepeater->runMessageNumberDisplayThread(repeatedNumberDisplayInterval);
gKafkaRepeater->run();
}
catch (std::exception & e) {
LOG(FATAL) << "exception: " << e.what();
return 1;
}
google::ShutdownGoogleLogging();
return 0;
}
<commit_msg>tools kafka_repeater: support simple forwarding mode.<commit_after>/*
The MIT License (MIT)
Copyright (c) [2016] [BTC.COM]
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 <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <err.h>
#include <errno.h>
#include <unistd.h>
#include <iostream>
#include <boost/interprocess/sync/file_lock.hpp>
#include <glog/logging.h>
#include <libconfig.h++>
#include "ShareConvertor.hpp"
#include "ShareDiffChanger.hpp"
#include "SharePrinter.hpp"
using namespace std;
using namespace libconfig;
// kafka repeater
KafkaRepeater *gKafkaRepeater = nullptr;
void handler(int sig) {
if (gKafkaRepeater) {
gKafkaRepeater->stop();
}
}
void usage() {
fprintf(stderr, "Usage:\n\tkafka_repeater -c \"kafka_repeater.cfg\" -l \"log_kafka_repeater\"\n");
}
template<typename S, typename V>
void readFromSetting(const S &setting,
const string &key,
V &value,
bool optional = false)
{
if (!setting.lookupValue(key, value) && !optional) {
LOG(FATAL) << "config section missing key: " << key;
}
}
int main(int argc, char **argv) {
char *optLogDir = NULL;
char *optConf = NULL;
int c;
if (argc <= 1) {
usage();
return 1;
}
while ((c = getopt(argc, argv, "c:l:h")) != -1) {
switch (c) {
case 'c':
optConf = optarg;
break;
case 'l':
optLogDir = optarg;
break;
case 'h': default:
usage();
exit(0);
}
}
// Initialize Google's logging library.
google::InitGoogleLogging(argv[0]);
if (optLogDir == NULL || strcmp(optLogDir, "stderr") == 0) {
FLAGS_logtostderr = 1;
} else {
FLAGS_log_dir = string(optLogDir);
}
// Log messages at a level >= this flag are automatically sent to
// stderr in addition to log files.
FLAGS_stderrthreshold = 3; // 3: FATAL
FLAGS_max_log_size = 100; // max log file size 100 MB
FLAGS_logbuflevel = -1; // don't buffer logs
FLAGS_stop_logging_if_full_disk = true;
// Read the file. If there is an error, report it and exit.
libconfig::Config cfg;
try
{
cfg.readFile(optConf);
} catch(const FileIOException &fioex) {
std::cerr << "I/O error while reading file." << std::endl;
return(EXIT_FAILURE);
} catch(const ParseException &pex) {
std::cerr << "Parse error at " << pex.getFile() << ":" << pex.getLine()
<< " - " << pex.getError() << std::endl;
return(EXIT_FAILURE);
}
// lock cfg file:
// you can't run more than one process with the same config file
/*boost::interprocess::file_lock pidFileLock(optConf);
if (pidFileLock.try_lock() == false) {
LOG(FATAL) << "lock cfg file fail";
return(EXIT_FAILURE);
}*/
signal(SIGTERM, handler);
signal(SIGINT, handler);
try {
bool enableShareConvBtcV2ToV1 = false;
bool enableShareDiffChangerBtcV1 = false;
bool enableShareDiffChangerBtcV2ToV1 = false;
bool enableSharePrinterBtcV1 = false;
int repeatedNumberDisplayInterval = 10;
readFromSetting(cfg, "share_convertor.bitcoin_v2_to_v1", enableShareConvBtcV2ToV1, true);
readFromSetting(cfg, "share_diff_changer.bitcoin_v1", enableShareDiffChangerBtcV1, true);
readFromSetting(cfg, "share_diff_changer.bitcoin_v2_to_v1", enableShareDiffChangerBtcV2ToV1, true);
readFromSetting(cfg, "share_printer.bitcoin_v1", enableSharePrinterBtcV1, true);
readFromSetting(cfg, "log.repeated_number_display_interval", repeatedNumberDisplayInterval, true);
if (enableShareConvBtcV2ToV1) {
gKafkaRepeater = new ShareConvertorBitcoinV2ToV1(
cfg.lookup("kafka.in_brokers"), cfg.lookup("kafka.in_topic"), cfg.lookup("kafka.in_group_id"),
cfg.lookup("kafka.out_brokers"), cfg.lookup("kafka.out_topic")
);
}
else if (enableShareDiffChangerBtcV1) {
gKafkaRepeater = new ShareDiffChangerBitcoinV1(
cfg.lookup("kafka.in_brokers"), cfg.lookup("kafka.in_topic"), cfg.lookup("kafka.in_group_id"),
cfg.lookup("kafka.out_brokers"), cfg.lookup("kafka.out_topic")
);
int jobTimeOffset = 30;
readFromSetting(cfg, "share_diff_changer.job_time_offset", jobTimeOffset, true);
if (!dynamic_cast<ShareDiffChangerBitcoinV1*>(gKafkaRepeater)->initStratumJobConsumer(
cfg.lookup("share_diff_changer.job_brokers"), cfg.lookup("share_diff_changer.job_topic"),
cfg.lookup("share_diff_changer.job_group_id"), jobTimeOffset
)) {
LOG(FATAL) << "kafka repeater init failed";
return 1;
}
}
else if (enableShareDiffChangerBtcV2ToV1) {
gKafkaRepeater = new ShareDiffChangerBitcoinV2ToV1(
cfg.lookup("kafka.in_brokers"), cfg.lookup("kafka.in_topic"), cfg.lookup("kafka.in_group_id"),
cfg.lookup("kafka.out_brokers"), cfg.lookup("kafka.out_topic")
);
int jobTimeOffset = 30;
readFromSetting(cfg, "share_diff_changer.job_time_offset", jobTimeOffset, true);
if (!dynamic_cast<ShareDiffChangerBitcoinV2ToV1*>(gKafkaRepeater)->initStratumJobConsumer(
cfg.lookup("share_diff_changer.job_brokers"), cfg.lookup("share_diff_changer.job_topic"),
cfg.lookup("share_diff_changer.job_group_id"), jobTimeOffset
)) {
LOG(FATAL) << "kafka repeater init failed";
return 1;
}
}
else if (enableSharePrinterBtcV1) {
gKafkaRepeater = new SharePrinterBitcoinV1(
cfg.lookup("kafka.in_brokers"), cfg.lookup("kafka.in_topic"), cfg.lookup("kafka.in_group_id"),
cfg.lookup("kafka.out_brokers"), cfg.lookup("kafka.out_topic")
);
}
else {
gKafkaRepeater = new KafkaRepeater(
cfg.lookup("kafka.in_brokers"), cfg.lookup("kafka.in_topic"), cfg.lookup("kafka.in_group_id"),
cfg.lookup("kafka.out_brokers"), cfg.lookup("kafka.out_topic")
);
}
if (!gKafkaRepeater->init()) {
LOG(FATAL) << "kafka repeater init failed";
return 1;
}
gKafkaRepeater->runMessageNumberDisplayThread(repeatedNumberDisplayInterval);
gKafkaRepeater->run();
}
catch (std::exception & e) {
LOG(FATAL) << "exception: " << e.what();
return 1;
}
google::ShutdownGoogleLogging();
return 0;
}
<|endoftext|> |
<commit_before>#include "timing/timing.hpp"
#include "graphics/displayimage.hpp"
#include "tree.hpp"
#include <sys/stat.h>
#include <queue>
#include <string.h>
int main(int argc, char **argv)
{
cairo_surface_t *surface;
cairo_t *context;
int x, y, i,
width, height, depth,
screen, pressed_key,
png;
double r, b, v;
QTnode *tree;
bool rendering;
struct XWin **xwin;
/* Get the arguments */
if(argc != 3) {
printf("Usage: nbody rendering resultsdir\n");
exit(1);
}
if(*argv[1] == '0') {
rendering = false;
} else {
rendering = true;
}
char buf[strlen(argv[2]) + 10];
/* Set window size */
width = 1024;
height = 1024;
depth = 32;
/* Create the drawing surface */
if(rendering) {
/* Create the X11 window */
xwin = (struct XWin **)calloc(sizeof(struct XWin *), 1);
xwindow_init(width, height, depth, xwin);
surface = cairo_xlib_surface_create((*xwin)->dsp, (*xwin)->win, DefaultVisual((*xwin)->dsp, screen), width, height);
cairo_xlib_surface_set_size(surface, width, height);
} else {
surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height);
}
context = cairo_create(surface);
cairo_scale(context, width, height);
/* Create the quad tree */
tree = init_tree(4, NULL);
for(i = 0; i < 1000; ++i) {
tree->insert(phys_gen_particle());
}
png = 0;
while(1) {
if(rendering) {
if((*xwin)->should_close) {
break;
}
}
std::queue <QTnode *> nodes;
QTnode *t;
/* Fill particles */
timing(tree->calc_global_accel());
timing(tree->move_shit());
if(rendering) {
/* Wait on the input (also sync up to disable flickering) */
if(input_ready(xwin)) {
pressed_key = get_key(xwin);
}
}
/* Clear the surface with black */
cairo_set_source_rgb(context, 0.0, 0.0, 0.0);
cairo_paint(context);
nodes.push(tree);
while (!nodes.empty()) {
t = nodes.front();
nodes.pop();
if (!t->children.empty()) {
for (i = 0; i < t->children.size(); i++) {
nodes.push(t->children[i]);
}
} else {
for (std::list <Particle>::iterator p = t->particles.begin(); p != t->particles.end(); p++) {
v = f2_norm((*p).vel);
if(v >= 0.4) {
r = 1.0; b = 0.0;
} else if(v < 0.5) {
b = 1.0; r = 0.0;
}
cairo_set_source_rgba(context, (double)r, 0.0, (double)b, 1.0);
cairo_rectangle(context, (*p).pos.x,
(*p).pos.y, 2e-3, 2e-3);
cairo_fill(context);
cairo_set_source_rgba(context, (double)r, 0.0, (double)b, 0.2);
cairo_rectangle(context, (*p).pos.x - 1e-3,
(*p).pos.y - 1e-3, 4e-3, 4e-3);
cairo_fill(context);
}
}
}
if(rendering) {
/* Flush the X window */
flush_input(xwin);
update_screen(xwin);
} else {
mkdir(argv[2], S_IRWXU | S_IRWXG);
sprintf(buf, "%s/%05d.png", argv[2], png++);
printf("Making %s\n", buf);
cairo_surface_write_to_png (surface, buf);
}
}
destroy_tree(tree);
cairo_destroy(context);
cairo_surface_destroy(surface);
if(rendering) {
xwindow_del(xwin);
}
return 0;
}
<commit_msg>Reverted back to phys.hpp<commit_after>#include "timing/timing.hpp"
#include "graphics/displayimage.hpp"
#include "tree.hpp"
#include <sys/stat.h>
#include <queue>
#include <string.h>
int main(int argc, char **argv)
{
cairo_surface_t *surface;
cairo_t *context;
int x, y, i,
width, height, depth,
screen, pressed_key,
png;
double r, b, v;
QTnode *tree;
bool rendering;
struct XWin **xwin;
/* Get the arguments */
if(argc != 3) {
printf("Usage: nbody rendering resultsdir\n");
exit(1);
}
if(*argv[1] == '0') {
rendering = false;
} else {
rendering = true;
}
char buf[strlen(argv[2]) + 10];
/* Set window size */
width = 1024;
height = 1024;
depth = 32;
/* Create the drawing surface */
if(rendering) {
/* Create the X11 window */
xwin = (struct XWin **)calloc(sizeof(struct XWin *), 1);
xwindow_init(width, height, depth, xwin);
surface = cairo_xlib_surface_create((*xwin)->dsp, (*xwin)->win, DefaultVisual((*xwin)->dsp, screen), width, height);
cairo_xlib_surface_set_size(surface, width, height);
} else {
surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height);
}
context = cairo_create(surface);
cairo_scale(context, width, height);
phys_init(1000);
png = 0;
while(1) {
if(rendering) {
if((*xwin)->should_close) {
break;
}
/* Wait on the input (also sync up to disable flickering) */
if(input_ready(xwin)) {
pressed_key = get_key(xwin);
}
}
/* Clear the surface with black */
cairo_set_source_rgb(context, 0.0, 0.0, 0.0);
cairo_paint(context);
for (int i = 0; i < N; i++) {
v = f2_norm(particles[i].vel);
if(v >= 0.4) {
r = 1.0; b = 0.0;
} else if(v < 0.5) {
b = 1.0; r = 0.0;
}
cairo_set_source_rgba(context, (double)r, 0.0, (double)b, 1.0);
cairo_rectangle(context, particles[i].pos.x,
particles[i].pos.y, 2e-3, 2e-3);
cairo_fill(context);
cairo_set_source_rgba(context, (double)r, 0.0, (double)b, 0.2);
cairo_rectangle(context, particles[i].pos.x - 1e-3,
particles[i].pos.y - 1e-3, 4e-3, 4e-3);
cairo_fill(context);
}
if(rendering) {
/* Flush the X window */
flush_input(xwin);
update_screen(xwin);
} else {
mkdir(argv[2], S_IRWXU | S_IRWXG);
sprintf(buf, "%s/%05d.png", argv[2], png++);
printf("Making %s\n", buf);
cairo_surface_write_to_png (surface, buf);
}
/* Get the new particles */
phys_step(1/60.0);
}
destroy_tree(tree);
cairo_destroy(context);
cairo_surface_destroy(surface);
if(rendering) {
xwindow_del(xwin);
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <math.h>
using namespace std;
int main(int argc, char* argv[]) {
if (argc != 2) {
cout << "This program requires 1 integer input!" << endl;
exit(0);
}
long totalSum = 0;
int inputtedNum = atoi(argv[1]);
for (int i = 1; i <= inputtedNum; i++) {
long val = (long)pow(i, i);
totalSum += val;
cout << val << endl;
}
cout << "Total Sum - " << totalSum <<endl;
return 0;
}
<commit_msg>Update SumOfSelfPowers.cpp<commit_after>#include <iostream>
#include <math.h>
using namespace std;
int main(int argc, char* argv[]) {
if (argc != 2) {
cout << "This program requires 1 integer input!" << endl;
exit(0);
}
long totalSum = 0;
int inputtedNum = atoi(argv[1]);
for (int i = 1; i <= inputtedNum; i++) {
long val = (long)pow(i, i);
totalSum += val;
cout << val << endl;
}
cout << "Total Sum - " << totalSum <<endl;
system("pause");
return 0;
}
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/DataStructures/DataGroupBuilder.h"
#include "SurgSim/Framework/Assert.h"
#include "SurgSim/Input/InputComponent.h"
#include "SurgSim/Input/OutputComponent.h"
#include "SurgSim/Math/Matrix.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Physics/RigidRepresentation.h"
#include "SurgSim/Physics/VirtualToolCoupler.h"
using SurgSim::Math::Vector3d;
using SurgSim::Math::Matrix33d;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Quaterniond;
namespace SurgSim
{
namespace Physics
{
Vector3d computeRotationVector(const RigidTransform3d& t1, const RigidTransform3d& t2)
{
Quaterniond q1(t1.linear());
Quaterniond q2(t2.linear());
double angle;
Vector3d axis;
SurgSim::Math::computeAngleAndAxis((q1 * q2.inverse()).normalized(), &angle, &axis);
return angle * axis;
}
VirtualToolCoupler::VirtualToolCoupler(const std::string& name) :
SurgSim::Framework::Behavior(name),
m_poseName("pose"),
m_linearStiffness(0.0),
m_linearDamping(0.0),
m_angularStiffness(0.0),
m_angularDamping(0.0),
m_outputForceScaling(1.0),
m_outputTorqueScaling(1.0)
{
SurgSim::DataStructures::DataGroupBuilder builder;
builder.addVector("force");
builder.addMatrix("forcePositionJacobian");
builder.addVector("inputPosition");
builder.addMatrix("forceLinearVelocityJacobian");
builder.addVector("inputLinearVelocity");
builder.addVector("torque");
builder.addMatrix("torqueAngleJacobian");
builder.addMatrix("inputOrientation");
builder.addMatrix("torqueAngularVelocityJacobian");
builder.addVector("inputAngularVelocity");
m_outputData = builder.createData();
}
VirtualToolCoupler::~VirtualToolCoupler()
{
}
void VirtualToolCoupler::setInput(const std::shared_ptr<SurgSim::Input::InputComponent> input)
{
m_input = input;
}
void VirtualToolCoupler::setOutput(const std::shared_ptr<SurgSim::Input::OutputComponent> output)
{
m_output = output;
}
void VirtualToolCoupler::setRepresentation(const std::shared_ptr<SurgSim::Physics::RigidRepresentation> rigid)
{
m_rigid = rigid;
}
void VirtualToolCoupler::setPoseName(const std::string& poseName)
{
m_poseName = poseName;
}
void VirtualToolCoupler::update(double dt)
{
SurgSim::DataStructures::DataGroup inputData;
SURGSIM_ASSERT(m_input) << "VirtualToolCoupler named " << getName() << " does not have an Input Component.";
m_input->getData(&inputData);
RigidTransform3d inputPose;
if (inputData.poses().get(m_poseName, &inputPose))
{
// TODO(ryanbeasley): If the RigidRepresentation is not colliding, we should turn off the VTC forces and set the
// RigidRepresentation's state to the input state.
Vector3d inputLinearVelocity, inputAngularVelocity;
inputLinearVelocity.setZero();
inputData.vectors().get("linearVelocity", &inputLinearVelocity);
inputAngularVelocity.setZero();
inputData.vectors().get("angularVelocity", &inputAngularVelocity);
SURGSIM_ASSERT(m_rigid) << "VirtualToolCoupler named " << getName() << " does not have a Representation.";
RigidRepresentationState objectState(m_rigid->getCurrentState());
RigidTransform3d objectPose(objectState.getPose());
Vector3d force = m_linearStiffness * (inputPose.translation() - objectPose.translation());
force += m_linearDamping * (inputLinearVelocity - objectState.getLinearVelocity());
Vector3d torque = m_angularStiffness * computeRotationVector(inputPose, objectPose);
torque += m_angularDamping * (inputAngularVelocity - objectState.getAngularVelocity());
const Matrix33d identity3x3 = Matrix33d::Identity();
const Matrix33d linearStiffnessMatrix = m_linearStiffness * identity3x3;
const Matrix33d linearDampingMatrix = m_linearDamping * identity3x3;
const Matrix33d angularStiffnessMatrix = m_angularStiffness * identity3x3;
const Matrix33d angularDampingMatrix = m_angularDamping * identity3x3;
m_rigid->addExternalForce(force, linearStiffnessMatrix, linearDampingMatrix);
m_rigid->addExternalTorque(torque, angularStiffnessMatrix, angularDampingMatrix);
if (m_output)
{
m_outputData.vectors().set("force", -force * m_outputForceScaling);
m_outputData.matrices().set("forcePositionJacobian", -linearStiffnessMatrix * m_outputForceScaling);
m_outputData.vectors().set("inputPosition", inputPose.translation());
m_outputData.matrices().set("forceVelocityJacobian", -linearDampingMatrix * m_outputForceScaling);
m_outputData.vectors().set("inputLinearVelocity", inputLinearVelocity);
m_outputData.vectors().set("torque", -force * m_outputForceScaling);
m_outputData.matrices().set("torqueAngleJacobian", -angularStiffnessMatrix * m_outputForceScaling);
m_outputData.matrices().set("inputOrientation", inputPose.linear());
m_outputData.matrices().set("torqueAngularVelocityJacobian", -angularDampingMatrix * m_outputForceScaling);
m_outputData.vectors().set("inputAngularVelocity", inputAngularVelocity);
m_output->setData(m_outputData);
}
}
}
bool VirtualToolCoupler::doInitialize()
{
return true;
}
bool VirtualToolCoupler::doWakeUp()
{
return true;
}
int VirtualToolCoupler::getTargetManagerType() const
{
return SurgSim::Framework::MANAGER_TYPE_PHYSICS;
}
void VirtualToolCoupler::setLinearStiffness(double linearStiffness)
{
m_linearStiffness = linearStiffness;
}
void VirtualToolCoupler::setLinearDamping(double linearDamping)
{
m_linearDamping = linearDamping;
}
void VirtualToolCoupler::setAngularStiffness(double angularStiffness)
{
m_angularStiffness = angularStiffness;
}
void VirtualToolCoupler::setAngularDamping(double angularDamping)
{
m_angularDamping = angularDamping;
}
void VirtualToolCoupler::setOutputForceScaling(double forceScaling)
{
m_outputForceScaling = forceScaling;
}
void VirtualToolCoupler::setOutputTorqueScaling(double torqueScaling)
{
m_outputTorqueScaling = torqueScaling;
}
}; /// Physics
}; /// SurgSim
<commit_msg>Fix name of data in output DataGroup in VirtualToolCoupler.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/DataStructures/DataGroupBuilder.h"
#include "SurgSim/Framework/Assert.h"
#include "SurgSim/Input/InputComponent.h"
#include "SurgSim/Input/OutputComponent.h"
#include "SurgSim/Math/Matrix.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Physics/RigidRepresentation.h"
#include "SurgSim/Physics/VirtualToolCoupler.h"
using SurgSim::Math::Vector3d;
using SurgSim::Math::Matrix33d;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Quaterniond;
namespace SurgSim
{
namespace Physics
{
Vector3d computeRotationVector(const RigidTransform3d& t1, const RigidTransform3d& t2)
{
Quaterniond q1(t1.linear());
Quaterniond q2(t2.linear());
double angle;
Vector3d axis;
SurgSim::Math::computeAngleAndAxis((q1 * q2.inverse()).normalized(), &angle, &axis);
return angle * axis;
}
VirtualToolCoupler::VirtualToolCoupler(const std::string& name) :
SurgSim::Framework::Behavior(name),
m_poseName("pose"),
m_linearStiffness(0.0),
m_linearDamping(0.0),
m_angularStiffness(0.0),
m_angularDamping(0.0),
m_outputForceScaling(1.0),
m_outputTorqueScaling(1.0)
{
SurgSim::DataStructures::DataGroupBuilder builder;
builder.addVector("force");
builder.addMatrix("forcePositionJacobian");
builder.addVector("inputPosition");
builder.addMatrix("forceLinearVelocityJacobian");
builder.addVector("inputLinearVelocity");
builder.addVector("torque");
builder.addMatrix("torqueAngleJacobian");
builder.addMatrix("inputOrientation");
builder.addMatrix("torqueAngularVelocityJacobian");
builder.addVector("inputAngularVelocity");
m_outputData = builder.createData();
}
VirtualToolCoupler::~VirtualToolCoupler()
{
}
void VirtualToolCoupler::setInput(const std::shared_ptr<SurgSim::Input::InputComponent> input)
{
m_input = input;
}
void VirtualToolCoupler::setOutput(const std::shared_ptr<SurgSim::Input::OutputComponent> output)
{
m_output = output;
}
void VirtualToolCoupler::setRepresentation(const std::shared_ptr<SurgSim::Physics::RigidRepresentation> rigid)
{
m_rigid = rigid;
}
void VirtualToolCoupler::setPoseName(const std::string& poseName)
{
m_poseName = poseName;
}
void VirtualToolCoupler::update(double dt)
{
SurgSim::DataStructures::DataGroup inputData;
SURGSIM_ASSERT(m_input) << "VirtualToolCoupler named " << getName() << " does not have an Input Component.";
m_input->getData(&inputData);
RigidTransform3d inputPose;
if (inputData.poses().get(m_poseName, &inputPose))
{
// TODO(ryanbeasley): If the RigidRepresentation is not colliding, we should turn off the VTC forces and set the
// RigidRepresentation's state to the input state.
Vector3d inputLinearVelocity, inputAngularVelocity;
inputLinearVelocity.setZero();
inputData.vectors().get("linearVelocity", &inputLinearVelocity);
inputAngularVelocity.setZero();
inputData.vectors().get("angularVelocity", &inputAngularVelocity);
SURGSIM_ASSERT(m_rigid) << "VirtualToolCoupler named " << getName() << " does not have a Representation.";
RigidRepresentationState objectState(m_rigid->getCurrentState());
RigidTransform3d objectPose(objectState.getPose());
Vector3d force = m_linearStiffness * (inputPose.translation() - objectPose.translation());
force += m_linearDamping * (inputLinearVelocity - objectState.getLinearVelocity());
Vector3d torque = m_angularStiffness * computeRotationVector(inputPose, objectPose);
torque += m_angularDamping * (inputAngularVelocity - objectState.getAngularVelocity());
const Matrix33d identity3x3 = Matrix33d::Identity();
const Matrix33d linearStiffnessMatrix = m_linearStiffness * identity3x3;
const Matrix33d linearDampingMatrix = m_linearDamping * identity3x3;
const Matrix33d angularStiffnessMatrix = m_angularStiffness * identity3x3;
const Matrix33d angularDampingMatrix = m_angularDamping * identity3x3;
m_rigid->addExternalForce(force, linearStiffnessMatrix, linearDampingMatrix);
m_rigid->addExternalTorque(torque, angularStiffnessMatrix, angularDampingMatrix);
if (m_output)
{
m_outputData.vectors().set("force", -force * m_outputForceScaling);
m_outputData.matrices().set("forcePositionJacobian", -linearStiffnessMatrix * m_outputForceScaling);
m_outputData.vectors().set("inputPosition", inputPose.translation());
m_outputData.matrices().set("forceLinearVelocityJacobian", -linearDampingMatrix * m_outputForceScaling);
m_outputData.vectors().set("inputLinearVelocity", inputLinearVelocity);
m_outputData.vectors().set("torque", -force * m_outputForceScaling);
m_outputData.matrices().set("torqueAngleJacobian", -angularStiffnessMatrix * m_outputForceScaling);
m_outputData.matrices().set("inputOrientation", inputPose.linear());
m_outputData.matrices().set("torqueAngularVelocityJacobian", -angularDampingMatrix * m_outputForceScaling);
m_outputData.vectors().set("inputAngularVelocity", inputAngularVelocity);
m_output->setData(m_outputData);
}
}
}
bool VirtualToolCoupler::doInitialize()
{
return true;
}
bool VirtualToolCoupler::doWakeUp()
{
return true;
}
int VirtualToolCoupler::getTargetManagerType() const
{
return SurgSim::Framework::MANAGER_TYPE_PHYSICS;
}
void VirtualToolCoupler::setLinearStiffness(double linearStiffness)
{
m_linearStiffness = linearStiffness;
}
void VirtualToolCoupler::setLinearDamping(double linearDamping)
{
m_linearDamping = linearDamping;
}
void VirtualToolCoupler::setAngularStiffness(double angularStiffness)
{
m_angularStiffness = angularStiffness;
}
void VirtualToolCoupler::setAngularDamping(double angularDamping)
{
m_angularDamping = angularDamping;
}
void VirtualToolCoupler::setOutputForceScaling(double forceScaling)
{
m_outputForceScaling = forceScaling;
}
void VirtualToolCoupler::setOutputTorqueScaling(double torqueScaling)
{
m_outputTorqueScaling = torqueScaling;
}
}; /// Physics
}; /// SurgSim
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkRawImageIOTest3.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
//#include <iostream>
#include <fstream>
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkRawImageIO.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIterator.h"
int itkRawImageIOTest3(int, char**)
{
typedef itk::Image<unsigned short,2> ImageType;
typedef ImageType::PixelType PixelType;
typedef itk::ImageRegionIterator<
ImageType > ImageIteratorType;
typedef itk::ImageRegionConstIterator<
ImageType > ImageConstIteratorType;
typedef itk::RawImageIO<PixelType,
ImageType::ImageDimension> RawImageIOType;
// Create a source object (in this case a random image generator).
// The source object is templated on the output type.
//
ImageType::SizeType size;
size[0]=517; // prime numbers are good bug testers...
size[1]=293;
ImageType::RegionType region;
region.SetIndex( ImageType::IndexType::ZeroIndex );
region.SetSize(size);
ImageType::Pointer image = ImageType::New();
image->SetRegions( region );
image->Allocate();
ImageIteratorType ii( image, region );
PixelType value = itk::NumericTraits< PixelType >::Zero;
ii.GoToBegin();
while( ii.IsAtEnd() )
{
ii.Set( value );
++value;
++ii;
}
RawImageIOType::Pointer io = RawImageIOType::New();
// Write out the image
itk::ImageFileWriter<ImageType>::Pointer writer;
writer = itk::ImageFileWriter<ImageType>::New();
writer->SetInput( image );
writer->SetFileName("junk.raw");
writer->SetImageIO(io);
writer->Write();
// Create a source object (in this case a reader)
itk::ImageFileReader<ImageType>::Pointer reader;
reader = itk::ImageFileReader<ImageType>::New();
reader->SetImageIO(io);
reader->SetFileName("junk.raw");
reader->Update();
// Compare pixel by pixel in memory
ImageConstIteratorType it( reader->GetOutput(),
reader->GetOutput()->GetBufferedRegion() );
ImageConstIteratorType ot( image,
image->GetBufferedRegion() );
it.GoToBegin();
ot.GoToBegin();
while( !it.IsAtEnd() )
{
const PixelType iv = it.Get();
const PixelType ov = ot.Get();
if( iv != ov )
{
std::cerr << "Error in read/write of pixel " << it.GetIndex() << std::endl;
std::cerr << "Read value is : " << iv << std::endl;
std::cerr << "it should be : " << ov << std::endl;
std::cerr << "Test FAILED ! " << std::endl;
return EXIT_FAILURE;
}
++it;
++ot;
}
writer->SetInput(reader->GetOutput());
writer->SetFileName("junk2.raw");
writer->SetInput(reader->GetOutput());
writer->Write();
std::cerr << "Test PASSED ! " << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>FIX: IsAtEnd() wasn't negated in a while loop<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkRawImageIOTest3.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
//#include <iostream>
#include <fstream>
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkRawImageIO.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIterator.h"
int itkRawImageIOTest3(int, char**)
{
typedef itk::Image<unsigned short,2> ImageType;
typedef ImageType::PixelType PixelType;
typedef itk::ImageRegionIterator<
ImageType > ImageIteratorType;
typedef itk::ImageRegionConstIterator<
ImageType > ImageConstIteratorType;
typedef itk::RawImageIO<PixelType,
ImageType::ImageDimension> RawImageIOType;
// Create a source object (in this case a random image generator).
// The source object is templated on the output type.
//
ImageType::SizeType size;
size[0]=517; // prime numbers are good bug testers...
size[1]=293;
ImageType::RegionType region;
region.SetIndex( ImageType::IndexType::ZeroIndex );
region.SetSize(size);
ImageType::Pointer image = ImageType::New();
image->SetRegions( region );
image->Allocate();
ImageIteratorType ii( image, region );
PixelType value = itk::NumericTraits< PixelType >::Zero;
ii.GoToBegin();
while( !ii.IsAtEnd() )
{
ii.Set( value );
++value;
++ii;
}
RawImageIOType::Pointer io = RawImageIOType::New();
io->SetByteOrderToBigEndian();
// Write out the image
itk::ImageFileWriter<ImageType>::Pointer writer;
writer = itk::ImageFileWriter<ImageType>::New();
writer->SetInput( image );
writer->SetFileName("junk.raw");
writer->SetImageIO(io);
writer->Write();
// Create a source object (in this case a reader)
itk::ImageFileReader<ImageType>::Pointer reader;
reader = itk::ImageFileReader<ImageType>::New();
reader->SetImageIO(io);
reader->SetFileName("junk.raw");
reader->Update();
// Compare pixel by pixel in memory
ImageConstIteratorType it( reader->GetOutput(),
reader->GetOutput()->GetBufferedRegion() );
ImageConstIteratorType ot( image,
image->GetBufferedRegion() );
it.GoToBegin();
ot.GoToBegin();
while( !it.IsAtEnd() )
{
const PixelType iv = it.Get();
const PixelType ov = ot.Get();
if( iv != ov )
{
std::cerr << "Error in read/write of pixel " << it.GetIndex() << std::endl;
std::cerr << "Read value is : " << iv << std::endl;
std::cerr << "it should be : " << ov << std::endl;
std::cerr << "Test FAILED ! " << std::endl;
return EXIT_FAILURE;
}
++it;
++ot;
}
writer->SetInput(reader->GetOutput());
writer->SetFileName("junk2.raw");
writer->SetInput(reader->GetOutput());
writer->Write();
std::cerr << "Test PASSED ! " << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkRawImageIOTest5.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <fstream>
#include "itkRawImageIO.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkImageRegionIterator.h"
template <class TPixel>
class RawImageReaderAndWriter
{
public:
typedef unsigned char PixelType;
typedef itk::RawImageIO< PixelType, 2 > RawImageIOType;
typedef itk::Image< PixelType, 2 > ImageType;
public:
RawImageReaderAndWriter()
{
m_Image = ImageType::New();
typename ImageType::RegionType region;
typename ImageType::SizeType size;
typename ImageType::IndexType start;
size[0] = 16; // To fill the range of 8 bits image
size[1] = 16;
region.SetSize( size );
region.SetIndex( start );
m_Image->SetRegions( region );
m_Image->Allocate();
PixelType value = itk::NumericTraits< PixelType >::Zero;
// Fill the image with incremental values.
typedef itk::ImageRegionIterator< ImageType > IteratorType;
IteratorType it( m_Image, region );
it.GoToBegin();
while( it.IsAtEnd() )
{
it.Set( value );
++value;
++it;
}
m_Error = false;
}
void Write()
{
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( m_FileName.c_str() );
writer->SetInput( m_Image );
RawImageIOType::Pointer rawImageIO = RawImageIOType::New();
writer->SetImageIO( rawImageIO );
writer->Update();
}
void Read()
{
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( m_FileName.c_str() );
RawImageIOType::Pointer rawImageIO = RawImageIOType::New();
reader->SetImageIO( rawImageIO );
reader->Update();
ImageType::ConstPointer image = reader->GetOutput();
//
// Verify the content of the image.
//
typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType;
ConstIteratorType it1( m_Image, m_Image->GetLargestPossibleRegion() );
ConstIteratorType it2( image, image->GetLargestPossibleRegion() );
it1.GoToBegin();
it2.GoToBegin();
m_Error = false;
while( it1.IsAtEnd() )
{
if( it1.Get() != it1.Get() )
{
m_Error = true;
break;
}
++it1;
++it2;
}
}
void SetFileName( const std::string & filename )
{
m_FileName = filename;
}
bool GetError() const
{
return m_Error;
}
private:
std::string m_FileName;
typename ImageType::Pointer m_Image;
bool m_Error;
};
int itkRawImageIOTest5(int argc, char*argv[])
{
if(argc < 2)
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " TemporaryDirectoryName" << std::endl;
return EXIT_FAILURE;
}
std::string directory = argv[1];
//
// Test the pixel type = "char"
//
std::cout << "Testing for pixel type = char " << std::endl;
RawImageReaderAndWriter< char > tester1;
std::string filename = directory + "/RawImageIOTest5a.raw";
tester1.SetFileName( filename );
try
{
tester1.Write();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught while writing char type." << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
try
{
tester1.Read();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught while reading char type." << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
if( tester1.GetError() )
{
std::cerr << "Error while comparing the char type images." << std::endl;
return EXIT_FAILURE;
}
//
// Test the pixel type = "signed char"
//
std::cout << "Testing for pixel type = signed char " << std::endl;
RawImageReaderAndWriter< signed char > tester2;
filename = directory + "/RawImageIOTest5b.raw";
tester2.SetFileName( filename );
try
{
tester2.Write();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught while writing signed char type." << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
try
{
tester2.Read();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught while reading signed char type." << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
if( tester2.GetError() )
{
std::cerr << "Error while comparing the signed char type images." << std::endl;
return EXIT_FAILURE;
}
//
// Test the pixel type = "unsigned char"
//
std::cout << "Testing for pixel type = unsigned char " << std::endl;
RawImageReaderAndWriter< unsigned char > tester3;
filename = directory + "/RawImageIOTest5c.raw";
tester3.SetFileName( filename );
try
{
tester3.Write();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught while writing unsigned char type." << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
try
{
tester3.Read();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught while reading unsigned char type." << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
if( tester3.GetError() )
{
std::cerr << "Error while comparing the unsigned char type images." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test PASSED !!" << std::endl << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>ENH: Adding setup code for the RawImageIO object.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkRawImageIOTest5.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <fstream>
#include "itkRawImageIO.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkImageRegionIterator.h"
template <class TPixel>
class RawImageReaderAndWriter
{
public:
typedef unsigned char PixelType;
typedef itk::RawImageIO< PixelType, 2 > RawImageIOType;
typedef itk::Image< PixelType, 2 > ImageType;
public:
RawImageReaderAndWriter()
{
m_Image = ImageType::New();
typename ImageType::RegionType region;
typename ImageType::SizeType size;
typename ImageType::IndexType start;
size[0] = 16; // To fill the range of 8 bits image
size[1] = 16;
region.SetSize( size );
region.SetIndex( start );
m_Image->SetRegions( region );
m_Image->Allocate();
PixelType value = itk::NumericTraits< PixelType >::Zero;
// Fill the image with incremental values.
typedef itk::ImageRegionIterator< ImageType > IteratorType;
IteratorType it( m_Image, region );
it.GoToBegin();
while( it.IsAtEnd() )
{
it.Set( value );
++value;
++it;
}
m_Error = false;
}
void Write()
{
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( m_FileName.c_str() );
writer->SetInput( m_Image );
RawImageIOType::Pointer rawImageIO = RawImageIOType::New();
writer->SetImageIO( rawImageIO );
writer->Update();
}
void Read()
{
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( m_FileName.c_str() );
RawImageIOType::Pointer rawImageIO = RawImageIOType::New();
reader->SetImageIO( rawImageIO );
unsigned int dim[2] = {16,16};
double spacing[2] = {1.0, 1.0};
double origin[2] = {0.0,0.0};
for(unsigned int i=0; i<2; i++)
{
rawImageIO->SetDimensions(i,dim[i]);
rawImageIO->SetSpacing(i,spacing[i]);
rawImageIO->SetOrigin(i,origin[i]);
}
rawImageIO->SetHeaderSize(0);
rawImageIO->SetByteOrderToLittleEndian();
rawImageIO->SetNumberOfComponents(1);
reader->Update();
ImageType::ConstPointer image = reader->GetOutput();
//
// Verify the content of the image.
//
typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType;
ConstIteratorType it1( m_Image, m_Image->GetLargestPossibleRegion() );
ConstIteratorType it2( image, image->GetLargestPossibleRegion() );
it1.GoToBegin();
it2.GoToBegin();
m_Error = false;
while( it1.IsAtEnd() )
{
if( it1.Get() != it1.Get() )
{
m_Error = true;
break;
}
++it1;
++it2;
}
}
void SetFileName( const std::string & filename )
{
m_FileName = filename;
}
bool GetError() const
{
return m_Error;
}
private:
std::string m_FileName;
typename ImageType::Pointer m_Image;
bool m_Error;
};
int itkRawImageIOTest5(int argc, char*argv[])
{
if(argc < 2)
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " TemporaryDirectoryName" << std::endl;
return EXIT_FAILURE;
}
std::string directory = argv[1];
//
// Test the pixel type = "char"
//
std::cout << "Testing for pixel type = char " << std::endl;
RawImageReaderAndWriter< char > tester1;
std::string filename = directory + "/RawImageIOTest5a.raw";
tester1.SetFileName( filename );
try
{
tester1.Write();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught while writing char type." << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
try
{
tester1.Read();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught while reading char type." << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
if( tester1.GetError() )
{
std::cerr << "Error while comparing the char type images." << std::endl;
return EXIT_FAILURE;
}
//
// Test the pixel type = "signed char"
//
std::cout << "Testing for pixel type = signed char " << std::endl;
RawImageReaderAndWriter< signed char > tester2;
filename = directory + "/RawImageIOTest5b.raw";
tester2.SetFileName( filename );
try
{
tester2.Write();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught while writing signed char type." << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
try
{
tester2.Read();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught while reading signed char type." << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
if( tester2.GetError() )
{
std::cerr << "Error while comparing the signed char type images." << std::endl;
return EXIT_FAILURE;
}
//
// Test the pixel type = "unsigned char"
//
std::cout << "Testing for pixel type = unsigned char " << std::endl;
RawImageReaderAndWriter< unsigned char > tester3;
filename = directory + "/RawImageIOTest5c.raw";
tester3.SetFileName( filename );
try
{
tester3.Write();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught while writing unsigned char type." << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
try
{
tester3.Read();
}
catch( itk::ExceptionObject & excp )
{
std::cerr << "Exception caught while reading unsigned char type." << std::endl;
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
if( tester3.GetError() )
{
std::cerr << "Error while comparing the unsigned char type images." << std::endl;
return EXIT_FAILURE;
}
std::cout << "Test PASSED !!" << std::endl << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2013 Torus Knot Software Ltd
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 "ZipArchiveTests.h"
#include "OgreZip.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include "macUtils.h"
#endif
using namespace Ogre;
// Register the suite
CPPUNIT_TEST_SUITE_REGISTRATION( ZipArchiveTests );
void ZipArchiveTests::setUp()
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
testPath = macBundlePath() + "/Contents/Resources/Media/misc/ArchiveTest.zip";
#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32
testPath = "./Tests/OgreMain/misc/ArchiveTest.zip";
#else
testPath = "../Tests/OgreMain/misc/ArchiveTest.zip";
#endif
}
void ZipArchiveTests::tearDown()
{
}
void ZipArchiveTests::testListNonRecursive()
{
ZipArchive arch(testPath, "Zip");
arch.load();
StringVectorPtr vec = arch.list(false);
CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size());
CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(0));
CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(1));
}
void ZipArchiveTests::testListRecursive()
{
ZipArchive arch(testPath, "Zip");
arch.load();
StringVectorPtr vec = arch.list(true);
CPPUNIT_ASSERT_EQUAL((size_t)6, vec->size());
CPPUNIT_ASSERT_EQUAL(String("file.material"), vec->at(0));
CPPUNIT_ASSERT_EQUAL(String("file2.material"), vec->at(1));
CPPUNIT_ASSERT_EQUAL(String("file3.material"), vec->at(2));
CPPUNIT_ASSERT_EQUAL(String("file4.material"), vec->at(3));
CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(4));
CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(5));
}
void ZipArchiveTests::testListFileInfoNonRecursive()
{
ZipArchive arch(testPath, "Zip");
arch.load();
FileInfoListPtr vec = arch.listFileInfo(false);
CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size());
FileInfo& fi1 = vec->at(0);
CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename);
CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path);
CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize);
FileInfo& fi2 = vec->at(1);
CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename);
CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path);
CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize);
}
void ZipArchiveTests::testListFileInfoRecursive()
{
ZipArchive arch(testPath, "Zip");
arch.load();
FileInfoListPtr vec = arch.listFileInfo(true);
CPPUNIT_ASSERT_EQUAL((size_t)6, vec->size());
FileInfo& fi3 = vec->at(0);
CPPUNIT_ASSERT_EQUAL(String("file.material"), fi3.filename);
CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi3.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.uncompressedSize);
FileInfo& fi4 = vec->at(1);
CPPUNIT_ASSERT_EQUAL(String("file2.material"), fi4.filename);
CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi4.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.uncompressedSize);
FileInfo& fi5 = vec->at(2);
CPPUNIT_ASSERT_EQUAL(String("file3.material"), fi5.filename);
CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi5.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.uncompressedSize);
FileInfo& fi6 = vec->at(3);
CPPUNIT_ASSERT_EQUAL(String("file4.material"), fi6.filename);
CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi6.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.uncompressedSize);
FileInfo& fi1 = vec->at(4);
CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename);
CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path);
CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize);
FileInfo& fi2 = vec->at(5);
CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename);
CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path);
CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize);
}
void ZipArchiveTests::testFindNonRecursive()
{
ZipArchive arch(testPath, "Zip");
arch.load();
StringVectorPtr vec = arch.find("*.txt", false);
CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size());
CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(0));
CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(1));
}
void ZipArchiveTests::testFindRecursive()
{
ZipArchive arch(testPath, "Zip");
arch.load();
StringVectorPtr vec = arch.find("*.material", true);
CPPUNIT_ASSERT_EQUAL((size_t)4, vec->size());
CPPUNIT_ASSERT_EQUAL(String("file.material"), vec->at(0));
CPPUNIT_ASSERT_EQUAL(String("file2.material"), vec->at(1));
CPPUNIT_ASSERT_EQUAL(String("file3.material"), vec->at(2));
CPPUNIT_ASSERT_EQUAL(String("file4.material"), vec->at(3));
}
void ZipArchiveTests::testFindFileInfoNonRecursive()
{
ZipArchive arch(testPath, "Zip");
arch.load();
FileInfoListPtr vec = arch.findFileInfo("*.txt", false);
CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size());
FileInfo& fi1 = vec->at(0);
CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename);
CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path);
CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize);
FileInfo& fi2 = vec->at(1);
CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename);
CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path);
CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize);
}
void ZipArchiveTests::testFindFileInfoRecursive()
{
ZipArchive arch(testPath, "Zip");
arch.load();
FileInfoListPtr vec = arch.findFileInfo("*.material", true);
CPPUNIT_ASSERT_EQUAL((size_t)4, vec->size());
FileInfo& fi3 = vec->at(0);
CPPUNIT_ASSERT_EQUAL(String("file.material"), fi3.filename);
CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi3.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.uncompressedSize);
FileInfo& fi4 = vec->at(1);
CPPUNIT_ASSERT_EQUAL(String("file2.material"), fi4.filename);
CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi4.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.uncompressedSize);
FileInfo& fi5 = vec->at(2);
CPPUNIT_ASSERT_EQUAL(String("file3.material"), fi5.filename);
CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi5.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.uncompressedSize);
FileInfo& fi6 = vec->at(3);
CPPUNIT_ASSERT_EQUAL(String("file4.material"), fi6.filename);
CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi6.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.uncompressedSize);
}
void ZipArchiveTests::testFileRead()
{
ZipArchive arch(testPath, "Zip");
arch.load();
DataStreamPtr stream = arch.open("rootfile.txt");
CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 1"), stream->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 1"), stream->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 1"), stream->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 1"), stream->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 1"), stream->getLine());
CPPUNIT_ASSERT(stream->eof());
}
void ZipArchiveTests::testReadInterleave()
{
// Test overlapping reads from same archive
ZipArchive arch(testPath, "Zip");
arch.load();
// File 1
DataStreamPtr stream1 = arch.open("rootfile.txt");
CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 1"), stream1->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 1"), stream1->getLine());
// File 2
DataStreamPtr stream2 = arch.open("rootfile2.txt");
CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 2"), stream2->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 2"), stream2->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 2"), stream2->getLine());
// File 1
CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 1"), stream1->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 1"), stream1->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 1"), stream1->getLine());
CPPUNIT_ASSERT(stream1->eof());
// File 2
CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 2"), stream2->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 2"), stream2->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 6 in file 2"), stream2->getLine());
CPPUNIT_ASSERT(stream2->eof());
}
<commit_msg>Add fallback path for ZipArchiveTests.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2013 Torus Knot Software Ltd
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 "ZipArchiveTests.h"
#include "OgreZip.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include "macUtils.h"
#endif
using namespace Ogre;
// Register the suite
CPPUNIT_TEST_SUITE_REGISTRATION( ZipArchiveTests );
void ZipArchiveTests::setUp()
{
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
testPath = macBundlePath() + "/Contents/Resources/Media/misc/ArchiveTest.zip";
#elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32
testPath = "./Tests/OgreMain/misc/ArchiveTest.zip";
#else
testPath = "../Tests/OgreMain/misc/ArchiveTest.zip";
#endif
}
void ZipArchiveTests::tearDown()
{
}
void ZipArchiveTests::testListNonRecursive()
{
ZipArchive arch(testPath, "Zip");
try {
arch.load();
} catch (Ogre::Exception e) {
// If it starts in build/bin/debug
arch = ZipArchive("../../../" + testPath, "Zip");
arch.load();
}
StringVectorPtr vec = arch.list(false);
CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size());
CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(0));
CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(1));
}
void ZipArchiveTests::testListRecursive()
{
ZipArchive arch(testPath, "Zip");
try {
arch.load();
}
catch (Ogre::Exception e) {
// If it starts in build/bin/debug
arch = ZipArchive("../../../" + testPath, "Zip");
arch.load();
}
StringVectorPtr vec = arch.list(true);
CPPUNIT_ASSERT_EQUAL((size_t)6, vec->size());
CPPUNIT_ASSERT_EQUAL(String("file.material"), vec->at(0));
CPPUNIT_ASSERT_EQUAL(String("file2.material"), vec->at(1));
CPPUNIT_ASSERT_EQUAL(String("file3.material"), vec->at(2));
CPPUNIT_ASSERT_EQUAL(String("file4.material"), vec->at(3));
CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(4));
CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(5));
}
void ZipArchiveTests::testListFileInfoNonRecursive()
{
ZipArchive arch(testPath, "Zip");
try {
arch.load();
}
catch (Ogre::Exception e) {
// If it starts in build/bin/debug
arch = ZipArchive("../../../" + testPath, "Zip");
arch.load();
}
FileInfoListPtr vec = arch.listFileInfo(false);
CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size());
FileInfo& fi1 = vec->at(0);
CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename);
CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path);
CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize);
FileInfo& fi2 = vec->at(1);
CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename);
CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path);
CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize);
}
void ZipArchiveTests::testListFileInfoRecursive()
{
ZipArchive arch(testPath, "Zip");
try {
arch.load();
}
catch (Ogre::Exception e) {
// If it starts in build/bin/debug
arch = ZipArchive("../../../" + testPath, "Zip");
arch.load();
}
FileInfoListPtr vec = arch.listFileInfo(true);
CPPUNIT_ASSERT_EQUAL((size_t)6, vec->size());
FileInfo& fi3 = vec->at(0);
CPPUNIT_ASSERT_EQUAL(String("file.material"), fi3.filename);
CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi3.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.uncompressedSize);
FileInfo& fi4 = vec->at(1);
CPPUNIT_ASSERT_EQUAL(String("file2.material"), fi4.filename);
CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi4.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.uncompressedSize);
FileInfo& fi5 = vec->at(2);
CPPUNIT_ASSERT_EQUAL(String("file3.material"), fi5.filename);
CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi5.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.uncompressedSize);
FileInfo& fi6 = vec->at(3);
CPPUNIT_ASSERT_EQUAL(String("file4.material"), fi6.filename);
CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi6.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.uncompressedSize);
FileInfo& fi1 = vec->at(4);
CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename);
CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path);
CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize);
FileInfo& fi2 = vec->at(5);
CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename);
CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path);
CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize);
}
void ZipArchiveTests::testFindNonRecursive()
{
ZipArchive arch(testPath, "Zip");
try {
arch.load();
}
catch (Ogre::Exception e) {
// If it starts in build/bin/debug
arch = ZipArchive("../../../" + testPath, "Zip");
arch.load();
}
StringVectorPtr vec = arch.find("*.txt", false);
CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size());
CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), vec->at(0));
CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), vec->at(1));
}
void ZipArchiveTests::testFindRecursive()
{
ZipArchive arch(testPath, "Zip");
try {
arch.load();
}
catch (Ogre::Exception e) {
// If it starts in build/bin/debug
arch = ZipArchive("../../../" + testPath, "Zip");
arch.load();
}
StringVectorPtr vec = arch.find("*.material", true);
CPPUNIT_ASSERT_EQUAL((size_t)4, vec->size());
CPPUNIT_ASSERT_EQUAL(String("file.material"), vec->at(0));
CPPUNIT_ASSERT_EQUAL(String("file2.material"), vec->at(1));
CPPUNIT_ASSERT_EQUAL(String("file3.material"), vec->at(2));
CPPUNIT_ASSERT_EQUAL(String("file4.material"), vec->at(3));
}
void ZipArchiveTests::testFindFileInfoNonRecursive()
{
ZipArchive arch(testPath, "Zip");
try {
arch.load();
}
catch (Ogre::Exception e) {
// If it starts in build/bin/debug
arch = ZipArchive("../../../" + testPath, "Zip");
arch.load();
}
FileInfoListPtr vec = arch.findFileInfo("*.txt", false);
CPPUNIT_ASSERT_EQUAL((size_t)2, vec->size());
FileInfo& fi1 = vec->at(0);
CPPUNIT_ASSERT_EQUAL(String("rootfile.txt"), fi1.filename);
CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi1.path);
CPPUNIT_ASSERT_EQUAL((size_t)40, fi1.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)130, fi1.uncompressedSize);
FileInfo& fi2 = vec->at(1);
CPPUNIT_ASSERT_EQUAL(String("rootfile2.txt"), fi2.filename);
CPPUNIT_ASSERT_EQUAL(StringUtil::BLANK, fi2.path);
CPPUNIT_ASSERT_EQUAL((size_t)45, fi2.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)156, fi2.uncompressedSize);
}
void ZipArchiveTests::testFindFileInfoRecursive()
{
ZipArchive arch(testPath, "Zip");
try {
arch.load();
}
catch (Ogre::Exception e) {
// If it starts in build/bin/debug
arch = ZipArchive("../../../" + testPath, "Zip");
arch.load();
}
FileInfoListPtr vec = arch.findFileInfo("*.material", true);
CPPUNIT_ASSERT_EQUAL((size_t)4, vec->size());
FileInfo& fi3 = vec->at(0);
CPPUNIT_ASSERT_EQUAL(String("file.material"), fi3.filename);
CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi3.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi3.uncompressedSize);
FileInfo& fi4 = vec->at(1);
CPPUNIT_ASSERT_EQUAL(String("file2.material"), fi4.filename);
CPPUNIT_ASSERT_EQUAL(String("level1/materials/scripts/"), fi4.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi4.uncompressedSize);
FileInfo& fi5 = vec->at(2);
CPPUNIT_ASSERT_EQUAL(String("file3.material"), fi5.filename);
CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi5.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi5.uncompressedSize);
FileInfo& fi6 = vec->at(3);
CPPUNIT_ASSERT_EQUAL(String("file4.material"), fi6.filename);
CPPUNIT_ASSERT_EQUAL(String("level2/materials/scripts/"), fi6.path);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.compressedSize);
CPPUNIT_ASSERT_EQUAL((size_t)0, fi6.uncompressedSize);
}
void ZipArchiveTests::testFileRead()
{
ZipArchive arch(testPath, "Zip");
try {
arch.load();
}
catch (Ogre::Exception e) {
// If it starts in build/bin/debug
arch = ZipArchive("../../../" + testPath, "Zip");
arch.load();
}
DataStreamPtr stream = arch.open("rootfile.txt");
CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 1"), stream->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 1"), stream->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 1"), stream->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 1"), stream->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 1"), stream->getLine());
CPPUNIT_ASSERT(stream->eof());
}
void ZipArchiveTests::testReadInterleave()
{
// Test overlapping reads from same archive
ZipArchive arch(testPath, "Zip");
try {
arch.load();
}
catch (Ogre::Exception e) {
// If it starts in build/bin/debug
arch = ZipArchive("../../../" + testPath, "Zip");
arch.load();
}
// File 1
DataStreamPtr stream1 = arch.open("rootfile.txt");
CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 1"), stream1->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 1"), stream1->getLine());
// File 2
DataStreamPtr stream2 = arch.open("rootfile2.txt");
CPPUNIT_ASSERT_EQUAL(String("this is line 1 in file 2"), stream2->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 2 in file 2"), stream2->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 2"), stream2->getLine());
// File 1
CPPUNIT_ASSERT_EQUAL(String("this is line 3 in file 1"), stream1->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 1"), stream1->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 1"), stream1->getLine());
CPPUNIT_ASSERT(stream1->eof());
// File 2
CPPUNIT_ASSERT_EQUAL(String("this is line 4 in file 2"), stream2->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 5 in file 2"), stream2->getLine());
CPPUNIT_ASSERT_EQUAL(String("this is line 6 in file 2"), stream2->getLine());
CPPUNIT_ASSERT(stream2->eof());
}
<|endoftext|> |
<commit_before>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <asio.hpp>
#include <ctime>
#include <cstring>
#include <vector>
#include <functional>
#include "common.hxx"
#include "auth.hxx"
#include "service.hxx"
#include "realm.hxx"
#include "clientelle.hxx"
#include "client.hxx"
#include "packets.hxx"
using namespace std;
Client::Client(const Realm* realm_,
const asio::ip::udp::endpoint& ep)
: realm(realm_),
endpoint(ep),
online(false),
lastContact(time(NULL)),
advert(realm, endpoint),
advertIterator(realm),
isIteratingAdverts(false),
advertIterationTimer(service)
{ }
Client::Client(const Client& that)
: realm(that.realm),
endpoint(that.endpoint),
online(that.online),
lastContact(that.lastContact),
advert(that.advert),
advertIterator(that.advertIterator),
isIteratingAdverts(that.isIteratingAdverts),
advertIterationTimer(service)
{ }
bool Client::isOnline() const {
return online && time(NULL) < lastContact + CONNECTION_TIMEOUT;
}
void Client::kill() {
online = false;
}
const asio::ip::udp::endpoint& Client::getEndpoint() const {
return endpoint;
}
void (Client::*const Client::messages[256])(const byte*, unsigned) = {
&Client::connect,
&Client::ping,
&Client::proxy,
&Client::post,
&Client::list,
&Client::sign,
&Client::bye,
//NULLs to end of array are implicit
};
#define READ(type,from) (*(reinterpret_cast<const type*>(from)))
#define WRITE(type,to) (*(reinterpret_cast<type*>(to)))
void Client::connect(const byte* dat, unsigned len) {
contact();
//Check length sanity
if (len < 2*4 + HMAC_SIZE + 2 ||
len > 2*4 + HMAC_SIZE + MAX_CLIENT_NAME_LENGTH + 1)
return;
//Ensure NUL-terminated
if (dat[len-1]) return;
unsigned id = READ(unsigned, dat);
unsigned timestamp = READ(unsigned, dat+4);
byte hmac[HMAC_SIZE];
memcpy(hmac, dat+8, HMAC_SIZE);
const char* name = (const char*)(dat+8+HMAC_SIZE);
if (!*name) return; //Empty name
if (authenticate(realm, id, timestamp, name, hmac)) {
online = true;
this->id = id;
this->name = name;
//Send response
byte dontKnowWhoIAm = 1;
ping(&dontKnowWhoIAm, 1);
}
}
void Client::ping(const byte* dat, unsigned len) {
contact();
if (len == 1 && dat[0]) {
//Client needs to know its external address/port
vector<byte> response(1 + realm->addressSize + 2);
response[0] = PAK_YOUARE;
realm->encodeAddress(&response[1], endpoint.address());
WRITE(unsigned short, &response[response.size()-2]) = endpoint.port();
sendPacket(endpoint, &response[0], response.size());
} else {
//Just respond for the sake of two-way traffic
byte response = PAK_PONG;
sendPacket(endpoint, &response, 1);
}
}
void Client::proxy(const byte* dat, unsigned len) {
contact();
if (len > MAX_PROXY_SIZE + realm->addressSize + 2) return;
if (len < 1 + realm->addressSize + 2) return;
asio::ip::address addr;
unsigned short port;
realm->decodeAddress(addr, dat);
port = READ(unsigned short, dat+realm->addressSize);
//OK, send the packet if there is a client on that endpoint
asio::ip::udp::endpoint ep(addr, port);
if (getClientForEndpoint(realm, ep, false)) {
byte pack[1+MAX_PROXY_SIZE];
pack[0] = PAK_FROMOTHER;
memcpy(&pack[1], dat + realm->addressSize + 2, len-realm->addressSize-2);
sendPacket(ep, pack, 1 + len-realm->addressSize-2);
}
}
void Client::post(const byte* dat, unsigned len) {
contact();
if (len > MAX_ADVERTISEMENT_SIZE)
return;
advert.setData(dat, len);
}
void Client::list(const byte* dat, unsigned len) {
contact();
if (isIteratingAdverts) return;
isIteratingAdverts = true;
advertIterator.reset();
setIterationTimer();
}
void Client::sign(const byte* dat, unsigned len) {
contact();
//TODO
}
void Client::bye(const byte* dat, unsigned len) {
contact();
online = false;
}
void Client::contact() {
lastContact = time(NULL);
}
//G++'s bind1st seems to be broken, as it tries to overload its operator() in a
//forbidden manner.
struct ClientTHBind1st {
Client* that;
void (*f)(Client*, const asio::error_code&);
void operator()(const asio::error_code& code) {
f(that, code);
}
};
void Client::setIterationTimer() {
advertIterationTimer.expires_from_now(boost::posix_time::milliseconds(512));
ClientTHBind1st f;
f.that = this;
f.f = &Client::timerHandler_static;
advertIterationTimer.async_wait(f);
}
void Client::timerHandler_static(Client* c, const asio::error_code& code) {
c->timerHandler(code);
}
void Client::timerHandler(const asio::error_code&) {
asio::ip::udp::endpoint from;
vector<byte> pack(1);
if (advertIterator.next(from, pack)) {
pack[0] = PAK_ADVERT;
sendPacket(endpoint, &pack[0], pack.size());
setIterationTimer();
} else {
isIteratingAdverts = false;
}
}
<commit_msg>Add client-debugging code.<commit_after>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <asio.hpp>
#include <ctime>
#include <cstring>
#include <vector>
#include <functional>
#include "common.hxx"
#include "auth.hxx"
#include "service.hxx"
#include "realm.hxx"
#include "clientelle.hxx"
#include "client.hxx"
#include "packets.hxx"
using namespace std;
#ifdef CLIENT_DEBUG
#include <iostream>
#define debug(str) cerr << str << endl
#else
#define debug(str)
#endif
Client::Client(const Realm* realm_,
const asio::ip::udp::endpoint& ep)
: realm(realm_),
endpoint(ep),
online(false),
lastContact(time(NULL)),
advert(realm, endpoint),
advertIterator(realm),
isIteratingAdverts(false),
advertIterationTimer(service)
{ }
Client::Client(const Client& that)
: realm(that.realm),
endpoint(that.endpoint),
online(that.online),
lastContact(that.lastContact),
advert(that.advert),
advertIterator(that.advertIterator),
isIteratingAdverts(that.isIteratingAdverts),
advertIterationTimer(service)
{ }
bool Client::isOnline() const {
return online && time(NULL) < lastContact + CONNECTION_TIMEOUT;
}
void Client::kill() {
online = false;
}
const asio::ip::udp::endpoint& Client::getEndpoint() const {
return endpoint;
}
void (Client::*const Client::messages[256])(const byte*, unsigned) = {
&Client::connect,
&Client::ping,
&Client::proxy,
&Client::post,
&Client::list,
&Client::sign,
&Client::bye,
//NULLs to end of array are implicit
};
#define READ(type,from) (*(reinterpret_cast<const type*>(from)))
#define WRITE(type,to) (*(reinterpret_cast<type*>(to)))
void Client::connect(const byte* dat, unsigned len) {
contact();
debug(">> CONNECT");
//Check length sanity
if (len < 2*4 + HMAC_SIZE + 2 ||
len > 2*4 + HMAC_SIZE + MAX_CLIENT_NAME_LENGTH + 1)
return;
debug("Length OK");
//Ensure NUL-terminated
if (dat[len-1]) return;
debug("NUL OK");
unsigned id = READ(unsigned, dat);
unsigned timestamp = READ(unsigned, dat+4);
byte hmac[HMAC_SIZE];
memcpy(hmac, dat+8, HMAC_SIZE);
const char* name = (const char*)(dat+8+HMAC_SIZE);
if (!*name) return; //Empty name
debug("Name OK");
if (authenticate(realm, id, timestamp, name, hmac)) {
debug("Auth OK");
online = true;
this->id = id;
this->name = name;
//Send response
byte dontKnowWhoIAm = 1;
ping(&dontKnowWhoIAm, 1);
}
}
void Client::ping(const byte* dat, unsigned len) {
contact();
if (len == 1 && dat[0]) {
//Client needs to know its external address/port
vector<byte> response(1 + realm->addressSize + 2);
response[0] = PAK_YOUARE;
realm->encodeAddress(&response[1], endpoint.address());
WRITE(unsigned short, &response[response.size()-2]) = endpoint.port();
sendPacket(endpoint, &response[0], response.size());
} else {
//Just respond for the sake of two-way traffic
byte response = PAK_PONG;
sendPacket(endpoint, &response, 1);
}
}
void Client::proxy(const byte* dat, unsigned len) {
contact();
if (len > MAX_PROXY_SIZE + realm->addressSize + 2) return;
if (len < 1 + realm->addressSize + 2) return;
asio::ip::address addr;
unsigned short port;
realm->decodeAddress(addr, dat);
port = READ(unsigned short, dat+realm->addressSize);
//OK, send the packet if there is a client on that endpoint
asio::ip::udp::endpoint ep(addr, port);
if (getClientForEndpoint(realm, ep, false)) {
byte pack[1+MAX_PROXY_SIZE];
pack[0] = PAK_FROMOTHER;
memcpy(&pack[1], dat + realm->addressSize + 2, len-realm->addressSize-2);
sendPacket(ep, pack, 1 + len-realm->addressSize-2);
}
}
void Client::post(const byte* dat, unsigned len) {
contact();
if (len > MAX_ADVERTISEMENT_SIZE)
return;
advert.setData(dat, len);
}
void Client::list(const byte* dat, unsigned len) {
contact();
if (isIteratingAdverts) return;
isIteratingAdverts = true;
advertIterator.reset();
setIterationTimer();
}
void Client::sign(const byte* dat, unsigned len) {
contact();
//TODO
}
void Client::bye(const byte* dat, unsigned len) {
contact();
online = false;
}
void Client::contact() {
lastContact = time(NULL);
}
//G++'s bind1st seems to be broken, as it tries to overload its operator() in a
//forbidden manner.
struct ClientTHBind1st {
Client* that;
void (*f)(Client*, const asio::error_code&);
void operator()(const asio::error_code& code) {
f(that, code);
}
};
void Client::setIterationTimer() {
advertIterationTimer.expires_from_now(boost::posix_time::milliseconds(512));
ClientTHBind1st f;
f.that = this;
f.f = &Client::timerHandler_static;
advertIterationTimer.async_wait(f);
}
void Client::timerHandler_static(Client* c, const asio::error_code& code) {
c->timerHandler(code);
}
void Client::timerHandler(const asio::error_code&) {
asio::ip::udp::endpoint from;
vector<byte> pack(1);
if (advertIterator.next(from, pack)) {
pack[0] = PAK_ADVERT;
sendPacket(endpoint, &pack[0], pack.size());
setIterationTimer();
} else {
isIteratingAdverts = false;
}
}
<|endoftext|> |
<commit_before>void AliAnalysisTaskSEVertexingHFTest()
{
//
// Test macro for the AliAnalysisTaskSE for heavy-flavour vertexing
// A.Dainese, andrea.dainese@lnl.infn.it
//
Bool_t inputAOD=kTRUE; // otherwise, ESD
Bool_t createAOD=kFALSE; // kTRUE: create AOD and use it as input to vertexing
// kFALSE: use ESD as input to vertexing
Bool_t writeKineToAOD = kTRUE;
TString mode="local"; // otherwise, "grid"
Bool_t useParFiles=kFALSE;
gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/LoadLibraries.C");
LoadLibraries(useParFiles);
TChain *chain = 0;
if(mode=="local") {
// Local files
TString treeName,fileName;
if(inputAOD) {
treeName="aodTree";
fileName="AliAOD.root";
} else {
treeName="esdTree";
fileName="AliESDs.root";
}
chain = new TChain(treeName.Data());
chain->Add(fileName.Data());
} else if (mode=="grid") {
//Fetch files with AliEn :
const char *collectionfile = "Collection.xml";
TGrid::Connect("alien://") ;
TAlienCollection *coll = TAlienCollection::Open(collectionfile);
if(inputAOD) { // input AOD
chain = new TChain("aodTree");
while(coll->Next()) chain->Add(coll->GetTURL(""));
} else { // input ESD
//Create an AliRunTagCuts and an AliEventTagCuts Object and impose some selection criteria
AliRunTagCuts *runCuts = new AliRunTagCuts();
AliEventTagCuts *eventCuts = new AliEventTagCuts();
AliLHCTagCuts *lhcCuts = new AliLHCTagCuts();
AliDetectorTagCuts *detCuts = new AliDetectorTagCuts();
eventCuts->SetMultiplicityRange(0,20000);
//Create an AliTagAnalysis Object and chain the tags
AliTagAnalysis *tagAna = new AliTagAnalysis();
tagAna->SetType("ESD");
TGridResult *tagResult = coll->GetGridResult("",0,0);
tagResult->Print();
tagAna->ChainGridTags(tagResult);
//Create a new esd chain and assign the chain that is returned by querying the tags
chain = tagAna->QueryTags(runCuts,lhcCuts,detCuts,eventCuts);
}
} else {
printf("ERROR: mode has to be \"local\" or \"grid\" \n");
return;
}
// Create the analysis manager
AliAnalysisManager *mgr = new AliAnalysisManager("My Manager","My Manager");
mgr->SetDebugLevel(10);
// Input Handler
AliInputEventHandler *inputHandler = 0;
if(inputAOD) {
inputHandler = new AliAODInputHandler();
} else {
inputHandler = new AliESDInputHandler();
}
mgr->SetInputEventHandler(inputHandler);
// Output
AliAODHandler *aodHandler = new AliAODHandler();
if(createAOD) {
aodHandler->SetOutputFileName("AliAODs.root");
} else {
aodHandler->SetOutputFileName("AliAOD.VertexingHF.root");
aodHandler->SetCreateNonStandardAOD();
}
mgr->SetOutputEventHandler(aodHandler);
if(!inputAOD && createAOD) {
// MC Truth
AliMCEventHandler* mcHandler = new AliMCEventHandler();
if(writeKineToAOD) mgr->SetMCtruthEventHandler(mcHandler);
AliAnalysisTaskMCParticleFilter *kinefilter = new AliAnalysisTaskMCParticleFilter("Particle Filter");
if(writeKineToAOD) mgr->AddTask(kinefilter);
// Barrel Tracks
AliAnalysisTaskESDfilter *filter = new AliAnalysisTaskESDfilter("Filter");
mgr->AddTask(filter);
AliESDtrackCuts* esdTrackCutsHF = new AliESDtrackCuts("AliESDtrackCuts", "Heavy flavour");
esdTrackCutsHF->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kAny);
AliAnalysisFilter* trackFilter = new AliAnalysisFilter("trackFilter");
trackFilter->AddCuts(esdTrackCutsHF);
filter->SetTrackFilter(trackFilter);
// Pipelining
mgr->ConnectInput(filter,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(filter,0,mgr->GetCommonOutputContainer());
if(writeKineToAOD) {
mgr->ConnectInput(kinefilter,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(kinefilter,0,mgr->GetCommonOutputContainer());
}
}
// Vertexing analysis task
gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/AddTaskVertexingHF.C");
AliAnalysisTaskSEVertexingHF *hfTask = AddTaskVertexingHF();
//
// Run the analysis
//
printf("CHAIN HAS %d ENTRIES\n",(Int_t)chain->GetEntries());
if(!mgr->InitAnalysis()) return;
mgr->PrintStatus();
TStopwatch watch;
watch.Start();
mgr->StartAnalysis(mode.Data(),chain);
watch.Stop();
watch.Print();
return;
}
<commit_msg>Changed output file name from AliAODs.root to AliAOD.root<commit_after>void AliAnalysisTaskSEVertexingHFTest()
{
//
// Test macro for the AliAnalysisTaskSE for heavy-flavour vertexing
// A.Dainese, andrea.dainese@lnl.infn.it
//
Bool_t inputAOD=kTRUE; // otherwise, ESD
Bool_t createAOD=kFALSE; // kTRUE: create AOD and use it as input to vertexing
// kFALSE: use ESD as input to vertexing
Bool_t writeKineToAOD = kTRUE;
TString mode="local"; // otherwise, "grid"
Bool_t useParFiles=kFALSE;
gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/LoadLibraries.C");
LoadLibraries(useParFiles);
TChain *chain = 0;
if(mode=="local") {
// Local files
TString treeName,fileName;
if(inputAOD) {
treeName="aodTree";
fileName="AliAOD.root";
} else {
treeName="esdTree";
fileName="AliESDs.root";
}
chain = new TChain(treeName.Data());
chain->Add(fileName.Data());
} else if (mode=="grid") {
//Fetch files with AliEn :
const char *collectionfile = "Collection.xml";
TGrid::Connect("alien://") ;
TAlienCollection *coll = TAlienCollection::Open(collectionfile);
if(inputAOD) { // input AOD
chain = new TChain("aodTree");
while(coll->Next()) chain->Add(coll->GetTURL(""));
} else { // input ESD
//Create an AliRunTagCuts and an AliEventTagCuts Object and impose some selection criteria
AliRunTagCuts *runCuts = new AliRunTagCuts();
AliEventTagCuts *eventCuts = new AliEventTagCuts();
AliLHCTagCuts *lhcCuts = new AliLHCTagCuts();
AliDetectorTagCuts *detCuts = new AliDetectorTagCuts();
eventCuts->SetMultiplicityRange(0,20000);
//Create an AliTagAnalysis Object and chain the tags
AliTagAnalysis *tagAna = new AliTagAnalysis();
tagAna->SetType("ESD");
TGridResult *tagResult = coll->GetGridResult("",0,0);
tagResult->Print();
tagAna->ChainGridTags(tagResult);
//Create a new esd chain and assign the chain that is returned by querying the tags
chain = tagAna->QueryTags(runCuts,lhcCuts,detCuts,eventCuts);
}
} else {
printf("ERROR: mode has to be \"local\" or \"grid\" \n");
return;
}
// Create the analysis manager
AliAnalysisManager *mgr = new AliAnalysisManager("My Manager","My Manager");
mgr->SetDebugLevel(10);
// Input Handler
AliInputEventHandler *inputHandler = 0;
if(inputAOD) {
inputHandler = new AliAODInputHandler();
} else {
inputHandler = new AliESDInputHandler();
}
mgr->SetInputEventHandler(inputHandler);
// Output
AliAODHandler *aodHandler = new AliAODHandler();
if(createAOD) {
aodHandler->SetOutputFileName("AliAOD.root");
} else {
aodHandler->SetOutputFileName("AliAOD.VertexingHF.root");
aodHandler->SetCreateNonStandardAOD();
}
mgr->SetOutputEventHandler(aodHandler);
if(!inputAOD && createAOD) {
// MC Truth
AliMCEventHandler* mcHandler = new AliMCEventHandler();
if(writeKineToAOD) mgr->SetMCtruthEventHandler(mcHandler);
AliAnalysisTaskMCParticleFilter *kinefilter = new AliAnalysisTaskMCParticleFilter("Particle Filter");
if(writeKineToAOD) mgr->AddTask(kinefilter);
// Barrel Tracks
AliAnalysisTaskESDfilter *filter = new AliAnalysisTaskESDfilter("Filter");
mgr->AddTask(filter);
AliESDtrackCuts* esdTrackCutsHF = new AliESDtrackCuts("AliESDtrackCuts", "Heavy flavour");
esdTrackCutsHF->SetClusterRequirementITS(AliESDtrackCuts::kSPD,AliESDtrackCuts::kAny);
AliAnalysisFilter* trackFilter = new AliAnalysisFilter("trackFilter");
trackFilter->AddCuts(esdTrackCutsHF);
filter->SetTrackFilter(trackFilter);
// Pipelining
mgr->ConnectInput(filter,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(filter,0,mgr->GetCommonOutputContainer());
if(writeKineToAOD) {
mgr->ConnectInput(kinefilter,0,mgr->GetCommonInputContainer());
mgr->ConnectOutput(kinefilter,0,mgr->GetCommonOutputContainer());
}
}
// Vertexing analysis task
gROOT->LoadMacro("$ALICE_ROOT/PWG3/vertexingHF/AddTaskVertexingHF.C");
AliAnalysisTaskSEVertexingHF *hfTask = AddTaskVertexingHF();
//
// Run the analysis
//
printf("CHAIN HAS %d ENTRIES\n",(Int_t)chain->GetEntries());
if(!mgr->InitAnalysis()) return;
mgr->PrintStatus();
TStopwatch watch;
watch.Start();
mgr->StartAnalysis(mode.Data(),chain);
watch.Stop();
watch.Print();
return;
}
<|endoftext|> |
<commit_before>/*
* File: pping.cpp
* Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
*/
#include "sedna.h"
#include "pping.h"
#include "d_printf.h"
#ifdef _WIN32
#define PPING_STACK_SIZE 10240
#else
#define PPING_STACK_SIZE 102400
#endif
#define PPING_KEEP_ALIVE_MSG 'a'
#define PPING_DISCONNECT_MSG 'b'
#define PPING_LSTNR_QUEUE_LEN 100
////////////////////////////////////////////////////////////////////////////////
/// pping_client
////////////////////////////////////////////////////////////////////////////////
U_THREAD_PROC(pping_client_thread_proc, arg)
{
if (uThreadBlockAllSignals(NULL) != 0)
d_printf1("Failed to block signals for pping_client_thread_proc");
pping_client *ppc = (pping_client*)arg;
char c = PPING_KEEP_ALIVE_MSG;
while (true)
{
if (ppc->stop_keep_alive) return 0;
if (usend(ppc->sock, &c, sizeof(c), NULL) != sizeof(c))
{
if (!ppc->stop_keep_alive)
{
sedna_soft_fault("SEDNA GOVERNOR is down", ppc->component);
}
}
UUnnamedSemaphoreDownTimeout(&(ppc->sem), 1000, NULL);
}
return 0;
}
pping_client::pping_client(int _port_, int _component_, const char* _host_)
{
#ifdef PPING_ON
port = _port_;
if (_host_ && strlen(_host_) < PPING_MAX_HOSTLEN)
strcpy(host, _host_);
else
strcpy(host, "127.0.0.1");
component = _component_;
stop_keep_alive = false;
initialized = false;
#endif
}
pping_client::~pping_client()
{
#ifdef PPING_ON
#endif
}
void pping_client::startup(SednaUserException& e)
{
startup(e, false);
}
void pping_client::startup(SednaUserSoftException& e)
{
startup(e, true);
}
void pping_client::throw_exception(SednaUserException& e, bool is_soft)
{
if (is_soft) throw dynamic_cast<SednaUserSoftException&>(e);
else throw e;
}
void pping_client::startup(SednaUserException& e, bool is_soft)
{
#ifdef PPING_ON
sock = usocket(AF_INET, SOCK_STREAM, 0, __sys_call_error);
if (sock == U_INVALID_SOCKET) throw USER_ENV_EXCEPTION("Failed to create socket", false);
if (uconnect_tcp(sock, port, host, __sys_call_error) == U_SOCKET_ERROR) throw_exception(e, is_soft);
if (UUnnamedSemaphoreCreate(&sem, 0, NULL, __sys_call_error) != 0)
throw USER_ENV_EXCEPTION("Failed to create semaphore", false);
uResVal res = uCreateThread(pping_client_thread_proc, this, &client_thread_handle, PPING_STACK_SIZE, NULL, __sys_call_error);
if (res != 0) throw USER_ENV_EXCEPTION("Failed to create pping client thread", false);
initialized = true;
#endif
}
void pping_client::shutdown()
{
#ifdef PPING_ON
if (!initialized) return;
stop_keep_alive = true;
if (UUnnamedSemaphoreUp(&sem, NULL) != 0)
throw USER_ENV_EXCEPTION("Failed to up semaphore", false);
if (uThreadJoin(client_thread_handle, NULL) != 0)
throw USER_ENV_EXCEPTION("Error waiting for pping client thread to shutdown", false);
if (uCloseThreadHandle(client_thread_handle, NULL) != 0)
throw USER_EXCEPTION2(SE4063, "pping client_thread");
char c = PPING_DISCONNECT_MSG;
if (usend(sock, &c, sizeof(char), NULL) != sizeof(char))
throw SYSTEM_EXCEPTION("pping server is down");
if (uclose_socket(sock, NULL) == U_SOCKET_ERROR)
throw USER_ENV_EXCEPTION("Failed to close socket", false);
if (UUnnamedSemaphoreRelease(&sem, NULL) != 0)
throw USER_ENV_EXCEPTION("Failed to release semaphore", false);
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// pping_server
////////////////////////////////////////////////////////////////////////////////
struct pping_serv_arg
{
pping_server *pps;
USOCKET sock;
int id; // thread_table id
};
U_THREAD_PROC(pping_server_cli_thread_proc, arg)
{
if (uThreadBlockAllSignals(NULL) != 0)
d_printf1("Failed to block signals for SSMMsg_server_proc");
pping_server *pps = ((pping_serv_arg*)arg)->pps;
USOCKET sock = ((pping_serv_arg*)arg)->sock;
int id = ((pping_serv_arg*)arg)->id;
int component = ((pping_serv_arg*)arg)->pps->component;
delete ((pping_serv_arg*)arg);
char c = PPING_DISCONNECT_MSG;
while (true)
{
if (urecv(sock, &c, sizeof(c), NULL) != sizeof(c)) goto sys_failure;
if (c == PPING_DISCONNECT_MSG) break;
if (c != PPING_KEEP_ALIVE_MSG) goto sys_failure;
}
//d_printf1("pping_server's client is closed\n");
if (uclose_socket(sock, NULL) == U_SOCKET_ERROR) goto sys_failure;
pps->thread_table[id].is_running = false;
return 0;
sys_failure:
sedna_soft_fault("One of SEDNA processes is down", component);
return 0;
}
U_THREAD_PROC(pping_server_lstn_thread_proc, arg)
{
if (uThreadBlockAllSignals(NULL) != 0)
d_printf1("Failed to block signals for SSMMsg_server_proc");
pping_server *pps = (pping_server*)arg;
int i = 0;
while (true)
{
pping_serv_arg *pps_arg = new pping_serv_arg;
//accept a call from a client
pps_arg->pps = pps;
pps_arg->id = -1;
pps_arg->sock = uaccept(pps->sock, NULL);
if (pps_arg->sock == U_INVALID_SOCKET || pps->close_lstn_thread)
{
if (pps->close_lstn_thread)
{
for (i = 0; i < PPING_SERVER_THREAD_TABLE_SIZE; ++i)
{
if (!(pps->thread_table[i].is_empty))
{
if (uThreadJoin(pps->thread_table[i].handle, NULL) != 0)
goto sys_failure;
if (uCloseThreadHandle(pps->thread_table[i].handle, NULL) != 0)
goto sys_failure;
pps->thread_table[i].handle = (UTHANDLE)0;
pps->thread_table[i].is_running = true;
pps->thread_table[i].is_empty = true;
}
}
return 0;
}
else goto sys_failure;
}
for (i = 0; i < PPING_SERVER_THREAD_TABLE_SIZE; ++i)
{
if (!(pps->thread_table[i].is_empty) &&
!(pps->thread_table[i].is_running))
{
if (uThreadJoin(pps->thread_table[i].handle, NULL) != 0)
goto sys_failure;
if (uCloseThreadHandle(pps->thread_table[i].handle, NULL) != 0)
goto sys_failure;
pps->thread_table[i].handle = (UTHANDLE)0;
pps->thread_table[i].is_running = true;
pps->thread_table[i].is_empty = true;
}
if (pps_arg->id == -1 && pps->thread_table[i].is_empty)
pps_arg->id = i;
}
pps->thread_table[pps_arg->id].is_running = true;
pps->thread_table[pps_arg->id].is_empty = false;
uResVal res = uCreateThread(pping_server_cli_thread_proc,
pps_arg,
&(pps->thread_table[pps_arg->id].handle),
PPING_STACK_SIZE,
NULL,
NULL);
if (res != 0) goto sys_failure;
}
return 0;
sys_failure:
sedna_soft_fault("Malfunction in SEDNA GOVERNOR", pps->component);
return 0;
}
pping_server::pping_server(int _port_, int _component_)
{
#ifdef PPING_ON
port = _port_;
component = _component_;
close_lstn_thread = false;
initialized = false;
for (int i = 0; i < PPING_SERVER_THREAD_TABLE_SIZE; ++i)
{
thread_table[i].handle = (UTHANDLE)0;
thread_table[i].is_running = true;
thread_table[i].is_empty = true;
}
#endif
}
pping_server::~pping_server()
{
#ifdef PPING_ON
#endif
}
void pping_server::startup()
{
#ifdef PPING_ON
sock = usocket(AF_INET, SOCK_STREAM, 0, __sys_call_error);
if (sock == U_INVALID_SOCKET) throw USER_ENV_EXCEPTION("Failed to create socket", false);
if (uNotInheritDescriptor(UHANDLE(sock), __sys_call_error) != 0) throw USER_EXCEPTION(SE4080);
if (ubind_tcp(sock, port, __sys_call_error) == U_SOCKET_ERROR) throw USER_ENV_EXCEPTION2("Failed to bind socket", usocket_error_translator(), false);
if (ulisten(sock, PPING_LSTNR_QUEUE_LEN, __sys_call_error) == U_SOCKET_ERROR) throw USER_ENV_EXCEPTION("Failed to listen socket", false);
uResVal res = uCreateThread(pping_server_lstn_thread_proc, this, &server_lstn_thread_handle, PPING_STACK_SIZE, NULL, __sys_call_error);
if (res != 0) throw USER_ENV_EXCEPTION("Failed to create pping server thread", false);
initialized = true;
#endif
}
void pping_server::shutdown()
{
#ifdef PPING_ON
if (!initialized) return;
close_lstn_thread = true;
// send closing message: begin
USOCKET s = usocket(AF_INET, SOCK_STREAM, 0, NULL);
if (s == U_INVALID_SOCKET)
throw USER_ENV_EXCEPTION("Failed to create socket", false);
if (uconnect_tcp(s, port, "127.0.0.1", NULL) == U_SOCKET_ERROR)
throw USER_ENV_EXCEPTION("Failed to create TCP connection", false);
char c = PPING_KEEP_ALIVE_MSG;
usend(s, &c, sizeof(c), NULL);
if (uclose_socket(s, NULL) != 0)
throw USER_ENV_EXCEPTION("Failed to close socket", false);
// send closin message: end
if (uclose_socket(sock, NULL) != 0)
throw USER_ENV_EXCEPTION("Failed to close socket", false);
if (uThreadJoin(server_lstn_thread_handle, NULL) != 0)
throw USER_ENV_EXCEPTION("Error waiting for pping server_lstn thread to shutdown", false);
if (uCloseThreadHandle(server_lstn_thread_handle, NULL) != 0)
throw USER_EXCEPTION2(SE4063, "pping server_lstn_thread");
#endif
}
<commit_msg>pping not inherit socket 2<commit_after>/*
* File: pping.cpp
* Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
*/
#include "sedna.h"
#include "pping.h"
#include "d_printf.h"
#ifdef _WIN32
#define PPING_STACK_SIZE 10240
#else
#define PPING_STACK_SIZE 102400
#endif
#define PPING_KEEP_ALIVE_MSG 'a'
#define PPING_DISCONNECT_MSG 'b'
#define PPING_LSTNR_QUEUE_LEN 100
////////////////////////////////////////////////////////////////////////////////
/// pping_client
////////////////////////////////////////////////////////////////////////////////
U_THREAD_PROC(pping_client_thread_proc, arg)
{
if (uThreadBlockAllSignals(NULL) != 0)
d_printf1("Failed to block signals for pping_client_thread_proc");
pping_client *ppc = (pping_client*)arg;
char c = PPING_KEEP_ALIVE_MSG;
while (true)
{
if (ppc->stop_keep_alive) return 0;
if (usend(ppc->sock, &c, sizeof(c), NULL) != sizeof(c))
{
if (!ppc->stop_keep_alive)
{
sedna_soft_fault("SEDNA GOVERNOR is down", ppc->component);
}
}
UUnnamedSemaphoreDownTimeout(&(ppc->sem), 1000, NULL);
}
return 0;
}
pping_client::pping_client(int _port_, int _component_, const char* _host_)
{
#ifdef PPING_ON
port = _port_;
if (_host_ && strlen(_host_) < PPING_MAX_HOSTLEN)
strcpy(host, _host_);
else
strcpy(host, "127.0.0.1");
component = _component_;
stop_keep_alive = false;
initialized = false;
#endif
}
pping_client::~pping_client()
{
#ifdef PPING_ON
#endif
}
void pping_client::startup(SednaUserException& e)
{
startup(e, false);
}
void pping_client::startup(SednaUserSoftException& e)
{
startup(e, true);
}
void pping_client::throw_exception(SednaUserException& e, bool is_soft)
{
if (is_soft) throw dynamic_cast<SednaUserSoftException&>(e);
else throw e;
}
void pping_client::startup(SednaUserException& e, bool is_soft)
{
#ifdef PPING_ON
sock = usocket(AF_INET, SOCK_STREAM, 0, __sys_call_error);
if (sock == U_INVALID_SOCKET) throw USER_ENV_EXCEPTION("Failed to create socket", false);
if (uconnect_tcp(sock, port, host, __sys_call_error) == U_SOCKET_ERROR) throw_exception(e, is_soft);
if (UUnnamedSemaphoreCreate(&sem, 0, NULL, __sys_call_error) != 0)
throw USER_ENV_EXCEPTION("Failed to create semaphore", false);
uResVal res = uCreateThread(pping_client_thread_proc, this, &client_thread_handle, PPING_STACK_SIZE, NULL, __sys_call_error);
if (res != 0) throw USER_ENV_EXCEPTION("Failed to create pping client thread", false);
initialized = true;
#endif
}
void pping_client::shutdown()
{
#ifdef PPING_ON
if (!initialized) return;
stop_keep_alive = true;
if (UUnnamedSemaphoreUp(&sem, NULL) != 0)
throw USER_ENV_EXCEPTION("Failed to up semaphore", false);
if (uThreadJoin(client_thread_handle, NULL) != 0)
throw USER_ENV_EXCEPTION("Error waiting for pping client thread to shutdown", false);
if (uCloseThreadHandle(client_thread_handle, NULL) != 0)
throw USER_EXCEPTION2(SE4063, "pping client_thread");
char c = PPING_DISCONNECT_MSG;
if (usend(sock, &c, sizeof(char), NULL) != sizeof(char))
throw SYSTEM_EXCEPTION("pping server is down");
if (uclose_socket(sock, NULL) == U_SOCKET_ERROR)
throw USER_ENV_EXCEPTION("Failed to close socket", false);
if (UUnnamedSemaphoreRelease(&sem, NULL) != 0)
throw USER_ENV_EXCEPTION("Failed to release semaphore", false);
#endif
}
////////////////////////////////////////////////////////////////////////////////
/// pping_server
////////////////////////////////////////////////////////////////////////////////
struct pping_serv_arg
{
pping_server *pps;
USOCKET sock;
int id; // thread_table id
};
U_THREAD_PROC(pping_server_cli_thread_proc, arg)
{
if (uThreadBlockAllSignals(NULL) != 0)
d_printf1("Failed to block signals for SSMMsg_server_proc");
pping_server *pps = ((pping_serv_arg*)arg)->pps;
USOCKET sock = ((pping_serv_arg*)arg)->sock;
int id = ((pping_serv_arg*)arg)->id;
int component = ((pping_serv_arg*)arg)->pps->component;
delete ((pping_serv_arg*)arg);
char c = PPING_DISCONNECT_MSG;
while (true)
{
if (urecv(sock, &c, sizeof(c), NULL) != sizeof(c)) goto sys_failure;
if (c == PPING_DISCONNECT_MSG) break;
if (c != PPING_KEEP_ALIVE_MSG) goto sys_failure;
}
//d_printf1("pping_server's client is closed\n");
if (uclose_socket(sock, NULL) == U_SOCKET_ERROR) goto sys_failure;
pps->thread_table[id].is_running = false;
return 0;
sys_failure:
sedna_soft_fault("One of SEDNA processes is down", component);
return 0;
}
U_THREAD_PROC(pping_server_lstn_thread_proc, arg)
{
if (uThreadBlockAllSignals(NULL) != 0)
d_printf1("Failed to block signals for SSMMsg_server_proc");
pping_server *pps = (pping_server*)arg;
int i = 0;
while (true)
{
pping_serv_arg *pps_arg = new pping_serv_arg;
//accept a call from a client
pps_arg->pps = pps;
pps_arg->id = -1;
pps_arg->sock = uaccept(pps->sock, NULL);
if (pps_arg->sock == U_INVALID_SOCKET || pps->close_lstn_thread)
{
if (pps->close_lstn_thread)
{
for (i = 0; i < PPING_SERVER_THREAD_TABLE_SIZE; ++i)
{
if (!(pps->thread_table[i].is_empty))
{
if (uThreadJoin(pps->thread_table[i].handle, NULL) != 0)
goto sys_failure;
if (uCloseThreadHandle(pps->thread_table[i].handle, NULL) != 0)
goto sys_failure;
pps->thread_table[i].handle = (UTHANDLE)0;
pps->thread_table[i].is_running = true;
pps->thread_table[i].is_empty = true;
}
}
return 0;
}
else goto sys_failure;
}
if (uNotInheritDescriptor(UHANDLE(pps_arg->sock), __sys_call_error) != 0) throw USER_EXCEPTION(SE4080);
for (i = 0; i < PPING_SERVER_THREAD_TABLE_SIZE; ++i)
{
if (!(pps->thread_table[i].is_empty) &&
!(pps->thread_table[i].is_running))
{
if (uThreadJoin(pps->thread_table[i].handle, NULL) != 0)
goto sys_failure;
if (uCloseThreadHandle(pps->thread_table[i].handle, NULL) != 0)
goto sys_failure;
pps->thread_table[i].handle = (UTHANDLE)0;
pps->thread_table[i].is_running = true;
pps->thread_table[i].is_empty = true;
}
if (pps_arg->id == -1 && pps->thread_table[i].is_empty)
pps_arg->id = i;
}
pps->thread_table[pps_arg->id].is_running = true;
pps->thread_table[pps_arg->id].is_empty = false;
uResVal res = uCreateThread(pping_server_cli_thread_proc,
pps_arg,
&(pps->thread_table[pps_arg->id].handle),
PPING_STACK_SIZE,
NULL,
NULL);
if (res != 0) goto sys_failure;
}
return 0;
sys_failure:
sedna_soft_fault("Malfunction in SEDNA GOVERNOR", pps->component);
return 0;
}
pping_server::pping_server(int _port_, int _component_)
{
#ifdef PPING_ON
port = _port_;
component = _component_;
close_lstn_thread = false;
initialized = false;
for (int i = 0; i < PPING_SERVER_THREAD_TABLE_SIZE; ++i)
{
thread_table[i].handle = (UTHANDLE)0;
thread_table[i].is_running = true;
thread_table[i].is_empty = true;
}
#endif
}
pping_server::~pping_server()
{
#ifdef PPING_ON
#endif
}
void pping_server::startup()
{
#ifdef PPING_ON
sock = usocket(AF_INET, SOCK_STREAM, 0, __sys_call_error);
if (sock == U_INVALID_SOCKET) throw USER_ENV_EXCEPTION("Failed to create socket", false);
if (uNotInheritDescriptor(UHANDLE(sock), __sys_call_error) != 0) throw USER_EXCEPTION(SE4080);
if (ubind_tcp(sock, port, __sys_call_error) == U_SOCKET_ERROR) throw USER_ENV_EXCEPTION2("Failed to bind socket", usocket_error_translator(), false);
if (ulisten(sock, PPING_LSTNR_QUEUE_LEN, __sys_call_error) == U_SOCKET_ERROR) throw USER_ENV_EXCEPTION("Failed to listen socket", false);
uResVal res = uCreateThread(pping_server_lstn_thread_proc, this, &server_lstn_thread_handle, PPING_STACK_SIZE, NULL, __sys_call_error);
if (res != 0) throw USER_ENV_EXCEPTION("Failed to create pping server thread", false);
initialized = true;
#endif
}
void pping_server::shutdown()
{
#ifdef PPING_ON
if (!initialized) return;
close_lstn_thread = true;
// send closing message: begin
USOCKET s = usocket(AF_INET, SOCK_STREAM, 0, NULL);
if (s == U_INVALID_SOCKET)
throw USER_ENV_EXCEPTION("Failed to create socket", false);
if (uconnect_tcp(s, port, "127.0.0.1", NULL) == U_SOCKET_ERROR)
throw USER_ENV_EXCEPTION("Failed to create TCP connection", false);
char c = PPING_KEEP_ALIVE_MSG;
usend(s, &c, sizeof(c), NULL);
if (uclose_socket(s, NULL) != 0)
throw USER_ENV_EXCEPTION("Failed to close socket", false);
// send closin message: end
if (uclose_socket(sock, NULL) != 0)
throw USER_ENV_EXCEPTION("Failed to close socket", false);
if (uThreadJoin(server_lstn_thread_handle, NULL) != 0)
throw USER_ENV_EXCEPTION("Error waiting for pping server_lstn thread to shutdown", false);
if (uCloseThreadHandle(server_lstn_thread_handle, NULL) != 0)
throw USER_EXCEPTION2(SE4063, "pping server_lstn_thread");
#endif
}
<|endoftext|> |
<commit_before>/*
Copyright libCellML Contributors
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 "libcellml/logger.h"
#include <algorithm>
#include <vector>
#include "libcellml/component.h"
#include "libcellml/types.h"
namespace libcellml {
/**
* @brief The Logger::LoggerImpl struct.
*
* This struct is the private implementation struct for the LoggerImpl class. Separating
* the implementation from the definition allows for greater flexibility when
* distributing the code.
*/
struct Logger::LoggerImpl
{
std::vector<size_t> mErrors;
std::vector<size_t> mWarnings;
std::vector<size_t> mMessages;
std::vector<IssuePtr> mIssues;
};
Logger::Logger()
: mPimpl(new LoggerImpl())
{
}
Logger::~Logger()
{
delete mPimpl;
}
size_t Logger::errorCount() const
{
return mPimpl->mErrors.size();
}
IssuePtr Logger::error(size_t index) const
{
IssuePtr issue = nullptr;
if (index < mPimpl->mErrors.size()) {
issue = mPimpl->mIssues.at(mPimpl->mErrors.at(index));
}
return issue;
}
bool Logger::removeError(size_t index)
{
if (index < mPimpl->mErrors.size()) {
mPimpl->mIssues.erase(mPimpl->mIssues.begin() + mPimpl->mErrors.at(index));
mPimpl->mErrors.erase(mPimpl->mErrors.begin() + index);
return true;
}
return false;
}
size_t Logger::warningCount() const
{
return mPimpl->mWarnings.size();
}
IssuePtr Logger::warning(size_t index) const
{
IssuePtr issue = nullptr;
if (index < mPimpl->mWarnings.size()) {
issue = mPimpl->mIssues.at(mPimpl->mWarnings.at(index));
}
return issue;
}
bool Logger::removeWarning(size_t index)
{
if (index < mPimpl->mWarnings.size()) {
mPimpl->mIssues.erase(mPimpl->mIssues.begin() + mPimpl->mWarnings.at(index));
mPimpl->mWarnings.erase(mPimpl->mWarnings.begin() + index);
return true;
}
return false;
}
size_t Logger::messageCount() const
{
return mPimpl->mMessages.size();
}
IssuePtr Logger::message(size_t index) const
{
IssuePtr issue = nullptr;
if (index < mPimpl->mMessages.size()) {
issue = mPimpl->mIssues.at(mPimpl->mMessages.at(index));
}
return issue;
}
bool Logger::removeMessage(size_t index)
{
if (index < mPimpl->mMessages.size()) {
mPimpl->mIssues.erase(mPimpl->mIssues.begin() + mPimpl->mMessages.at(index));
mPimpl->mMessages.erase(mPimpl->mMessages.begin() + index);
return true;
}
return false;
}
void Logger::removeAllIssues()
{
mPimpl->mIssues.clear();
mPimpl->mErrors.clear();
mPimpl->mWarnings.clear();
mPimpl->mMessages.clear();
}
void Logger::addIssue(const IssuePtr &issue)
{
// When an issue is added, update the appropriate array based on its level.
size_t index = mPimpl->mIssues.size();
mPimpl->mIssues.push_back(issue);
libcellml::Issue::Level level = issue->level();
switch (level) {
case libcellml::Issue::Level::ERROR:
mPimpl->mErrors.push_back(index);
break;
case libcellml::Issue::Level::WARNING:
mPimpl->mWarnings.push_back(index);
break;
case libcellml::Issue::Level::MESSAGE:
mPimpl->mMessages.push_back(index);
break;
}
}
size_t Logger::issueCount() const
{
return mPimpl->mIssues.size();
}
IssuePtr Logger::issue(size_t index) const
{
IssuePtr issue = nullptr;
if (index < mPimpl->mIssues.size()) {
issue = mPimpl->mIssues.at(index);
}
return issue;
}
bool Logger::removeIssue(size_t index)
{
auto issue = this->issue(index);
if (issue != nullptr) {
mPimpl->mIssues.erase(mPimpl->mIssues.begin() + index);
libcellml::Issue::Level level = issue->level();
switch (level) {
case libcellml::Issue::Level::ERROR:
mPimpl->mErrors.erase(std::remove_if(mPimpl->mErrors.begin(), mPimpl->mErrors.end(), [=](size_t errorIndex) -> bool { return errorIndex == index; }), mPimpl->mErrors.end());
break;
case libcellml::Issue::Level::WARNING:
mPimpl->mWarnings.erase(std::remove_if(mPimpl->mWarnings.begin(), mPimpl->mWarnings.end(), [=](size_t warningIndex) -> bool { return warningIndex == index; }), mPimpl->mWarnings.end());
break;
case libcellml::Issue::Level::MESSAGE:
mPimpl->mMessages.erase(std::remove_if(mPimpl->mMessages.begin(), mPimpl->mMessages.end(), [=](size_t messageIndex) -> bool { return messageIndex == index; }), mPimpl->mMessages.end());
break;
}
return true;
}
return false;
}
} // namespace libcellml
<commit_msg>Cast size_t to ptr_diff_t for pointer arithmetic.<commit_after>/*
Copyright libCellML Contributors
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 "libcellml/logger.h"
#include <algorithm>
#include <vector>
#include "libcellml/component.h"
#include "libcellml/types.h"
namespace libcellml {
/**
* @brief The Logger::LoggerImpl struct.
*
* This struct is the private implementation struct for the LoggerImpl class. Separating
* the implementation from the definition allows for greater flexibility when
* distributing the code.
*/
struct Logger::LoggerImpl
{
std::vector<size_t> mErrors;
std::vector<size_t> mWarnings;
std::vector<size_t> mMessages;
std::vector<IssuePtr> mIssues;
};
Logger::Logger()
: mPimpl(new LoggerImpl())
{
}
Logger::~Logger()
{
delete mPimpl;
}
size_t Logger::errorCount() const
{
return mPimpl->mErrors.size();
}
IssuePtr Logger::error(size_t index) const
{
IssuePtr issue = nullptr;
if (index < mPimpl->mErrors.size()) {
issue = mPimpl->mIssues.at(mPimpl->mErrors.at(index));
}
return issue;
}
bool Logger::removeError(size_t index)
{
if (index < mPimpl->mErrors.size()) {
mPimpl->mIssues.erase(mPimpl->mIssues.begin() + ptrdiff_t(mPimpl->mErrors.at(index)));
mPimpl->mErrors.erase(mPimpl->mErrors.begin() + ptrdiff_t(index));
return true;
}
return false;
}
size_t Logger::warningCount() const
{
return mPimpl->mWarnings.size();
}
IssuePtr Logger::warning(size_t index) const
{
IssuePtr issue = nullptr;
if (index < mPimpl->mWarnings.size()) {
issue = mPimpl->mIssues.at(mPimpl->mWarnings.at(index));
}
return issue;
}
bool Logger::removeWarning(size_t index)
{
if (index < mPimpl->mWarnings.size()) {
mPimpl->mIssues.erase(mPimpl->mIssues.begin() + ptrdiff_t(mPimpl->mWarnings.at(index)));
mPimpl->mWarnings.erase(mPimpl->mWarnings.begin() + ptrdiff_t(index));
return true;
}
return false;
}
size_t Logger::messageCount() const
{
return mPimpl->mMessages.size();
}
IssuePtr Logger::message(size_t index) const
{
IssuePtr issue = nullptr;
if (index < mPimpl->mMessages.size()) {
issue = mPimpl->mIssues.at(mPimpl->mMessages.at(index));
}
return issue;
}
bool Logger::removeMessage(size_t index)
{
if (index < mPimpl->mMessages.size()) {
mPimpl->mIssues.erase(mPimpl->mIssues.begin() + ptrdiff_t(mPimpl->mMessages.at(index)));
mPimpl->mMessages.erase(mPimpl->mMessages.begin() + ptrdiff_t(index));
return true;
}
return false;
}
void Logger::removeAllIssues()
{
mPimpl->mIssues.clear();
mPimpl->mErrors.clear();
mPimpl->mWarnings.clear();
mPimpl->mMessages.clear();
}
void Logger::addIssue(const IssuePtr &issue)
{
// When an issue is added, update the appropriate array based on its level.
size_t index = mPimpl->mIssues.size();
mPimpl->mIssues.push_back(issue);
libcellml::Issue::Level level = issue->level();
switch (level) {
case libcellml::Issue::Level::ERROR:
mPimpl->mErrors.push_back(index);
break;
case libcellml::Issue::Level::WARNING:
mPimpl->mWarnings.push_back(index);
break;
case libcellml::Issue::Level::MESSAGE:
mPimpl->mMessages.push_back(index);
break;
}
}
size_t Logger::issueCount() const
{
return mPimpl->mIssues.size();
}
IssuePtr Logger::issue(size_t index) const
{
IssuePtr issue = nullptr;
if (index < mPimpl->mIssues.size()) {
issue = mPimpl->mIssues.at(index);
}
return issue;
}
bool Logger::removeIssue(size_t index)
{
auto issue = this->issue(index);
if (issue != nullptr) {
mPimpl->mIssues.erase(mPimpl->mIssues.begin() + ptrdiff_t(index));
libcellml::Issue::Level level = issue->level();
switch (level) {
case libcellml::Issue::Level::ERROR:
mPimpl->mErrors.erase(std::remove_if(mPimpl->mErrors.begin(), mPimpl->mErrors.end(), [=](size_t errorIndex) -> bool { return errorIndex == index; }), mPimpl->mErrors.end());
break;
case libcellml::Issue::Level::WARNING:
mPimpl->mWarnings.erase(std::remove_if(mPimpl->mWarnings.begin(), mPimpl->mWarnings.end(), [=](size_t warningIndex) -> bool { return warningIndex == index; }), mPimpl->mWarnings.end());
break;
case libcellml::Issue::Level::MESSAGE:
mPimpl->mMessages.erase(std::remove_if(mPimpl->mMessages.begin(), mPimpl->mMessages.end(), [=](size_t messageIndex) -> bool { return messageIndex == index; }), mPimpl->mMessages.end());
break;
}
return true;
}
return false;
}
} // namespace libcellml
<|endoftext|> |
<commit_before>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
bbox.maxX = std::numeric_limits<float>::min();
bbox.maxY = std::numeric_limits<float>::min();
bbox.minX = std::numeric_limits<float>::max();
bbox.minY = std::numeric_limits<float>::max();
_useRamanan = false;
// Load image
_path = "/Users/spherik//Documents/WORK/PhD/Bosphorus/originals/bs000/bs000_E_FEAR_0.obj";
//_path = "/home/spherik/Documents/PhD/Bosphorus/originals/bs000/bs000_E_FEAR_0.obj";
//_path = "/Volumes/Dades/spherik/Documents/WORK/PhD/Bosphorus/originals/bs000/bs000_E_ANGER_0.obj";
string imageFilename = _path;
ofStringReplace(imageFilename, "originals", "images");
ofStringReplace(imageFilename, ".obj", ".png");
_colorImage.loadImage(imageFilename);
//Load mesh
string fpCoordFilename = _path;
string fpTriFilename = _path;
_mesh.setMode(OF_PRIMITIVE_TRIANGLES);
if(_useRamanan)
{
ofStringReplace(fpCoordFilename, "originals", "ramanan2D");
ofStringReplace(fpCoordFilename, ".obj", ".dat");
ofStringReplace(fpTriFilename, "originals", "ramanan3D");
vector<string> splitString = ofSplitString( fpTriFilename, "/");
ofStringReplace(fpTriFilename, splitString[splitString.size()-1], "ramanan.tri");
ofStringReplace(fpTriFilename, splitString[splitString.size()-2], "");
}
else
{
ofStringReplace(fpCoordFilename, "originals", "ToyFace");
ofStringReplace(fpCoordFilename, ".obj", ".dat");
ofStringReplace(fpTriFilename, "originals", "ToyFace");
vector<string> splitString = ofSplitString( fpTriFilename, "/");
ofStringReplace(fpTriFilename, splitString[splitString.size()-1], "ramanan.tri");
ofStringReplace(fpTriFilename, splitString[splitString.size()-2], "");
cout << fpCoordFilename << endl;
}
//cout << fpTriFilename << endl;
int numRows = 0;
int readRows = 0;
ifstream fin; //declare a file stream
fin.open( ofToDataPath(fpCoordFilename).c_str() ); //open your text file
vector<ofVec3f> vertices;
vector<ofVec2f> texCoord; //declare a vector of strings to store data
vector<ofIndexType> indexs;
cout << imageFilename << endl;
fin >> numRows;
while(readRows < numRows) //as long as theres still text to be read
{
float x,y,z;
ofSpherePrimitive spherePrimitive;
spherePrimitive.setRadius(5.0);
fin >> x >> y;
cout <<"Coord tex:" << x << ", " << y << endl;
spherePrimitive.setPosition(ofVec3f(1.0*x*_colorImage.width,1.0*y*_colorImage.height,0.0) );
vertices.push_back(ofVec3f(1.0*x*_colorImage.width,1.0*y*_colorImage.height,0.0));
texCoord.push_back(ofVec2f(1.0*x,1.0*y));
_verticesSpheres.push_back(spherePrimitive);
bbox.maxX = max(bbox.maxX, x*_colorImage.width);
bbox.maxY = max(bbox.maxY, y*_colorImage.height);
bbox.minX = min(bbox.minX, x*_colorImage.width);
bbox.minY = min(bbox.minY, y*_colorImage.height);
readRows++;
}
fin.close();
cout << "I've read " << vertices.size() << "vertices" << endl;
_blackMesh.addVertices(vertices);
_mesh.addVertices(vertices);
_mesh.addTexCoords(texCoord);
fin.open( ofToDataPath(fpTriFilename).c_str() ); //open your text file
fin >> numRows;
while(fin!=NULL) //as long as theres still text to be read
{
int x,y,z;
fin >> x >> y >> z;
indexs.push_back(x-1);
indexs.push_back(y-1);
indexs.push_back(z-1);
}
fin.close();
_mesh.addIndices(indexs);
_blackMesh.addIndices(indexs);
// Set normals
ofEnableNormalizedTexCoords();
int nV = _mesh.getNumVertices();
int nT = _mesh.getNumIndices()/3;
vector<ofPoint> norm(nV);
for (int t=0; t<nT; t++) {
int i1 = _mesh.getIndex(3*t);
int i2 = _mesh.getIndex(3*t+1);
int i3 = _mesh.getIndex(3*t+2);
const ofPoint &p1 = _mesh.getVertex(i1);
const ofPoint &p2 = _mesh.getVertex(i2);
const ofPoint &p3 = _mesh.getVertex(i3);
ofPoint dir = ((p2 -p1).cross(p3-p1)).normalized();
norm[i1] -= dir;
norm[i2] -= dir;
norm[i3] -= dir;
}
for (int i = 0; i < nV; i++) {
norm[i].normalize();
ofVec3f v = _mesh.getVertex(i);
v.z += 0.1;
_blackMesh.setVertex(i, v);
}
_mesh.clearNormals();
_mesh.addNormals(norm);
//printf("%d - %d\n", numRows, _mesh.getNumVertices());
//cout << bbox.minX << ", " << bbox.maxX << endl;
//cout << bbox.minY << ", " << bbox.maxY << endl;
// Material
materialColor.setBrightness(250.f);
//materialColor.setSaturation(200);
material.setSpecularColor(materialColor);
material.setAmbientColor(ofFloatColor(255.f,255.f,255.f,255.f));
// Camera
testCam.setupPerspective(true, 60, 1, 1500, ofVec2f(0.0));
testCam.setPosition(bbox.minX+(bbox.maxX-bbox.minX)/2.0,bbox.minY+(bbox.maxY-bbox.minY)/2.0,1000.0);
testCam.lookAt(ofVec3f(bbox.minX+(bbox.maxX-bbox.minX)/2.0,bbox.minY+(bbox.maxY-bbox.minY)/2.0,0.0), ofVec3f(0.0,1.0,0.0));
//cout << "MVP: " << testCam.getModelViewProjectionMatrix() << endl << "------------------------" << endl;
ofEnableDepthTest();
cout << "Setup Mesh has :" << _mesh.getNumVertices() << endl;
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
testCam.begin(ofGetCurrentViewport());
// Draw mesh
material.begin();
ofSetColor(255,255,255);
//glPushName(0);
_colorImage.getTextureReference().bind();
_mesh.draw();
_colorImage.getTextureReference().unbind();
//glPopName();
_mesh.axis().drawWireframe();
material.end();
// Draw black mesh
ofSetColor(0.0, 0.0, 0.0);
_blackMesh.drawWireframe();
// Draw spheres
ofSetColor(255,255,255);
for(int i = 0; i < _verticesSpheres.size(); i++)
{
//glPushName(i);
_verticesSpheres[i].draw();
//glPopName();
}
testCam.end();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
if(key == 's')
save();
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
//cout << "Dragged: " << x << ", " << y << "->";
if(_pickedId>-1)
{
ofVec3f newPos = testCam.screenToWorld(ofVec3f(x,ofGetHeight()-y,0.999333), ofGetCurrentViewport());
newPos.z = 0.0;
//cout << _mesh.getVertex(_pickedId) << " - " << x << ", " << y << endl;
_mesh.disableTextures();
_mesh.setTexCoord(_pickedId, ofVec2f(newPos.x/_colorImage.width,newPos.y/_colorImage.height));
_mesh.enableTextures();
_mesh.setVertex(_pickedId, newPos);
_verticesSpheres[_pickedId].setPosition(newPos);
newPos.z = 0.1;
_blackMesh.setVertex(_pickedId, newPos);
}
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
_pickedId = glSelect(x,y);
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
_pickedId = -1;
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
//--------------------------------------------------------------
// From: http://forum.openframeworks.cc/t/problem-with-picking-objects-in-opengl/2143/5
int ofApp::glSelect(int x, int y)
{
GLuint buff[512] = {0};
GLint hits, view[4];
//GLfloat proj_matrixgl[16];
ofRectangle viewport = ofGetCurrentViewport();
/*
This choose the buffer where store the values for the selection data
*/
glSelectBuffer(512, buff);
/*
This retrieves info about the viewport
*/
glGetIntegerv(GL_VIEWPORT, view);
//glGetFloatv(GL_PROJECTION_MATRIX, proj_matrixgl);
ofMatrix4x4 proj_matrix = testCam.getProjectionMatrix(viewport);
/*
Switching in selecton mode
*/
glRenderMode(GL_SELECT);
/*
Clearing the names' stack
This stack contains all the info about the objects
*/
glInitNames();
/*
Now modify the viewing volume, restricting selection area around the cursor
*/
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
/*
restrict the draw to an area around the cursor
*/
gluPickMatrix(x, y, 1.0, 1.0, view);
glMultMatrixf(proj_matrix.getPtr());
/*
Draw the objects onto the screen
*/
glMatrixMode(GL_MODELVIEW);
/*
draw only the names in the stack, and fill the array
*/
/******** draw(); *****/
glPushMatrix();
glLoadIdentity();
glMultMatrixf(testCam.getModelViewMatrix().getPtr());
//glPushName(0);
_mesh.draw();
//glPopName();
// Draw spheres
for(int i = 0; i < _verticesSpheres.size(); i++)
{
glPushName(i);
_verticesSpheres[i].draw();
glPopName();
}
glPopMatrix();
/*
Do you remeber? We do pushMatrix in PROJECTION mode
*/
glMatrixMode(GL_PROJECTION);
glPopMatrix();
/*
get number of objects drawed in that area
and return to render mode
*/
hits = glRenderMode(GL_RENDER);
/*
Get nearest object
*/
unsigned int j;
GLuint *ptr, minZ, minminZ, nearestId = -1, *ptrNames, numberOfNames;
//printf ("hits = %d\n", hits);
ptr = (GLuint *) buff;
minminZ = 0xffffffff;
for (int i = 0; i < hits; i++) {
numberOfNames = *ptr;
ptr++;
minZ = *ptr;
ptrNames = ptr+2;
if(minminZ>minZ && numberOfNames>0){
minminZ = minZ;
nearestId = ptrNames[0];
}
/*printf("%d names found:",numberOfNames);
for (j = 0; j < numberOfNames; j++,ptrNames++) {
printf ("%d ", *ptrNames);
}
printf ("\n");*/
ptr += numberOfNames+2;
}
printf("nearest id %d\n",nearestId);
glMatrixMode(GL_MODELVIEW);
/*
Return nearest object
*/
return nearestId;
}
void ofApp::save()
{
string fpCoordFilename = _path;
if(_useRamanan)
{
ofStringReplace(fpCoordFilename, "originals", "ramanan2D");
}
else
{
ofStringReplace(fpCoordFilename, "originals", "ToyFace");
}
ofStringReplace(fpCoordFilename, ".obj", ".dat");
cout << "Save Mesh has :" << _mesh.getNumVertices() << endl;
ofstream fout; //declare a file stream
fout.open( ofToDataPath(fpCoordFilename).c_str() ); //open your text file
fout << _mesh.getNumVertices();
for (int i = 0; i < _mesh.getNumVertices(); i++) {
ofVec3f pos = _mesh.getVertex(i);
fout << endl << pos.x/_colorImage.width << " " << pos.y/_colorImage.height ;
}
fout.close();
}
<commit_msg>Added loadMesh and updated camera parameters<commit_after>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
bbox.maxX = std::numeric_limits<float>::min();
bbox.maxY = std::numeric_limits<float>::min();
bbox.minX = std::numeric_limits<float>::max();
bbox.minY = std::numeric_limits<float>::max();
_useRamanan = false;
// Load image
_path = "/Users/spherik//Documents/WORK/PhD/Bosphorus/originals/bs000/bs000_E_FEAR_0.obj";
//_path = "/home/spherik/Documents/PhD/Bosphorus/originals/bs000/bs000_E_FEAR_0.obj";
//_path = "/Volumes/Dades/spherik/Documents/WORK/PhD/Bosphorus/originals/bs000/bs000_E_ANGER_0.obj";
if(!loadMesh(_path))
{
ofExit();
}
cout << "BBox:" << endl << "* Min: " << bbox.minX << ", " << bbox.minY << endl << "* Max: " << bbox.maxX << ", " << bbox.maxY << endl << "* Center: " << bbox.minX+(bbox.maxX-bbox.minX)/2.0 << ", " << bbox.minY+(bbox.maxY-bbox.minY)<< endl;
float diagonal = sqrt((bbox.maxX-bbox.minX)*(bbox.maxX-bbox.minX)+(bbox.maxY-bbox.minY)*(bbox.maxY-bbox.minY));
// Material
materialColor.setBrightness(250.f);
//materialColor.setSaturation(200);
material.setSpecularColor(materialColor);
material.setAmbientColor(ofFloatColor(255.f,255.f,255.f,255.f));
// Camera
float viewAngle = 60.0;
double distance = (diagonal/2.0)/sin((viewAngle*(pi/180)/2.0));
std::cout << "Diagonal: " << diagonal << ". Distance: " << distance << endl;
testCam.setupPerspective(true, viewAngle, 1, distance*1.5, ofVec2f(0.0));
testCam.setPosition(bbox.minX+(bbox.maxX-bbox.minX)/2.0,bbox.minY+(bbox.maxY-bbox.minY)/2.0,distance);
testCam.lookAt(ofVec3f(bbox.minX+(bbox.maxX-bbox.minX)/2.0,bbox.minY+(bbox.maxY-bbox.minY)/2.0,0.0), ofVec3f(0.0,1.0,0.0));
cout << "MVP: " << testCam.getModelViewProjectionMatrix() << endl << "------------------------" << endl;
ofEnableDepthTest();
cout << "Setup Mesh has :" << _mesh.getNumVertices() << endl;
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
//ofTrueTypeFont ttf;
//ttf.loadFont("verdana.ttf", 32, true, true, true);
ofSetColor(255);
ofDrawBitmapString("FPS: "+ ofToString((int) ofGetFrameRate()), 10, 20);
testCam.begin(ofGetCurrentViewport());
// Draw mesh
material.begin();
ofSetColor(255,255,255);
//glPushName(0);
_colorImage.getTextureReference().bind();
_mesh.draw();
_colorImage.getTextureReference().unbind();
//glPopName();
_mesh.axis().drawWireframe();
material.end();
// Draw black mesh
ofSetColor(0.0, 0.0, 0.0);
_blackMesh.drawWireframe();
// Draw spheres
ofSetColor(255,255,255);
for(int i = 0; i < _verticesSpheres.size(); i++)
{
//glPushName(i);
_verticesSpheres[i].draw();
//glPopName();
}
testCam.end();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
if(key == 's')
save();
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
//cout << "Dragged: " << x << ", " << y << "->";
if(_pickedId>-1)
{
ofVec3f newPos = testCam.screenToWorld(ofVec3f(x,ofGetHeight()-y,0.999333), ofGetCurrentViewport());
newPos.z = 0.0;
//cout << _mesh.getVertex(_pickedId) << " - " << x << ", " << y << endl;
_mesh.disableTextures();
_mesh.setTexCoord(_pickedId, ofVec2f(newPos.x/_colorImage.width,newPos.y/_colorImage.height));
_mesh.enableTextures();
_mesh.setVertex(_pickedId, newPos);
_verticesSpheres[_pickedId].setPosition(newPos);
newPos.z = 0.1;
_blackMesh.setVertex(_pickedId, newPos);
}
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
_pickedId = glSelect(x,y);
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
_pickedId = -1;
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
//--------------------------------------------------------------
// From: http://forum.openframeworks.cc/t/problem-with-picking-objects-in-opengl/2143/5
int ofApp::glSelect(int x, int y)
{
GLuint buff[512] = {0};
GLint hits, view[4];
//GLfloat proj_matrixgl[16];
ofRectangle viewport = ofGetCurrentViewport();
/*
This choose the buffer where store the values for the selection data
*/
glSelectBuffer(512, buff);
/*
This retrieves info about the viewport
*/
glGetIntegerv(GL_VIEWPORT, view);
//glGetFloatv(GL_PROJECTION_MATRIX, proj_matrixgl);
ofMatrix4x4 proj_matrix = testCam.getProjectionMatrix(viewport);
/*
Switching in selecton mode
*/
glRenderMode(GL_SELECT);
/*
Clearing the names' stack
This stack contains all the info about the objects
*/
glInitNames();
/*
Now modify the viewing volume, restricting selection area around the cursor
*/
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
/*
restrict the draw to an area around the cursor
*/
gluPickMatrix(x, y, 1.0, 1.0, view);
glMultMatrixf(proj_matrix.getPtr());
/*
Draw the objects onto the screen
*/
glMatrixMode(GL_MODELVIEW);
/*
draw only the names in the stack, and fill the array
*/
/******** draw(); *****/
glPushMatrix();
glLoadIdentity();
glMultMatrixf(testCam.getModelViewMatrix().getPtr());
//glPushName(0);
_mesh.draw();
//glPopName();
// Draw spheres
for(int i = 0; i < _verticesSpheres.size(); i++)
{
glPushName(i);
_verticesSpheres[i].draw();
glPopName();
}
glPopMatrix();
/*
Do you remeber? We do pushMatrix in PROJECTION mode
*/
glMatrixMode(GL_PROJECTION);
glPopMatrix();
/*
get number of objects drawed in that area
and return to render mode
*/
hits = glRenderMode(GL_RENDER);
/*
Get nearest object
*/
unsigned int j;
GLuint *ptr, minZ, minminZ, nearestId = -1, *ptrNames, numberOfNames;
//printf ("hits = %d\n", hits);
ptr = (GLuint *) buff;
minminZ = 0xffffffff;
for (int i = 0; i < hits; i++) {
numberOfNames = *ptr;
ptr++;
minZ = *ptr;
ptrNames = ptr+2;
if(minminZ>minZ && numberOfNames>0){
minminZ = minZ;
nearestId = ptrNames[0];
}
/*printf("%d names found:",numberOfNames);
for (j = 0; j < numberOfNames; j++,ptrNames++) {
printf ("%d ", *ptrNames);
}
printf ("\n");*/
ptr += numberOfNames+2;
}
printf("nearest id %d\n",nearestId);
glMatrixMode(GL_MODELVIEW);
/*
Return nearest object
*/
return nearestId;
}
void ofApp::save()
{
string fpCoordFilename = _path;
if(_useRamanan)
{
ofStringReplace(fpCoordFilename, "originals", "ramanan2D");
}
else
{
ofStringReplace(fpCoordFilename, "originals", "ToyFace");
}
ofStringReplace(fpCoordFilename, ".obj", ".dat");
cout << "Save Mesh has :" << _mesh.getNumVertices() << endl;
ofstream fout; //declare a file stream
fout.open( ofToDataPath(fpCoordFilename).c_str() ); //open your text file
fout << _mesh.getNumVertices();
for (int i = 0; i < _mesh.getNumVertices(); i++) {
ofVec3f pos = _mesh.getVertex(i);
fout << endl << pos.x/_colorImage.width << " " << pos.y/_colorImage.height ;
}
fout.close();
}
bool ofApp::loadMesh(string filename)
{
string imageFilename = filename;
ofStringReplace(imageFilename, "originals", "images");
ofStringReplace(imageFilename, ".obj", ".png");
_colorImage.loadImage(imageFilename);
//Load mesh
string fpCoordFilename = filename;
string fpTriFilename = filename;
_mesh.setMode(OF_PRIMITIVE_TRIANGLES);
if(_useRamanan)
{
ofStringReplace(fpCoordFilename, "originals", "ramanan2D");
ofStringReplace(fpCoordFilename, ".obj", ".dat");
ofStringReplace(fpTriFilename, "originals", "ramanan3D");
vector<string> splitString = ofSplitString( fpTriFilename, "/");
ofStringReplace(fpTriFilename, splitString[splitString.size()-1], "ramanan.tri");
ofStringReplace(fpTriFilename, splitString[splitString.size()-2], "");
}
else
{
ofStringReplace(fpCoordFilename, "originals", "ToyFace");
ofStringReplace(fpCoordFilename, ".obj", ".dat");
ofStringReplace(fpTriFilename, "originals", "ToyFace");
vector<string> splitString = ofSplitString( fpTriFilename, "/");
ofStringReplace(fpTriFilename, splitString[splitString.size()-1], "ramanan.tri");
ofStringReplace(fpTriFilename, splitString[splitString.size()-2], "");
cout << fpCoordFilename << endl;
}
//cout << fpTriFilename << endl;
int numRows = 0;
int readRows = 0;
ifstream fin; //declare a file stream
fin.open( ofToDataPath(fpCoordFilename).c_str() ); //open your text file
vector<ofVec3f> vertices;
vector<ofVec2f> texCoord;
vector<ofIndexType> indexs;
cout << imageFilename << endl;
fin >> numRows;
while(readRows < numRows) //as long as theres still text to be read
{
float x,y,z;
ofSpherePrimitive spherePrimitive;
spherePrimitive.setRadius(5.0);
fin >> x >> y;
spherePrimitive.setPosition(ofVec3f(1.0*x*_colorImage.width,1.0*y*_colorImage.height,0.0) );
vertices.push_back(ofVec3f(1.0*x*_colorImage.width,1.0*y*_colorImage.height,0.0));
texCoord.push_back(ofVec2f(1.0*x,1.0*y));
_verticesSpheres.push_back(spherePrimitive);
bbox.maxX = max(bbox.maxX, x*_colorImage.width);
bbox.maxY = max(bbox.maxY, y*_colorImage.height);
bbox.minX = min(bbox.minX, x*_colorImage.width);
bbox.minY = min(bbox.minY, y*_colorImage.height);
readRows++;
}
fin.close();
cout << "I've read " << vertices.size() << "vertices" << endl;
_blackMesh.addVertices(vertices);
_mesh.addVertices(vertices);
_mesh.addTexCoords(texCoord);
fin.open( ofToDataPath(fpTriFilename).c_str() ); //open your text file
fin >> numRows;
while(fin!=NULL) //as long as theres still text to be read
{
int x,y,z;
fin >> x >> y >> z;
indexs.push_back(x-1);
indexs.push_back(y-1);
indexs.push_back(z-1);
}
fin.close();
_mesh.addIndices(indexs);
_blackMesh.addIndices(indexs);
// Set normals
ofEnableNormalizedTexCoords();
int nV = _mesh.getNumVertices();
int nT = _mesh.getNumIndices()/3;
vector<ofPoint> norm(nV);
for (int t=0; t<nT; t++) {
int i1 = _mesh.getIndex(3*t);
int i2 = _mesh.getIndex(3*t+1);
int i3 = _mesh.getIndex(3*t+2);
const ofPoint &p1 = _mesh.getVertex(i1);
const ofPoint &p2 = _mesh.getVertex(i2);
const ofPoint &p3 = _mesh.getVertex(i3);
ofPoint dir = ((p2 -p1).cross(p3-p1)).normalized();
norm[i1] -= dir;
norm[i2] -= dir;
norm[i3] -= dir;
}
for (int i = 0; i < nV; i++) {
norm[i].normalize();
ofVec3f v = _mesh.getVertex(i);
v.z += 0.1;
_blackMesh.setVertex(i, v);
}
_mesh.clearNormals();
_mesh.addNormals(norm);
return true;
}
<|endoftext|> |
<commit_before>#include "order.h"
void Order::init(vector<Task> tasks, vector<Maitenance> maitenance_v){
int machine1_ready_time = 10000, first_job_rt_pos = 0, iter;
if (tasks[0].get_ready_t() == 0) {machine1_ready_time = 0;}
else{
//finding smallest ready_time
for (unsigned int i = 0; i < tasks.size(); i++){
if (tasks[i].get_ready_t() < machine1_ready_time) {
machine1_ready_time = tasks[i].get_ready_t();
first_job_rt_pos = i;
}
}
//swapping jobs with first
iter_swap(tasks.begin()+0, tasks.begin()+first_job_rt_pos);
}
machine1.init(1, tasks[0].get_ready_t());
machine2.init(2, tasks[0].get_ready_t());
for (unsigned int i = 0; i < tasks.size(); i++){
iter = i;
if (machine1.get_stop_t() >= tasks[i].get_ready_t()){ // when fits perfectly
while (!machine1.add(tasks[i], maitenance_v)){
tasks.push_back(tasks[i]);
tasks.erase(tasks.begin()+i);
iter++;
if (iter == tasks.size())
{
iter = i;
break;
}
}
if( machine2.get_stop_t() >= tasks[i].get_ready_t()){
machine2.add(tasks[i], maitenance_v);
}else{
machine2.set_stop_t(tasks[i].get_ready_t());
machine2.add(tasks[i], maitenance_v);}
}
else{ // if machine1.get_stop_t() > tasks[i].get_ready_t()
for (unsigned int j = i + 1; j < tasks.size(); j++){
if(machine1.get_stop_t() >= tasks[i].get_ready_t()){
iter_swap(tasks.begin()+i, tasks.begin()+j);
break;
}
}
if (machine1.get_stop_t() >= tasks[i].get_ready_t()){
while (!machine1.add(tasks[i], maitenance_v)){
tasks.push_back(tasks[i]);
tasks.erase(tasks.begin()+i);
iter++;
if (iter == tasks.size())
{
iter = i;
break;
}
}
if( machine2.get_stop_t() >= tasks[i].get_ready_t()){
machine2.add(tasks[i], maitenance_v);
}else{
machine2.set_stop_t(tasks[i].get_ready_t());
machine2.add(tasks[i], maitenance_v);}
}else{ //move rt
while (!machine1.add(tasks[i], maitenance_v)){
tasks.push_back(tasks[i]);
tasks.erase(tasks.begin()+i);
iter++;
if (iter == tasks.size())
{
iter = i;
break;
}
}
if( machine2.get_stop_t() >= tasks[i].get_ready_t()){
machine2.add(tasks[i], maitenance_v);
}else{
machine2.set_stop_t(tasks[i].get_ready_t());
machine2.add(tasks[i], maitenance_v);
}
}
}
}
}
int Order::get_exectime(){
return exec_t;
}
vector<Task> Order::get_tasks(){
return this->machine1.get_tasks();
}
<commit_msg>order<commit_after>#include "order.h"
void Order::init(vector<Task> tasks, vector<Maitenance> maitenance_v){
int machine1_ready_time = 10000, first_job_rt_pos = 0, iter;
if (tasks[0].get_ready_t() == 0) {machine1_ready_time = 0;}
else{
//finding smallest ready_time
for (unsigned int i = 0; i < tasks.size(); i++){
if (tasks[i].get_ready_t() < machine1_ready_time) {
machine1_ready_time = tasks[i].get_ready_t();
first_job_rt_pos = i;
}
}
//swapping jobs with first
iter_swap(tasks.begin()+0, tasks.begin()+first_job_rt_pos);
}
machine1.init(1, tasks[0].get_ready_t());
machine2.init(2, tasks[0].get_ready_t());
for (unsigned int i = 0; i < tasks.size(); i++){
iter = i;
if (machine1.get_stop_t() >= tasks[i].get_ready_t()){ // when fits perfectly
while (!machine1.add(tasks[i], maitenance_v)){
tasks.push_back(tasks[i]);
tasks.erase(tasks.begin()+i);
iter++;
if (iter == tasks.size())
{
iter = i;
break;
}
}
if( machine2.get_stop_t() >= machine1.get_stop_t()){
machine2.add(tasks[i], maitenance_v);
}else{
machine2.set_stop_t(machine1.get_stop_t());
machine2.add(tasks[i], maitenance_v);}
}
else{ // if machine1.get_stop_t() > tasks[i].get_ready_t()
for (unsigned int j = i + 1; j < tasks.size(); j++){
if(machine1.get_stop_t() >= tasks[i].get_ready_t()){
iter_swap(tasks.begin()+i, tasks.begin()+j);
break;
}
if ( j == tasks.size() -1 ){
machine1.set_stop_t(tasks[i].get_ready_t());
}
}
i--;
}
}
}
int Order::get_exectime(){
return exec_t;
}
vector<Task> Order::get_tasks(){
return this->machine1.get_tasks();
}
<|endoftext|> |
<commit_before>/* Calf DSP Library utility application.
* DSSI GUI application.
* Copyright (C) 2007 Krzysztof Foltman
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
#include <sys/wait.h>
#include "config.h"
#include <calf/gui.h>
#include <calf/giface.h>
#include <calf/lv2_data_access.h>
#include <calf/lv2_ui.h>
#include <calf/lv2_uri_map.h>
#include <calf/lv2_external_ui.h>
#include <calf/lv2helpers.h>
#include <calf/utils.h>
#include <glib.h>
using namespace std;
using namespace calf_plugins;
using namespace calf_utils;
struct LV2_Calf_Descriptor {
plugin_ctl_iface *(*get_pci)(LV2_Handle Instance);
};
/// Temporary assignment to a slot in vector<bool>
typedef scope_assign<bool, vector<bool>::reference> TempSendSetter;
/// Common data and functions for GTK+ GUI and External GUI
struct plugin_proxy_base
{
const plugin_metadata_iface *plugin_metadata;
LV2UI_Write_Function write_function;
LV2UI_Controller controller;
// Values extracted from the Features array from the host
/// Handle to the plugin instance
LV2_Handle instance_handle;
/// Data access feature instance
LV2_Extension_Data_Feature *data_access;
/// URI map feature
LV2_URI_Map_Feature *uri_map;
/// External UI host feature (must be set when instantiating external UI plugins)
lv2_external_ui_host *ext_ui_host;
/// Instance pointer - usually NULL unless the host supports instance-access extension
plugin_ctl_iface *instance;
/// If true, a given parameter (not port) may be sent to host - it is blocked when the parameter is written to by the host
vector<bool> sends;
/// Map of parameter name to parameter index (used for mapping configure values to string ports)
map<string, int> params_by_name;
/// Values of parameters (float control ports)
vector<float> params;
/// Number of parameters (non-audio ports)
int param_count;
/// Number of the first parameter port
int param_offset;
plugin_proxy_base(const plugin_metadata_iface *metadata, LV2UI_Write_Function wf, LV2UI_Controller c, const LV2_Feature* const* features);
/// Send a float value to a control port in the host
void send_float_to_host(int param_no, float value);
/// Send a string value to a string port in the host, by name (configure-like mechanism)
char *configure(const char *key, const char *value);
/// Enable sending to host for all ports
void enable_all_sends();
/// Obtain instance pointers
void resolve_instance();
/// Obtain line graph interface if available
const line_graph_iface *get_line_graph_iface() const;
/// Obtain phase graph interface if available
const phase_graph_iface *get_phase_graph_iface() const;
/// Map an URI to an integer value using a given URI map
uint32_t map_uri(const char *mapURI, const char *keyURI);
};
plugin_proxy_base::plugin_proxy_base(const plugin_metadata_iface *metadata, LV2UI_Write_Function wf, LV2UI_Controller c, const LV2_Feature* const* features)
{
plugin_metadata = metadata;
write_function = wf;
controller = c;
instance = NULL;
instance_handle = NULL;
data_access = NULL;
ext_ui_host = NULL;
param_count = metadata->get_param_count();
param_offset = metadata->get_param_port_offset();
/// Block all updates until GUI is ready
sends.resize(param_count, false);
params.resize(param_count);
for (int i = 0; i < param_count; i++)
{
const parameter_properties *pp = metadata->get_param_props(i);
params_by_name[pp->short_name] = i;
params[i] = pp->def_value;
}
for (int i = 0; features[i]; i++)
{
if (!strcmp(features[i]->URI, "http://lv2plug.in/ns/ext/instance-access"))
{
instance_handle = features[i]->data;
}
else if (!strcmp(features[i]->URI, "http://lv2plug.in/ns/ext/data-access"))
{
data_access = (LV2_Extension_Data_Feature *)features[i]->data;
}
else if (!strcmp(features[i]->URI, LV2_EXTERNAL_UI_URI))
{
ext_ui_host = (lv2_external_ui_host *)features[i]->data;
}
}
resolve_instance();
}
void plugin_proxy_base::send_float_to_host(int param_no, float value)
{
params[param_no] = value;
if (sends[param_no]) {
TempSendSetter _a_(sends[param_no], false);
write_function(controller, param_no + param_offset, sizeof(float), 0, ¶ms[param_no]);
}
}
void plugin_proxy_base::resolve_instance()
{
fprintf(stderr, "CALF DEBUG: instance %p data %p\n", instance_handle, data_access);
if (instance_handle && data_access)
{
LV2_Calf_Descriptor *calf = (LV2_Calf_Descriptor *)(*data_access->data_access)("http://foltman.com/ns/calf-plugin-instance");
fprintf(stderr, "CALF DEBUG: calf %p cpi %p\n", calf, calf ? calf->get_pci : NULL);
if (calf && calf->get_pci)
instance = calf->get_pci(instance_handle);
}
}
uint32_t plugin_proxy_base::map_uri(const char *mapURI, const char *keyURI)
{
if (!uri_map)
return 0;
return uri_map->uri_to_id(uri_map->callback_data, mapURI, keyURI);
}
const line_graph_iface *plugin_proxy_base::get_line_graph_iface() const
{
if (instance)
return instance->get_line_graph_iface();
return NULL;
}
const phase_graph_iface *plugin_proxy_base::get_phase_graph_iface() const
{
if (instance)
return instance->get_phase_graph_iface();
return NULL;
}
char *plugin_proxy_base::configure(const char *key, const char *value)
{
if (instance)
return instance->configure(key, value);
else
return strdup("Configuration not available because of lack of instance-access/data-access");
}
void plugin_proxy_base::enable_all_sends()
{
sends.clear();
sends.resize(param_count, true);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Plugin controller that uses LV2 host with help of instance/data access to remotely
/// control a plugin from the GUI
struct lv2_plugin_proxy: public plugin_ctl_iface, public plugin_proxy_base, public gui_environment
{
/// Plugin GTK+ GUI object pointer
plugin_gui *gui;
/// Glib source ID for update timer
int source_id;
lv2_plugin_proxy(const plugin_metadata_iface *md, LV2UI_Write_Function wf, LV2UI_Controller c, const LV2_Feature* const* f)
: plugin_proxy_base(md, wf, c, f)
{
gui = NULL;
if (instance)
{
conditions.insert("directlink");
conditions.insert("configure");
}
conditions.insert("lv2gui");
}
virtual float get_param_value(int param_no) {
if (param_no < 0 || param_no >= param_count)
return 0;
return params[param_no];
}
virtual void set_param_value(int param_no, float value) {
if (param_no < 0 || param_no >= param_count)
return;
send_float_to_host(param_no, value);
}
virtual bool activate_preset(int bank, int program)
{
return false;
}
/// Override for a method in plugin_ctl_iface - trivial delegation to base class
virtual char *configure(const char *key, const char *value) { return plugin_proxy_base::configure(key, value); }
virtual float get_level(unsigned int port) { return 0.f; }
virtual void execute(int command_no) { assert(0); }
virtual void send_configures(send_configure_iface *sci)
{
if (instance)
{
fprintf(stderr, "Send configures...\n");
instance->send_configures(sci);
}
else
fprintf(stderr, "Configuration not available because of lack of instance-access/data-access\n");
}
virtual int send_status_updates(send_updates_iface *sui, int last_serial)
{
if (instance)
return instance->send_status_updates(sui, last_serial);
else // no status updates because of lack of instance-access/data-access
return 0;
}
virtual const plugin_metadata_iface *get_metadata_iface() const { return plugin_metadata; }
/// Override for a method in plugin_ctl_iface - trivial delegation to base class
virtual const line_graph_iface *get_line_graph_iface() const { return plugin_proxy_base::get_line_graph_iface(); }
/// Override for a method in plugin_ctl_iface - trivial delegation to base class
virtual const phase_graph_iface *get_phase_graph_iface() const { return plugin_proxy_base::get_phase_graph_iface(); }
};
static gboolean plugin_on_idle(void *data)
{
plugin_gui *self = (plugin_gui *)data;
self->on_idle();
return TRUE;
}
LV2UI_Handle gui_instantiate(const struct _LV2UI_Descriptor* descriptor,
const char* plugin_uri,
const char* bundle_path,
LV2UI_Write_Function write_function,
LV2UI_Controller controller,
LV2UI_Widget* widget,
const LV2_Feature* const* features)
{
const plugin_metadata_iface *md = plugin_registry::instance().get_by_uri(plugin_uri);
if (!md)
return NULL;
lv2_plugin_proxy *proxy = new lv2_plugin_proxy(md, write_function, controller, features);
if (!proxy)
return NULL;
gtk_rc_parse(PKGLIBDIR "calf.rc");
plugin_gui_window *window = new plugin_gui_window(proxy, NULL);
plugin_gui *gui = new plugin_gui(window);
const char *xml = proxy->plugin_metadata->get_gui_xml();
assert(xml);
*(GtkWidget **)(widget) = gui->create_from_xml(proxy, xml);
proxy->enable_all_sends();
if (*(GtkWidget **)(widget))
proxy->source_id = g_timeout_add_full(G_PRIORITY_LOW, 1000/30, plugin_on_idle, gui, NULL); // 30 fps should be enough for everybody
gui->show_rack_ears(proxy->get_config()->rack_ears);
return (LV2UI_Handle)gui;
}
void gui_cleanup(LV2UI_Handle handle)
{
plugin_gui *gui = (plugin_gui *)handle;
lv2_plugin_proxy *proxy = dynamic_cast<lv2_plugin_proxy *>(gui->plugin);
if (proxy->source_id)
g_source_remove(proxy->source_id);
delete gui;
}
void gui_port_event(LV2UI_Handle handle, uint32_t port, uint32_t buffer_size, uint32_t format, const void *buffer)
{
plugin_gui *gui = (plugin_gui *)handle;
lv2_plugin_proxy *proxy = dynamic_cast<lv2_plugin_proxy *>(gui->plugin);
assert(proxy);
float v = *(float *)buffer;
int param = port - proxy->plugin_metadata->get_param_port_offset();
if (param >= proxy->plugin_metadata->get_param_count())
return;
if (!proxy->sends[param])
return;
if (fabs(gui->plugin->get_param_value(param) - v) < 0.00001)
return;
{
TempSendSetter _a_(proxy->sends[param], false);
gui->set_param_value(param, v);
}
}
const void *gui_extension(const char *uri)
{
return NULL;
}
const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index)
{
static LV2UI_Descriptor gtkgui;
gtkgui.URI = "http://calf.sourceforge.net/plugins/gui/gtk2-gui";
gtkgui.instantiate = gui_instantiate;
gtkgui.cleanup = gui_cleanup;
gtkgui.port_event = gui_port_event;
gtkgui.extension_data = gui_extension;
if (!index--)
return >kgui;
return NULL;
}
<commit_msg>Attempt to fix initialisation of non-port values in the GUI.<commit_after>/* Calf DSP Library utility application.
* DSSI GUI application.
* Copyright (C) 2007 Krzysztof Foltman
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
#include <sys/wait.h>
#include "config.h"
#include <calf/gui.h>
#include <calf/giface.h>
#include <calf/lv2_data_access.h>
#include <calf/lv2_ui.h>
#include <calf/lv2_uri_map.h>
#include <calf/lv2_external_ui.h>
#include <calf/lv2helpers.h>
#include <calf/utils.h>
#include <glib.h>
using namespace std;
using namespace calf_plugins;
using namespace calf_utils;
struct LV2_Calf_Descriptor {
plugin_ctl_iface *(*get_pci)(LV2_Handle Instance);
};
/// Temporary assignment to a slot in vector<bool>
typedef scope_assign<bool, vector<bool>::reference> TempSendSetter;
/// Common data and functions for GTK+ GUI and External GUI
struct plugin_proxy_base
{
const plugin_metadata_iface *plugin_metadata;
LV2UI_Write_Function write_function;
LV2UI_Controller controller;
// Values extracted from the Features array from the host
/// Handle to the plugin instance
LV2_Handle instance_handle;
/// Data access feature instance
LV2_Extension_Data_Feature *data_access;
/// URI map feature
LV2_URI_Map_Feature *uri_map;
/// External UI host feature (must be set when instantiating external UI plugins)
lv2_external_ui_host *ext_ui_host;
/// Instance pointer - usually NULL unless the host supports instance-access extension
plugin_ctl_iface *instance;
/// If true, a given parameter (not port) may be sent to host - it is blocked when the parameter is written to by the host
vector<bool> sends;
/// Map of parameter name to parameter index (used for mapping configure values to string ports)
map<string, int> params_by_name;
/// Values of parameters (float control ports)
vector<float> params;
/// Number of parameters (non-audio ports)
int param_count;
/// Number of the first parameter port
int param_offset;
plugin_proxy_base(const plugin_metadata_iface *metadata, LV2UI_Write_Function wf, LV2UI_Controller c, const LV2_Feature* const* features);
/// Send a float value to a control port in the host
void send_float_to_host(int param_no, float value);
/// Send a string value to a string port in the host, by name (configure-like mechanism)
char *configure(const char *key, const char *value);
/// Enable sending to host for all ports
void enable_all_sends();
/// Obtain instance pointers
void resolve_instance();
/// Obtain line graph interface if available
const line_graph_iface *get_line_graph_iface() const;
/// Obtain phase graph interface if available
const phase_graph_iface *get_phase_graph_iface() const;
/// Map an URI to an integer value using a given URI map
uint32_t map_uri(const char *mapURI, const char *keyURI);
};
plugin_proxy_base::plugin_proxy_base(const plugin_metadata_iface *metadata, LV2UI_Write_Function wf, LV2UI_Controller c, const LV2_Feature* const* features)
{
plugin_metadata = metadata;
write_function = wf;
controller = c;
instance = NULL;
instance_handle = NULL;
data_access = NULL;
ext_ui_host = NULL;
param_count = metadata->get_param_count();
param_offset = metadata->get_param_port_offset();
/// Block all updates until GUI is ready
sends.resize(param_count, false);
params.resize(param_count);
for (int i = 0; i < param_count; i++)
{
const parameter_properties *pp = metadata->get_param_props(i);
params_by_name[pp->short_name] = i;
params[i] = pp->def_value;
}
for (int i = 0; features[i]; i++)
{
if (!strcmp(features[i]->URI, "http://lv2plug.in/ns/ext/instance-access"))
{
instance_handle = features[i]->data;
}
else if (!strcmp(features[i]->URI, "http://lv2plug.in/ns/ext/data-access"))
{
data_access = (LV2_Extension_Data_Feature *)features[i]->data;
}
else if (!strcmp(features[i]->URI, LV2_EXTERNAL_UI_URI))
{
ext_ui_host = (lv2_external_ui_host *)features[i]->data;
}
}
resolve_instance();
}
void plugin_proxy_base::send_float_to_host(int param_no, float value)
{
params[param_no] = value;
if (sends[param_no]) {
TempSendSetter _a_(sends[param_no], false);
write_function(controller, param_no + param_offset, sizeof(float), 0, ¶ms[param_no]);
}
}
void plugin_proxy_base::resolve_instance()
{
fprintf(stderr, "CALF DEBUG: instance %p data %p\n", instance_handle, data_access);
if (instance_handle && data_access)
{
LV2_Calf_Descriptor *calf = (LV2_Calf_Descriptor *)(*data_access->data_access)("http://foltman.com/ns/calf-plugin-instance");
fprintf(stderr, "CALF DEBUG: calf %p cpi %p\n", calf, calf ? calf->get_pci : NULL);
if (calf && calf->get_pci)
instance = calf->get_pci(instance_handle);
}
}
uint32_t plugin_proxy_base::map_uri(const char *mapURI, const char *keyURI)
{
if (!uri_map)
return 0;
return uri_map->uri_to_id(uri_map->callback_data, mapURI, keyURI);
}
const line_graph_iface *plugin_proxy_base::get_line_graph_iface() const
{
if (instance)
return instance->get_line_graph_iface();
return NULL;
}
const phase_graph_iface *plugin_proxy_base::get_phase_graph_iface() const
{
if (instance)
return instance->get_phase_graph_iface();
return NULL;
}
char *plugin_proxy_base::configure(const char *key, const char *value)
{
if (instance)
return instance->configure(key, value);
else
return strdup("Configuration not available because of lack of instance-access/data-access");
}
void plugin_proxy_base::enable_all_sends()
{
sends.clear();
sends.resize(param_count, true);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Plugin controller that uses LV2 host with help of instance/data access to remotely
/// control a plugin from the GUI
struct lv2_plugin_proxy: public plugin_ctl_iface, public plugin_proxy_base, public gui_environment
{
/// Plugin GTK+ GUI object pointer
plugin_gui *gui;
/// Glib source ID for update timer
int source_id;
lv2_plugin_proxy(const plugin_metadata_iface *md, LV2UI_Write_Function wf, LV2UI_Controller c, const LV2_Feature* const* f)
: plugin_proxy_base(md, wf, c, f)
{
gui = NULL;
if (instance)
{
conditions.insert("directlink");
conditions.insert("configure");
}
conditions.insert("lv2gui");
}
virtual float get_param_value(int param_no) {
if (param_no < 0 || param_no >= param_count)
return 0;
return params[param_no];
}
virtual void set_param_value(int param_no, float value) {
if (param_no < 0 || param_no >= param_count)
return;
send_float_to_host(param_no, value);
}
virtual bool activate_preset(int bank, int program)
{
return false;
}
/// Override for a method in plugin_ctl_iface - trivial delegation to base class
virtual char *configure(const char *key, const char *value) { return plugin_proxy_base::configure(key, value); }
virtual float get_level(unsigned int port) { return 0.f; }
virtual void execute(int command_no) { assert(0); }
virtual void send_configures(send_configure_iface *sci)
{
if (instance)
{
fprintf(stderr, "Send configures...\n");
instance->send_configures(sci);
}
else
fprintf(stderr, "Configuration not available because of lack of instance-access/data-access\n");
}
virtual int send_status_updates(send_updates_iface *sui, int last_serial)
{
if (instance)
return instance->send_status_updates(sui, last_serial);
else // no status updates because of lack of instance-access/data-access
return 0;
}
virtual const plugin_metadata_iface *get_metadata_iface() const { return plugin_metadata; }
/// Override for a method in plugin_ctl_iface - trivial delegation to base class
virtual const line_graph_iface *get_line_graph_iface() const { return plugin_proxy_base::get_line_graph_iface(); }
/// Override for a method in plugin_ctl_iface - trivial delegation to base class
virtual const phase_graph_iface *get_phase_graph_iface() const { return plugin_proxy_base::get_phase_graph_iface(); }
};
static gboolean plugin_on_idle(void *data)
{
plugin_gui *self = (plugin_gui *)data;
self->on_idle();
return TRUE;
}
LV2UI_Handle gui_instantiate(const struct _LV2UI_Descriptor* descriptor,
const char* plugin_uri,
const char* bundle_path,
LV2UI_Write_Function write_function,
LV2UI_Controller controller,
LV2UI_Widget* widget,
const LV2_Feature* const* features)
{
const plugin_metadata_iface *md = plugin_registry::instance().get_by_uri(plugin_uri);
if (!md)
return NULL;
lv2_plugin_proxy *proxy = new lv2_plugin_proxy(md, write_function, controller, features);
if (!proxy)
return NULL;
gtk_rc_parse(PKGLIBDIR "calf.rc");
plugin_gui_window *window = new plugin_gui_window(proxy, NULL);
plugin_gui *gui = new plugin_gui(window);
const char *xml = proxy->plugin_metadata->get_gui_xml();
assert(xml);
*(GtkWidget **)(widget) = gui->create_from_xml(proxy, xml);
proxy->enable_all_sends();
proxy->send_configures(gui);
if (*(GtkWidget **)(widget))
proxy->source_id = g_timeout_add_full(G_PRIORITY_LOW, 1000/30, plugin_on_idle, gui, NULL); // 30 fps should be enough for everybody
gui->show_rack_ears(proxy->get_config()->rack_ears);
return (LV2UI_Handle)gui;
}
void gui_cleanup(LV2UI_Handle handle)
{
plugin_gui *gui = (plugin_gui *)handle;
lv2_plugin_proxy *proxy = dynamic_cast<lv2_plugin_proxy *>(gui->plugin);
if (proxy->source_id)
g_source_remove(proxy->source_id);
delete gui;
}
void gui_port_event(LV2UI_Handle handle, uint32_t port, uint32_t buffer_size, uint32_t format, const void *buffer)
{
plugin_gui *gui = (plugin_gui *)handle;
lv2_plugin_proxy *proxy = dynamic_cast<lv2_plugin_proxy *>(gui->plugin);
assert(proxy);
float v = *(float *)buffer;
int param = port - proxy->plugin_metadata->get_param_port_offset();
if (param >= proxy->plugin_metadata->get_param_count())
return;
if (!proxy->sends[param])
return;
if (fabs(gui->plugin->get_param_value(param) - v) < 0.00001)
return;
{
TempSendSetter _a_(proxy->sends[param], false);
gui->set_param_value(param, v);
}
}
const void *gui_extension(const char *uri)
{
return NULL;
}
const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index)
{
static LV2UI_Descriptor gtkgui;
gtkgui.URI = "http://calf.sourceforge.net/plugins/gui/gtk2-gui";
gtkgui.instantiate = gui_instantiate;
gtkgui.cleanup = gui_cleanup;
gtkgui.port_event = gui_port_event;
gtkgui.extension_data = gui_extension;
if (!index--)
return >kgui;
return NULL;
}
<|endoftext|> |
<commit_before>/* Calf DSP Library utility application.
* DSSI GUI application.
* Copyright (C) 2007 Krzysztof Foltman
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <getopt.h>
#include <stdint.h>
#include <stdlib.h>
#include <config.h>
#include <calf/giface.h>
#include <calf/gui.h>
#include <calf/modules.h>
#include <calf/modules_dev.h>
#include <calf/benchmark.h>
#include <calf/lv2-gui.h>
#include <calf/preset_gui.h>
using namespace std;
using namespace dsp;
using namespace synth;
struct plugin_proxy_base: public plugin_ctl_iface
{
LV2UI_Write_Function write_function;
LV2UI_Controller controller;
bool send;
plugin_gui *gui;
plugin_proxy_base()
{
send = false;
gui = NULL;
}
void setup(LV2UI_Write_Function wfn, LV2UI_Controller ctl)
{
write_function = wfn;
controller = ctl;
}
};
template<class Module>
struct plugin_proxy: public plugin_proxy_base, public line_graph_iface
{
float params[Module::param_count];
plugin_proxy()
{
send = true;
for (int i = 0; i < Module::param_count; i++)
params[i] = Module::param_props[i].def_value;
}
virtual parameter_properties *get_param_props(int param_no) {
return Module::param_props + param_no;
}
virtual float get_param_value(int param_no) {
if (param_no < 0 || param_no >= Module::param_count)
return 0;
return params[param_no];
}
virtual void set_param_value(int param_no, float value) {
if (param_no < 0 || param_no >= Module::param_count)
return;
params[param_no] = value;
if (send) {
send = false;
write_function(controller, param_no + Module::in_count + Module::out_count, sizeof(float), ¶ms[param_no]);
send = true;
}
}
virtual int get_param_count() {
return Module::param_count;
}
virtual int get_param_port_offset() {
return Module::in_count + Module::out_count;
}
virtual const char *get_gui_xml() {
return Module::get_gui_xml();
}
virtual line_graph_iface *get_line_graph_iface() {
return this;
}
virtual bool activate_preset(int bank, int program) {
return false;
}
virtual bool get_graph(int index, int subindex, float *data, int points, cairo_t *context) {
return Module::get_static_graph(index, subindex, params[index], data, points, context);
}
};
plugin_proxy_base *create_plugin_proxy(const char *effect_name)
{
if (!strcmp(effect_name, "Reverb"))
return new plugin_proxy<reverb_audio_module>();
else if (!strcmp(effect_name, "Flanger"))
return new plugin_proxy<flanger_audio_module>();
else if (!strcmp(effect_name, "Filter"))
return new plugin_proxy<filter_audio_module>();
else if (!strcmp(effect_name, "Monosynth"))
return new plugin_proxy<monosynth_audio_module>();
else if (!strcmp(effect_name, "VintageDelay"))
return new plugin_proxy<vintage_delay_audio_module>();
#ifdef ENABLE_EXPERIMENTAL
else if (!strcmp(effect_name, "Organ"))
return new plugin_proxy<organ_audio_module>();
else if (!strcmp(effect_name, "RotarySpeaker"))
return new plugin_proxy<rotary_speaker_audio_module>();
#endif
else
return NULL;
}
LV2UI_Descriptor gui;
LV2UI_Handle gui_instantiate(const struct _LV2UI_Descriptor* descriptor,
const char* plugin_uri,
const char* bundle_path,
LV2UI_Write_Function write_function,
LV2UI_Controller controller,
LV2UI_Widget* widget,
const LV2_Feature* const* features)
{
plugin_proxy_base *proxy = create_plugin_proxy(plugin_uri + sizeof("http://calf.sourceforge.net/plugins/") - 1);
proxy->setup(write_function, controller);
// dummy window
plugin_gui_window *window = new plugin_gui_window;
window->conditions.insert("lv2gui");
plugin_gui *gui = new plugin_gui(window);
*(GtkWidget **)(widget) = gui->create(proxy);
return (LV2UI_Handle)gui;
}
void gui_cleanup(LV2UI_Handle handle)
{
plugin_gui *gui = (plugin_gui *)handle;
delete gui;
}
void gui_port_event(LV2UI_Handle handle, uint32_t port, uint32_t buffer_size, const void *buffer)
{
plugin_gui *gui = (plugin_gui *)handle;
float v = *(float *)buffer;
// printf("spv %d %f\n", port, v);
port -= gui->plugin->get_param_port_offset();
if (port >= (uint32_t)gui->plugin->get_param_count())
return;
gui->set_param_value(port, v);
}
const void *gui_extension(const char *uri)
{
return NULL;
}
namespace synth {
// this function is normally implemented in preset_gui.cpp, but we're not using that file
void activate_preset(GtkAction *action, activate_preset_params *params)
{
}
// so is this function
void store_preset(GtkWindow *toplevel, plugin_gui *gui)
{
}
};
const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index)
{
gui.URI = "http://calf.sourceforge.net/plugins/gui/gtk2-gui";
gui.instantiate = gui_instantiate;
gui.cleanup = gui_cleanup;
gui.port_event = gui_port_event;
gui.extension_data = gui_extension;
switch(index) {
case 0:
return &gui;
default:
return NULL;
}
}
<commit_msg>+ LV2 GUI: use XML-based GUI if available<commit_after>/* Calf DSP Library utility application.
* DSSI GUI application.
* Copyright (C) 2007 Krzysztof Foltman
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <getopt.h>
#include <stdint.h>
#include <stdlib.h>
#include <config.h>
#include <calf/giface.h>
#include <calf/gui.h>
#include <calf/modules.h>
#include <calf/modules_dev.h>
#include <calf/benchmark.h>
#include <calf/lv2-gui.h>
#include <calf/preset_gui.h>
using namespace std;
using namespace dsp;
using namespace synth;
struct plugin_proxy_base: public plugin_ctl_iface
{
LV2UI_Write_Function write_function;
LV2UI_Controller controller;
bool send;
plugin_gui *gui;
plugin_proxy_base()
{
send = false;
gui = NULL;
}
void setup(LV2UI_Write_Function wfn, LV2UI_Controller ctl)
{
write_function = wfn;
controller = ctl;
}
};
template<class Module>
struct plugin_proxy: public plugin_proxy_base, public line_graph_iface
{
float params[Module::param_count];
plugin_proxy()
{
send = true;
for (int i = 0; i < Module::param_count; i++)
params[i] = Module::param_props[i].def_value;
}
virtual parameter_properties *get_param_props(int param_no) {
return Module::param_props + param_no;
}
virtual float get_param_value(int param_no) {
if (param_no < 0 || param_no >= Module::param_count)
return 0;
return params[param_no];
}
virtual void set_param_value(int param_no, float value) {
if (param_no < 0 || param_no >= Module::param_count)
return;
params[param_no] = value;
if (send) {
send = false;
write_function(controller, param_no + Module::in_count + Module::out_count, sizeof(float), ¶ms[param_no]);
send = true;
}
}
virtual int get_param_count() {
return Module::param_count;
}
virtual int get_param_port_offset() {
return Module::in_count + Module::out_count;
}
virtual const char *get_gui_xml() {
return Module::get_gui_xml();
}
virtual line_graph_iface *get_line_graph_iface() {
return this;
}
virtual bool activate_preset(int bank, int program) {
return false;
}
virtual bool get_graph(int index, int subindex, float *data, int points, cairo_t *context) {
return Module::get_static_graph(index, subindex, params[index], data, points, context);
}
};
plugin_proxy_base *create_plugin_proxy(const char *effect_name)
{
if (!strcmp(effect_name, "Reverb"))
return new plugin_proxy<reverb_audio_module>();
else if (!strcmp(effect_name, "Flanger"))
return new plugin_proxy<flanger_audio_module>();
else if (!strcmp(effect_name, "Filter"))
return new plugin_proxy<filter_audio_module>();
else if (!strcmp(effect_name, "Monosynth"))
return new plugin_proxy<monosynth_audio_module>();
else if (!strcmp(effect_name, "VintageDelay"))
return new plugin_proxy<vintage_delay_audio_module>();
#ifdef ENABLE_EXPERIMENTAL
else if (!strcmp(effect_name, "Organ"))
return new plugin_proxy<organ_audio_module>();
else if (!strcmp(effect_name, "RotarySpeaker"))
return new plugin_proxy<rotary_speaker_audio_module>();
#endif
else
return NULL;
}
LV2UI_Descriptor gui;
LV2UI_Handle gui_instantiate(const struct _LV2UI_Descriptor* descriptor,
const char* plugin_uri,
const char* bundle_path,
LV2UI_Write_Function write_function,
LV2UI_Controller controller,
LV2UI_Widget* widget,
const LV2_Feature* const* features)
{
plugin_proxy_base *proxy = create_plugin_proxy(plugin_uri + sizeof("http://calf.sourceforge.net/plugins/") - 1);
proxy->setup(write_function, controller);
// dummy window
plugin_gui_window *window = new plugin_gui_window;
window->conditions.insert("lv2gui");
plugin_gui *gui = new plugin_gui(window);
const char *xml = proxy->get_gui_xml();
if (xml)
*(GtkWidget **)(widget) = gui->create_from_xml(proxy, xml);
else
*(GtkWidget **)(widget) = gui->create(proxy);
return (LV2UI_Handle)gui;
}
void gui_cleanup(LV2UI_Handle handle)
{
plugin_gui *gui = (plugin_gui *)handle;
delete gui;
}
void gui_port_event(LV2UI_Handle handle, uint32_t port, uint32_t buffer_size, const void *buffer)
{
plugin_gui *gui = (plugin_gui *)handle;
float v = *(float *)buffer;
// printf("spv %d %f\n", port, v);
port -= gui->plugin->get_param_port_offset();
if (port >= (uint32_t)gui->plugin->get_param_count())
return;
gui->set_param_value(port, v);
}
const void *gui_extension(const char *uri)
{
return NULL;
}
namespace synth {
// this function is normally implemented in preset_gui.cpp, but we're not using that file
void activate_preset(GtkAction *action, activate_preset_params *params)
{
}
// so is this function
void store_preset(GtkWindow *toplevel, plugin_gui *gui)
{
}
};
const LV2UI_Descriptor* lv2ui_descriptor(uint32_t index)
{
gui.URI = "http://calf.sourceforge.net/plugins/gui/gtk2-gui";
gui.instantiate = gui_instantiate;
gui.cleanup = gui_cleanup;
gui.port_event = gui_port_event;
gui.extension_data = gui_extension;
switch(index) {
case 0:
return &gui;
default:
return NULL;
}
}
<|endoftext|> |
<commit_before>// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// 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 <cassert>
#include <limits>
#include "geo/int-size.hh"
#include "geo/size.hh"
namespace faint{
bool IntSize::operator==(const IntSize& other) const{
return w == other.w && h == other.h;
}
bool IntSize::operator!=(const IntSize& other) const{
return !((*this)==other);
}
int area(const IntSize& sz){
return sz.w * sz.h;
}
IntSize min_coords(const IntSize& lhs, const IntSize& rhs){
return IntSize(std::min(lhs.w, rhs.w), std::min(lhs.h, rhs.h));
}
IntSize max_coords(const IntSize& lhs, const IntSize& rhs){
return IntSize(std::max(lhs.w, rhs.w), std::max(lhs.h, rhs.h));
}
IntSize operator+(const IntSize& lhs, const IntSize& rhs){
return IntSize(lhs.w + rhs.w, lhs.h + rhs.h);
}
IntSize operator-(const IntSize& lhs, const IntSize& rhs){
return IntSize(lhs.w - rhs.w, lhs.h - rhs.h);
}
IntSize operator*(const IntSize& lhs, const IntSize& rhs){
return IntSize(lhs.w * rhs.w, lhs.h * rhs.h);
}
IntSize operator*(const IntSize& size, int scalar){
return IntSize(scalar * size.w, scalar * size.h);
}
IntSize operator*(int scalar, const IntSize& size){
return size * scalar;
}
IntSize operator/(const IntSize& size, int scalar){
return IntSize(size.w / scalar, size.h / scalar);
}
IntSize transposed(const IntSize& sz){
return IntSize(sz.h, sz.w);
}
Size operator*(const IntSize& size, coord scale){
return Size(size.w * scale, size.h * scale);
}
Size operator*(coord scale, const IntSize& size){
return size * scale;
}
Size operator/(const IntSize& size, coord scale){
return Size(size.w / scale, size.h / scale);
}
bool area_less(const IntSize& size, int area){
assert(size.w >= 0 && size.h >= 0 && area >= 0);
if (size.w == 0 || size.h == 0){
return false;
}
if (size.w > std::numeric_limits<int>::max() / size.h){
return false;
}
return size.w * size.h < area;
}
} // namespace
<commit_msg>Tidied up int-size.<commit_after>// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// 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 <cassert>
#include <limits>
#include "geo/int-size.hh"
#include "geo/size.hh"
namespace faint{
bool IntSize::operator==(const IntSize& other) const{
return w == other.w && h == other.h;
}
bool IntSize::operator!=(const IntSize& other) const{
return !((*this)==other);
}
int area(const IntSize& sz){
return sz.w * sz.h;
}
IntSize min_coords(const IntSize& lhs, const IntSize& rhs){
return {std::min(lhs.w, rhs.w), std::min(lhs.h, rhs.h)};
}
IntSize max_coords(const IntSize& lhs, const IntSize& rhs){
return {std::max(lhs.w, rhs.w), std::max(lhs.h, rhs.h)};
}
IntSize operator+(const IntSize& lhs, const IntSize& rhs){
return {lhs.w + rhs.w, lhs.h + rhs.h};
}
IntSize operator-(const IntSize& lhs, const IntSize& rhs){
return {lhs.w - rhs.w, lhs.h - rhs.h};
}
IntSize operator*(const IntSize& lhs, const IntSize& rhs){
return {lhs.w * rhs.w, lhs.h * rhs.h};
}
IntSize operator*(const IntSize& size, int scalar){
return {scalar * size.w, scalar * size.h};
}
IntSize operator*(int scalar, const IntSize& size){
return size * scalar;
}
IntSize operator/(const IntSize& size, int scalar){
return {size.w / scalar, size.h / scalar};
}
IntSize transposed(const IntSize& sz){
return {sz.h, sz.w};
}
Size operator*(const IntSize& size, coord scale){
return {size.w * scale, size.h * scale};
}
Size operator*(coord scale, const IntSize& size){
return size * scale;
}
Size operator/(const IntSize& size, coord scale){
return {size.w / scale, size.h / scale};
}
bool area_less(const IntSize& size, int area){
assert(size.w >= 0 && size.h >= 0 && area >= 0);
if (size.w == 0 || size.h == 0){
return false;
}
if (size.w > std::numeric_limits<int>::max() / size.h){
return false;
}
return size.w * size.h < area;
}
} // namespace
<|endoftext|> |
<commit_before>#include "console.h"
#include "engine.h"
#include "pathos/render/render_overlay.h"
#include "pathos/overlay/display_object.h"
#include "pathos/overlay/rectangle.h"
#include "pathos/overlay/label.h"
#include "pathos/overlay/brush.h"
#include "pathos/util/string_conversion.h"
#include "pathos/util/math_lib.h"
#define MAX_HINT_LIST 8
#define HINT_LABEL_WIDTH 300
#define HINT_LABEL_HEIGHT 20
namespace pathos {
static constexpr float LEFT_MARGIN = 10.0f;
static constexpr float LINE_GAP = 20.0f;
static constexpr size_t MAX_LINES = 18;
static constexpr size_t MAX_HISTORY = 64;
ConsoleWindow::ConsoleWindow(OverlayRenderer* renderer2D)
: initialized(false)
, visible(true)
, windowWidth(0)
, windowHeight(0)
, renderer(renderer2D)
, root(nullptr)
, background(nullptr)
, inputText(nullptr)
, hintBackground(nullptr)
, inputHistoryCursor(0)
{
CHECK(renderer != nullptr);
}
ConsoleWindow::~ConsoleWindow() {
if (root) delete root;
if (background) delete background;
}
bool ConsoleWindow::initialize(uint16 width, uint16 height) {
windowWidth = width;
windowHeight = height;
root = DisplayObject2D::createRoot();
background = new Rectangle(windowWidth, windowHeight);
background->setBrush(new SolidColorBrush(0.0f, 0.0f, 0.1f));
root->addChild(background);
inputText = new Label(L"> ");
inputText->setX(10.0f);
inputText->setY(height - 30.0f);
root->addChild(inputText);
hintBackground = new Rectangle(HINT_LABEL_WIDTH, 10.0f + (MAX_HINT_LIST + 1) * HINT_LABEL_HEIGHT);
hintBackground->setBrush(new SolidColorBrush(0.0f, 0.1f, 0.1f));
hintBackground->setX(10.0f);
hintBackground->setY(windowHeight - 40.0f - (MAX_HINT_LIST + 1) * HINT_LABEL_HEIGHT);
hintBackground->setVisible(false);
root->addChild(hintBackground);
for (int32 i = 0; i <= MAX_HINT_LIST; ++i) {
Label* hint = new Label(L"...");
hint->setX(0.0f);
hint->setY((float)(i * HINT_LABEL_HEIGHT));
hint->setVisible(false);
hintList.push_back(hint);
root->addChild(hint);
}
initialized = true;
return initialized;
}
void ConsoleWindow::renderConsoleWindow(RenderCommandList& cmdList) {
if (visible) {
renderer->renderOverlay(cmdList, root);
}
}
void ConsoleWindow::toggle() {
visible = !visible;
}
bool ConsoleWindow::isVisible() const {
return visible;
}
void ConsoleWindow::onKeyPress(unsigned char ascii) {
if (ascii == 0x08) {
// backspace
if (currentInput.size() > 0) {
currentInput = currentInput.substr(0, currentInput.size() - 1);
}
} else if (ascii == 13) {
// enter
addLine(currentInput.data(), true);
currentInput = L"";
} else {
currentInput += ascii;
}
updateInputLine();
}
void ConsoleWindow::showPreviousHistory() {
if (inputHistory.size() > 0) {
inputHistoryCursor = pathos::max(0, inputHistoryCursor - 1);
currentInput = inputHistory[inputHistoryCursor];
updateInputLine();
}
}
void ConsoleWindow::showNextHistory() {
if (inputHistory.size() > 0) {
inputHistoryCursor = pathos::min((int32)inputHistory.size(), inputHistoryCursor + 1);
currentInput = (inputHistoryCursor == (int32)inputHistory.size()) ? L"" : inputHistory[inputHistoryCursor];
updateInputLine();
}
}
Label* ConsoleWindow::addLine(const char* text, bool addToHistory) {
std::wstring buffer;
pathos::MBCS_TO_WCHAR(text, buffer);
return addLine(buffer.data(), addToHistory);
}
Label* ConsoleWindow::addLine(const wchar_t* text, bool addToHistory) {
if (wcslen(text) == 0) {
return nullptr;
}
Label* label = new Label(text);
label->setX(LEFT_MARGIN);
label->setY(textList.size() * LINE_GAP);
textList.push_back(label);
root->addChild(label);
if (textList.size() > MAX_LINES) {
Label* old = textList.front();
root->removeChild(old);
textList.pop_front();
delete old;
for (Label* label : textList) {
label->setY(label->getY() - LINE_GAP);
}
}
evaluate(text);
if (addToHistory) {
addInputHistory(text);
}
return label;
}
void ConsoleWindow::updateInputLine() {
std::wstring input2 = L"> " + currentInput;
inputText->setVisible(true);
inputText->setText(input2.data());
updateHint(currentInput, currentInput.size() == 0);
}
void ConsoleWindow::updateHint(const std::wstring& currentText, bool forceHide) {
if (forceHide) {
hintBackground->setVisible(false);
for (int32 i = 0; i <= MAX_HINT_LIST; ++i) {
hintList[i]->setVisible(false);
}
return;
}
enum class HintCategory {
Exec = 0,
CVar = 1
};
std::vector<std::wstring> allCommands;
std::vector<HintCategory> hintCategories;
for (const auto& it : gEngine->getExecMap()) {
std::wstring wcmd;
pathos::MBCS_TO_WCHAR(it.first, wcmd);
allCommands.push_back(wcmd);
hintCategories.push_back(HintCategory::Exec);
}
std::string currentTextMBCS;
std::vector<std::string> matchingCVars;
pathos::WCHAR_TO_MBCS(currentText, currentTextMBCS);
ConsoleVariableManager::get().getCVarNamesWithPrefix(currentTextMBCS.c_str(), matchingCVars);
for (const auto& it : matchingCVars) {
std::wstring cvarNameW;
pathos::MBCS_TO_WCHAR(it, cvarNameW);
allCommands.push_back(cvarNameW);
hintCategories.push_back(HintCategory::CVar);
}
int32 hintIx = 0;
int32 totalMatching = 0;
for (int32 i = 0; i < allCommands.size(); ++i) {
const std::wstring& cmd = allCommands[i];
const HintCategory cat = hintCategories[i];
if (cmd.find(currentInput) == 0) {
totalMatching += 1;
if (hintIx > MAX_HINT_LIST) {
continue;
} else if (hintIx == MAX_HINT_LIST) {
hintList[MAX_HINT_LIST]->setText(L"...");
hintList[MAX_HINT_LIST]->setColor(vector3(1.0f, 1.0f, 1.0f));
} else {
hintList[hintIx]->setText(cmd.c_str());
vector3 c = (cat == HintCategory::Exec) ? vector3(1.0f, 1.0f, 0.0f) : vector3(1.0f, 1.0f, 1.0f);
hintList[hintIx]->setColor(c);
}
hintIx += 1;
}
}
if (totalMatching > MAX_HINT_LIST) {
wchar_t buffer[256];
swprintf_s(buffer, L"%d more...", totalMatching - MAX_HINT_LIST);
hintList[MAX_HINT_LIST]->setText(buffer);
}
float baseY = windowHeight - 40.0f - (HINT_LABEL_HEIGHT * hintIx);
for (int32 i = 0; i < hintIx; ++i) {
hintList[i]->setVisible(true);
hintList[i]->setX(20.0f);
hintList[i]->setY(baseY + i * HINT_LABEL_HEIGHT);
}
for (int32 i = hintIx; i <= MAX_HINT_LIST; ++i) {
hintList[i]->setVisible(false);
}
hintBackground->setVisible(hintIx != 0);
}
void ConsoleWindow::evaluate(const wchar_t* text) {
std::string command;
pathos::WCHAR_TO_MBCS(text, command);
auto ix = command.find(' ');
std::string header = ix == string::npos ? command : command.substr(0, ix);
// Execute registered procedure if exists
if (gEngine->execute(command)) {
return;
}
// Is it a cvar?
if (auto cvar = ConsoleVariableManager::get().find(header.data())) {
std::string msg = command.substr(ix + 1);
if (ix == string::npos) {
cvar->print(this);
} else {
cvar->parse(msg.data(), this);
}
}
}
void ConsoleWindow::addInputHistory(const wchar_t* inputText) {
inputHistory.push_back(inputText);
if (inputHistory.size() > MAX_HISTORY) {
inputHistory.erase(inputHistory.begin());
}
inputHistoryCursor = (int32)inputHistory.size();
}
}
namespace pathos {
///////////////////////////////////////////////////////////
// ConsoleVariable
pathos::ConsoleVariableManager& ConsoleVariableManager::get()
{
static ConsoleVariableManager inst;
return inst;
}
ConsoleVariableBase* ConsoleVariableManager::find(const char* name) {
for (auto it = registry.begin(); it != registry.end(); ++it) {
ConsoleVariableBase* cvar = *it;
if(_strcmpi(cvar->name.data(), name) == 0) {
return cvar;
}
}
return nullptr;
}
void ConsoleVariableManager::registerCVar(ConsoleVariableBase* cvar)
{
std::lock_guard<std::mutex> lockRegistry(registryLock);
registry.push_back(cvar);
}
void ConsoleVariableManager::getCVarNamesWithPrefix(const char* prefix, std::vector<std::string>& outNames)
{
outNames.clear();
for (const auto& it : registry) {
if (it->name.find(prefix) == 0) {
outNames.push_back(it->name);
}
}
}
ConsoleVariableBase::ConsoleVariableBase() {
ConsoleVariableManager::get().registerCVar(this);
}
}
<commit_msg>Resize console width to window width<commit_after>#include "console.h"
#include "engine.h"
#include "pathos/render/render_overlay.h"
#include "pathos/overlay/display_object.h"
#include "pathos/overlay/rectangle.h"
#include "pathos/overlay/label.h"
#include "pathos/overlay/brush.h"
#include "pathos/util/string_conversion.h"
#include "pathos/util/math_lib.h"
#define MAX_HINT_LIST 8
#define HINT_LABEL_WIDTH 300
#define HINT_LABEL_HEIGHT 20
namespace pathos {
static constexpr float LEFT_MARGIN = 10.0f;
static constexpr float LINE_GAP = 20.0f;
static constexpr size_t MAX_LINES = 18;
static constexpr size_t MAX_HISTORY = 64;
ConsoleWindow::ConsoleWindow(OverlayRenderer* renderer2D)
: initialized(false)
, visible(true)
, windowWidth(0)
, windowHeight(0)
, renderer(renderer2D)
, root(nullptr)
, background(nullptr)
, inputText(nullptr)
, hintBackground(nullptr)
, inputHistoryCursor(0)
{
CHECK(renderer != nullptr);
}
ConsoleWindow::~ConsoleWindow() {
if (root) delete root;
if (background) delete background;
}
bool ConsoleWindow::initialize(uint16 width, uint16 height) {
windowWidth = width;
windowHeight = height;
root = DisplayObject2D::createRoot();
background = new Rectangle(windowWidth, windowHeight);
background->setBrush(new SolidColorBrush(0.0f, 0.0f, 0.1f));
root->addChild(background);
inputText = new Label(L"> ");
inputText->setX(10.0f);
inputText->setY(height - 30.0f);
root->addChild(inputText);
hintBackground = new Rectangle(HINT_LABEL_WIDTH, 10.0f + (MAX_HINT_LIST + 1) * HINT_LABEL_HEIGHT);
hintBackground->setBrush(new SolidColorBrush(0.0f, 0.1f, 0.1f));
hintBackground->setX(10.0f);
hintBackground->setY(windowHeight - 40.0f - (MAX_HINT_LIST + 1) * HINT_LABEL_HEIGHT);
hintBackground->setVisible(false);
root->addChild(hintBackground);
for (int32 i = 0; i <= MAX_HINT_LIST; ++i) {
Label* hint = new Label(L"...");
hint->setX(0.0f);
hint->setY((float)(i * HINT_LABEL_HEIGHT));
hint->setVisible(false);
hintList.push_back(hint);
root->addChild(hint);
}
initialized = true;
return initialized;
}
void ConsoleWindow::renderConsoleWindow(RenderCommandList& cmdList) {
if (visible) {
windowWidth = gEngine->getConfig().windowWidth;
background->setSize(windowWidth, windowHeight);
renderer->renderOverlay(cmdList, root);
}
}
void ConsoleWindow::toggle() {
visible = !visible;
}
bool ConsoleWindow::isVisible() const {
return visible;
}
void ConsoleWindow::onKeyPress(unsigned char ascii) {
if (ascii == 0x08) {
// backspace
if (currentInput.size() > 0) {
currentInput = currentInput.substr(0, currentInput.size() - 1);
}
} else if (ascii == 13) {
// enter
addLine(currentInput.data(), true);
currentInput = L"";
} else {
currentInput += ascii;
}
updateInputLine();
}
void ConsoleWindow::showPreviousHistory() {
if (inputHistory.size() > 0) {
inputHistoryCursor = pathos::max(0, inputHistoryCursor - 1);
currentInput = inputHistory[inputHistoryCursor];
updateInputLine();
}
}
void ConsoleWindow::showNextHistory() {
if (inputHistory.size() > 0) {
inputHistoryCursor = pathos::min((int32)inputHistory.size(), inputHistoryCursor + 1);
currentInput = (inputHistoryCursor == (int32)inputHistory.size()) ? L"" : inputHistory[inputHistoryCursor];
updateInputLine();
}
}
Label* ConsoleWindow::addLine(const char* text, bool addToHistory) {
std::wstring buffer;
pathos::MBCS_TO_WCHAR(text, buffer);
return addLine(buffer.data(), addToHistory);
}
Label* ConsoleWindow::addLine(const wchar_t* text, bool addToHistory) {
if (wcslen(text) == 0) {
return nullptr;
}
Label* label = new Label(text);
label->setX(LEFT_MARGIN);
label->setY(textList.size() * LINE_GAP);
textList.push_back(label);
root->addChild(label);
if (textList.size() > MAX_LINES) {
Label* old = textList.front();
root->removeChild(old);
textList.pop_front();
delete old;
for (Label* label : textList) {
label->setY(label->getY() - LINE_GAP);
}
}
evaluate(text);
if (addToHistory) {
addInputHistory(text);
}
return label;
}
void ConsoleWindow::updateInputLine() {
std::wstring input2 = L"> " + currentInput;
inputText->setVisible(true);
inputText->setText(input2.data());
updateHint(currentInput, currentInput.size() == 0);
}
void ConsoleWindow::updateHint(const std::wstring& currentText, bool forceHide) {
if (forceHide) {
hintBackground->setVisible(false);
for (int32 i = 0; i <= MAX_HINT_LIST; ++i) {
hintList[i]->setVisible(false);
}
return;
}
enum class HintCategory {
Exec = 0,
CVar = 1
};
std::vector<std::wstring> allCommands;
std::vector<HintCategory> hintCategories;
for (const auto& it : gEngine->getExecMap()) {
std::wstring wcmd;
pathos::MBCS_TO_WCHAR(it.first, wcmd);
allCommands.push_back(wcmd);
hintCategories.push_back(HintCategory::Exec);
}
std::string currentTextMBCS;
std::vector<std::string> matchingCVars;
pathos::WCHAR_TO_MBCS(currentText, currentTextMBCS);
ConsoleVariableManager::get().getCVarNamesWithPrefix(currentTextMBCS.c_str(), matchingCVars);
for (const auto& it : matchingCVars) {
std::wstring cvarNameW;
pathos::MBCS_TO_WCHAR(it, cvarNameW);
allCommands.push_back(cvarNameW);
hintCategories.push_back(HintCategory::CVar);
}
int32 hintIx = 0;
int32 totalMatching = 0;
for (int32 i = 0; i < allCommands.size(); ++i) {
const std::wstring& cmd = allCommands[i];
const HintCategory cat = hintCategories[i];
if (cmd.find(currentInput) == 0) {
totalMatching += 1;
if (hintIx > MAX_HINT_LIST) {
continue;
} else if (hintIx == MAX_HINT_LIST) {
hintList[MAX_HINT_LIST]->setText(L"...");
hintList[MAX_HINT_LIST]->setColor(vector3(1.0f, 1.0f, 1.0f));
} else {
hintList[hintIx]->setText(cmd.c_str());
vector3 c = (cat == HintCategory::Exec) ? vector3(1.0f, 1.0f, 0.0f) : vector3(1.0f, 1.0f, 1.0f);
hintList[hintIx]->setColor(c);
}
hintIx += 1;
}
}
if (totalMatching > MAX_HINT_LIST) {
wchar_t buffer[256];
swprintf_s(buffer, L"%d more...", totalMatching - MAX_HINT_LIST);
hintList[MAX_HINT_LIST]->setText(buffer);
}
float baseY = windowHeight - 40.0f - (HINT_LABEL_HEIGHT * hintIx);
for (int32 i = 0; i < hintIx; ++i) {
hintList[i]->setVisible(true);
hintList[i]->setX(20.0f);
hintList[i]->setY(baseY + i * HINT_LABEL_HEIGHT);
}
for (int32 i = hintIx; i <= MAX_HINT_LIST; ++i) {
hintList[i]->setVisible(false);
}
hintBackground->setVisible(hintIx != 0);
}
void ConsoleWindow::evaluate(const wchar_t* text) {
std::string command;
pathos::WCHAR_TO_MBCS(text, command);
auto ix = command.find(' ');
std::string header = ix == string::npos ? command : command.substr(0, ix);
// Execute registered procedure if exists
if (gEngine->execute(command)) {
return;
}
// Is it a cvar?
if (auto cvar = ConsoleVariableManager::get().find(header.data())) {
std::string msg = command.substr(ix + 1);
if (ix == string::npos) {
cvar->print(this);
} else {
cvar->parse(msg.data(), this);
}
}
}
void ConsoleWindow::addInputHistory(const wchar_t* inputText) {
inputHistory.push_back(inputText);
if (inputHistory.size() > MAX_HISTORY) {
inputHistory.erase(inputHistory.begin());
}
inputHistoryCursor = (int32)inputHistory.size();
}
}
namespace pathos {
///////////////////////////////////////////////////////////
// ConsoleVariable
pathos::ConsoleVariableManager& ConsoleVariableManager::get()
{
static ConsoleVariableManager inst;
return inst;
}
ConsoleVariableBase* ConsoleVariableManager::find(const char* name) {
for (auto it = registry.begin(); it != registry.end(); ++it) {
ConsoleVariableBase* cvar = *it;
if(_strcmpi(cvar->name.data(), name) == 0) {
return cvar;
}
}
return nullptr;
}
void ConsoleVariableManager::registerCVar(ConsoleVariableBase* cvar)
{
std::lock_guard<std::mutex> lockRegistry(registryLock);
registry.push_back(cvar);
}
void ConsoleVariableManager::getCVarNamesWithPrefix(const char* prefix, std::vector<std::string>& outNames)
{
outNames.clear();
for (const auto& it : registry) {
if (it->name.find(prefix) == 0) {
outNames.push_back(it->name);
}
}
}
ConsoleVariableBase::ConsoleVariableBase() {
ConsoleVariableManager::get().registerCVar(this);
}
}
<|endoftext|> |
<commit_before>//===-- interception_linux.cc -----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Windows-specific interception methods.
//===----------------------------------------------------------------------===//
#ifdef _WIN32
#include "interception.h"
#include <windows.h>
namespace __interception {
bool GetRealFunctionAddress(const char *func_name, uptr *func_addr) {
const char *DLLS[] = {
"msvcr80.dll",
"msvcr90.dll",
"kernel32.dll",
NULL
};
*func_addr = 0;
for (size_t i = 0; *func_addr == 0 && DLLS[i]; ++i) {
*func_addr = GetProcAddress(GetModuleHandleA(DLLS[i]), func_name);
}
return (*func_addr != 0);
}
// FIXME: internal_str* and internal_mem* functions should be moved from the
// ASan sources into interception/.
static void _memset(void *p, int value, size_t sz) {
for (size_t i = 0; i < sz; ++i)
((char*)p)[i] = (char)value;
}
static void _memcpy(void *dst, void *src, size_t sz) {
char *dst_c = (char*)dst,
*src_c = (char*)src;
for (size_t i = 0; i < sz; ++i)
dst_c[i] = src_c[i];
}
static void WriteJumpInstruction(char *jmp_from, char *to) {
// jmp XXYYZZWW = E9 WW ZZ YY XX, where XXYYZZWW is an offset fromt jmp_from
// to the next instruction to the destination.
ptrdiff_t offset = to - jmp_from - 5;
*jmp_from = '\xE9';
*(ptrdiff_t*)(jmp_from + 1) = offset;
}
bool OverrideFunction(uptr old_func, uptr new_func, uptr *orig_old_func) {
#ifdef _WIN64
# error OverrideFunction was not tested on x64
#endif
// Basic idea:
// We write 5 bytes (jmp-to-new_func) at the beginning of the 'old_func'
// to override it. We want to be able to execute the original 'old_func' from
// the wrapper, so we need to keep the leading 5+ bytes ('head') of the
// original instructions somewhere with a "jmp old_func+head".
// We call these 'head'+5 bytes of instructions a "trampoline".
// Trampolines are allocated from a common pool.
const int POOL_SIZE = 1024;
static char *pool = NULL;
static size_t pool_used = 0;
if (pool == NULL) {
pool = (char*)VirtualAlloc(NULL, POOL_SIZE,
MEM_RESERVE | MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
// FIXME: set PAGE_EXECUTE_READ access after setting all interceptors?
if (pool == NULL)
return false;
_memset(pool, 0xCC /* int 3 */, POOL_SIZE);
}
char* old_bytes = (char*)old_func;
char* trampoline = pool + pool_used;
// Find out the number of bytes of the instructions we need to copy to the
// island and store it in 'head'.
size_t head = 0;
while (head < 5) {
switch (old_bytes[head]) {
case '\x55': // push ebp
case '\x56': // push esi
case '\x57': // push edi
head++;
continue;
}
switch (*(unsigned short*)(old_bytes + head)) { // NOLINT
case 0xFF8B: // 8B FF = mov edi, edi
case 0xEC8B: // 8B EC = mov ebp, esp
case 0xC033: // 33 C0 = xor eax, eax
head += 2;
continue;
case 0xEC83: // 83 EC XX = sub esp, XX
head += 3;
continue;
case 0xC1F7: // F7 C1 XX YY ZZ WW = test ecx, WWZZYYXX
head += 6;
continue;
}
switch (0x00FFFFFF & *(unsigned int*)(old_bytes + head)) {
case 0x24448A: // 8A 44 24 XX = mov eal, dword ptr [esp+XXh]
case 0x244C8B: // 8B 4C 24 XX = mov ecx, dword ptr [esp+XXh]
case 0x24548B: // 8B 54 24 XX = mov edx, dword ptr [esp+XXh]
case 0x247C8B: // 8B 7C 24 XX = mov edi, dword ptr [esp+XXh]
head += 4;
continue;
}
// Unknown instruction!
return false;
}
if (pool_used + head + 5 > POOL_SIZE)
return false;
// Now put the "jump to trampoline" instruction into the original code.
DWORD old_prot, unused_prot;
if (!VirtualProtect((void*)old_func, head, PAGE_EXECUTE_READWRITE,
&old_prot))
return false;
// Put the needed instructions into the trampoline bytes.
_memcpy(trampoline, old_bytes, head);
WriteJumpInstruction(trampoline + head, old_bytes + head);
*orig_old_func = (uptr)trampoline;
pool_used += head + 5;
// Intercept the 'old_func'.
WriteJumpInstruction(old_bytes, (char*)new_func);
_memset(old_bytes + 5, 0xCC /* int 3 */, head - 5);
if (!VirtualProtect((void*)old_func, head, old_prot, &unused_prot))
return false; // not clear if this failure bothers us.
return true;
}
} // namespace __interception
#endif // _WIN32
<commit_msg>[Sanitizer] fix windows build<commit_after>//===-- interception_linux.cc -----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of AddressSanitizer, an address sanity checker.
//
// Windows-specific interception methods.
//===----------------------------------------------------------------------===//
#ifdef _WIN32
#include "interception.h"
#include <windows.h>
namespace __interception {
bool GetRealFunctionAddress(const char *func_name, uptr *func_addr) {
const char *DLLS[] = {
"msvcr80.dll",
"msvcr90.dll",
"kernel32.dll",
NULL
};
*func_addr = 0;
for (size_t i = 0; *func_addr == 0 && DLLS[i]; ++i) {
*func_addr = (uptr)GetProcAddress(GetModuleHandleA(DLLS[i]), func_name);
}
return (*func_addr != 0);
}
// FIXME: internal_str* and internal_mem* functions should be moved from the
// ASan sources into interception/.
static void _memset(void *p, int value, size_t sz) {
for (size_t i = 0; i < sz; ++i)
((char*)p)[i] = (char)value;
}
static void _memcpy(void *dst, void *src, size_t sz) {
char *dst_c = (char*)dst,
*src_c = (char*)src;
for (size_t i = 0; i < sz; ++i)
dst_c[i] = src_c[i];
}
static void WriteJumpInstruction(char *jmp_from, char *to) {
// jmp XXYYZZWW = E9 WW ZZ YY XX, where XXYYZZWW is an offset fromt jmp_from
// to the next instruction to the destination.
ptrdiff_t offset = to - jmp_from - 5;
*jmp_from = '\xE9';
*(ptrdiff_t*)(jmp_from + 1) = offset;
}
bool OverrideFunction(uptr old_func, uptr new_func, uptr *orig_old_func) {
#ifdef _WIN64
# error OverrideFunction was not tested on x64
#endif
// Basic idea:
// We write 5 bytes (jmp-to-new_func) at the beginning of the 'old_func'
// to override it. We want to be able to execute the original 'old_func' from
// the wrapper, so we need to keep the leading 5+ bytes ('head') of the
// original instructions somewhere with a "jmp old_func+head".
// We call these 'head'+5 bytes of instructions a "trampoline".
// Trampolines are allocated from a common pool.
const int POOL_SIZE = 1024;
static char *pool = NULL;
static size_t pool_used = 0;
if (pool == NULL) {
pool = (char*)VirtualAlloc(NULL, POOL_SIZE,
MEM_RESERVE | MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
// FIXME: set PAGE_EXECUTE_READ access after setting all interceptors?
if (pool == NULL)
return false;
_memset(pool, 0xCC /* int 3 */, POOL_SIZE);
}
char* old_bytes = (char*)old_func;
char* trampoline = pool + pool_used;
// Find out the number of bytes of the instructions we need to copy to the
// island and store it in 'head'.
size_t head = 0;
while (head < 5) {
switch (old_bytes[head]) {
case '\x55': // push ebp
case '\x56': // push esi
case '\x57': // push edi
head++;
continue;
}
switch (*(unsigned short*)(old_bytes + head)) { // NOLINT
case 0xFF8B: // 8B FF = mov edi, edi
case 0xEC8B: // 8B EC = mov ebp, esp
case 0xC033: // 33 C0 = xor eax, eax
head += 2;
continue;
case 0xEC83: // 83 EC XX = sub esp, XX
head += 3;
continue;
case 0xC1F7: // F7 C1 XX YY ZZ WW = test ecx, WWZZYYXX
head += 6;
continue;
}
switch (0x00FFFFFF & *(unsigned int*)(old_bytes + head)) {
case 0x24448A: // 8A 44 24 XX = mov eal, dword ptr [esp+XXh]
case 0x244C8B: // 8B 4C 24 XX = mov ecx, dword ptr [esp+XXh]
case 0x24548B: // 8B 54 24 XX = mov edx, dword ptr [esp+XXh]
case 0x247C8B: // 8B 7C 24 XX = mov edi, dword ptr [esp+XXh]
head += 4;
continue;
}
// Unknown instruction!
return false;
}
if (pool_used + head + 5 > POOL_SIZE)
return false;
// Now put the "jump to trampoline" instruction into the original code.
DWORD old_prot, unused_prot;
if (!VirtualProtect((void*)old_func, head, PAGE_EXECUTE_READWRITE,
&old_prot))
return false;
// Put the needed instructions into the trampoline bytes.
_memcpy(trampoline, old_bytes, head);
WriteJumpInstruction(trampoline + head, old_bytes + head);
*orig_old_func = (uptr)trampoline;
pool_used += head + 5;
// Intercept the 'old_func'.
WriteJumpInstruction(old_bytes, (char*)new_func);
_memset(old_bytes + 5, 0xCC /* int 3 */, head - 5);
if (!VirtualProtect((void*)old_func, head, old_prot, &unused_prot))
return false; // not clear if this failure bothers us.
return true;
}
} // namespace __interception
#endif // _WIN32
<|endoftext|> |
<commit_before>#include "include/http_server.h"
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stdlib.h>
#include <unistd.h>
#include <exception>
#include <signal.h>
#include <evhttp.h>
void process_get_request(struct evhttp_request *req, void *arg)
{
struct evbuffer *buf = evbuffer_new();
if (buf == NULL) return;
evbuffer_add_printf(buf, "Get Request", evhttp_request_uri(req));
evhttp_send_reply(req, HTTP_OK, "OK", buf);
}
void process_post_request(struct evhttp_request *req, void *arg)
{
struct evbuffer *buf = evbuffer_new();
if (!buf == NULL)
{
evbuffer_add_printf(buf, "Post Request", evhttp_request_uri(req));
evhttp_send_reply(req, HTTP_OK, "OK", buf);
}
}
//Process a request
void process_request(struct evhttp_request *req, void *arg){
std::cout << req->type << std::endl;
if (req->type == 1)
{
process_get_request(req, arg);
}
else if (req->type == 2)
{
process_post_request(req, arg);
}
else if (req->type == 8)
{
std::cout << "Put Detected" << std::endl;
}
else if (req->type == 16)
{
std::cout << "Delete Detected" << std::endl;
}
}
//Shutdown the application
void shutdown()
{
//Delete objects off the heap
delete http;
}
//Catch a Signal (for example, keyboard interrupt)
void my_signal_handler(int s){
std::cout << ("Caught signal") << std::endl;
std::string signal_type = std::to_string(s);
std::cout << (signal_type) << std::endl;
shutdown();
exit(1);
}
int main()
{
//Set up a handler for any signal events so that we always shutdown gracefully
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = my_signal_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
//Set up the HTTP Server
HttpServer http;
http.bind_callback("0.0.0.0", 12345, process_request);
//Listen for Requests
http.recv();
return 0;
}
<commit_msg>HTTP Server fixes<commit_after>#include "include/http_server.h"
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <stdlib.h>
#include <unistd.h>
#include <exception>
#include <signal.h>
#include <evhttp.h>
void process_get_request(struct evhttp_request *req, void *arg)
{
struct evbuffer *buf = evbuffer_new();
if (buf == NULL) return;
evbuffer_add_printf(buf, "Get Request", evhttp_request_uri(req));
evhttp_send_reply(req, HTTP_OK, "OK", buf);
}
void process_post_request(struct evhttp_request *req, void *arg)
{
struct evbuffer *buf = evbuffer_new();
if (!buf == NULL)
{
evbuffer_add_printf(buf, "Post Request", evhttp_request_uri(req));
evhttp_send_reply(req, HTTP_OK, "OK", buf);
}
}
//Process a request
void process_request(struct evhttp_request *req, void *arg){
std::cout << req->type << std::endl;
if (req->type == 1)
{
process_get_request(req, arg);
}
else if (req->type == 2)
{
process_post_request(req, arg);
}
else if (req->type == 8)
{
std::cout << "Put Detected" << std::endl;
}
else if (req->type == 16)
{
std::cout << "Delete Detected" << std::endl;
}
}
//Shutdown the application
// void shutdown()
// {
//
// }
//Catch a Signal (for example, keyboard interrupt)
void my_signal_handler(int s){
std::cout << ("Caught signal") << std::endl;
std::string signal_type = std::to_string(s);
std::cout << (signal_type) << std::endl;
//shutdown();
exit(1);
}
int main()
{
//Set up a handler for any signal events so that we always shutdown gracefully
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = my_signal_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
//Set up the HTTP Server
HttpServer http;
http.bind_callback("0.0.0.0", 12345, process_request);
//Listen for Requests
http.recv();
return 0;
}
<|endoftext|> |
<commit_before>#include "banklistsqlmodel.h"
#include "townlistsqlmodel.h"
#include "cashpointsqlmodel.h"
#include "serverapi.h"
#include "icoimageprovider.h"
#include "locationservice.h"
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QFile>
#include <QDebug>
#include <QtCore/QSettings>
#include <QtCore/QStandardPaths>
QStringList getSqlQuery(const QString &queryFileName)
{
QFile queryFile(queryFileName);
if (!queryFile.open(QFile::ReadOnly | QFile::Text))
{
QTextStream(stderr) << "Cannot open " << queryFileName << " file" << endl;
return QStringList();
}
QString queryStr = queryFile.readAll();
return queryStr.split(";", QString::SkipEmptyParts);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents, false);
app.setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, false);
app.setOrganizationName("Agnia");
app.setApplicationName("CashPoints");
const QString path =
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
#else
QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
#endif
QSettings settings(path, QSettings::NativeFormat);
// bank list db
const QString banksConnName = "banks";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", banksConnName);
db.setDatabaseName(":memory:");
if (!db.open())
{
qFatal("Cannot create inmem database. Abort.");
return 1;
}
db.transaction();
db.exec("CREATE TABLE banks (id integer primary key, name text, licence integer, "
"name_tr text, town text, rating integer, "
"name_tr_alt text, tel text, ico_path text, mine integer)");
db.exec("CREATE TABLE towns (id integer primary key, name text, name_tr text, "
"region_id integer, regional_center integer, mine integer)");
db.exec("CREATE TABLE regions (id integer primary key, name text)");
db.exec("CREATE TABLE cp (id integer primary key, type text, bank_id integer, "
"town_id integer, cord_lon real, cord_lat real, address text, "
"address_comment text, metro_name text, main_office integer, "
"without_weekend integer, round_the_clock integer, "
"works_as_shop integer, rub integer, usd integer, "
"eur integer, cash_in integer)");
db.commit();
qRegisterMetaType<ServerApiPtr>("ServerApiPtr");
ServerApi *api = new ServerApi("localhost", 8080);
const QStringList icons = {
":/icon/star.svg",
":/icon/star_gray.svg",
":/icon/aim.svg",
":/icon/zoom_in.svg",
":/icon/zoom_out.svg",
":/icon/marker.svg"
};
IcoImageProvider *imageProvider = new IcoImageProvider;
for (const QString &icoPath : icons) {
QFile file(icoPath);
if (file.open(QIODevice::ReadOnly)) {
QString resName = icoPath.split('/').last();
imageProvider->loadSvgImage(resName, file.readAll());
qDebug() << icoPath << "loaded as" << resName;
}
}
BankListSqlModel *bankListModel =
new BankListSqlModel(banksConnName, api, imageProvider, &settings);
TownListSqlModel *townListModel =
new TownListSqlModel(banksConnName, api, imageProvider, &settings);
CashPointSqlModel *cashpointModel =
new CashPointSqlModel(banksConnName, api, imageProvider, &settings);
LocationService *locationService = new LocationService(&app);
QQmlApplicationEngine engine;
engine.addImportPath("qrc:/ui");
engine.addImageProvider(QLatin1String("ico"), imageProvider);
engine.rootContext()->setContextProperty("bankListModel", bankListModel);
engine.rootContext()->setContextProperty("townListModel", townListModel);
engine.rootContext()->setContextProperty("cashpointModel", cashpointModel);
engine.rootContext()->setContextProperty("serverApi", api);
engine.rootContext()->setContextProperty("locationService", locationService);
engine.load(QUrl(QStringLiteral("qrc:/ui/main.qml")));
QObject *appWindow = nullptr;
for (QObject *obj : engine.rootObjects()) {
if (obj->objectName() == "appWindow") {
appWindow = obj;
break;
}
}
Q_ASSERT(appWindow);
QObject::connect(api, SIGNAL(pong(bool)), appWindow, SIGNAL(pong(bool)));
/// update bank and town list after successfull ping
QMetaObject::Connection connection = QObject::connect(api, &ServerApi::pong,
[&](bool ok) {
static int attempts = 0;
attempts++;
if (ok) {
qDebug() << "Connected to server";
QObject::disconnect(connection);
bankListModel->updateFromServer();
townListModel->updateFromServer();
} else {
if (attempts > 3) {
return;
}
api->ping();
}
});
api->ping();
const int exitStatus = app.exec();
delete cashpointModel;
delete townListModel;
delete bankListModel;
delete api;
db.close();
return exitStatus;
}
<commit_msg>[C|Client] Fix crash in QQmlApplicationEngine destructor on app exit<commit_after>#include "banklistsqlmodel.h"
#include "townlistsqlmodel.h"
#include "cashpointsqlmodel.h"
#include "serverapi.h"
#include "icoimageprovider.h"
#include "locationservice.h"
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QFile>
#include <QDebug>
#include <QtCore/QSettings>
#include <QtCore/QStandardPaths>
QStringList getSqlQuery(const QString &queryFileName)
{
QFile queryFile(queryFileName);
if (!queryFile.open(QFile::ReadOnly | QFile::Text))
{
QTextStream(stderr) << "Cannot open " << queryFileName << " file" << endl;
return QStringList();
}
QString queryStr = queryFile.readAll();
return queryStr.split(";", QString::SkipEmptyParts);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setAttribute(Qt::AA_SynthesizeMouseForUnhandledTouchEvents, false);
app.setAttribute(Qt::AA_SynthesizeTouchForUnhandledMouseEvents, false);
app.setOrganizationName("Agnia");
app.setApplicationName("CashPoints");
const QString path =
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
#else
QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
#endif
QSettings settings(path, QSettings::NativeFormat);
// bank list db
const QString banksConnName = "banks";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", banksConnName);
db.setDatabaseName(":memory:");
if (!db.open())
{
qFatal("Cannot create inmem database. Abort.");
return 1;
}
db.transaction();
db.exec("CREATE TABLE banks (id integer primary key, name text, licence integer, "
"name_tr text, town text, rating integer, "
"name_tr_alt text, tel text, ico_path text, mine integer)");
db.exec("CREATE TABLE towns (id integer primary key, name text, name_tr text, "
"region_id integer, regional_center integer, mine integer)");
db.exec("CREATE TABLE regions (id integer primary key, name text)");
db.exec("CREATE TABLE cp (id integer primary key, type text, bank_id integer, "
"town_id integer, cord_lon real, cord_lat real, address text, "
"address_comment text, metro_name text, main_office integer, "
"without_weekend integer, round_the_clock integer, "
"works_as_shop integer, rub integer, usd integer, "
"eur integer, cash_in integer)");
db.commit();
qRegisterMetaType<ServerApiPtr>("ServerApiPtr");
ServerApi *api = new ServerApi("localhost", 8080);
const QStringList icons = {
":/icon/star.svg",
":/icon/star_gray.svg",
":/icon/aim.svg",
":/icon/zoom_in.svg",
":/icon/zoom_out.svg",
":/icon/marker.svg"
};
IcoImageProvider *imageProvider = new IcoImageProvider;
for (const QString &icoPath : icons) {
QFile file(icoPath);
if (file.open(QIODevice::ReadOnly)) {
QString resName = icoPath.split('/').last();
imageProvider->loadSvgImage(resName, file.readAll());
qDebug() << icoPath << "loaded as" << resName;
}
}
BankListSqlModel *bankListModel =
new BankListSqlModel(banksConnName, api, imageProvider, &settings);
TownListSqlModel *townListModel =
new TownListSqlModel(banksConnName, api, imageProvider, &settings);
CashPointSqlModel *cashpointModel =
new CashPointSqlModel(banksConnName, api, imageProvider, &settings);
LocationService *locationService = new LocationService(&app);
QQmlApplicationEngine *engine = new QQmlApplicationEngine;
engine->addImportPath("qrc:/ui");
engine->addImageProvider(QLatin1String("ico"), imageProvider);
engine->rootContext()->setContextProperty("bankListModel", bankListModel);
engine->rootContext()->setContextProperty("townListModel", townListModel);
engine->rootContext()->setContextProperty("cashpointModel", cashpointModel);
engine->rootContext()->setContextProperty("serverApi", api);
engine->rootContext()->setContextProperty("locationService", locationService);
engine->load(QUrl(QStringLiteral("qrc:/ui/main.qml")));
QObject *appWindow = nullptr;
for (QObject *obj : engine->rootObjects()) {
if (obj->objectName() == "appWindow") {
appWindow = obj;
break;
}
}
Q_ASSERT(appWindow);
QObject::connect(api, SIGNAL(pong(bool)), appWindow, SIGNAL(pong(bool)));
/// update bank and town list after successfull ping
QMetaObject::Connection connection = QObject::connect(api, &ServerApi::pong,
[&](bool ok) {
static int attempts = 0;
attempts++;
if (ok) {
qDebug() << "Connected to server";
QObject::disconnect(connection);
bankListModel->updateFromServer();
townListModel->updateFromServer();
} else {
if (attempts > 3) {
return;
}
api->ping();
}
});
api->ping();
const int exitStatus = app.exec();
delete engine;
delete cashpointModel;
delete townListModel;
delete bankListModel;
delete api;
db.close();
return exitStatus;
}
<|endoftext|> |
<commit_before>//=-- lsan_thread.cc ------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of LeakSanitizer.
// See lsan_thread.h for details.
//
//===----------------------------------------------------------------------===//
#include "lsan_thread.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_placement_new.h"
#include "sanitizer_common/sanitizer_thread_registry.h"
#include "sanitizer_common/sanitizer_tls_get_addr.h"
#include "lsan_allocator.h"
namespace __lsan {
const u32 kInvalidTid = (u32) -1;
static ThreadRegistry *thread_registry;
static THREADLOCAL u32 current_thread_tid = kInvalidTid;
static ThreadContextBase *CreateThreadContext(u32 tid) {
void *mem = MmapOrDie(sizeof(ThreadContext), "ThreadContext");
return new(mem) ThreadContext(tid);
}
static const uptr kMaxThreads = 1 << 13;
static const uptr kThreadQuarantineSize = 64;
void InitializeThreadRegistry() {
static char thread_registry_placeholder[sizeof(ThreadRegistry)] ALIGNED(64);
thread_registry = new(thread_registry_placeholder)
ThreadRegistry(CreateThreadContext, kMaxThreads, kThreadQuarantineSize);
}
u32 GetCurrentThread() {
return current_thread_tid;
}
void SetCurrentThread(u32 tid) {
current_thread_tid = tid;
}
ThreadContext::ThreadContext(int tid)
: ThreadContextBase(tid),
stack_begin_(0),
stack_end_(0),
cache_begin_(0),
cache_end_(0),
tls_begin_(0),
tls_end_(0),
dtls_(nullptr) {}
struct OnStartedArgs {
uptr stack_begin, stack_end,
cache_begin, cache_end,
tls_begin, tls_end;
DTLS *dtls;
};
void ThreadContext::OnStarted(void *arg) {
OnStartedArgs *args = reinterpret_cast<OnStartedArgs *>(arg);
stack_begin_ = args->stack_begin;
stack_end_ = args->stack_end;
tls_begin_ = args->tls_begin;
tls_end_ = args->tls_end;
cache_begin_ = args->cache_begin;
cache_end_ = args->cache_end;
dtls_ = args->dtls;
}
void ThreadContext::OnFinished() {
AllocatorThreadFinish();
DTLS_Destroy();
}
u32 ThreadCreate(u32 parent_tid, uptr user_id, bool detached) {
return thread_registry->CreateThread(user_id, detached, parent_tid,
/* arg */ nullptr);
}
void ThreadStart(u32 tid, uptr os_id) {
OnStartedArgs args;
uptr stack_size = 0;
uptr tls_size = 0;
GetThreadStackAndTls(tid == 0, &args.stack_begin, &stack_size,
&args.tls_begin, &tls_size);
args.stack_end = args.stack_begin + stack_size;
args.tls_end = args.tls_begin + tls_size;
GetAllocatorCacheRange(&args.cache_begin, &args.cache_end);
args.dtls = DTLS_Get();
thread_registry->StartThread(tid, os_id, &args);
}
void ThreadFinish() {
thread_registry->FinishThread(GetCurrentThread());
}
ThreadContext *CurrentThreadContext() {
if (!thread_registry) return nullptr;
if (GetCurrentThread() == kInvalidTid)
return nullptr;
// No lock needed when getting current thread.
return (ThreadContext *)thread_registry->GetThreadLocked(GetCurrentThread());
}
static bool FindThreadByUid(ThreadContextBase *tctx, void *arg) {
uptr uid = (uptr)arg;
if (tctx->user_id == uid && tctx->status != ThreadStatusInvalid) {
return true;
}
return false;
}
u32 ThreadTid(uptr uid) {
return thread_registry->FindThread(FindThreadByUid, (void*)uid);
}
void ThreadJoin(u32 tid) {
CHECK_NE(tid, kInvalidTid);
thread_registry->JoinThread(tid, /* arg */nullptr);
}
void EnsureMainThreadIDIsCorrect() {
if (GetCurrentThread() == 0)
CurrentThreadContext()->os_id = GetTid();
}
///// Interface to the common LSan module. /////
bool GetThreadRangesLocked(uptr os_id, uptr *stack_begin, uptr *stack_end,
uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
uptr *cache_end, DTLS **dtls) {
ThreadContext *context = static_cast<ThreadContext *>(
thread_registry->FindThreadContextByOsIDLocked(os_id));
if (!context) return false;
*stack_begin = context->stack_begin();
*stack_end = context->stack_end();
*tls_begin = context->tls_begin();
*tls_end = context->tls_end();
*cache_begin = context->cache_begin();
*cache_end = context->cache_end();
*dtls = context->dtls();
return true;
}
void ForEachExtraStackRange(uptr os_id, RangeIteratorCallback callback,
void *arg) {
}
void LockThreadRegistry() {
thread_registry->Lock();
}
void UnlockThreadRegistry() {
thread_registry->Unlock();
}
} // namespace __lsan
<commit_msg>[compiler-rt][lsan] Fix compiler error due to attribute (windows)<commit_after>//=-- lsan_thread.cc ------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of LeakSanitizer.
// See lsan_thread.h for details.
//
//===----------------------------------------------------------------------===//
#include "lsan_thread.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_placement_new.h"
#include "sanitizer_common/sanitizer_thread_registry.h"
#include "sanitizer_common/sanitizer_tls_get_addr.h"
#include "lsan_allocator.h"
namespace __lsan {
const u32 kInvalidTid = (u32) -1;
static ThreadRegistry *thread_registry;
static THREADLOCAL u32 current_thread_tid = kInvalidTid;
static ThreadContextBase *CreateThreadContext(u32 tid) {
void *mem = MmapOrDie(sizeof(ThreadContext), "ThreadContext");
return new(mem) ThreadContext(tid);
}
static const uptr kMaxThreads = 1 << 13;
static const uptr kThreadQuarantineSize = 64;
void InitializeThreadRegistry() {
static ALIGNED(64) char thread_registry_placeholder[sizeof(ThreadRegistry)];
thread_registry = new(thread_registry_placeholder)
ThreadRegistry(CreateThreadContext, kMaxThreads, kThreadQuarantineSize);
}
u32 GetCurrentThread() {
return current_thread_tid;
}
void SetCurrentThread(u32 tid) {
current_thread_tid = tid;
}
ThreadContext::ThreadContext(int tid)
: ThreadContextBase(tid),
stack_begin_(0),
stack_end_(0),
cache_begin_(0),
cache_end_(0),
tls_begin_(0),
tls_end_(0),
dtls_(nullptr) {}
struct OnStartedArgs {
uptr stack_begin, stack_end,
cache_begin, cache_end,
tls_begin, tls_end;
DTLS *dtls;
};
void ThreadContext::OnStarted(void *arg) {
OnStartedArgs *args = reinterpret_cast<OnStartedArgs *>(arg);
stack_begin_ = args->stack_begin;
stack_end_ = args->stack_end;
tls_begin_ = args->tls_begin;
tls_end_ = args->tls_end;
cache_begin_ = args->cache_begin;
cache_end_ = args->cache_end;
dtls_ = args->dtls;
}
void ThreadContext::OnFinished() {
AllocatorThreadFinish();
DTLS_Destroy();
}
u32 ThreadCreate(u32 parent_tid, uptr user_id, bool detached) {
return thread_registry->CreateThread(user_id, detached, parent_tid,
/* arg */ nullptr);
}
void ThreadStart(u32 tid, uptr os_id) {
OnStartedArgs args;
uptr stack_size = 0;
uptr tls_size = 0;
GetThreadStackAndTls(tid == 0, &args.stack_begin, &stack_size,
&args.tls_begin, &tls_size);
args.stack_end = args.stack_begin + stack_size;
args.tls_end = args.tls_begin + tls_size;
GetAllocatorCacheRange(&args.cache_begin, &args.cache_end);
args.dtls = DTLS_Get();
thread_registry->StartThread(tid, os_id, &args);
}
void ThreadFinish() {
thread_registry->FinishThread(GetCurrentThread());
}
ThreadContext *CurrentThreadContext() {
if (!thread_registry) return nullptr;
if (GetCurrentThread() == kInvalidTid)
return nullptr;
// No lock needed when getting current thread.
return (ThreadContext *)thread_registry->GetThreadLocked(GetCurrentThread());
}
static bool FindThreadByUid(ThreadContextBase *tctx, void *arg) {
uptr uid = (uptr)arg;
if (tctx->user_id == uid && tctx->status != ThreadStatusInvalid) {
return true;
}
return false;
}
u32 ThreadTid(uptr uid) {
return thread_registry->FindThread(FindThreadByUid, (void*)uid);
}
void ThreadJoin(u32 tid) {
CHECK_NE(tid, kInvalidTid);
thread_registry->JoinThread(tid, /* arg */nullptr);
}
void EnsureMainThreadIDIsCorrect() {
if (GetCurrentThread() == 0)
CurrentThreadContext()->os_id = GetTid();
}
///// Interface to the common LSan module. /////
bool GetThreadRangesLocked(uptr os_id, uptr *stack_begin, uptr *stack_end,
uptr *tls_begin, uptr *tls_end, uptr *cache_begin,
uptr *cache_end, DTLS **dtls) {
ThreadContext *context = static_cast<ThreadContext *>(
thread_registry->FindThreadContextByOsIDLocked(os_id));
if (!context) return false;
*stack_begin = context->stack_begin();
*stack_end = context->stack_end();
*tls_begin = context->tls_begin();
*tls_end = context->tls_end();
*cache_begin = context->cache_begin();
*cache_end = context->cache_end();
*dtls = context->dtls();
return true;
}
void ForEachExtraStackRange(uptr os_id, RangeIteratorCallback callback,
void *arg) {
}
void LockThreadRegistry() {
thread_registry->Lock();
}
void UnlockThreadRegistry() {
thread_registry->Unlock();
}
} // namespace __lsan
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2015.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include "config.hpp"
void print_usage(){
std::cout << "Usage: spotter [options] <command> file [file...]" << std::endl;
std::cout << "Supported commands: " << std::endl;
std::cout << " * train" << std::endl;
std::cout << "Supported options: " << std::endl;
std::cout << " -1 : Method 1" << std::endl;
std::cout << " -2 : Method 2" << std::endl;
std::cout << " -half : Takes half resolution images only" << std::endl;
std::cout << " -quarter : Takes quarter resolution images only" << std::endl;
std::cout << " -third : Takes third resolution images only" << std::endl;
std::cout << " -svm : Use a SVM" << std::endl;
std::cout << " -view : Load the DBN and visualize its weights" << std::endl;
std::cout << " -sub : Takes only a subset of the dataset to train" << std::endl;
}
config parse_args(int argc, char** argv){
config conf;
for(std::size_t i = 1; i < static_cast<size_t>(argc); ++i){
conf.args.emplace_back(argv[i]);
}
std::size_t i = 0;
for(; i < conf.args.size(); ++i){
if(conf.args[i] == "-0"){
conf.method_0 = true;
} else if(conf.args[i] == "-1"){
conf.method_1 = true;
} else if(conf.args[i] == "-2"){
conf.method_2 = true;
} else if(conf.args[i] == "-half"){
conf.half = true;
} else if(conf.args[i] == "-quarter"){
conf.quarter = true;
} else if(conf.args[i] == "-third"){
conf.third = true;
} else if(conf.args[i] == "-svm"){
conf.svm = true;
} else if(conf.args[i] == "-view"){
conf.view = true;
} else if(conf.args[i] == "-sub"){
conf.sub = true;
} else if(conf.args[i] == "-all"){
conf.all = true;
} else if(conf.args[i] == "-washington"){
conf.washington = true;
} else if(conf.args[i] == "-parzival"){
conf.washington = true;
} else {
break;
}
}
conf.command = conf.args[i++];
for(; i < conf.args.size(); ++i){
conf.files.push_back(conf.args[i]);
}
return conf;
}
<commit_msg>Cleanup<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2015.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include "config.hpp"
void print_usage(){
std::cout << "Usage: spotter [options] <command> file [file...]" << std::endl;
std::cout << "Supported commands: " << std::endl;
std::cout << " * train" << std::endl;
std::cout << "Supported options: " << std::endl;
std::cout << " -1 : Method 1" << std::endl;
std::cout << " -2 : Method 2" << std::endl;
std::cout << " -half : Takes half resolution images only" << std::endl;
std::cout << " -quarter : Takes quarter resolution images only" << std::endl;
std::cout << " -third : Takes third resolution images only" << std::endl;
std::cout << " -svm : Use a SVM" << std::endl;
std::cout << " -view : Load the DBN and visualize its weights" << std::endl;
std::cout << " -sub : Takes only a subset of the dataset to train" << std::endl;
}
config parse_args(int argc, char** argv){
config conf;
for(std::size_t i = 1; i < static_cast<size_t>(argc); ++i){
conf.args.emplace_back(argv[i]);
}
std::size_t i = 0;
for(; i < conf.args.size(); ++i){
if(conf.args[i] == "-0"){
conf.method_0 = true;
} else if(conf.args[i] == "-1"){
conf.method_1 = true;
} else if(conf.args[i] == "-2"){
conf.method_2 = true;
} else if(conf.args[i] == "-full"){
//Simply here for consistency sake
} else if(conf.args[i] == "-half"){
conf.half = true;
} else if(conf.args[i] == "-quarter"){
conf.quarter = true;
} else if(conf.args[i] == "-third"){
conf.third = true;
} else if(conf.args[i] == "-svm"){
conf.svm = true;
} else if(conf.args[i] == "-view"){
conf.view = true;
} else if(conf.args[i] == "-sub"){
conf.sub = true;
} else if(conf.args[i] == "-all"){
conf.all = true;
} else if(conf.args[i] == "-washington"){
conf.washington = true;
conf.parzival = false;
} else if(conf.args[i] == "-parzival"){
conf.washington = false;
conf.parzival = true;
} else {
break;
}
}
conf.command = conf.args[i++];
for(; i < conf.args.size(); ++i){
conf.files.push_back(conf.args[i]);
}
return conf;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qfont.h"
#include "qfont_p.h"
#include "qfontengine_p.h"
#include "qtextengine_p.h"
#include "qfontmetrics.h"
#include "qfontinfo.h"
#include "qwidget.h"
#include "qpainter.h"
#include <limits.h>
#include "qt_windows.h"
#include <private/qapplication_p.h>
#include "qapplication.h"
#include <private/qunicodetables_p.h>
#include <qfontdatabase.h>
QT_BEGIN_NAMESPACE
extern HDC shared_dc(); // common dc for all fonts
extern QFont::Weight weightFromInteger(int weight); // qfontdatabase.cpp
// ### maybe move to qapplication_win
QFont qt_LOGFONTtoQFont(LOGFONT& lf, bool /*scale*/)
{
QString family = QString::fromWCharArray(lf.lfFaceName);
QFont qf(family);
qf.setItalic(lf.lfItalic);
if (lf.lfWeight != FW_DONTCARE)
qf.setWeight(weightFromInteger(lf.lfWeight));
int lfh = qAbs(lf.lfHeight);
qf.setPointSizeF(lfh * 72.0 / GetDeviceCaps(shared_dc(),LOGPIXELSY));
qf.setUnderline(false);
qf.setOverline(false);
qf.setStrikeOut(false);
return qf;
}
static inline float pixelSize(const QFontDef &request, int dpi)
{
float pSize;
if (request.pointSize != -1)
pSize = request.pointSize * dpi/ 72.;
else
pSize = request.pixelSize;
return pSize;
}
static inline float pointSize(const QFontDef &fd, int dpi)
{
float pSize;
if (fd.pointSize < 0)
pSize = fd.pixelSize * 72. / ((float)dpi);
else
pSize = fd.pointSize;
return pSize;
}
/*****************************************************************************
QFont member functions
*****************************************************************************/
void QFont::initialize()
{
}
void QFont::cleanup()
{
QFontCache::cleanup();
}
HFONT QFont::handle() const
{
QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
Q_ASSERT(engine != 0);
if (engine->type() == QFontEngine::Multi)
engine = static_cast<QFontEngineMulti *>(engine)->engine(0);
if (engine->type() == QFontEngine::Win)
return static_cast<QFontEngineWin *>(engine)->hfont;
return 0;
}
QString QFont::rawName() const
{
return family();
}
void QFont::setRawName(const QString &name)
{
setFamily(name);
}
QString QFont::defaultFamily() const
{
switch(d->request.styleHint) {
case QFont::Times:
return QString::fromLatin1("Times New Roman");
case QFont::Courier:
case QFont::Monospace:
return QString::fromLatin1("Courier New");
case QFont::Decorative:
return QString::fromLatin1("Bookman Old Style");
case QFont::Cursive:
return QString::fromLatin1("Comic Sans MS");
case QFont::Fantasy:
return QString::fromLatin1("Impact");
case QFont::Helvetica:
return QString::fromLatin1("Arial");
case QFont::System:
default:
return QString::fromLatin1("MS Sans Serif");
}
}
QString QFont::lastResortFamily() const
{
return QString::fromLatin1("helvetica");
}
QString QFont::lastResortFont() const
{
return QString::fromLatin1("arial");
}
QT_END_NAMESPACE
<commit_msg>Fix#10893: Use system font in UI.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qfont.h"
#include "qfont_p.h"
#include "qfontengine_p.h"
#include "qtextengine_p.h"
#include "qfontmetrics.h"
#include "qfontinfo.h"
#include "qwidget.h"
#include "qpainter.h"
#include <limits.h>
#include "qt_windows.h"
#include <private/qapplication_p.h>
#include "qapplication.h"
#include <private/qunicodetables_p.h>
#include <qfontdatabase.h>
#include <windows.h>
QT_BEGIN_NAMESPACE
extern HDC shared_dc(); // common dc for all fonts
extern QFont::Weight weightFromInteger(int weight); // qfontdatabase.cpp
// ### maybe move to qapplication_win
QFont qt_LOGFONTtoQFont(LOGFONT& lf, bool /*scale*/)
{
QString family = QString::fromWCharArray(lf.lfFaceName);
#ifdef QT_ENABLE_FREETYPE_FOR_WIN
// Substitute font by myself.
// Windows return font family name which should be substituted from SystemParametersInfo().
// If we use GDI's font engine, Windows substitute font family.
// If we use FreeType, FreeType don't do that, and we need to substitute font by myself.
//std::cout << "family: " << family.toUtf8().data() << std::endl;
{
HKEY key;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes"), 0, KEY_READ, &key) == ERROR_SUCCESS) {
int i = 0;
TCHAR buff[MAX_PATH];
DWORD size = sizeof(buff) / sizeof(buff[0]);
BYTE data[1024*4];
DWORD dataSize = sizeof(data)/sizeof(data[0]);
DWORD type;
while (RegEnumValue(key, i++, buff, &size, NULL, &type, data, &dataSize) == ERROR_SUCCESS) {
QString subFamily = QString::fromWCharArray(buff);
if (family.compare(subFamily) == 0) {
if (type == REG_SZ)
family = QString::fromWCharArray((WCHAR *)data);
break;
}
size = sizeof(buff) / sizeof(buff[0]);
dataSize = sizeof(data)/sizeof(data[0]);
}
}
}
//std::cout << "use family: " << family.toUtf8().data() << std::endl;
#endif
QFont qf(family);
qf.setItalic(lf.lfItalic);
if (lf.lfWeight != FW_DONTCARE)
qf.setWeight(weightFromInteger(lf.lfWeight));
int lfh = qAbs(lf.lfHeight);
qf.setPointSizeF(lfh * 72.0 / GetDeviceCaps(shared_dc(),LOGPIXELSY));
qf.setUnderline(false);
qf.setOverline(false);
qf.setStrikeOut(false);
return qf;
}
static inline float pixelSize(const QFontDef &request, int dpi)
{
float pSize;
if (request.pointSize != -1)
pSize = request.pointSize * dpi/ 72.;
else
pSize = request.pixelSize;
return pSize;
}
static inline float pointSize(const QFontDef &fd, int dpi)
{
float pSize;
if (fd.pointSize < 0)
pSize = fd.pixelSize * 72. / ((float)dpi);
else
pSize = fd.pointSize;
return pSize;
}
/*****************************************************************************
QFont member functions
*****************************************************************************/
void QFont::initialize()
{
}
void QFont::cleanup()
{
QFontCache::cleanup();
}
HFONT QFont::handle() const
{
QFontEngine *engine = d->engineForScript(QUnicodeTables::Common);
Q_ASSERT(engine != 0);
if (engine->type() == QFontEngine::Multi)
engine = static_cast<QFontEngineMulti *>(engine)->engine(0);
if (engine->type() == QFontEngine::Win)
return static_cast<QFontEngineWin *>(engine)->hfont;
return 0;
}
QString QFont::rawName() const
{
return family();
}
void QFont::setRawName(const QString &name)
{
setFamily(name);
}
QString QFont::defaultFamily() const
{
switch(d->request.styleHint) {
case QFont::Times:
return QString::fromLatin1("Times New Roman");
case QFont::Courier:
case QFont::Monospace:
return QString::fromLatin1("Courier New");
case QFont::Decorative:
return QString::fromLatin1("Bookman Old Style");
case QFont::Cursive:
return QString::fromLatin1("Comic Sans MS");
case QFont::Fantasy:
return QString::fromLatin1("Impact");
case QFont::Helvetica:
return QString::fromLatin1("Arial");
case QFont::System:
default:
return QString::fromLatin1("MS Sans Serif");
}
}
QString QFont::lastResortFamily() const
{
return QString::fromLatin1("helvetica");
}
QString QFont::lastResortFont() const
{
return QString::fromLatin1("arial");
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>#include <cassert>
#include <stdexcept>
#include "pn/net.hh"
#include "pn/place.hh"
#include "pn/transition.hh"
namespace pnmc { namespace pn {
/*------------------------------------------------------------------------------------------------*/
/// @brief Used by Boost.MultiIndex.
struct add_post_place_to_transition
{
const unsigned int new_valuation;
const std::string new_place_id;
add_post_place_to_transition(unsigned int valuation, const std::string& id)
: new_valuation(valuation), new_place_id(id)
{}
void
operator()(transition& t)
const
{
t.post.insert(std::make_pair(new_place_id , new_valuation));
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Used by Boost.MultiIndex.
struct add_pre_place_to_transition
{
const unsigned int new_valuation;
const std::string new_place_id;
add_pre_place_to_transition(unsigned int valuation, const std::string& id)
: new_valuation(valuation), new_place_id(id)
{}
void
operator()(transition& t)
const
{
t.pre.insert(std::make_pair(new_place_id, new_valuation));
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Used by Boost.MultiIndex.
struct update_place
{
const unsigned int marking;
update_place(unsigned int m)
: marking(m)
{}
void
operator()(place& p)
const
{
p.marking = marking;
}
};
/*------------------------------------------------------------------------------------------------*/
net::net()
: name(), places_set(), transitions_set(), modules(nullptr)
{}
/*------------------------------------------------------------------------------------------------*/
const place&
net::add_place(const std::string& pid, unsigned int marking)
{
const auto cit = places_set.get<id_index>().find(pid);
if (cit == places_set.get<id_index>().cend())
{
return *places_set.insert({pid, marking}).first;
}
else
{
// This place was created before by add_post_place() or add_pre_place().
// At this time, the marking was not known. Thus, we now update it.
// The assert() is here because modify() would return false if the place could not have been
// modified (when bmi sees a conflict on unique keys). Which is impossible here, because
// the marking is not a unique key.
assert(places_set.modify(cit, update_place(marking)));
return *cit;
}
}
/*------------------------------------------------------------------------------------------------*/
const transition&
net::add_transition(const std::string& tid, const std::string& label)
{
static std::size_t transition_index = 0;
const auto insertion = transitions_set.insert({tid, label, transition_index++});
if (not insertion.second)
{
throw std::runtime_error("Transition " + tid + " already exists");
}
return *insertion.first;
}
/*------------------------------------------------------------------------------------------------*/
void
net::add_post_place(const std::string& tid, const std::string& post, unsigned int valuation)
{
const auto it = transitions_set.get<id_index>().find(tid);
transitions_set.modify(it, add_post_place_to_transition(valuation, post));
if (places().find(post) == places().end())
{
add_place(post, 0);
}
}
/*------------------------------------------------------------------------------------------------*/
void
net::add_pre_place(const std::string& tid, const std::string& pre, unsigned int valuation)
{
const auto it = transitions_set.get<id_index>().find(tid);
transitions_set.modify(it, add_pre_place_to_transition(valuation, pre));
if (places().find(pre) == places().end())
{
add_place(pre, 0);
}
}
/*------------------------------------------------------------------------------------------------*/
const net::places_type::index<net::id_index>::type&
net::places()
const noexcept
{
return places_set.get<id_index>();
}
/*------------------------------------------------------------------------------------------------*/
const net::transitions_type::index<net::id_index>::type&
net::transitions()
const noexcept
{
return transitions_set.get<id_index>();
}
/*------------------------------------------------------------------------------------------------*/
const transition&
net::get_transition_by_index(std::size_t index)
const
{
return *transitions_set.get<index_index>().find(index);
}
/*------------------------------------------------------------------------------------------------*/
}} // namespace pnmc::pn
<commit_msg>Remove assert() that deactivated code in release mode (duh!).<commit_after>#include <cassert>
#include <stdexcept>
#include "pn/net.hh"
#include "pn/place.hh"
#include "pn/transition.hh"
namespace pnmc { namespace pn {
/*------------------------------------------------------------------------------------------------*/
/// @brief Used by Boost.MultiIndex.
struct add_post_place_to_transition
{
const unsigned int new_valuation;
const std::string new_place_id;
add_post_place_to_transition(unsigned int valuation, const std::string& id)
: new_valuation(valuation), new_place_id(id)
{}
void
operator()(transition& t)
const
{
t.post.insert(std::make_pair(new_place_id , new_valuation));
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Used by Boost.MultiIndex.
struct add_pre_place_to_transition
{
const unsigned int new_valuation;
const std::string new_place_id;
add_pre_place_to_transition(unsigned int valuation, const std::string& id)
: new_valuation(valuation), new_place_id(id)
{}
void
operator()(transition& t)
const
{
t.pre.insert(std::make_pair(new_place_id, new_valuation));
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Used by Boost.MultiIndex.
struct update_place
{
const unsigned int marking;
update_place(unsigned int m)
: marking(m)
{}
void
operator()(place& p)
const
{
p.marking = marking;
}
};
/*------------------------------------------------------------------------------------------------*/
net::net()
: name(), places_set(), transitions_set(), modules(nullptr)
{}
/*------------------------------------------------------------------------------------------------*/
const place&
net::add_place(const std::string& pid, unsigned int marking)
{
const auto cit = places_set.get<id_index>().find(pid);
if (cit == places_set.get<id_index>().cend())
{
return *places_set.insert({pid, marking}).first;
}
else
{
// This place was created before by add_post_place() or add_pre_place().
// At this time, the marking was not known. Thus, we now update it.
places_set.modify(cit, update_place(marking));
return *cit;
}
}
/*------------------------------------------------------------------------------------------------*/
const transition&
net::add_transition(const std::string& tid, const std::string& label)
{
static std::size_t transition_index = 0;
const auto insertion = transitions_set.insert({tid, label, transition_index++});
if (not insertion.second)
{
throw std::runtime_error("Transition " + tid + " already exists");
}
return *insertion.first;
}
/*------------------------------------------------------------------------------------------------*/
void
net::add_post_place(const std::string& tid, const std::string& post, unsigned int valuation)
{
const auto it = transitions_set.get<id_index>().find(tid);
transitions_set.modify(it, add_post_place_to_transition(valuation, post));
if (places().find(post) == places().end())
{
add_place(post, 0);
}
}
/*------------------------------------------------------------------------------------------------*/
void
net::add_pre_place(const std::string& tid, const std::string& pre, unsigned int valuation)
{
const auto it = transitions_set.get<id_index>().find(tid);
transitions_set.modify(it, add_pre_place_to_transition(valuation, pre));
if (places().find(pre) == places().end())
{
add_place(pre, 0);
}
}
/*------------------------------------------------------------------------------------------------*/
const net::places_type::index<net::id_index>::type&
net::places()
const noexcept
{
return places_set.get<id_index>();
}
/*------------------------------------------------------------------------------------------------*/
const net::transitions_type::index<net::id_index>::type&
net::transitions()
const noexcept
{
return transitions_set.get<id_index>();
}
/*------------------------------------------------------------------------------------------------*/
const transition&
net::get_transition_by_index(std::size_t index)
const
{
return *transitions_set.get<index_index>().find(index);
}
/*------------------------------------------------------------------------------------------------*/
}} // namespace pnmc::pn
<|endoftext|> |
<commit_before>#include "pn/net.hh"
#include "pn/place.hh"
#include "pn/transition.hh"
namespace pnmc { namespace pn {
/*------------------------------------------------------------------------------------------------*/
/// @brief Used by Boost.MultiIndex.
struct add_post_place_to_transition
{
const unsigned int new_valuation;
const unsigned int new_place_id;
add_post_place_to_transition(unsigned int valuation, unsigned int id)
: new_valuation(valuation), new_place_id(id)
{}
void
operator()(transition& t)
const
{
t.post.insert(std::make_pair(new_place_id , new_valuation));
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Used by Boost.MultiIndex.
struct add_pre_place_to_transition
{
const unsigned int new_valuation;
const unsigned int new_place_id;
add_pre_place_to_transition(unsigned int valuation, unsigned int id)
: new_valuation(valuation), new_place_id(id)
{}
void
operator()(transition& t)
const
{
t.pre.insert(std::make_pair(new_place_id, new_valuation));
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Used by Boost.MultiIndex.
struct update_place_helper
{
const unsigned int marking;
update_place_helper(unsigned int m)
: marking(m)
{}
void
operator()(place& p)
const
{
p.marking = marking;
}
};
/*------------------------------------------------------------------------------------------------*/
net::net()
: places_(), transitions_(), root_unit(), initial_place()
{}
/*------------------------------------------------------------------------------------------------*/
const place&
net::add_place(unsigned int pid, unsigned int marking, unsigned int unit)
{
assert(places_by_id().find(pid) == places_by_id().cend());
return *places_.get<insertion_index>().push_back({pid, marking, unit}).first;
}
/*------------------------------------------------------------------------------------------------*/
void
net::update_place(unsigned int id, unsigned int marking)
{
const auto cit = places_by_id().find(id);
assert(cit != places_by_id().cend());
places_.get<id_index>().modify(cit, update_place_helper(marking));
}
/*------------------------------------------------------------------------------------------------*/
const transition&
net::add_transition(unsigned int id)
{
const auto cit = transitions_.get<id_index>().find(id);
if (cit == transitions_.get<id_index>().cend())
{
return *transitions_.get<id_index>().insert(transition(id)).first;
}
else
{
return *cit;
}
}
/*------------------------------------------------------------------------------------------------*/
void
net::add_post_place(unsigned int id, unsigned int post, unsigned int valuation)
{
assert(places_by_id().find(post) != places_by_id().end());
const auto it = transitions_.get<id_index>().find(id);
transitions_.modify(it, add_post_place_to_transition(valuation, post));
}
/*------------------------------------------------------------------------------------------------*/
void
net::add_pre_place(unsigned int id, unsigned int pre, unsigned int valuation)
{
assert(places_by_id().find(pre) != places_by_id().end());
const auto it = transitions_.get<id_index>().find(id);
transitions_.modify(it, add_pre_place_to_transition(valuation, pre));
}
/*------------------------------------------------------------------------------------------------*/
const net::places_type::index<net::insertion_index>::type&
net::places()
const noexcept
{
return places_.get<insertion_index>();
}
/*------------------------------------------------------------------------------------------------*/
const net::places_type::index<net::id_index>::type&
net::places_by_id()
const noexcept
{
return places_.get<id_index>();
}
/*------------------------------------------------------------------------------------------------*/
std::vector<std::reference_wrapper<const place>>
net::places_of_unit(unsigned int i)
const
{
const auto p = places_.get<unit_index>().equal_range(i);
return std::vector<std::reference_wrapper<const place>>(p.first, p.second);
}
/*------------------------------------------------------------------------------------------------*/
unsigned int
net::unit_of_place(unsigned int place)
const
{
return places_.get<id_index>().find(place)->unit;
}
/*------------------------------------------------------------------------------------------------*/
std::size_t
net::units_size()
const noexcept
{
const auto& places = places_.get<unit_index>();
return places.empty() ? 0 : std::prev(places_.get<unit_index>().end())->unit + 1;
}
/*------------------------------------------------------------------------------------------------*/
const net::transitions_type::index<net::id_index>::type&
net::transitions()
const noexcept
{
return transitions_.get<id_index>();
}
/*------------------------------------------------------------------------------------------------*/
}} // namespace pnmc::pn
<commit_msg>Sort places of a unit by id.<commit_after>#include "pn/net.hh"
#include "pn/place.hh"
#include "pn/transition.hh"
namespace pnmc { namespace pn {
/*------------------------------------------------------------------------------------------------*/
/// @brief Used by Boost.MultiIndex.
struct add_post_place_to_transition
{
const unsigned int new_valuation;
const unsigned int new_place_id;
add_post_place_to_transition(unsigned int valuation, unsigned int id)
: new_valuation(valuation), new_place_id(id)
{}
void
operator()(transition& t)
const
{
t.post.insert(std::make_pair(new_place_id , new_valuation));
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Used by Boost.MultiIndex.
struct add_pre_place_to_transition
{
const unsigned int new_valuation;
const unsigned int new_place_id;
add_pre_place_to_transition(unsigned int valuation, unsigned int id)
: new_valuation(valuation), new_place_id(id)
{}
void
operator()(transition& t)
const
{
t.pre.insert(std::make_pair(new_place_id, new_valuation));
}
};
/*------------------------------------------------------------------------------------------------*/
/// @brief Used by Boost.MultiIndex.
struct update_place_helper
{
const unsigned int marking;
update_place_helper(unsigned int m)
: marking(m)
{}
void
operator()(place& p)
const
{
p.marking = marking;
}
};
/*------------------------------------------------------------------------------------------------*/
net::net()
: places_(), transitions_(), root_unit(), initial_place()
{}
/*------------------------------------------------------------------------------------------------*/
const place&
net::add_place(unsigned int pid, unsigned int marking, unsigned int unit)
{
assert(places_by_id().find(pid) == places_by_id().cend());
return *places_.get<insertion_index>().push_back({pid, marking, unit}).first;
}
/*------------------------------------------------------------------------------------------------*/
void
net::update_place(unsigned int id, unsigned int marking)
{
const auto cit = places_by_id().find(id);
assert(cit != places_by_id().cend());
places_.get<id_index>().modify(cit, update_place_helper(marking));
}
/*------------------------------------------------------------------------------------------------*/
const transition&
net::add_transition(unsigned int id)
{
const auto cit = transitions_.get<id_index>().find(id);
if (cit == transitions_.get<id_index>().cend())
{
return *transitions_.get<id_index>().insert(transition(id)).first;
}
else
{
return *cit;
}
}
/*------------------------------------------------------------------------------------------------*/
void
net::add_post_place(unsigned int id, unsigned int post, unsigned int valuation)
{
assert(places_by_id().find(post) != places_by_id().end());
const auto it = transitions_.get<id_index>().find(id);
transitions_.modify(it, add_post_place_to_transition(valuation, post));
}
/*------------------------------------------------------------------------------------------------*/
void
net::add_pre_place(unsigned int id, unsigned int pre, unsigned int valuation)
{
assert(places_by_id().find(pre) != places_by_id().end());
const auto it = transitions_.get<id_index>().find(id);
transitions_.modify(it, add_pre_place_to_transition(valuation, pre));
}
/*------------------------------------------------------------------------------------------------*/
const net::places_type::index<net::insertion_index>::type&
net::places()
const noexcept
{
return places_.get<insertion_index>();
}
/*------------------------------------------------------------------------------------------------*/
const net::places_type::index<net::id_index>::type&
net::places_by_id()
const noexcept
{
return places_.get<id_index>();
}
/*------------------------------------------------------------------------------------------------*/
std::vector<std::reference_wrapper<const place>>
net::places_of_unit(unsigned int i)
const
{
const auto p = places_.get<unit_index>().equal_range(i);
std::vector<std::reference_wrapper<const place>> res(p.first, p.second);
std::sort(res.begin(), res.end());
return res;
}
/*------------------------------------------------------------------------------------------------*/
unsigned int
net::unit_of_place(unsigned int place)
const
{
return places_.get<id_index>().find(place)->unit;
}
/*------------------------------------------------------------------------------------------------*/
std::size_t
net::units_size()
const noexcept
{
const auto& places = places_.get<unit_index>();
return places.empty() ? 0 : std::prev(places_.get<unit_index>().end())->unit + 1;
}
/*------------------------------------------------------------------------------------------------*/
const net::transitions_type::index<net::id_index>::type&
net::transitions()
const noexcept
{
return transitions_.get<id_index>();
}
/*------------------------------------------------------------------------------------------------*/
}} // namespace pnmc::pn
<|endoftext|> |
<commit_before>#include <iostream>
#include "prefs.h"
#include "logging.h"
#include "viewer_window.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
bool auto_reload_plugins;
bool impersonate_dre = false;
bool logging_enabled = true;
bool getAutoReloadPlugins() { return auto_reload_plugins; }
void setAutoReloadPlugins(bool reload_automatically) {
auto_reload_plugins = reload_automatically;
}
bool getLoggingEnabled() { return logging_enabled; }
bool getImpersonateDRE() { return impersonate_dre; }
void setImpersonateDRE(bool impersonate) { impersonate_dre = impersonate; }
const char * auto_reload_plugin_key = "auto_reload_plugins";
const char * impersonate_dre_key = "impersonate_dre";
const char * logging_enabled_key = "logging_enabled";
bool loadPrefs(const boost::filesystem::path & path) {
//open file, and deserialize
std::ifstream f(path.string());
if(f.fail()) {
std::cerr << "Couldn't open properties file: " << path.string() << std::endl;
return false;
}
boost::property_tree::ptree prefs;
read_json(f, prefs);
BOOST_FOREACH(boost::property_tree::ptree::value_type & window_detail_val, prefs.get_child("windows")) {
showViewerWindow(window_detail_val.second);
}
auto_reload_plugins = prefs.get<bool>(auto_reload_plugin_key, true);
impersonate_dre = prefs.get<bool>(impersonate_dre_key, false);
bool logging_enabled_loaded = prefs.get<bool>(logging_enabled_key, true);
if(false == logging_enabled_loaded) {
LOG("Logging disabled via prefs file");
}
LOG("Loaded prefs from " + path.string());
logging_enabled = logging_enabled_loaded;
return true;
}
bool savePrefs(const boost::filesystem::path & path) {
boost::property_tree::ptree prefs;
boost::property_tree::ptree windows = getViewerWindowsDetails();
prefs.put("author", "Lee C. Baker");
prefs.put("compile_date", __DATE__ " " __TIME__);
prefs.add_child("windows", windows);
prefs.put(auto_reload_plugin_key, auto_reload_plugins);
prefs.put(impersonate_dre_key, impersonate_dre);
prefs.put(logging_enabled_key, logging_enabled);
//serialize and save to file
std::ofstream f(path.string());
if(f.fail()) {
return false;
}
try {
write_json(f, prefs);
} catch(boost::property_tree::json_parser_error & e) {
LOG(std::string("Error writing preferences file at ") + path.string());
LOG(e.filename() + ":" + std::to_string(e.line()));
LOG(e.message());
return false;
}
return false == f.fail();
}<commit_msg>Fix crash when the preferences file isn't valid JSON.<commit_after>#include <iostream>
#include "prefs.h"
#include "logging.h"
#include "viewer_window.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
bool auto_reload_plugins;
bool impersonate_dre = false;
bool logging_enabled = true;
bool getAutoReloadPlugins() { return auto_reload_plugins; }
void setAutoReloadPlugins(bool reload_automatically) {
auto_reload_plugins = reload_automatically;
}
bool getLoggingEnabled() { return logging_enabled; }
bool getImpersonateDRE() { return impersonate_dre; }
void setImpersonateDRE(bool impersonate) { impersonate_dre = impersonate; }
const char * auto_reload_plugin_key = "auto_reload_plugins";
const char * impersonate_dre_key = "impersonate_dre";
const char * logging_enabled_key = "logging_enabled";
bool loadPrefs(const boost::filesystem::path & path) {
//open file, and deserialize
std::ifstream f(path.string());
if(f.fail()) {
std::cerr << "Couldn't open properties file: " << path.string() << std::endl;
return false;
}
boost::property_tree::ptree prefs;
try {
read_json(f, prefs);
} catch (const boost::property_tree::json_parser_error & e) {
LOG(std::string("Error parsing preferences file at ") + path.string());
LOG(std::string("Error: ") + e.what());
LOG("Preferences going back to default.");
return false;
}
BOOST_FOREACH(boost::property_tree::ptree::value_type & window_detail_val, prefs.get_child("windows")) {
showViewerWindow(window_detail_val.second);
}
auto_reload_plugins = prefs.get<bool>(auto_reload_plugin_key, true);
impersonate_dre = prefs.get<bool>(impersonate_dre_key, false);
bool logging_enabled_loaded = prefs.get<bool>(logging_enabled_key, true);
if(false == logging_enabled_loaded) {
LOG("Logging disabled via prefs file");
}
LOG("Loaded prefs from " + path.string());
logging_enabled = logging_enabled_loaded;
return true;
}
bool savePrefs(const boost::filesystem::path & path) {
boost::property_tree::ptree prefs;
boost::property_tree::ptree windows = getViewerWindowsDetails();
prefs.put("author", "Lee C. Baker");
prefs.put("compile_date", __DATE__ " " __TIME__);
prefs.add_child("windows", windows);
prefs.put(auto_reload_plugin_key, auto_reload_plugins);
prefs.put(impersonate_dre_key, impersonate_dre);
prefs.put(logging_enabled_key, logging_enabled);
//serialize and save to file
std::ofstream f(path.string());
if(f.fail()) {
return false;
}
try {
write_json(f, prefs);
} catch(boost::property_tree::json_parser_error & e) {
LOG(std::string("Error writing preferences file at ") + path.string());
LOG(e.filename() + ":" + std::to_string(e.line()));
LOG(e.message());
return false;
}
return false == f.fail();
}<|endoftext|> |
<commit_before>/*
Copyright (c) 2014 Noel R. Cower
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 USEOR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include "context.hh"
#include "write_context.hh"
#include "read_context.hh"
#include "error_strings.hh"
s_sz_context::s_sz_context(sz_allocator_t *alloc)
: error(sz_errstr_no_error)
, ctx_alloc(alloc)
, stream(NULL)
, stream_pos(0)
{
// nop
}
s_sz_context::~s_sz_context()
{
// nop
}
sz_response_t
s_sz_context::file_error() const
{
if (sz_stream_eof(stream)) {
error = sz_errstr_eof;
return SZ_ERROR_EOF;
} else {
if (mode() == SZ_READER) {
error = sz_errstr_cannot_read;
return SZ_ERROR_CANNOT_READ;
} else {
error = sz_errstr_cannot_write;
return SZ_ERROR_CANNOT_WRITE;
}
}
}
sz_response_t
s_sz_context::set_stream(sz_stream_t *stream)
{
if (stream == NULL) {
error = sz_errstr_null_stream;
return SZ_ERROR_INVALID_STREAM;
} else if (opened()) {
error = sz_errstr_open_set_stream;
return SZ_ERROR_CONTEXT_OPEN;
}
this->stream = stream;
stream_pos = sz_stream_tell(stream);
return SZ_SUCCESS;
}
sz_response_t
sz_check_context(const sz_context_t *ctx, sz_mode_t mode)
{
if (NULL == ctx) {
return SZ_ERROR_NULL_CONTEXT;
}
if (mode != ctx->mode()) {
ctx->error =
(mode == SZ_READER)
? sz_errstr_read_on_write
: sz_errstr_write_on_read;
return SZ_ERROR_INVALID_OPERATION;
}
return SZ_SUCCESS;
}
SZ_DEF_BEGIN
const char *
sz_get_error(sz_context_t *ctx)
{
return ctx ? ctx->error : NULL;
}
sz_context_t *
sz_new_context(sz_mode_t mode, sz_allocator_t *allocator)
{
if (!allocator) {
allocator = sz_default_allocator();
}
void *memory = NULL;
switch (mode) {
case SZ_READER: {
memory = sz_malloc(sizeof(sz_read_context_t), allocator);
new (memory) sz_read_context_t(allocator);
} break;
case SZ_WRITER: {
memory = sz_malloc(sizeof(sz_write_context_t), allocator);
new (memory) sz_write_context_t(allocator);
} break;
default: break;
}
return (sz_context_t *)memory;
}
sz_response_t
sz_destroy_context(sz_context_t *ctx)
{
if (ctx == NULL) {
return SZ_ERROR_NULL_CONTEXT;
}
sz_allocator_t *alloc = ctx->ctx_alloc;
ctx->~sz_context_t();
sz_free(ctx, alloc);
return SZ_SUCCESS;
}
sz_response_t
sz_close(sz_context_t *ctx)
{
if (ctx == NULL) {
return SZ_ERROR_NULL_CONTEXT;
}
return ctx->close();
}
sz_response_t
sz_open(sz_context_t *ctx)
{
if (ctx == NULL) {
return SZ_ERROR_NULL_CONTEXT;
}
return ctx->open();
}
SZ_DEF_END
<commit_msg>Add missing sz_set_stream.<commit_after>/*
Copyright (c) 2014 Noel R. Cower
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 USEOR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include "context.hh"
#include "write_context.hh"
#include "read_context.hh"
#include "error_strings.hh"
s_sz_context::s_sz_context(sz_allocator_t *alloc)
: error(sz_errstr_no_error)
, ctx_alloc(alloc)
, stream(NULL)
, stream_pos(0)
{
// nop
}
s_sz_context::~s_sz_context()
{
// nop
}
sz_response_t
s_sz_context::file_error() const
{
if (sz_stream_eof(stream)) {
error = sz_errstr_eof;
return SZ_ERROR_EOF;
} else {
if (mode() == SZ_READER) {
error = sz_errstr_cannot_read;
return SZ_ERROR_CANNOT_READ;
} else {
error = sz_errstr_cannot_write;
return SZ_ERROR_CANNOT_WRITE;
}
}
}
sz_response_t
s_sz_context::set_stream(sz_stream_t *stream)
{
if (stream == NULL) {
error = sz_errstr_null_stream;
return SZ_ERROR_INVALID_STREAM;
} else if (opened()) {
error = sz_errstr_open_set_stream;
return SZ_ERROR_CONTEXT_OPEN;
}
this->stream = stream;
stream_pos = sz_stream_tell(stream);
return SZ_SUCCESS;
}
sz_response_t
sz_check_context(const sz_context_t *ctx, sz_mode_t mode)
{
if (NULL == ctx) {
return SZ_ERROR_NULL_CONTEXT;
}
if (mode != ctx->mode()) {
ctx->error =
(mode == SZ_READER)
? sz_errstr_read_on_write
: sz_errstr_write_on_read;
return SZ_ERROR_INVALID_OPERATION;
}
return SZ_SUCCESS;
}
SZ_DEF_BEGIN
const char *
sz_get_error(sz_context_t *ctx)
{
return ctx ? ctx->error : NULL;
}
sz_response_t
sz_set_stream(sz_context_t *ctx, sz_stream_t *stream)
{
return ctx ? ctx->set_stream(stream) : SZ_ERROR_NULL_CONTEXT;
}
sz_context_t *
sz_new_context(sz_mode_t mode, sz_allocator_t *allocator)
{
if (!allocator) {
allocator = sz_default_allocator();
}
void *memory = NULL;
switch (mode) {
case SZ_READER: {
memory = sz_malloc(sizeof(sz_read_context_t), allocator);
new (memory) sz_read_context_t(allocator);
} break;
case SZ_WRITER: {
memory = sz_malloc(sizeof(sz_write_context_t), allocator);
new (memory) sz_write_context_t(allocator);
} break;
default: break;
}
return (sz_context_t *)memory;
}
sz_response_t
sz_destroy_context(sz_context_t *ctx)
{
if (ctx == NULL) {
return SZ_ERROR_NULL_CONTEXT;
}
sz_allocator_t *alloc = ctx->ctx_alloc;
ctx->~sz_context_t();
sz_free(ctx, alloc);
return SZ_SUCCESS;
}
sz_response_t
sz_close(sz_context_t *ctx)
{
if (ctx == NULL) {
return SZ_ERROR_NULL_CONTEXT;
}
return ctx->close();
}
sz_response_t
sz_open(sz_context_t *ctx)
{
if (ctx == NULL) {
return SZ_ERROR_NULL_CONTEXT;
}
return ctx->open();
}
SZ_DEF_END
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, The Bifrost Authors. All rights reserved.
* Copyright (c) 2016, NVIDIA CORPORATION. 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 Bifrost Authors 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 ``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 <bifrost/memory.h>
#include "utils.hpp"
#include "cuda.hpp"
#include "trace.hpp"
#include <cstdlib> // For posix_memalign
#include <cstring> // For memcpy
#include <iostream>
#define BF_IS_POW2(x) (x) && !((x) & ((x) - 1))
static_assert(BF_IS_POW2(BF_ALIGNMENT), "BF_ALIGNMENT must be a power of 2");
#undef BF_IS_POW2
//static_assert(BF_ALIGNMENT >= 8, "BF_ALIGNMENT must be >= 8");
BFstatus bfGetSpace(const void* ptr, BFspace* space) {
BF_ASSERT(ptr, BF_STATUS_INVALID_POINTER);
#if !defined BF_CUDA_ENABLED || !BF_CUDA_ENABLED
*space = BF_SPACE_SYSTEM;
#else
cudaPointerAttributes ptr_attrs;
cudaError_t ret = cudaPointerGetAttributes(&ptr_attrs, ptr);
BF_ASSERT(ret == cudaSuccess || ret == cudaErrorInvalidValue,
BF_STATUS_DEVICE_ERROR);
if( ret == cudaErrorInvalidValue ) {
// TODO: Is there a better way to find out how a pointer was allocated?
// Alternatively, is there a way to prevent this from showing
// up in cuda-memcheck?
// Note: cudaPointerGetAttributes only works for memory allocated with
// CUDA API functions, so if it fails we just assume sysmem.
*space = BF_SPACE_SYSTEM;
// WAR to avoid the ignored failure showing up later
cudaGetLastError();
} else if( ptr_attrs.isManaged ) {
*space = BF_SPACE_CUDA_MANAGED;
} else {
switch( ptr_attrs.memoryType ) {
case cudaMemoryTypeHost: *space = BF_SPACE_SYSTEM; break;
case cudaMemoryTypeDevice: *space = BF_SPACE_CUDA; break;
default: {
// This should never be reached
BF_FAIL("Valid memoryType", BF_STATUS_INTERNAL_ERROR);
}
}
}
#endif
return BF_STATUS_SUCCESS;
}
const char* bfGetSpaceString(BFspace space) {
// TODO: Is there a better way to do this that does not involve hard
// coding all of these values twice (one in memory.h for the
// enum, once here)?
switch( space ) {
case BF_SPACE_AUTO: return "auto";
case BF_SPACE_SYSTEM: return "system";
case BF_SPACE_CUDA: return "cuda";
case BF_SPACE_CUDA_HOST: return "cuda_host";
case BF_SPACE_CUDA_MANAGED: return "cuda_managed";
default: return "unknown";
}
}
BFstatus bfMalloc(void** ptr, BFsize size, BFspace space) {
//printf("bfMalloc(%p, %lu, %i)\n", ptr, size, space);
void* data;
switch( space ) {
case BF_SPACE_SYSTEM: {
//data = std::aligned_alloc(std::max(BF_ALIGNMENT,8), size);
int err = ::posix_memalign((void**)&data, std::max(BF_ALIGNMENT,8), size);
BF_ASSERT(!err, BF_STATUS_MEM_ALLOC_FAILED);
//if( err ) data = nullptr;
//printf("bfMalloc --> %p\n", data);
break;
}
#if defined BF_CUDA_ENABLED && BF_CUDA_ENABLED
case BF_SPACE_CUDA: {
BF_CHECK_CUDA(cudaMalloc((void**)&data, size),
BF_STATUS_MEM_ALLOC_FAILED);
break;
}
case BF_SPACE_CUDA_HOST: {
unsigned flags = cudaHostAllocDefault;
BF_CHECK_CUDA(cudaHostAlloc((void**)&data, size, flags),
BF_STATUS_MEM_ALLOC_FAILED);
break;
}
case BF_SPACE_CUDA_MANAGED: {
unsigned flags = cudaMemAttachGlobal;
BF_CHECK_CUDA(cudaMallocManaged((void**)&data, size, flags),
BF_STATUS_MEM_ALLOC_FAILED);
break;
}
#endif
default: BF_FAIL("Valid bfMalloc() space", BF_STATUS_INVALID_SPACE);
}
//return data;
*ptr = data;
return BF_STATUS_SUCCESS;
}
BFstatus bfFree(void* ptr, BFspace space) {
BF_ASSERT(ptr, BF_STATUS_INVALID_POINTER);
if( space == BF_SPACE_AUTO ) {
bfGetSpace(ptr, &space);
}
switch( space ) {
case BF_SPACE_SYSTEM: ::free(ptr); break;
#if defined BF_CUDA_ENABLED && BF_CUDA_ENABLED
case BF_SPACE_CUDA: cudaFree(ptr); break;
case BF_SPACE_CUDA_HOST: cudaFreeHost(ptr); break;
case BF_SPACE_CUDA_MANAGED: cudaFree(ptr); break;
#endif
default: BF_FAIL("Valid bfFree() space", BF_STATUS_INVALID_ARGUMENT);
}
return BF_STATUS_SUCCESS;
}
BFstatus bfMemcpy(void* dst,
BFspace dst_space,
const void* src,
BFspace src_space,
BFsize count) {
if( count ) {
BF_ASSERT(dst, BF_STATUS_INVALID_POINTER);
BF_ASSERT(src, BF_STATUS_INVALID_POINTER);
#if !defined BF_CUDA_ENABLED || !BF_CUDA_ENABLED
::memcpy(dst, src, count);
#else
// Note: Explicitly dispatching to ::memcpy was found to be much faster
// than using cudaMemcpyDefault.
if( src_space == BF_SPACE_AUTO ) bfGetSpace(src, &src_space);
if( dst_space == BF_SPACE_AUTO ) bfGetSpace(dst, &dst_space);
cudaMemcpyKind kind = cudaMemcpyDefault;
switch( src_space ) {
case BF_SPACE_CUDA_HOST: // fall-through
case BF_SPACE_SYSTEM: {
switch( dst_space ) {
case BF_SPACE_CUDA_HOST: // fall-through
case BF_SPACE_SYSTEM: ::memcpy(dst, src, count); return BF_STATUS_SUCCESS;
case BF_SPACE_CUDA: kind = cudaMemcpyHostToDevice; break;
// TODO: BF_SPACE_CUDA_MANAGED
default: BF_FAIL("Valid bfMemcpy dst space", BF_STATUS_INVALID_ARGUMENT);
}
break;
}
case BF_SPACE_CUDA: {
switch( dst_space ) {
case BF_SPACE_CUDA_HOST: // fall-through
case BF_SPACE_SYSTEM: kind = cudaMemcpyDeviceToHost; break;
case BF_SPACE_CUDA: kind = cudaMemcpyDeviceToDevice; break;
// TODO: BF_SPACE_CUDA_MANAGED
default: BF_FAIL("Valid bfMemcpy dst space", BF_STATUS_INVALID_ARGUMENT);
}
break;
}
default: BF_FAIL("Valid bfMemcpy src space", BF_STATUS_INVALID_ARGUMENT);
}
BF_TRACE_STREAM(g_cuda_stream);
BF_CHECK_CUDA(cudaMemcpyAsync(dst, src, count, kind, g_cuda_stream),
BF_STATUS_MEM_OP_FAILED);
#endif
}
return BF_STATUS_SUCCESS;
}
void memcpy2D(void* dst,
BFsize dst_stride,
const void* src,
BFsize src_stride,
BFsize width,
BFsize height) {
//std::cout << "memcpy2D dst: " << dst << ", " << dst_stride << std::endl;
//std::cout << "memcpy2D src: " << src << ", " << src_stride << std::endl;
//std::cout << "memcpy2D shp: " << width << ", " << height << std::endl;
for( BFsize row=0; row<height; ++row ) {
::memcpy((char*)dst + row*dst_stride,
(char*)src + row*src_stride,
width);
}
}
BFstatus bfMemcpy2D(void* dst,
BFsize dst_stride,
BFspace dst_space,
const void* src,
BFsize src_stride,
BFspace src_space,
BFsize width, // bytes
BFsize height) { // rows
if( width*height ) {
BF_ASSERT(dst, BF_STATUS_INVALID_POINTER);
BF_ASSERT(src, BF_STATUS_INVALID_POINTER);
#if !defined BF_CUDA_ENABLED || !BF_CUDA_ENABLED
memcpy2D(dst, dst_stride, src, src_stride, width, height);
#else
// Note: Explicitly dispatching to ::memcpy was found to be much faster
// than using cudaMemcpyDefault.
if( src_space == BF_SPACE_AUTO ) bfGetSpace(src, &src_space);
if( dst_space == BF_SPACE_AUTO ) bfGetSpace(dst, &dst_space);
cudaMemcpyKind kind = cudaMemcpyDefault;
switch( src_space ) {
case BF_SPACE_CUDA_HOST: // fall-through
case BF_SPACE_SYSTEM: {
switch( dst_space ) {
case BF_SPACE_CUDA_HOST: // fall-through
case BF_SPACE_SYSTEM: memcpy2D(dst, dst_stride, src, src_stride, width, height); return BF_STATUS_SUCCESS;
case BF_SPACE_CUDA: kind = cudaMemcpyHostToDevice; break;
// TODO: Is this the right thing to do?
case BF_SPACE_CUDA_MANAGED: kind = cudaMemcpyDefault; break;
default: BF_FAIL("Valid bfMemcpy2D dst space", BF_STATUS_INVALID_ARGUMENT);
}
break;
}
case BF_SPACE_CUDA: {
switch( dst_space ) {
case BF_SPACE_CUDA_HOST: // fall-through
case BF_SPACE_SYSTEM: kind = cudaMemcpyDeviceToHost; break;
case BF_SPACE_CUDA: kind = cudaMemcpyDeviceToDevice; break;
// TODO: Is this the right thing to do?
case BF_SPACE_CUDA_MANAGED: kind = cudaMemcpyDefault; break;
default: BF_FAIL("Valid bfMemcpy2D dst space", BF_STATUS_INVALID_ARGUMENT);
}
break;
}
default: BF_FAIL("Valid bfMemcpy2D src space", BF_STATUS_INVALID_ARGUMENT);
}
BF_TRACE_STREAM(g_cuda_stream);
BF_CHECK_CUDA(cudaMemcpy2DAsync(dst, dst_stride,
src, src_stride,
width, height,
kind, g_cuda_stream),
BF_STATUS_MEM_OP_FAILED);
#endif
}
return BF_STATUS_SUCCESS;
}
BFstatus bfMemset(void* ptr,
BFspace space,
int value,
BFsize count) {
BF_ASSERT(ptr, BF_STATUS_INVALID_POINTER);
if( count ) {
if( space == BF_SPACE_AUTO ) {
// TODO: Check status here
bfGetSpace(ptr, &space);
}
switch( space ) {
case BF_SPACE_SYSTEM: ::memset(ptr, value, count); break;
#if defined BF_CUDA_ENABLED && BF_CUDA_ENABLED
case BF_SPACE_CUDA_HOST: ::memset(ptr, value, count); break;
case BF_SPACE_CUDA: // Fall-through
case BF_SPACE_CUDA_MANAGED: {
BF_TRACE_STREAM(g_cuda_stream);
BF_CHECK_CUDA(cudaMemsetAsync(ptr, value, count, g_cuda_stream),
BF_STATUS_MEM_OP_FAILED);
break;
}
#endif
default: BF_FAIL("Valid bfMemset space", BF_STATUS_INVALID_ARGUMENT);
}
}
return BF_STATUS_SUCCESS;
}
void memset2D(void* ptr,
BFsize stride,
int value,
BFsize width,
BFsize height) {
for( BFsize row=0; row<height; ++row ) {
::memset((char*)ptr + row*stride, value, width);
}
}
BFstatus bfMemset2D(void* ptr,
BFsize stride,
BFspace space,
int value,
BFsize width, // bytes
BFsize height) { // rows
BF_ASSERT(ptr, BF_STATUS_INVALID_POINTER);
if( width*height ) {
if( space == BF_SPACE_AUTO ) {
bfGetSpace(ptr, &space);
}
switch( space ) {
case BF_SPACE_SYSTEM: memset2D(ptr, stride, value, width, height); break;
#if defined BF_CUDA_ENABLED && BF_CUDA_ENABLED
case BF_SPACE_CUDA_HOST: memset2D(ptr, stride, value, width, height); break;
case BF_SPACE_CUDA: // Fall-through
case BF_SPACE_CUDA_MANAGED: {
BF_TRACE_STREAM(g_cuda_stream);
BF_CHECK_CUDA(cudaMemset2DAsync(ptr, stride, value, width, height, g_cuda_stream),
BF_STATUS_MEM_OP_FAILED);
break;
}
#endif
default: BF_FAIL("Valid bfMemset2D space", BF_STATUS_INVALID_ARGUMENT);
}
}
return BF_STATUS_SUCCESS;
}
BFsize bfGetAlignment() {
return BF_ALIGNMENT;
}
<commit_msg>Cleaned up a few compiler warnings in memory.cpp under CUDA 10+.<commit_after>/*
* Copyright (c) 2016, The Bifrost Authors. All rights reserved.
* Copyright (c) 2016, NVIDIA CORPORATION. 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 Bifrost Authors 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 ``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 <bifrost/memory.h>
#include "utils.hpp"
#include "cuda.hpp"
#include "trace.hpp"
#include <cstdlib> // For posix_memalign
#include <cstring> // For memcpy
#include <iostream>
#define BF_IS_POW2(x) (x) && !((x) & ((x) - 1))
static_assert(BF_IS_POW2(BF_ALIGNMENT), "BF_ALIGNMENT must be a power of 2");
#undef BF_IS_POW2
//static_assert(BF_ALIGNMENT >= 8, "BF_ALIGNMENT must be >= 8");
BFstatus bfGetSpace(const void* ptr, BFspace* space) {
BF_ASSERT(ptr, BF_STATUS_INVALID_POINTER);
#if !defined BF_CUDA_ENABLED || !BF_CUDA_ENABLED
*space = BF_SPACE_SYSTEM;
#else
cudaPointerAttributes ptr_attrs;
cudaError_t ret = cudaPointerGetAttributes(&ptr_attrs, ptr);
BF_ASSERT(ret == cudaSuccess || ret == cudaErrorInvalidValue,
BF_STATUS_DEVICE_ERROR);
if( ret == cudaErrorInvalidValue ) {
// TODO: Is there a better way to find out how a pointer was allocated?
// Alternatively, is there a way to prevent this from showing
// up in cuda-memcheck?
// Note: cudaPointerGetAttributes only works for memory allocated with
// CUDA API functions, so if it fails we just assume sysmem.
*space = BF_SPACE_SYSTEM;
// WAR to avoid the ignored failure showing up later
cudaGetLastError();
#if defined(__CUDACC_VER_MAJOR__) && __CUDACC_VER_MAJOR__ >= 10
} else {
switch( ptr_attrs.type ) {
case cudaMemoryTypeHost: *space = BF_SPACE_SYSTEM; break;
case cudaMemoryTypeDevice: *space = BF_SPACE_CUDA; break;
case cudaMemoryTypeManaged: *space = BF_SPACE_CUDA_MANAGED; break
default: {
// This should never be reached
BF_FAIL("Valid memoryType", BF_STATUS_INTERNAL_ERROR);
}
}
#else
} else if( ptr_attrs.isManaged ) {
*space = BF_SPACE_CUDA_MANAGED;
} else {
switch( ptr_attrs.memoryType ) {
case cudaMemoryTypeHost: *space = BF_SPACE_SYSTEM; break;
case cudaMemoryTypeDevice: *space = BF_SPACE_CUDA; break;
default: {
// This should never be reached
BF_FAIL("Valid memoryType", BF_STATUS_INTERNAL_ERROR);
}
}
}
#endif // defined(__CUDACC_VER_MAJOR__) && __CUDACC_VER_MAJOR__ >= 10
#endif
return BF_STATUS_SUCCESS;
}
const char* bfGetSpaceString(BFspace space) {
// TODO: Is there a better way to do this that does not involve hard
// coding all of these values twice (one in memory.h for the
// enum, once here)?
switch( space ) {
case BF_SPACE_AUTO: return "auto";
case BF_SPACE_SYSTEM: return "system";
case BF_SPACE_CUDA: return "cuda";
case BF_SPACE_CUDA_HOST: return "cuda_host";
case BF_SPACE_CUDA_MANAGED: return "cuda_managed";
default: return "unknown";
}
}
BFstatus bfMalloc(void** ptr, BFsize size, BFspace space) {
//printf("bfMalloc(%p, %lu, %i)\n", ptr, size, space);
void* data;
switch( space ) {
case BF_SPACE_SYSTEM: {
//data = std::aligned_alloc(std::max(BF_ALIGNMENT,8), size);
int err = ::posix_memalign((void**)&data, std::max(BF_ALIGNMENT,8), size);
BF_ASSERT(!err, BF_STATUS_MEM_ALLOC_FAILED);
//if( err ) data = nullptr;
//printf("bfMalloc --> %p\n", data);
break;
}
#if defined BF_CUDA_ENABLED && BF_CUDA_ENABLED
case BF_SPACE_CUDA: {
BF_CHECK_CUDA(cudaMalloc((void**)&data, size),
BF_STATUS_MEM_ALLOC_FAILED);
break;
}
case BF_SPACE_CUDA_HOST: {
unsigned flags = cudaHostAllocDefault;
BF_CHECK_CUDA(cudaHostAlloc((void**)&data, size, flags),
BF_STATUS_MEM_ALLOC_FAILED);
break;
}
case BF_SPACE_CUDA_MANAGED: {
unsigned flags = cudaMemAttachGlobal;
BF_CHECK_CUDA(cudaMallocManaged((void**)&data, size, flags),
BF_STATUS_MEM_ALLOC_FAILED);
break;
}
#endif
default: BF_FAIL("Valid bfMalloc() space", BF_STATUS_INVALID_SPACE);
}
//return data;
*ptr = data;
return BF_STATUS_SUCCESS;
}
BFstatus bfFree(void* ptr, BFspace space) {
BF_ASSERT(ptr, BF_STATUS_INVALID_POINTER);
if( space == BF_SPACE_AUTO ) {
bfGetSpace(ptr, &space);
}
switch( space ) {
case BF_SPACE_SYSTEM: ::free(ptr); break;
#if defined BF_CUDA_ENABLED && BF_CUDA_ENABLED
case BF_SPACE_CUDA: cudaFree(ptr); break;
case BF_SPACE_CUDA_HOST: cudaFreeHost(ptr); break;
case BF_SPACE_CUDA_MANAGED: cudaFree(ptr); break;
#endif
default: BF_FAIL("Valid bfFree() space", BF_STATUS_INVALID_ARGUMENT);
}
return BF_STATUS_SUCCESS;
}
BFstatus bfMemcpy(void* dst,
BFspace dst_space,
const void* src,
BFspace src_space,
BFsize count) {
if( count ) {
BF_ASSERT(dst, BF_STATUS_INVALID_POINTER);
BF_ASSERT(src, BF_STATUS_INVALID_POINTER);
#if !defined BF_CUDA_ENABLED || !BF_CUDA_ENABLED
::memcpy(dst, src, count);
#else
// Note: Explicitly dispatching to ::memcpy was found to be much faster
// than using cudaMemcpyDefault.
if( src_space == BF_SPACE_AUTO ) bfGetSpace(src, &src_space);
if( dst_space == BF_SPACE_AUTO ) bfGetSpace(dst, &dst_space);
cudaMemcpyKind kind = cudaMemcpyDefault;
switch( src_space ) {
case BF_SPACE_CUDA_HOST: // fall-through
case BF_SPACE_SYSTEM: {
switch( dst_space ) {
case BF_SPACE_CUDA_HOST: // fall-through
case BF_SPACE_SYSTEM: ::memcpy(dst, src, count); return BF_STATUS_SUCCESS;
case BF_SPACE_CUDA: kind = cudaMemcpyHostToDevice; break;
// TODO: BF_SPACE_CUDA_MANAGED
default: BF_FAIL("Valid bfMemcpy dst space", BF_STATUS_INVALID_ARGUMENT);
}
break;
}
case BF_SPACE_CUDA: {
switch( dst_space ) {
case BF_SPACE_CUDA_HOST: // fall-through
case BF_SPACE_SYSTEM: kind = cudaMemcpyDeviceToHost; break;
case BF_SPACE_CUDA: kind = cudaMemcpyDeviceToDevice; break;
// TODO: BF_SPACE_CUDA_MANAGED
default: BF_FAIL("Valid bfMemcpy dst space", BF_STATUS_INVALID_ARGUMENT);
}
break;
}
default: BF_FAIL("Valid bfMemcpy src space", BF_STATUS_INVALID_ARGUMENT);
}
BF_TRACE_STREAM(g_cuda_stream);
BF_CHECK_CUDA(cudaMemcpyAsync(dst, src, count, kind, g_cuda_stream),
BF_STATUS_MEM_OP_FAILED);
#endif
}
return BF_STATUS_SUCCESS;
}
void memcpy2D(void* dst,
BFsize dst_stride,
const void* src,
BFsize src_stride,
BFsize width,
BFsize height) {
//std::cout << "memcpy2D dst: " << dst << ", " << dst_stride << std::endl;
//std::cout << "memcpy2D src: " << src << ", " << src_stride << std::endl;
//std::cout << "memcpy2D shp: " << width << ", " << height << std::endl;
for( BFsize row=0; row<height; ++row ) {
::memcpy((char*)dst + row*dst_stride,
(char*)src + row*src_stride,
width);
}
}
BFstatus bfMemcpy2D(void* dst,
BFsize dst_stride,
BFspace dst_space,
const void* src,
BFsize src_stride,
BFspace src_space,
BFsize width, // bytes
BFsize height) { // rows
if( width && height ) {
BF_ASSERT(dst, BF_STATUS_INVALID_POINTER);
BF_ASSERT(src, BF_STATUS_INVALID_POINTER);
#if !defined BF_CUDA_ENABLED || !BF_CUDA_ENABLED
memcpy2D(dst, dst_stride, src, src_stride, width, height);
#else
// Note: Explicitly dispatching to ::memcpy was found to be much faster
// than using cudaMemcpyDefault.
if( src_space == BF_SPACE_AUTO ) bfGetSpace(src, &src_space);
if( dst_space == BF_SPACE_AUTO ) bfGetSpace(dst, &dst_space);
cudaMemcpyKind kind = cudaMemcpyDefault;
switch( src_space ) {
case BF_SPACE_CUDA_HOST: // fall-through
case BF_SPACE_SYSTEM: {
switch( dst_space ) {
case BF_SPACE_CUDA_HOST: // fall-through
case BF_SPACE_SYSTEM: memcpy2D(dst, dst_stride, src, src_stride, width, height); return BF_STATUS_SUCCESS;
case BF_SPACE_CUDA: kind = cudaMemcpyHostToDevice; break;
// TODO: Is this the right thing to do?
case BF_SPACE_CUDA_MANAGED: kind = cudaMemcpyDefault; break;
default: BF_FAIL("Valid bfMemcpy2D dst space", BF_STATUS_INVALID_ARGUMENT);
}
break;
}
case BF_SPACE_CUDA: {
switch( dst_space ) {
case BF_SPACE_CUDA_HOST: // fall-through
case BF_SPACE_SYSTEM: kind = cudaMemcpyDeviceToHost; break;
case BF_SPACE_CUDA: kind = cudaMemcpyDeviceToDevice; break;
// TODO: Is this the right thing to do?
case BF_SPACE_CUDA_MANAGED: kind = cudaMemcpyDefault; break;
default: BF_FAIL("Valid bfMemcpy2D dst space", BF_STATUS_INVALID_ARGUMENT);
}
break;
}
default: BF_FAIL("Valid bfMemcpy2D src space", BF_STATUS_INVALID_ARGUMENT);
}
BF_TRACE_STREAM(g_cuda_stream);
BF_CHECK_CUDA(cudaMemcpy2DAsync(dst, dst_stride,
src, src_stride,
width, height,
kind, g_cuda_stream),
BF_STATUS_MEM_OP_FAILED);
#endif
}
return BF_STATUS_SUCCESS;
}
BFstatus bfMemset(void* ptr,
BFspace space,
int value,
BFsize count) {
BF_ASSERT(ptr, BF_STATUS_INVALID_POINTER);
if( count ) {
if( space == BF_SPACE_AUTO ) {
// TODO: Check status here
bfGetSpace(ptr, &space);
}
switch( space ) {
case BF_SPACE_SYSTEM: ::memset(ptr, value, count); break;
#if defined BF_CUDA_ENABLED && BF_CUDA_ENABLED
case BF_SPACE_CUDA_HOST: ::memset(ptr, value, count); break;
case BF_SPACE_CUDA: // Fall-through
case BF_SPACE_CUDA_MANAGED: {
BF_TRACE_STREAM(g_cuda_stream);
BF_CHECK_CUDA(cudaMemsetAsync(ptr, value, count, g_cuda_stream),
BF_STATUS_MEM_OP_FAILED);
break;
}
#endif
default: BF_FAIL("Valid bfMemset space", BF_STATUS_INVALID_ARGUMENT);
}
}
return BF_STATUS_SUCCESS;
}
void memset2D(void* ptr,
BFsize stride,
int value,
BFsize width,
BFsize height) {
for( BFsize row=0; row<height; ++row ) {
::memset((char*)ptr + row*stride, value, width);
}
}
BFstatus bfMemset2D(void* ptr,
BFsize stride,
BFspace space,
int value,
BFsize width, // bytes
BFsize height) { // rows
BF_ASSERT(ptr, BF_STATUS_INVALID_POINTER);
if( width && height ) {
if( space == BF_SPACE_AUTO ) {
bfGetSpace(ptr, &space);
}
switch( space ) {
case BF_SPACE_SYSTEM: memset2D(ptr, stride, value, width, height); break;
#if defined BF_CUDA_ENABLED && BF_CUDA_ENABLED
case BF_SPACE_CUDA_HOST: memset2D(ptr, stride, value, width, height); break;
case BF_SPACE_CUDA: // Fall-through
case BF_SPACE_CUDA_MANAGED: {
BF_TRACE_STREAM(g_cuda_stream);
BF_CHECK_CUDA(cudaMemset2DAsync(ptr, stride, value, width, height, g_cuda_stream),
BF_STATUS_MEM_OP_FAILED);
break;
}
#endif
default: BF_FAIL("Valid bfMemset2D space", BF_STATUS_INVALID_ARGUMENT);
}
}
return BF_STATUS_SUCCESS;
}
BFsize bfGetAlignment() {
return BF_ALIGNMENT;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestAxisActor3D.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSphereSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkAxisActor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkCamera.h"
#include "vtkStringArray.h"
#include "vtkSmartPointer.h"
#include "vtkTestUtilities.h"
//----------------------------------------------------------------------------
int TestAxisActor3D( int vtkNotUsed(argc), char * vtkNotUsed(argv) [] )
{
// Create the axis actor
vtkSmartPointer<vtkAxisActor> axis =
vtkSmartPointer<vtkAxisActor>::New();
axis->SetPoint1(0,0,0);
axis->SetPoint2(1,1,0);
axis->SetBounds(0,1,0,0,0,0);
axis->SetTickLocationToBoth();
axis->SetAxisTypeToX();
axis->SetTitle("1.0");
axis->SetTitleScale(0.5);
axis->SetTitleVisibility(1);
axis->SetMajorTickSize(0.01);
axis->SetRange(0,1);
vtkSmartPointer<vtkStringArray> labels =
vtkSmartPointer<vtkStringArray>::New();
labels->SetNumberOfTuples(1);
labels->SetValue(0,"X");
axis->SetLabels(labels);
axis->SetLabelScale(.2);
axis->MinorTicksVisibleOff();
axis->SetDeltaMajor(0,.1);
axis->SetCalculateTitleOffset(0);
axis->SetCalculateLabelOffset(0);
axis->Print(std::cout);
vtkSmartPointer<vtkSphereSource> source =
vtkSmartPointer<vtkSphereSource>::New();
source->SetCenter(1,1,1);
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(source->GetOutputPort());
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
// Create the RenderWindow, Renderer and both Actors
vtkSmartPointer<vtkRenderer> ren1 =
vtkRenderer::New();
vtkSmartPointer<vtkRenderWindow> renWin =
vtkRenderWindow::New();
renWin->AddRenderer(ren1);
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkRenderWindowInteractor::New();
iren->SetRenderWindow(renWin);
axis->SetCamera(ren1->GetActiveCamera());
ren1->AddActor(actor);
ren1->AddActor(axis);
ren1->SetBackground(.3, .4, .5);
renWin->SetSize(500,200);
ren1->ResetCamera();
ren1->ResetCameraClippingRange();
// render the image
iren->Initialize();
renWin->Render();
iren->Start();
return EXIT_SUCCESS;
}
<commit_msg>BUG: Missing SmartPointers<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestAxisActor3D.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSphereSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkAxisActor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkCamera.h"
#include "vtkStringArray.h"
#include "vtkSmartPointer.h"
#include "vtkTestUtilities.h"
//----------------------------------------------------------------------------
int TestAxisActor3D( int vtkNotUsed(argc), char * vtkNotUsed(argv) [] )
{
// Create the axis actor
vtkSmartPointer<vtkAxisActor> axis =
vtkSmartPointer<vtkAxisActor>::New();
axis->SetPoint1(0,0,0);
axis->SetPoint2(1,1,0);
axis->SetBounds(0,1,0,0,0,0);
axis->SetTickLocationToBoth();
axis->SetAxisTypeToX();
axis->SetTitle("1.0");
axis->SetTitleScale(0.5);
axis->SetTitleVisibility(1);
axis->SetMajorTickSize(0.01);
axis->SetRange(0,1);
vtkSmartPointer<vtkStringArray> labels =
vtkSmartPointer<vtkStringArray>::New();
labels->SetNumberOfTuples(1);
labels->SetValue(0,"X");
axis->SetLabels(labels);
axis->SetLabelScale(.2);
axis->MinorTicksVisibleOff();
axis->SetDeltaMajor(0,.1);
axis->SetCalculateTitleOffset(0);
axis->SetCalculateLabelOffset(0);
axis->Print(std::cout);
vtkSmartPointer<vtkSphereSource> source =
vtkSmartPointer<vtkSphereSource>::New();
source->SetCenter(1,1,1);
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(source->GetOutputPort());
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
// Create the RenderWindow, Renderer and both Actors
vtkSmartPointer<vtkRenderer> ren1 =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWin =
vtkSmartPointer<vtkRenderWindow>::New();
renWin->AddRenderer(ren1);
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
iren->SetRenderWindow(renWin);
axis->SetCamera(ren1->GetActiveCamera());
ren1->AddActor(actor);
ren1->AddActor(axis);
ren1->SetBackground(.3, .4, .5);
renWin->SetSize(500,200);
ren1->ResetCamera();
ren1->ResetCameraClippingRange();
// render the image
iren->Initialize();
renWin->Render();
iren->Start();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011 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:
*
* 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 APPLE AND ITS 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 APPLE OR ITS 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"
#include "core/rendering/RenderThemeChromiumAndroid.h"
#include "CSSValueKeywords.h"
#include "InputTypeNames.h"
#include "UserAgentStyleSheets.h"
#include "core/platform/ScrollbarTheme.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderMediaControls.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderProgress.h"
#include "core/rendering/RenderSlider.h"
#include "platform/LayoutTestSupport.h"
#include "platform/graphics/Color.h"
#include "public/platform/android/WebThemeEngine.h"
#include "public/platform/Platform.h"
#include "wtf/StdLibExtras.h"
namespace WebCore {
PassRefPtr<RenderTheme> RenderThemeChromiumAndroid::create()
{
return adoptRef(new RenderThemeChromiumAndroid());
}
RenderTheme& RenderTheme::theme()
{
DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumAndroid::create()));
return *renderTheme;
}
RenderThemeChromiumAndroid::~RenderThemeChromiumAndroid()
{
}
Color RenderThemeChromiumAndroid::systemColor(CSSValueID cssValueId) const
{
if (isRunningLayoutTest() && cssValueId == CSSValueButtonface) {
// Match Linux button color in layout tests.
static const Color linuxButtonGrayColor(0xffdddddd);
return linuxButtonGrayColor;
}
return RenderTheme::systemColor(cssValueId);
}
String RenderThemeChromiumAndroid::extraMediaControlsStyleSheet()
{
return String(mediaControlsAndroidUserAgentStyleSheet, sizeof(mediaControlsAndroidUserAgentStyleSheet));
}
String RenderThemeChromiumAndroid::extraDefaultStyleSheet()
{
return RenderThemeChromiumDefault::extraDefaultStyleSheet() +
String(themeChromiumAndroidUserAgentStyleSheet, sizeof(themeChromiumAndroidUserAgentStyleSheet));
}
void RenderThemeChromiumAndroid::adjustInnerSpinButtonStyle(RenderStyle* style, Element*) const
{
if (isRunningLayoutTest()) {
// Match Linux spin button style in layout tests.
// FIXME: Consider removing the conditional if a future Android theme matches this.
IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartInnerSpinButton);
style->setWidth(Length(size.width(), Fixed));
style->setMinWidth(Length(size.width(), Fixed));
}
}
bool RenderThemeChromiumAndroid::paintMediaOverlayPlayButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
return RenderMediaControls::paintMediaControlsPart(MediaOverlayPlayButton, object, paintInfo, rect);
}
int RenderThemeChromiumAndroid::menuListArrowPadding() const
{
// We cannot use the scrollbar thickness here, as it's width is 0 on Android.
// Instead, use the width of the scrollbar down arrow.
IntSize scrollbarSize = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartScrollbarDownArrow);
return scrollbarSize.width();
}
bool RenderThemeChromiumAndroid::supportsDataListUI(const AtomicString& type) const
{
// FIXME: Add other input types.
return type == InputTypeNames::text || type == InputTypeNames::search || type == InputTypeNames::url
|| type == InputTypeNames::tel || type == InputTypeNames::email || type == InputTypeNames::number
|| type == InputTypeNames::color;
}
} // namespace WebCore
<commit_msg>Enable datalist for range input type on Android<commit_after>/*
* Copyright (C) 2011 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:
*
* 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 APPLE AND ITS 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 APPLE OR ITS 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"
#include "core/rendering/RenderThemeChromiumAndroid.h"
#include "CSSValueKeywords.h"
#include "InputTypeNames.h"
#include "UserAgentStyleSheets.h"
#include "core/platform/ScrollbarTheme.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderMediaControls.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderProgress.h"
#include "core/rendering/RenderSlider.h"
#include "platform/LayoutTestSupport.h"
#include "platform/graphics/Color.h"
#include "public/platform/android/WebThemeEngine.h"
#include "public/platform/Platform.h"
#include "wtf/StdLibExtras.h"
namespace WebCore {
PassRefPtr<RenderTheme> RenderThemeChromiumAndroid::create()
{
return adoptRef(new RenderThemeChromiumAndroid());
}
RenderTheme& RenderTheme::theme()
{
DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumAndroid::create()));
return *renderTheme;
}
RenderThemeChromiumAndroid::~RenderThemeChromiumAndroid()
{
}
Color RenderThemeChromiumAndroid::systemColor(CSSValueID cssValueId) const
{
if (isRunningLayoutTest() && cssValueId == CSSValueButtonface) {
// Match Linux button color in layout tests.
static const Color linuxButtonGrayColor(0xffdddddd);
return linuxButtonGrayColor;
}
return RenderTheme::systemColor(cssValueId);
}
String RenderThemeChromiumAndroid::extraMediaControlsStyleSheet()
{
return String(mediaControlsAndroidUserAgentStyleSheet, sizeof(mediaControlsAndroidUserAgentStyleSheet));
}
String RenderThemeChromiumAndroid::extraDefaultStyleSheet()
{
return RenderThemeChromiumDefault::extraDefaultStyleSheet() +
String(themeChromiumAndroidUserAgentStyleSheet, sizeof(themeChromiumAndroidUserAgentStyleSheet));
}
void RenderThemeChromiumAndroid::adjustInnerSpinButtonStyle(RenderStyle* style, Element*) const
{
if (isRunningLayoutTest()) {
// Match Linux spin button style in layout tests.
// FIXME: Consider removing the conditional if a future Android theme matches this.
IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartInnerSpinButton);
style->setWidth(Length(size.width(), Fixed));
style->setMinWidth(Length(size.width(), Fixed));
}
}
bool RenderThemeChromiumAndroid::paintMediaOverlayPlayButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
return RenderMediaControls::paintMediaControlsPart(MediaOverlayPlayButton, object, paintInfo, rect);
}
int RenderThemeChromiumAndroid::menuListArrowPadding() const
{
// We cannot use the scrollbar thickness here, as it's width is 0 on Android.
// Instead, use the width of the scrollbar down arrow.
IntSize scrollbarSize = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartScrollbarDownArrow);
return scrollbarSize.width();
}
bool RenderThemeChromiumAndroid::supportsDataListUI(const AtomicString& type) const
{
// FIXME: Add other input types.
return type == InputTypeNames::text || type == InputTypeNames::search || type == InputTypeNames::url
|| type == InputTypeNames::tel || type == InputTypeNames::email || type == InputTypeNames::number
|| type == InputTypeNames::color
|| type == InputTypeNames::range;
}
} // namespace WebCore
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Author: Arman Pazouki, Milad Rakhsha
// =============================================================================
//
// Implementation of fsi system that includes all subclasses for proximity and
// force calculation, and time integration
// =============================================================================
#include "chrono_fsi/ChSystemFsi.h"
#include "chrono/fea/ChElementCableANCF.h"
#include "chrono/fea/ChElementShellANCF.h"
#include "chrono/fea/ChMesh.h"
#include "chrono/fea/ChNodeFEAxyzD.h"
namespace chrono {
namespace fsi {
//--------------------------------------------------------------------------------------------------------------------------------
ChSystemFsi::ChSystemFsi(ChSystem* other_physicalSystem, bool other_haveFluid, ChFluidDynamics::Integrator type)
: mphysicalSystem(other_physicalSystem), haveFluid(other_haveFluid), mTime(0) {
fsiData = new ChFsiDataManager();
paramsH = new SimParams;
numObjectsH = &(fsiData->numObjects);
fluidIntegrator = type;
bceWorker = new ChBce(&(fsiData->sortedSphMarkersD), &(fsiData->markersProximityD), &(fsiData->fsiGeneralData),
paramsH, numObjectsH);
fluidDynamics = new ChFluidDynamics(bceWorker, fsiData, paramsH, numObjectsH, fluidIntegrator);
fsi_mesh = std::make_shared<fea::ChMesh>();
fsiBodeisPtr.resize(0);
fsiShellsPtr.resize(0);
fsiCablesPtr.resize(0);
fsiNodesPtr.resize(0);
fsiInterface = new ChFsiInterface(
paramsH, &(fsiData->fsiBodiesH), &(fsiData->fsiMeshH), mphysicalSystem, &fsiBodeisPtr, &fsiNodesPtr,
&fsiCablesPtr, &fsiShellsPtr, fsi_mesh, &(fsiData->fsiGeneralData.CableElementsNodesH),
&(fsiData->fsiGeneralData.CableElementsNodes), &(fsiData->fsiGeneralData.ShellElementsNodesH),
&(fsiData->fsiGeneralData.ShellElementsNodes), &(fsiData->fsiGeneralData.rigid_FSI_ForcesD),
&(fsiData->fsiGeneralData.rigid_FSI_TorquesD), &(fsiData->fsiGeneralData.Flex_FSI_ForcesD));
}
//--------------------------------------------------------------------------------------------------------------------------------
void ChSystemFsi::Finalize() {
printf("\n\nChSystemFsi::Finalize 1-FinalizeData\n");
FinalizeData();
if (haveFluid) {
printf("\n\nChSystemFsi::Finalize 2-bceWorker->Finalize\n");
bceWorker->Finalize(&(fsiData->sphMarkersD1), &(fsiData->fsiBodiesD1), &(fsiData->fsiMeshD));
printf("\n\nChSystemFsi::Finalize 3-fluidDynamics->Finalize\n");
fluidDynamics->Finalize();
std::cout << "referenceArraySize in 3-fluidDynamics->Finalize"
<< GetDataManager()->fsiGeneralData.referenceArray.size() << "\n";
}
}
//--------------------------------------------------------------------------------------------------------------------------------
ChSystemFsi::~ChSystemFsi() {
delete fsiData;
delete paramsH;
delete bceWorker;
delete fluidDynamics;
delete fsiInterface;
}
//--------------------------------------------------------------------------------------------------------------------------------
void ChSystemFsi::CopyDeviceDataToHalfStep() {
thrust::copy(fsiData->sphMarkersD1.posRadD.begin(), fsiData->sphMarkersD1.posRadD.end(),
fsiData->sphMarkersD2.posRadD.begin());
thrust::copy(fsiData->sphMarkersD1.velMasD.begin(), fsiData->sphMarkersD1.velMasD.end(),
fsiData->sphMarkersD2.velMasD.begin());
thrust::copy(fsiData->sphMarkersD1.rhoPresMuD.begin(), fsiData->sphMarkersD1.rhoPresMuD.end(),
fsiData->sphMarkersD2.rhoPresMuD.begin());
}
void ChSystemFsi::SetFluidSystemLinearSolver(ChFsiLinearSolver::SolverType other_solverType) {
fluidDynamics->GetForceSystem()->SetLinearSolver(other_solverType);
}
//--------------------------------------------------------------------------------------------------------------------------------
void ChSystemFsi::DoStepDynamics_FSI() {
/// The following is used to execute the previous Explicit SPH
if (fluidDynamics->GetIntegratorType() == ChFluidDynamics::Integrator::ExplicitSPH) {
fsiInterface->Copy_ChSystem_to_External();
this->CopyDeviceDataToHalfStep();
ChDeviceUtils::FillMyThrust4(fsiData->fsiGeneralData.derivVelRhoD, mR4(0));
fluidDynamics->IntegrateSPH(&(fsiData->sphMarkersD2), &(fsiData->sphMarkersD1), &(fsiData->fsiBodiesD1),
&(fsiData->fsiMeshD), 0.5 * paramsH->dT);
bceWorker->Rigid_Forces_Torques(&(fsiData->sphMarkersD1), &(fsiData->fsiBodiesD1));
fsiInterface->Add_Rigid_ForceTorques_To_ChSystem();
mTime += 0.5 * paramsH->dT;
mphysicalSystem->DoStepDynamics(0.5 * paramsH->dT);
fsiInterface->Copy_fsiBodies_ChSystem_to_FluidSystem(&(fsiData->fsiBodiesD2));
bceWorker->UpdateRigidMarkersPositionVelocity(&(fsiData->sphMarkersD2), &(fsiData->fsiBodiesD2));
fluidDynamics->IntegrateSPH(&(fsiData->sphMarkersD1), &(fsiData->sphMarkersD2), &(fsiData->fsiBodiesD2),
&(fsiData->fsiMeshD), 0.5 * paramsH->dT);
bceWorker->Rigid_Forces_Torques(&(fsiData->sphMarkersD2), &(fsiData->fsiBodiesD2));
fsiInterface->Add_Rigid_ForceTorques_To_ChSystem();
mTime -= 0.5 * paramsH->dT;
fsiInterface->Copy_External_To_ChSystem();
mTime += paramsH->dT;
mphysicalSystem->DoStepDynamics(0.5 * paramsH->dT);
//
fsiInterface->Copy_fsiBodies_ChSystem_to_FluidSystem(&(fsiData->fsiBodiesD1));
bceWorker->UpdateRigidMarkersPositionVelocity(&(fsiData->sphMarkersD1), &(fsiData->fsiBodiesD1));
// Density re-initialization
int tStep = mTime / paramsH->dT;
if ((tStep % (paramsH->densityReinit + 1) == 0)) {
fluidDynamics->DensityReinitialization();
}
} else {
/// A different coupling scheme is used for implicit SPH formulations
printf("Copy_ChSystem_to_External\n");
fsiInterface->Copy_ChSystem_to_External();
printf("IntegrateIISPH\n");
fluidDynamics->IntegrateSPH(&(fsiData->sphMarkersD2), &(fsiData->sphMarkersD2), &(fsiData->fsiBodiesD2),
&(fsiData->fsiMeshD), 0.0);
printf("Fluid-structure forces\n");
bceWorker->Rigid_Forces_Torques(&(fsiData->sphMarkersD2), &(fsiData->fsiBodiesD2));
fsiInterface->Add_Rigid_ForceTorques_To_ChSystem();
bceWorker->Flex_Forces(&(fsiData->sphMarkersD2), &(fsiData->fsiMeshD));
// Note that because of applying forces to the nodal coordinates using SetForce() no other external forces can
// be applied, or if any thing has been applied will be rewritten by Add_Flex_Forces_To_ChSystem();
fsiInterface->Add_Flex_Forces_To_ChSystem();
// paramsH->dT_Flex = paramsH->dT;
mTime += 1 * paramsH->dT;
if (paramsH->dT_Flex == 0)
paramsH->dT_Flex = paramsH->dT;
int sync = (paramsH->dT / paramsH->dT_Flex);
if (sync < 1)
sync = 1;
printf("%d * DoStepChronoSystem with dt= %f\n", sync, paramsH->dT / sync);
for (int t = 0; t < sync; t++) {
mphysicalSystem->DoStepDynamics(paramsH->dT / sync);
}
printf("Update Rigid Marker\n");
fsiInterface->Copy_fsiBodies_ChSystem_to_FluidSystem(&(fsiData->fsiBodiesD2));
bceWorker->UpdateRigidMarkersPositionVelocity(&(fsiData->sphMarkersD2), &(fsiData->fsiBodiesD2));
printf("Update Flexible Marker\n");
fsiInterface->Copy_fsiNodes_ChSystem_to_FluidSystem(&(fsiData->fsiMeshD));
bceWorker->UpdateFlexMarkersPositionVelocity(&(fsiData->sphMarkersD2), &(fsiData->fsiMeshD));
printf("=================================================================================================\n");
}
}
//--------------------------------------------------------------------------------------------------------------------------------
void ChSystemFsi::DoStepDynamics_ChronoRK2() {
fsiInterface->Copy_ChSystem_to_External();
mTime += 0.5 * paramsH->dT;
mphysicalSystem->DoStepDynamics(0.5 * paramsH->dT);
mTime -= 0.5 * paramsH->dT;
fsiInterface->Copy_External_To_ChSystem();
mTime += paramsH->dT;
mphysicalSystem->DoStepDynamics(1.0 * paramsH->dT);
}
void SetIntegratorType(ChFluidDynamics::Integrator type) {}
//--------------------------------------------------------------------------------------------------------------------------------
void ChSystemFsi::FinalizeData() {
printf("\n\nfsiInterface->ResizeChronoBodiesData()\n");
fsiInterface->ResizeChronoBodiesData();
int fea_node = 0;
fsiInterface->ResizeChronoCablesData(CableElementsNodes, &(fsiData->fsiGeneralData.CableElementsNodesH));
fsiInterface->ResizeChronoShellsData(ShellElementsNodes, &(fsiData->fsiGeneralData.ShellElementsNodesH));
fsiInterface->ResizeChronoFEANodesData();
printf("\nfsiData->ResizeDataManager...\n");
fea_node = fsi_mesh->GetNnodes();
fsiData->ResizeDataManager(fea_node);
printf("\n\nfsiInterface->Copy_fsiBodies_ChSystem_to_FluidSystem()\n");
fsiInterface->Copy_fsiBodies_ChSystem_to_FluidSystem(&(fsiData->fsiBodiesD1));
fsiInterface->Copy_fsiNodes_ChSystem_to_FluidSystem(&(fsiData->fsiMeshD));
std::cout << "referenceArraySize in FinalizeData " << GetDataManager()->fsiGeneralData.referenceArray.size()
<< "\n";
fsiData->fsiBodiesD2 = fsiData->fsiBodiesD1; //(2) construct midpoint rigid data
}
//--------------------------------------------------------------------------------------------------------------------------------
} // end namespace fsi
} // end namespace chrono
<commit_msg>fixed a minor time-integration issue<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Author: Arman Pazouki, Milad Rakhsha
// =============================================================================
//
// Implementation of fsi system that includes all subclasses for proximity and
// force calculation, and time integration
// =============================================================================
#include "chrono_fsi/ChSystemFsi.h"
#include "chrono/fea/ChElementCableANCF.h"
#include "chrono/fea/ChElementShellANCF.h"
#include "chrono/fea/ChMesh.h"
#include "chrono/fea/ChNodeFEAxyzD.h"
namespace chrono {
namespace fsi {
//--------------------------------------------------------------------------------------------------------------------------------
ChSystemFsi::ChSystemFsi(ChSystem* other_physicalSystem, bool other_haveFluid, ChFluidDynamics::Integrator type)
: mphysicalSystem(other_physicalSystem), haveFluid(other_haveFluid), mTime(0) {
fsiData = new ChFsiDataManager();
paramsH = new SimParams;
numObjectsH = &(fsiData->numObjects);
fluidIntegrator = type;
bceWorker = new ChBce(&(fsiData->sortedSphMarkersD), &(fsiData->markersProximityD), &(fsiData->fsiGeneralData),
paramsH, numObjectsH);
fluidDynamics = new ChFluidDynamics(bceWorker, fsiData, paramsH, numObjectsH, fluidIntegrator);
fsi_mesh = std::make_shared<fea::ChMesh>();
fsiBodeisPtr.resize(0);
fsiShellsPtr.resize(0);
fsiCablesPtr.resize(0);
fsiNodesPtr.resize(0);
fsiInterface = new ChFsiInterface(
paramsH, &(fsiData->fsiBodiesH), &(fsiData->fsiMeshH), mphysicalSystem, &fsiBodeisPtr, &fsiNodesPtr,
&fsiCablesPtr, &fsiShellsPtr, fsi_mesh, &(fsiData->fsiGeneralData.CableElementsNodesH),
&(fsiData->fsiGeneralData.CableElementsNodes), &(fsiData->fsiGeneralData.ShellElementsNodesH),
&(fsiData->fsiGeneralData.ShellElementsNodes), &(fsiData->fsiGeneralData.rigid_FSI_ForcesD),
&(fsiData->fsiGeneralData.rigid_FSI_TorquesD), &(fsiData->fsiGeneralData.Flex_FSI_ForcesD));
}
//--------------------------------------------------------------------------------------------------------------------------------
void ChSystemFsi::Finalize() {
printf("\n\nChSystemFsi::Finalize 1-FinalizeData\n");
FinalizeData();
if (haveFluid) {
printf("\n\nChSystemFsi::Finalize 2-bceWorker->Finalize\n");
bceWorker->Finalize(&(fsiData->sphMarkersD1), &(fsiData->fsiBodiesD1), &(fsiData->fsiMeshD));
printf("\n\nChSystemFsi::Finalize 3-fluidDynamics->Finalize\n");
fluidDynamics->Finalize();
std::cout << "referenceArraySize in 3-fluidDynamics->Finalize"
<< GetDataManager()->fsiGeneralData.referenceArray.size() << "\n";
}
}
//--------------------------------------------------------------------------------------------------------------------------------
ChSystemFsi::~ChSystemFsi() {
delete fsiData;
delete paramsH;
delete bceWorker;
delete fluidDynamics;
delete fsiInterface;
}
//--------------------------------------------------------------------------------------------------------------------------------
void ChSystemFsi::CopyDeviceDataToHalfStep() {
thrust::copy(fsiData->sphMarkersD1.posRadD.begin(), fsiData->sphMarkersD1.posRadD.end(),
fsiData->sphMarkersD2.posRadD.begin());
thrust::copy(fsiData->sphMarkersD1.velMasD.begin(), fsiData->sphMarkersD1.velMasD.end(),
fsiData->sphMarkersD2.velMasD.begin());
thrust::copy(fsiData->sphMarkersD1.rhoPresMuD.begin(), fsiData->sphMarkersD1.rhoPresMuD.end(),
fsiData->sphMarkersD2.rhoPresMuD.begin());
}
void ChSystemFsi::SetFluidSystemLinearSolver(ChFsiLinearSolver::SolverType other_solverType) {
fluidDynamics->GetForceSystem()->SetLinearSolver(other_solverType);
}
//--------------------------------------------------------------------------------------------------------------------------------
void ChSystemFsi::DoStepDynamics_FSI() {
/// The following is used to execute the previous Explicit SPH
if (fluidDynamics->GetIntegratorType() == ChFluidDynamics::Integrator::ExplicitSPH) {
fsiInterface->Copy_ChSystem_to_External();
this->CopyDeviceDataToHalfStep();
ChDeviceUtils::FillMyThrust4(fsiData->fsiGeneralData.derivVelRhoD, mR4(0));
fluidDynamics->IntegrateSPH(&(fsiData->sphMarkersD2), &(fsiData->sphMarkersD1), &(fsiData->fsiBodiesD1),
&(fsiData->fsiMeshD), 0.5 * paramsH->dT);
bceWorker->Rigid_Forces_Torques(&(fsiData->sphMarkersD1), &(fsiData->fsiBodiesD1));
fsiInterface->Add_Rigid_ForceTorques_To_ChSystem();
mTime += 0.5 * paramsH->dT;
mphysicalSystem->DoStepDynamics(0.5 * paramsH->dT);
fsiInterface->Copy_fsiBodies_ChSystem_to_FluidSystem(&(fsiData->fsiBodiesD2));
bceWorker->UpdateRigidMarkersPositionVelocity(&(fsiData->sphMarkersD2), &(fsiData->fsiBodiesD2));
fluidDynamics->IntegrateSPH(&(fsiData->sphMarkersD1), &(fsiData->sphMarkersD2), &(fsiData->fsiBodiesD2),
&(fsiData->fsiMeshD), 1.0 * paramsH->dT);
bceWorker->Rigid_Forces_Torques(&(fsiData->sphMarkersD2), &(fsiData->fsiBodiesD2));
fsiInterface->Add_Rigid_ForceTorques_To_ChSystem();
mTime -= 0.5 * paramsH->dT;
fsiInterface->Copy_External_To_ChSystem();
mTime += paramsH->dT;
mphysicalSystem->DoStepDynamics(0.5 * paramsH->dT);
//
fsiInterface->Copy_fsiBodies_ChSystem_to_FluidSystem(&(fsiData->fsiBodiesD1));
bceWorker->UpdateRigidMarkersPositionVelocity(&(fsiData->sphMarkersD1), &(fsiData->fsiBodiesD1));
// Density re-initialization
int tStep = mTime / paramsH->dT;
if ((tStep % (paramsH->densityReinit + 1) == 0)) {
fluidDynamics->DensityReinitialization();
}
} else {
/// A different coupling scheme is used for implicit SPH formulations
printf("Copy_ChSystem_to_External\n");
fsiInterface->Copy_ChSystem_to_External();
printf("IntegrateIISPH\n");
fluidDynamics->IntegrateSPH(&(fsiData->sphMarkersD2), &(fsiData->sphMarkersD2), &(fsiData->fsiBodiesD2),
&(fsiData->fsiMeshD), 0.0);
printf("Fluid-structure forces\n");
bceWorker->Rigid_Forces_Torques(&(fsiData->sphMarkersD2), &(fsiData->fsiBodiesD2));
fsiInterface->Add_Rigid_ForceTorques_To_ChSystem();
bceWorker->Flex_Forces(&(fsiData->sphMarkersD2), &(fsiData->fsiMeshD));
// Note that because of applying forces to the nodal coordinates using SetForce() no other external forces can
// be applied, or if any thing has been applied will be rewritten by Add_Flex_Forces_To_ChSystem();
fsiInterface->Add_Flex_Forces_To_ChSystem();
// paramsH->dT_Flex = paramsH->dT;
mTime += 1 * paramsH->dT;
if (paramsH->dT_Flex == 0)
paramsH->dT_Flex = paramsH->dT;
int sync = (paramsH->dT / paramsH->dT_Flex);
if (sync < 1)
sync = 1;
printf("%d * DoStepChronoSystem with dt= %f\n", sync, paramsH->dT / sync);
for (int t = 0; t < sync; t++) {
mphysicalSystem->DoStepDynamics(paramsH->dT / sync);
}
printf("Update Rigid Marker\n");
fsiInterface->Copy_fsiBodies_ChSystem_to_FluidSystem(&(fsiData->fsiBodiesD2));
bceWorker->UpdateRigidMarkersPositionVelocity(&(fsiData->sphMarkersD2), &(fsiData->fsiBodiesD2));
printf("Update Flexible Marker\n");
fsiInterface->Copy_fsiNodes_ChSystem_to_FluidSystem(&(fsiData->fsiMeshD));
bceWorker->UpdateFlexMarkersPositionVelocity(&(fsiData->sphMarkersD2), &(fsiData->fsiMeshD));
printf("=================================================================================================\n");
}
}
//--------------------------------------------------------------------------------------------------------------------------------
void ChSystemFsi::DoStepDynamics_ChronoRK2() {
fsiInterface->Copy_ChSystem_to_External();
mTime += 0.5 * paramsH->dT;
mphysicalSystem->DoStepDynamics(0.5 * paramsH->dT);
mTime -= 0.5 * paramsH->dT;
fsiInterface->Copy_External_To_ChSystem();
mTime += paramsH->dT;
mphysicalSystem->DoStepDynamics(1.0 * paramsH->dT);
}
void SetIntegratorType(ChFluidDynamics::Integrator type) {}
//--------------------------------------------------------------------------------------------------------------------------------
void ChSystemFsi::FinalizeData() {
printf("\n\nfsiInterface->ResizeChronoBodiesData()\n");
fsiInterface->ResizeChronoBodiesData();
int fea_node = 0;
fsiInterface->ResizeChronoCablesData(CableElementsNodes, &(fsiData->fsiGeneralData.CableElementsNodesH));
fsiInterface->ResizeChronoShellsData(ShellElementsNodes, &(fsiData->fsiGeneralData.ShellElementsNodesH));
fsiInterface->ResizeChronoFEANodesData();
printf("\nfsiData->ResizeDataManager...\n");
fea_node = fsi_mesh->GetNnodes();
fsiData->ResizeDataManager(fea_node);
printf("\n\nfsiInterface->Copy_fsiBodies_ChSystem_to_FluidSystem()\n");
fsiInterface->Copy_fsiBodies_ChSystem_to_FluidSystem(&(fsiData->fsiBodiesD1));
fsiInterface->Copy_fsiNodes_ChSystem_to_FluidSystem(&(fsiData->fsiMeshD));
std::cout << "referenceArraySize in FinalizeData " << GetDataManager()->fsiGeneralData.referenceArray.size()
<< "\n";
fsiData->fsiBodiesD2 = fsiData->fsiBodiesD1; //(2) construct midpoint rigid data
}
//--------------------------------------------------------------------------------------------------------------------------------
} // end namespace fsi
} // end namespace chrono
<|endoftext|> |
<commit_before>// 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/DataArray.hpp>
#include <nix/hdf5/DataArrayHDF5.hpp>
#include <nix/hdf5/SimpleTagHDF5.hpp>
#include <nix/hdf5/FeatureHDF5.hpp>
#include <nix/hdf5/DataSet.hpp>
#include <nix/Exception.hpp>
using namespace std;
using namespace nix;
using namespace nix::base;
using namespace nix::hdf5;
SimpleTagHDF5::SimpleTagHDF5(shared_ptr<IFile> file, shared_ptr<IBlock> block, const Group &group, const string &id)
: EntityWithSourcesHDF5(file, block, group, id), references_list(group, "references")
{
feature_group = group.openGroup("features", false);
}
SimpleTagHDF5::SimpleTagHDF5(shared_ptr<IFile> file, shared_ptr<IBlock> block, const Group &group, const string &id,
const string &type, const string &name, const std::vector<double> &position)
: SimpleTagHDF5(file, block, group, id, type, name, position, util::getTime())
{
}
SimpleTagHDF5::SimpleTagHDF5(shared_ptr<IFile> file, shared_ptr<IBlock> block, const Group &group, const string &id,
const string &type, const string &name, const std::vector<double> &position, const time_t time)
: EntityWithSourcesHDF5(file, block, group, id, type, name, time), references_list(group, "references")
{
feature_group = group.openGroup("features");
this->position(position);
}
vector<string> SimpleTagHDF5::units() const {
vector<string> units;
group().getData("units", units);
return units;
}
void SimpleTagHDF5::units(const vector<string> &units) {
group().setData("units", units);
forceUpdatedAt();
}
void SimpleTagHDF5::units(const none_t t) {
if (group().hasData("units")) {
group().removeData("units");
}
forceUpdatedAt();
}
vector<double> SimpleTagHDF5::position() const {
vector<double> position;
if (group().hasData("position")) {
group().getData("position", position);
}
return position;
}
void SimpleTagHDF5::position(const vector<double> &position) {
group().setData("position", position);
}
void SimpleTagHDF5::position(const none_t t) {
if (group().hasData("position")) {
group().removeData("position");
}
forceUpdatedAt();
}
vector<double> SimpleTagHDF5::extent() const {
vector<double> extent;
group().getData("extent", extent);
return extent;
}
void SimpleTagHDF5::extent(const vector<double> &extent) {
group().setData("extent", extent);
}
void SimpleTagHDF5::extent(const none_t t) {
if (group().hasData("extent")) {
group().removeData("extent");
}
forceUpdatedAt();
}
// Methods concerning references.
bool SimpleTagHDF5::hasReference(const std::string &id) const {
return references_list.has(id);
}
size_t SimpleTagHDF5::referenceCount() const {
return references_list.count();
}
shared_ptr<IDataArray> SimpleTagHDF5::getReference(const std::string &id) const {
shared_ptr<IDataArray> da;
if (hasReference(id)) {
da = block()->getDataArray(id);
}
return da;
}
shared_ptr<IDataArray> SimpleTagHDF5::getReference(size_t index) const {
shared_ptr<IDataArray> da;
std::vector<std::string> refs = references_list.get();
if (index < refs.size()) {
string id = refs[index];
da = getReference(id);
} else {
throw OutOfBounds("No data array at given index", index);
}
return da;
}
void SimpleTagHDF5::addReference(const std::string &id) {
if (!block()->hasDataArray(id)) {
throw runtime_error("Unable to find data array with reference_id " +
id + " on block " + block()->id());
}
references_list.add(id);
}
bool SimpleTagHDF5::removeReference(const std::string &id) {
return references_list.remove(id);
}
// TODO fix this when base entities are fixed
void SimpleTagHDF5::references(const std::vector<DataArray> &references) {
vector<string> ids(references.size());
for (size_t i = 0; i < references.size(); i++) {
ids[i] = references[i].id();
}
references_list.set(ids);
}
// Methods concerning features.
bool SimpleTagHDF5::hasFeature(const string &id) const {
return feature_group.hasGroup(id);
}
size_t SimpleTagHDF5::featureCount() const {
return feature_group.objectCount();
}
shared_ptr<IFeature> SimpleTagHDF5::getFeature(const std::string &id) const {
shared_ptr<IFeature> feature;
if (hasFeature(id)) {
Group group = feature_group.openGroup(id, false);
// TODO unnecessary IO (see #316)
string link_type;
group.getAttr("link_type", link_type);
LinkType linkType = linkTypeFromString(link_type);
string dataId;
group.getAttr("data", dataId);
DataArray data = block()->getDataArray(dataId);
feature = make_shared<FeatureHDF5>(file(), block(), group, id, data, linkType);
}
return feature;
}
shared_ptr<IFeature> SimpleTagHDF5::getFeature(size_t index) const {
string id = feature_group.objectName(index);
return getFeature(id);
}
shared_ptr<IFeature> SimpleTagHDF5::createFeature(const std::string &data_array_id, LinkType link_type) {
if (link_type == LinkType::Indexed) {
throw std::runtime_error("LinkType 'indexed' is not valid for SimpleTag entities and can only be used for DataTag entities.");
}
string rep_id = util::createId("feature");
while (feature_group.hasObject(rep_id))
rep_id = util::createId("feature");
Group group = feature_group.openGroup(rep_id, true);
DataArray data = block()->getDataArray(data_array_id);
return make_shared<FeatureHDF5>(file(), block(), group, rep_id, data, link_type);
}
bool SimpleTagHDF5::deleteFeature(const string &id) {
if (feature_group.hasGroup(id)) {
feature_group.removeGroup(id);
return true;
} else {
return false;
}
}
// Other methods and functions
SimpleTagHDF5::~SimpleTagHDF5()
{
}
<commit_msg>SimpleTagHDF5: changed getter to use getter-ctors<commit_after>// 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/DataArray.hpp>
#include <nix/hdf5/DataArrayHDF5.hpp>
#include <nix/hdf5/SimpleTagHDF5.hpp>
#include <nix/hdf5/FeatureHDF5.hpp>
#include <nix/hdf5/DataSet.hpp>
#include <nix/Exception.hpp>
using namespace std;
using namespace nix;
using namespace nix::base;
using namespace nix::hdf5;
SimpleTagHDF5::SimpleTagHDF5(shared_ptr<IFile> file, shared_ptr<IBlock> block, const Group &group, const string &id)
: EntityWithSourcesHDF5(file, block, group, id), references_list(group, "references")
{
feature_group = group.openGroup("features", false);
}
SimpleTagHDF5::SimpleTagHDF5(shared_ptr<IFile> file, shared_ptr<IBlock> block, const Group &group, const string &id,
const string &type, const string &name, const std::vector<double> &position)
: SimpleTagHDF5(file, block, group, id, type, name, position, util::getTime())
{
}
SimpleTagHDF5::SimpleTagHDF5(shared_ptr<IFile> file, shared_ptr<IBlock> block, const Group &group, const string &id,
const string &type, const string &name, const std::vector<double> &position, const time_t time)
: EntityWithSourcesHDF5(file, block, group, id, type, name, time), references_list(group, "references")
{
feature_group = group.openGroup("features");
this->position(position);
}
vector<string> SimpleTagHDF5::units() const {
vector<string> units;
group().getData("units", units);
return units;
}
void SimpleTagHDF5::units(const vector<string> &units) {
group().setData("units", units);
forceUpdatedAt();
}
void SimpleTagHDF5::units(const none_t t) {
if (group().hasData("units")) {
group().removeData("units");
}
forceUpdatedAt();
}
vector<double> SimpleTagHDF5::position() const {
vector<double> position;
if (group().hasData("position")) {
group().getData("position", position);
}
return position;
}
void SimpleTagHDF5::position(const vector<double> &position) {
group().setData("position", position);
}
void SimpleTagHDF5::position(const none_t t) {
if (group().hasData("position")) {
group().removeData("position");
}
forceUpdatedAt();
}
vector<double> SimpleTagHDF5::extent() const {
vector<double> extent;
group().getData("extent", extent);
return extent;
}
void SimpleTagHDF5::extent(const vector<double> &extent) {
group().setData("extent", extent);
}
void SimpleTagHDF5::extent(const none_t t) {
if (group().hasData("extent")) {
group().removeData("extent");
}
forceUpdatedAt();
}
// Methods concerning references.
bool SimpleTagHDF5::hasReference(const std::string &id) const {
return references_list.has(id);
}
size_t SimpleTagHDF5::referenceCount() const {
return references_list.count();
}
shared_ptr<IDataArray> SimpleTagHDF5::getReference(const std::string &id) const {
shared_ptr<IDataArray> da;
if (hasReference(id)) {
da = block()->getDataArray(id);
}
return da;
}
shared_ptr<IDataArray> SimpleTagHDF5::getReference(size_t index) const {
shared_ptr<IDataArray> da;
std::vector<std::string> refs = references_list.get();
if (index < refs.size()) {
string id = refs[index];
da = getReference(id);
} else {
throw OutOfBounds("No data array at given index", index);
}
return da;
}
void SimpleTagHDF5::addReference(const std::string &id) {
if (!block()->hasDataArray(id)) {
throw runtime_error("Unable to find data array with reference_id " +
id + " on block " + block()->id());
}
references_list.add(id);
}
bool SimpleTagHDF5::removeReference(const std::string &id) {
return references_list.remove(id);
}
// TODO fix this when base entities are fixed
void SimpleTagHDF5::references(const std::vector<DataArray> &references) {
vector<string> ids(references.size());
for (size_t i = 0; i < references.size(); i++) {
ids[i] = references[i].id();
}
references_list.set(ids);
}
// Methods concerning features.
bool SimpleTagHDF5::hasFeature(const string &id) const {
return feature_group.hasGroup(id);
}
size_t SimpleTagHDF5::featureCount() const {
return feature_group.objectCount();
}
shared_ptr<IFeature> SimpleTagHDF5::getFeature(const std::string &id) const {
shared_ptr<IFeature> feature;
if (hasFeature(id)) {
Group group = feature_group.openGroup(id, false);
feature = make_shared<FeatureHDF5>(file(), block(), group, id);
}
return feature;
}
shared_ptr<IFeature> SimpleTagHDF5::getFeature(size_t index) const {
string id = feature_group.objectName(index);
return getFeature(id);
}
shared_ptr<IFeature> SimpleTagHDF5::createFeature(const std::string &data_array_id, LinkType link_type) {
if (link_type == LinkType::Indexed) {
throw std::runtime_error("LinkType 'indexed' is not valid for SimpleTag entities and can only be used for DataTag entities.");
}
string rep_id = util::createId("feature");
while (feature_group.hasObject(rep_id))
rep_id = util::createId("feature");
Group group = feature_group.openGroup(rep_id, true);
DataArray data = block()->getDataArray(data_array_id);
return make_shared<FeatureHDF5>(file(), block(), group, rep_id, data, link_type);
}
bool SimpleTagHDF5::deleteFeature(const string &id) {
if (feature_group.hasGroup(id)) {
feature_group.removeGroup(id);
return true;
} else {
return false;
}
}
// Other methods and functions
SimpleTagHDF5::~SimpleTagHDF5()
{
}
<|endoftext|> |
<commit_before>/*************************************************
* Karatsuba Multiplication Source File *
* (C) 1999-2007 The Botan Project *
*************************************************/
#include <botan/mp_core.h>
#include <botan/mem_ops.h>
namespace Botan {
namespace {
/*************************************************
* Simple O(N^2) Multiplication *
*************************************************/
void bigint_simple_mul(word z[], const word x[], u32bit x_size,
const word y[], u32bit y_size)
{
clear_mem(z, x_size + y_size);
for(u32bit j = 0; j != x_size; ++j)
z[j+y_size] = bigint_mul_add_words(z + j, y, y_size, x[j]);
}
/*************************************************
* Karatsuba Multiplication Operation *
*************************************************/
void karatsuba_mul(word z[], const word x[], const word y[], u32bit N,
word workspace[])
{
const u32bit KARATSUBA_MUL_LOWER_SIZE = BOTAN_KARAT_MUL_THRESHOLD;
if(N == 6)
bigint_comba_mul6(z, x, y);
else if(N == 8)
bigint_comba_mul8(z, x, y);
else if(N < KARATSUBA_MUL_LOWER_SIZE || N % 2)
bigint_simple_mul(z, x, N, y, N);
else
{
const u32bit N2 = N / 2;
const word* x0 = x;
const word* x1 = x + N2;
const word* y0 = y;
const word* y1 = y + N2;
word* z0 = z;
word* z1 = z + N;
const s32bit cmp0 = bigint_cmp(x0, N2, x1, N2);
const s32bit cmp1 = bigint_cmp(y1, N2, y0, N2);
clear_mem(workspace, 2*N);
if(cmp0 && cmp1)
{
if(cmp0 > 0)
bigint_sub3(z0, x0, N2, x1, N2);
else
bigint_sub3(z0, x1, N2, x0, N2);
if(cmp1 > 0)
bigint_sub3(z1, y1, N2, y0, N2);
else
bigint_sub3(z1, y0, N2, y1, N2);
karatsuba_mul(workspace, z0, z1, N2, workspace+N);
}
karatsuba_mul(z0, x0, y0, N2, workspace+N);
karatsuba_mul(z1, x1, y1, N2, workspace+N);
word carry = bigint_add3_nc(workspace+N, z0, N, z1, N);
carry += bigint_add2_nc(z + N2, N, workspace + N, N);
bigint_add2_nc(z + N + N2, N2, &carry, 1);
if((cmp0 == cmp1) || (cmp0 == 0) || (cmp1 == 0))
bigint_add2(z + N2, 2*N-N2, workspace, N);
else
bigint_sub2(z + N2, 2*N-N2, workspace, N);
}
}
/*************************************************
* Pick a good size for the Karatsuba multiply *
*************************************************/
u32bit karatsuba_size(u32bit z_size,
u32bit x_size, u32bit x_sw,
u32bit y_size, u32bit y_sw)
{
if(x_sw > x_size || x_sw > y_size || y_sw > x_size || y_sw > y_size)
return 0;
if(((x_size == x_sw) && (x_size % 2)) ||
((y_size == y_sw) && (y_size % 2)))
return 0;
u32bit start = (x_sw > y_sw) ? x_sw : y_sw;
u32bit end = (x_size < y_size) ? x_size : y_size;
if(start == end)
{
if(start % 2)
return 0;
return start;
}
for(u32bit j = start; j <= end; ++j)
{
if(j % 2)
continue;
if(2*j > z_size)
return 0;
if(x_sw <= j && j <= x_size && y_sw <= j && j <= y_size)
{
if(j % 4 == 2 &&
(j+2) <= x_size && (j+2) <= y_size && 2*(j+2) <= z_size)
return j+2;
return j;
}
}
return 0;
}
/*************************************************
* Handle small operand multiplies *
*************************************************/
void handle_small_mul(word z[], u32bit z_size,
const word x[], u32bit x_size, u32bit x_sw,
const word y[], u32bit y_size, u32bit y_sw)
{
if(x_sw == 1) bigint_linmul3(z, y, y_sw, x[0]);
else if(y_sw == 1) bigint_linmul3(z, x, x_sw, y[0]);
else if(x_sw <= 4 && x_size >= 4 &&
y_sw <= 4 && y_size >= 4 && z_size >= 8)
bigint_comba_mul4(z, x, y);
else if(x_sw <= 6 && x_size >= 6 &&
y_sw <= 6 && y_size >= 6 && z_size >= 12)
bigint_comba_mul6(z, x, y);
else if(x_sw <= 8 && x_size >= 8 &&
y_sw <= 8 && y_size >= 8 && z_size >= 16)
bigint_comba_mul8(z, x, y);
else
bigint_simple_mul(z, x, x_sw, y, y_sw);
}
}
/*************************************************
* Multiplication Algorithm Dispatcher *
*************************************************/
void bigint_mul(word z[], u32bit z_size, word workspace[],
const word x[], u32bit x_size, u32bit x_sw,
const word y[], u32bit y_size, u32bit y_sw)
{
if(x_size <= 8 || y_size <= 8)
{
handle_small_mul(z, z_size, x, x_size, x_sw, y, y_size, y_sw);
return;
}
const u32bit N = karatsuba_size(z_size, x_size, x_sw, y_size, y_sw);
if(N)
{
clear_mem(workspace, 2*N);
karatsuba_mul(z, x, y, N, workspace);
}
else
bigint_simple_mul(z, x, x_sw, y, y_sw);
}
}
<commit_msg>Mark start and end as const in karatsuba_size since they are never modified after assignment.<commit_after>/*************************************************
* Karatsuba Multiplication Source File *
* (C) 1999-2007 The Botan Project *
*************************************************/
#include <botan/mp_core.h>
#include <botan/mem_ops.h>
namespace Botan {
namespace {
/*************************************************
* Simple O(N^2) Multiplication *
*************************************************/
void bigint_simple_mul(word z[], const word x[], u32bit x_size,
const word y[], u32bit y_size)
{
clear_mem(z, x_size + y_size);
for(u32bit j = 0; j != x_size; ++j)
z[j+y_size] = bigint_mul_add_words(z + j, y, y_size, x[j]);
}
/*************************************************
* Karatsuba Multiplication Operation *
*************************************************/
void karatsuba_mul(word z[], const word x[], const word y[], u32bit N,
word workspace[])
{
const u32bit KARATSUBA_MUL_LOWER_SIZE = BOTAN_KARAT_MUL_THRESHOLD;
if(N == 6)
bigint_comba_mul6(z, x, y);
else if(N == 8)
bigint_comba_mul8(z, x, y);
else if(N < KARATSUBA_MUL_LOWER_SIZE || N % 2)
bigint_simple_mul(z, x, N, y, N);
else
{
const u32bit N2 = N / 2;
const word* x0 = x;
const word* x1 = x + N2;
const word* y0 = y;
const word* y1 = y + N2;
word* z0 = z;
word* z1 = z + N;
const s32bit cmp0 = bigint_cmp(x0, N2, x1, N2);
const s32bit cmp1 = bigint_cmp(y1, N2, y0, N2);
clear_mem(workspace, 2*N);
if(cmp0 && cmp1)
{
if(cmp0 > 0)
bigint_sub3(z0, x0, N2, x1, N2);
else
bigint_sub3(z0, x1, N2, x0, N2);
if(cmp1 > 0)
bigint_sub3(z1, y1, N2, y0, N2);
else
bigint_sub3(z1, y0, N2, y1, N2);
karatsuba_mul(workspace, z0, z1, N2, workspace+N);
}
karatsuba_mul(z0, x0, y0, N2, workspace+N);
karatsuba_mul(z1, x1, y1, N2, workspace+N);
word carry = bigint_add3_nc(workspace+N, z0, N, z1, N);
carry += bigint_add2_nc(z + N2, N, workspace + N, N);
bigint_add2_nc(z + N + N2, N2, &carry, 1);
if((cmp0 == cmp1) || (cmp0 == 0) || (cmp1 == 0))
bigint_add2(z + N2, 2*N-N2, workspace, N);
else
bigint_sub2(z + N2, 2*N-N2, workspace, N);
}
}
/*************************************************
* Pick a good size for the Karatsuba multiply *
*************************************************/
u32bit karatsuba_size(u32bit z_size,
u32bit x_size, u32bit x_sw,
u32bit y_size, u32bit y_sw)
{
if(x_sw > x_size || x_sw > y_size || y_sw > x_size || y_sw > y_size)
return 0;
if(((x_size == x_sw) && (x_size % 2)) ||
((y_size == y_sw) && (y_size % 2)))
return 0;
const u32bit start = (x_sw > y_sw) ? x_sw : y_sw;
const u32bit end = (x_size < y_size) ? x_size : y_size;
if(start == end)
{
if(start % 2)
return 0;
return start;
}
for(u32bit j = start; j <= end; ++j)
{
if(j % 2)
continue;
if(2*j > z_size)
return 0;
if(x_sw <= j && j <= x_size && y_sw <= j && j <= y_size)
{
if(j % 4 == 2 &&
(j+2) <= x_size && (j+2) <= y_size && 2*(j+2) <= z_size)
return j+2;
return j;
}
}
return 0;
}
/*************************************************
* Handle small operand multiplies *
*************************************************/
void handle_small_mul(word z[], u32bit z_size,
const word x[], u32bit x_size, u32bit x_sw,
const word y[], u32bit y_size, u32bit y_sw)
{
if(x_sw == 1) bigint_linmul3(z, y, y_sw, x[0]);
else if(y_sw == 1) bigint_linmul3(z, x, x_sw, y[0]);
else if(x_sw <= 4 && x_size >= 4 &&
y_sw <= 4 && y_size >= 4 && z_size >= 8)
bigint_comba_mul4(z, x, y);
else if(x_sw <= 6 && x_size >= 6 &&
y_sw <= 6 && y_size >= 6 && z_size >= 12)
bigint_comba_mul6(z, x, y);
else if(x_sw <= 8 && x_size >= 8 &&
y_sw <= 8 && y_size >= 8 && z_size >= 16)
bigint_comba_mul8(z, x, y);
else
bigint_simple_mul(z, x, x_sw, y, y_sw);
}
}
/*************************************************
* Multiplication Algorithm Dispatcher *
*************************************************/
void bigint_mul(word z[], u32bit z_size, word workspace[],
const word x[], u32bit x_size, u32bit x_sw,
const word y[], u32bit y_size, u32bit y_sw)
{
if(x_size <= 8 || y_size <= 8)
{
handle_small_mul(z, z_size, x, x_size, x_sw, y, y_size, y_sw);
return;
}
const u32bit N = karatsuba_size(z_size, x_size, x_sw, y_size, y_sw);
if(N)
{
clear_mem(workspace, 2*N);
karatsuba_mul(z, x, y, N, workspace);
}
else
bigint_simple_mul(z, x, x_sw, y, y_sw);
}
}
<|endoftext|> |
<commit_before>// STL
#include <iostream>
#include <string>
// CppUnit
#include <extracppunit/CppUnitCore.hpp>
// StdAir
#include <stdair/STDAIR_Types.hpp>
#include <stdair/bom/BomRootKey.hpp>
#include <stdair/bom/InventoryKey.hpp>
#include <stdair/bom/FlightDateKey.hpp>
#include <stdair/bom/SegmentDateKey.hpp>
#include <stdair/bom/LegDateKey.hpp>
#include <stdair/bom/SegmentCabinKey.hpp>
#include <stdair/bom/LegCabinKey.hpp>
#include <stdair/bom/BookingClassKey.hpp>
#include <stdair/bom/BomRoot.hpp>
#include <stdair/bom/Inventory.hpp>
#include <stdair/bom/FlightDate.hpp>
#include <stdair/bom/SegmentDate.hpp>
#include <stdair/bom/LegDate.hpp>
#include <stdair/bom/SegmentCabin.hpp>
#include <stdair/bom/LegCabin.hpp>
#include <stdair/bom/BookingClass.hpp>
#include <stdair/bom/Network.hpp>
#include <stdair/bom/BomList.hpp>
#include <stdair/bom/BomMap.hpp>
#include <stdair/bom/AirlineFeatureSet.hpp>
#include <stdair/bom/AirlineFeature.hpp>
#include <stdair/factory/FacBomContent.hpp>
#include <stdair/factory/FacSupervisor.hpp>
#include <stdair/service/Logger.hpp>
// AirSched
#include <airsched/factory/FacSupervisor.hpp>
#include <airsched/command/Simulator.hpp>
#include <airsched/AIRSCHED_Service.hpp>
// AirSched Test Suite
#include <test/airsched/AirlineScheduleTestSuite.hpp>
// //////////////////////////////////////////////////////////////////////
void externalMemoryManagementHelper() {
/**
The standard initialisation requires an (CSV) input file to be given.
The initialisation then parses that file and builds the corresponding
inventories.
<br><br>
So, though inventories are already built by the initialisation process,
another one is built from scratch, in order to test the stdair object
construction with a fine granularity.
*/
try {
// Input file name
std::string lInputFilename ("../samples/schedule02.csv");
// Output log File
std::string lLogFilename ("AirlineScheduleTestSuite.log");
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the set of required airline features
stdair::AirlineFeatureSet& lAirlineFeatureSet =
stdair::FacBomContent::instance().create<stdair::AirlineFeatureSet>();
// Initialise an AirlineFeature object
const stdair::AirlineCode_T lAirlineCode ("BA");
stdair::AirlineFeatureKey_T lAirlineFeatureKey (lAirlineCode);
stdair::AirlineFeature& lAirlineFeature = stdair::FacBomContent::
instance().create<stdair::AirlineFeature> (lAirlineFeatureKey);
stdair::FacBomContent::
linkWithParent<stdair::AirlineFeature> (lAirlineFeature,
lAirlineFeatureSet);
// The analysis starts at January 1, 2000
const stdair::Date_T lStartAnalysisDate (2000, 1, 1);
AIRSCHED::AIRSCHED_Service airschedService (logOutputFile,
lAirlineFeatureSet,
lStartAnalysisDate,
lInputFilename);
// DEBUG
STDAIR_LOG_DEBUG ("Welcome to Air-Schedule");
// Step 0.0: initialisation
// Create the root of the Bom tree (i.e., a BomRoot object)
stdair::BomRoot& lBomRoot =
stdair::FacBomContent::instance().create<stdair::BomRoot>();
// Step 0.1: Inventory level
// Create an Inventory (BA)
stdair::InventoryKey_T lInventoryKey (lAirlineCode);
stdair::Inventory& lInventory =
stdair::FacBomContent::instance().create<stdair::Inventory>(lInventoryKey);
stdair::FacBomContent::linkWithParent<stdair::Inventory> (lInventory,
lBomRoot);
// Display the inventory
STDAIR_LOG_DEBUG ("Inventory: " << lInventory.toString());
// Step 0.2: Flight-date level
// Create a FlightDate (BA15/10-JUN-2010)
const stdair::FlightNumber_T lFlightNumber = 15;
const stdair::Date_T lDate (2010, 6, 10);
stdair::FlightDateKey_T lFlightDateKey (lFlightNumber, lDate);
stdair::FlightDate& lFlightDate = stdair::FacBomContent::
instance().create<stdair::FlightDate> (lFlightDateKey);
stdair::FacBomContent::linkWithParent<stdair::FlightDate> (lFlightDate,
lInventory);
// Display the flight-date
STDAIR_LOG_DEBUG ("FlightDate: " << lFlightDate.toString());
// Step 0.3: Segment-date level
// Create a first SegmentDate (LHR-SYD)
const stdair::AirportCode_T lLHR ("LHR");
const stdair::AirportCode_T lSYD ("SYD");
stdair::SegmentDateKey_T lSegmentDateKey (lLHR, lSYD);
stdair::SegmentDate& lLHRSYDSegment =
stdair::FacBomContent::
instance().create<stdair::SegmentDate> (lSegmentDateKey);
stdair::FacBomContent::linkWithParent<stdair::SegmentDate> (lLHRSYDSegment,
lFlightDate);
// Display the segment-date
STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRSYDSegment.toString());
// Create a second SegmentDate (LHR-BKK)
const stdair::AirportCode_T lBKK ("BKK");
lSegmentDateKey = stdair::SegmentDateKey_T (lLHR, lBKK);
stdair::SegmentDate& lLHRBKKSegment =
stdair::FacBomContent::
instance().create<stdair::SegmentDate> (lSegmentDateKey);
stdair::FacBomContent::linkWithParent<stdair::SegmentDate> (lLHRBKKSegment,
lFlightDate);
// Display the segment-date
STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRBKKSegment.toString());
// Create a third SegmentDate (BKK-SYD)
lSegmentDateKey = stdair::SegmentDateKey_T (lBKK, lSYD);
stdair::SegmentDate& lBKKSYDSegment =
stdair::FacBomContent::
instance().create<stdair::SegmentDate> (lSegmentDateKey);
stdair::FacBomContent::linkWithParent<stdair::SegmentDate> (lBKKSYDSegment,
lFlightDate);
// Display the segment-date
STDAIR_LOG_DEBUG ("SegmentDate: " << lBKKSYDSegment.toString());
// Step 0.4: Leg-date level
// Create a first LegDate (LHR)
stdair::LegDateKey_T lLegDateKey (lLHR);
stdair::LegDate& lLHRLeg =
stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
stdair::FacBomContent::linkWithParent<stdair::LegDate>(lLHRLeg, lFlightDate);
// Display the leg-date
STDAIR_LOG_DEBUG ("LegDate: " << lLHRLeg.toString());
// Create a second LegDate (BKK)
lLegDateKey = stdair::LegDateKey_T (lBKK);
stdair::LegDate& lBKKLeg =
stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
stdair::FacBomContent::linkWithParent<stdair::LegDate>(lBKKLeg, lFlightDate);
// Display the leg-date
STDAIR_LOG_DEBUG ("LegDate: " << lBKKLeg.toString());
// Step 0.5: segment-cabin level
// Create a SegmentCabin (Y) of the Segment LHR-BKK;
const stdair::CabinCode_T lY ("Y");
stdair::SegmentCabinKey_T lYSegmentCabinKey (lY);
stdair::SegmentCabin& lLHRBKKSegmentYCabin =
stdair::FacBomContent::
instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
stdair::FacBomContent::
linkWithParent<stdair::SegmentCabin> (lLHRBKKSegmentYCabin,lLHRBKKSegment);
// Display the segment-cabin
STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRBKKSegmentYCabin.toString());
// Create a SegmentCabin (Y) of the Segment BKK-SYD;
stdair::SegmentCabin& lBKKSYDSegmentYCabin =
stdair::FacBomContent::
instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
stdair::FacBomContent::
linkWithParent<stdair::SegmentCabin> (lBKKSYDSegmentYCabin,lBKKSYDSegment);
// Display the segment-cabin
STDAIR_LOG_DEBUG ("SegmentCabin: " << lBKKSYDSegmentYCabin.toString());
// Create a SegmentCabin (Y) of the Segment LHR-SYD;
stdair::SegmentCabin& lLHRSYDSegmentYCabin =
stdair::FacBomContent::
instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
stdair::FacBomContent::
linkWithParent<stdair::SegmentCabin> (lLHRSYDSegmentYCabin,lLHRSYDSegment);
// Display the segment-cabin
STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRSYDSegmentYCabin.toString());
// Step 0.6: leg-cabin level
// Create a LegCabin (Y) of the Leg LHR-BKK;
stdair::LegCabinKey_T lYLegCabinKey (lY);
stdair::LegCabin& lLHRLegYCabin =
stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
stdair::FacBomContent::linkWithParent<stdair::LegCabin> (lLHRLegYCabin,
lLHRLeg);
// Display the leg-cabin
STDAIR_LOG_DEBUG ("LegCabin: " << lLHRLegYCabin.toString());
// Create a LegCabin (Y) of the Leg BKK-SYD;
stdair::LegCabin& lBKKLegYCabin =
stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
stdair::FacBomContent::linkWithParent<stdair::LegCabin> (lBKKLegYCabin,
lBKKLeg);
// Display the leg-cabin
STDAIR_LOG_DEBUG ("LegCabin: " << lBKKLegYCabin.toString());
// Step 0.7: booking class level
// Create a BookingClass (Q) of the Segment LHR-BKK, cabin Y;
const stdair::ClassCode_T lQ ("Q");
stdair::BookingClassKey_T lQBookingClassKey (lQ);
stdair::BookingClass& lLHRBKKSegmentYCabinQClass =
stdair::FacBomContent::
instance().create<stdair::BookingClass> (lQBookingClassKey);
stdair::FacBomContent::
linkWithParent<stdair::BookingClass> (lLHRBKKSegmentYCabinQClass,
lLHRBKKSegmentYCabin);
// Display the booking class
STDAIR_LOG_DEBUG ("BookingClass: "
<< lLHRBKKSegmentYCabinQClass.toString());
// Browse the BomRoot and display the created objects.
STDAIR_LOG_DEBUG ("Browse the BomRoot");
const stdair::InventoryList_T& lInventoryList = lBomRoot.getInventoryList();
for (stdair::InventoryList_T::iterator itInv = lInventoryList.begin();
itInv != lInventoryList.end(); ++itInv) {
const stdair::Inventory& lCurrentInventory = *itInv;
STDAIR_LOG_DEBUG ("Inventory: " << lCurrentInventory.toString());
}
// Close the Log outputFile
logOutputFile.close();
// Clean the memory.
// stdair::FacSupervisor::instance().cleanBomContentLayer();
// stdair::FacSupervisor::instance().cleanBomStructureLayer();
// AIRSCHED::FacSupervisor::instance().cleanServiceLayer();
// AIRSCHED::FacSupervisor::instance().cleanLoggerService();
} catch (const std::exception& stde) {
std::cerr << "Standard exception: " << stde.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception" << std::endl;
}
}
// //////////////////////////////////////////////////////////////////////
void AirlineScheduleTestSuite::externalMemoryManagement() {
CPPUNIT_ASSERT_NO_THROW (externalMemoryManagementHelper(););
}
// //////////////////////////////////////////////////////////////////////
void scheduleParsingHelper() {
try {
// DEBUG
STDAIR_LOG_DEBUG ("Schedule Parsing Test");
// Output log File
std::string lLogFilename ("AirlineScheduleTestSuite.log");
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Input file name
std::string lInputFilename ("../samples/schedule02.csv");
// Create a dummy AirlineFeature object for the test.
stdair::AirlineFeatureSet& lAirlineFeatureSet =
stdair::FacBomContent::instance().create<stdair::AirlineFeatureSet>();
const stdair::AirlineCode_T lAirlineCode ("BA");
stdair::AirlineFeatureKey_T lAirlineFeatureKey (lAirlineCode);
stdair::AirlineFeature& lAirlineFeature = stdair::FacBomContent::
instance().create<stdair::AirlineFeature> (lAirlineFeatureKey);
stdair::FacBomContent::
linkWithParent<stdair::AirlineFeature> (lAirlineFeature,
lAirlineFeatureSet);
const stdair::Date_T lStartAnalysisDate (2000, 1, 1);
AIRSCHED::AIRSCHED_Service airschedService (logOutputFile,
lAirlineFeatureSet,
lStartAnalysisDate,
lInputFilename);
// Start a mini-simulation
airschedService.simulate();
} catch (const std::exception& stde) {
std::cerr << "Standard exception: " << stde.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception" << std::endl;
}
}
// //////////////////////////////////////////////////////////////////////
void AirlineScheduleTestSuite::scheduleParsing() {
CPPUNIT_ASSERT_NO_THROW (scheduleParsingHelper(););
}
// //////////////////////////////////////////////////////////////////////
AirlineScheduleTestSuite::AirlineScheduleTestSuite () {
_describeKey << "Running test on AIRSCHED Optimisation function";
}
// /////////////// M A I N /////////////////
CPPUNIT_MAIN()
<commit_msg>[Dev] The log output stream initialisation has been moved into the StdAir library.<commit_after>// STL
#include <iostream>
#include <string>
// CppUnit
#include <extracppunit/CppUnitCore.hpp>
// StdAir
#include <stdair/STDAIR_Types.hpp>
#include <stdair/bom/BomRootKey.hpp>
#include <stdair/bom/InventoryKey.hpp>
#include <stdair/bom/FlightDateKey.hpp>
#include <stdair/bom/SegmentDateKey.hpp>
#include <stdair/bom/LegDateKey.hpp>
#include <stdair/bom/SegmentCabinKey.hpp>
#include <stdair/bom/LegCabinKey.hpp>
#include <stdair/bom/BookingClassKey.hpp>
#include <stdair/bom/BomRoot.hpp>
#include <stdair/bom/Inventory.hpp>
#include <stdair/bom/FlightDate.hpp>
#include <stdair/bom/SegmentDate.hpp>
#include <stdair/bom/LegDate.hpp>
#include <stdair/bom/SegmentCabin.hpp>
#include <stdair/bom/LegCabin.hpp>
#include <stdair/bom/BookingClass.hpp>
#include <stdair/bom/Network.hpp>
#include <stdair/bom/BomList.hpp>
#include <stdair/bom/BomMap.hpp>
#include <stdair/bom/AirlineFeatureSet.hpp>
#include <stdair/bom/AirlineFeature.hpp>
#include <stdair/factory/FacBomContent.hpp>
#include <stdair/factory/FacSupervisor.hpp>
#include <stdair/service/Logger.hpp>
// AirSched
#include <airsched/factory/FacSupervisor.hpp>
#include <airsched/command/Simulator.hpp>
#include <airsched/AIRSCHED_Service.hpp>
// AirSched Test Suite
#include <test/airsched/AirlineScheduleTestSuite.hpp>
// //////////////////////////////////////////////////////////////////////
void externalMemoryManagementHelper() {
/**
The standard initialisation requires an (CSV) input file to be given.
The initialisation then parses that file and builds the corresponding
inventories.
<br><br>
So, though inventories are already built by the initialisation process,
another one is built from scratch, in order to test the stdair object
construction with a fine granularity.
*/
try {
// Input file name
std::string lInputFilename ("../samples/schedule02.csv");
// Output log File
std::string lLogFilename ("AirlineScheduleTestSuite.log");
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the set of required airline features
stdair::AirlineFeatureSet& lAirlineFeatureSet =
stdair::FacBomContent::instance().create<stdair::AirlineFeatureSet>();
// Initialise an AirlineFeature object
const stdair::AirlineCode_T lAirlineCode ("BA");
stdair::AirlineFeatureKey_T lAirlineFeatureKey (lAirlineCode);
stdair::AirlineFeature& lAirlineFeature = stdair::FacBomContent::
instance().create<stdair::AirlineFeature> (lAirlineFeatureKey);
stdair::FacBomContent::
linkWithParent<stdair::AirlineFeature> (lAirlineFeature,
lAirlineFeatureSet);
// The analysis starts at January 1, 2000
const stdair::Date_T lStartAnalysisDate (2000, 1, 1);
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
AIRSCHED::AIRSCHED_Service airschedService (lLogParams,
lAirlineFeatureSet,
lStartAnalysisDate,
lInputFilename);
// DEBUG
STDAIR_LOG_DEBUG ("Welcome to Air-Schedule");
// Step 0.0: initialisation
// Create the root of the Bom tree (i.e., a BomRoot object)
stdair::BomRoot& lBomRoot =
stdair::FacBomContent::instance().create<stdair::BomRoot>();
// Step 0.1: Inventory level
// Create an Inventory (BA)
stdair::InventoryKey_T lInventoryKey (lAirlineCode);
stdair::Inventory& lInventory =
stdair::FacBomContent::instance().create<stdair::Inventory>(lInventoryKey);
stdair::FacBomContent::linkWithParent<stdair::Inventory> (lInventory,
lBomRoot);
// Display the inventory
STDAIR_LOG_DEBUG ("Inventory: " << lInventory.toString());
// Step 0.2: Flight-date level
// Create a FlightDate (BA15/10-JUN-2010)
const stdair::FlightNumber_T lFlightNumber = 15;
const stdair::Date_T lDate (2010, 6, 10);
stdair::FlightDateKey_T lFlightDateKey (lFlightNumber, lDate);
stdair::FlightDate& lFlightDate = stdair::FacBomContent::
instance().create<stdair::FlightDate> (lFlightDateKey);
stdair::FacBomContent::linkWithParent<stdair::FlightDate> (lFlightDate,
lInventory);
// Display the flight-date
STDAIR_LOG_DEBUG ("FlightDate: " << lFlightDate.toString());
// Step 0.3: Segment-date level
// Create a first SegmentDate (LHR-SYD)
const stdair::AirportCode_T lLHR ("LHR");
const stdair::AirportCode_T lSYD ("SYD");
stdair::SegmentDateKey_T lSegmentDateKey (lLHR, lSYD);
stdair::SegmentDate& lLHRSYDSegment =
stdair::FacBomContent::
instance().create<stdair::SegmentDate> (lSegmentDateKey);
stdair::FacBomContent::linkWithParent<stdair::SegmentDate> (lLHRSYDSegment,
lFlightDate);
// Display the segment-date
STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRSYDSegment.toString());
// Create a second SegmentDate (LHR-BKK)
const stdair::AirportCode_T lBKK ("BKK");
lSegmentDateKey = stdair::SegmentDateKey_T (lLHR, lBKK);
stdair::SegmentDate& lLHRBKKSegment =
stdair::FacBomContent::
instance().create<stdair::SegmentDate> (lSegmentDateKey);
stdair::FacBomContent::linkWithParent<stdair::SegmentDate> (lLHRBKKSegment,
lFlightDate);
// Display the segment-date
STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRBKKSegment.toString());
// Create a third SegmentDate (BKK-SYD)
lSegmentDateKey = stdair::SegmentDateKey_T (lBKK, lSYD);
stdair::SegmentDate& lBKKSYDSegment =
stdair::FacBomContent::
instance().create<stdair::SegmentDate> (lSegmentDateKey);
stdair::FacBomContent::linkWithParent<stdair::SegmentDate> (lBKKSYDSegment,
lFlightDate);
// Display the segment-date
STDAIR_LOG_DEBUG ("SegmentDate: " << lBKKSYDSegment.toString());
// Step 0.4: Leg-date level
// Create a first LegDate (LHR)
stdair::LegDateKey_T lLegDateKey (lLHR);
stdair::LegDate& lLHRLeg =
stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
stdair::FacBomContent::linkWithParent<stdair::LegDate>(lLHRLeg, lFlightDate);
// Display the leg-date
STDAIR_LOG_DEBUG ("LegDate: " << lLHRLeg.toString());
// Create a second LegDate (BKK)
lLegDateKey = stdair::LegDateKey_T (lBKK);
stdair::LegDate& lBKKLeg =
stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
stdair::FacBomContent::linkWithParent<stdair::LegDate>(lBKKLeg, lFlightDate);
// Display the leg-date
STDAIR_LOG_DEBUG ("LegDate: " << lBKKLeg.toString());
// Step 0.5: segment-cabin level
// Create a SegmentCabin (Y) of the Segment LHR-BKK;
const stdair::CabinCode_T lY ("Y");
stdair::SegmentCabinKey_T lYSegmentCabinKey (lY);
stdair::SegmentCabin& lLHRBKKSegmentYCabin =
stdair::FacBomContent::
instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
stdair::FacBomContent::
linkWithParent<stdair::SegmentCabin> (lLHRBKKSegmentYCabin,lLHRBKKSegment);
// Display the segment-cabin
STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRBKKSegmentYCabin.toString());
// Create a SegmentCabin (Y) of the Segment BKK-SYD;
stdair::SegmentCabin& lBKKSYDSegmentYCabin =
stdair::FacBomContent::
instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
stdair::FacBomContent::
linkWithParent<stdair::SegmentCabin> (lBKKSYDSegmentYCabin,lBKKSYDSegment);
// Display the segment-cabin
STDAIR_LOG_DEBUG ("SegmentCabin: " << lBKKSYDSegmentYCabin.toString());
// Create a SegmentCabin (Y) of the Segment LHR-SYD;
stdair::SegmentCabin& lLHRSYDSegmentYCabin =
stdair::FacBomContent::
instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
stdair::FacBomContent::
linkWithParent<stdair::SegmentCabin> (lLHRSYDSegmentYCabin,lLHRSYDSegment);
// Display the segment-cabin
STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRSYDSegmentYCabin.toString());
// Step 0.6: leg-cabin level
// Create a LegCabin (Y) of the Leg LHR-BKK;
stdair::LegCabinKey_T lYLegCabinKey (lY);
stdair::LegCabin& lLHRLegYCabin =
stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
stdair::FacBomContent::linkWithParent<stdair::LegCabin> (lLHRLegYCabin,
lLHRLeg);
// Display the leg-cabin
STDAIR_LOG_DEBUG ("LegCabin: " << lLHRLegYCabin.toString());
// Create a LegCabin (Y) of the Leg BKK-SYD;
stdair::LegCabin& lBKKLegYCabin =
stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
stdair::FacBomContent::linkWithParent<stdair::LegCabin> (lBKKLegYCabin,
lBKKLeg);
// Display the leg-cabin
STDAIR_LOG_DEBUG ("LegCabin: " << lBKKLegYCabin.toString());
// Step 0.7: booking class level
// Create a BookingClass (Q) of the Segment LHR-BKK, cabin Y;
const stdair::ClassCode_T lQ ("Q");
stdair::BookingClassKey_T lQBookingClassKey (lQ);
stdair::BookingClass& lLHRBKKSegmentYCabinQClass =
stdair::FacBomContent::
instance().create<stdair::BookingClass> (lQBookingClassKey);
stdair::FacBomContent::
linkWithParent<stdair::BookingClass> (lLHRBKKSegmentYCabinQClass,
lLHRBKKSegmentYCabin);
// Display the booking class
STDAIR_LOG_DEBUG ("BookingClass: "
<< lLHRBKKSegmentYCabinQClass.toString());
// Browse the BomRoot and display the created objects.
STDAIR_LOG_DEBUG ("Browse the BomRoot");
const stdair::InventoryList_T& lInventoryList = lBomRoot.getInventoryList();
for (stdair::InventoryList_T::iterator itInv = lInventoryList.begin();
itInv != lInventoryList.end(); ++itInv) {
const stdair::Inventory& lCurrentInventory = *itInv;
STDAIR_LOG_DEBUG ("Inventory: " << lCurrentInventory.toString());
}
// Close the Log outputFile
logOutputFile.close();
// Clean the memory.
// stdair::FacSupervisor::instance().cleanBomContentLayer();
// stdair::FacSupervisor::instance().cleanBomStructureLayer();
// AIRSCHED::FacSupervisor::instance().cleanServiceLayer();
// AIRSCHED::FacSupervisor::instance().cleanLoggerService();
} catch (const std::exception& stde) {
std::cerr << "Standard exception: " << stde.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception" << std::endl;
}
}
// //////////////////////////////////////////////////////////////////////
void AirlineScheduleTestSuite::externalMemoryManagement() {
CPPUNIT_ASSERT_NO_THROW (externalMemoryManagementHelper(););
}
// //////////////////////////////////////////////////////////////////////
void scheduleParsingHelper() {
try {
// DEBUG
STDAIR_LOG_DEBUG ("Schedule Parsing Test");
// Output log File
std::string lLogFilename ("AirlineScheduleTestSuite.log");
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Input file name
std::string lInputFilename ("../samples/schedule02.csv");
// Create a dummy AirlineFeature object for the test.
stdair::AirlineFeatureSet& lAirlineFeatureSet =
stdair::FacBomContent::instance().create<stdair::AirlineFeatureSet>();
const stdair::AirlineCode_T lAirlineCode ("BA");
stdair::AirlineFeatureKey_T lAirlineFeatureKey (lAirlineCode);
stdair::AirlineFeature& lAirlineFeature = stdair::FacBomContent::
instance().create<stdair::AirlineFeature> (lAirlineFeatureKey);
stdair::FacBomContent::
linkWithParent<stdair::AirlineFeature> (lAirlineFeature,
lAirlineFeatureSet);
const stdair::Date_T lStartAnalysisDate (2000, 1, 1);
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
AIRSCHED::AIRSCHED_Service airschedService (lLogParams,
lAirlineFeatureSet,
lStartAnalysisDate,
lInputFilename);
// Start a mini-simulation
airschedService.simulate();
} catch (const std::exception& stde) {
std::cerr << "Standard exception: " << stde.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception" << std::endl;
}
}
// //////////////////////////////////////////////////////////////////////
void AirlineScheduleTestSuite::scheduleParsing() {
CPPUNIT_ASSERT_NO_THROW (scheduleParsingHelper(););
}
// //////////////////////////////////////////////////////////////////////
AirlineScheduleTestSuite::AirlineScheduleTestSuite () {
_describeKey << "Running test on AIRSCHED Optimisation function";
}
// /////////////// M A I N /////////////////
CPPUNIT_MAIN()
<|endoftext|> |
<commit_before>// Source : https://leetcode.com/problems/substring-with-concatenation-of-all-words/
// Author : Siyuan Xu
// Date : 2015-08-05
/**********************************************************************************
*
* You are given a string, S, and a list of words, L, that are all of the same length.
* Find all starting indices of substring(s) in S that is a concatenation of each word
* in L exactly once and without any intervening characters.
*
* For example, given:
* S: "barfoothefoobarman"
* L: ["foo", "bar"]
*
* You should return the indices: [0,9].
* (order does not matter).
*
*
**********************************************************************************/
//store words in map (straightforwad solution)
//768ms
class Solution1 {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
unordered_map<string, int> map;
for (auto s : words) {
map[s]++;
}
int wordLen = words[0].size();
int windowLen = wordLen * words.size();
for (int i = 0; i < s.length() - windowLen + 1; i++) {
unordered_map<string, int> count;
for (int j = 0; j < words.size(); j++) {
string word = s.substr(i + j*wordLen, wordLen);
if (map.find(word) != map.end()) {
count[word]++;
if (count[word] > map[word])
break;
if (j == words.size() - 1) {
res.push_back(i);
}
}
else break;
}
}
return res;
}
};
class Solution2 {
public:
vector<int> findSubstring(string s, vector<string>& words) {
unordered_map<string, int> counts;
for (string word : words)
counts[word]++;
int n = s.length(), num = words.size(), len = words[0].length();
vector<int> indexes;
for (int i = 0; i < n - num * len + 1; i++) {
unordered_map<string, int> seen;
int j = 0;
for (; j < num; j++) {
string word = s.substr(i + j * len, len);
if (counts.find(word) != counts.end()) {
seen[word]++;
if (seen[word] > counts[word])
break;
}
else break;
}
if (j == num) indexes.push_back(i);
}
return indexes;
}
};
<commit_msg>Update substringWithConcatenationOfAllWords.cpp<commit_after>// Source : https://leetcode.com/problems/substring-with-concatenation-of-all-words/
// Author : Siyuan Xu
// Date : 2015-08-05
/**********************************************************************************
*
* You are given a string, S, and a list of words, L, that are all of the same length.
* Find all starting indices of substring(s) in S that is a concatenation of each word
* in L exactly once and without any intervening characters.
*
* For example, given:
* S: "barfoothefoobarman"
* L: ["foo", "bar"]
*
* You should return the indices: [0,9].
* (order does not matter).
*
*
**********************************************************************************/
//store words in map (straightforwad solution)
//768ms
class Solution1 {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> res;
unordered_map<string, int> map;
for (auto s : words) {
map[s]++;
}
int wordLen = words[0].size();
int windowLen = wordLen * words.size();
for (int i = 0; i < s.length() - windowLen + 1; i++) {
unordered_map<string, int> count;
for (int j = 0; j < words.size(); j++) {
string word = s.substr(i + j*wordLen, wordLen);
if (map.find(word) != map.end()) {
count[word]++;
if (count[word] > map[word])
break;
if (j == words.size() - 1) {
res.push_back(i);
}
}
else break;
}
}
return res;
}
};
class Solution2 {
public:
vector<int> findSubstring(string s, vector<string>& words) {
unordered_map<string, int> counts;
for (string word : words)
counts[word]++;
int n = s.length(), num = words.size(), len = words[0].length();
vector<int> indexes;
for (int i = 0; i < n - num * len + 1; i++) {
unordered_map<string, int> seen;
int j = 0;
for (; j < num; j++) {
string word = s.substr(i + j * len, len);
if (counts.find(word) != counts.end()) {
seen[word]++;
if (seen[word] > counts[word])
break;
}
else break;
}
if (j == num) indexes.push_back(i);
}
return indexes;
}
};
//better solution
//https://leetcode.com/discuss/22289/my-ac-c-code-o-n-complexity-26ms
class Solution {
// The general idea:
// Construct a hash function f for L, f: vector<string> -> int,
// Then use the return value of f to check whether a substring is a concatenation
// of all words in L.
// f has two levels, the first level is a hash function f1 for every single word in L.
// f1 : string -> double
// So with f1, L is converted into a vector of float numbers
// Then another hash function f2 is defined to convert a vector of doubles into a single int.
// Finally f(L) := f2(f1(L))
// To obtain lower complexity, we require f1 and f2 can be computed through moving window.
// The following corner case also needs to be considered:
// f2(f1(["ab", "cd"])) != f2(f1(["ac", "bd"]))
// There are many possible options for f2 and f1.
// The following code only shows one possibility (probably not the best),
// f2 is the function "hash" in the class,
// f1([a1, a2, ... , an]) := int( decimal_part(log(a1) + log(a2) + ... + log(an)) * 1000000000 )
public:
// The complexity of this function is O(nW).
double hash(double f, double code[], string &word) {
double result = 0.;
for (auto &c : word) result = result * f + code[c];
return result;
}
vector<int> findSubstring(string S, vector<string> &L) {
uniform_real_distribution<double> unif(0., 1.);
default_random_engine seed;
double code[128];
for (auto &d : code) d = unif(seed);
double f = unif(seed) / 5. + 0.8;
double value = 0;
// The complexity of the following for loop is O(L.size( ) * nW).
for (auto &str : L) value += log(hash(f, code, str));
int unit = 1e9;
int key = (value-floor(value))*unit;
int nS = S.size(), nL = L.size(), nW = L[0].size();
double fn = pow(f, nW-1.);
vector<int> result;
if (nS < nW) return result;
vector<double> values(nS-nW+1);
string word(S.begin(), S.begin()+nW);
values[0] = hash(f, code, word);
// Use a moving window to hash every word with length nW in S to a float number,
// which is stored in vector values[]
// The complexity of this step is O(nS).
for (int i=1; i<=nS-nW; ++i) values[i] = (values[i-1] - code[S[i-1]]*fn)*f + code[S[i+nW-1]];
// This for loop will run nW times, each iteration has a complexity O(nS/nW)
// So the overall complexity is O(nW * (nS / nW)) = O(nS)
for (int i=0; i<nW; ++i) {
int j0=i, j1=i, k=0;
double sum = 0.;
// Use a moving window to hash every L.size() continuous words with length nW in S.
// This while loop will terminate within nS/nW iterations since the increasement of j1 is nW,
// So the complexity of this while loop is O(nS / nW).
while(j1<=nS-nW) {
sum += log(values[j1]);
++k;
j1 += nW;
if (k==nL) {
int key1 = (sum-floor(sum)) * unit;
if (key1==key) result.push_back(j0);
sum -= log(values[j0]);
--k;
j0 += nW;
}
}
}
return result;
}
};
<|endoftext|> |
<commit_before>#include <cpp-pcp-client/connector/client_metadata.hpp>
#include <cpp-pcp-client/connector/errors.hpp>
#include <leatherman/util/scope_exit.hpp>
#define LEATHERMAN_LOGGING_NAMESPACE CPP_PCP_CLIENT_LOGGING_PREFIX".client_metadata"
#include <leatherman/logging/logging.hpp>
#include <openssl/x509v3.h>
#include <openssl/ssl.h>
#include <stdio.h> // std::fopen
namespace PCPClient {
// Get rid of OSX 10.7 and greater deprecation warnings.
#if defined(__APPLE__) && defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#endif
static const std::string PCP_URI_SCHEME { "pcp://" };
// TODO(ale): consider moving the SSL functions elsewhere
void validatePrivateKeyCertPair(const std::string& key, const std::string& crt) {
auto ctx = SSL_CTX_new(SSLv23_method());
leatherman::util::scope_exit ctx_cleaner {
[ctx]() { SSL_CTX_free(ctx); }
};
if ( ctx == nullptr ) {
throw connection_config_error { "failed to create SSL context" };
}
if ( SSL_CTX_use_certificate_file(ctx, crt.c_str(), SSL_FILETYPE_PEM) <= 0 ) {
throw connection_config_error { "failed to open cert" };
}
if ( SSL_CTX_use_PrivateKey_file(ctx, key.c_str(), SSL_FILETYPE_PEM) <= 0 ) {
throw connection_config_error { "failed to load private key" };
}
if ( !SSL_CTX_check_private_key(ctx) ) {
throw connection_config_error { "mismatch between private key and cert " };
}
}
std::string getCommonNameFromCert(const std::string& client_crt_path) {
std::unique_ptr<std::FILE, int(*)(std::FILE*)> fp {
std::fopen(client_crt_path.data(), "r"), std::fclose };
if (fp == nullptr) {
throw connection_config_error { "certificate file '" + client_crt_path
+ "' does not exist" };
}
std::unique_ptr<X509, void(*)(X509*)> cert {
PEM_read_X509(fp.get(), NULL, NULL, NULL), X509_free };
if (cert == nullptr) {
throw connection_config_error { "certificate file '" + client_crt_path
+ "' is invalid" };
}
auto subj = X509_get_subject_name(cert.get());
auto name_entry = X509_NAME_get_entry(subj, 0);
if (name_entry == nullptr) {
throw connection_config_error { "failed to retrieve the client common "
"name from " + client_crt_path };
}
ASN1_STRING* asn1_name = X509_NAME_ENTRY_get_data(name_entry);
unsigned char* name_ptr = ASN1_STRING_data(asn1_name);
int name_size = ASN1_STRING_length(asn1_name);
return std::string { name_ptr, name_ptr + name_size };
}
#if defined(__APPLE__) && defined(__clang__)
#pragma clang diagnostic pop
#endif
ClientMetadata::ClientMetadata(const std::string& _client_type,
const std::string& _ca,
const std::string& _crt,
const std::string& _key)
: ca { _ca },
crt { _crt },
key { _key },
client_type { _client_type },
common_name { getCommonNameFromCert(crt) },
uri { PCP_URI_SCHEME + common_name + "/" + client_type } {
LOG_INFO("Retrieved common name from the certificate and determined "
"the client URI: %1%", uri);
validatePrivateKeyCertPair(key, crt);
LOG_INFO("Validated the private key / certificate pair");
}
} // namespace PCPClient
<commit_msg>(PCP-5) Add log messages to SSL functions<commit_after>#include <cpp-pcp-client/connector/client_metadata.hpp>
#include <cpp-pcp-client/connector/errors.hpp>
#include <leatherman/util/scope_exit.hpp>
#define LEATHERMAN_LOGGING_NAMESPACE CPP_PCP_CLIENT_LOGGING_PREFIX".client_metadata"
#include <leatherman/logging/logging.hpp>
#include <openssl/x509v3.h>
#include <openssl/ssl.h>
#include <stdio.h> // std::fopen
namespace PCPClient {
// Get rid of OSX 10.7 and greater deprecation warnings.
#if defined(__APPLE__) && defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#endif
static const std::string PCP_URI_SCHEME { "pcp://" };
// TODO(ale): consider moving the SSL functions elsewhere
void validatePrivateKeyCertPair(const std::string& key, const std::string& crt) {
LOG_TRACE("About to validate private key / certificate pair: '%1%' / '%2%'",
key, crt);
auto ctx = SSL_CTX_new(SSLv23_method());
leatherman::util::scope_exit ctx_cleaner {
[ctx]() { SSL_CTX_free(ctx); }
};
if ( ctx == nullptr ) {
throw connection_config_error { "failed to create SSL context" };
}
if ( SSL_CTX_use_certificate_file(ctx, crt.c_str(), SSL_FILETYPE_PEM) <= 0 ) {
LOG_TRACE("Created SSL context");
throw connection_config_error { "failed to open cert" };
}
if ( SSL_CTX_use_PrivateKey_file(ctx, key.c_str(), SSL_FILETYPE_PEM) <= 0 ) {
LOG_TRACE("Certificate loaded");
throw connection_config_error { "failed to load private key" };
}
if ( !SSL_CTX_check_private_key(ctx) ) {
LOG_TRACE("Private key loaded");
throw connection_config_error { "mismatch between private key and cert " };
}
LOG_TRACE("Private key / certificate pair has been successfully validated");
}
std::string getCommonNameFromCert(const std::string& crt) {
LOG_TRACE("Retrieving client name from certificate '%1%'", crt);
std::unique_ptr<std::FILE, int(*)(std::FILE*)> fp {
std::fopen(crt.data(), "r"), std::fclose };
if (fp == nullptr) {
throw connection_config_error { "certificate file '" + crt
+ "' does not exist" };
}
std::unique_ptr<X509, void(*)(X509*)> cert {
PEM_read_X509(fp.get(), NULL, NULL, NULL), X509_free };
if (cert == nullptr) {
throw connection_config_error { "certificate file '" + crt
+ "' is invalid" };
}
auto subj = X509_get_subject_name(cert.get());
auto name_entry = X509_NAME_get_entry(subj, 0);
if (name_entry == nullptr) {
throw connection_config_error { "failed to retrieve the client common "
"name from " + crt };
}
ASN1_STRING* asn1_name = X509_NAME_ENTRY_get_data(name_entry);
unsigned char* name_ptr = ASN1_STRING_data(asn1_name);
int name_size = ASN1_STRING_length(asn1_name);
return std::string { name_ptr, name_ptr + name_size };
}
#if defined(__APPLE__) && defined(__clang__)
#pragma clang diagnostic pop
#endif
ClientMetadata::ClientMetadata(const std::string& _client_type,
const std::string& _ca,
const std::string& _crt,
const std::string& _key)
: ca { _ca },
crt { _crt },
key { _key },
client_type { _client_type },
common_name { getCommonNameFromCert(crt) },
uri { PCP_URI_SCHEME + common_name + "/" + client_type } {
LOG_INFO("Retrieved common name from the certificate and determined "
"the client URI: %1%", uri);
validatePrivateKeyCertPair(key, crt);
LOG_INFO("Validated the private key / certificate pair");
}
} // namespace PCPClient
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Nokia Corporation and its Subsidiary(-ies) 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."
** $QT_END_LICENSE$
**
****************************************************************************/
#include "windows.h"
#include <QApplication>
#include "mainwindow.h"
#ifdef WIN32_DLL
__declspec(dllimport) boolean MemTest;
/*gvc.lib cgraph.lib*/
#ifdef WITH_CGRAPH
#pragma comment( lib, "cgraph.lib" )
#else
#pragma comment( lib, "graph.lib" )
#endif
#pragma comment( lib, "gvc.lib" )
#endif
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(mdi);
QApplication app(argc, argv);
MainWindow mainWin;
mainWin.show();
return app.exec();
}
<commit_msg>Wrap windows.h in #ifdef WINDOWS<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "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 Nokia Corporation and its Subsidiary(-ies) 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."
** $QT_END_LICENSE$
**
****************************************************************************/
#ifdef WIN32_DLL
#include "windows.h"
#endif
#include <QApplication>
#include "mainwindow.h"
#ifdef WIN32_DLL
__declspec(dllimport) boolean MemTest;
/*gvc.lib cgraph.lib*/
#ifdef WITH_CGRAPH
#pragma comment( lib, "cgraph.lib" )
#else
#pragma comment( lib, "graph.lib" )
#endif
#pragma comment( lib, "gvc.lib" )
#endif
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(mdi);
QApplication app(argc, argv);
MainWindow mainWin;
mainWin.show();
return app.exec();
}
<|endoftext|> |
<commit_before>/*
* -------------
* Dark Oberon
* -------------
*
* An advanced strategy game.
*
* Copyright (C) 2002 - 2005 Valeria Sventova, Jiri Krejsa, Peter Knut,
* Martin Kosalko, Marian Cerny, Michal Kral
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (see docs/gpl.txt) as
* published by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*/
/**
* @file dodata.cpp
*
* Resources functions.
*
* @author Peter Knut
*
* @date 2003, 2004
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "doconfig.h"
#include "dodata.h"
#include "doengine.h"
#include "domouse.h"
#include "tga.h"
//=========================================================================
// Defines
//=========================================================================
// sound types
#define DAT_ST_MODULE -1
#define DAT_ST_SAMPLE 0
#define DAT_ST_STREAM 1
//=========================================================================
// Global variables
//=========================================================================
TTEX_TABLE fonts_table; //!< Textures used by fonts.
TTEX_TABLE gui_table; //!< Common texures used for gui objects.
#if SOUND
TSND_TABLE sounds_table; //!< Common sounds used in menu and game.
#endif
GLFfont *font0 = NULL; //!< Basic font.
//=========================================================================
// Useful Methods.
//=========================================================================
bool fReadString(char **txt, FILE *fr)
{
unsigned char len = 0;
fread(&len, sizeof(len), 1, fr);
if (len) {
*txt = NEW char[len+1];
fread(*txt, sizeof(char), len, fr);
(*txt)[len] = 0;
}
return (len > 0);
}
//=========================================================================
// TTEX_TABLE
//=========================================================================
/**
* Load textures from *.dat.
*
* @param file_name Filename of the dat file.
*
* @return @c true on success, @c false otherwise.
*/
bool TTEX_TABLE::Load(const char *file_name, int mag_filter, int min_filter)
{
FILE *fr;
Info(LogMsg("Loading textures from '%s'", file_name));
if (!(fr = fopen(file_name, "rb"))) {
Error(LogMsg("Can not open file '%s'", file_name));
return false;
}
TGA_INFO tga;
int format, iformat;
char header[257];
T_BYTE version;
long textures_seek = 0;
int tid, gid; // texture id, group id
TGUI_TEXTURE *tex;
int atime; // animation time [miliseconds]
T_BYTE ttype; // texture type
T_BYTE hcount; // horizontal frames count
T_BYTE vcount; // vertical frames count
int pointx, pointy;
unsigned int dsize; // data size
// file header
fread(header, sizeof(char), strlen(DAT_FILE_HEADER), fr);
header[strlen(DAT_FILE_HEADER)] = 0;
if (strcmp(header, DAT_FILE_HEADER)) {
fclose(fr);
return false;
}
// file version
fread(&version, sizeof(version), 1, fr);
if (version > DAT_MAX_VERSION || version < DAT_MIN_VERSION) {
Error(LogMsg("Version of data file '%s' is not allowed", file_name));
fclose(fr);
return false;
}
// seeks
fread(&textures_seek, sizeof(textures_seek), 1, fr);
if (!textures_seek) {
Error(LogMsg("Data file '%s' does not contain any textures", file_name));
fclose(fr);
return false;
}
glEnable(GL_TEXTURE_2D);
// texture groups table
fseek(fr, textures_seek, SEEK_SET);
fread(&count, sizeof(count), 1, fr);
if (!(groups = NEW TTEX_GROUP[count])) {
Critical(LogMsg("Can not allocate memory for texture groups table from '%s'", file_name));
fclose(fr);
return false;
}
// texture groups
for (gid = 0; gid < count; gid++) {
fReadString(&groups[gid].name, fr);
fread(&groups[gid].count, sizeof(groups[gid].count), 1, fr);
if (!(groups[gid].textures = NEW TGUI_TEXTURE[groups[gid].count])) {
Critical(LogMsg("Can not allocate memory for texture table from '%s'", file_name));
fclose(fr);
return false;
}
// textures
for (tid = 0; tid < groups[gid].count; tid++) {
tex = groups[gid].textures + tid;
// read values from file
fReadString(&tex->id, fr);
fread(&hcount, sizeof(hcount), 1, fr);
fread(&vcount, sizeof(vcount), 1, fr);
fread(&atime, sizeof(atime), 1, fr);
fread(&pointx, sizeof(pointx), 1, fr);
fread(&pointy, sizeof(pointy), 1, fr);
fread(&ttype, sizeof(ttype), 1, fr);
fread(&dsize, sizeof(dsize), 1, fr);
// generate id for texture
glGenTextures(1, &tex->gl_id);
// read TGA image
if (!tgaRead(fr, &tga, TGA_RESCALE)) {
Error(LogMsg("Error reading TGA data from '%s'", file_name));
return false;
}
if (tga.bytesperpixel == 3) format = iformat = GL_RGB;
else format = iformat = GL_RGBA;
// generate texture
glBindTexture(GL_TEXTURE_2D, tex->gl_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);
// upload to memory
if (min_filter == GL_NEAREST || min_filter == GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, iformat, tga.width, tga.height, 0, format, GL_UNSIGNED_BYTE, (void *)tga.data);
else gluBuild2DMipmaps(GL_TEXTURE_2D, iformat, tga.width, tga.height, format, GL_UNSIGNED_BYTE, (void *)tga.data);
// fill texture
tex->type = (TGUI_TEX_TYPE)ttype;
tex->point_x = -(GLfloat)pointx;
tex->point_y = -(GLfloat)pointy;
tex->h_count = hcount;
tex->v_count = vcount;
tex->frames_count = hcount * vcount;
tex->frame_width = tga.original_width / hcount;
tex->frame_height = tga.original_height / vcount;
tex->width = tga.width;
tex->height = tga.height;
tex->frame_time = (double)atime / (1000 * tex->frames_count);
// free memory
free(tga.data);
tga.data = NULL;
} // for tid
} // for gid
fclose(fr);
return true;
}
//=========================================================================
// TSND_TABLE
//=========================================================================
#if SOUND
bool TSND_TABLE::Load(const char *file_name)
{
if (!file_name) return false;
Info(LogMsg("Loading sounds from '%s'", file_name));
char header[257];
T_BYTE version;
int sounds_seek = 0;
FILE *fr;
TMODULE *music = NULL;
TSAMPLE *sample = NULL;
TSTREAM *stream = NULL;
TSOUND *snd;
int sid;
char sformat;
char stype;
int dsize;
long dseek;
char *data;
char *id;
Clear();
if (!(fr = fopen(file_name, "rb"))) {
Error(LogMsg("Can not open file '%s'", file_name));
return false;
}
// file header
fread(header, sizeof(char), strlen(DAT_FILE_HEADER), fr);
header[strlen(DAT_FILE_HEADER)] = 0;
if (strcmp(header, DAT_FILE_HEADER)) {
fclose(fr);
return false;
}
// file version
fread(&version, sizeof(version), 1, fr);
if (version > DAT_MAX_VERSION || version < DAT_MIN_VERSION) {
Error(LogMsg("Version of data file '%s' is not allowed", file_name));
fclose(fr);
return false;
}
// seeks
fread(&sounds_seek, sizeof(sounds_seek), 1, fr); // textures
if (version > 2) fread(&sounds_seek, sizeof(sounds_seek), 1, fr); // sounds
else sounds_seek = 0;
if (!sounds_seek) {
Error(LogMsg("Data file '%s' does not contain any sounds", file_name));
fclose(fr);
return false;
}
// sounds table
fseek(fr, sounds_seek, SEEK_SET);
fread(&count, sizeof(count), 1, fr);
if (!(sounds = NEW TSOUND *[count])) {
Critical(LogMsg("Can not allocate memory for sounds table from '%s'", file_name));
fclose(fr);
return false;
}
for (sid = 0; sid < count; sid++) sounds[sid] = NULL;
// sounds
for (sid = 0; sid < count; sid++) {
music = NULL;
sample = NULL;
data = NULL;
// read values from file
fReadString(&id, fr);
fread(&sformat, sizeof(sformat), 1, fr);
fread(&stype, sizeof(stype), 1, fr);
fread(&dsize, sizeof(dsize), 1, fr);
dseek = ftell(fr);
switch (stype) {
case DAT_ST_MODULE:
music = NEW TMODULE();
sounds[sid] = music;
break;
case DAT_ST_STREAM:
stream = NEW TSTREAM();
sounds[sid] = stream;
break;
case DAT_ST_SAMPLE:
default:
sample = NEW TSAMPLE();
sounds[sid] = sample;
break;
}
snd = sounds[sid];
// fill sound
snd->id = id;
snd->format = (TSOUND_FORMAT)sformat;
// load data
if (stype != DAT_ST_STREAM) {
if (!(data = NEW char[dsize])) {
Critical(LogMsg("Can not allocate memory for sound data from '%s'", file_name));
Clear();
return false;
}
fread(data, sizeof(char), dsize, fr);
}
else fseek(fr, dsize, SEEK_CUR);
// load sound
if (sample)
sample->Load(data, dsize);
else if (music)
music->Load(data, dsize);
else if (stream)
stream->Load(file_name, dseek, dsize);
// free data
if (data) delete[] data;
}
fclose(fr);
return true;
}
void TSND_TABLE::Clear(void) {
int i;
if (sounds) {
for (i = 0; i < count; i++)
if (sounds[i]) delete sounds[i];
delete[] sounds;
sounds = NULL;
}
count = 0;
};
TSOUND * TSND_TABLE::GetSound(char * id) {
int i;
for (i = 0; i < count; i++)
if (!(strcmp(id, sounds[i]->id))) return sounds[i];
return NULL;
}
#endif
//=========================================================================
// Data
//=========================================================================
/**
* Load textures.
*/
bool LoadData(void)
{
Info("Loading data");
if (fonts_table.Load(DAT_FONTS_NAME, config.tex_mag_filter, config.tex_min_filter) &&
gui_table.Load(DAT_GUI_NAME, GL_LINEAR, GL_LINEAR) &&
mouse.LoadData(DAT_CURSORS_NAME)
#if SOUND
&& sounds_table.Load(DAT_GUI_NAME)
#endif
)
{
#if SOUND
PrepareSounds();
#endif
return true;
}
else {
DeleteData();
Critical("Can not load data.");
return false;
}
}
/**
* Delete textures sets.
*/
void DeleteData(void)
{
fonts_table.Clear();
mouse.DeleteData();
gui_table.Clear();
#if SOUND
sounds_table.Clear();
#endif
}
//=========================================================================
// Fonts data
//=========================================================================
/**
* Initializes the fonts. Creates fonts.
*
* @return @c true on success, @c false otherwise.
*/
bool CreateFonts(void)
{
// common font
if ((font0 = glfNewFont(fonts_table.groups[DAT_TGID_BASIC_FONT].textures[0].gl_id,
128, 256,
16, 12,
8, 16, 7,
config.scr_width, config.scr_height)))
{
glfSetFontBase(font0, 32, 32 - 96);
return true;
}
else {
Critical("Can not create fonts");
return false;
}
}
/**
* Destroys fonts structures.
*/
void DestroyFonts(void)
{
glfDeleteFont(font0);
}
//=========================================================================
// END
//=========================================================================
// vim:ts=2:sw=2:et:
<commit_msg>for the texture_seek size issue<commit_after>/*
* -------------
* Dark Oberon
* -------------
*
* An advanced strategy game.
*
* Copyright (C) 2002 - 2005 Valeria Sventova, Jiri Krejsa, Peter Knut,
* Martin Kosalko, Marian Cerny, Michal Kral
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (see docs/gpl.txt) as
* published by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*/
/**
* @file dodata.cpp
*
* Resources functions.
*
* @author Peter Knut
*
* @date 2003, 2004
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "doconfig.h"
#include "dodata.h"
#include "doengine.h"
#include "domouse.h"
#include "tga.h"
//=========================================================================
// Defines
//=========================================================================
// sound types
#define DAT_ST_MODULE -1
#define DAT_ST_SAMPLE 0
#define DAT_ST_STREAM 1
//=========================================================================
// Global variables
//=========================================================================
TTEX_TABLE fonts_table; //!< Textures used by fonts.
TTEX_TABLE gui_table; //!< Common texures used for gui objects.
#if SOUND
TSND_TABLE sounds_table; //!< Common sounds used in menu and game.
#endif
GLFfont *font0 = NULL; //!< Basic font.
//=========================================================================
// Useful Methods.
//=========================================================================
bool fReadString(char **txt, FILE *fr)
{
unsigned char len = 0;
fread(&len, sizeof(len), 1, fr);
if (len) {
*txt = NEW char[len+1];
fread(*txt, sizeof(char), len, fr);
(*txt)[len] = 0;
}
return (len > 0);
}
//=========================================================================
// TTEX_TABLE
//=========================================================================
/**
* Load textures from *.dat.
*
* @param file_name Filename of the dat file.
*
* @return @c true on success, @c false otherwise.
*/
bool TTEX_TABLE::Load(const char *file_name, int mag_filter, int min_filter)
{
FILE *fr;
Info(LogMsg("Loading textures from '%s'", file_name));
if (!(fr = fopen(file_name, "rb"))) {
Error(LogMsg("Can not open file '%s'", file_name));
return false;
}
TGA_INFO tga;
int format, iformat;
char header[257];
T_BYTE version;
long textures_seek = 0;
int tid, gid; // texture id, group id
TGUI_TEXTURE *tex;
int atime; // animation time [miliseconds]
T_BYTE ttype; // texture type
T_BYTE hcount; // horizontal frames count
T_BYTE vcount; // vertical frames count
int pointx, pointy;
unsigned int dsize; // data size
// file header
fread(header, sizeof(char), strlen(DAT_FILE_HEADER), fr);
header[strlen(DAT_FILE_HEADER)] = 0;
if (strcmp(header, DAT_FILE_HEADER)) {
fclose(fr);
return false;
}
// file version
fread(&version, sizeof(version), 1, fr);
if (version > DAT_MAX_VERSION || version < DAT_MIN_VERSION) {
Error(LogMsg("Version of data file '%s' is not allowed", file_name));
fclose(fr);
return false;
}
// seeks
fread(&textures_seek, 4, 1, fr);
if (!textures_seek) {
Error(LogMsg("Data file '%s' does not contain any textures", file_name));
fclose(fr);
return false;
}
glEnable(GL_TEXTURE_2D);
// texture groups table
fseek(fr, textures_seek, SEEK_SET);
fread(&count, sizeof(count), 1, fr);
if (!(groups = NEW TTEX_GROUP[count])) {
Critical(LogMsg("Can not allocate memory for texture groups table from '%s'", file_name));
fclose(fr);
return false;
}
// texture groups
for (gid = 0; gid < count; gid++) {
fReadString(&groups[gid].name, fr);
fread(&groups[gid].count, sizeof(groups[gid].count), 1, fr);
if (!(groups[gid].textures = NEW TGUI_TEXTURE[groups[gid].count])) {
Critical(LogMsg("Can not allocate memory for texture table from '%s'", file_name));
fclose(fr);
return false;
}
// textures
for (tid = 0; tid < groups[gid].count; tid++) {
tex = groups[gid].textures + tid;
// read values from file
fReadString(&tex->id, fr);
fread(&hcount, sizeof(hcount), 1, fr);
fread(&vcount, sizeof(vcount), 1, fr);
fread(&atime, sizeof(atime), 1, fr);
fread(&pointx, sizeof(pointx), 1, fr);
fread(&pointy, sizeof(pointy), 1, fr);
fread(&ttype, sizeof(ttype), 1, fr);
fread(&dsize, sizeof(dsize), 1, fr);
// generate id for texture
glGenTextures(1, &tex->gl_id);
// read TGA image
if (!tgaRead(fr, &tga, TGA_RESCALE)) {
Error(LogMsg("Error reading TGA data from '%s'", file_name));
return false;
}
if (tga.bytesperpixel == 3) format = iformat = GL_RGB;
else format = iformat = GL_RGBA;
// generate texture
glBindTexture(GL_TEXTURE_2D, tex->gl_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);
// upload to memory
if (min_filter == GL_NEAREST || min_filter == GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, iformat, tga.width, tga.height, 0, format, GL_UNSIGNED_BYTE, (void *)tga.data);
else gluBuild2DMipmaps(GL_TEXTURE_2D, iformat, tga.width, tga.height, format, GL_UNSIGNED_BYTE, (void *)tga.data);
// fill texture
tex->type = (TGUI_TEX_TYPE)ttype;
tex->point_x = -(GLfloat)pointx;
tex->point_y = -(GLfloat)pointy;
tex->h_count = hcount;
tex->v_count = vcount;
tex->frames_count = hcount * vcount;
tex->frame_width = tga.original_width / hcount;
tex->frame_height = tga.original_height / vcount;
tex->width = tga.width;
tex->height = tga.height;
tex->frame_time = (double)atime / (1000 * tex->frames_count);
// free memory
free(tga.data);
tga.data = NULL;
} // for tid
} // for gid
fclose(fr);
return true;
}
//=========================================================================
// TSND_TABLE
//=========================================================================
#if SOUND
bool TSND_TABLE::Load(const char *file_name)
{
if (!file_name) return false;
Info(LogMsg("Loading sounds from '%s'", file_name));
char header[257];
T_BYTE version;
int sounds_seek = 0;
FILE *fr;
TMODULE *music = NULL;
TSAMPLE *sample = NULL;
TSTREAM *stream = NULL;
TSOUND *snd;
int sid;
char sformat;
char stype;
int dsize;
long dseek;
char *data;
char *id;
Clear();
if (!(fr = fopen(file_name, "rb"))) {
Error(LogMsg("Can not open file '%s'", file_name));
return false;
}
// file header
fread(header, sizeof(char), strlen(DAT_FILE_HEADER), fr);
header[strlen(DAT_FILE_HEADER)] = 0;
if (strcmp(header, DAT_FILE_HEADER)) {
fclose(fr);
return false;
}
// file version
fread(&version, sizeof(version), 1, fr);
if (version > DAT_MAX_VERSION || version < DAT_MIN_VERSION) {
Error(LogMsg("Version of data file '%s' is not allowed", file_name));
fclose(fr);
return false;
}
// seeks
fread(&sounds_seek, sizeof(sounds_seek), 1, fr); // textures
if (version > 2) fread(&sounds_seek, sizeof(sounds_seek), 1, fr); // sounds
else sounds_seek = 0;
if (!sounds_seek) {
Error(LogMsg("Data file '%s' does not contain any sounds", file_name));
fclose(fr);
return false;
}
// sounds table
fseek(fr, sounds_seek, SEEK_SET);
fread(&count, sizeof(count), 1, fr);
if (!(sounds = NEW TSOUND *[count])) {
Critical(LogMsg("Can not allocate memory for sounds table from '%s'", file_name));
fclose(fr);
return false;
}
for (sid = 0; sid < count; sid++) sounds[sid] = NULL;
// sounds
for (sid = 0; sid < count; sid++) {
music = NULL;
sample = NULL;
data = NULL;
// read values from file
fReadString(&id, fr);
fread(&sformat, sizeof(sformat), 1, fr);
fread(&stype, sizeof(stype), 1, fr);
fread(&dsize, sizeof(dsize), 1, fr);
dseek = ftell(fr);
switch (stype) {
case DAT_ST_MODULE:
music = NEW TMODULE();
sounds[sid] = music;
break;
case DAT_ST_STREAM:
stream = NEW TSTREAM();
sounds[sid] = stream;
break;
case DAT_ST_SAMPLE:
default:
sample = NEW TSAMPLE();
sounds[sid] = sample;
break;
}
snd = sounds[sid];
// fill sound
snd->id = id;
snd->format = (TSOUND_FORMAT)sformat;
// load data
if (stype != DAT_ST_STREAM) {
if (!(data = NEW char[dsize])) {
Critical(LogMsg("Can not allocate memory for sound data from '%s'", file_name));
Clear();
return false;
}
fread(data, sizeof(char), dsize, fr);
}
else fseek(fr, dsize, SEEK_CUR);
// load sound
if (sample)
sample->Load(data, dsize);
else if (music)
music->Load(data, dsize);
else if (stream)
stream->Load(file_name, dseek, dsize);
// free data
if (data) delete[] data;
}
fclose(fr);
return true;
}
void TSND_TABLE::Clear(void) {
int i;
if (sounds) {
for (i = 0; i < count; i++)
if (sounds[i]) delete sounds[i];
delete[] sounds;
sounds = NULL;
}
count = 0;
};
TSOUND * TSND_TABLE::GetSound(char * id) {
int i;
for (i = 0; i < count; i++)
if (!(strcmp(id, sounds[i]->id))) return sounds[i];
return NULL;
}
#endif
//=========================================================================
// Data
//=========================================================================
/**
* Load textures.
*/
bool LoadData(void)
{
Info("Loading data");
if (fonts_table.Load(DAT_FONTS_NAME, config.tex_mag_filter, config.tex_min_filter) &&
gui_table.Load(DAT_GUI_NAME, GL_LINEAR, GL_LINEAR) &&
mouse.LoadData(DAT_CURSORS_NAME)
#if SOUND
&& sounds_table.Load(DAT_GUI_NAME)
#endif
)
{
#if SOUND
PrepareSounds();
#endif
return true;
}
else {
DeleteData();
Critical("Can not load data.");
return false;
}
}
/**
* Delete textures sets.
*/
void DeleteData(void)
{
fonts_table.Clear();
mouse.DeleteData();
gui_table.Clear();
#if SOUND
sounds_table.Clear();
#endif
}
//=========================================================================
// Fonts data
//=========================================================================
/**
* Initializes the fonts. Creates fonts.
*
* @return @c true on success, @c false otherwise.
*/
bool CreateFonts(void)
{
// common font
if ((font0 = glfNewFont(fonts_table.groups[DAT_TGID_BASIC_FONT].textures[0].gl_id,
128, 256,
16, 12,
8, 16, 7,
config.scr_width, config.scr_height)))
{
glfSetFontBase(font0, 32, 32 - 96);
return true;
}
else {
Critical("Can not create fonts");
return false;
}
}
/**
* Destroys fonts structures.
*/
void DestroyFonts(void)
{
glfDeleteFont(font0);
}
//=========================================================================
// END
//=========================================================================
// vim:ts=2:sw=2:et:
<|endoftext|> |
<commit_before>#include <glib.h>
#include <qpid/messaging/Message.h>
#include <qpid/messaging/Receiver.h>
#include <qpid/messaging/Sender.h>
#include <qpid/messaging/Session.h>
#include <qpid/messaging/Connection.h>
#include <gqpidmessage.h>
#include <iostream>
using namespace qpid::messaging;
struct _GQpidMessage
{
Message msg;
_GQpidMessage(const gchar *add): msg(add)
{
}
_GQpidMessage(Message &m): msg(m)
{
}
};
GQpidMessage*
g_qpid_message_new(gchar* text)
{
GQpidMessage *msg;
msg = new GQpidMessage (text);
return msg;
}
GQpidMessage*
g_qpid_message_new_from_msg(Message &m)
{
GQpidMessage *msg;
msg = new GQpidMessage (m);
return msg;
}
const gchar*
g_qpid_message_get_content(GQpidMessage *msg)
{
g_return_val_if_fail (msg != NULL, NULL);
std::string s = msg->msg.getContent();
return s.c_str();
}
void
g_qpid_message_send(GQpidMessage *msg, Sender &s)
{
g_return_if_fail (msg != NULL);
s.send(msg->msg);
return;
}
void
g_qpid_message_reject_session(GQpidMessage *msg, Session &s)
{
g_return_if_fail (msg != NULL);
s.reject(msg->msg);
return;
}
void
g_qpid_message_release_session(GQpidMessage *msg, Session &s)
{
g_return_if_fail (msg != NULL);
s.release(msg->msg);
return;
}
<commit_msg>gqpidmessage.cpp: API documentation added & format fixed.<commit_after>#include <glib.h>
#include <qpid/messaging/Message.h>
#include <qpid/messaging/Receiver.h>
#include <qpid/messaging/Sender.h>
#include <qpid/messaging/Session.h>
#include <qpid/messaging/Connection.h>
#include <gqpidmessage.h>
#include <iostream>
using namespace qpid::messaging;
struct _GQpidMessage
{
Message msg;
_GQpidMessage(const gchar *add): msg(add)
{
}
_GQpidMessage(Message &m): msg(m)
{
}
};
/**
* g_qpid_message_new:
* @text: the message text
*
* Creates a new message with the given text.
*
* Return value: a newly allocated #GQpidMessage.
* You must free it with g_qpid_message_free() when
* are finished with it.
**/
GQpidMessage*
g_qpid_message_new(gchar* text)
{
GQpidMessage *msg;
msg = new GQpidMessage (text);
return msg;
}
GQpidMessage*
g_qpid_message_new_from_msg(Message &m)
{
GQpidMessage *msg;
msg = new GQpidMessage (m);
return msg;
}
/**
* g_qpid_message_get_content:
* @msg: a #GQpidMessage* object
*
* Gets the content of the message.
*
* Return value: it returns the message string as gchar*.
**/
const gchar*
g_qpid_message_get_content(GQpidMessage *msg)
{
g_return_val_if_fail (msg != NULL, NULL);
std::string s = msg->msg.getContent();
return s.c_str();
}
void
g_qpid_message_send(GQpidMessage *msg, Sender &s)
{
g_return_if_fail (msg != NULL);
s.send(msg->msg);
return;
}
void
g_qpid_message_reject_session(GQpidMessage *msg, Session &s)
{
g_return_if_fail (msg != NULL);
s.reject(msg->msg);
return;
}
void
g_qpid_message_release_session(GQpidMessage *msg, Session &s)
{
g_return_if_fail (msg != NULL);
s.release(msg->msg);
return;
}
<|endoftext|> |
<commit_before>#include "kwm.h"
CFMachPortRef EventTap;
kwm_code KWMCode;
std::string KwmFilePath;
std::string HotkeySOFullFilePath;
uint32_t MaxDisplayCount = 5;
uint32_t ActiveDisplaysCount;
CGDirectDisplayID ActiveDisplays[5];
screen_info *Screen;
int CurrentSpace = 0;
int PrevSpace = -1;
std::vector<screen_info> DisplayLst;
std::vector<window_info> WindowLst;
std::vector<std::string> FloatingAppLst;
std::vector<int> FloatingWindowLst;
ProcessSerialNumber FocusedPSN;
window_info *FocusedWindow;
focus_option KwmFocusMode;
int KwmSplitMode = -1;
int MarkedWindowID = -1;
pthread_t BackgroundThread;
pthread_t DaemonThread;
pthread_mutex_t BackgroundLock;
CGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)
{
switch(Type)
{
case kCGEventTapDisabledByTimeout:
case kCGEventTapDisabledByUserInput:
{
DEBUG("Restarting Event Tap")
CGEventTapEnable(EventTap, true);
} break;
case kCGEventKeyDown:
{
CGEventFlags Flags = CGEventGetFlags(Event);
bool CmdKey = (Flags & kCGEventFlagMaskCommand) == kCGEventFlagMaskCommand;
bool AltKey = (Flags & kCGEventFlagMaskAlternate) == kCGEventFlagMaskAlternate;
bool CtrlKey = (Flags & kCGEventFlagMaskControl) == kCGEventFlagMaskControl;
bool ShiftKey = (Flags & kCGEventFlagMaskShift) == kCGEventFlagMaskShift;
CGKeyCode Keycode = (CGKeyCode)CGEventGetIntegerValueField(Event, kCGKeyboardEventKeycode);
std::string NewHotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());
if(NewHotkeySOFileTime != KWMCode.HotkeySOFileTime)
{
DEBUG("Reloading hotkeys.so")
UnloadKwmCode(&KWMCode);
KWMCode = LoadKwmCode();
}
if(KWMCode.IsValid)
{
// Hotkeys specific to Kwms functionality
if(KWMCode.KWMHotkeyCommands(CmdKey, CtrlKey, AltKey, Keycode))
return NULL;
// Capture custom hotkeys specified by the user
if(KWMCode.CustomHotkeyCommands(CmdKey, CtrlKey, AltKey, Keycode))
return NULL;
// Let system hotkeys pass through as normal
if(KWMCode.SystemHotkeyCommands(CmdKey, CtrlKey, AltKey, Keycode))
return Event;
int NewKeycode;
KWMCode.RemapKeys(Event, &CmdKey, &CtrlKey, &AltKey, &ShiftKey, Keycode, &NewKeycode);
if(NewKeycode != -1)
{
CGEventSetFlags(Event, 0);
if(CmdKey)
CGEventSetFlags(Event, kCGEventFlagMaskCommand);
if(AltKey)
CGEventSetFlags(Event, kCGEventFlagMaskAlternate);
if(CtrlKey)
CGEventSetFlags(Event, kCGEventFlagMaskControl);
if(ShiftKey)
CGEventSetFlags(Event, kCGEventFlagMaskShift);
CGEventSetIntegerValueField(Event, kCGKeyboardEventKeycode, NewKeycode);
}
}
if(KwmFocusMode == FocusModeAutofocus)
{
CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);
CGEventPostToPSN(&FocusedPSN, Event);
return NULL;
}
} break;
case kCGEventMouseMoved:
{
if(KwmFocusMode != FocusModeDisabled)
{
pthread_mutex_lock(&BackgroundLock);
FocusWindowBelowCursor();
pthread_mutex_unlock(&BackgroundLock);
}
} break;
}
return Event;
}
kwm_code LoadKwmCode()
{
kwm_code Code = {};
Code.HotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());
Code.KwmHotkeySO = dlopen(HotkeySOFullFilePath.c_str(), RTLD_LAZY);
if(Code.KwmHotkeySO)
{
Code.KWMHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "KWMHotkeyCommands");
Code.SystemHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "SystemHotkeyCommands");
Code.CustomHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "CustomHotkeyCommands");
Code.RemapKeys = (kwm_key_remap*) dlsym(Code.KwmHotkeySO, "RemapKeys");
}
else
{
DEBUG("LoadKwmCode() Could not open '" << HotkeySOFullFilePath << "'")
}
Code.IsValid = (Code.KWMHotkeyCommands && Code.SystemHotkeyCommands && Code.CustomHotkeyCommands && Code.RemapKeys);
return Code;
}
void UnloadKwmCode(kwm_code *Code)
{
if(Code->KwmHotkeySO)
dlclose(Code->KwmHotkeySO);
Code->HotkeySOFileTime = "";
Code->KWMHotkeyCommands = 0;
Code->SystemHotkeyCommands = 0;
Code->CustomHotkeyCommands = 0;
Code->RemapKeys = 0;
Code->IsValid = 0;
}
std::string KwmGetFileTime(const char *File)
{
struct stat attr;
stat(File, &attr);
return ctime(&attr.st_mtime);
}
void KwmRestart()
{
DEBUG("KWM Restarting..")
const char **ExecArgs = new const char*[2];
ExecArgs[0] = "kwm";
ExecArgs[1] = NULL;
std::string KwmBinPath = KwmFilePath + "/kwm";
execv(KwmBinPath.c_str(), (char**)ExecArgs);
}
void * KwmWindowMonitor(void*)
{
while(1)
{
if(KwmFocusMode != FocusModeDisabled)
{
pthread_mutex_lock(&BackgroundLock);
UpdateWindowTree();
pthread_mutex_unlock(&BackgroundLock);
}
usleep(200000);
}
}
void KwmInit()
{
if(!CheckPrivileges())
Fatal("Could not access OSX Accessibility!");
if (pthread_mutex_init(&BackgroundLock, NULL) != 0)
Fatal("Could not create mutex!");
if(KwmStartDaemon())
pthread_create(&DaemonThread, NULL, &KwmDaemonHandleConnectionBG, NULL);
else
Fatal("Kwm: Could not start daemon..");
KwmFilePath = getcwd(NULL, 0);
HotkeySOFullFilePath = KwmFilePath + "/hotkeys.so";
KwmFocusMode = FocusModeAutoraise;
KWMCode = LoadKwmCode();
GetActiveDisplays();
pthread_create(&BackgroundThread, NULL, &KwmWindowMonitor, NULL);
}
bool CheckPrivileges()
{
const void * Keys[] = { kAXTrustedCheckOptionPrompt };
const void * Values[] = { kCFBooleanTrue };
CFDictionaryRef Options;
Options = CFDictionaryCreate(kCFAllocatorDefault,
Keys, Values, sizeof(Keys) / sizeof(*Keys),
&kCFCopyStringDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
return AXIsProcessTrustedWithOptions(Options);
}
void Fatal(const std::string &Err)
{
std::cout << Err << std::endl;
exit(1);
}
int main(int argc, char **argv)
{
KwmInit();
CGEventMask EventMask;
CFRunLoopSourceRef RunLoopSource;
EventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventMouseMoved));
EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, EventMask, CGEventCallback, NULL);
if(!EventTap || !CGEventTapIsEnabled(EventTap))
Fatal("ERROR: Could not create event-tap!");
RunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, EventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), RunLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(EventTap, true);
CFRunLoopRun();
return 0;
}
<commit_msg>kwm now has an rc file used to load settings on startup<commit_after>#include "kwm.h"
CFMachPortRef EventTap;
kwm_code KWMCode;
std::string KwmFilePath;
std::string HotkeySOFullFilePath;
uint32_t MaxDisplayCount = 5;
uint32_t ActiveDisplaysCount;
CGDirectDisplayID ActiveDisplays[5];
screen_info *Screen;
int CurrentSpace = 0;
int PrevSpace = -1;
std::vector<screen_info> DisplayLst;
std::vector<window_info> WindowLst;
std::vector<std::string> FloatingAppLst;
std::vector<int> FloatingWindowLst;
ProcessSerialNumber FocusedPSN;
window_info *FocusedWindow;
focus_option KwmFocusMode;
int KwmSplitMode = -1;
int MarkedWindowID = -1;
pthread_t BackgroundThread;
pthread_t DaemonThread;
pthread_mutex_t BackgroundLock;
CGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)
{
switch(Type)
{
case kCGEventTapDisabledByTimeout:
case kCGEventTapDisabledByUserInput:
{
DEBUG("Restarting Event Tap")
CGEventTapEnable(EventTap, true);
} break;
case kCGEventKeyDown:
{
CGEventFlags Flags = CGEventGetFlags(Event);
bool CmdKey = (Flags & kCGEventFlagMaskCommand) == kCGEventFlagMaskCommand;
bool AltKey = (Flags & kCGEventFlagMaskAlternate) == kCGEventFlagMaskAlternate;
bool CtrlKey = (Flags & kCGEventFlagMaskControl) == kCGEventFlagMaskControl;
bool ShiftKey = (Flags & kCGEventFlagMaskShift) == kCGEventFlagMaskShift;
CGKeyCode Keycode = (CGKeyCode)CGEventGetIntegerValueField(Event, kCGKeyboardEventKeycode);
std::string NewHotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());
if(NewHotkeySOFileTime != KWMCode.HotkeySOFileTime)
{
DEBUG("Reloading hotkeys.so")
UnloadKwmCode(&KWMCode);
KWMCode = LoadKwmCode();
}
if(KWMCode.IsValid)
{
// Hotkeys specific to Kwms functionality
if(KWMCode.KWMHotkeyCommands(CmdKey, CtrlKey, AltKey, Keycode))
return NULL;
// Capture custom hotkeys specified by the user
if(KWMCode.CustomHotkeyCommands(CmdKey, CtrlKey, AltKey, Keycode))
return NULL;
// Let system hotkeys pass through as normal
if(KWMCode.SystemHotkeyCommands(CmdKey, CtrlKey, AltKey, Keycode))
return Event;
int NewKeycode;
KWMCode.RemapKeys(Event, &CmdKey, &CtrlKey, &AltKey, &ShiftKey, Keycode, &NewKeycode);
if(NewKeycode != -1)
{
CGEventSetFlags(Event, 0);
if(CmdKey)
CGEventSetFlags(Event, kCGEventFlagMaskCommand);
if(AltKey)
CGEventSetFlags(Event, kCGEventFlagMaskAlternate);
if(CtrlKey)
CGEventSetFlags(Event, kCGEventFlagMaskControl);
if(ShiftKey)
CGEventSetFlags(Event, kCGEventFlagMaskShift);
CGEventSetIntegerValueField(Event, kCGKeyboardEventKeycode, NewKeycode);
}
}
if(KwmFocusMode == FocusModeAutofocus)
{
CGEventSetIntegerValueField(Event, kCGKeyboardEventAutorepeat, 0);
CGEventPostToPSN(&FocusedPSN, Event);
return NULL;
}
} break;
case kCGEventMouseMoved:
{
if(KwmFocusMode != FocusModeDisabled)
{
pthread_mutex_lock(&BackgroundLock);
FocusWindowBelowCursor();
pthread_mutex_unlock(&BackgroundLock);
}
} break;
}
return Event;
}
kwm_code LoadKwmCode()
{
kwm_code Code = {};
Code.HotkeySOFileTime = KwmGetFileTime(HotkeySOFullFilePath.c_str());
Code.KwmHotkeySO = dlopen(HotkeySOFullFilePath.c_str(), RTLD_LAZY);
if(Code.KwmHotkeySO)
{
Code.KWMHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "KWMHotkeyCommands");
Code.SystemHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "SystemHotkeyCommands");
Code.CustomHotkeyCommands = (kwm_hotkey_commands*) dlsym(Code.KwmHotkeySO, "CustomHotkeyCommands");
Code.RemapKeys = (kwm_key_remap*) dlsym(Code.KwmHotkeySO, "RemapKeys");
}
else
{
DEBUG("LoadKwmCode() Could not open '" << HotkeySOFullFilePath << "'")
}
Code.IsValid = (Code.KWMHotkeyCommands && Code.SystemHotkeyCommands && Code.CustomHotkeyCommands && Code.RemapKeys);
return Code;
}
void UnloadKwmCode(kwm_code *Code)
{
if(Code->KwmHotkeySO)
dlclose(Code->KwmHotkeySO);
Code->HotkeySOFileTime = "";
Code->KWMHotkeyCommands = 0;
Code->SystemHotkeyCommands = 0;
Code->CustomHotkeyCommands = 0;
Code->RemapKeys = 0;
Code->IsValid = 0;
}
std::string KwmGetFileTime(const char *File)
{
struct stat attr;
stat(File, &attr);
return ctime(&attr.st_mtime);
}
void KwmRestart()
{
DEBUG("KWM Restarting..")
const char **ExecArgs = new const char*[2];
ExecArgs[0] = "kwm";
ExecArgs[1] = NULL;
std::string KwmBinPath = KwmFilePath + "/kwm";
execv(KwmBinPath.c_str(), (char**)ExecArgs);
}
void * KwmWindowMonitor(void*)
{
while(1)
{
if(KwmFocusMode != FocusModeDisabled)
{
pthread_mutex_lock(&BackgroundLock);
UpdateWindowTree();
pthread_mutex_unlock(&BackgroundLock);
}
usleep(200000);
}
}
void KwmExecuteConfig()
{
char *HomeP = std::getenv("HOME");
if(!HomeP)
Fatal("Failed to get environment variable 'HOME'");
std::string ENV_HOME = HomeP;
std::string KWM_CONFIG_FILE = ".kwmrc";
std::ifstream ConfigFD(ENV_HOME + "/" + KWM_CONFIG_FILE);
if(ConfigFD.fail())
{
std::cout << "Could not open "
<< ENV_HOME
<< "/"
<< KWM_CONFIG_FILE
<< ", make sure the file exists.";
return;
}
std::string Line;
while(std::getline(ConfigFD, Line))
{
if(!Line.empty() && Line[0] != '#')
system(Line.c_str());
}
}
void KwmInit()
{
if(!CheckPrivileges())
Fatal("Could not access OSX Accessibility!");
if (pthread_mutex_init(&BackgroundLock, NULL) != 0)
Fatal("Could not create mutex!");
if(KwmStartDaemon())
pthread_create(&DaemonThread, NULL, &KwmDaemonHandleConnectionBG, NULL);
else
Fatal("Kwm: Could not start daemon..");
KwmFilePath = getcwd(NULL, 0);
HotkeySOFullFilePath = KwmFilePath + "/hotkeys.so";
KwmFocusMode = FocusModeAutoraise;
KwmExecuteConfig();
KWMCode = LoadKwmCode();
GetActiveDisplays();
pthread_create(&BackgroundThread, NULL, &KwmWindowMonitor, NULL);
}
bool CheckPrivileges()
{
const void * Keys[] = { kAXTrustedCheckOptionPrompt };
const void * Values[] = { kCFBooleanTrue };
CFDictionaryRef Options;
Options = CFDictionaryCreate(kCFAllocatorDefault,
Keys, Values, sizeof(Keys) / sizeof(*Keys),
&kCFCopyStringDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
return AXIsProcessTrustedWithOptions(Options);
}
void Fatal(const std::string &Err)
{
std::cout << Err << std::endl;
exit(1);
}
int main(int argc, char **argv)
{
KwmInit();
CGEventMask EventMask;
CFRunLoopSourceRef RunLoopSource;
EventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventMouseMoved));
EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, EventMask, CGEventCallback, NULL);
if(!EventTap || !CGEventTapIsEnabled(EventTap))
Fatal("ERROR: Could not create event-tap!");
RunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, EventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), RunLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(EventTap, true);
CFRunLoopRun();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018-2019 Nagisa Sekiguchi
*
* 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 "server.h"
namespace ydsh {
namespace lsp {
// #######################
// ## LSPServer ##
// #######################
void LSPServer::bindAll() {
auto voidIface = this->interface();
this->bind("shutdown", voidIface, &LSPServer::shutdown);
this->bind("exit", voidIface, &LSPServer::exit);
auto clientCap = this->interface("ClientCapabilities", {
field("workspace", any, false),
field("textDocument", any, false)
});
this->bind("initialize",
this->interface("InitializeParams", {
field("processId", integer),
field("rootPath", string | null ,false),
field("rootUri", string | null),
field("initializationOptions", any, false),
field("capabilities", object(clientCap->getName())),
field("trace", string, false)
}), &LSPServer::initialize
);
}
void LSPServer::run() {
while(true) {
this->transport.dispatch(*this);
}
}
Reply<InitializeResult> LSPServer::initialize(const InitializeParams ¶ms) {
this->logger(LogLevel::INFO, "initialize server ....");
if(this->init) {
//FIXME: check duplicated initialization
}
this->init = true;
(void) params; //FIXME: currently not used
InitializeResult ret; //FIXME: set supported capabilities
return std::move(ret);
}
Reply<void> LSPServer::shutdown() {
this->logger(LogLevel::INFO, "try to shutdown ....");
this->willExit = true;
return nullptr;
}
void LSPServer::exit() {
int s = this->willExit ? 0 : 1;
this->logger(LogLevel::INFO, "exit server: %d", s);
std::exit(s); // always success
}
} // namespace lsp
} // namespace ydsh<commit_msg>[LSP] add error check to initialize request<commit_after>/*
* Copyright (C) 2018-2019 Nagisa Sekiguchi
*
* 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 "server.h"
namespace ydsh {
namespace lsp {
// #######################
// ## LSPServer ##
// #######################
void LSPServer::bindAll() {
auto voidIface = this->interface();
this->bind("shutdown", voidIface, &LSPServer::shutdown);
this->bind("exit", voidIface, &LSPServer::exit);
auto clientCap = this->interface("ClientCapabilities", {
field("workspace", any, false),
field("textDocument", any, false)
});
this->bind("initialize",
this->interface("InitializeParams", {
field("processId", integer),
field("rootPath", string | null ,false),
field("rootUri", string | null),
field("initializationOptions", any, false),
field("capabilities", object(clientCap->getName())),
field("trace", string, false)
}), &LSPServer::initialize
);
}
void LSPServer::run() {
while(true) {
this->transport.dispatch(*this);
}
}
Reply<InitializeResult> LSPServer::initialize(const InitializeParams ¶ms) {
this->logger(LogLevel::INFO, "initialize server ....");
if(this->init) {
return newError(ErrorCode::InvalidRequest, "server has already initialized");
}
this->init = true;
(void) params; //FIXME: currently not used
InitializeResult ret; //FIXME: set supported capabilities
return std::move(ret);
}
Reply<void> LSPServer::shutdown() {
this->logger(LogLevel::INFO, "try to shutdown ....");
this->willExit = true;
return nullptr;
}
void LSPServer::exit() {
int s = this->willExit ? 0 : 1;
this->logger(LogLevel::INFO, "exit server: %d", s);
std::exit(s); // always success
}
} // namespace lsp
} // namespace ydsh<|endoftext|> |
<commit_before>/*
This file is part of Kontact.
Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>
Copyright (c) 2005-2006,2008 Allen Winter <winter@kde.org>
Copyright (c) 2008 Thomas McGuire <mcguire@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "summaryeventinfo.h"
#include <libkdepim/kpimprefs.h>
#include <korganizer/stdcalendar.h>
#include <kcal/incidenceformatter.h>
using namespace KCal;
#include <KSystemTimeZones>
#include <QDate>
#include <QStringList>
bool SummaryEventInfo::mShowBirthdays = true;
bool SummaryEventInfo::mShowAnniversaries = true;
void SummaryEventInfo::setShowSpecialEvents( bool showBirthdays,
bool showAnniversaries )
{
mShowBirthdays = showBirthdays;
mShowAnniversaries = showAnniversaries;
}
bool SummaryEventInfo::skip( KCal::Event *event )
{
//simply check categories because the birthdays resource always adds
//the appropriate category to the event.
QStringList c = event->categories();
if ( !mShowBirthdays &&
c.contains( i18n( "BIRTHDAY" ), Qt::CaseInsensitive ) ) {
return true;
}
if ( !mShowAnniversaries &&
c.contains( i18n( "ANNIVERSARY" ), Qt::CaseInsensitive ) ) {
return true;
}
return false;
}
void SummaryEventInfo::dateDiff( const QDate &date, int &days )
{
QDate currentDate;
QDate eventDate;
if ( QDate::isLeapYear( date.year() ) && date.month() == 2 && date.day() == 29 ) {
currentDate = QDate( date.year(), QDate::currentDate().month(), QDate::currentDate().day() );
if ( !QDate::isLeapYear( QDate::currentDate().year() ) ) {
eventDate = QDate( date.year(), date.month(), 28 ); // celebrate one day earlier ;)
} else {
eventDate = QDate( date.year(), date.month(), date.day() );
}
} else {
currentDate = QDate( QDate::currentDate().year(),
QDate::currentDate().month(),
QDate::currentDate().day() );
eventDate = QDate( QDate::currentDate().year(), date.month(), date.day() );
}
int offset = currentDate.daysTo( eventDate );
if ( offset < 0 ) {
days = 365 + offset;
if ( QDate::isLeapYear( QDate::currentDate().year() ) ) {
days++;
}
} else {
days = offset;
}
}
SummaryEventInfo::SummaryEventInfo()
: makeBold( false )
{
}
SummaryEventInfo::List SummaryEventInfo::eventsForDate( const QDate &date,
KCal::Calendar *calendar )
{
KCal::Event *ev;
KCal::Event::List events_orig = calendar->events( date, calendar->timeSpec() );
KCal::Event::List::ConstIterator it = events_orig.constBegin();
KCal::Event::List events;
events.setAutoDelete( false ); //do not autodelete. we need these active
KDateTime qdt;
KDateTime::Spec spec = KSystemTimeZones::local();
QDate currentDate = QDate::currentDate();
// prevent implicitely sharing while finding recurring events
// replacing the QDate with the currentDate
for ( ; it != events_orig.constEnd(); ++it ) {
ev = (*it)->clone();
if ( ev->recursOn( date, calendar->timeSpec() ) ) {
qdt = ev->dtStart();
qdt.setDate( date );
ev->setDtStart( qdt );
}
if ( !skip( ev ) ) {
events.append( ev );
}
}
// sort the events for this date by summary
events = KCal::Calendar::sortEvents( &events,
KCal::EventSortSummary,
KCal::SortDirectionAscending );
// sort the events for this date by start date
events = KCal::Calendar::sortEvents( &events,
KCal::EventSortStartDate,
KCal::SortDirectionAscending );
List eventInfoList;
for ( it=events.constBegin(); it != events.constEnd(); ++it ) {
ev = *it;
int daysTo = -1;
// Count number of days remaining in multiday event
int span = 1;
int dayof = 1;
if ( ev->isMultiDay() ) {
QDate d = ev->dtStart().date();
if ( d < currentDate ) {
dayof += d.daysTo( currentDate );
span += d.daysTo( currentDate );
d = currentDate;
}
while ( d < ev->dtEnd().date() ) {
if ( d < date ) {
dayof++;
}
span++;
d = d.addDays( 1 );
}
}
QDate startOfMultiday = ev->dtStart().date();
if ( startOfMultiday < currentDate ) {
startOfMultiday = currentDate;
}
bool firstDayOfMultiday = ( date == startOfMultiday );
// If this date is part of a floating, multiday event, then we
// only make a print for the first day of the event.
if ( ev->isMultiDay() && ev->allDay() &&
( currentDate > ev->dtStart().date() || !firstDayOfMultiday ) ) {
continue;
}
SummaryEventInfo *summaryEvent = new SummaryEventInfo();
eventInfoList.append( summaryEvent );
// Event
summaryEvent->ev = ev;
// Start date label
QString str = "";
QDate sD = QDate( date.year(), date.month(), date.day() );
if ( ( sD.month() == currentDate.month() ) &&
( sD.day() == currentDate.day() ) ) {
str = i18nc( "the appointment is today", "Today" );
summaryEvent->makeBold = true;
} else if ( ( sD.month() == currentDate.addDays( 1 ).month() ) &&
( sD.day() == currentDate.addDays( 1 ).day() ) ) {
str = i18nc( "the appointment is tomorrow", "Tomorrow" );
} else {
str = KGlobal::locale()->formatDate( sD, KLocale::FancyLongDate );
}
summaryEvent->startDate = str;
// Print the date span for multiday, floating events, for the
// first day of the event only.
if ( ev->isMultiDay() && ev->allDay() && firstDayOfMultiday && span > 1 ) {
str = IncidenceFormatter::dateToString( ev->dtStart(), false, spec ) +
" -\n " +
IncidenceFormatter::dateToString( ev->dtEnd(), false, spec );
}
summaryEvent->dateSpan = str;
// Days to go label
str = "";
dateDiff( startOfMultiday, daysTo );
if ( ev->isMultiDay() && !ev->allDay() ) {
dateDiff( date, daysTo );
}
if ( daysTo > 0 ) {
str = i18np( "in 1 day", "in %1 days", daysTo );
} else {
str = i18n( "now" );
}
summaryEvent->daysToGo = str;
// Summary label
str = ev->richSummary();
if ( ev->isMultiDay() && !ev->allDay() ) {
str.append( QString( " (%1/%2)" ).arg( dayof ).arg( span ) );
}
summaryEvent->summaryText = str;
summaryEvent->summaryUrl = ev->uid();
QString tipText(
KCal::IncidenceFormatter::toolTipStr( calendar, ev, date, true, KSystemTimeZones::local() ) );
if ( !tipText.isEmpty() ) {
summaryEvent->summaryTooltip = tipText;
}
// Time range label (only for non-floating events)
str = "";
if ( !ev->allDay() ) {
QTime sST = ev->dtStart().toTimeSpec( spec ).time();
QTime sET = ev->dtEnd().toTimeSpec( spec ).time();
if ( ev->isMultiDay() ) {
if ( ev->dtStart().date() < date ) {
sST = QTime( 0, 0 );
}
if ( ev->dtEnd().date() > date ) {
sET = QTime( 23, 59 );
}
}
str = i18nc( "Time from - to", "%1 - %2",
KGlobal::locale()->formatTime( sST ),
KGlobal::locale()->formatTime( sET ) );
summaryEvent->timeRange = str;
}
}
return eventInfoList;
}
<commit_msg>for Todays's events with a specified start time, show a countdown (X hrs Y mins) until the start. since the summary page doesn't update itself every minute, this countdown can't be relied on, but it could prove useful.<commit_after>/*
This file is part of Kontact.
Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>
Copyright (c) 2005-2006,2008 Allen Winter <winter@kde.org>
Copyright (c) 2008 Thomas McGuire <mcguire@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "summaryeventinfo.h"
#include "korganizer/stdcalendar.h"
#include <KCal/IncidenceFormatter>
using namespace KCal;
#include <KSystemTimeZones>
#include <QDate>
#include <QStringList>
bool SummaryEventInfo::mShowBirthdays = true;
bool SummaryEventInfo::mShowAnniversaries = true;
void SummaryEventInfo::setShowSpecialEvents( bool showBirthdays,
bool showAnniversaries )
{
mShowBirthdays = showBirthdays;
mShowAnniversaries = showAnniversaries;
}
bool SummaryEventInfo::skip( KCal::Event *event )
{
//simply check categories because the birthdays resource always adds
//the appropriate category to the event.
QStringList c = event->categories();
if ( !mShowBirthdays &&
c.contains( i18n( "BIRTHDAY" ), Qt::CaseInsensitive ) ) {
return true;
}
if ( !mShowAnniversaries &&
c.contains( i18n( "ANNIVERSARY" ), Qt::CaseInsensitive ) ) {
return true;
}
return false;
}
void SummaryEventInfo::dateDiff( const QDate &date, int &days )
{
QDate currentDate;
QDate eventDate;
if ( QDate::isLeapYear( date.year() ) && date.month() == 2 && date.day() == 29 ) {
currentDate = QDate( date.year(), QDate::currentDate().month(), QDate::currentDate().day() );
if ( !QDate::isLeapYear( QDate::currentDate().year() ) ) {
eventDate = QDate( date.year(), date.month(), 28 ); // celebrate one day earlier ;)
} else {
eventDate = QDate( date.year(), date.month(), date.day() );
}
} else {
currentDate = QDate( QDate::currentDate().year(),
QDate::currentDate().month(),
QDate::currentDate().day() );
eventDate = QDate( QDate::currentDate().year(), date.month(), date.day() );
}
int offset = currentDate.daysTo( eventDate );
if ( offset < 0 ) {
days = 365 + offset;
if ( QDate::isLeapYear( QDate::currentDate().year() ) ) {
days++;
}
} else {
days = offset;
}
}
SummaryEventInfo::SummaryEventInfo()
: makeBold( false )
{
}
SummaryEventInfo::List SummaryEventInfo::eventsForDate( const QDate &date,
KCal::Calendar *calendar )
{
KCal::Event *ev;
KCal::Event::List events_orig = calendar->events( date, calendar->timeSpec() );
KCal::Event::List::ConstIterator it = events_orig.constBegin();
KCal::Event::List events;
events.setAutoDelete( false ); //do not autodelete. we need these active
KDateTime qdt;
KDateTime::Spec spec = KSystemTimeZones::local();
QDate currentDate = QDate::currentDate();
// prevent implicitely sharing while finding recurring events
// replacing the QDate with the currentDate
for ( ; it != events_orig.constEnd(); ++it ) {
ev = (*it)->clone();
if ( ev->recursOn( date, calendar->timeSpec() ) ) {
qdt = ev->dtStart();
qdt.setDate( date );
ev->setDtStart( qdt );
}
if ( !skip( ev ) ) {
events.append( ev );
}
}
// sort the events for this date by summary
events = KCal::Calendar::sortEvents( &events,
KCal::EventSortSummary,
KCal::SortDirectionAscending );
// sort the events for this date by start date
events = KCal::Calendar::sortEvents( &events,
KCal::EventSortStartDate,
KCal::SortDirectionAscending );
List eventInfoList;
for ( it=events.constBegin(); it != events.constEnd(); ++it ) {
ev = *it;
int daysTo = -1;
// Count number of days remaining in multiday event
int span = 1;
int dayof = 1;
if ( ev->isMultiDay() ) {
QDate d = ev->dtStart().date();
if ( d < currentDate ) {
dayof += d.daysTo( currentDate );
span += d.daysTo( currentDate );
d = currentDate;
}
while ( d < ev->dtEnd().date() ) {
if ( d < date ) {
dayof++;
}
span++;
d = d.addDays( 1 );
}
}
QDate startOfMultiday = ev->dtStart().date();
if ( startOfMultiday < currentDate ) {
startOfMultiday = currentDate;
}
bool firstDayOfMultiday = ( date == startOfMultiday );
// If this date is part of a floating, multiday event, then we
// only make a print for the first day of the event.
if ( ev->isMultiDay() && ev->allDay() &&
( currentDate > ev->dtStart().date() || !firstDayOfMultiday ) ) {
continue;
}
SummaryEventInfo *summaryEvent = new SummaryEventInfo();
eventInfoList.append( summaryEvent );
// Event
summaryEvent->ev = ev;
// Start date label
QString str = "";
QDate sD = QDate( date.year(), date.month(), date.day() );
if ( ( sD.month() == currentDate.month() ) &&
( sD.day() == currentDate.day() ) ) {
str = i18nc( "the appointment is today", "Today" );
summaryEvent->makeBold = true;
} else if ( ( sD.month() == currentDate.addDays( 1 ).month() ) &&
( sD.day() == currentDate.addDays( 1 ).day() ) ) {
str = i18nc( "the appointment is tomorrow", "Tomorrow" );
} else {
str = KGlobal::locale()->formatDate( sD, KLocale::FancyLongDate );
}
summaryEvent->startDate = str;
// Print the date span for multiday, floating events, for the
// first day of the event only.
if ( ev->isMultiDay() && ev->allDay() && firstDayOfMultiday && span > 1 ) {
str = IncidenceFormatter::dateToString( ev->dtStart(), false, spec ) +
" -\n " +
IncidenceFormatter::dateToString( ev->dtEnd(), false, spec );
}
summaryEvent->dateSpan = str;
// Days to go label
str = "";
dateDiff( startOfMultiday, daysTo );
if ( ev->isMultiDay() && !ev->allDay() ) {
dateDiff( date, daysTo );
}
if ( daysTo > 0 ) {
str = i18np( "in 1 day", "in %1 days", daysTo );
} else {
if ( !ev->allDay() ) {
str = i18nc( "eg. in 1 hour 2 minutes", "in " );
int secs = KDateTime::currentDateTime( spec ).secsTo( ev->dtStart() );
int hours = secs / 3600;
if ( hours > 0 ) {
str += i18ncp( "use abbreviation for hour to keep the text short",
"1 hr", "%1 hrs", hours );
str += ' ';
secs -= ( hours * 3600 );
}
int mins = secs / 60;
if ( mins > 0 ) {
str += i18ncp( "use abbreviation for minute to keep the text short",
"1 min", "%1 mins", mins );
}
} else {
str = i18n( "all day" );
}
}
summaryEvent->daysToGo = str;
// Summary label
str = ev->richSummary();
if ( ev->isMultiDay() && !ev->allDay() ) {
str.append( QString( " (%1/%2)" ).arg( dayof ).arg( span ) );
}
summaryEvent->summaryText = str;
summaryEvent->summaryUrl = ev->uid();
QString tipText( KCal::IncidenceFormatter::toolTipStr( calendar, ev, date, true, spec ) );
if ( !tipText.isEmpty() ) {
summaryEvent->summaryTooltip = tipText;
}
// Time range label (only for non-floating events)
str = "";
if ( !ev->allDay() ) {
QTime sST = ev->dtStart().toTimeSpec( spec ).time();
QTime sET = ev->dtEnd().toTimeSpec( spec ).time();
if ( ev->isMultiDay() ) {
if ( ev->dtStart().date() < date ) {
sST = QTime( 0, 0 );
}
if ( ev->dtEnd().date() > date ) {
sET = QTime( 23, 59 );
}
}
str = i18nc( "Time from - to", "%1 - %2",
KGlobal::locale()->formatTime( sST ),
KGlobal::locale()->formatTime( sET ) );
summaryEvent->timeRange = str;
}
}
return eventInfoList;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "porting.hpp"
#include "config.hpp"
#include "endian.hpp"
#include "engine.hpp"
#include "parser.hpp"
#include "hamsterdb.hpp"
#include "berkeleydb.hpp"
#include "misc.hpp"
engine::engine(config *c)
: m_config(c), m_parser(0), m_opcount(0)
{
m_db[0]=new hamsterdb(m_config);
m_db[1]=new berkeleydb(m_config);
}
engine::~engine()
{
for (int i=0; i<2; i++) {
if (m_db[i]) {
m_db[i]->close();
delete m_db[i];
m_db[i]=0;
}
}
}
void
engine::set_parser(parser *p)
{
m_parser=p;
}
bool
engine::create(bool numeric)
{
if (numeric)
m_config->numeric=true;
for (int i=0; i<2; i++) {
ham_status_t st=m_db[i]->create();
if (st) {
TRACE(("db[%d]: create failed w/ status %d\n", i, st));
return (false);
}
}
if (m_config->txn_group) {
return (txn_begin());
}
return (true);
}
bool
engine::open(bool numeric)
{
if (numeric)
m_config->numeric=true;
for (int i=0; i<2; i++) {
ham_status_t st=m_db[i]->open();
if (st) {
TRACE(("db[%d]: open failed w/ status %d\n", i, st));
return (false);
}
}
return (true);
}
bool
engine::insert(const char *keytok, const char *data)
{
ham_u32_t numkey=0;
ham_size_t data_size;
ham_key_t key;
ham_record_t rec;
ham_status_t st[2];
VERBOSE(("insert: key: %s, data: %s\n", keytok, data));
memset(&key, 0, sizeof(key));
memset(&rec, 0, sizeof(rec));
/*
* check flag NUMERIC_KEY
*/
if (m_config->numeric) {
numkey=strtoul(keytok, 0, 0);
if (!numkey) {
TRACE(("line %d: key is invalid\n", m_parser->get_lineno()));
return (false);
}
numkey=ham_h2db32(numkey);
key.data=(void *)&numkey;
key.size=sizeof(numkey);
}
else {
key.data=(void *)keytok;
key.size=(ham_size_t)strlen(keytok)+1;
}
/*
* allocate and initialize data
*/
data_size=strtoul(data, 0, 0);
if (data_size) {
if (data_size>m_config->data_size) {
m_config->data_size=data_size;
m_config->data_ptr=realloc(m_config->data_ptr, data_size);
if (!m_config->data_ptr) {
TRACE(("line %d: out of memory\n", m_parser->get_lineno()));
return 0;
}
}
/* always start with a random number - otherwise berkeleydb fails
* too often when duplicate keys are inserted with duplicate
* records */
for (ham_size_t i=0; i<data_size; i++)
((char *)m_config->data_ptr)[i]=(m_parser->get_lineno()+i)&0xff;
if (data_size>=sizeof(unsigned))
*(unsigned *)m_config->data_ptr=m_parser->get_lineno();
rec.data=m_config->data_ptr;
rec.size=data_size;
}
for (int i=0; i<2; i++) {
st[i]=m_db[i]->insert(&key, &rec);
if (st[i])
VERBOSE(("db[%d]: insert failed w/ status %d\n", i, st[i]));
}
if (!compare_status(st))
return (false);
if (m_config->txn_group>0)
return (inc_opcount());
return (true);
}
bool
engine::erase(const char *keytok)
{
ham_u32_t numkey=0;
ham_key_t key;
ham_status_t st[2];
VERBOSE(("erase: key: %s\n", keytok));
memset(&key, 0, sizeof(key));
/*
* check flag NUMERIC_KEY
*/
if (m_config->numeric) {
numkey=strtoul(keytok, 0, 0);
if (!numkey) {
TRACE(("line %d: key is invalid\n", m_parser->get_lineno()));
return (false);
}
numkey=ham_h2db32(numkey);
key.data=(void *)&numkey;
key.size=sizeof(numkey);
}
else {
key.data=(void *)keytok;
key.size=(ham_size_t)strlen(keytok);
}
for (int i=0; i<2; i++) {
st[i]=m_db[i]->erase(&key);
if (st[i])
VERBOSE(("db[%d]: erase failed w/ status %d\n", i, st[i]));
}
if (!compare_status(st))
return (false);
if (m_config->txn_group>0)
return (inc_opcount());
return (true);
}
bool
engine::find(const char *keytok)
{
ham_u32_t numkey=0;
ham_key_t key;
ham_record_t rec[2];
ham_status_t st[2];
VERBOSE(("find: key: %s\n", keytok));
memset(&key, 0, sizeof(key));
memset(&rec[0], 0, sizeof(rec[0]));
memset(&rec[1], 0, sizeof(rec[1]));
/*
* check flag NUMERIC_KEY
*/
if (m_config->numeric) {
numkey=strtoul(keytok, 0, 0);
if (!numkey) {
TRACE(("line %d: key is invalid\n", m_parser->get_lineno()));
return (false);
}
numkey=ham_h2db32(numkey);
key.data=(void *)&numkey;
key.size=sizeof(numkey);
}
else {
key.data=(void *)keytok;
key.size=(ham_size_t)strlen(keytok);
}
for (int i=0; i<2; i++) {
st[i]=m_db[i]->find(&key, &rec[i]);
if (st[i])
VERBOSE(("db[%d]: find failed w/ status %d\n", i, st[i]));
}
if (!compare_records(&rec[0], &rec[1])) {
TRACE(("record mismatch\n"));
return false;
}
if (!compare_status(st))
return (false);
if (m_config->txn_group>0)
return (inc_opcount());
return (true);
}
bool
engine::fullcheck(void)
{
ham_key_t key[2];
ham_record_t rec[2];
void *c[2];
ham_status_t st[2];
st[0]=m_db[0]->check_integrity();
st[1]=m_db[1]->check_integrity();
if (!compare_status(st))
return false;
c[0]=m_db[0]->create_cursor();
c[1]=m_db[1]->create_cursor();
for(;;) {
memset(key, 0, sizeof(key));
memset(rec, 0, sizeof(rec));
if (m_config->puseralloc) {
key[0].data=m_config->puseralloc;
key[0].flags=HAM_KEY_USER_ALLOC;
/* keysize is a 16-bit value! */
assert(USER_MALLOC_KEYRECSIZE > 65530);
key[0].size=65530;
rec[0].data = static_cast<char *>(m_config->puseralloc) + 65530;
rec[0].size = USER_MALLOC_KEYRECSIZE - 65530;
rec[0].flags=HAM_RECORD_USER_ALLOC;
}
/* first: berkeley db */
if (m_config->fullcheck_find) {
st[1]=m_db[1]->get_next(c[1], &key[1], &rec[1],
HAM_SKIP_DUPLICATES);
}
else if (m_config->fullcheck_backwards) {
st[1]=m_db[1]->get_previous(c[1], &key[1], &rec[1], 0);
}
else {
st[1]=m_db[1]->get_next(c[1], &key[1], &rec[1], 0);
}
/* then: hamster db */
if (m_config->fullcheck_find) {
/*
* different behaviour for BDB and hamsterdb:
*
* since BDB is used in this mode to fetch keys from its database
* and hamsterdb can only /look/ for keys, it's no use feeding
* hamsterdb an (illegal) key to look for when BDB didn't deliver
* one.
*
* This mode does NOT discover keys lurking in the hamsterdb
* database which are NOT in the BDB database. Use regular
* fullcheck or fullcheck-backwards to cover that sort of thing.
*/
if (st[1]==HAM_KEY_NOT_FOUND)
st[0]=st[1];
else
st[0]=m_db[0]->find(&key[1], &rec[0]); /* !! */
}
else if (m_config->fullcheck_backwards)
st[0]=m_db[0]->get_previous(c[0], &key[0], &rec[0], 0);
else
st[0]=m_db[0]->get_next(c[0], &key[0], &rec[0], 0);
if (m_config->verbose>1) {
if (m_config->numeric)
printf("fullcheck: %d/%d, keys %d/%d, blob size %d/%d\n",
st[0], st[1],
key[0].data ? *(int *)key[0].data : 0,
key[1].data ? *(int *)key[1].data : 0,
rec[0].size, rec[1].size);
else
printf("fullcheck: %d/%d, keys %s/%s, blob size %d/%d\n",
st[0], st[1],
key[0].data ? (char *)key[0].data : "(null)",
key[1].data ? (char *)key[1].data : "(null)",
rec[0].size, rec[1].size);
}
if (key[0].data && *(unsigned *)key[0].data==128 && rec[0].size==350) {
printf("hit\n");
}
if (!compare_status(st))
return false;
if (st[0]!=0)
break;
if (!compare_records(&rec[0], &rec[1])) {
TRACE(("record mismatch\n"));
return false;
}
}
m_db[0]->close_cursor(c[0]);
m_db[1]->close_cursor(c[1]);
return (true);
}
bool
engine::close(bool noreopen/* =false */)
{
for (int i=0; i<2; i++) {
ham_status_t st=m_db[i]->close();
if (st) {
TRACE(("db[%d]: close failed w/ status %d\n", i, st));
return (false);
}
}
if (!noreopen && m_config->reopen) {
VERBOSE(("reopen\n"));
if (!open(m_config->numeric))
return (false);
if (!fullcheck())
return (false);
if (!close(true))
return (false);
}
return (true);
}
bool
engine::flush(void)
{
for (int i=0; i<2; i++) {
ham_status_t st=m_db[i]->flush();
if (st) {
TRACE(("db[%d]: flush failed w/ status %d\n", i, st));
return (false);
}
}
return (true);
}
bool
engine::txn_begin(void)
{
for (int i=0; i<2; i++) {
ham_status_t st=m_db[i]->txn_begin();
if (st) {
TRACE(("db[%d]: txn_begin failed w/ status %d\n", i, st));
return (false);
}
}
return (true);
}
bool
engine::txn_commit(void)
{
for (int i=0; i<2; i++) {
ham_status_t st=m_db[i]->txn_commit();
if (st) {
TRACE(("db[%d]: txn_begin failed w/ status %d\n", i, st));
return (false);
}
}
return (true);
}
bool
engine::compare_records(ham_record_t *rec1, ham_record_t *rec2)
{
if (rec1->size!=rec2->size)
return (false);
if (!rec1->size && !rec2->size)
return (true);
if ((rec1->data && !rec2->data) || (rec2->data && !rec1->data))
return (false);
if (!rec1->data && !rec2->data)
return (true);
return (memcmp(rec1->data, rec2->data, rec1->size)==0);
}
bool
engine::inc_opcount(void)
{
if (++m_opcount>=m_config->txn_group) {
if (!txn_commit())
return (false);
if (!txn_begin())
return (false);
m_opcount=0;
}
return (true);
}
bool
engine::compare_status(ham_status_t st[2])
{
if (st[0]!=st[1]) {
TRACE(("status mismatch - %d vs %d\n"
" ----> (%s) vs (%s)\n",
st[0], st[1],
ham_strerror(st[0]), ham_strerror(st[1])));
return false;
}
return (true);
}
<commit_msg>removed debug output<commit_after>#include <iostream>
#include "porting.hpp"
#include "config.hpp"
#include "endian.hpp"
#include "engine.hpp"
#include "parser.hpp"
#include "hamsterdb.hpp"
#include "berkeleydb.hpp"
#include "misc.hpp"
engine::engine(config *c)
: m_config(c), m_parser(0), m_opcount(0)
{
m_db[0]=new hamsterdb(m_config);
m_db[1]=new berkeleydb(m_config);
}
engine::~engine()
{
for (int i=0; i<2; i++) {
if (m_db[i]) {
m_db[i]->close();
delete m_db[i];
m_db[i]=0;
}
}
}
void
engine::set_parser(parser *p)
{
m_parser=p;
}
bool
engine::create(bool numeric)
{
if (numeric)
m_config->numeric=true;
for (int i=0; i<2; i++) {
ham_status_t st=m_db[i]->create();
if (st) {
TRACE(("db[%d]: create failed w/ status %d\n", i, st));
return (false);
}
}
if (m_config->txn_group) {
return (txn_begin());
}
return (true);
}
bool
engine::open(bool numeric)
{
if (numeric)
m_config->numeric=true;
for (int i=0; i<2; i++) {
ham_status_t st=m_db[i]->open();
if (st) {
TRACE(("db[%d]: open failed w/ status %d\n", i, st));
return (false);
}
}
return (true);
}
bool
engine::insert(const char *keytok, const char *data)
{
ham_u32_t numkey=0;
ham_size_t data_size;
ham_key_t key;
ham_record_t rec;
ham_status_t st[2];
VERBOSE(("insert: key: %s, data: %s\n", keytok, data));
memset(&key, 0, sizeof(key));
memset(&rec, 0, sizeof(rec));
/*
* check flag NUMERIC_KEY
*/
if (m_config->numeric) {
numkey=strtoul(keytok, 0, 0);
if (!numkey) {
TRACE(("line %d: key is invalid\n", m_parser->get_lineno()));
return (false);
}
numkey=ham_h2db32(numkey);
key.data=(void *)&numkey;
key.size=sizeof(numkey);
}
else {
key.data=(void *)keytok;
key.size=(ham_size_t)strlen(keytok)+1;
}
/*
* allocate and initialize data
*/
data_size=strtoul(data, 0, 0);
if (data_size) {
if (data_size>m_config->data_size) {
m_config->data_size=data_size;
m_config->data_ptr=realloc(m_config->data_ptr, data_size);
if (!m_config->data_ptr) {
TRACE(("line %d: out of memory\n", m_parser->get_lineno()));
return 0;
}
}
/* always start with a random number - otherwise berkeleydb fails
* too often when duplicate keys are inserted with duplicate
* records */
for (ham_size_t i=0; i<data_size; i++)
((char *)m_config->data_ptr)[i]=(m_parser->get_lineno()+i)&0xff;
if (data_size>=sizeof(unsigned))
*(unsigned *)m_config->data_ptr=m_parser->get_lineno();
rec.data=m_config->data_ptr;
rec.size=data_size;
}
for (int i=0; i<2; i++) {
st[i]=m_db[i]->insert(&key, &rec);
if (st[i])
VERBOSE(("db[%d]: insert failed w/ status %d\n", i, st[i]));
}
if (!compare_status(st))
return (false);
if (m_config->txn_group>0)
return (inc_opcount());
return (true);
}
bool
engine::erase(const char *keytok)
{
ham_u32_t numkey=0;
ham_key_t key;
ham_status_t st[2];
VERBOSE(("erase: key: %s\n", keytok));
memset(&key, 0, sizeof(key));
/*
* check flag NUMERIC_KEY
*/
if (m_config->numeric) {
numkey=strtoul(keytok, 0, 0);
if (!numkey) {
TRACE(("line %d: key is invalid\n", m_parser->get_lineno()));
return (false);
}
numkey=ham_h2db32(numkey);
key.data=(void *)&numkey;
key.size=sizeof(numkey);
}
else {
key.data=(void *)keytok;
key.size=(ham_size_t)strlen(keytok);
}
for (int i=0; i<2; i++) {
st[i]=m_db[i]->erase(&key);
if (st[i])
VERBOSE(("db[%d]: erase failed w/ status %d\n", i, st[i]));
}
if (!compare_status(st))
return (false);
if (m_config->txn_group>0)
return (inc_opcount());
return (true);
}
bool
engine::find(const char *keytok)
{
ham_u32_t numkey=0;
ham_key_t key;
ham_record_t rec[2];
ham_status_t st[2];
VERBOSE(("find: key: %s\n", keytok));
memset(&key, 0, sizeof(key));
memset(&rec[0], 0, sizeof(rec[0]));
memset(&rec[1], 0, sizeof(rec[1]));
/*
* check flag NUMERIC_KEY
*/
if (m_config->numeric) {
numkey=strtoul(keytok, 0, 0);
if (!numkey) {
TRACE(("line %d: key is invalid\n", m_parser->get_lineno()));
return (false);
}
numkey=ham_h2db32(numkey);
key.data=(void *)&numkey;
key.size=sizeof(numkey);
}
else {
key.data=(void *)keytok;
key.size=(ham_size_t)strlen(keytok);
}
for (int i=0; i<2; i++) {
st[i]=m_db[i]->find(&key, &rec[i]);
if (st[i])
VERBOSE(("db[%d]: find failed w/ status %d\n", i, st[i]));
}
if (!compare_records(&rec[0], &rec[1])) {
TRACE(("record mismatch\n"));
return false;
}
if (!compare_status(st))
return (false);
if (m_config->txn_group>0)
return (inc_opcount());
return (true);
}
bool
engine::fullcheck(void)
{
ham_key_t key[2];
ham_record_t rec[2];
void *c[2];
ham_status_t st[2];
st[0]=m_db[0]->check_integrity();
st[1]=m_db[1]->check_integrity();
if (!compare_status(st))
return false;
c[0]=m_db[0]->create_cursor();
c[1]=m_db[1]->create_cursor();
for(;;) {
memset(key, 0, sizeof(key));
memset(rec, 0, sizeof(rec));
if (m_config->puseralloc) {
key[0].data=m_config->puseralloc;
key[0].flags=HAM_KEY_USER_ALLOC;
/* keysize is a 16-bit value! */
assert(USER_MALLOC_KEYRECSIZE > 65530);
key[0].size=65530;
rec[0].data = static_cast<char *>(m_config->puseralloc) + 65530;
rec[0].size = USER_MALLOC_KEYRECSIZE - 65530;
rec[0].flags=HAM_RECORD_USER_ALLOC;
}
/* first: berkeley db */
if (m_config->fullcheck_find) {
st[1]=m_db[1]->get_next(c[1], &key[1], &rec[1],
HAM_SKIP_DUPLICATES);
}
else if (m_config->fullcheck_backwards) {
st[1]=m_db[1]->get_previous(c[1], &key[1], &rec[1], 0);
}
else {
st[1]=m_db[1]->get_next(c[1], &key[1], &rec[1], 0);
}
/* then: hamster db */
if (m_config->fullcheck_find) {
/*
* different behaviour for BDB and hamsterdb:
*
* since BDB is used in this mode to fetch keys from its database
* and hamsterdb can only /look/ for keys, it's no use feeding
* hamsterdb an (illegal) key to look for when BDB didn't deliver
* one.
*
* This mode does NOT discover keys lurking in the hamsterdb
* database which are NOT in the BDB database. Use regular
* fullcheck or fullcheck-backwards to cover that sort of thing.
*/
if (st[1]==HAM_KEY_NOT_FOUND)
st[0]=st[1];
else
st[0]=m_db[0]->find(&key[1], &rec[0]); /* !! */
}
else if (m_config->fullcheck_backwards)
st[0]=m_db[0]->get_previous(c[0], &key[0], &rec[0], 0);
else
st[0]=m_db[0]->get_next(c[0], &key[0], &rec[0], 0);
if (m_config->verbose>1) {
if (m_config->numeric)
printf("fullcheck: %d/%d, keys %d/%d, blob size %d/%d\n",
st[0], st[1],
key[0].data ? *(int *)key[0].data : 0,
key[1].data ? *(int *)key[1].data : 0,
rec[0].size, rec[1].size);
else
printf("fullcheck: %d/%d, keys %s/%s, blob size %d/%d\n",
st[0], st[1],
key[0].data ? (char *)key[0].data : "(null)",
key[1].data ? (char *)key[1].data : "(null)",
rec[0].size, rec[1].size);
}
/*
if (key[0].data && *(unsigned *)key[0].data==12 && rec[0].size==835) {
printf("hit\n");
}
*/
if (!compare_status(st))
return false;
if (st[0]!=0)
break;
if (!compare_records(&rec[0], &rec[1])) {
TRACE(("record mismatch\n"));
return false;
}
}
m_db[0]->close_cursor(c[0]);
m_db[1]->close_cursor(c[1]);
return (true);
}
bool
engine::close(bool noreopen/* =false */)
{
for (int i=0; i<2; i++) {
ham_status_t st=m_db[i]->close();
if (st) {
TRACE(("db[%d]: close failed w/ status %d\n", i, st));
return (false);
}
}
if (!noreopen && m_config->reopen) {
VERBOSE(("reopen\n"));
if (!open(m_config->numeric))
return (false);
if (!fullcheck())
return (false);
if (!close(true))
return (false);
}
return (true);
}
bool
engine::flush(void)
{
for (int i=0; i<2; i++) {
ham_status_t st=m_db[i]->flush();
if (st) {
TRACE(("db[%d]: flush failed w/ status %d\n", i, st));
return (false);
}
}
return (true);
}
bool
engine::txn_begin(void)
{
for (int i=0; i<2; i++) {
ham_status_t st=m_db[i]->txn_begin();
if (st) {
TRACE(("db[%d]: txn_begin failed w/ status %d\n", i, st));
return (false);
}
}
return (true);
}
bool
engine::txn_commit(void)
{
for (int i=0; i<2; i++) {
ham_status_t st=m_db[i]->txn_commit();
if (st) {
TRACE(("db[%d]: txn_begin failed w/ status %d\n", i, st));
return (false);
}
}
return (true);
}
bool
engine::compare_records(ham_record_t *rec1, ham_record_t *rec2)
{
if (rec1->size!=rec2->size)
return (false);
if (!rec1->size && !rec2->size)
return (true);
if ((rec1->data && !rec2->data) || (rec2->data && !rec1->data))
return (false);
if (!rec1->data && !rec2->data)
return (true);
return (memcmp(rec1->data, rec2->data, rec1->size)==0);
}
bool
engine::inc_opcount(void)
{
if (++m_opcount>=m_config->txn_group) {
if (!txn_commit())
return (false);
if (!txn_begin())
return (false);
m_opcount=0;
}
return (true);
}
bool
engine::compare_status(ham_status_t st[2])
{
if (st[0]!=st[1]) {
TRACE(("status mismatch - %d vs %d\n"
" ----> (%s) vs (%s)\n",
st[0], st[1],
ham_strerror(st[0]), ham_strerror(st[1])));
return false;
}
return (true);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011, Dylan Sarber <dwsarber@gmail.com>
*
* See LICENSE for licensing information.
*/
#include "engine.h"
#include "inputmanager.h"
#include "renderer.h"
#include "scriptmanager.h"
#include "logog/logog.hpp"
/* Constructors & Destructor
------------------------------------------------------------------------------*/
Engine::Engine() : is_running(true) {}
Engine::~Engine() {
// if (scene_root != NULL) {
// delete scene_root;
// }
delete engine_scriptor;
delete renderer;
delete input;
}
/* Public Interface
------------------------------------------------------------------------------*/
void Engine::load_config()
{
}
void Engine::init()
{
INFO("Initializing Engine.");
input = new InputManager();
renderer = new Renderer();
engine_scriptor = ScriptManager::new_environment("engine");
}
void Engine::run()
{
while (is_running)
{
process_input();
update();
render();
}
}
void Engine::process_input()
{
input->update_input_state();
}
void Engine::render() {}
void Engine::update() {}
<commit_msg>Configuration File Access<commit_after>/*
* Copyright (c) 2011, Dylan Sarber <dwsarber@gmail.com>
*
* See LICENSE for licensing information.
*/
#include "engine.h"
#include "inputmanager.h"
#include "renderer.h"
#include "scriptmanager.h"
#include "logog/logog.hpp"
#include <fstream>
/* Constructors & Destructor
------------------------------------------------------------------------------*/
Engine::Engine() : is_running(true) {}
Engine::~Engine() {
// if (scene_root != NULL) {
// delete scene_root;
// }
delete engine_scriptor;
delete renderer;
delete input;
}
/* Public Interface
------------------------------------------------------------------------------*/
void Engine::load_config()
{
// Open default config file
{
using namespace std;
fstream config_file;
config_file.open("tempest.ini", fstream::in);
// Read configuration from file into configuration structure
// Close config file
config_file.close();
}
// Verify values and provide defaults if necessary
}
void Engine::init()
{
INFO("Initializing Engine.");
input = new InputManager();
renderer = new Renderer();
engine_scriptor = ScriptManager::new_environment("engine");
}
void Engine::run()
{
while (is_running)
{
process_input();
update();
render();
}
}
void Engine::process_input()
{
input->update_input_state();
}
void Engine::render() {}
void Engine::update() {}
<|endoftext|> |
<commit_before>/**
* @mainpage COSSB(Component-based Open & Simple Service Broker)
* @details COSSB�뒗 �궗臾쇱씤�꽣�꽬(IoT) �쑀臾댁꽑 �꽕�듃�썙�겕 �솚寃쎌뿉�꽌 留먮떒 �옣移섍컙 �꽌鍮꾩뒪 �긽�샇�슫�슜�꽦(Inter-operability)怨� �솗�옣�꽦�쓣 吏��썝 �븯湲곗쐞�븳 �냼�봽�듃�썾�뼱 �봽�젅�엫�썙�겕�엯�땲�떎.
*/
/**
* @file engine.cpp
* @brief COSSB Engine
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 9
* @details COSSB Engine main starter
*/
#include <iostream>
#include <csignal>
#include <cstdlib>
#include <popt.h>
#include <memory>
#include "cossb.hpp"
using namespace std;
using namespace cossb;
void destroy() {
cossb::core::cossb_destroy();
_exit(EXIT_SUCCESS);
}
/**
* @brief SIGINT signal callback function
* @details Stop all services and destroy all instances
*/
void sigc_interrupt(int param) {
destroy();
}
/**
* @brief Main routine
* @param command
* @details Start with default components
*/
int main(int argc, char* argv[])
{
signal(SIGINT, sigc_interrupt);
char* config_file = nullptr;
char* util = nullptr;
struct poptOption optionTable[] =
{
{"run", 'r', POPT_ARG_NONE, 0, 'r', "Run Engine with default configuration", ""},
{"version", 'v', POPT_ARG_NONE, 0, 'v', "Version", "version"},
{"config", 'c', POPT_ARG_STRING, (void*)config_file, 'c', "Open configuration file", "XML Configuration file"},
{"utility", 'u', POPT_ARG_STRING, (void*)util, 'u', "use COSSB utilities", "target utility"},
POPT_AUTOHELP
POPT_TABLEEND
};
poptContext optionCon = poptGetContext(NULL, argc, (const char**)argv, optionTable, 0);
poptSetOtherOptionHelp(optionCon, "<option>");
if(argc<2)
{
std::cout << poptStrerror(POPT_ERROR_NOARG) << endl;
_exit(EXIT_SUCCESS);
}
int opt = 0;
while((opt = poptGetNextOpt(optionCon))>=0)
{
switch(opt)
{
// install components
case 'v':
{
std::cout << COSSB_NAME << COSSB_VERSION << " (Released " << __DATE__ << " " <<__TIME__ << ")" << std::endl;
_exit(EXIT_SUCCESS);
} break;
//load configuration file
case 'c':
{
string manifest = (const char*)poptGetOptArg(optionCon);
if(!manifest.empty())
{
if(!cossb::core::cossb_init(manifest.c_str()))
destroy();
}
}
break;
//run with default configuration file(manifest.xml)
case 'r':
{
cossb_log->log(log::loglevel::INFO, "Initializing....");
if(!cossb::core::cossb_init("manifest.xml"))
destroy();
else
cossb_log->log(log::loglevel::INFO, fmt::format("{}{} Now Starting....",COSSB_NAME, COSSB_VERSION).c_str());
}
break;
//use COSSB utility
case 'u':
{
string target = (const char*)poptGetOptArg(optionCon);
cossb_log->log(log::loglevel::INFO, fmt::format("Execute COSSB {} Utility..", target).c_str());
interface::iutility* _utility = new util::utilloader(target.c_str());
_utility->launch(argc, argv);
delete _utility;
}
break;
}
}
if (opt<-1)
{
cout << poptBadOption(optionCon, POPT_BADOPTION_NOALIAS) << ":" << poptStrerror(opt) << endl;
destroy();
}
//start the cossb service
cossb::core::cossb_start();
pause();
poptFreeContext(optionCon);
destroy();
return 0;
}
<commit_msg>change for only one opt<commit_after>/**
* @mainpage COSSB(Component-based Open & Simple Service Broker)
* @details COSSB�뒗 �궗臾쇱씤�꽣�꽬(IoT) �쑀臾댁꽑 �꽕�듃�썙�겕 �솚寃쎌뿉�꽌 留먮떒 �옣移섍컙 �꽌鍮꾩뒪 �긽�샇�슫�슜�꽦(Inter-operability)怨� �솗�옣�꽦�쓣 吏��썝 �븯湲곗쐞�븳 �냼�봽�듃�썾�뼱 �봽�젅�엫�썙�겕�엯�땲�떎.
*/
/**
* @file engine.cpp
* @brief COSSB Engine
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 9
* @details COSSB Engine main starter
*/
#include <iostream>
#include <csignal>
#include <cstdlib>
#include <popt.h>
#include <memory>
#include "cossb.hpp"
using namespace std;
using namespace cossb;
void destroy() {
cossb::core::cossb_destroy();
_exit(EXIT_SUCCESS);
}
/**
* @brief SIGINT signal callback function
* @details Stop all services and destroy all instances
*/
void sigc_interrupt(int param) {
destroy();
}
/**
* @brief Main routine
* @param command
* @details Start with default components
*/
int main(int argc, char* argv[])
{
signal(SIGINT, sigc_interrupt);
char* config_file = nullptr;
char* util = nullptr;
struct poptOption optionTable[] =
{
{"run", 'r', POPT_ARG_NONE, 0, 'r', "Run Engine with default configuration", ""},
{"version", 'v', POPT_ARG_NONE, 0, 'v', "Version", "version"},
{"config", 'c', POPT_ARG_STRING, (void*)config_file, 'c', "Open configuration file", "XML Configuration file"},
{"utility", 'u', POPT_ARG_STRING, (void*)util, 'u', "Target utility name to use for COSSB", "target utility"},
POPT_AUTOHELP
POPT_TABLEEND
};
poptContext optionCon = poptGetContext(NULL, argc, (const char**)argv, optionTable, 0);
poptSetOtherOptionHelp(optionCon, "<option>");
if(argc<2)
{
std::cout << poptStrerror(POPT_ERROR_NOARG) << endl;
_exit(EXIT_SUCCESS);
}
//only one opt
int opt = poptGetNextOpt(optionCon);
if(opt>=0)
{
switch(opt)
{
// install components
case 'v':
{
std::cout << COSSB_NAME << COSSB_VERSION << " (Released " << __DATE__ << " " <<__TIME__ << ")" << std::endl;
_exit(EXIT_SUCCESS);
} break;
//load configuration file
case 'c':
{
string manifest = (const char*)poptGetOptArg(optionCon);
if(!manifest.empty())
{
if(!cossb::core::cossb_init(manifest.c_str()))
destroy();
else
cossb_log->log(log::loglevel::INFO, fmt::format("{}{} Now Starting....",COSSB_NAME, COSSB_VERSION).c_str());
//start the cossb service
cossb::core::cossb_start();
pause();
}
}
break;
//run with default configuration file(manifest.xml)
case 'r':
{
cossb_log->log(log::loglevel::INFO, "Initializing....");
if(!cossb::core::cossb_init("manifest.xml"))
destroy();
else
cossb_log->log(log::loglevel::INFO, fmt::format("{}{} Now Starting....",COSSB_NAME, COSSB_VERSION).c_str());
//start the cossb service
cossb::core::cossb_start();
pause();
}
break;
//use COSSB utility
case 'u':
{
string target = (const char*)poptGetOptArg(optionCon);
cossb_log->log(log::loglevel::INFO, fmt::format("Execute COSSB {} utility..", target).c_str());
interface::iutility* _utility = new util::utilloader(target.c_str());
_utility->launch(argc, argv);
delete _utility;
}
break;
}
}
if (opt<-1)
{
cout << poptBadOption(optionCon, POPT_BADOPTION_NOALIAS) << ":" << poptStrerror(opt) << endl;
destroy();
}
poptFreeContext(optionCon);
destroy();
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2011 Neevarp Yhtroom
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.
*/
#ifdef WIN32
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include "../src/Debug.h"
#include "../src/TestSet.h"
#include "TestString.h"
using namespace std;
using lepcpplib::TestSet;
class TestMain : public TestSet
{
public:
TestMain()
{
add(new TestString());
};
};
int main(int argc, char** argv)
{
TestMain* pTM = new TestMain();
unsigned int passCount = 0;
unsigned int failCount = 0;
pTM->run(passCount, failCount);
delete pTM;
#ifdef WIN32
_CrtDumpMemoryLeaks();
#endif
}
<commit_msg>Cleanup the main test runner.<commit_after>/*
Copyright (c) 2011 Neevarp Yhtroom
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 "../src/Debug.h"
#include "../src/TestSet.h"
#include "TestString.h"
using lepcpplib::TestSet;
class TestMain : public TestSet
{
public:
TestMain()
{
add(new TestString());
};
};
int main(int argc, char** argv)
{
TestMain* pTest = new TestMain();
unsigned int passCount = 0;
unsigned int failCount = 0;
pTest->run(passCount, failCount);
delete pTest;
#ifdef WIN32
_CrtDumpMemoryLeaks();
#endif
}
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "kudu/rpc/rpcz_store.h"
#include <algorithm> // IWYU pragma: keep
#include <array>
#include <cstdint>
#include <mutex> // for unique_lock
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <google/protobuf/message.h>
#include "kudu/gutil/port.h"
#include "kudu/gutil/ref_counted.h"
#include "kudu/gutil/strings/human_readable.h"
#include "kudu/gutil/strings/stringpiece.h"
#include "kudu/gutil/walltime.h"
#include "kudu/rpc/inbound_call.h"
#include "kudu/rpc/rpc_header.pb.h"
#include "kudu/rpc/rpc_introspection.pb.h"
#include "kudu/rpc/service_if.h"
#include "kudu/util/atomic.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/monotime.h"
#include "kudu/util/trace.h"
#include "kudu/util/trace_metrics.h"
DEFINE_bool(rpc_dump_all_traces, false,
"If true, dump all RPC traces at INFO level");
TAG_FLAG(rpc_dump_all_traces, advanced);
TAG_FLAG(rpc_dump_all_traces, runtime);
DEFINE_int32(rpc_duration_too_long_ms, 1000,
"Threshold (in milliseconds) above which a RPC is considered too long and its "
"duration and method name are logged at INFO level. The time measured is between "
"when a RPC is accepted and when its call handler completes.");
TAG_FLAG(rpc_duration_too_long_ms, advanced);
TAG_FLAG(rpc_duration_too_long_ms, runtime);
using std::pair;
using std::string;
using std::vector;
using std::unique_ptr;
namespace kudu {
namespace rpc {
// Sample an RPC call once every N milliseconds within each
// bucket. If the current sample in a latency bucket is older
// than this threshold, a new sample will be taken.
static const int kSampleIntervalMs = 1000;
static const int kBucketThresholdsMs[] = {10, 100, 1000};
static constexpr int kNumBuckets = arraysize(kBucketThresholdsMs) + 1;
// An instance of this class is created For each RPC method implemented
// on the server. It keeps several recent samples for each RPC, currently
// based on fixed time buckets.
class MethodSampler {
public:
MethodSampler() {}
~MethodSampler() {}
// Potentially sample a single call.
void SampleCall(InboundCall* call);
// Dump the current samples.
void GetSamplePBs(RpczMethodPB* pb);
private:
// Convert the trace metrics from 't' into protobuf entries in 'sample_pb'.
// This function recurses through the parent-child relationship graph,
// keeping the current tree path in 'child_path' (empty at the root).
static void GetTraceMetrics(const Trace& t,
const string& child_path,
RpczSamplePB* sample_pb);
// An individual recorded sample.
struct Sample {
RequestHeader header;
scoped_refptr<Trace> trace;
int duration_ms;
};
// A sample, including the particular time at which it was
// sampled, and a lock protecting it.
struct SampleBucket {
SampleBucket() : last_sample_time(0) {}
AtomicInt<int64_t> last_sample_time;
simple_spinlock sample_lock;
Sample sample;
};
std::array<SampleBucket, kNumBuckets> buckets_;
DISALLOW_COPY_AND_ASSIGN(MethodSampler);
};
MethodSampler* RpczStore::SamplerForCall(InboundCall* call) {
if (PREDICT_FALSE(!call->method_info())) {
return nullptr;
}
// Most likely, we already have a sampler created for the call.
{
shared_lock<rw_spinlock> l(samplers_lock_.get_lock());
auto it = method_samplers_.find(call->method_info());
if (PREDICT_TRUE(it != method_samplers_.end())) {
return it->second.get();
}
}
// If missing, create a new sampler for this method and try to insert it.
unique_ptr<MethodSampler> ms(new MethodSampler());
std::lock_guard<percpu_rwlock> lock(samplers_lock_);
auto it = method_samplers_.find(call->method_info());
if (it != method_samplers_.end()) {
return it->second.get();
}
auto* ret = ms.get();
method_samplers_[call->method_info()] = std::move(ms);
return ret;
}
void MethodSampler::SampleCall(InboundCall* call) {
// First determine which sample bucket to put this in.
int duration_ms = call->timing().TotalDuration().ToMilliseconds();
SampleBucket* bucket = &buckets_[kNumBuckets - 1];
for (int i = 0 ; i < kNumBuckets - 1; i++) {
if (duration_ms < kBucketThresholdsMs[i]) {
bucket = &buckets_[i];
break;
}
}
MicrosecondsInt64 now = GetMonoTimeMicros();
int64_t us_since_trace = now - bucket->last_sample_time.Load();
if (us_since_trace > kSampleIntervalMs * 1000) {
Sample new_sample = {call->header(), call->trace(), duration_ms};
{
std::unique_lock<simple_spinlock> lock(bucket->sample_lock, std::try_to_lock);
// If another thread is already taking a sample, it's not worth waiting.
if (!lock.owns_lock()) {
return;
}
std::swap(bucket->sample, new_sample);
bucket->last_sample_time.Store(now);
}
VLOG(2) << "Sampled call " << call->ToString();
}
}
void MethodSampler::GetTraceMetrics(const Trace& t,
const string& child_path,
RpczSamplePB* sample_pb) {
auto m = t.metrics().Get();
for (const auto& e : m) {
auto* pb = sample_pb->add_metrics();
pb->set_key(e.first);
pb->set_value(e.second);
if (!child_path.empty()) {
pb->set_child_path(child_path);
}
}
for (const auto& child_pair : t.ChildTraces()) {
string path = child_path;
if (!path.empty()) {
path += ".";
}
path += child_pair.first.ToString();
GetTraceMetrics(*child_pair.second.get(), path, sample_pb);
}
}
void MethodSampler::GetSamplePBs(RpczMethodPB* method_pb) {
for (auto& bucket : buckets_) {
if (bucket.last_sample_time.Load() == 0) continue;
std::unique_lock<simple_spinlock> lock(bucket.sample_lock);
auto* sample_pb = method_pb->add_samples();
sample_pb->mutable_header()->CopyFrom(bucket.sample.header);
sample_pb->set_trace(bucket.sample.trace->DumpToString(Trace::INCLUDE_TIME_DELTAS));
GetTraceMetrics(*bucket.sample.trace.get(), "", sample_pb);
sample_pb->set_duration_ms(bucket.sample.duration_ms);
}
}
RpczStore::RpczStore() {}
RpczStore::~RpczStore() {}
void RpczStore::AddCall(InboundCall* call) {
LogTrace(call);
auto* sampler = SamplerForCall(call);
if (PREDICT_FALSE(!sampler)) return;
sampler->SampleCall(call);
}
void RpczStore::DumpPB(const DumpRpczStoreRequestPB& req,
DumpRpczStoreResponsePB* resp) {
vector<pair<RpcMethodInfo*, MethodSampler*>> samplers;
{
shared_lock<rw_spinlock> l(samplers_lock_.get_lock());
for (const auto& p : method_samplers_) {
samplers.emplace_back(p.first, p.second.get());
}
}
for (const auto& p : samplers) {
auto* sampler = p.second;
RpczMethodPB* method_pb = resp->add_methods();
// TODO: use the actual RPC name instead of the request type name.
// Currently this isn't conveniently plumbed here, but the type name
// is close enough.
method_pb->set_method_name(p.first->req_prototype->GetTypeName());
sampler->GetSamplePBs(method_pb);
}
}
void RpczStore::LogTrace(InboundCall* call) {
int duration_ms = call->timing().TotalDuration().ToMilliseconds();
if (call->header_.has_timeout_millis() && call->header_.timeout_millis() > 0) {
double log_threshold = call->header_.timeout_millis() * 0.75f;
if (duration_ms > log_threshold) {
// TODO: consider pushing this onto another thread since it may be slow.
// The traces may also be too large to fit in a log message.
int64_t timeout_ms = call->header_.timeout_millis();
LOG(WARNING) << call->ToString() << " took " << duration_ms << " ms "
<< "(" << HumanReadableElapsedTime::ToShortString(duration_ms * .001) << "). "
<< "Client timeout " << timeout_ms << " ms "
<< "(" << HumanReadableElapsedTime::ToShortString(timeout_ms * .001) << ")";
string s = call->trace()->DumpToString();
if (!s.empty()) {
LOG(WARNING) << "Trace:\n" << s;
}
return;
}
}
if (PREDICT_FALSE(FLAGS_rpc_dump_all_traces)) {
LOG(INFO) << call->ToString() << " took " << duration_ms << "ms. Trace:";
call->trace()->Dump(&LOG(INFO), true);
} else if (duration_ms > FLAGS_rpc_duration_too_long_ms) {
LOG(INFO) << call->ToString() << " took " << duration_ms << "ms. "
<< "Request Metrics: " << call->trace()->MetricsAsJSON();
}
}
} // namespace rpc
} // namespace kudu
<commit_msg>KUDU-2996: trace when rpc_duration_too_long_ms exceeded<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "kudu/rpc/rpcz_store.h"
#include <algorithm> // IWYU pragma: keep
#include <array>
#include <cstdint>
#include <map>
#include <mutex> // for unique_lock
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <google/protobuf/message.h>
#include "kudu/gutil/port.h"
#include "kudu/gutil/ref_counted.h"
#include "kudu/gutil/strings/human_readable.h"
#include "kudu/gutil/strings/stringpiece.h"
#include "kudu/gutil/walltime.h"
#include "kudu/rpc/inbound_call.h"
#include "kudu/rpc/rpc_header.pb.h"
#include "kudu/rpc/rpc_introspection.pb.h"
#include "kudu/rpc/service_if.h"
#include "kudu/util/atomic.h"
#include "kudu/util/flag_tags.h"
#include "kudu/util/monotime.h"
#include "kudu/util/trace.h"
#include "kudu/util/trace_metrics.h"
DEFINE_bool(rpc_dump_all_traces, false,
"If true, dump all RPC traces at INFO level");
TAG_FLAG(rpc_dump_all_traces, advanced);
TAG_FLAG(rpc_dump_all_traces, runtime);
DEFINE_int32(rpc_duration_too_long_ms, 1000,
"Threshold (in milliseconds) above which a RPC is considered too long and its "
"duration and method name are logged at INFO level. The time measured is between "
"when a RPC is accepted and when its call handler completes.");
TAG_FLAG(rpc_duration_too_long_ms, advanced);
TAG_FLAG(rpc_duration_too_long_ms, runtime);
using std::pair;
using std::string;
using std::vector;
using std::unique_ptr;
namespace kudu {
namespace rpc {
// Sample an RPC call once every N milliseconds within each
// bucket. If the current sample in a latency bucket is older
// than this threshold, a new sample will be taken.
static const int kSampleIntervalMs = 1000;
static const int kBucketThresholdsMs[] = {10, 100, 1000};
static constexpr int kNumBuckets = arraysize(kBucketThresholdsMs) + 1;
// An instance of this class is created For each RPC method implemented
// on the server. It keeps several recent samples for each RPC, currently
// based on fixed time buckets.
class MethodSampler {
public:
MethodSampler() {}
~MethodSampler() {}
// Potentially sample a single call.
void SampleCall(InboundCall* call);
// Dump the current samples.
void GetSamplePBs(RpczMethodPB* pb);
private:
// Convert the trace metrics from 't' into protobuf entries in 'sample_pb'.
// This function recurses through the parent-child relationship graph,
// keeping the current tree path in 'child_path' (empty at the root).
static void GetTraceMetrics(const Trace& t,
const string& child_path,
RpczSamplePB* sample_pb);
// An individual recorded sample.
struct Sample {
RequestHeader header;
scoped_refptr<Trace> trace;
int duration_ms;
};
// A sample, including the particular time at which it was
// sampled, and a lock protecting it.
struct SampleBucket {
SampleBucket() : last_sample_time(0) {}
AtomicInt<int64_t> last_sample_time;
simple_spinlock sample_lock;
Sample sample;
};
std::array<SampleBucket, kNumBuckets> buckets_;
DISALLOW_COPY_AND_ASSIGN(MethodSampler);
};
MethodSampler* RpczStore::SamplerForCall(InboundCall* call) {
if (PREDICT_FALSE(!call->method_info())) {
return nullptr;
}
// Most likely, we already have a sampler created for the call.
{
shared_lock<rw_spinlock> l(samplers_lock_.get_lock());
auto it = method_samplers_.find(call->method_info());
if (PREDICT_TRUE(it != method_samplers_.end())) {
return it->second.get();
}
}
// If missing, create a new sampler for this method and try to insert it.
unique_ptr<MethodSampler> ms(new MethodSampler());
std::lock_guard<percpu_rwlock> lock(samplers_lock_);
auto it = method_samplers_.find(call->method_info());
if (it != method_samplers_.end()) {
return it->second.get();
}
auto* ret = ms.get();
method_samplers_[call->method_info()] = std::move(ms);
return ret;
}
void MethodSampler::SampleCall(InboundCall* call) {
// First determine which sample bucket to put this in.
int duration_ms = call->timing().TotalDuration().ToMilliseconds();
SampleBucket* bucket = &buckets_[kNumBuckets - 1];
for (int i = 0 ; i < kNumBuckets - 1; i++) {
if (duration_ms < kBucketThresholdsMs[i]) {
bucket = &buckets_[i];
break;
}
}
MicrosecondsInt64 now = GetMonoTimeMicros();
int64_t us_since_trace = now - bucket->last_sample_time.Load();
if (us_since_trace > kSampleIntervalMs * 1000) {
Sample new_sample = {call->header(), call->trace(), duration_ms};
{
std::unique_lock<simple_spinlock> lock(bucket->sample_lock, std::try_to_lock);
// If another thread is already taking a sample, it's not worth waiting.
if (!lock.owns_lock()) {
return;
}
std::swap(bucket->sample, new_sample);
bucket->last_sample_time.Store(now);
}
VLOG(2) << "Sampled call " << call->ToString();
}
}
void MethodSampler::GetTraceMetrics(const Trace& t,
const string& child_path,
RpczSamplePB* sample_pb) {
auto m = t.metrics().Get();
for (const auto& e : m) {
auto* pb = sample_pb->add_metrics();
pb->set_key(e.first);
pb->set_value(e.second);
if (!child_path.empty()) {
pb->set_child_path(child_path);
}
}
for (const auto& child_pair : t.ChildTraces()) {
string path = child_path;
if (!path.empty()) {
path += ".";
}
path += child_pair.first.ToString();
GetTraceMetrics(*child_pair.second.get(), path, sample_pb);
}
}
void MethodSampler::GetSamplePBs(RpczMethodPB* method_pb) {
for (auto& bucket : buckets_) {
if (bucket.last_sample_time.Load() == 0) continue;
std::unique_lock<simple_spinlock> lock(bucket.sample_lock);
auto* sample_pb = method_pb->add_samples();
sample_pb->mutable_header()->CopyFrom(bucket.sample.header);
sample_pb->set_trace(bucket.sample.trace->DumpToString(Trace::INCLUDE_TIME_DELTAS));
GetTraceMetrics(*bucket.sample.trace.get(), "", sample_pb);
sample_pb->set_duration_ms(bucket.sample.duration_ms);
}
}
RpczStore::RpczStore() {}
RpczStore::~RpczStore() {}
void RpczStore::AddCall(InboundCall* call) {
LogTrace(call);
auto* sampler = SamplerForCall(call);
if (PREDICT_FALSE(!sampler)) return;
sampler->SampleCall(call);
}
void RpczStore::DumpPB(const DumpRpczStoreRequestPB& req,
DumpRpczStoreResponsePB* resp) {
vector<pair<RpcMethodInfo*, MethodSampler*>> samplers;
{
shared_lock<rw_spinlock> l(samplers_lock_.get_lock());
for (const auto& p : method_samplers_) {
samplers.emplace_back(p.first, p.second.get());
}
}
for (const auto& p : samplers) {
auto* sampler = p.second;
RpczMethodPB* method_pb = resp->add_methods();
// TODO: use the actual RPC name instead of the request type name.
// Currently this isn't conveniently plumbed here, but the type name
// is close enough.
method_pb->set_method_name(p.first->req_prototype->GetTypeName());
sampler->GetSamplePBs(method_pb);
}
}
void RpczStore::LogTrace(InboundCall* call) {
int duration_ms = call->timing().TotalDuration().ToMilliseconds();
if (call->header_.has_timeout_millis() && call->header_.timeout_millis() > 0) {
double log_threshold = call->header_.timeout_millis() * 0.75f;
if (duration_ms > log_threshold) {
// TODO: consider pushing this onto another thread since it may be slow.
// The traces may also be too large to fit in a log message.
int64_t timeout_ms = call->header_.timeout_millis();
LOG(WARNING) << call->ToString() << " took " << duration_ms << " ms "
<< "(" << HumanReadableElapsedTime::ToShortString(duration_ms * .001) << "). "
<< "Client timeout " << timeout_ms << " ms "
<< "(" << HumanReadableElapsedTime::ToShortString(timeout_ms * .001) << ")";
string s = call->trace()->DumpToString();
if (!s.empty()) {
LOG(WARNING) << "Trace:\n" << s;
}
return;
}
}
if (duration_ms > FLAGS_rpc_duration_too_long_ms ||
PREDICT_FALSE(FLAGS_rpc_dump_all_traces)) {
const auto flags = (duration_ms > FLAGS_rpc_duration_too_long_ms)
? Trace::INCLUDE_ALL : Trace::INCLUDE_TIME_DELTAS;
LOG(INFO) << call->ToString() << " took " << duration_ms << "ms. Trace:";
call->trace()->Dump(&LOG(INFO), flags);
}
}
} // namespace rpc
} // namespace kudu
<|endoftext|> |
<commit_before>//===-- MipsInstPrinter.cpp - Convert Mips MCInst to assembly syntax ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class prints an Mips MCInst to a .s file.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "asm-printer"
#include "MipsInstPrinter.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#include "MipsGenAsmWriter.inc"
const char* Mips::MipsFCCToString(Mips::CondCode CC) {
switch (CC) {
case FCOND_F:
case FCOND_T: return "f";
case FCOND_UN:
case FCOND_OR: return "un";
case FCOND_OEQ:
case FCOND_UNE: return "eq";
case FCOND_UEQ:
case FCOND_ONE: return "ueq";
case FCOND_OLT:
case FCOND_UGE: return "olt";
case FCOND_ULT:
case FCOND_OGE: return "ult";
case FCOND_OLE:
case FCOND_UGT: return "ole";
case FCOND_ULE:
case FCOND_OGT: return "ule";
case FCOND_SF:
case FCOND_ST: return "sf";
case FCOND_NGLE:
case FCOND_GLE: return "ngle";
case FCOND_SEQ:
case FCOND_SNE: return "seq";
case FCOND_NGL:
case FCOND_GL: return "ngl";
case FCOND_LT:
case FCOND_NLT: return "lt";
case FCOND_NGE:
case FCOND_GE: return "nge";
case FCOND_LE:
case FCOND_NLE: return "le";
case FCOND_NGT:
case FCOND_GT: return "ngt";
}
llvm_unreachable("Impossible condition code!");
}
void MipsInstPrinter::printRegName(raw_ostream &OS, unsigned RegNo) const {
OS << '$' << StringRef(getRegisterName(RegNo)).lower();
}
void MipsInstPrinter::printInst(const MCInst *MI, raw_ostream &O,
StringRef Annot) {
printInstruction(MI, O);
printAnnotation(O, Annot);
}
static void printExpr(const MCExpr *Expr, raw_ostream &OS) {
int Offset = 0;
const MCSymbolRefExpr *SRE;
if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
SRE = dyn_cast<MCSymbolRefExpr>(BE->getLHS());
const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(BE->getRHS());
assert(SRE && CE && "Binary expression must be sym+const.");
Offset = CE->getValue();
}
else if (!(SRE = dyn_cast<MCSymbolRefExpr>(Expr)))
assert(false && "Unexpected MCExpr type.");
MCSymbolRefExpr::VariantKind Kind = SRE->getKind();
switch (Kind) {
default: llvm_unreachable("Invalid kind!");
case MCSymbolRefExpr::VK_None: break;
case MCSymbolRefExpr::VK_Mips_GPREL: OS << "%gp_rel("; break;
case MCSymbolRefExpr::VK_Mips_GOT_CALL: OS << "%call16("; break;
case MCSymbolRefExpr::VK_Mips_GOT16: OS << "%got("; break;
case MCSymbolRefExpr::VK_Mips_GOT: OS << "%got("; break;
case MCSymbolRefExpr::VK_Mips_ABS_HI: OS << "%hi("; break;
case MCSymbolRefExpr::VK_Mips_ABS_LO: OS << "%lo("; break;
case MCSymbolRefExpr::VK_Mips_TLSGD: OS << "%tlsgd("; break;
case MCSymbolRefExpr::VK_Mips_TLSLDM: OS << "%tlsldm("; break;
case MCSymbolRefExpr::VK_Mips_DTPREL_HI: OS << "%dtprel_hi("; break;
case MCSymbolRefExpr::VK_Mips_DTPREL_LO: OS << "%dtprel_lo("; break;
case MCSymbolRefExpr::VK_Mips_GOTTPREL: OS << "%gottprel("; break;
case MCSymbolRefExpr::VK_Mips_TPREL_HI: OS << "%tprel_hi("; break;
case MCSymbolRefExpr::VK_Mips_TPREL_LO: OS << "%tprel_lo("; break;
case MCSymbolRefExpr::VK_Mips_GPOFF_HI: OS << "%hi(%neg(%gp_rel("; break;
case MCSymbolRefExpr::VK_Mips_GPOFF_LO: OS << "%lo(%neg(%gp_rel("; break;
case MCSymbolRefExpr::VK_Mips_GOT_DISP: OS << "%got_disp("; break;
case MCSymbolRefExpr::VK_Mips_GOT_PAGE: OS << "%got_page("; break;
case MCSymbolRefExpr::VK_Mips_GOT_OFST: OS << "%got_ofst("; break;
}
OS << SRE->getSymbol();
if (Offset) {
if (Offset > 0)
OS << '+';
OS << Offset;
}
if ((Kind == MCSymbolRefExpr::VK_Mips_GPOFF_HI) ||
(Kind == MCSymbolRefExpr::VK_Mips_GPOFF_LO))
OS << ")))";
else if (Kind != MCSymbolRefExpr::VK_None)
OS << ')';
}
void MipsInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) {
const MCOperand &Op = MI->getOperand(OpNo);
if (Op.isReg()) {
printRegName(O, Op.getReg());
return;
}
if (Op.isImm()) {
O << Op.getImm();
return;
}
assert(Op.isExpr() && "unknown operand kind in printOperand");
printExpr(Op.getExpr(), O);
}
void MipsInstPrinter::printUnsignedImm(const MCInst *MI, int opNum,
raw_ostream &O) {
const MCOperand &MO = MI->getOperand(opNum);
if (MO.isImm())
O << (unsigned short int)MO.getImm();
else
printOperand(MI, opNum, O);
}
void MipsInstPrinter::
printMemOperand(const MCInst *MI, int opNum, raw_ostream &O) {
// Load/Store memory operands -- imm($reg)
// If PIC target the target is loaded as the
// pattern lw $25,%call16($28)
printOperand(MI, opNum+1, O);
O << "(";
printOperand(MI, opNum, O);
O << ")";
}
void MipsInstPrinter::
printMemOperandEA(const MCInst *MI, int opNum, raw_ostream &O) {
// when using stack locations for not load/store instructions
// print the same way as all normal 3 operand instructions.
printOperand(MI, opNum, O);
O << ", ";
printOperand(MI, opNum+1, O);
return;
}
void MipsInstPrinter::
printFCCOperand(const MCInst *MI, int opNum, raw_ostream &O) {
const MCOperand& MO = MI->getOperand(opNum);
O << MipsFCCToString((Mips::CondCode)MO.getImm());
}
<commit_msg>Enclose instruction rdhwr with directives, which are needed when target is mips32 rev1 (the directives are emitted when target is mips32r2 too).<commit_after>//===-- MipsInstPrinter.cpp - Convert Mips MCInst to assembly syntax ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class prints an Mips MCInst to a .s file.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "asm-printer"
#include "MipsInstPrinter.h"
#include "MipsInstrInfo.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#include "MipsGenAsmWriter.inc"
const char* Mips::MipsFCCToString(Mips::CondCode CC) {
switch (CC) {
case FCOND_F:
case FCOND_T: return "f";
case FCOND_UN:
case FCOND_OR: return "un";
case FCOND_OEQ:
case FCOND_UNE: return "eq";
case FCOND_UEQ:
case FCOND_ONE: return "ueq";
case FCOND_OLT:
case FCOND_UGE: return "olt";
case FCOND_ULT:
case FCOND_OGE: return "ult";
case FCOND_OLE:
case FCOND_UGT: return "ole";
case FCOND_ULE:
case FCOND_OGT: return "ule";
case FCOND_SF:
case FCOND_ST: return "sf";
case FCOND_NGLE:
case FCOND_GLE: return "ngle";
case FCOND_SEQ:
case FCOND_SNE: return "seq";
case FCOND_NGL:
case FCOND_GL: return "ngl";
case FCOND_LT:
case FCOND_NLT: return "lt";
case FCOND_NGE:
case FCOND_GE: return "nge";
case FCOND_LE:
case FCOND_NLE: return "le";
case FCOND_NGT:
case FCOND_GT: return "ngt";
}
llvm_unreachable("Impossible condition code!");
}
void MipsInstPrinter::printRegName(raw_ostream &OS, unsigned RegNo) const {
OS << '$' << StringRef(getRegisterName(RegNo)).lower();
}
void MipsInstPrinter::printInst(const MCInst *MI, raw_ostream &O,
StringRef Annot) {
switch (MI->getOpcode()) {
default:
break;
case Mips::RDHWR:
case Mips::RDHWR64:
O << "\t.set\tpush\n";
O << "\t.set\tmips32r2\n";
}
printInstruction(MI, O);
printAnnotation(O, Annot);
switch (MI->getOpcode()) {
default:
break;
case Mips::RDHWR:
case Mips::RDHWR64:
O << "\n\t.set\tpop";
}
}
static void printExpr(const MCExpr *Expr, raw_ostream &OS) {
int Offset = 0;
const MCSymbolRefExpr *SRE;
if (const MCBinaryExpr *BE = dyn_cast<MCBinaryExpr>(Expr)) {
SRE = dyn_cast<MCSymbolRefExpr>(BE->getLHS());
const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(BE->getRHS());
assert(SRE && CE && "Binary expression must be sym+const.");
Offset = CE->getValue();
}
else if (!(SRE = dyn_cast<MCSymbolRefExpr>(Expr)))
assert(false && "Unexpected MCExpr type.");
MCSymbolRefExpr::VariantKind Kind = SRE->getKind();
switch (Kind) {
default: llvm_unreachable("Invalid kind!");
case MCSymbolRefExpr::VK_None: break;
case MCSymbolRefExpr::VK_Mips_GPREL: OS << "%gp_rel("; break;
case MCSymbolRefExpr::VK_Mips_GOT_CALL: OS << "%call16("; break;
case MCSymbolRefExpr::VK_Mips_GOT16: OS << "%got("; break;
case MCSymbolRefExpr::VK_Mips_GOT: OS << "%got("; break;
case MCSymbolRefExpr::VK_Mips_ABS_HI: OS << "%hi("; break;
case MCSymbolRefExpr::VK_Mips_ABS_LO: OS << "%lo("; break;
case MCSymbolRefExpr::VK_Mips_TLSGD: OS << "%tlsgd("; break;
case MCSymbolRefExpr::VK_Mips_TLSLDM: OS << "%tlsldm("; break;
case MCSymbolRefExpr::VK_Mips_DTPREL_HI: OS << "%dtprel_hi("; break;
case MCSymbolRefExpr::VK_Mips_DTPREL_LO: OS << "%dtprel_lo("; break;
case MCSymbolRefExpr::VK_Mips_GOTTPREL: OS << "%gottprel("; break;
case MCSymbolRefExpr::VK_Mips_TPREL_HI: OS << "%tprel_hi("; break;
case MCSymbolRefExpr::VK_Mips_TPREL_LO: OS << "%tprel_lo("; break;
case MCSymbolRefExpr::VK_Mips_GPOFF_HI: OS << "%hi(%neg(%gp_rel("; break;
case MCSymbolRefExpr::VK_Mips_GPOFF_LO: OS << "%lo(%neg(%gp_rel("; break;
case MCSymbolRefExpr::VK_Mips_GOT_DISP: OS << "%got_disp("; break;
case MCSymbolRefExpr::VK_Mips_GOT_PAGE: OS << "%got_page("; break;
case MCSymbolRefExpr::VK_Mips_GOT_OFST: OS << "%got_ofst("; break;
}
OS << SRE->getSymbol();
if (Offset) {
if (Offset > 0)
OS << '+';
OS << Offset;
}
if ((Kind == MCSymbolRefExpr::VK_Mips_GPOFF_HI) ||
(Kind == MCSymbolRefExpr::VK_Mips_GPOFF_LO))
OS << ")))";
else if (Kind != MCSymbolRefExpr::VK_None)
OS << ')';
}
void MipsInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O) {
const MCOperand &Op = MI->getOperand(OpNo);
if (Op.isReg()) {
printRegName(O, Op.getReg());
return;
}
if (Op.isImm()) {
O << Op.getImm();
return;
}
assert(Op.isExpr() && "unknown operand kind in printOperand");
printExpr(Op.getExpr(), O);
}
void MipsInstPrinter::printUnsignedImm(const MCInst *MI, int opNum,
raw_ostream &O) {
const MCOperand &MO = MI->getOperand(opNum);
if (MO.isImm())
O << (unsigned short int)MO.getImm();
else
printOperand(MI, opNum, O);
}
void MipsInstPrinter::
printMemOperand(const MCInst *MI, int opNum, raw_ostream &O) {
// Load/Store memory operands -- imm($reg)
// If PIC target the target is loaded as the
// pattern lw $25,%call16($28)
printOperand(MI, opNum+1, O);
O << "(";
printOperand(MI, opNum, O);
O << ")";
}
void MipsInstPrinter::
printMemOperandEA(const MCInst *MI, int opNum, raw_ostream &O) {
// when using stack locations for not load/store instructions
// print the same way as all normal 3 operand instructions.
printOperand(MI, opNum, O);
O << ", ";
printOperand(MI, opNum+1, O);
return;
}
void MipsInstPrinter::
printFCCOperand(const MCInst *MI, int opNum, raw_ostream &O) {
const MCOperand& MO = MI->getOperand(opNum);
O << MipsFCCToString((Mips::CondCode)MO.getImm());
}
<|endoftext|> |
<commit_before>//===--------------------- R600MergeVectorRegisters.cpp -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This pass merges inputs of swizzeable instructions into vector sharing
/// common data and/or have enough undef subreg using swizzle abilities.
///
/// For instance let's consider the following pseudo code :
/// vreg5<def> = REG_SEQ vreg1, sub0, vreg2, sub1, vreg3, sub2, undef, sub3
/// ...
/// vreg7<def> = REG_SEQ vreg1, sub0, vreg3, sub1, undef, sub2, vreg4, sub3
/// (swizzable Inst) vreg7, SwizzleMask : sub0, sub1, sub2, sub3
///
/// is turned into :
/// vreg5<def> = REG_SEQ vreg1, sub0, vreg2, sub1, vreg3, sub2, undef, sub3
/// ...
/// vreg7<def> = INSERT_SUBREG vreg4, sub3
/// (swizzable Inst) vreg7, SwizzleMask : sub0, sub2, sub1, sub3
///
/// This allow regalloc to reduce register pressure for vector registers and
/// to reduce MOV count.
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "vec-merger"
#include "llvm/Support/Debug.h"
#include "AMDGPU.h"
#include "R600InstrInfo.h"
#include "llvm/CodeGen/DFAPacketizer.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
using namespace llvm;
namespace {
static bool
isImplicitlyDef(MachineRegisterInfo &MRI, unsigned Reg) {
for (MachineRegisterInfo::def_iterator It = MRI.def_begin(Reg),
E = MRI.def_end(); It != E; ++It) {
return (*It).isImplicitDef();
}
llvm_unreachable("Reg without a def");
return false;
}
class RegSeqInfo {
public:
MachineInstr *Instr;
DenseMap<unsigned, unsigned> RegToChan;
std::vector<unsigned> UndefReg;
RegSeqInfo(MachineRegisterInfo &MRI, MachineInstr *MI) : Instr(MI) {
assert (MI->getOpcode() == AMDGPU::REG_SEQUENCE);
for (unsigned i = 1, e = Instr->getNumOperands(); i < e; i+=2) {
MachineOperand &MO = Instr->getOperand(i);
unsigned Chan = Instr->getOperand(i + 1).getImm();
if (isImplicitlyDef(MRI, MO.getReg()))
UndefReg.push_back(Chan);
else
RegToChan[MO.getReg()] = Chan;
}
}
RegSeqInfo() {}
bool operator==(const RegSeqInfo &RSI) const {
return RSI.Instr == Instr;
}
};
class R600VectorRegMerger : public MachineFunctionPass {
private:
MachineRegisterInfo *MRI;
const R600InstrInfo *TII;
bool canSwizzle(const MachineInstr &) const;
bool areAllUsesSwizzeable(unsigned Reg) const;
void SwizzleInput(MachineInstr &,
const std::vector<std::pair<unsigned, unsigned> > &) const;
bool tryMergeVector(const RegSeqInfo *, RegSeqInfo *,
std::vector<std::pair<unsigned, unsigned> > &Remap) const;
bool tryMergeUsingCommonSlot(RegSeqInfo &RSI, RegSeqInfo &CompatibleRSI,
std::vector<std::pair<unsigned, unsigned> > &RemapChan);
bool tryMergeUsingFreeSlot(RegSeqInfo &RSI, RegSeqInfo &CompatibleRSI,
std::vector<std::pair<unsigned, unsigned> > &RemapChan);
MachineInstr *RebuildVector(RegSeqInfo *MI,
const RegSeqInfo *BaseVec,
const std::vector<std::pair<unsigned, unsigned> > &RemapChan) const;
void RemoveMI(MachineInstr *);
void trackRSI(const RegSeqInfo &RSI);
typedef DenseMap<unsigned, std::vector<MachineInstr *> > InstructionSetMap;
DenseMap<MachineInstr *, RegSeqInfo> PreviousRegSeq;
InstructionSetMap PreviousRegSeqByReg;
InstructionSetMap PreviousRegSeqByUndefCount;
public:
static char ID;
R600VectorRegMerger(TargetMachine &tm) : MachineFunctionPass(ID),
TII (static_cast<const R600InstrInfo *>(tm.getInstrInfo())) { }
void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<MachineDominatorTree>();
AU.addPreserved<MachineDominatorTree>();
AU.addRequired<MachineLoopInfo>();
AU.addPreserved<MachineLoopInfo>();
MachineFunctionPass::getAnalysisUsage(AU);
}
const char *getPassName() const {
return "R600 Vector Registers Merge Pass";
}
bool runOnMachineFunction(MachineFunction &Fn);
};
char R600VectorRegMerger::ID = 0;
bool R600VectorRegMerger::canSwizzle(const MachineInstr &MI)
const {
if (TII->get(MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)
return true;
switch (MI.getOpcode()) {
case AMDGPU::R600_ExportSwz:
case AMDGPU::EG_ExportSwz:
return true;
default:
return false;
}
}
bool R600VectorRegMerger::tryMergeVector(const RegSeqInfo *Untouched,
RegSeqInfo *ToMerge, std::vector< std::pair<unsigned, unsigned> > &Remap)
const {
unsigned CurrentUndexIdx = 0;
for (DenseMap<unsigned, unsigned>::iterator It = ToMerge->RegToChan.begin(),
E = ToMerge->RegToChan.end(); It != E; ++It) {
DenseMap<unsigned, unsigned>::const_iterator PosInUntouched =
Untouched->RegToChan.find((*It).first);
if (PosInUntouched != Untouched->RegToChan.end()) {
Remap.push_back(std::pair<unsigned, unsigned>
((*It).second, (*PosInUntouched).second));
continue;
}
if (CurrentUndexIdx >= Untouched->UndefReg.size())
return false;
Remap.push_back(std::pair<unsigned, unsigned>
((*It).second, Untouched->UndefReg[CurrentUndexIdx++]));
}
return true;
}
MachineInstr *R600VectorRegMerger::RebuildVector(
RegSeqInfo *RSI, const RegSeqInfo *BaseRSI,
const std::vector<std::pair<unsigned, unsigned> > &RemapChan) const {
unsigned Reg = RSI->Instr->getOperand(0).getReg();
MachineBasicBlock::iterator Pos = RSI->Instr;
MachineBasicBlock &MBB = *Pos->getParent();
DebugLoc DL = Pos->getDebugLoc();
unsigned SrcVec = BaseRSI->Instr->getOperand(0).getReg();
DenseMap<unsigned, unsigned> UpdatedRegToChan = BaseRSI->RegToChan;
std::vector<unsigned> UpdatedUndef = BaseRSI->UndefReg;
for (DenseMap<unsigned, unsigned>::iterator It = RSI->RegToChan.begin(),
E = RSI->RegToChan.end(); It != E; ++It) {
if (BaseRSI->RegToChan.find((*It).first) != BaseRSI->RegToChan.end()) {
UpdatedRegToChan[(*It).first] = (*It).second;
continue;
}
unsigned DstReg = MRI->createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
unsigned SubReg = (*It).first;
unsigned Swizzle = (*It).second;
unsigned Chan;
for (unsigned j = 0, je = RemapChan.size(); j < je; j++) {
if (RemapChan[j].first == Swizzle) {
Chan = RemapChan[j].second;
break;
}
}
MachineInstr *Tmp = BuildMI(MBB, Pos, DL, TII->get(AMDGPU::INSERT_SUBREG),
DstReg)
.addReg(SrcVec)
.addReg(SubReg)
.addImm(Chan);
UpdatedRegToChan[SubReg] = Chan;
for (std::vector<unsigned>::iterator RemoveIt = UpdatedUndef.begin(),
RemoveE = UpdatedUndef.end(); RemoveIt != RemoveE; ++ RemoveIt) {
if (*RemoveIt == Chan)
UpdatedUndef.erase(RemoveIt);
}
DEBUG(dbgs() << " ->"; Tmp->dump(););
SrcVec = DstReg;
}
Pos = BuildMI(MBB, Pos, DL, TII->get(AMDGPU::COPY), Reg)
.addReg(SrcVec);
DEBUG(dbgs() << " ->"; Pos->dump(););
DEBUG(dbgs() << " Updating Swizzle:\n");
for (MachineRegisterInfo::use_iterator It = MRI->use_begin(Reg),
E = MRI->use_end(); It != E; ++It) {
DEBUG(dbgs() << " ";(*It).dump(); dbgs() << " ->");
SwizzleInput(*It, RemapChan);
DEBUG((*It).dump());
}
RSI->Instr->eraseFromParent();
// Update RSI
RSI->Instr = Pos;
RSI->RegToChan = UpdatedRegToChan;
RSI->UndefReg = UpdatedUndef;
return Pos;
}
void R600VectorRegMerger::RemoveMI(MachineInstr *MI) {
for (InstructionSetMap::iterator It = PreviousRegSeqByReg.begin(),
E = PreviousRegSeqByReg.end(); It != E; ++It) {
std::vector<MachineInstr *> &MIs = (*It).second;
MIs.erase(std::find(MIs.begin(), MIs.end(), MI), MIs.end());
}
for (InstructionSetMap::iterator It = PreviousRegSeqByUndefCount.begin(),
E = PreviousRegSeqByUndefCount.end(); It != E; ++It) {
std::vector<MachineInstr *> &MIs = (*It).second;
MIs.erase(std::find(MIs.begin(), MIs.end(), MI), MIs.end());
}
}
void R600VectorRegMerger::SwizzleInput(MachineInstr &MI,
const std::vector<std::pair<unsigned, unsigned> > &RemapChan) const {
unsigned Offset;
if (TII->get(MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)
Offset = 2;
else
Offset = 3;
for (unsigned i = 0; i < 4; i++) {
unsigned Swizzle = MI.getOperand(i + Offset).getImm() + 1;
for (unsigned j = 0, e = RemapChan.size(); j < e; j++) {
if (RemapChan[j].first == Swizzle) {
MI.getOperand(i + Offset).setImm(RemapChan[j].second - 1);
break;
}
}
}
}
bool R600VectorRegMerger::areAllUsesSwizzeable(unsigned Reg) const {
for (MachineRegisterInfo::use_iterator It = MRI->use_begin(Reg),
E = MRI->use_end(); It != E; ++It) {
if (!canSwizzle(*It))
return false;
}
return true;
}
bool R600VectorRegMerger::tryMergeUsingCommonSlot(RegSeqInfo &RSI,
RegSeqInfo &CompatibleRSI,
std::vector<std::pair<unsigned, unsigned> > &RemapChan) {
for (MachineInstr::mop_iterator MOp = RSI.Instr->operands_begin(),
MOE = RSI.Instr->operands_end(); MOp != MOE; ++MOp) {
if (!MOp->isReg())
continue;
if (PreviousRegSeqByReg[MOp->getReg()].empty())
continue;
std::vector<MachineInstr *> MIs = PreviousRegSeqByReg[MOp->getReg()];
for (unsigned i = 0, e = MIs.size(); i < e; i++) {
CompatibleRSI = PreviousRegSeq[MIs[i]];
if (RSI == CompatibleRSI)
continue;
if (tryMergeVector(&CompatibleRSI, &RSI, RemapChan))
return true;
}
}
return false;
}
bool R600VectorRegMerger::tryMergeUsingFreeSlot(RegSeqInfo &RSI,
RegSeqInfo &CompatibleRSI,
std::vector<std::pair<unsigned, unsigned> > &RemapChan) {
unsigned NeededUndefs = 4 - RSI.UndefReg.size();
if (PreviousRegSeqByUndefCount[NeededUndefs].empty())
return false;
std::vector<MachineInstr *> &MIs =
PreviousRegSeqByUndefCount[NeededUndefs];
CompatibleRSI = PreviousRegSeq[MIs.back()];
tryMergeVector(&CompatibleRSI, &RSI, RemapChan);
return true;
}
void R600VectorRegMerger::trackRSI(const RegSeqInfo &RSI) {
for (DenseMap<unsigned, unsigned>::const_iterator
It = RSI.RegToChan.begin(), E = RSI.RegToChan.end(); It != E; ++It) {
PreviousRegSeqByReg[(*It).first].push_back(RSI.Instr);
}
PreviousRegSeqByUndefCount[RSI.UndefReg.size()].push_back(RSI.Instr);
PreviousRegSeq[RSI.Instr] = RSI;
}
bool R600VectorRegMerger::runOnMachineFunction(MachineFunction &Fn) {
MRI = &(Fn.getRegInfo());
for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
MBB != MBBe; ++MBB) {
MachineBasicBlock *MB = MBB;
PreviousRegSeq.clear();
PreviousRegSeqByReg.clear();
PreviousRegSeqByUndefCount.clear();
for (MachineBasicBlock::iterator MII = MB->begin(), MIIE = MB->end();
MII != MIIE; ++MII) {
MachineInstr *MI = MII;
if (MI->getOpcode() != AMDGPU::REG_SEQUENCE)
continue;
RegSeqInfo RSI(*MRI, MI);
// All uses of MI are swizzeable ?
unsigned Reg = MI->getOperand(0).getReg();
if (!areAllUsesSwizzeable(Reg))
continue;
DEBUG (dbgs() << "Trying to optimize ";
MI->dump();
);
RegSeqInfo CandidateRSI;
std::vector<std::pair<unsigned, unsigned> > RemapChan;
DEBUG(dbgs() << "Using common slots...\n";);
if (tryMergeUsingCommonSlot(RSI, CandidateRSI, RemapChan)) {
// Remove CandidateRSI mapping
RemoveMI(CandidateRSI.Instr);
MII = RebuildVector(&RSI, &CandidateRSI, RemapChan);
trackRSI(RSI);
continue;
}
DEBUG(dbgs() << "Using free slots...\n";);
RemapChan.clear();
if (tryMergeUsingFreeSlot(RSI, CandidateRSI, RemapChan)) {
RemoveMI(CandidateRSI.Instr);
MII = RebuildVector(&RSI, &CandidateRSI, RemapChan);
trackRSI(RSI);
continue;
}
//Failed to merge
trackRSI(RSI);
}
}
return false;
}
}
llvm::FunctionPass *llvm::createR600VectorRegMerger(TargetMachine &tm) {
return new R600VectorRegMerger(tm);
}
<commit_msg>Trailing linefeed.<commit_after>//===--------------------- R600MergeVectorRegisters.cpp -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This pass merges inputs of swizzeable instructions into vector sharing
/// common data and/or have enough undef subreg using swizzle abilities.
///
/// For instance let's consider the following pseudo code :
/// vreg5<def> = REG_SEQ vreg1, sub0, vreg2, sub1, vreg3, sub2, undef, sub3
/// ...
/// vreg7<def> = REG_SEQ vreg1, sub0, vreg3, sub1, undef, sub2, vreg4, sub3
/// (swizzable Inst) vreg7, SwizzleMask : sub0, sub1, sub2, sub3
///
/// is turned into :
/// vreg5<def> = REG_SEQ vreg1, sub0, vreg2, sub1, vreg3, sub2, undef, sub3
/// ...
/// vreg7<def> = INSERT_SUBREG vreg4, sub3
/// (swizzable Inst) vreg7, SwizzleMask : sub0, sub2, sub1, sub3
///
/// This allow regalloc to reduce register pressure for vector registers and
/// to reduce MOV count.
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "vec-merger"
#include "llvm/Support/Debug.h"
#include "AMDGPU.h"
#include "R600InstrInfo.h"
#include "llvm/CodeGen/DFAPacketizer.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
using namespace llvm;
namespace {
static bool
isImplicitlyDef(MachineRegisterInfo &MRI, unsigned Reg) {
for (MachineRegisterInfo::def_iterator It = MRI.def_begin(Reg),
E = MRI.def_end(); It != E; ++It) {
return (*It).isImplicitDef();
}
llvm_unreachable("Reg without a def");
return false;
}
class RegSeqInfo {
public:
MachineInstr *Instr;
DenseMap<unsigned, unsigned> RegToChan;
std::vector<unsigned> UndefReg;
RegSeqInfo(MachineRegisterInfo &MRI, MachineInstr *MI) : Instr(MI) {
assert (MI->getOpcode() == AMDGPU::REG_SEQUENCE);
for (unsigned i = 1, e = Instr->getNumOperands(); i < e; i+=2) {
MachineOperand &MO = Instr->getOperand(i);
unsigned Chan = Instr->getOperand(i + 1).getImm();
if (isImplicitlyDef(MRI, MO.getReg()))
UndefReg.push_back(Chan);
else
RegToChan[MO.getReg()] = Chan;
}
}
RegSeqInfo() {}
bool operator==(const RegSeqInfo &RSI) const {
return RSI.Instr == Instr;
}
};
class R600VectorRegMerger : public MachineFunctionPass {
private:
MachineRegisterInfo *MRI;
const R600InstrInfo *TII;
bool canSwizzle(const MachineInstr &) const;
bool areAllUsesSwizzeable(unsigned Reg) const;
void SwizzleInput(MachineInstr &,
const std::vector<std::pair<unsigned, unsigned> > &) const;
bool tryMergeVector(const RegSeqInfo *, RegSeqInfo *,
std::vector<std::pair<unsigned, unsigned> > &Remap) const;
bool tryMergeUsingCommonSlot(RegSeqInfo &RSI, RegSeqInfo &CompatibleRSI,
std::vector<std::pair<unsigned, unsigned> > &RemapChan);
bool tryMergeUsingFreeSlot(RegSeqInfo &RSI, RegSeqInfo &CompatibleRSI,
std::vector<std::pair<unsigned, unsigned> > &RemapChan);
MachineInstr *RebuildVector(RegSeqInfo *MI,
const RegSeqInfo *BaseVec,
const std::vector<std::pair<unsigned, unsigned> > &RemapChan) const;
void RemoveMI(MachineInstr *);
void trackRSI(const RegSeqInfo &RSI);
typedef DenseMap<unsigned, std::vector<MachineInstr *> > InstructionSetMap;
DenseMap<MachineInstr *, RegSeqInfo> PreviousRegSeq;
InstructionSetMap PreviousRegSeqByReg;
InstructionSetMap PreviousRegSeqByUndefCount;
public:
static char ID;
R600VectorRegMerger(TargetMachine &tm) : MachineFunctionPass(ID),
TII (static_cast<const R600InstrInfo *>(tm.getInstrInfo())) { }
void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<MachineDominatorTree>();
AU.addPreserved<MachineDominatorTree>();
AU.addRequired<MachineLoopInfo>();
AU.addPreserved<MachineLoopInfo>();
MachineFunctionPass::getAnalysisUsage(AU);
}
const char *getPassName() const {
return "R600 Vector Registers Merge Pass";
}
bool runOnMachineFunction(MachineFunction &Fn);
};
char R600VectorRegMerger::ID = 0;
bool R600VectorRegMerger::canSwizzle(const MachineInstr &MI)
const {
if (TII->get(MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)
return true;
switch (MI.getOpcode()) {
case AMDGPU::R600_ExportSwz:
case AMDGPU::EG_ExportSwz:
return true;
default:
return false;
}
}
bool R600VectorRegMerger::tryMergeVector(const RegSeqInfo *Untouched,
RegSeqInfo *ToMerge, std::vector< std::pair<unsigned, unsigned> > &Remap)
const {
unsigned CurrentUndexIdx = 0;
for (DenseMap<unsigned, unsigned>::iterator It = ToMerge->RegToChan.begin(),
E = ToMerge->RegToChan.end(); It != E; ++It) {
DenseMap<unsigned, unsigned>::const_iterator PosInUntouched =
Untouched->RegToChan.find((*It).first);
if (PosInUntouched != Untouched->RegToChan.end()) {
Remap.push_back(std::pair<unsigned, unsigned>
((*It).second, (*PosInUntouched).second));
continue;
}
if (CurrentUndexIdx >= Untouched->UndefReg.size())
return false;
Remap.push_back(std::pair<unsigned, unsigned>
((*It).second, Untouched->UndefReg[CurrentUndexIdx++]));
}
return true;
}
MachineInstr *R600VectorRegMerger::RebuildVector(
RegSeqInfo *RSI, const RegSeqInfo *BaseRSI,
const std::vector<std::pair<unsigned, unsigned> > &RemapChan) const {
unsigned Reg = RSI->Instr->getOperand(0).getReg();
MachineBasicBlock::iterator Pos = RSI->Instr;
MachineBasicBlock &MBB = *Pos->getParent();
DebugLoc DL = Pos->getDebugLoc();
unsigned SrcVec = BaseRSI->Instr->getOperand(0).getReg();
DenseMap<unsigned, unsigned> UpdatedRegToChan = BaseRSI->RegToChan;
std::vector<unsigned> UpdatedUndef = BaseRSI->UndefReg;
for (DenseMap<unsigned, unsigned>::iterator It = RSI->RegToChan.begin(),
E = RSI->RegToChan.end(); It != E; ++It) {
if (BaseRSI->RegToChan.find((*It).first) != BaseRSI->RegToChan.end()) {
UpdatedRegToChan[(*It).first] = (*It).second;
continue;
}
unsigned DstReg = MRI->createVirtualRegister(&AMDGPU::R600_Reg128RegClass);
unsigned SubReg = (*It).first;
unsigned Swizzle = (*It).second;
unsigned Chan;
for (unsigned j = 0, je = RemapChan.size(); j < je; j++) {
if (RemapChan[j].first == Swizzle) {
Chan = RemapChan[j].second;
break;
}
}
MachineInstr *Tmp = BuildMI(MBB, Pos, DL, TII->get(AMDGPU::INSERT_SUBREG),
DstReg)
.addReg(SrcVec)
.addReg(SubReg)
.addImm(Chan);
UpdatedRegToChan[SubReg] = Chan;
for (std::vector<unsigned>::iterator RemoveIt = UpdatedUndef.begin(),
RemoveE = UpdatedUndef.end(); RemoveIt != RemoveE; ++ RemoveIt) {
if (*RemoveIt == Chan)
UpdatedUndef.erase(RemoveIt);
}
DEBUG(dbgs() << " ->"; Tmp->dump(););
SrcVec = DstReg;
}
Pos = BuildMI(MBB, Pos, DL, TII->get(AMDGPU::COPY), Reg)
.addReg(SrcVec);
DEBUG(dbgs() << " ->"; Pos->dump(););
DEBUG(dbgs() << " Updating Swizzle:\n");
for (MachineRegisterInfo::use_iterator It = MRI->use_begin(Reg),
E = MRI->use_end(); It != E; ++It) {
DEBUG(dbgs() << " ";(*It).dump(); dbgs() << " ->");
SwizzleInput(*It, RemapChan);
DEBUG((*It).dump());
}
RSI->Instr->eraseFromParent();
// Update RSI
RSI->Instr = Pos;
RSI->RegToChan = UpdatedRegToChan;
RSI->UndefReg = UpdatedUndef;
return Pos;
}
void R600VectorRegMerger::RemoveMI(MachineInstr *MI) {
for (InstructionSetMap::iterator It = PreviousRegSeqByReg.begin(),
E = PreviousRegSeqByReg.end(); It != E; ++It) {
std::vector<MachineInstr *> &MIs = (*It).second;
MIs.erase(std::find(MIs.begin(), MIs.end(), MI), MIs.end());
}
for (InstructionSetMap::iterator It = PreviousRegSeqByUndefCount.begin(),
E = PreviousRegSeqByUndefCount.end(); It != E; ++It) {
std::vector<MachineInstr *> &MIs = (*It).second;
MIs.erase(std::find(MIs.begin(), MIs.end(), MI), MIs.end());
}
}
void R600VectorRegMerger::SwizzleInput(MachineInstr &MI,
const std::vector<std::pair<unsigned, unsigned> > &RemapChan) const {
unsigned Offset;
if (TII->get(MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)
Offset = 2;
else
Offset = 3;
for (unsigned i = 0; i < 4; i++) {
unsigned Swizzle = MI.getOperand(i + Offset).getImm() + 1;
for (unsigned j = 0, e = RemapChan.size(); j < e; j++) {
if (RemapChan[j].first == Swizzle) {
MI.getOperand(i + Offset).setImm(RemapChan[j].second - 1);
break;
}
}
}
}
bool R600VectorRegMerger::areAllUsesSwizzeable(unsigned Reg) const {
for (MachineRegisterInfo::use_iterator It = MRI->use_begin(Reg),
E = MRI->use_end(); It != E; ++It) {
if (!canSwizzle(*It))
return false;
}
return true;
}
bool R600VectorRegMerger::tryMergeUsingCommonSlot(RegSeqInfo &RSI,
RegSeqInfo &CompatibleRSI,
std::vector<std::pair<unsigned, unsigned> > &RemapChan) {
for (MachineInstr::mop_iterator MOp = RSI.Instr->operands_begin(),
MOE = RSI.Instr->operands_end(); MOp != MOE; ++MOp) {
if (!MOp->isReg())
continue;
if (PreviousRegSeqByReg[MOp->getReg()].empty())
continue;
std::vector<MachineInstr *> MIs = PreviousRegSeqByReg[MOp->getReg()];
for (unsigned i = 0, e = MIs.size(); i < e; i++) {
CompatibleRSI = PreviousRegSeq[MIs[i]];
if (RSI == CompatibleRSI)
continue;
if (tryMergeVector(&CompatibleRSI, &RSI, RemapChan))
return true;
}
}
return false;
}
bool R600VectorRegMerger::tryMergeUsingFreeSlot(RegSeqInfo &RSI,
RegSeqInfo &CompatibleRSI,
std::vector<std::pair<unsigned, unsigned> > &RemapChan) {
unsigned NeededUndefs = 4 - RSI.UndefReg.size();
if (PreviousRegSeqByUndefCount[NeededUndefs].empty())
return false;
std::vector<MachineInstr *> &MIs =
PreviousRegSeqByUndefCount[NeededUndefs];
CompatibleRSI = PreviousRegSeq[MIs.back()];
tryMergeVector(&CompatibleRSI, &RSI, RemapChan);
return true;
}
void R600VectorRegMerger::trackRSI(const RegSeqInfo &RSI) {
for (DenseMap<unsigned, unsigned>::const_iterator
It = RSI.RegToChan.begin(), E = RSI.RegToChan.end(); It != E; ++It) {
PreviousRegSeqByReg[(*It).first].push_back(RSI.Instr);
}
PreviousRegSeqByUndefCount[RSI.UndefReg.size()].push_back(RSI.Instr);
PreviousRegSeq[RSI.Instr] = RSI;
}
bool R600VectorRegMerger::runOnMachineFunction(MachineFunction &Fn) {
MRI = &(Fn.getRegInfo());
for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
MBB != MBBe; ++MBB) {
MachineBasicBlock *MB = MBB;
PreviousRegSeq.clear();
PreviousRegSeqByReg.clear();
PreviousRegSeqByUndefCount.clear();
for (MachineBasicBlock::iterator MII = MB->begin(), MIIE = MB->end();
MII != MIIE; ++MII) {
MachineInstr *MI = MII;
if (MI->getOpcode() != AMDGPU::REG_SEQUENCE)
continue;
RegSeqInfo RSI(*MRI, MI);
// All uses of MI are swizzeable ?
unsigned Reg = MI->getOperand(0).getReg();
if (!areAllUsesSwizzeable(Reg))
continue;
DEBUG (dbgs() << "Trying to optimize ";
MI->dump();
);
RegSeqInfo CandidateRSI;
std::vector<std::pair<unsigned, unsigned> > RemapChan;
DEBUG(dbgs() << "Using common slots...\n";);
if (tryMergeUsingCommonSlot(RSI, CandidateRSI, RemapChan)) {
// Remove CandidateRSI mapping
RemoveMI(CandidateRSI.Instr);
MII = RebuildVector(&RSI, &CandidateRSI, RemapChan);
trackRSI(RSI);
continue;
}
DEBUG(dbgs() << "Using free slots...\n";);
RemapChan.clear();
if (tryMergeUsingFreeSlot(RSI, CandidateRSI, RemapChan)) {
RemoveMI(CandidateRSI.Instr);
MII = RebuildVector(&RSI, &CandidateRSI, RemapChan);
trackRSI(RSI);
continue;
}
//Failed to merge
trackRSI(RSI);
}
}
return false;
}
}
llvm::FunctionPass *llvm::createR600VectorRegMerger(TargetMachine &tm) {
return new R600VectorRegMerger(tm);
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "combat.h"
#include "obj_base_clothing.h"
static int grapple(TBeing *c, TBeing *victim, spellNumT skill)
{
int percent;
int level, i = 0;
int rc;
int bKnown;
int grapple_move = 25 + ::number(1,10);
TThing *obj = NULL;
TBaseClothing *tbc = NULL;
int suitDam = 0;
if (c->checkPeaceful("You feel too peaceful to contemplate violence.\n\r"))
return FALSE;
if (c->getCombatMode() == ATTACK_BERSERK) {
c->sendTo("You are berserking! You can't focus enough to grapple anyone!\n\r");
return FALSE;
}
if (victim == c) {
c->sendTo("Aren't we funny today?\n\r");
return FALSE;
}
if (c->noHarmCheck(victim))
return FALSE;
if (victim->isImmortal() || IS_SET(victim->specials.act, ACT_IMMORTAL)) {
c->sendTo("You can't grapple an immortal.\n\r");
return FALSE;
}
if (c->riding) {
c->sendTo("Grappling while mounted is impossible!\n\r");
return FALSE;
}
if (victim->isFlying()) {
c->sendTo("You can't grapple someone that is flying.\n\r");
return FALSE;
}
if (c->isSwimming()) {
c->sendTo("You can't grapple with all this water around.\n\r");
return FALSE;
}
if (c->getMove() < grapple_move) {
c->sendTo("You lack the vitality to grapple.\n\r");
return FALSE;
}
c->addToMove(-grapple_move);
percent = 0;
percent += c->getDexReaction() * 5;
percent -= victim->getDexReaction() * 10;
if (victim->riding) {
// difficult
percent -= 35;
}
level = c->getSkillLevel(skill);
bKnown = c->getSkillValue(skill);
if ((bSuccess(c, bKnown + percent, skill) &&
// insure they can hit this critter
(i = c->specialAttack(victim,skill)) &&
i != GUARANTEED_FAILURE &&
// make sure they have reasonable training
(percent < bKnown)) ||
!victim->awake()) {
if (victim->canCounterMove(bKnown/2)) {
SV(skill);
act("$N blocks your grapple attempt and knocks you to the $g.", TRUE, c, 0, victim, TO_CHAR, ANSI_RED);
act("$N blocks $n's attempt to grapple, and knocks $m to the $g.", TRUE, c, 0, victim, TO_NOTVICT);
act("You evade $n's attempt to grapple, and knock $m to the $g.", TRUE, c, 0, victim, TO_VICT);
c->cantHit += c->loseRound(5 - (min(50, level) / 12));
rc = c->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return rc;
rc = c->trySpringleap(victim);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
} else {
if (victim->riding) {
act("You pull $N off $p.", FALSE, c, victim->riding, victim, TO_CHAR);
act("$n pulls $N off $p.", FALSE, c, victim->riding, victim, TO_NOTVICT);
act("$n pulls you off $p.", FALSE, c, victim->riding, victim, TO_VICT);
victim->dismount(POSITION_STANDING);
}
c->sendTo("You tie your opponent up, with an excellent maneuver.\n\r");
act("$n wrestles $N to the $g with an excellent maneuver.", TRUE, c, 0, victim, TO_NOTVICT);
act("$n wrestles you to the $g.", TRUE, c, 0, victim, TO_VICT);
#if 0
// c->cantHit += c->loseRound( 1 + level/ 12);
// victim->cantHit += victim->loseRound(3 + level/ 12);
if (::number(0,3))
c->cantHit += c->loseRound(3 + level/ 12);
c->addToWait(combatRound(2));
if (!::number(0,3))
victim->addToWait(combatRound(2));
// Moved below
if (c->fight())
c->stopFighting();
if (victim->fight())
victim->stopFighting();
#endif
// if eqipment worn on body is spiked, add a little extra 10-20-00, -dash
if (((obj = c->equipment[WEAR_BODY]) &&
(tbc = dynamic_cast<TBaseClothing *>(obj)) &&
(tbc->isSpiked()||tbc->isObjStat(ITEM_SPIKED)))) {
suitDam = (int)((tbc->getWeight()/10) + 1);
act("The spikes on your $o sink into $N.", FALSE, c, tbc, victim, TO_CHAR);
act("The spikes on $n's $o sink into $N.", FALSE, c, tbc, victim, TO_NOTVICT);
act("The spikes on $n's $o sink into you.", FALSE, c, tbc, victim, TO_VICT);
if (c->reconcileDamage(victim, suitDam, TYPE_STAB) == -1)
return DELETE_VICT;
}
rc = c->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return rc;
rc = c->trySpringleap(victim);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
rc = victim->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_VICT;
rc = victim->trySpringleap(c);
if (IS_SET_DELETE(rc, DELETE_THIS) && IS_SET_DELETE(rc, DELETE_VICT))
return rc;
else if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_VICT;
else if (IS_SET_DELETE(rc, DELETE_VICT))
return DELETE_THIS;
if (!victim->fight()) {
if (c->fight()) {
if (c->fight() != victim) {
act("You now turn your attention to $N!",
TRUE, c, 0, victim, TO_CHAR);
act("$n now turns $s attention to $N!",
TRUE, c, 0, victim, TO_NOTVICT);
act("$n has turned $s attention to you!",
TRUE, c, 0, victim, TO_VICT);
}
c->stopFighting();
c->setCharFighting(victim);
} else {
c->setCharFighting(victim);
}
c->setVictFighting(victim);
} else if (::number(1,5) < 4) {
if (c->fight() && (c->fight() != victim)) {
act("You now turn your attention to $N!",
TRUE, c, 0, victim, TO_CHAR);
act("$n now turns $s attention to $N!",
TRUE, c, 0, victim, TO_NOTVICT);
act("$n has turned $s attention to you!",
TRUE, c, 0, victim, TO_VICT);
}
if (victim->fight() && (victim->fight() != c)) {
act("$N now turns $S attention to you!",
TRUE, c, 0, victim, TO_CHAR);
act("$N now turns $S attention to $n!",
TRUE, c, 0, victim, TO_NOTVICT);
act("You now turn your attention to $n!",
TRUE, c, 0, victim, TO_VICT);
}
if (c->fight())
c->stopFighting();
if (victim->fight())
victim->stopFighting();
c->setCharFighting(victim);
c->setVictFighting(victim);
}
if (::number(0,3))
c->cantHit += c->loseRound(2 + level/ 12);
if (!::number(0,3))
victim->cantHit += victim->loseRound(2 + level/ 12);
if (victim->spelltask) {
victim->addToDistracted(1, FALSE);
}
victim->addToWait(combatRound(1));
}
} else {
c->cantHit += c->loseRound(5 - (min(level, 50)/ 12));
c->addToWait(combatRound(1));
rc = c->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return rc;
rc = c->trySpringleap(victim);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
act("You try to wrestle $N to the $g, but end up falling on your butt.", TRUE, c, 0, victim, TO_CHAR);
act("$n makes a nice wrestling move, but falls on $s butt.", TRUE, c, 0, 0, TO_ROOM);
if (!victim->fight()) {
act("$N turns $S attention to $n", TRUE, c, 0, victim, TO_NOTVICT);
c->setCharFighting(victim);
c->setVictFighting(victim);
}
}
c->reconcileHurt(victim, 0.01);
return TRUE;
}
int TBeing::doGrapple(const char *argument, TBeing *vict)
{
int rc;
char name_buf[30];
TBeing *victim;
spellNumT skill = getSkillNum(SKILL_GRAPPLE);
if (checkBusy(NULL)) {
return FALSE;
}
only_argument(argument, name_buf);
if (!(victim = vict)) {
if (!(victim = get_char_room_vis(this, name_buf))) {
if (!(victim = fight())) {
sendTo("Grapple whom?\n\r");
return FALSE;
}
}
}
if (!doesKnowSkill(skill)) {
sendTo("You know nothing about grappling.\n\r");
return FALSE;
}
if (!sameRoom(*victim)) {
sendTo("That person isn't around.\n\r");
return FALSE;
}
rc = grapple(this, victim, skill);
if (rc)
addSkillLag(skill, rc);
if (IS_SET_DELETE(rc, DELETE_VICT)) {
if (vict)
return rc;
delete victim;
victim = NULL;
REM_DELETE(rc, DELETE_VICT);
}
return rc;
}
<commit_msg>changed lag times for grapple<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "combat.h"
#include "obj_base_clothing.h"
static int grapple(TBeing *c, TBeing *victim, spellNumT skill)
{
int percent;
int level, i = 0;
int rc;
int bKnown;
int grapple_move = 25 + ::number(1,10);
TThing *obj = NULL;
TBaseClothing *tbc = NULL;
int suitDam = 0;
if (c->checkPeaceful("You feel too peaceful to contemplate violence.\n\r"))
return FALSE;
if (c->getCombatMode() == ATTACK_BERSERK) {
c->sendTo("You are berserking! You can't focus enough to grapple anyone!\n\r");
return FALSE;
}
if (victim == c) {
c->sendTo("Aren't we funny today?\n\r");
return FALSE;
}
if (c->noHarmCheck(victim))
return FALSE;
if (victim->isImmortal() || IS_SET(victim->specials.act, ACT_IMMORTAL)) {
c->sendTo("You can't grapple an immortal.\n\r");
return FALSE;
}
if (c->riding) {
c->sendTo("Grappling while mounted is impossible!\n\r");
return FALSE;
}
if (victim->isFlying()) {
c->sendTo("You can't grapple someone that is flying.\n\r");
return FALSE;
}
if (c->isSwimming()) {
c->sendTo("You can't grapple with all this water around.\n\r");
return FALSE;
}
if (c->getMove() < grapple_move) {
c->sendTo("You lack the vitality to grapple.\n\r");
return FALSE;
}
c->addToMove(-grapple_move);
percent = 0;
percent += c->getDexReaction() * 5;
percent -= victim->getDexReaction() * 10;
if (victim->riding) {
// difficult
percent -= 35;
}
level = c->getSkillLevel(skill);
bKnown = c->getSkillValue(skill);
if ((bSuccess(c, bKnown + percent, skill) &&
// insure they can hit this critter
(i = c->specialAttack(victim,skill)) &&
i != GUARANTEED_FAILURE &&
// make sure they have reasonable training
(percent < bKnown)) ||
!victim->awake()) {
if (victim->canCounterMove(bKnown/2)) {
SV(skill);
act("$N blocks your grapple attempt and knocks you to the $g.", TRUE, c, 0, victim, TO_CHAR, ANSI_RED);
act("$N blocks $n's attempt to grapple, and knocks $m to the $g.", TRUE, c, 0, victim, TO_NOTVICT);
act("You evade $n's attempt to grapple, and knock $m to the $g.", TRUE, c, 0, victim, TO_VICT);
c->cantHit += c->loseRound(5 - (min(50, level) / 12));
rc = c->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return rc;
rc = c->trySpringleap(victim);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
} else {
if (victim->riding) {
act("You pull $N off $p.", FALSE, c, victim->riding, victim, TO_CHAR);
act("$n pulls $N off $p.", FALSE, c, victim->riding, victim, TO_NOTVICT);
act("$n pulls you off $p.", FALSE, c, victim->riding, victim, TO_VICT);
victim->dismount(POSITION_STANDING);
}
c->sendTo("You tie your opponent up, with an excellent maneuver.\n\r");
act("$n wrestles $N to the $g with an excellent maneuver.", TRUE, c, 0, victim, TO_NOTVICT);
act("$n wrestles you to the $g.", TRUE, c, 0, victim, TO_VICT);
// if eqipment worn on body is spiked, add a little extra 10-20-00, -dash
if (((obj = c->equipment[WEAR_BODY]) &&
(tbc = dynamic_cast<TBaseClothing *>(obj)) &&
(tbc->isSpiked()||tbc->isObjStat(ITEM_SPIKED)))) {
suitDam = (int)((tbc->getWeight()/10) + 1);
act("The spikes on your $o sink into $N.", FALSE, c, tbc, victim, TO_CHAR);
act("The spikes on $n's $o sink into $N.", FALSE, c, tbc, victim, TO_NOTVICT);
act("The spikes on $n's $o sink into you.", FALSE, c, tbc, victim, TO_VICT);
if (c->reconcileDamage(victim, suitDam, TYPE_STAB) == -1)
return DELETE_VICT;
}
rc = c->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return rc;
rc = c->trySpringleap(victim);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
rc = victim->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_VICT;
rc = victim->trySpringleap(c);
if (IS_SET_DELETE(rc, DELETE_THIS) && IS_SET_DELETE(rc, DELETE_VICT))
return rc;
else if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_VICT;
else if (IS_SET_DELETE(rc, DELETE_VICT))
return DELETE_THIS;
if (!victim->fight()) {
if (c->fight()) {
if (c->fight() != victim) {
act("You now turn your attention to $N!",
TRUE, c, 0, victim, TO_CHAR);
act("$n now turns $s attention to $N!",
TRUE, c, 0, victim, TO_NOTVICT);
act("$n has turned $s attention to you!",
TRUE, c, 0, victim, TO_VICT);
}
c->stopFighting();
c->setCharFighting(victim);
} else {
c->setCharFighting(victim);
}
c->setVictFighting(victim);
} else if (::number(1,5) < 4) {
if (c->fight() && (c->fight() != victim)) {
act("You now turn your attention to $N!",
TRUE, c, 0, victim, TO_CHAR);
act("$n now turns $s attention to $N!",
TRUE, c, 0, victim, TO_NOTVICT);
act("$n has turned $s attention to you!",
TRUE, c, 0, victim, TO_VICT);
}
if (victim->fight() && (victim->fight() != c)) {
act("$N now turns $S attention to you!",
TRUE, c, 0, victim, TO_CHAR);
act("$N now turns $S attention to $n!",
TRUE, c, 0, victim, TO_NOTVICT);
act("You now turn your attention to $n!",
TRUE, c, 0, victim, TO_VICT);
}
if (c->fight())
c->stopFighting();
if (victim->fight())
victim->stopFighting();
c->setCharFighting(victim);
c->setVictFighting(victim);
}
c->cantHit += c->loseRound(4);
victim->cantHit += victim->loseRound(4);
if (victim->spelltask) {
victim->addToDistracted(1, FALSE);
}
victim->addToWait(combatRound(5));
}
} else {
c->cantHit += c->loseRound(5 - (min(level, 50)/ 12));
c->addToWait(combatRound(1));
rc = c->crashLanding(POSITION_SITTING);
if (IS_SET_DELETE(rc, DELETE_THIS))
return rc;
rc = c->trySpringleap(victim);
if (IS_SET_DELETE(rc, DELETE_THIS) || IS_SET_DELETE(rc, DELETE_VICT))
return rc;
act("You try to wrestle $N to the $g, but end up falling on your butt.", TRUE, c, 0, victim, TO_CHAR);
act("$n makes a nice wrestling move, but falls on $s butt.", TRUE, c, 0, 0, TO_ROOM);
if (!victim->fight()) {
act("$N turns $S attention to $n", TRUE, c, 0, victim, TO_NOTVICT);
c->setCharFighting(victim);
c->setVictFighting(victim);
}
}
c->reconcileHurt(victim, 0.01);
return TRUE;
}
int TBeing::doGrapple(const char *argument, TBeing *vict)
{
int rc;
char name_buf[30];
TBeing *victim;
spellNumT skill = getSkillNum(SKILL_GRAPPLE);
if (checkBusy(NULL)) {
return FALSE;
}
only_argument(argument, name_buf);
if (!(victim = vict)) {
if (!(victim = get_char_room_vis(this, name_buf))) {
if (!(victim = fight())) {
sendTo("Grapple whom?\n\r");
return FALSE;
}
}
}
if (!doesKnowSkill(skill)) {
sendTo("You know nothing about grappling.\n\r");
return FALSE;
}
if (!sameRoom(*victim)) {
sendTo("That person isn't around.\n\r");
return FALSE;
}
rc = grapple(this, victim, skill);
if (rc)
addSkillLag(skill, rc);
if (IS_SET_DELETE(rc, DELETE_VICT)) {
if (vict)
return rc;
delete victim;
victim = NULL;
REM_DELETE(rc, DELETE_VICT);
}
return rc;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2019 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#define CAF_SUITE stream_transport
#include "caf/net/stream_transport.hpp"
#include "caf/net/test/host_fixture.hpp"
#include "caf/test/dsl.hpp"
#include "caf/binary_deserializer.hpp"
#include "caf/byte.hpp"
#include "caf/detail/scope_guard.hpp"
#include "caf/make_actor.hpp"
#include "caf/net/actor_proxy_impl.hpp"
#include "caf/net/endpoint_manager.hpp"
#include "caf/net/make_endpoint_manager.hpp"
#include "caf/net/multiplexer.hpp"
#include "caf/net/stream_socket.hpp"
#include "caf/serializer_impl.hpp"
#include "caf/span.hpp"
using namespace caf;
using namespace caf::net;
namespace {
constexpr string_view hello_manager = "hello manager!";
struct fixture : test_coordinator_fixture<>, host_fixture {
fixture() {
mpx = std::make_shared<multiplexer>();
if (auto err = mpx->init())
CAF_FAIL("mpx->init failed: " << sys.render(err));
mpx->set_thread_id();
}
bool handle_io_event() override {
return mpx->poll_once(false);
}
multiplexer_ptr mpx;
};
class dummy_application {
public:
dummy_application(std::shared_ptr<std::vector<byte>> rec_buf)
: rec_buf_(std::move(rec_buf)){
// nop
};
~dummy_application() = default;
template <class Parent>
error init(Parent&) {
return none;
}
template <class Parent>
void write_message(Parent& parent,
std::unique_ptr<endpoint_manager_queue::message> ptr) {
parent.write_packet(ptr->payload);
}
template <class Parent>
error handle_data(Parent&, span<const byte> data) {
rec_buf_->clear();
rec_buf_->insert(rec_buf_->begin(), data.begin(), data.end());
return none;
}
template <class Parent>
void resolve(Parent& parent, string_view path, const actor& listener) {
actor_id aid = 42;
auto hid = "0011223344556677889900112233445566778899";
auto nid = unbox(make_node_id(42, hid));
actor_config cfg;
endpoint_manager_ptr ptr{&parent.manager()};
auto p = make_actor<actor_proxy_impl, strong_actor_ptr>(aid, nid,
&parent.system(),
cfg,
std::move(ptr));
anon_send(listener, resolve_atom::value,
std::string{path.begin(), path.end()}, p);
}
template <class Parent>
void timeout(Parent&, atom_value, uint64_t) {
// nop
}
template <class Parent>
void new_proxy(Parent&, actor_id) {
// nop
}
template <class Parent>
void local_actor_down(Parent&, actor_id, error) {
// nop
}
void handle_error(sec) {
// nop
}
static expected<std::vector<byte>> serialize(actor_system& sys,
const type_erased_tuple& x) {
std::vector<byte> result;
serializer_impl<std::vector<byte>> sink{sys, result};
if (auto err = message::save(sink, x))
return err;
return result;
}
private:
std::shared_ptr<std::vector<byte>> rec_buf_;
};
} // namespace
CAF_TEST_FIXTURE_SCOPE(endpoint_manager_tests, fixture)
CAF_TEST(receive) {
using transport_type = stream_transport<dummy_application>;
std::vector<byte> read_buf(1024);
CAF_CHECK_EQUAL(mpx->num_socket_managers(), 1u);
auto buf = std::make_shared<std::vector<byte>>();
auto sockets = unbox(make_stream_socket_pair());
if (auto err = nonblocking(sockets.second, true))
CAF_FAIL("nonblocking() returned an error: " << err);
CAF_CHECK_EQUAL(read(sockets.second, make_span(read_buf)),
sec::unavailable_or_would_block);
auto guard = detail::make_scope_guard([&] { close(sockets.second); });
transport_type transport{sockets.first, dummy_application{buf}};
transport.configure_read(net::receive_policy::exactly(hello_manager.size()));
auto mgr = make_endpoint_manager(mpx, sys, transport);
CAF_CHECK_EQUAL(mgr->init(), none);
CAF_CHECK_EQUAL(mpx->num_socket_managers(), 2u);
CAF_CHECK_EQUAL(write(sockets.second, as_bytes(make_span(hello_manager))),
hello_manager.size());
CAF_MESSAGE("wrote " << hello_manager.size() << " bytes.");
run();
CAF_CHECK_EQUAL(string_view(reinterpret_cast<char*>(buf->data()),
buf->size()),
hello_manager);
}
CAF_TEST(resolve and proxy communication) {
using transport_type = stream_transport<dummy_application>;
std::vector<byte> read_buf(1024);
auto buf = std::make_shared<std::vector<byte>>();
auto sockets = unbox(make_stream_socket_pair());
nonblocking(sockets.second, true);
auto guard = detail::make_scope_guard([&] { close(sockets.second); });
auto mgr = make_endpoint_manager(mpx, sys,
transport_type{sockets.first,
dummy_application{buf}});
CAF_CHECK_EQUAL(mgr->init(), none);
run();
mgr->resolve(unbox(make_uri("test:/id/42")), self);
run();
self->receive(
[&](resolve_atom, const std::string&, const strong_actor_ptr& p) {
CAF_MESSAGE("got a proxy, send a message to it");
self->send(actor_cast<actor>(p), "hello proxy!");
},
after(std::chrono::seconds(0)) >>
[&] { CAF_FAIL("manager did not respond with a proxy."); });
run();
auto read_res = read(sockets.second, make_span(read_buf));
if (!holds_alternative<size_t>(read_res))
CAF_FAIL("read() returned an error: " << sys.render(get<sec>(read_res)));
read_buf.resize(get<size_t>(read_res));
CAF_MESSAGE("receive buffer contains " << read_buf.size() << " bytes");
message msg;
binary_deserializer source{sys, read_buf};
CAF_CHECK_EQUAL(source(msg), none);
if (msg.match_elements<std::string>())
CAF_CHECK_EQUAL(msg.get_as<std::string>(0), "hello proxy!");
else
CAF_ERROR("expected a string, got: " << to_string(msg));
}
CAF_TEST_FIXTURE_SCOPE_END()
<commit_msg>Streamline test<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2019 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#define CAF_SUITE stream_transport
#include "caf/net/stream_transport.hpp"
#include "caf/net/test/host_fixture.hpp"
#include "caf/test/dsl.hpp"
#include "caf/binary_deserializer.hpp"
#include "caf/byte.hpp"
#include "caf/detail/scope_guard.hpp"
#include "caf/make_actor.hpp"
#include "caf/net/actor_proxy_impl.hpp"
#include "caf/net/endpoint_manager.hpp"
#include "caf/net/endpoint_manager_impl.hpp"
#include "caf/net/make_endpoint_manager.hpp"
#include "caf/net/multiplexer.hpp"
#include "caf/net/stream_socket.hpp"
#include "caf/serializer_impl.hpp"
#include "caf/span.hpp"
using namespace caf;
using namespace caf::net;
namespace {
constexpr string_view hello_manager = "hello manager!";
struct fixture : test_coordinator_fixture<>, host_fixture {
using buffer_type = std::vector<byte>;
using buffer_ptr = std::shared_ptr<buffer_type>;
fixture() : recv_buf(1024), shared_buf{std::make_shared<buffer_type>()} {
mpx = std::make_shared<multiplexer>();
if (auto err = mpx->init())
CAF_FAIL("mpx->init failed: " << sys.render(err));
mpx->set_thread_id();
CAF_CHECK_EQUAL(mpx->num_socket_managers(), 1u);
auto sockets = unbox(make_stream_socket_pair());
send_socket = sockets.first;
recv_socket = sockets.second;
if (auto err = nonblocking(recv_socket, true))
CAF_FAIL("nonblocking returned an error: " << err);
}
~fixture() {
close(send_socket);
}
bool handle_io_event() override {
return mpx->poll_once(false);
}
multiplexer_ptr mpx;
buffer_type recv_buf;
stream_socket send_socket;
stream_socket recv_socket;
buffer_ptr shared_buf;
};
class dummy_application {
using buffer_type = std::vector<byte>;
using buffer_ptr = std::shared_ptr<buffer_type>;
public:
dummy_application(buffer_ptr rec_buf)
: rec_buf_(std::move(rec_buf)){
// nop
};
~dummy_application() = default;
template <class Parent>
error init(Parent&) {
return none;
}
template <class Parent>
void write_message(Parent& parent,
std::unique_ptr<endpoint_manager_queue::message> ptr) {
parent.write_packet(ptr->payload);
}
template <class Parent>
error handle_data(Parent&, span<const byte> data) {
rec_buf_->clear();
rec_buf_->insert(rec_buf_->begin(), data.begin(), data.end());
return none;
}
template <class Parent>
void resolve(Parent& parent, string_view path, const actor& listener) {
actor_id aid = 42;
auto hid = "0011223344556677889900112233445566778899";
auto nid = unbox(make_node_id(42, hid));
actor_config cfg;
endpoint_manager_ptr ptr{&parent.manager()};
auto p = make_actor<actor_proxy_impl, strong_actor_ptr>(aid, nid,
&parent.system(),
cfg,
std::move(ptr));
anon_send(listener, resolve_atom::value,
std::string{path.begin(), path.end()}, p);
}
template <class Parent>
void timeout(Parent&, atom_value, uint64_t) {
// nop
}
template <class Parent>
void new_proxy(Parent&, actor_id) {
// nop
}
template <class Parent>
void local_actor_down(Parent&, actor_id, error) {
// nop
}
void handle_error(sec) {
// nop
}
static expected<buffer_type> serialize(actor_system& sys,
const type_erased_tuple& x) {
buffer_type result;
serializer_impl<buffer_type> sink{sys, result};
if (auto err = message::save(sink, x))
return err;
return result;
}
private:
buffer_ptr rec_buf_;
};
} // namespace
CAF_TEST_FIXTURE_SCOPE(endpoint_manager_tests, fixture)
CAF_TEST(receive) {
using transport_type = stream_transport<dummy_application>;
auto mgr = make_endpoint_manager(mpx, sys,
transport_type{recv_socket,
dummy_application{
shared_buf}});
CAF_CHECK_EQUAL(mgr->init(), none);
auto mgr_impl = mgr.downcast<endpoint_manager_impl<transport_type>>();
CAF_CHECK(mgr_impl != nullptr);
auto& transport = mgr_impl->transport();
transport.configure_read(receive_policy::exactly(hello_manager.size()));
CAF_CHECK_EQUAL(mpx->num_socket_managers(), 2u);
CAF_CHECK_EQUAL(write(send_socket, as_bytes(make_span(hello_manager))),
hello_manager.size());
CAF_MESSAGE("wrote " << hello_manager.size() << " bytes.");
run();
CAF_CHECK_EQUAL(string_view(reinterpret_cast<char*>(shared_buf->data()),
shared_buf->size()),
hello_manager);
}
CAF_TEST(resolve and proxy communication) {
using transport_type = stream_transport<dummy_application>;
auto mgr = make_endpoint_manager(mpx, sys,
transport_type{send_socket,
dummy_application{
shared_buf}});
CAF_CHECK_EQUAL(mgr->init(), none);
run();
mgr->resolve(unbox(make_uri("test:/id/42")), self);
run();
self->receive(
[&](resolve_atom, const std::string&, const strong_actor_ptr& p) {
CAF_MESSAGE("got a proxy, send a message to it");
self->send(actor_cast<actor>(p), "hello proxy!");
},
after(std::chrono::seconds(0)) >>
[&] { CAF_FAIL("manager did not respond with a proxy."); });
run();
auto read_res = read(recv_socket, make_span(recv_buf));
if (!holds_alternative<size_t>(read_res))
CAF_FAIL("read() returned an error: " << sys.render(get<sec>(read_res)));
recv_buf.resize(get<size_t>(read_res));
CAF_MESSAGE("receive buffer contains " << recv_buf.size() << " bytes");
message msg;
binary_deserializer source{sys, recv_buf};
CAF_CHECK_EQUAL(source(msg), none);
if (msg.match_elements<std::string>())
CAF_CHECK_EQUAL(msg.get_as<std::string>(0), "hello proxy!");
else
CAF_ERROR("expected a string, got: " << to_string(msg));
}
CAF_TEST_FIXTURE_SCOPE_END()
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* 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 St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <QDateTime>
/*!
\page Logging
\brief The library (and ContexKit in general) use a simple logging system designed
to unify the output and make the debugging easier.
\section API
Four types of log messages (presented here in the order of importance) are supported:
\b Test, \b Debug, \b Warning and \b Critical.
The first one, the \b Test message requires some attention. It's meant to be used
from tests and unit-tests to log various stages of the test execution. It'll make
the test output more easily filterable.
The log messages can be used like this:
\code
contextTest() << "This is some message";
contextDebug() << "My value is:" << someVariable;
contextWarning() << "Expecting key:" << something.getKey();
contextCritical() << 5 << " is bigger than " << 4;
\endcode
\section compilecontrol Compile-time verbosity control
During the compile time certain defines can be used to turn-off debug messages.
Those defines are:
\code
CONTEXT_LOG_HIDE_TEST
CONTEXT_LOG_HIDE_DEBUG
CONTEXT_LOG_HIDE_WARNING
CONTEXT_LOG_HIDE_CRITICAL
\endcode
A given define makes a respective macro message evaluate to an empty code. To be precise:
it makes the macro message evaluate to an inline do-nothing class that is optimized by the
compiler to do nothing.
When ie. \c CONTEXT_LOG_HIDE_DEBUG define is used to turn off \c contextDebug()
messages, the actual string content of the debug messages is \b not included in the binary
and during runtime the machine does not spend time evaluating it.
Those compile-time control defines are integrated in the build/configure system.
\section runtimecontrol Run-time verbosity control
During run-time, the amount of debugging can be limited (filtered) but it can't be increased
(expanded). In other words, if a package was compiled with warnings-only, it's not possible
to make it show debug messages at runtime. But it is possible to make it criticals-only.
The filtering happens via env variables. The major player is the \c CONTEXT_LOG_VERBOSITY variable
which can be set to \c TEST, \c DEBUG, \c WARNING and \c CRITICAL. The \c CONTEXT_LOG_VERBOSITY
specifies the minimal level of the messages shown. Ie. \c CONTEXT_LOG_VERBOSITY set to
\c WARNING will show only warning and criticals.
The format of the output can be tweaked with \c CONTEXT_LOG_HIDE_TIMESTAMPS and \c CONTEXT_LOG_USE_COLOR.
The first one makes the messages shorter by skipping the timestamp info. The second one adds a
little bit of ANSI coloring to the messages.
\c CONTEXT_LOG_SHOW_MODULE will filter-out (kill) all messages \b except the ones coming from the
specified module. Ie.:
\code
CONTEXT_LOG_SHOW_MODULE=subscriber ./some-binary
\endcode
...will run \c ./some-binary showing log messages \b only from \c subscriber module.
Lastly, \c CONTEXT_LOG_HIDE_MODULE will hide log messages coming from the specified module.
All other messages will be show.
*/
/* NullIODevice */
/*!
\class NullIODevice
\brief Device that kills all input.
This class is a \c QIODevice implementation that kills everything sent to it.
We set this as a output device for stream in ContextRealLogger when given debug
message type was disabled at \b runtime.
*/
qint64 NullIODevice::readData(char*, qint64)
{
return 0;
}
qint64 NullIODevice::writeData(const char*, qint64)
{
return 0;
}
/* ContextRealLogger */
/*!
\class ContextRealLogger
\brief A real logging class.
This is used by the actual macros to print messages.
*/
bool ContextRealLogger::showTest = true;
bool ContextRealLogger::showDebug = true;
bool ContextRealLogger::showWarning = true;
bool ContextRealLogger::showCritical = true;
bool ContextRealLogger::hideTimestamps = false;
bool ContextRealLogger::useColor = false;
char* ContextRealLogger::showModule = NULL;
char* ContextRealLogger::hideModule = NULL;
bool ContextRealLogger::initialized = false;
/// Initialize the class by checking the enviornment variables and setting
/// the message output params. The log level is set from \c CONTEXT_LOG_VERBOSITY
/// and from this env var the showTest, showDebug, showWarning... are set. By default
/// everything is displayed at runtime. It's also possible to not show timestamps in
/// messages and spice-up the output with some color.
void ContextRealLogger::initialize()
{
if (getenv("CONTEXT_LOG_HIDE_TIMESTAMPS") != NULL)
hideTimestamps = true;
if (getenv("CONTEXT_LOG_USE_COLOR") != NULL)
useColor = true;
showModule = getenv("CONTEXT_LOG_SHOW_MODULE");
hideModule = getenv("CONTEXT_LOG_HIDE_MODULE");
const char *verbosity = getenv("CONTEXT_LOG_VERBOSITY");
if (! verbosity)
return;
if (strcmp(verbosity, "TEST") == 0) {
// Do nothing, all left true
} else if (strcmp(verbosity, "DEBUG") == 0) {
showTest = false;
} else if (strcmp(verbosity, "WARNING") == 0) {
showTest = false;
showDebug = false;
} else if (strcmp(verbosity, "CRITICAL") == 0) {
showTest = false;
showDebug = false;
showWarning = false;
} else if (strcmp(verbosity, "NONE") == 0) {
showDebug = false;
showTest = false;
showDebug = false;
showWarning = false;
}
initialized = true;
}
/// Constructor. Called by the macros. \a func is the function name, \a file is
/// is the current source file and \a line specifies the line number.
ContextRealLogger::ContextRealLogger(int msgType, const char *func, const char *file, int line)
: QTextStream(stderr)
{
nullDevice = NULL;
if (! initialized) {
// This is not thread safe, but our initialization depends on
// non-mutable parts anyways, so we should be ok.
initialize();
}
const char *msgTypeString = NULL;
// Killing by msg type
if (msgType == CONTEXT_LOG_MSG_TYPE_DEBUG) {
if (! showDebug) {
killOutput();
return;
} else
msgTypeString = "DEBUG";
} else if (msgType == CONTEXT_LOG_MSG_TYPE_WARNING) {
if (! showWarning) {
killOutput();
return;
} else
msgTypeString = (useColor) ? "\033[103mWARNING\033[0m" : "WARNING";
} else if (msgType == CONTEXT_LOG_MSG_TYPE_CRITICAL) {
if (! showCritical) {
killOutput();
return;
} else
msgTypeString = (useColor) ? "\033[101mCRITICAL\033[0m" : "CRITICAL";
} else if (msgType == CONTEXT_LOG_MSG_TYPE_TEST) {
if (! showTest) {
killOutput();
return;
} else
msgTypeString = "TEST";
}
// Killing if we're not the module we're interested in
if (showModule && strcmp(showModule, CONTEXT_LOG_MODULE_NAME) != 0) {
killOutput();
return;
}
// Killing if we're the module we're NOT interested in
if (hideModule && strcmp(hideModule, CONTEXT_LOG_MODULE_NAME) == 0) {
killOutput();
return;
}
if (! hideTimestamps)
*this << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << " ";
*this << "[" << CONTEXT_LOG_MODULE_NAME << "]" << " ";
*this << msgTypeString << " ";
*this << "[" << file << ":" << line << ":" << func << "] ";
}
/// Make sure this logger will print nothing.
void ContextRealLogger::killOutput()
{
if (nullDevice)
return;
nullDevice = new NullIODevice();
setDevice(new NullIODevice());
return;
}
/// Prints \b end-of-line before going down.
ContextRealLogger::~ContextRealLogger()
{
*this << "\n";
delete nullDevice;
}
<commit_msg>Updating the documentation about modules.<commit_after>/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <marius.vollmer@nokia.com>
*
* 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 St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <QDateTime>
/*!
\page Logging
\brief The library (and ContexKit in general) use a simple logging system designed
to unify the output and make the debugging easier.
\section API
Four types of log messages (presented here in the order of importance) are supported:
\b Test, \b Debug, \b Warning and \b Critical.
The first one, the \b Test message requires some attention. It's meant to be used
from tests and unit-tests to log various stages of the test execution. It'll make
the test output more easily filterable.
The log messages can be used like this:
\code
contextTest() << "This is some message";
contextDebug() << "My value is:" << someVariable;
contextWarning() << "Expecting key:" << something.getKey();
contextCritical() << 5 << " is bigger than " << 4;
\endcode
\section compilecontrol Compile-time verbosity control
During the compile time certain defines can be used to turn-off debug messages.
Those defines are:
\code
CONTEXT_LOG_HIDE_TEST
CONTEXT_LOG_HIDE_DEBUG
CONTEXT_LOG_HIDE_WARNING
CONTEXT_LOG_HIDE_CRITICAL
\endcode
A given define makes a respective macro message evaluate to an empty code. To be precise:
it makes the macro message evaluate to an inline do-nothing class that is optimized by the
compiler to do nothing.
When ie. \c CONTEXT_LOG_HIDE_DEBUG define is used to turn off \c contextDebug()
messages, the actual string content of the debug messages is \b not included in the binary
and during runtime the machine does not spend time evaluating it.
Those compile-time control defines are integrated in the build/configure system.
\section runtimecontrol Run-time verbosity control
During run-time, the amount of debugging can be limited (filtered) but it can't be increased
(expanded). In other words, if a package was compiled with warnings-only, it's not possible
to make it show debug messages at runtime. But it is possible to make it criticals-only.
The filtering happens via env variables. The major player is the \c CONTEXT_LOG_VERBOSITY variable
which can be set to \c TEST, \c DEBUG, \c WARNING and \c CRITICAL. The \c CONTEXT_LOG_VERBOSITY
specifies the minimal level of the messages shown. Ie. \c CONTEXT_LOG_VERBOSITY set to
\c WARNING will show only warning and criticals.
The format of the output can be tweaked with \c CONTEXT_LOG_HIDE_TIMESTAMPS and \c CONTEXT_LOG_USE_COLOR.
The first one makes the messages shorter by skipping the timestamp info. The second one adds a
little bit of ANSI coloring to the messages.
\c CONTEXT_LOG_SHOW_MODULE will filter-out (kill) all messages \b except the ones coming from the
specified module. Ie.:
\code
CONTEXT_LOG_SHOW_MODULE=subscriber ./some-binary
\endcode
...will run \c ./some-binary showing log messages \b only from \c subscriber module.
Lastly, \c CONTEXT_LOG_HIDE_MODULE will hide log messages coming from the specified module.
All other messages will be show.
\section modules Modules in logging
In previous section we discussed and mentioned modules. For the purpose of logging,
a module is a piece of code (not neccesarily limited to one binary or shared object) that
forms one component (feature-wise). Specyfying and naming the modules is used
to set the origin of the logging messages.
The logging module is set using the \c CONTEXT_LOG_MODULE_NAME define. It should be
(in most cases) defined in the build system and automatically applied to the whole source code.
Typically (with autotools) this can be achieved with something similar too:
\code
...
AM_CXXFLAGS = '-DCONTEXT_LOG_MODULE_NAME="libtest"'
...
\endcode
If \c CONTEXT_LOG_MODULE_NAME is undefined, the log messages will be marked as coming from an
\b "Undefined" module.
*/
/* NullIODevice */
/*!
\class NullIODevice
\brief Device that kills all input.
This class is a \c QIODevice implementation that kills everything sent to it.
We set this as a output device for stream in ContextRealLogger when given debug
message type was disabled at \b runtime.
*/
qint64 NullIODevice::readData(char*, qint64)
{
return 0;
}
qint64 NullIODevice::writeData(const char*, qint64)
{
return 0;
}
/* ContextRealLogger */
/*!
\class ContextRealLogger
\brief A real logging class.
This is used by the actual macros to print messages.
*/
bool ContextRealLogger::showTest = true;
bool ContextRealLogger::showDebug = true;
bool ContextRealLogger::showWarning = true;
bool ContextRealLogger::showCritical = true;
bool ContextRealLogger::hideTimestamps = false;
bool ContextRealLogger::useColor = false;
char* ContextRealLogger::showModule = NULL;
char* ContextRealLogger::hideModule = NULL;
bool ContextRealLogger::initialized = false;
/// Initialize the class by checking the enviornment variables and setting
/// the message output params. The log level is set from \c CONTEXT_LOG_VERBOSITY
/// and from this env var the showTest, showDebug, showWarning... are set. By default
/// everything is displayed at runtime. It's also possible to not show timestamps in
/// messages and spice-up the output with some color.
void ContextRealLogger::initialize()
{
if (getenv("CONTEXT_LOG_HIDE_TIMESTAMPS") != NULL)
hideTimestamps = true;
if (getenv("CONTEXT_LOG_USE_COLOR") != NULL)
useColor = true;
showModule = getenv("CONTEXT_LOG_SHOW_MODULE");
hideModule = getenv("CONTEXT_LOG_HIDE_MODULE");
const char *verbosity = getenv("CONTEXT_LOG_VERBOSITY");
if (! verbosity)
return;
if (strcmp(verbosity, "TEST") == 0) {
// Do nothing, all left true
} else if (strcmp(verbosity, "DEBUG") == 0) {
showTest = false;
} else if (strcmp(verbosity, "WARNING") == 0) {
showTest = false;
showDebug = false;
} else if (strcmp(verbosity, "CRITICAL") == 0) {
showTest = false;
showDebug = false;
showWarning = false;
} else if (strcmp(verbosity, "NONE") == 0) {
showDebug = false;
showTest = false;
showDebug = false;
showWarning = false;
}
initialized = true;
}
/// Constructor. Called by the macros. \a func is the function name, \a file is
/// is the current source file and \a line specifies the line number.
ContextRealLogger::ContextRealLogger(int msgType, const char *func, const char *file, int line)
: QTextStream(stderr)
{
nullDevice = NULL;
if (! initialized) {
// This is not thread safe, but our initialization depends on
// non-mutable parts anyways, so we should be ok.
initialize();
}
const char *msgTypeString = NULL;
// Killing by msg type
if (msgType == CONTEXT_LOG_MSG_TYPE_DEBUG) {
if (! showDebug) {
killOutput();
return;
} else
msgTypeString = "DEBUG";
} else if (msgType == CONTEXT_LOG_MSG_TYPE_WARNING) {
if (! showWarning) {
killOutput();
return;
} else
msgTypeString = (useColor) ? "\033[103mWARNING\033[0m" : "WARNING";
} else if (msgType == CONTEXT_LOG_MSG_TYPE_CRITICAL) {
if (! showCritical) {
killOutput();
return;
} else
msgTypeString = (useColor) ? "\033[101mCRITICAL\033[0m" : "CRITICAL";
} else if (msgType == CONTEXT_LOG_MSG_TYPE_TEST) {
if (! showTest) {
killOutput();
return;
} else
msgTypeString = "TEST";
}
// Killing if we're not the module we're interested in
if (showModule && strcmp(showModule, CONTEXT_LOG_MODULE_NAME) != 0) {
killOutput();
return;
}
// Killing if we're the module we're NOT interested in
if (hideModule && strcmp(hideModule, CONTEXT_LOG_MODULE_NAME) == 0) {
killOutput();
return;
}
if (! hideTimestamps)
*this << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << " ";
*this << "[" << CONTEXT_LOG_MODULE_NAME << "]" << " ";
*this << msgTypeString << " ";
*this << "[" << file << ":" << line << ":" << func << "] ";
}
/// Make sure this logger will print nothing.
void ContextRealLogger::killOutput()
{
if (nullDevice)
return;
nullDevice = new NullIODevice();
setDevice(new NullIODevice());
return;
}
/// Prints \b end-of-line before going down.
ContextRealLogger::~ContextRealLogger()
{
*this << "\n";
delete nullDevice;
}
<|endoftext|> |
<commit_before>// ------------------------------------------------------------------------
// audioio-jack.cpp: Interface to JACK audio framework
// Copyright (C) 2001-2003,2008,2009 Kai Vehmanen
//
// Attributes:
// eca-style-version: 3 (see Ecasound Programmer's Guide)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// ------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <jack/jack.h>
#include <kvu_dbc.h>
#include <kvu_numtostr.h>
#include "audioio.h"
#include "eca-version.h"
#include "eca-logger.h"
#include "samplebuffer.h"
#include "audioio_jack.h"
#include "audioio_jack_manager.h"
#ifdef ECA_ENABLE_AUDIOIO_PLUGINS
/* see eca-static-object-maps.cpp */
static const char* audio_io_keyword_const = "jack";
static const char* audio_io_keyword_regex_const = "(^jack$)|(^jack_alsa$)|(^jack_auto$)|(^jack_generic$)";
AUDIO_IO* audio_io_descriptor(void) { return new AUDIO_IO_JACK(); }
const char* audio_io_keyword(void) {return audio_io_keyword_const; }
const char* audio_io_keyword_regex(void){return audio_io_keyword_regex_const; }
int audio_io_interface_version(void) { return ecasound_library_version_current; }
#endif
AUDIO_IO_JACK::AUDIO_IO_JACK (void)
: jackmgr_rep(0),
myid_rep(0),
error_flag_rep(false)
{
ECA_LOG_MSG(ECA_LOGGER::functions, "constructor");
}
AUDIO_IO_JACK::~AUDIO_IO_JACK(void)
{
if (is_open() == true && is_running()) stop();
if (is_open() == true) {
close();
}
}
AUDIO_IO_MANAGER* AUDIO_IO_JACK::create_object_manager(void) const
{
return new AUDIO_IO_JACK_MANAGER();
}
void AUDIO_IO_JACK::set_manager(AUDIO_IO_JACK_MANAGER* mgr, int id)
{
string mgrname = (mgr != 0 ? mgr->name() : "null");
ECA_LOG_MSG(ECA_LOGGER::system_objects,
"setting manager to " + mgrname);
jackmgr_rep = mgr;
myid_rep = id;
}
void AUDIO_IO_JACK::open(void) throw(AUDIO_IO::SETUP_ERROR&)
{
ECA_LOG_MSG(ECA_LOGGER::system_objects, "open");
#ifdef WORDS_BIGENDIAN
set_sample_format(ECA_AUDIO_FORMAT::sfmt_f32_be);
#else
set_sample_format(ECA_AUDIO_FORMAT::sfmt_f32_le);
#endif
toggle_interleaved_channels(false);
if (jackmgr_rep != 0) {
string my_in_portname ("in"), my_out_portname ("out");
if (label() == "jack" &&
params_rep.size() > 2 &&
params_rep[2].size() > 0) {
my_in_portname = my_out_portname = params_rep[2];
}
/* note: deprecated interface */
else if (label() == "jack_generic" &&
params_rep.size() > 1) {
my_in_portname = my_out_portname = params_rep[1];
}
jackmgr_rep->open(myid_rep);
if (jackmgr_rep->is_open() != true) {
/* unable to open connection to jackd, exit */
throw(SETUP_ERROR(SETUP_ERROR::unexpected, "AUDIOIO-JACK: Unable to open JACK-client"));
}
if (samples_per_second() != jackmgr_rep->samples_per_second()) {
set_samples_per_second(jackmgr_rep->samples_per_second());
ECA_LOG_MSG(ECA_LOGGER::system_objects,
"Note! Locking to jackd samplerate " +
kvu_numtostr(samples_per_second()));
}
if (buffersize() != jackmgr_rep->buffersize()) {
long int jackd_bsize = jackmgr_rep->buffersize();
jackmgr_rep->close(myid_rep);
throw(SETUP_ERROR(SETUP_ERROR::unexpected,
"AUDIOIO-JACK: Cannot connect open connection! Buffersize " +
kvu_numtostr(buffersize()) + " differs from JACK server's buffersize of " +
kvu_numtostr(jackd_bsize) + "."));
}
if (io_mode() == AUDIO_IO::io_read) {
jackmgr_rep->register_jack_ports(myid_rep, channels(), my_in_portname);
}
else {
jackmgr_rep->register_jack_ports(myid_rep, channels(), my_out_portname);
}
/* - make automatic connections */
if (label() == "jack" &&
params_rep.size() > 1 &&
params_rep[1].size() > 0) {
/* note: if 2nd param given, use it as the client to autoconnect to */
jackmgr_rep->auto_connect_jack_port_client(myid_rep, params_rep[1], channels());
}
else if (label() == "jack_multi") {
int i;
for(i = 0; i < channels(); i++) {
if (static_cast<int>(params_rep.size()) > i + 1 &&
params_rep[i + 1].size() > 0) {
ECA_LOG_MSG(ECA_LOGGER::user_objects,
"adding auto connection from " +
my_out_portname + "_" + kvu_numtostr(i + 1) +
" to " +
params_rep[i + 1]);
jackmgr_rep->auto_connect_jack_port(myid_rep, i + 1, params_rep[i + 1]);
}
}
}
else if (label() == "jack_alsa") {
/* note: deprecated feature: 'alsa_pcm' is hidden in the port
list returned by jack_get_ports(), but as you can still
connect with the direct backend names, we have to keep this
code around to be backward compatible */
string in_aconn_portprefix, out_aconn_portprefix;
in_aconn_portprefix = "alsa_pcm:capture_";
out_aconn_portprefix = "alsa_pcm:playback_";
for(int n = 0; n < channels(); n++) {
if (io_mode() == AUDIO_IO::io_read) {
jackmgr_rep->auto_connect_jack_port(myid_rep, n + 1, in_aconn_portprefix + kvu_numtostr(n + 1));
}
else {
jackmgr_rep->auto_connect_jack_port(myid_rep, n + 1, out_aconn_portprefix + kvu_numtostr(n + 1));
}
}
}
/* note: deprecated interface, plain "jack" should be used now */
else if (label() == "jack_auto" &&
params_rep.size() > 1 &&
params_rep[1].size() > 0) {
jackmgr_rep->auto_connect_jack_port_client(myid_rep, params_rep[1], channels());
}
}
AUDIO_IO_DEVICE::open();
}
void AUDIO_IO_JACK::close(void)
{
ECA_LOG_MSG(ECA_LOGGER::system_objects, "close");
if (jackmgr_rep != 0) {
jackmgr_rep->unregister_jack_ports(myid_rep);
jackmgr_rep->close(myid_rep);
}
AUDIO_IO_DEVICE::close();
}
bool AUDIO_IO_JACK::finished(void) const
{
if (is_open() != true ||
jackmgr_rep == 0 ||
jackmgr_rep->is_open() != true ||
error_flag_rep == true)
return true;
return false;
}
long int AUDIO_IO_JACK::read_samples(void* target_buffer, long int samples)
{
if (jackmgr_rep != 0) {
DBC_CHECK(samples == jackmgr_rep->buffersize());
long int res = jackmgr_rep->read_samples(myid_rep, target_buffer, samples);
return res;
}
return 0;
}
void AUDIO_IO_JACK::write_buffer(SAMPLE_BUFFER* sbuf)
{
/* note: this is reimplemented only to catch errors with unsupported
* input streams (e.g. one produces by 'resample' object' */
if (sbuf->length_in_samples() != jackmgr_rep->buffersize() &&
sbuf->event_tag_test(SAMPLE_BUFFER::tag_end_of_stream) != true) {
error_flag_rep = true;
ECA_LOG_MSG(ECA_LOGGER::errors,
"ERROR: Variable size input buffers detected at JACK output, stopping processing. "
"This can happen e.g. with a 'resample' input object.");
}
AUDIO_IO_DEVICE::write_buffer(sbuf);
}
void AUDIO_IO_JACK::write_samples(void* target_buffer, long int samples)
{
DBC_CHECK(samples <= jackmgr_rep->buffersize());
if (jackmgr_rep != 0) {
jackmgr_rep->write_samples(myid_rep, target_buffer, samples);
}
}
void AUDIO_IO_JACK::prepare(void)
{
ECA_LOG_MSG(ECA_LOGGER::system_objects, "prepare / " + label());
error_flag_rep = false;
AUDIO_IO_DEVICE::prepare();
}
void AUDIO_IO_JACK::start(void)
{
ECA_LOG_MSG(ECA_LOGGER::system_objects, "start / " + label());
AUDIO_IO_DEVICE::start();
}
void AUDIO_IO_JACK::stop(void)
{
ECA_LOG_MSG(ECA_LOGGER::system_objects, "stop / " + label());
AUDIO_IO_DEVICE::stop();
}
long int AUDIO_IO_JACK::latency(void) const
{
return jackmgr_rep == 0 ? 0 : jackmgr_rep->client_latency(myid_rep);
}
std::string AUDIO_IO_JACK::parameter_names(void) const
{
if (label() == "jack_generic")
return "label,portname";
else if (label() == "jack_auto")
return "label,client";
else if (label() == "jack_multi") {
string paramlist = "label,";
int i;
for(i = 0; i < channels(); i++) {
paramlist += ",dstport" + kvu_numtostr(i + 1);
}
return paramlist;
}
/* jack */
return "label,client,portprefix";
}
void AUDIO_IO_JACK::set_parameter(int param, std::string value)
{
if (param > static_cast<int>(params_rep.size()))
params_rep.resize(param);
params_rep[param - 1] = value;
if (param == 1) {
set_label(value);
}
}
std::string AUDIO_IO_JACK::get_parameter(int param) const
{
if (param > 0 && param <= static_cast<int>(params_rep.size()))
return params_rep[param - 1];
return AUDIO_IO::get_parameter(param);
}
<commit_msg>Fixed a bug in JACK variable buffer detection code<commit_after>// ------------------------------------------------------------------------
// audioio-jack.cpp: Interface to JACK audio framework
// Copyright (C) 2001-2003,2008,2009 Kai Vehmanen
//
// Attributes:
// eca-style-version: 3 (see Ecasound Programmer's Guide)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// ------------------------------------------------------------------------
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <jack/jack.h>
#include <kvu_dbc.h>
#include <kvu_numtostr.h>
#include "audioio.h"
#include "eca-version.h"
#include "eca-logger.h"
#include "samplebuffer.h"
#include "audioio_jack.h"
#include "audioio_jack_manager.h"
#ifdef ECA_ENABLE_AUDIOIO_PLUGINS
/* see eca-static-object-maps.cpp */
static const char* audio_io_keyword_const = "jack";
static const char* audio_io_keyword_regex_const = "(^jack$)|(^jack_alsa$)|(^jack_auto$)|(^jack_generic$)";
AUDIO_IO* audio_io_descriptor(void) { return new AUDIO_IO_JACK(); }
const char* audio_io_keyword(void) {return audio_io_keyword_const; }
const char* audio_io_keyword_regex(void){return audio_io_keyword_regex_const; }
int audio_io_interface_version(void) { return ecasound_library_version_current; }
#endif
AUDIO_IO_JACK::AUDIO_IO_JACK (void)
: jackmgr_rep(0),
myid_rep(0),
error_flag_rep(false)
{
ECA_LOG_MSG(ECA_LOGGER::functions, "constructor");
}
AUDIO_IO_JACK::~AUDIO_IO_JACK(void)
{
if (is_open() == true && is_running()) stop();
if (is_open() == true) {
close();
}
}
AUDIO_IO_MANAGER* AUDIO_IO_JACK::create_object_manager(void) const
{
return new AUDIO_IO_JACK_MANAGER();
}
void AUDIO_IO_JACK::set_manager(AUDIO_IO_JACK_MANAGER* mgr, int id)
{
string mgrname = (mgr != 0 ? mgr->name() : "null");
ECA_LOG_MSG(ECA_LOGGER::system_objects,
"setting manager to " + mgrname);
jackmgr_rep = mgr;
myid_rep = id;
}
void AUDIO_IO_JACK::open(void) throw(AUDIO_IO::SETUP_ERROR&)
{
ECA_LOG_MSG(ECA_LOGGER::system_objects, "open");
#ifdef WORDS_BIGENDIAN
set_sample_format(ECA_AUDIO_FORMAT::sfmt_f32_be);
#else
set_sample_format(ECA_AUDIO_FORMAT::sfmt_f32_le);
#endif
toggle_interleaved_channels(false);
if (jackmgr_rep != 0) {
string my_in_portname ("in"), my_out_portname ("out");
if (label() == "jack" &&
params_rep.size() > 2 &&
params_rep[2].size() > 0) {
my_in_portname = my_out_portname = params_rep[2];
}
/* note: deprecated interface */
else if (label() == "jack_generic" &&
params_rep.size() > 1) {
my_in_portname = my_out_portname = params_rep[1];
}
jackmgr_rep->open(myid_rep);
if (jackmgr_rep->is_open() != true) {
/* unable to open connection to jackd, exit */
throw(SETUP_ERROR(SETUP_ERROR::unexpected, "AUDIOIO-JACK: Unable to open JACK-client"));
}
if (samples_per_second() != jackmgr_rep->samples_per_second()) {
set_samples_per_second(jackmgr_rep->samples_per_second());
ECA_LOG_MSG(ECA_LOGGER::system_objects,
"Note! Locking to jackd samplerate " +
kvu_numtostr(samples_per_second()));
}
if (buffersize() != jackmgr_rep->buffersize()) {
long int jackd_bsize = jackmgr_rep->buffersize();
jackmgr_rep->close(myid_rep);
throw(SETUP_ERROR(SETUP_ERROR::unexpected,
"AUDIOIO-JACK: Cannot connect open connection! Buffersize " +
kvu_numtostr(buffersize()) + " differs from JACK server's buffersize of " +
kvu_numtostr(jackd_bsize) + "."));
}
if (io_mode() == AUDIO_IO::io_read) {
jackmgr_rep->register_jack_ports(myid_rep, channels(), my_in_portname);
}
else {
jackmgr_rep->register_jack_ports(myid_rep, channels(), my_out_portname);
}
/* - make automatic connections */
if (label() == "jack" &&
params_rep.size() > 1 &&
params_rep[1].size() > 0) {
/* note: if 2nd param given, use it as the client to autoconnect to */
jackmgr_rep->auto_connect_jack_port_client(myid_rep, params_rep[1], channels());
}
else if (label() == "jack_multi") {
int i;
for(i = 0; i < channels(); i++) {
if (static_cast<int>(params_rep.size()) > i + 1 &&
params_rep[i + 1].size() > 0) {
ECA_LOG_MSG(ECA_LOGGER::user_objects,
"adding auto connection from " +
my_out_portname + "_" + kvu_numtostr(i + 1) +
" to " +
params_rep[i + 1]);
jackmgr_rep->auto_connect_jack_port(myid_rep, i + 1, params_rep[i + 1]);
}
}
}
else if (label() == "jack_alsa") {
/* note: deprecated feature: 'alsa_pcm' is hidden in the port
list returned by jack_get_ports(), but as you can still
connect with the direct backend names, we have to keep this
code around to be backward compatible */
string in_aconn_portprefix, out_aconn_portprefix;
in_aconn_portprefix = "alsa_pcm:capture_";
out_aconn_portprefix = "alsa_pcm:playback_";
for(int n = 0; n < channels(); n++) {
if (io_mode() == AUDIO_IO::io_read) {
jackmgr_rep->auto_connect_jack_port(myid_rep, n + 1, in_aconn_portprefix + kvu_numtostr(n + 1));
}
else {
jackmgr_rep->auto_connect_jack_port(myid_rep, n + 1, out_aconn_portprefix + kvu_numtostr(n + 1));
}
}
}
/* note: deprecated interface, plain "jack" should be used now */
else if (label() == "jack_auto" &&
params_rep.size() > 1 &&
params_rep[1].size() > 0) {
jackmgr_rep->auto_connect_jack_port_client(myid_rep, params_rep[1], channels());
}
}
AUDIO_IO_DEVICE::open();
}
void AUDIO_IO_JACK::close(void)
{
ECA_LOG_MSG(ECA_LOGGER::system_objects, "close");
if (jackmgr_rep != 0) {
jackmgr_rep->unregister_jack_ports(myid_rep);
jackmgr_rep->close(myid_rep);
}
AUDIO_IO_DEVICE::close();
}
bool AUDIO_IO_JACK::finished(void) const
{
if (is_open() != true ||
jackmgr_rep == 0 ||
jackmgr_rep->is_open() != true ||
error_flag_rep == true)
return true;
return false;
}
long int AUDIO_IO_JACK::read_samples(void* target_buffer, long int samples)
{
if (jackmgr_rep != 0) {
DBC_CHECK(samples == jackmgr_rep->buffersize());
long int res = jackmgr_rep->read_samples(myid_rep, target_buffer, samples);
return res;
}
return 0;
}
void AUDIO_IO_JACK::write_buffer(SAMPLE_BUFFER* sbuf)
{
/* note: this is reimplemented only to catch errors with unsupported
* input streams (e.g. one produces by 'resample' object' */
if (sbuf->length_in_samples() > 0 &&
sbuf->length_in_samples() != jackmgr_rep->buffersize() &&
sbuf->event_tag_test(SAMPLE_BUFFER::tag_end_of_stream) != true) {
error_flag_rep = true;
ECA_LOG_MSG(ECA_LOGGER::errors,
"ERROR: Variable size input buffers detected at JACK output, stopping processing. "
"This can happen e.g. with a 'resample' input object.");
}
AUDIO_IO_DEVICE::write_buffer(sbuf);
}
void AUDIO_IO_JACK::write_samples(void* target_buffer, long int samples)
{
DBC_CHECK(samples <= jackmgr_rep->buffersize());
if (jackmgr_rep != 0) {
jackmgr_rep->write_samples(myid_rep, target_buffer, samples);
}
}
void AUDIO_IO_JACK::prepare(void)
{
ECA_LOG_MSG(ECA_LOGGER::system_objects, "prepare / " + label());
error_flag_rep = false;
AUDIO_IO_DEVICE::prepare();
}
void AUDIO_IO_JACK::start(void)
{
ECA_LOG_MSG(ECA_LOGGER::system_objects, "start / " + label());
AUDIO_IO_DEVICE::start();
}
void AUDIO_IO_JACK::stop(void)
{
ECA_LOG_MSG(ECA_LOGGER::system_objects, "stop / " + label());
AUDIO_IO_DEVICE::stop();
}
long int AUDIO_IO_JACK::latency(void) const
{
return jackmgr_rep == 0 ? 0 : jackmgr_rep->client_latency(myid_rep);
}
std::string AUDIO_IO_JACK::parameter_names(void) const
{
if (label() == "jack_generic")
return "label,portname";
else if (label() == "jack_auto")
return "label,client";
else if (label() == "jack_multi") {
string paramlist = "label,";
int i;
for(i = 0; i < channels(); i++) {
paramlist += ",dstport" + kvu_numtostr(i + 1);
}
return paramlist;
}
/* jack */
return "label,client,portprefix";
}
void AUDIO_IO_JACK::set_parameter(int param, std::string value)
{
if (param > static_cast<int>(params_rep.size()))
params_rep.resize(param);
params_rep[param - 1] = value;
if (param == 1) {
set_label(value);
}
}
std::string AUDIO_IO_JACK::get_parameter(int param) const
{
if (param > 0 && param <= static_cast<int>(params_rep.size()))
return params_rep[param - 1];
return AUDIO_IO::get_parameter(param);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: wrap_itkImageToImageFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkImageToImageFilter.h"
#include "itkImage.h"
#ifdef CABLE_CONFIGURATION
#include "itkCSwigImages.h"
#include "itkCSwigMacros.h"
namespace _cable_
{
const char* const group = ITK_WRAP_GROUP(itkImageToImageFilter);
namespace wrappers
{
ITK_WRAP_OBJECT2(ImageToImageFilter, image::F2, image::F2, itkImageToImageFilterF2F2);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::F2, image::UC2, itkImageToImageFilterF2UC2);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::F2, image::US2, itkImageToImageFilterF2US2);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::US2, image::F2, itkImageToImageFilterUS2F2);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::US2, image::UC2, itkImageToImageFilterUS2UC2);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::US2, image::US2, itkImageToImageFilterUS2US2);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::F3, image::F3, itkImageToImageFilterF3F3);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::F3, image::UC3, itkImageToImageFilterF3UC3);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::F3, image::US3, itkImageToImageFilterF3US3);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::US3, image::F3, itkImageToImageFilterUS3F3);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::US3, image::UC3, itkImageToImageFilterUS3UC3);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::US3, image::US3, itkImageToImageFilterUS3US3);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::UC3, image::UC3, itkImageToImageFilterUC3UC3);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::UC3, image::F3, itkImageToImageFilterUC3F3);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::UC3, image::SS3, itkImageToImageFilterUC3SS3);
ITK_WRAP_OBJECT2(ImageToImageFilter, image::UC3, image::US3, itkImageToImageFilterUC3US3);
}
}
#endif
<commit_msg>ENH: This file was split into _2D and _3D versions in order to keep the compilation unit size under control.<commit_after><|endoftext|> |
<commit_before>#include "output.hxx"
#include "thread.hxx"
using namespace std;
ResourceMutex<ostream> coutMutex(cout);
ResourceMutex<ostream> cerrMutex(cerr);
void out(ResourceMutex<ostream>& outRes, const string& msg)
{
ResourceLocker<ostream> locker(outRes);
locker.get() << msg;
}
void out(const string& msg) { out(coutMutex, msg); }
void outLn(const string& msg) { out(coutMutex, msg + "\n"); }
void err(const string& msg) { out(cerrMutex, msg); }
void errLn(const string& msg) { out(cerrMutex, msg + "\n"); }
<commit_msg>Force flush output<commit_after>#include "output.hxx"
#include "thread.hxx"
using namespace std;
ResourceMutex<ostream> coutMutex(cout);
ResourceMutex<ostream> cerrMutex(cerr);
void out(ResourceMutex<ostream>& outRes, const string& msg)
{
ResourceLocker<ostream> locker(outRes);
(locker.get() << msg).flush();
}
void out(const string& msg) { out(coutMutex, msg); }
void outLn(const string& msg) { out(coutMutex, msg + "\n"); }
void err(const string& msg) { out(cerrMutex, msg); }
void errLn(const string& msg) { out(cerrMutex, msg + "\n"); }
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <string>
#include "tokenize.hpp"
#include "parser.hpp"
#include "context.hpp"
using namespace std;
namespace Vole {
Parser::Parser(const char* s, Context& c)
: src(s), ctx(c), tokens(std::vector<Lexeme>()), index(0)
{ }
Value Parser::parse() {
tokenize(src, tokens, 1);
return parse_value();
}
Value Parser::parse_value() {
while (index < tokens.size()) {
Lexeme cur = tokens[index];
switch (cur.type) {
case Lexeme::Type::LPAREN: {
return parse_vector();
} break;
case Lexeme::Type::BOOLEAN: {
++index;
return ctx.new_boolean(cur.text == "#t");
} break;
case Lexeme::Type::NUMBER: {
++index;
return ctx.new_number(atof(cur.text.c_str()));
} break;
case Lexeme::Type::IDENTIFIER: {
++index;
return ctx.new_symbol(cur.text);
} break;
case Lexeme::Type::STRING: {
++index;
return ctx.new_string(cur.text);
} break;
case Lexeme::Type::QUOTE: {
++index;
return ctx.new_vector({ctx.new_symbol("quote"), parse_value()});
} break;
default: {
throw("unexpected lexeme type!");
}
}
}
return Value();
}
Value Parser::parse_vector() {
// pop left paren
++index;
vector<Value> vec;
while (tokens[index].type != Lexeme::Type::RPAREN) {
Value v = parse_value();
vec.push_back(v);
}
// pop right paren
++index;
return ctx.new_vector(vec);
}
}<commit_msg>need to check for #T too<commit_after>#include <cstdlib>
#include <string>
#include "tokenize.hpp"
#include "parser.hpp"
#include "context.hpp"
using namespace std;
namespace Vole {
Parser::Parser(const char* s, Context& c)
: src(s), ctx(c), tokens(std::vector<Lexeme>()), index(0)
{ }
Value Parser::parse() {
tokenize(src, tokens, 1);
return parse_value();
}
Value Parser::parse_value() {
while (index < tokens.size()) {
Lexeme cur = tokens[index];
switch (cur.type) {
case Lexeme::Type::LPAREN: {
return parse_vector();
} break;
case Lexeme::Type::BOOLEAN: {
++index;
return ctx.new_boolean((cur.text == "#t") | (cur.text == "#T"));
} break;
case Lexeme::Type::NUMBER: {
++index;
return ctx.new_number(atof(cur.text.c_str()));
} break;
case Lexeme::Type::IDENTIFIER: {
++index;
return ctx.new_symbol(cur.text);
} break;
case Lexeme::Type::STRING: {
++index;
return ctx.new_string(cur.text);
} break;
case Lexeme::Type::QUOTE: {
++index;
return ctx.new_vector({ctx.new_symbol("quote"), parse_value()});
} break;
default: {
throw("unexpected lexeme type!");
}
}
}
return Value();
}
Value Parser::parse_vector() {
// pop left paren
++index;
vector<Value> vec;
while (tokens[index].type != Lexeme::Type::RPAREN) {
Value v = parse_value();
vec.push_back(v);
}
// pop right paren
++index;
return ctx.new_vector(vec);
}
}<|endoftext|> |
<commit_before>#include "parser.h"
#include "controls.h"
#include "containers.h"
#include "adaptors.h"
using namespace std;
using namespace rapidxml;
std::unique_ptr<INotifyPropertyChanged> Serializer::deserialize()
{
AttrBag bag;
BindingBag bindings;
auto res = deserialize(nullptr, _doc.first_node(), bag, bindings);
auto elem = dynamic_cast<IVisualElement*>(res.get());
for (auto& def : bindings)
{
auto a = dynamic_cast<ControlBase*>(def.a);
auto b = dynamic_cast<ControlBase*>(elem->find_element(def.b_name));
if (!a || !b)
throw std::runtime_error("Selected object does not support binding!");
std::unique_ptr<Binding> binding(new Binding(
_factory, a, def.a_prop, b, def.b_prop));
a->add_binding(std::move(binding));
}
return res;
}
Serializer::Serializer(const char* filename, TypeFactory& factory)
: _factory(factory)
{
ifstream theFile(filename);
_buffer = vector<char>((istreambuf_iterator<char>(theFile)),
istreambuf_iterator<char>());
_buffer.push_back('\0');
_doc.parse<0>(_buffer.data());
}
std::string find_attribute(xml_node<>* node, const std::string& name,
const AttrBag& bag)
{
auto attr = node->first_attribute(name.c_str());
if (attr != nullptr) return attr->value();
for (auto p : bag)
{
if (p->name() == name) return p->value();
}
return "";
}
bool has_attribute(xml_node<>* node, const std::string& name, const AttrBag& bag)
{
auto attr = node->first_attribute(name.c_str());
if (attr != nullptr) return true;
for (auto p : bag)
{
if (p->name() == name) return true;
}
return false;
}
void Serializer::parse_container(Container* container,
xml_node<>* node,
const std::string& name,
const AttrBag& bag,
BindingBag& bindings)
{
for (auto sub_node = node->first_node();
sub_node;
sub_node = sub_node->next_sibling()) {
try
{
container->add_item(deserialize(container, sub_node, bag, bindings));
} catch (const exception& ex) {
LOG(ERROR) << "Parsing Error: " << ex.what() << " (" << node->name()
<< " " << name << ")" << endl;
}
}
}
unique_ptr<INotifyPropertyChanged> Serializer::deserialize(IVisualElement* parent,
xml_node<>* node,
const AttrBag& bag,
BindingBag& bindings)
{
string type = node->name();
auto name = find_attribute(node, "name", bag);
auto t_def = _factory.find_type(type);
if (!t_def)
{
stringstream ss; ss << "Unrecognized Visual Element (" << type
<< " " << name << ")";
throw runtime_error(ss.str());
}
auto res = t_def->default_construct();
for (auto prop_name : t_def->get_property_names())
{
auto p_def = t_def->get_property(prop_name);
if (has_attribute(node, p_def->get_name(), bag))
{
auto prop_text = find_attribute(node, p_def->get_name(), bag);
auto prop = p_def->create(res.get());
prop->set_value(prop_text);
}
}
auto panel = dynamic_cast<Container*>(res.get());
if (panel)
{
std::unique_ptr<BindingDef> binding;
parse_container(panel, node, name, bag, bindings);
}
/*auto name = find_attribute(node, "name", bag, "");
auto position_str = find_attribute(node, "position", bag, "");
auto position = parse_size(position_str);
auto size_str = find_attribute(node, "size", bag, "auto");
auto size = parse_size(size_str);
auto margin_str = find_attribute(node, "margin", bag, "0");
auto margin = parse_margin(margin_str);
auto align_str = find_attribute(node, "align", bag, "left");
auto align = parse_text_alignment(align_str);
auto txt_color_str = find_attribute(node, "text.color", bag, "black");
auto txt_color = parse_color(txt_color_str);
auto txt_align_str = find_attribute(node, "text.align", bag, "left");
auto txt_align = parse_text_alignment(txt_align_str);
auto txt_str = find_attribute(node, "text", bag, "");
std::unique_ptr<BindingDef> binding;
if (starts_with("{bind ", txt_str))
{
MinimalParser p(txt_str);
p.try_get_string("{bind ");
auto element_id = p.get_id();
p.req('.');
auto prop_name = p.get_id();
p.req('}');
p.req_eof();
LOG(INFO) << element_id << " " << prop_name;
binding.reset(new BindingDef
{
nullptr, // a is unknown at this point, will be filled in later
"text", // for now, we know exactly what attribute has the binding
element_id,
prop_name
});
txt_str = "";
}
auto color_str = find_attribute(node, "color", bag, "gray");
auto color = parse_color(color_str);
auto ori_str = find_attribute(node, "orientation", bag, "vertical");
auto orientation = parse_orientation(ori_str);
auto selected_str = find_attribute(node, "selected", bag, "\\");
auto visible_str = find_attribute(node, "visible", bag, "true");
auto visible = parse_bool(visible_str);
auto enabled_str = find_attribute(node, "enabled", bag, "true");
auto enabled = parse_bool(enabled_str);*/
/*if (type == "TextBlock")
{
res = shared_ptr<TextBlock>(new TextBlock(
name, txt_str, txt_align, position, size, txt_color
));
}
else if (type == "Button")
{
if (find_attribute(node, "text.align", bag, "\\") == "\\")
txt_align = Alignment::center; // override default for buttons
res = shared_ptr<Button>(new Button(
name, txt_str, txt_align, txt_color,
align, position, size, color
));
}
else if (type == "Slider")
{
auto min_str = find_attribute(node, "min", bag, "0");
auto max_str = find_attribute(node, "max", bag, "100");
auto step_str = find_attribute(node, "step", bag, "20");
auto value_str = find_attribute(node, "value", bag, "0");
auto min = parse_float(min_str);
auto max = parse_float(max_str);
auto step = parse_float(step_str);
auto value = parse_float(value_str);
res = shared_ptr<Slider>(new Slider(
name, align, position, size, color, txt_color,
orientation, min, max, step, value
));
}
else if (type == "StackPanel")
{
auto panel = shared_ptr<StackPanel>(new StackPanel(
name, position, size, align, orientation, nullptr
));
parse_container(panel.get(), node, name, bag, bindings);
res = panel;
}
else if (type == "Panel")
{
auto panel = shared_ptr<Panel>(new Panel(
name, position, size, align
));
parse_container(panel.get(), node, name, bag, bindings);
res = panel;
}
else if (type == "PageView")
{
auto panel = shared_ptr<PageView>(new PageView(
name, position, size, align
));
parse_container(panel.get(), node, name, bag, bindings);
auto selected_item = panel->find_element(selected_str);
panel->set_focused_child(selected_item);
res = panel;
}
else if (type == "Grid")
{
auto grid = shared_ptr<Grid>(new Grid(
name, position, size, align, orientation
));
for (auto sub_node = node->first_node();
sub_node;
sub_node = sub_node->next_sibling()) {
try
{
string sub_name = sub_node->name();
if (sub_name == "Break") grid->commit_line();
else grid->add_item(deserialize(grid.get(), sub_node, bag, bindings));
} catch (const exception& ex) {
LOG(ERROR) << "Parsing Error: " << ex.what() << " (" << type
<< " " << name << ")" << endl;
}
}
grid->commit_line();
res = grid;
}
else if (type == "Using")
{
auto sub_node = node->first_node();
AttrBag new_bag;
for (auto attr = node->first_attribute();
attr;
attr = attr->next_attribute()) {
new_bag.push_back(attr);
}
for (auto attr : bag)
{
auto it = std::find_if(new_bag.begin(), new_bag.end(),
[attr](xml_attribute<>* x) {
return std::string(x->name()) == attr->name();
});
if (it == new_bag.end())
{
new_bag.push_back(attr);
}
}
try
{
res = deserialize(parent, sub_node, new_bag, bindings);
} catch (const exception& ex) {
LOG(ERROR) << "Parsing Error: " << ex.what() << " (" << type
<< " " << name << ")" << endl;
}
if (sub_node->next_sibling())
{
stringstream ss;
ss << "Using should not have multiple nested items!";
throw runtime_error(ss.str());
}
}*/
// update controls parent before applying any adaptors
auto control = dynamic_cast<ControlBase*>(res.get());
if (control)
{
control->update_parent(parent);
auto margin_str = find_attribute(node, "margin", bag);
margin_str = (margin_str == "" ? "0" : margin_str);
auto margin = parse_margin(margin_str);
res = unique_ptr<MarginAdaptor>(
new MarginAdaptor(std::move(res), margin));
res = unique_ptr<VisibilityAdaptor>(
new VisibilityAdaptor(std::move(res)));
}
/*if (binding)
{
binding->a = res.get();
bindings.push_back(*binding);
}*/
return res;
}
<commit_msg>enabled back using blocks<commit_after>#include "parser.h"
#include "controls.h"
#include "containers.h"
#include "adaptors.h"
using namespace std;
using namespace rapidxml;
std::unique_ptr<INotifyPropertyChanged> Serializer::deserialize()
{
AttrBag bag;
BindingBag bindings;
auto res = deserialize(nullptr, _doc.first_node(), bag, bindings);
auto elem = dynamic_cast<IVisualElement*>(res.get());
for (auto& def : bindings)
{
auto a = dynamic_cast<ControlBase*>(def.a);
auto b = dynamic_cast<ControlBase*>(elem->find_element(def.b_name));
if (!a || !b)
throw std::runtime_error("Selected object does not support binding!");
std::unique_ptr<Binding> binding(new Binding(
_factory, a, def.a_prop, b, def.b_prop));
a->add_binding(std::move(binding));
}
return res;
}
Serializer::Serializer(const char* filename, TypeFactory& factory)
: _factory(factory)
{
ifstream theFile(filename);
_buffer = vector<char>((istreambuf_iterator<char>(theFile)),
istreambuf_iterator<char>());
_buffer.push_back('\0');
_doc.parse<0>(_buffer.data());
}
std::string find_attribute(xml_node<>* node, const std::string& name,
const AttrBag& bag)
{
auto attr = node->first_attribute(name.c_str());
if (attr != nullptr) return attr->value();
for (auto p : bag)
{
if (p->name() == name) return p->value();
}
return "";
}
bool has_attribute(xml_node<>* node, const std::string& name, const AttrBag& bag)
{
auto attr = node->first_attribute(name.c_str());
if (attr != nullptr) return true;
for (auto p : bag)
{
if (p->name() == name) return true;
}
return false;
}
void Serializer::parse_container(Container* container,
xml_node<>* node,
const std::string& name,
const AttrBag& bag,
BindingBag& bindings)
{
for (auto sub_node = node->first_node();
sub_node;
sub_node = sub_node->next_sibling()) {
try
{
container->add_item(deserialize(container, sub_node, bag, bindings));
} catch (const exception& ex) {
LOG(ERROR) << "Parsing Error: " << ex.what() << " (" << node->name()
<< " " << name << ")" << endl;
}
}
}
unique_ptr<INotifyPropertyChanged> Serializer::deserialize(IVisualElement* parent,
xml_node<>* node,
const AttrBag& bag,
BindingBag& bindings)
{
string type = node->name();
auto name = find_attribute(node, "name", bag);
if (type == "Using")
{
auto sub_node = node->first_node();
AttrBag new_bag;
for (auto attr = node->first_attribute();
attr;
attr = attr->next_attribute()) {
new_bag.push_back(attr);
}
for (auto attr : bag)
{
auto it = std::find_if(new_bag.begin(), new_bag.end(),
[attr](xml_attribute<>* x) {
return std::string(x->name()) == attr->name();
});
if (it == new_bag.end())
{
new_bag.push_back(attr);
}
}
if (sub_node->next_sibling())
{
stringstream ss;
ss << "Using should not have multiple nested items!";
throw runtime_error(ss.str());
}
try
{
return deserialize(parent, sub_node, new_bag, bindings);
} catch (const exception& ex) {
LOG(ERROR) << "Parsing Error: " << ex.what() << " (" << type
<< " " << name << ")" << endl;
}
}
auto t_def = _factory.find_type(type);
if (!t_def)
{
stringstream ss; ss << "Unrecognized Visual Element (" << type
<< " " << name << ")";
throw runtime_error(ss.str());
}
auto res = t_def->default_construct();
for (auto prop_name : t_def->get_property_names())
{
auto p_def = t_def->get_property(prop_name);
if (has_attribute(node, p_def->get_name(), bag))
{
auto prop_text = find_attribute(node, p_def->get_name(), bag);
auto prop = p_def->create(res.get());
prop->set_value(prop_text);
}
}
auto panel = dynamic_cast<Container*>(res.get());
if (panel)
{
std::unique_ptr<BindingDef> binding;
parse_container(panel, node, name, bag, bindings);
}
/*auto name = find_attribute(node, "name", bag, "");
auto position_str = find_attribute(node, "position", bag, "");
auto position = parse_size(position_str);
auto size_str = find_attribute(node, "size", bag, "auto");
auto size = parse_size(size_str);
auto margin_str = find_attribute(node, "margin", bag, "0");
auto margin = parse_margin(margin_str);
auto align_str = find_attribute(node, "align", bag, "left");
auto align = parse_text_alignment(align_str);
auto txt_color_str = find_attribute(node, "text.color", bag, "black");
auto txt_color = parse_color(txt_color_str);
auto txt_align_str = find_attribute(node, "text.align", bag, "left");
auto txt_align = parse_text_alignment(txt_align_str);
auto txt_str = find_attribute(node, "text", bag, "");
std::unique_ptr<BindingDef> binding;
if (starts_with("{bind ", txt_str))
{
MinimalParser p(txt_str);
p.try_get_string("{bind ");
auto element_id = p.get_id();
p.req('.');
auto prop_name = p.get_id();
p.req('}');
p.req_eof();
LOG(INFO) << element_id << " " << prop_name;
binding.reset(new BindingDef
{
nullptr, // a is unknown at this point, will be filled in later
"text", // for now, we know exactly what attribute has the binding
element_id,
prop_name
});
txt_str = "";
}
auto color_str = find_attribute(node, "color", bag, "gray");
auto color = parse_color(color_str);
auto ori_str = find_attribute(node, "orientation", bag, "vertical");
auto orientation = parse_orientation(ori_str);
auto selected_str = find_attribute(node, "selected", bag, "\\");
auto visible_str = find_attribute(node, "visible", bag, "true");
auto visible = parse_bool(visible_str);
auto enabled_str = find_attribute(node, "enabled", bag, "true");
auto enabled = parse_bool(enabled_str);*/
/*if (type == "TextBlock")
{
res = shared_ptr<TextBlock>(new TextBlock(
name, txt_str, txt_align, position, size, txt_color
));
}
else if (type == "Button")
{
if (find_attribute(node, "text.align", bag, "\\") == "\\")
txt_align = Alignment::center; // override default for buttons
res = shared_ptr<Button>(new Button(
name, txt_str, txt_align, txt_color,
align, position, size, color
));
}
else if (type == "Slider")
{
auto min_str = find_attribute(node, "min", bag, "0");
auto max_str = find_attribute(node, "max", bag, "100");
auto step_str = find_attribute(node, "step", bag, "20");
auto value_str = find_attribute(node, "value", bag, "0");
auto min = parse_float(min_str);
auto max = parse_float(max_str);
auto step = parse_float(step_str);
auto value = parse_float(value_str);
res = shared_ptr<Slider>(new Slider(
name, align, position, size, color, txt_color,
orientation, min, max, step, value
));
}
else if (type == "StackPanel")
{
auto panel = shared_ptr<StackPanel>(new StackPanel(
name, position, size, align, orientation, nullptr
));
parse_container(panel.get(), node, name, bag, bindings);
res = panel;
}
else if (type == "Panel")
{
auto panel = shared_ptr<Panel>(new Panel(
name, position, size, align
));
parse_container(panel.get(), node, name, bag, bindings);
res = panel;
}
else if (type == "PageView")
{
auto panel = shared_ptr<PageView>(new PageView(
name, position, size, align
));
parse_container(panel.get(), node, name, bag, bindings);
auto selected_item = panel->find_element(selected_str);
panel->set_focused_child(selected_item);
res = panel;
}
else if (type == "Grid")
{
auto grid = shared_ptr<Grid>(new Grid(
name, position, size, align, orientation
));
for (auto sub_node = node->first_node();
sub_node;
sub_node = sub_node->next_sibling()) {
try
{
string sub_name = sub_node->name();
if (sub_name == "Break") grid->commit_line();
else grid->add_item(deserialize(grid.get(), sub_node, bag, bindings));
} catch (const exception& ex) {
LOG(ERROR) << "Parsing Error: " << ex.what() << " (" << type
<< " " << name << ")" << endl;
}
}
grid->commit_line();
res = grid;
}
else if (type == "Using")
{
auto sub_node = node->first_node();
AttrBag new_bag;
for (auto attr = node->first_attribute();
attr;
attr = attr->next_attribute()) {
new_bag.push_back(attr);
}
for (auto attr : bag)
{
auto it = std::find_if(new_bag.begin(), new_bag.end(),
[attr](xml_attribute<>* x) {
return std::string(x->name()) == attr->name();
});
if (it == new_bag.end())
{
new_bag.push_back(attr);
}
}
try
{
res = deserialize(parent, sub_node, new_bag, bindings);
} catch (const exception& ex) {
LOG(ERROR) << "Parsing Error: " << ex.what() << " (" << type
<< " " << name << ")" << endl;
}
if (sub_node->next_sibling())
{
stringstream ss;
ss << "Using should not have multiple nested items!";
throw runtime_error(ss.str());
}
}*/
// update controls parent before applying any adaptors
auto control = dynamic_cast<ControlBase*>(res.get());
if (control)
{
control->update_parent(parent);
auto margin_str = find_attribute(node, "margin", bag);
margin_str = (margin_str == "" ? "0" : margin_str);
auto margin = parse_margin(margin_str);
res = unique_ptr<MarginAdaptor>(
new MarginAdaptor(std::move(res), margin));
res = unique_ptr<VisibilityAdaptor>(
new VisibilityAdaptor(std::move(res)));
}
/*if (binding)
{
binding->a = res.get();
bindings.push_back(*binding);
}*/
return res;
}
<|endoftext|> |
<commit_before>// parser.cpp
#include <iostream>
#include <fstream>
#include "parser.h"
#include "utility.h"
namespace parser {
using std::ifstream;
using std::cout;
using utility::string_to_int_vector;
using utility::string_to_double_vector;
using utility::string_to_string_vector;
InputParameters::InputParameters(int argc, char* argv[]) {
// Displayed options
po::options_description displayed_options {"Allowed options"};
// Command line options description
po::options_description cl_options {"Command line options"};
cl_options.add_options()
("help,h",
"Display available options")
("parameter_filename,i",
po::value<string>(),
"Input file")
;
displayed_options.add(cl_options);
// Parameter file options description
po::options_description inp_options {"System input and parameters"};
inp_options.add_options()
("origami_input_filename",
po::value<string>(&m_origami_input_filename),
"Origami input filename")
("binding_pot",
po::value<string>(&m_binding_pot),
"Binding potential to use")
("misbinding_pot",
po::value<string>(&m_misbinding_pot),
"Misbinding potential to use")
("stacking_pot",
po::value<string>(&m_stacking_pot),
"Stacking potential to use")
("temp",
po::value<double>(&m_temp)->default_value(300),
"System temperature (K)")
("staple_M",
po::value<double>(&m_staple_M)->default_value(1),
"Staple concentration (mol/L)")
("cation_M",
po::value<double>(&m_cation_M)->default_value(1),
"Cation concentration (mol/L)")
("temp_for_staple_u",
po::value<double>(&m_temp_for_staple_u)->default_value(300),
"Temperature to calculate chemical potential with")
("staple_u_mult",
po::value<double>(&m_staple_u_mult)->default_value(1),
"Multiplier for staple u")
("lattice_site_volume",
po::value<double>(&m_lattice_site_volume)->default_value(1),
"Volume per lattice site (L)")
("stacking_ene",
po::value<double>(&m_stacking_ene)->default_value(1),
"Stacking energy for constant potential")
("min_total_staples",
po::value<int>(&m_min_total_staples)->default_value(0),
"Min number of total staples")
("max_total_staples",
po::value<int>(&m_max_total_staples)->default_value(999),
"Max number of total staples")
("max_type_staples",
po::value<int>(&m_max_type_staples)->default_value(999),
"Max number of staples of a given type")
("excluded_staples",
po::value<string>(),
"Staple types to exclude")
("domain_update_biases_present",
po::value<bool>(&m_domain_update_biases_present)->default_value(false),
"Max number of staples of a given type")
("order_parameter_file",
po::value<string>(&m_ops_filename)->default_value(""),
"Order parameter specification file.")
("bias_functions_file",
po::value<string>(&m_bias_funcs_filename)->default_value(""),
"Bias function specification file.")
("bias_functions_mult",
po::value<double>(&m_bias_funcs_mult)->default_value(1),
"System bias function multiplier.")
("energy_filebase",
po::value<string>(&m_energy_filebase)->default_value(""),
"Filebase for read/write of energies")
("simulation_type",
po::value<string>(&m_simulation_type)->default_value("constant_temp"),
"constant_temp, annealing, or parallel_tempering")
;
displayed_options.add(inp_options);
po::options_description enum_options {"Enumeration options"};
enum_options.add_options()
("enumerate_staples_only",
po::value<bool>(&m_enumerate_staples_only)->default_value(false),
"Enumerate staples only")
;
displayed_options.add(enum_options);
po::options_description sim_options {"General simulation options"};
sim_options.add_options()
("random_seed",
po::value<int>(&m_random_seed)->default_value(-1),
"Seed for random number generator")
("movetype_file",
po::value<string>(&m_movetype_filename),
"Movetype specificiation file")
("num_walks_filename",
po::value<string>(&m_num_walks_filename)->default_value(""),
"Precalculated number of ideal random walks archive")
("restart_traj_file",
po::value<string>(&m_restart_traj_file)->default_value(""),
"Trajectory file to restart from")
("restart_traj_filebase",
po::value<string>(&m_restart_traj_filebase)->default_value(""),
"Trajectory restart filebase")
("restart_traj_postfix",
po::value<string>(&m_restart_traj_postfix)->default_value(".trj"),
"Trajectory restart postfix")
("restart_traj_files",
po::value<string>(),
"Trajectory restart files for each replicate")
("restart_step",
po::value<int>(&m_restart_step)->default_value(0),
"Step to restart from")
("restart_steps",
po::value<string>(),
"Restart step for each replicate")
("vmd_file_dir",
po::value<string>(&m_vmd_file_dir)->default_value(""),
"Directory containing VMD scripts for viewing simulations")
("centering_freq",
po::value<int>(&m_centering_freq)->default_value(0),
"Centering frequency")
("centering_domain",
po::value<int>(&m_centering_domain)->default_value(0),
"Domain to center on")
("constraint_check_freq",
po::value<int>(&m_constraint_check_freq)->default_value(0),
"Constraint check frequency")
("m_allow_nonsensical_ps",
po::value<bool>(&m_allow_nonsensical_ps)->default_value(false),
"Allow nonsensical exchange probabilities")
("max_duration",
po::value<double>(&m_max_duration)->default_value(10e9),
"Maximum duration of simulation (s)")
;
displayed_options.add(sim_options);
po::options_description cons_t_options {"Constant temperature options"};
cons_t_options.add_options()
("ct_steps",
po::value<long long int>(&m_ct_steps)->default_value(0),
"Number of MC steps")
;
displayed_options.add(cons_t_options);
po::options_description annealing_options {"Annealing simulation options"};
annealing_options.add_options()
("max_temp",
po::value<double>(&m_max_temp)->default_value(400),
"Maximum temperature for annealing")
("min_temp",
po::value<double>(&m_min_temp)->default_value(300),
"Minimum temperature for annealing")
("temp_interval",
po::value<double>(&m_temp_interval)->default_value(1),
"Temperature interval for annealing")
("steps_per_temp",
po::value<long long int>(&m_steps_per_temp)->default_value(0),
"Steps per temperature in annealing")
;
displayed_options.add(annealing_options);
po::options_description pt_options {"Parallel tempering simulation options"};
pt_options.add_options()
("temps",
po::value<string>(),
"Temperature list")
("num_reps",
po::value<int>(&m_num_reps)->default_value(1),
"Number of replicas")
("pt_steps",
po::value<long long int>(&m_pt_steps)->default_value(0),
"Number of MC steps")
("exchange_interval",
po::value<int>(&m_exchange_interval)->default_value(0),
"Steps between exchange attempts")
("constant_staple_M",
po::value<bool>(&m_constant_staple_M)->default_value(true),
"Hold staple concentration constant")
("chem_pot_mults",
po::value<string>(),
"Factor to multiply base chem pot for each rep")
("bias_mults",
po::value<string>(),
"Multiplier for system bias")
("restart_swap_file",
po::value<string>(&m_restart_swap_file)->default_value(""),
"Swap file to restart from")
;
displayed_options.add(pt_options);
po::options_description us_options {"Umbrella sampling simulation options"};
us_options.add_options()
("us_grid_bias_tag",
po::value<string>(&m_us_grid_bias_tag)->default_value(""),
"Tag of grid bias function to use for US")
("max_num_iters",
po::value<int>(&m_max_num_iters)->default_value(0),
"Number of iterations")
("max_D_bias",
po::value<double>(&m_max_D_bias)->default_value(0),
"Max change in bias per iteration")
("equil_steps",
po::value<long long int>(&m_equil_steps)->default_value(0),
"Number of equilibration steps")
("max_equil_dur",
po::value<long long int>(&m_max_equil_dur)->default_value(0),
"Maximum duration of equilibration (s)")
("iter_steps",
po::value<long long int>(&m_iter_steps)->default_value(0),
"Number of steps per iteration")
("max_iter_dur",
po::value<long long int>(&m_max_iter_dur)->default_value(0),
"Maximum duration of each iteration (s)")
("prod_steps",
po::value<long long int>(&m_prod_steps)->default_value(0),
"Number of production steps")
("max_prod_dur",
po::value<long long int>(&m_max_prod_dur)->default_value(0),
"Maximum duration of production (s)")
("max_rel_P_diff",
po::value<double>(&m_max_rel_P_diff)->default_value(0.1),
"Maximum allowed change in P for convergence")
("biases_file",
po::value<string>(&m_biases_file)->default_value(""),
"Initial guesses at grid biases")
("biases_filebase",
po::value<string>(&m_biases_filebase)->default_value(""),
"Filebase for grid bias files")
("multi_window",
po::value<bool>(&m_multi_window)->default_value(false),
"Use multiple windows")
("windows_file",
po::value<string>(&m_windows_file)->default_value(""),
"File containing windows as min/max pairs of tuples")
("local_dir",
po::value<string>(&m_local_dir)->default_value(""),
"Directory for local writes")
("central_dir",
po::value<string>(&m_central_dir)->default_value(""),
"Directory to get trajectories for starting steps")
;
displayed_options.add(us_options);
po::options_description out_options {"Output options"};
out_options.add_options()
("output_filebase",
po::value<string>(&m_output_filebase)->default_value(""),
"Base name for output files")
("logging_freq",
po::value<int>(&m_logging_freq)->default_value(0),
"Logging frequency")
("configs_output_freq",
po::value<int>(&m_configs_output_freq)->default_value(0),
"Configuration output write frequency")
("vtf_output_freq",
po::value<int>(&m_vtf_output_freq)->default_value(0),
"Configuration output write frequency")
("vcf_per_domain",
po::value<bool>(&m_vcf_per_domain)->default_value(false),
"Write a VCF entry for every domain grown")
("counts_output_freq",
po::value<int>(&m_counts_output_freq)->default_value(0),
"Counts output write frequency")
("energies_output_freq",
po::value<int>(&m_energies_output_freq)->default_value(0),
"Energies output write frequency")
("ops_to_output",
po::value<string>(),
"Order parameters to output to file")
("order_params_output_freq",
po::value<int>(&m_order_params_output_freq)->default_value(0),
"Order parameters write frequency")
("vmd_pipe_freq",
po::value<int>(&m_vmd_pipe_freq),
"Realtime VMD visualization updating frequency")
("create_vmd_instance",
po::value<bool>(&m_create_vmd_instance)->default_value(false),
"Create VMD instance")
;
displayed_options.add(out_options);
// Command line variable map
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, displayed_options), vm);
po::notify(vm);
if (vm.count("help")) {
cout << "\n";
cout << displayed_options;
cout << "\n";
exit(1);
}
if (not vm.count("parameter_filename")) {
cout << "Input parameter file must be provided.\n";
exit(1);
}
// Parameter file variable map
ifstream parameter_file {vm["parameter_filename"].as<string>()};
po::store(po::parse_config_file(parameter_file, displayed_options), vm);
po::notify(vm);
process_custom_types(vm);
}
void InputParameters::process_custom_types(po::variables_map vm) {
if (vm.count("excluded_staples")) {
string excluded_staples_s {vm["excluded_staples"].as<string>()};
m_excluded_staples = string_to_int_vector(excluded_staples_s);
}
if (vm.count("restart_traj_files")) {
string file_s = vm["restart_traj_files"].as<string>();
m_restart_traj_files = string_to_string_vector(file_s);
}
if (vm.count("temps")) {
string temps_s = vm["temps"].as<string>();
m_temps = string_to_double_vector(temps_s);
}
if (vm.count("chem_pot_mults")) {
string chem_pot_mults_s = vm["chem_pot_mults"].as<string>();
m_chem_pot_mults = string_to_double_vector(chem_pot_mults_s);
}
if (vm.count("bias_mults")) {
string bias_mults_s {vm["bias_mults"].as<string>()};
m_bias_mults = string_to_double_vector(bias_mults_s);
}
if (vm.count("ops_to_output")) {
string ops_to_output_s {vm["ops_to_output"].as<string>()};
if (ops_to_output_s != "") {
m_ops_to_output = string_to_string_vector(ops_to_output_s);
}
}
}
}
<commit_msg>Bad name for previously committed option<commit_after>// parser.cpp
#include <iostream>
#include <fstream>
#include "parser.h"
#include "utility.h"
namespace parser {
using std::ifstream;
using std::cout;
using utility::string_to_int_vector;
using utility::string_to_double_vector;
using utility::string_to_string_vector;
InputParameters::InputParameters(int argc, char* argv[]) {
// Displayed options
po::options_description displayed_options {"Allowed options"};
// Command line options description
po::options_description cl_options {"Command line options"};
cl_options.add_options()
("help,h",
"Display available options")
("parameter_filename,i",
po::value<string>(),
"Input file")
;
displayed_options.add(cl_options);
// Parameter file options description
po::options_description inp_options {"System input and parameters"};
inp_options.add_options()
("origami_input_filename",
po::value<string>(&m_origami_input_filename),
"Origami input filename")
("binding_pot",
po::value<string>(&m_binding_pot),
"Binding potential to use")
("misbinding_pot",
po::value<string>(&m_misbinding_pot),
"Misbinding potential to use")
("stacking_pot",
po::value<string>(&m_stacking_pot),
"Stacking potential to use")
("temp",
po::value<double>(&m_temp)->default_value(300),
"System temperature (K)")
("staple_M",
po::value<double>(&m_staple_M)->default_value(1),
"Staple concentration (mol/L)")
("cation_M",
po::value<double>(&m_cation_M)->default_value(1),
"Cation concentration (mol/L)")
("temp_for_staple_u",
po::value<double>(&m_temp_for_staple_u)->default_value(300),
"Temperature to calculate chemical potential with")
("staple_u_mult",
po::value<double>(&m_staple_u_mult)->default_value(1),
"Multiplier for staple u")
("lattice_site_volume",
po::value<double>(&m_lattice_site_volume)->default_value(1),
"Volume per lattice site (L)")
("stacking_ene",
po::value<double>(&m_stacking_ene)->default_value(1),
"Stacking energy for constant potential")
("min_total_staples",
po::value<int>(&m_min_total_staples)->default_value(0),
"Min number of total staples")
("max_total_staples",
po::value<int>(&m_max_total_staples)->default_value(999),
"Max number of total staples")
("max_type_staples",
po::value<int>(&m_max_type_staples)->default_value(999),
"Max number of staples of a given type")
("excluded_staples",
po::value<string>(),
"Staple types to exclude")
("domain_update_biases_present",
po::value<bool>(&m_domain_update_biases_present)->default_value(false),
"Max number of staples of a given type")
("order_parameter_file",
po::value<string>(&m_ops_filename)->default_value(""),
"Order parameter specification file.")
("bias_functions_file",
po::value<string>(&m_bias_funcs_filename)->default_value(""),
"Bias function specification file.")
("bias_functions_mult",
po::value<double>(&m_bias_funcs_mult)->default_value(1),
"System bias function multiplier.")
("energy_filebase",
po::value<string>(&m_energy_filebase)->default_value(""),
"Filebase for read/write of energies")
("simulation_type",
po::value<string>(&m_simulation_type)->default_value("constant_temp"),
"constant_temp, annealing, or parallel_tempering")
;
displayed_options.add(inp_options);
po::options_description enum_options {"Enumeration options"};
enum_options.add_options()
("enumerate_staples_only",
po::value<bool>(&m_enumerate_staples_only)->default_value(false),
"Enumerate staples only")
;
displayed_options.add(enum_options);
po::options_description sim_options {"General simulation options"};
sim_options.add_options()
("random_seed",
po::value<int>(&m_random_seed)->default_value(-1),
"Seed for random number generator")
("movetype_file",
po::value<string>(&m_movetype_filename),
"Movetype specificiation file")
("num_walks_filename",
po::value<string>(&m_num_walks_filename)->default_value(""),
"Precalculated number of ideal random walks archive")
("restart_traj_file",
po::value<string>(&m_restart_traj_file)->default_value(""),
"Trajectory file to restart from")
("restart_traj_filebase",
po::value<string>(&m_restart_traj_filebase)->default_value(""),
"Trajectory restart filebase")
("restart_traj_postfix",
po::value<string>(&m_restart_traj_postfix)->default_value(".trj"),
"Trajectory restart postfix")
("restart_traj_files",
po::value<string>(),
"Trajectory restart files for each replicate")
("restart_step",
po::value<int>(&m_restart_step)->default_value(0),
"Step to restart from")
("restart_steps",
po::value<string>(),
"Restart step for each replicate")
("vmd_file_dir",
po::value<string>(&m_vmd_file_dir)->default_value(""),
"Directory containing VMD scripts for viewing simulations")
("centering_freq",
po::value<int>(&m_centering_freq)->default_value(0),
"Centering frequency")
("centering_domain",
po::value<int>(&m_centering_domain)->default_value(0),
"Domain to center on")
("constraint_check_freq",
po::value<int>(&m_constraint_check_freq)->default_value(0),
"Constraint check frequency")
("allow_nonsensical_ps",
po::value<bool>(&m_allow_nonsensical_ps)->default_value(false),
"Allow nonsensical exchange probabilities")
("max_duration",
po::value<double>(&m_max_duration)->default_value(10e9),
"Maximum duration of simulation (s)")
;
displayed_options.add(sim_options);
po::options_description cons_t_options {"Constant temperature options"};
cons_t_options.add_options()
("ct_steps",
po::value<long long int>(&m_ct_steps)->default_value(0),
"Number of MC steps")
;
displayed_options.add(cons_t_options);
po::options_description annealing_options {"Annealing simulation options"};
annealing_options.add_options()
("max_temp",
po::value<double>(&m_max_temp)->default_value(400),
"Maximum temperature for annealing")
("min_temp",
po::value<double>(&m_min_temp)->default_value(300),
"Minimum temperature for annealing")
("temp_interval",
po::value<double>(&m_temp_interval)->default_value(1),
"Temperature interval for annealing")
("steps_per_temp",
po::value<long long int>(&m_steps_per_temp)->default_value(0),
"Steps per temperature in annealing")
;
displayed_options.add(annealing_options);
po::options_description pt_options {"Parallel tempering simulation options"};
pt_options.add_options()
("temps",
po::value<string>(),
"Temperature list")
("num_reps",
po::value<int>(&m_num_reps)->default_value(1),
"Number of replicas")
("pt_steps",
po::value<long long int>(&m_pt_steps)->default_value(0),
"Number of MC steps")
("exchange_interval",
po::value<int>(&m_exchange_interval)->default_value(0),
"Steps between exchange attempts")
("constant_staple_M",
po::value<bool>(&m_constant_staple_M)->default_value(true),
"Hold staple concentration constant")
("chem_pot_mults",
po::value<string>(),
"Factor to multiply base chem pot for each rep")
("bias_mults",
po::value<string>(),
"Multiplier for system bias")
("restart_swap_file",
po::value<string>(&m_restart_swap_file)->default_value(""),
"Swap file to restart from")
;
displayed_options.add(pt_options);
po::options_description us_options {"Umbrella sampling simulation options"};
us_options.add_options()
("us_grid_bias_tag",
po::value<string>(&m_us_grid_bias_tag)->default_value(""),
"Tag of grid bias function to use for US")
("max_num_iters",
po::value<int>(&m_max_num_iters)->default_value(0),
"Number of iterations")
("max_D_bias",
po::value<double>(&m_max_D_bias)->default_value(0),
"Max change in bias per iteration")
("equil_steps",
po::value<long long int>(&m_equil_steps)->default_value(0),
"Number of equilibration steps")
("max_equil_dur",
po::value<long long int>(&m_max_equil_dur)->default_value(0),
"Maximum duration of equilibration (s)")
("iter_steps",
po::value<long long int>(&m_iter_steps)->default_value(0),
"Number of steps per iteration")
("max_iter_dur",
po::value<long long int>(&m_max_iter_dur)->default_value(0),
"Maximum duration of each iteration (s)")
("prod_steps",
po::value<long long int>(&m_prod_steps)->default_value(0),
"Number of production steps")
("max_prod_dur",
po::value<long long int>(&m_max_prod_dur)->default_value(0),
"Maximum duration of production (s)")
("max_rel_P_diff",
po::value<double>(&m_max_rel_P_diff)->default_value(0.1),
"Maximum allowed change in P for convergence")
("biases_file",
po::value<string>(&m_biases_file)->default_value(""),
"Initial guesses at grid biases")
("biases_filebase",
po::value<string>(&m_biases_filebase)->default_value(""),
"Filebase for grid bias files")
("multi_window",
po::value<bool>(&m_multi_window)->default_value(false),
"Use multiple windows")
("windows_file",
po::value<string>(&m_windows_file)->default_value(""),
"File containing windows as min/max pairs of tuples")
("local_dir",
po::value<string>(&m_local_dir)->default_value(""),
"Directory for local writes")
("central_dir",
po::value<string>(&m_central_dir)->default_value(""),
"Directory to get trajectories for starting steps")
;
displayed_options.add(us_options);
po::options_description out_options {"Output options"};
out_options.add_options()
("output_filebase",
po::value<string>(&m_output_filebase)->default_value(""),
"Base name for output files")
("logging_freq",
po::value<int>(&m_logging_freq)->default_value(0),
"Logging frequency")
("configs_output_freq",
po::value<int>(&m_configs_output_freq)->default_value(0),
"Configuration output write frequency")
("vtf_output_freq",
po::value<int>(&m_vtf_output_freq)->default_value(0),
"Configuration output write frequency")
("vcf_per_domain",
po::value<bool>(&m_vcf_per_domain)->default_value(false),
"Write a VCF entry for every domain grown")
("counts_output_freq",
po::value<int>(&m_counts_output_freq)->default_value(0),
"Counts output write frequency")
("energies_output_freq",
po::value<int>(&m_energies_output_freq)->default_value(0),
"Energies output write frequency")
("ops_to_output",
po::value<string>(),
"Order parameters to output to file")
("order_params_output_freq",
po::value<int>(&m_order_params_output_freq)->default_value(0),
"Order parameters write frequency")
("vmd_pipe_freq",
po::value<int>(&m_vmd_pipe_freq),
"Realtime VMD visualization updating frequency")
("create_vmd_instance",
po::value<bool>(&m_create_vmd_instance)->default_value(false),
"Create VMD instance")
;
displayed_options.add(out_options);
// Command line variable map
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, displayed_options), vm);
po::notify(vm);
if (vm.count("help")) {
cout << "\n";
cout << displayed_options;
cout << "\n";
exit(1);
}
if (not vm.count("parameter_filename")) {
cout << "Input parameter file must be provided.\n";
exit(1);
}
// Parameter file variable map
ifstream parameter_file {vm["parameter_filename"].as<string>()};
po::store(po::parse_config_file(parameter_file, displayed_options), vm);
po::notify(vm);
process_custom_types(vm);
}
void InputParameters::process_custom_types(po::variables_map vm) {
if (vm.count("excluded_staples")) {
string excluded_staples_s {vm["excluded_staples"].as<string>()};
m_excluded_staples = string_to_int_vector(excluded_staples_s);
}
if (vm.count("restart_traj_files")) {
string file_s = vm["restart_traj_files"].as<string>();
m_restart_traj_files = string_to_string_vector(file_s);
}
if (vm.count("temps")) {
string temps_s = vm["temps"].as<string>();
m_temps = string_to_double_vector(temps_s);
}
if (vm.count("chem_pot_mults")) {
string chem_pot_mults_s = vm["chem_pot_mults"].as<string>();
m_chem_pot_mults = string_to_double_vector(chem_pot_mults_s);
}
if (vm.count("bias_mults")) {
string bias_mults_s {vm["bias_mults"].as<string>()};
m_bias_mults = string_to_double_vector(bias_mults_s);
}
if (vm.count("ops_to_output")) {
string ops_to_output_s {vm["ops_to_output"].as<string>()};
if (ops_to_output_s != "") {
m_ops_to_output = string_to_string_vector(ops_to_output_s);
}
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2018-2019 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <llmq/quorums.h>
#include <llmq/quorums_utils.h>
#include <chainparams.h>
#include <random.h>
#include <spork.h>
#include <validation.h>
#include <masternode/masternode-meta.h>
namespace llmq
{
std::vector<CDeterministicMNCPtr> CLLMQUtils::GetAllQuorumMembers(Consensus::LLMQType llmqType, const CBlockIndex* pindexQuorum)
{
auto& params = Params().GetConsensus().llmqs.at(llmqType);
auto allMns = deterministicMNManager->GetListForBlock(pindexQuorum);
auto modifier = ::SerializeHash(std::make_pair(llmqType, pindexQuorum->GetBlockHash()));
return allMns.CalculateQuorum(params.size, modifier);
}
uint256 CLLMQUtils::BuildCommitmentHash(Consensus::LLMQType llmqType, const uint256& blockHash, const std::vector<bool>& validMembers, const CBLSPublicKey& pubKey, const uint256& vvecHash)
{
CHashWriter hw(SER_NETWORK, 0);
hw << llmqType;
hw << blockHash;
hw << DYNBITSET(validMembers);
hw << pubKey;
hw << vvecHash;
return hw.GetHash();
}
uint256 CLLMQUtils::BuildSignHash(Consensus::LLMQType llmqType, const uint256& quorumHash, const uint256& id, const uint256& msgHash)
{
CHashWriter h(SER_GETHASH, 0);
h << llmqType;
h << quorumHash;
h << id;
h << msgHash;
return h.GetHash();
}
std::set<uint256> CLLMQUtils::GetQuorumConnections(Consensus::LLMQType llmqType, const CBlockIndex* pindexQuorum, const uint256& forMember, bool onlyOutbound)
{
auto& params = Params().GetConsensus().llmqs.at(llmqType);
auto mns = GetAllQuorumMembers(llmqType, pindexQuorum);
std::set<uint256> result;
if (!onlyOutbound) {
for (auto& dmn : mns) {
result.emplace(dmn->proTxHash);
}
return result;
}
if (sporkManager.IsSporkActive(SPORK_21_QUORUM_ALL_CONNECTED)) {
for (auto& dmn : mns) {
// this will cause deterministic behaviour between incoming and outgoing connections.
// Each member needs a connection to all other members, so we have each member paired. The below check
// will be true on one side and false on the other side of the pairing, so we avoid having both members
// initiating the connection.
if (dmn->proTxHash < forMember) {
result.emplace(dmn->proTxHash);
}
}
return result;
}
// TODO remove this after activation of SPORK_21_QUORUM_ALL_CONNECTED
auto calcOutbound = [&](size_t i, const uint256 proTxHash) {
// Connect to nodes at indexes (i+2^k)%n, where
// k: 0..max(1, floor(log2(n-1))-1)
// n: size of the quorum/ring
std::set<uint256> r;
int gap = 1;
int gap_max = (int)mns.size() - 1;
int k = 0;
while ((gap_max >>= 1) || k <= 1) {
size_t idx = (i + gap) % mns.size();
auto& otherDmn = mns[idx];
if (otherDmn->proTxHash == proTxHash) {
continue;
}
r.emplace(otherDmn->proTxHash);
gap <<= 1;
k++;
}
return r;
};
for (size_t i = 0; i < mns.size(); i++) {
auto& dmn = mns[i];
if (dmn->proTxHash == forMember) {
auto r = calcOutbound(i, dmn->proTxHash);
result.insert(r.begin(), r.end());
// there can be no two members with the same proTxHash, so return early
break;
}
}
return result;
}
std::set<size_t> CLLMQUtils::CalcDeterministicWatchConnections(Consensus::LLMQType llmqType, const CBlockIndex* pindexQuorum, size_t memberCount, size_t connectionCount)
{
static uint256 qwatchConnectionSeed;
static std::atomic<bool> qwatchConnectionSeedGenerated{false};
static CCriticalSection qwatchConnectionSeedCs;
if (!qwatchConnectionSeedGenerated) {
LOCK(qwatchConnectionSeedCs);
if (!qwatchConnectionSeedGenerated) {
qwatchConnectionSeed = GetRandHash();
qwatchConnectionSeedGenerated = true;
}
}
std::set<size_t> result;
uint256 rnd = qwatchConnectionSeed;
for (size_t i = 0; i < connectionCount; i++) {
rnd = ::SerializeHash(std::make_pair(rnd, std::make_pair(llmqType, pindexQuorum->GetBlockHash())));
result.emplace(rnd.GetUint64(0) % memberCount);
}
return result;
}
void CLLMQUtils::EnsureQuorumConnections(Consensus::LLMQType llmqType, const CBlockIndex *pindexQuorum, const uint256& myProTxHash, bool allowWatch)
{
auto members = GetAllQuorumMembers(llmqType, pindexQuorum);
bool isMember = std::find_if(members.begin(), members.end(), [&](const CDeterministicMNCPtr& dmn) { return dmn->proTxHash == myProTxHash; }) != members.end();
if (!isMember && !allowWatch) {
return;
}
std::set<uint256> connections;
if (isMember) {
connections = CLLMQUtils::GetQuorumConnections(llmqType, pindexQuorum, myProTxHash, true);
} else {
auto cindexes = CLLMQUtils::CalcDeterministicWatchConnections(llmqType, pindexQuorum, members.size(), 1);
for (auto idx : cindexes) {
connections.emplace(members[idx]->proTxHash);
}
}
if (!connections.empty()) {
if (!g_connman->HasMasternodeQuorumNodes(llmqType, pindexQuorum->GetBlockHash()) && LogAcceptCategory(BCLog::LLMQ)) {
auto mnList = deterministicMNManager->GetListAtChainTip();
std::string debugMsg = strprintf("CLLMQUtils::%s -- adding masternodes quorum connections for quorum %s:\n", __func__, pindexQuorum->GetBlockHash().ToString());
for (auto& c : connections) {
auto dmn = mnList.GetValidMN(c);
if (!dmn) {
debugMsg += strprintf(" %s (not in valid MN set anymore)\n", c.ToString());
} else {
debugMsg += strprintf(" %s (%s)\n", c.ToString(), dmn->pdmnState->addr.ToString(false));
}
}
LogPrint(BCLog::LLMQ, debugMsg.c_str());
}
g_connman->SetMasternodeQuorumNodes(llmqType, pindexQuorum->GetBlockHash(), connections);
}
}
void CLLMQUtils::AddQuorumProbeConnections(Consensus::LLMQType llmqType, const CBlockIndex *pindexQuorum, const uint256 &myProTxHash)
{
auto members = GetAllQuorumMembers(llmqType, pindexQuorum);
auto curTime = GetAdjustedTime();
std::set<uint256> probeConnections;
for (auto& dmn : members) {
if (dmn->proTxHash == myProTxHash) {
continue;
}
auto lastOutbound = mmetaman.GetMetaInfo(dmn->proTxHash)->GetLastOutboundSuccess();
// re-probe after 50 minutes so that the "good connection" check in the DKG doesn't fail just because we're on
// the brink of timeout
if (curTime - lastOutbound > 50 * 60) {
probeConnections.emplace(dmn->proTxHash);
}
}
if (!probeConnections.empty()) {
if (LogAcceptCategory(BCLog::LLMQ)) {
auto mnList = deterministicMNManager->GetListAtChainTip();
std::string debugMsg = strprintf("CLLMQUtils::%s -- adding masternodes probes for quorum %s:\n", __func__, pindexQuorum->GetBlockHash().ToString());
for (auto& c : probeConnections) {
auto dmn = mnList.GetValidMN(c);
if (!dmn) {
debugMsg += strprintf(" %s (not in valid MN set anymore)\n", c.ToString());
} else {
debugMsg += strprintf(" %s (%s)\n", c.ToString(), dmn->pdmnState->addr.ToString(false));
}
}
LogPrint(BCLog::LLMQ, debugMsg.c_str());
}
g_connman->AddPendingProbeConnections(probeConnections);
}
}
bool CLLMQUtils::IsQuorumActive(Consensus::LLMQType llmqType, const uint256& quorumHash)
{
auto& params = Params().GetConsensus().llmqs.at(llmqType);
// sig shares and recovered sigs are only accepted from recent/active quorums
// we allow one more active quorum as specified in consensus, as otherwise there is a small window where things could
// fail while we are on the brink of a new quorum
auto quorums = quorumManager->ScanQuorums(llmqType, (int)params.signingActiveQuorumCount + 1);
for (auto& q : quorums) {
if (q->qc.quorumHash == quorumHash) {
return true;
}
}
return false;
}
} // namespace llmq
<commit_msg>Fix onlyOutbound handling<commit_after>// Copyright (c) 2018-2019 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <llmq/quorums.h>
#include <llmq/quorums_utils.h>
#include <chainparams.h>
#include <random.h>
#include <spork.h>
#include <validation.h>
#include <masternode/masternode-meta.h>
namespace llmq
{
std::vector<CDeterministicMNCPtr> CLLMQUtils::GetAllQuorumMembers(Consensus::LLMQType llmqType, const CBlockIndex* pindexQuorum)
{
auto& params = Params().GetConsensus().llmqs.at(llmqType);
auto allMns = deterministicMNManager->GetListForBlock(pindexQuorum);
auto modifier = ::SerializeHash(std::make_pair(llmqType, pindexQuorum->GetBlockHash()));
return allMns.CalculateQuorum(params.size, modifier);
}
uint256 CLLMQUtils::BuildCommitmentHash(Consensus::LLMQType llmqType, const uint256& blockHash, const std::vector<bool>& validMembers, const CBLSPublicKey& pubKey, const uint256& vvecHash)
{
CHashWriter hw(SER_NETWORK, 0);
hw << llmqType;
hw << blockHash;
hw << DYNBITSET(validMembers);
hw << pubKey;
hw << vvecHash;
return hw.GetHash();
}
uint256 CLLMQUtils::BuildSignHash(Consensus::LLMQType llmqType, const uint256& quorumHash, const uint256& id, const uint256& msgHash)
{
CHashWriter h(SER_GETHASH, 0);
h << llmqType;
h << quorumHash;
h << id;
h << msgHash;
return h.GetHash();
}
std::set<uint256> CLLMQUtils::GetQuorumConnections(Consensus::LLMQType llmqType, const CBlockIndex* pindexQuorum, const uint256& forMember, bool onlyOutbound)
{
auto& params = Params().GetConsensus().llmqs.at(llmqType);
auto mns = GetAllQuorumMembers(llmqType, pindexQuorum);
std::set<uint256> result;
if (sporkManager.IsSporkActive(SPORK_21_QUORUM_ALL_CONNECTED)) {
for (auto& dmn : mns) {
// this will cause deterministic behaviour between incoming and outgoing connections.
// Each member needs a connection to all other members, so we have each member paired. The below check
// will be true on one side and false on the other side of the pairing, so we avoid having both members
// initiating the connection.
if (!onlyOutbound || dmn->proTxHash < forMember) {
result.emplace(dmn->proTxHash);
}
}
return result;
}
// TODO remove this after activation of SPORK_21_QUORUM_ALL_CONNECTED
auto calcOutbound = [&](size_t i, const uint256 proTxHash) {
// Connect to nodes at indexes (i+2^k)%n, where
// k: 0..max(1, floor(log2(n-1))-1)
// n: size of the quorum/ring
std::set<uint256> r;
int gap = 1;
int gap_max = (int)mns.size() - 1;
int k = 0;
while ((gap_max >>= 1) || k <= 1) {
size_t idx = (i + gap) % mns.size();
auto& otherDmn = mns[idx];
if (otherDmn->proTxHash == proTxHash) {
continue;
}
r.emplace(otherDmn->proTxHash);
gap <<= 1;
k++;
}
return r;
};
for (size_t i = 0; i < mns.size(); i++) {
auto& dmn = mns[i];
if (dmn->proTxHash == forMember) {
auto r = calcOutbound(i, dmn->proTxHash);
result.insert(r.begin(), r.end());
} else if (!onlyOutbound) {
auto r = calcOutbound(i, dmn->proTxHash);
if (r.count(forMember)) {
result.emplace(dmn->proTxHash);
}
}
}
return result;
}
std::set<size_t> CLLMQUtils::CalcDeterministicWatchConnections(Consensus::LLMQType llmqType, const CBlockIndex* pindexQuorum, size_t memberCount, size_t connectionCount)
{
static uint256 qwatchConnectionSeed;
static std::atomic<bool> qwatchConnectionSeedGenerated{false};
static CCriticalSection qwatchConnectionSeedCs;
if (!qwatchConnectionSeedGenerated) {
LOCK(qwatchConnectionSeedCs);
if (!qwatchConnectionSeedGenerated) {
qwatchConnectionSeed = GetRandHash();
qwatchConnectionSeedGenerated = true;
}
}
std::set<size_t> result;
uint256 rnd = qwatchConnectionSeed;
for (size_t i = 0; i < connectionCount; i++) {
rnd = ::SerializeHash(std::make_pair(rnd, std::make_pair(llmqType, pindexQuorum->GetBlockHash())));
result.emplace(rnd.GetUint64(0) % memberCount);
}
return result;
}
void CLLMQUtils::EnsureQuorumConnections(Consensus::LLMQType llmqType, const CBlockIndex *pindexQuorum, const uint256& myProTxHash, bool allowWatch)
{
auto members = GetAllQuorumMembers(llmqType, pindexQuorum);
bool isMember = std::find_if(members.begin(), members.end(), [&](const CDeterministicMNCPtr& dmn) { return dmn->proTxHash == myProTxHash; }) != members.end();
if (!isMember && !allowWatch) {
return;
}
std::set<uint256> connections;
if (isMember) {
connections = CLLMQUtils::GetQuorumConnections(llmqType, pindexQuorum, myProTxHash, true);
} else {
auto cindexes = CLLMQUtils::CalcDeterministicWatchConnections(llmqType, pindexQuorum, members.size(), 1);
for (auto idx : cindexes) {
connections.emplace(members[idx]->proTxHash);
}
}
if (!connections.empty()) {
if (!g_connman->HasMasternodeQuorumNodes(llmqType, pindexQuorum->GetBlockHash()) && LogAcceptCategory(BCLog::LLMQ)) {
auto mnList = deterministicMNManager->GetListAtChainTip();
std::string debugMsg = strprintf("CLLMQUtils::%s -- adding masternodes quorum connections for quorum %s:\n", __func__, pindexQuorum->GetBlockHash().ToString());
for (auto& c : connections) {
auto dmn = mnList.GetValidMN(c);
if (!dmn) {
debugMsg += strprintf(" %s (not in valid MN set anymore)\n", c.ToString());
} else {
debugMsg += strprintf(" %s (%s)\n", c.ToString(), dmn->pdmnState->addr.ToString(false));
}
}
LogPrint(BCLog::LLMQ, debugMsg.c_str());
}
g_connman->SetMasternodeQuorumNodes(llmqType, pindexQuorum->GetBlockHash(), connections);
}
}
void CLLMQUtils::AddQuorumProbeConnections(Consensus::LLMQType llmqType, const CBlockIndex *pindexQuorum, const uint256 &myProTxHash)
{
auto members = GetAllQuorumMembers(llmqType, pindexQuorum);
auto curTime = GetAdjustedTime();
std::set<uint256> probeConnections;
for (auto& dmn : members) {
if (dmn->proTxHash == myProTxHash) {
continue;
}
auto lastOutbound = mmetaman.GetMetaInfo(dmn->proTxHash)->GetLastOutboundSuccess();
// re-probe after 50 minutes so that the "good connection" check in the DKG doesn't fail just because we're on
// the brink of timeout
if (curTime - lastOutbound > 50 * 60) {
probeConnections.emplace(dmn->proTxHash);
}
}
if (!probeConnections.empty()) {
if (LogAcceptCategory(BCLog::LLMQ)) {
auto mnList = deterministicMNManager->GetListAtChainTip();
std::string debugMsg = strprintf("CLLMQUtils::%s -- adding masternodes probes for quorum %s:\n", __func__, pindexQuorum->GetBlockHash().ToString());
for (auto& c : probeConnections) {
auto dmn = mnList.GetValidMN(c);
if (!dmn) {
debugMsg += strprintf(" %s (not in valid MN set anymore)\n", c.ToString());
} else {
debugMsg += strprintf(" %s (%s)\n", c.ToString(), dmn->pdmnState->addr.ToString(false));
}
}
LogPrint(BCLog::LLMQ, debugMsg.c_str());
}
g_connman->AddPendingProbeConnections(probeConnections);
}
}
bool CLLMQUtils::IsQuorumActive(Consensus::LLMQType llmqType, const uint256& quorumHash)
{
auto& params = Params().GetConsensus().llmqs.at(llmqType);
// sig shares and recovered sigs are only accepted from recent/active quorums
// we allow one more active quorum as specified in consensus, as otherwise there is a small window where things could
// fail while we are on the brink of a new quorum
auto quorums = quorumManager->ScanQuorums(llmqType, (int)params.signingActiveQuorumCount + 1);
for (auto& q : quorums) {
if (q->qc.quorumHash == quorumHash) {
return true;
}
}
return false;
}
} // namespace llmq
<|endoftext|> |
<commit_before>// type_promotion.hpp
//
// Copyright (c) 2016 Piotr K. Semenov (piotr.k.semenov at gmail dot com)
// Distributed under the New BSD License. (See accompanying file LICENSE)
/*!
\file type_promotion.hpp
Provides the run-time overflow/underflow safety checks for basic arithmetics operations.
*/
#ifndef INC_LIBQ_TYPE_PROMOTION_HPP_
#define INC_LIBQ_TYPE_PROMOTION_HPP_
#include <boost/integer.hpp>
#include <boost/mpl/eval_if.hpp>
#include <limits>
#include <type_traits>
namespace libq {
namespace details {
/*!
\brief
\tparam T fixed-point type
\tparam delta_n
\tparam delta_f
*/
template<typename T, std::size_t delta_n, std::size_t delta_f, int delte_e>
class type_promotion_base {
public:
using promoted_type = T;
};
template<typename T,
std::size_t n,
std::size_t f,
int e,
class op,
class up,
std::size_t delta_n,
std::size_t delta_f,
int delta_e>
class type_promotion_base<libq::fixed_point<T, n, f, e, op, up>,
delta_n,
delta_f,
delta_e> {
using Q = libq::fixed_point<T, n, f, e, op, up>;
using this_class = type_promotion_base<Q, delta_n, delta_f, delta_e>;
using max_type = typename std::conditional<Q::is_signed,
std::intmax_t,
std::uintmax_t>::type;
enum: std::size_t {
sign_bit = static_cast<std::size_t>(Q::is_signed),
n = Q::bits_for_integral,
f = Q::bits_for_fractional
};
enum: int {
e = Q::scaling_factor_exponent
};
// simple "type" wrapper for lazy instantiation of its "internal" type
struct storage_type_promotion_traits {
// Note, boost::int_t takes a sign bit into account
using type = typename std::conditional<Q::is_signed,
typename boost::int_t<(n + delta_n) + (f + delta_f) + this_class::sign_bit>::least, // NOLINT
typename boost::uint_t<(n + delta_n) + (f + delta_f)>::least>::type; // NOLINT
};
struct storage_type_default_traits {
using type = typename Q::storage_type;
};
public:
enum: bool {
is_expandable = ((n + delta_n) + (f + delta_f) <=
std::numeric_limits<max_type>::digits)
};
/*!
\brief
*/
using promoted_storage_type =
typename boost::mpl::eval_if_c<this_class::is_expandable,
typename this_class::storage_type_promotion_traits, // NOLINT
typename this_class::storage_type_default_traits>::type; // NOLINT
using promoted_type = typename std::conditional<this_class::is_expandable,
libq::fixed_point<promoted_storage_type, n + delta_n, f + delta_f, e + delta_e, typename Q::overflow_policy, typename Q::underflow_policy>, // NOLINT
libq::fixed_point<promoted_storage_type, n, f, e, typename Q::overflow_policy, typename Q::underflow_policy> >::type; // NOLINT
};
} // namespace details
} // namespace libq
#endif // INC_LIBQ_TYPE_PROMOTION_HPP_
<commit_msg>[FIX] No cpplint errors more for type_promotion.hpp<commit_after>// type_promotion.hpp
//
// Copyright (c) 2016 Piotr K. Semenov (piotr.k.semenov at gmail dot com)
// Distributed under the New BSD License. (See accompanying file LICENSE)
/*!
\file type_promotion.hpp
Provides the run-time overflow/underflow safety checks for basic arithmetics operations.
*/
#ifndef INC_LIBQ_TYPE_PROMOTION_HPP_
#define INC_LIBQ_TYPE_PROMOTION_HPP_
#include <boost/integer.hpp>
#include <boost/mpl/eval_if.hpp>
#include <limits>
#include <type_traits>
namespace libq {
namespace details {
/*!
\brief
\tparam T fixed-point type
\tparam delta_n
\tparam delta_f
*/
template<typename T, std::size_t delta_n, std::size_t delta_f, int delte_e>
class type_promotion_base {
public:
using promoted_type = T;
};
template<typename T, std::size_t n, std::size_t f, int e, class op, class up, std::size_t delta_n, std::size_t delta_f, int delta_e> // NOLINT
class type_promotion_base<libq::fixed_point<T, n, f, e, op, up>, delta_n, delta_f, delta_e> { // NOLINT
using Q = libq::fixed_point<T, n, f, e, op, up>;
using this_class = type_promotion_base<Q, delta_n, delta_f, delta_e>;
using max_type = typename std::conditional<Q::is_signed,
std::intmax_t,
std::uintmax_t>::type;
enum: std::size_t {
sign_bit = static_cast<std::size_t>(Q::is_signed),
n = Q::bits_for_integral,
f = Q::bits_for_fractional
};
enum: int {
e = Q::scaling_factor_exponent
};
// simple "type" wrapper for lazy instantiation of its "internal" type
struct storage_type_promotion_traits {
// Note, boost::int_t takes a sign bit into account
using type = typename std::conditional<Q::is_signed,
typename boost::int_t<(n + delta_n) + (f + delta_f) + this_class::sign_bit>::least, // NOLINT
typename boost::uint_t<(n + delta_n) + (f + delta_f)>::least>::type; // NOLINT
};
struct storage_type_default_traits {
using type = typename Q::storage_type;
};
public:
enum: bool {
is_expandable = ((n + delta_n) + (f + delta_f) <=
std::numeric_limits<max_type>::digits)
};
/*!
\brief
*/
using promoted_storage_type =
typename boost::mpl::eval_if_c<this_class::is_expandable,
typename this_class::storage_type_promotion_traits, // NOLINT
typename this_class::storage_type_default_traits>::type; // NOLINT
using promoted_type = typename std::conditional<this_class::is_expandable,
libq::fixed_point<promoted_storage_type, n + delta_n, f + delta_f, e + delta_e, typename Q::overflow_policy, typename Q::underflow_policy>, // NOLINT
libq::fixed_point<promoted_storage_type, n, f, e, typename Q::overflow_policy, typename Q::underflow_policy> >::type; // NOLINT
};
} // namespace details
} // namespace libq
#endif // INC_LIBQ_TYPE_PROMOTION_HPP_
<|endoftext|> |
<commit_before>//===========================================
// Lumina-DE source code
// Copyright (c) 2017-2018, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "NativeWindowObject.h"
#include <QQmlEngine>
#include <QDebug>
#include <QBuffer>
// == QML Type Registration ==
void NativeWindowObject::RegisterType(){
static bool done = false;
if(done){ return; }
done=true;
qmlRegisterType<NativeWindowObject>("Lumina.Backend.NativeWindowObject",2,0, "NativeWindowObject");
}
// === PUBLIC ===
NativeWindowObject::NativeWindowObject(WId id) : QObject(){
winid = id;
frameid = 0;
dmgID = 0;
}
NativeWindowObject::~NativeWindowObject(){
hash.clear();
}
void NativeWindowObject::addFrameWinID(WId fid){
frameid = fid;
}
void NativeWindowObject::addDamageID(unsigned int dmg){
dmgID = dmg;
}
bool NativeWindowObject::isRelatedTo(WId tmp){
return (relatedTo.contains(tmp) || winid == tmp || frameid == tmp);
}
WId NativeWindowObject::id(){
return winid;
}
WId NativeWindowObject::frameId(){
return frameid;
}
unsigned int NativeWindowObject::damageId(){
return dmgID;
}
QVariant NativeWindowObject::property(NativeWindowObject::Property prop){
if(hash.contains(prop)){ return hash.value(prop); }
else if(prop == NativeWindowObject::RelatedWindows){ return QVariant::fromValue(relatedTo); }
return QVariant(); //null variant
}
void NativeWindowObject::setProperty(NativeWindowObject::Property prop, QVariant val, bool force){
if(prop == NativeWindowObject::RelatedWindows){ relatedTo = val.value< QList<WId> >(); }
else if(prop == NativeWindowObject::None || (!force && hash.value(prop)==val)){ return; }
else if(prop == NativeWindowObject::WinImage){
//special case - QImage is passed in, but QString is passed out (needed for QML)
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
val.value<QImage>().save(&buffer, "PNG");
QString img("data:image/png:base64,");
img.append(QString::fromLatin1(ba.toBase64().data()));
hash.insert(prop, img); //save the string instead
}
else{ hash.insert(prop, val); }
emitSinglePropChanged(prop);
emit PropertiesChanged(QList<NativeWindowObject::Property>() << prop, QList<QVariant>() << val);
}
void NativeWindowObject::setProperties(QList<NativeWindowObject::Property> props, QList<QVariant> vals, bool force){
for(int i=0; i<props.length(); i++){
if(i>=vals.length()){ props.removeAt(i); i--; continue; } //no corresponding value for this property
if(props[i] == NativeWindowObject::None || (!force && (hash.value(props[i]) == vals[i])) ){
props.removeAt(i); vals.removeAt(i); i--; continue; //Invalid property or identical value
}else if(props[i] == NativeWindowObject::WinImage){
//special case - QImage is passed in, but QString is passed out (needed for QML)
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
vals[i].value<QImage>().save(&buffer, "PNG");
QString img("data:image/png:base64,");
img.append(QString::fromLatin1(ba.toBase64().data()));
hash.insert(props[i], img); //save the string instead
}else{
hash.insert(props[i], vals[i]);
}
emitSinglePropChanged(props[i]);
}
emit PropertiesChanged(props, vals);
}
void NativeWindowObject::requestProperty(NativeWindowObject::Property prop, QVariant val, bool force){
if(prop == NativeWindowObject::None || prop == NativeWindowObject::RelatedWindows || (!force && hash.value(prop)==val) ){ return; }
emit RequestPropertiesChange(winid, QList<NativeWindowObject::Property>() << prop, QList<QVariant>() << val);
}
void NativeWindowObject::requestProperties(QList<NativeWindowObject::Property> props, QList<QVariant> vals, bool force){
//Verify/adjust inputs as needed
for(int i=0; i<props.length(); i++){
if(i>=vals.length()){ props.removeAt(i); i--; continue; } //no corresponding value for this property
if(props[i] == NativeWindowObject::None || props[i] == NativeWindowObject::RelatedWindows || (!force && hash.value(props[i])==vals[i]) ){ props.removeAt(i); vals.removeAt(i); i--; continue; } //Invalid property or identical value
/*if( (props[i] == NativeWindowObject::Visible || props[i] == NativeWindowObject::Active) && frameid !=0){
//These particular properties needs to change the frame - not the window itself
emit RequestPropertiesChange(frameid, QList<NativeWindowObject::Property>() << props[i], QList<QVariant>() << vals[i]);
props.removeAt(i); vals.removeAt(i); i--;
}*/
}
emit RequestPropertiesChange(winid, props, vals);
}
QRect NativeWindowObject::geometry(){
//Calculate the "full" geometry of the window + frame (if any)
//Check that the size is between the min/max limitations
QSize size = hash.value(NativeWindowObject::Size).toSize();
QSize min = hash.value(NativeWindowObject::MinSize).toSize();
QSize max = hash.value(NativeWindowObject::MaxSize).toSize();
if(min.isValid() && min.width() > size.width() ){ size.setWidth(min.width()); }
if(min.isValid() && min.height() > size.height()){ size.setHeight(min.height()); }
if(max.isValid() && max.width() < size.width() && max.width()>min.width()){ size.setWidth(max.width()); }
if(max.isValid() && max.height() < size.height() && max.height()>min.height()){ size.setHeight(max.height()); }
//Assemble the full geometry
QRect geom( hash.value(NativeWindowObject::GlobalPos).toPoint(), size );
//Now adjust the window geom by the frame margins
QList<int> frame = hash.value(NativeWindowObject::FrameExtents).value< QList<int> >(); //Left,Right,Top,Bottom
//qDebug() << "Calculate Geometry:" << geom << frame;
if(frame.length()==4){
geom = geom.adjusted( -frame[0], -frame[2], frame[1], frame[3] );
}
//qDebug() << " - Total:" << geom;
return geom;
}
// QML ACCESS FUNCTIONS (shortcuts for particular properties in a format QML can use)
QString NativeWindowObject::winImage(){
return this->property(NativeWindowObject::WinImage).toString();
}
QString NativeWindowObject::name(){
return this->property(NativeWindowObject::Name).toString();
}
QString NativeWindowObject::title(){
return this->property(NativeWindowObject::Title).toString();
}
QString NativeWindowObject::shortTitle(){
QString tmp = this->property(NativeWindowObject::ShortTitle).toString();
if(tmp.isEmpty()){ tmp = title(); }
if(tmp.isEmpty()){ tmp = name(); }
return tmp;
}
QIcon NativeWindowObject::icon(){
return this->property(NativeWindowObject::Name).value<QIcon>();
}
//QML Button states
bool NativeWindowObject::showCloseButton(){
QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
QList<NativeWindowObject::Type> badtypes;
badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
for(int i=0; i<types.length(); i++){
if(badtypes.contains(types[i])){ return false; }
}
return true;
}
bool NativeWindowObject::showMaxButton(){
QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
QList<NativeWindowObject::Type> badtypes;
badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
for(int i=0; i<types.length(); i++){
if(badtypes.contains(types[i])){ return false; }
}
return true;
}
bool NativeWindowObject::showMinButton(){
QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
QList<NativeWindowObject::Type> badtypes;
badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND << NativeWindowObject::T_DIALOG;
for(int i=0; i<types.length(); i++){
if(badtypes.contains(types[i])){ return false; }
}
return true;
}
bool NativeWindowObject::showTitlebar(){
QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
QList<NativeWindowObject::Type> badtypes;
badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
for(int i=0; i<types.length(); i++){
if(badtypes.contains(types[i])){ return false; }
}
return true;
}
bool NativeWindowObject::showGenericButton(){
QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
QList<NativeWindowObject::Type> badtypes;
badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
for(int i=0; i<types.length(); i++){
if(badtypes.contains(types[i])){ return false; }
}
return true;
}
bool NativeWindowObject::showWindowFrame(){
QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
QList<NativeWindowObject::Type> badtypes;
badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
for(int i=0; i<types.length(); i++){
if(badtypes.contains(types[i])){ return false; }
}
return true;
}
//QML Window States
bool NativeWindowObject::isSticky(){
return (this->property(NativeWindowObject::Workspace).toInt()<0 || this->property(NativeWindowObject::States).value<QList<NativeWindowObject::State> >().contains(NativeWindowObject::S_STICKY) );
}
int NativeWindowObject::workspace(){
return this->property(NativeWindowObject::Workspace).toInt();
}
//QML Geometry reporting
QRect NativeWindowObject::frameGeometry(){
return geometry();
}
QRect NativeWindowObject::imageGeometry(){
QRect geom( this->property(NativeWindowObject::GlobalPos).toPoint(), this->property(NativeWindowObject::Size).toSize() );
return geom;
}
// ==== PUBLIC SLOTS ===
void NativeWindowObject::toggleVisibility(){
setProperty(NativeWindowObject::Visible, !property(NativeWindowObject::Visible).toBool() );
}
void NativeWindowObject::requestClose(){
emit RequestClose(winid);
}
void NativeWindowObject::requestKill(){
emit RequestKill(winid);
}
void NativeWindowObject::requestPing(){
emit RequestPing(winid);
}
// ==== PRIVATE ====
void NativeWindowObject::emitSinglePropChanged(NativeWindowObject::Property prop){
//Simple switch to emit the QML-usable signals as properties are changed
switch(prop){
case NativeWindowObject::Name:
emit nameChanged(); break;
case NativeWindowObject::Title:
emit titleChanged(); break;
case NativeWindowObject::ShortTitle:
emit shortTitleChanged(); break;
case NativeWindowObject::Icon:
emit iconChanged(); break;
case NativeWindowObject::Workspace:
case NativeWindowObject::States:
emit stickyChanged(); break;
case NativeWindowObject::WinImage:
emit winImageChanged(); break;
case NativeWindowObject::WinTypes:
emit winTypeChanged(); break;
default:
break; //do nothing otherwise
}
}
<commit_msg>Get the QML reading the raw QImage data using the HTML data format (base64). This results in a usable image, but it flickers quite badly when the image changes. Might need to look into a QImageProvider that allows QML to read/use the raw image data rather than base64 as the transport medium.<commit_after>//===========================================
// Lumina-DE source code
// Copyright (c) 2017-2018, Ken Moore
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "NativeWindowObject.h"
#include <QQmlEngine>
#include <QDebug>
#include <QBuffer>
// == QML Type Registration ==
void NativeWindowObject::RegisterType(){
static bool done = false;
if(done){ return; }
done=true;
qmlRegisterType<NativeWindowObject>("Lumina.Backend.NativeWindowObject",2,0, "NativeWindowObject");
}
// === PUBLIC ===
NativeWindowObject::NativeWindowObject(WId id) : QObject(){
winid = id;
frameid = 0;
dmgID = 0;
}
NativeWindowObject::~NativeWindowObject(){
hash.clear();
}
void NativeWindowObject::addFrameWinID(WId fid){
frameid = fid;
}
void NativeWindowObject::addDamageID(unsigned int dmg){
dmgID = dmg;
}
bool NativeWindowObject::isRelatedTo(WId tmp){
return (relatedTo.contains(tmp) || winid == tmp || frameid == tmp);
}
WId NativeWindowObject::id(){
return winid;
}
WId NativeWindowObject::frameId(){
return frameid;
}
unsigned int NativeWindowObject::damageId(){
return dmgID;
}
QVariant NativeWindowObject::property(NativeWindowObject::Property prop){
if(hash.contains(prop)){ return hash.value(prop); }
else if(prop == NativeWindowObject::RelatedWindows){ return QVariant::fromValue(relatedTo); }
return QVariant(); //null variant
}
void NativeWindowObject::setProperty(NativeWindowObject::Property prop, QVariant val, bool force){
if(prop == NativeWindowObject::RelatedWindows){ relatedTo = val.value< QList<WId> >(); }
else if(prop == NativeWindowObject::None || (!force && hash.value(prop)==val)){ return; }
else if(prop == NativeWindowObject::WinImage){
//special case - QImage is passed in, but QString is passed out (needed for QML)
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
val.value<QImage>().save(&buffer, "PNG");
QString img("data:image/png;base64,");
img.append(QString::fromLatin1(ba.toBase64().data()));
qDebug() << "Image Data Header:" << img.section(",",0,0);
hash.insert(prop, img); //save the string instead
}
else{ hash.insert(prop, val); }
emitSinglePropChanged(prop);
emit PropertiesChanged(QList<NativeWindowObject::Property>() << prop, QList<QVariant>() << val);
}
void NativeWindowObject::setProperties(QList<NativeWindowObject::Property> props, QList<QVariant> vals, bool force){
for(int i=0; i<props.length(); i++){
if(i>=vals.length()){ props.removeAt(i); i--; continue; } //no corresponding value for this property
if(props[i] == NativeWindowObject::None || (!force && (hash.value(props[i]) == vals[i])) ){
props.removeAt(i); vals.removeAt(i); i--; continue; //Invalid property or identical value
}else if(props[i] == NativeWindowObject::WinImage){
//special case - QImage is passed in, but QString is passed out (needed for QML)
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
vals[i].value<QImage>().save(&buffer, "PNG");
QString img("data:image/png;base64,");
img.append(QString::fromLatin1(ba.toBase64().data()));
qDebug() << "Image Data Header:" << img.section(",",0,0);
hash.insert(props[i], img); //save the string instead
}else{
hash.insert(props[i], vals[i]);
}
emitSinglePropChanged(props[i]);
}
emit PropertiesChanged(props, vals);
}
void NativeWindowObject::requestProperty(NativeWindowObject::Property prop, QVariant val, bool force){
if(prop == NativeWindowObject::None || prop == NativeWindowObject::RelatedWindows || (!force && hash.value(prop)==val) ){ return; }
emit RequestPropertiesChange(winid, QList<NativeWindowObject::Property>() << prop, QList<QVariant>() << val);
}
void NativeWindowObject::requestProperties(QList<NativeWindowObject::Property> props, QList<QVariant> vals, bool force){
//Verify/adjust inputs as needed
for(int i=0; i<props.length(); i++){
if(i>=vals.length()){ props.removeAt(i); i--; continue; } //no corresponding value for this property
if(props[i] == NativeWindowObject::None || props[i] == NativeWindowObject::RelatedWindows || (!force && hash.value(props[i])==vals[i]) ){ props.removeAt(i); vals.removeAt(i); i--; continue; } //Invalid property or identical value
/*if( (props[i] == NativeWindowObject::Visible || props[i] == NativeWindowObject::Active) && frameid !=0){
//These particular properties needs to change the frame - not the window itself
emit RequestPropertiesChange(frameid, QList<NativeWindowObject::Property>() << props[i], QList<QVariant>() << vals[i]);
props.removeAt(i); vals.removeAt(i); i--;
}*/
}
emit RequestPropertiesChange(winid, props, vals);
}
QRect NativeWindowObject::geometry(){
//Calculate the "full" geometry of the window + frame (if any)
//Check that the size is between the min/max limitations
QSize size = hash.value(NativeWindowObject::Size).toSize();
QSize min = hash.value(NativeWindowObject::MinSize).toSize();
QSize max = hash.value(NativeWindowObject::MaxSize).toSize();
if(min.isValid() && min.width() > size.width() ){ size.setWidth(min.width()); }
if(min.isValid() && min.height() > size.height()){ size.setHeight(min.height()); }
if(max.isValid() && max.width() < size.width() && max.width()>min.width()){ size.setWidth(max.width()); }
if(max.isValid() && max.height() < size.height() && max.height()>min.height()){ size.setHeight(max.height()); }
//Assemble the full geometry
QRect geom( hash.value(NativeWindowObject::GlobalPos).toPoint(), size );
//Now adjust the window geom by the frame margins
QList<int> frame = hash.value(NativeWindowObject::FrameExtents).value< QList<int> >(); //Left,Right,Top,Bottom
//qDebug() << "Calculate Geometry:" << geom << frame;
if(frame.length()==4){
geom = geom.adjusted( -frame[0], -frame[2], frame[1], frame[3] );
}
//qDebug() << " - Total:" << geom;
return geom;
}
// QML ACCESS FUNCTIONS (shortcuts for particular properties in a format QML can use)
QString NativeWindowObject::winImage(){
return this->property(NativeWindowObject::WinImage).toString();
}
QString NativeWindowObject::name(){
return this->property(NativeWindowObject::Name).toString();
}
QString NativeWindowObject::title(){
return this->property(NativeWindowObject::Title).toString();
}
QString NativeWindowObject::shortTitle(){
QString tmp = this->property(NativeWindowObject::ShortTitle).toString();
if(tmp.isEmpty()){ tmp = title(); }
if(tmp.isEmpty()){ tmp = name(); }
return tmp;
}
QIcon NativeWindowObject::icon(){
return this->property(NativeWindowObject::Name).value<QIcon>();
}
//QML Button states
bool NativeWindowObject::showCloseButton(){
QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
QList<NativeWindowObject::Type> badtypes;
badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
for(int i=0; i<types.length(); i++){
if(badtypes.contains(types[i])){ return false; }
}
return true;
}
bool NativeWindowObject::showMaxButton(){
QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
QList<NativeWindowObject::Type> badtypes;
badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
for(int i=0; i<types.length(); i++){
if(badtypes.contains(types[i])){ return false; }
}
return true;
}
bool NativeWindowObject::showMinButton(){
QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
QList<NativeWindowObject::Type> badtypes;
badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND << NativeWindowObject::T_DIALOG;
for(int i=0; i<types.length(); i++){
if(badtypes.contains(types[i])){ return false; }
}
return true;
}
bool NativeWindowObject::showTitlebar(){
QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
QList<NativeWindowObject::Type> badtypes;
badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
for(int i=0; i<types.length(); i++){
if(badtypes.contains(types[i])){ return false; }
}
return true;
}
bool NativeWindowObject::showGenericButton(){
QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
QList<NativeWindowObject::Type> badtypes;
badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
for(int i=0; i<types.length(); i++){
if(badtypes.contains(types[i])){ return false; }
}
return true;
}
bool NativeWindowObject::showWindowFrame(){
QList<NativeWindowObject::Type> types = this->property(NativeWindowObject::WinTypes).value<QList < NativeWindowObject::Type> >();
QList<NativeWindowObject::Type> badtypes;
badtypes << NativeWindowObject::T_DESKTOP << NativeWindowObject::T_TOOLBAR << NativeWindowObject::T_MENU \
<< NativeWindowObject::T_SPLASH << NativeWindowObject::T_DROPDOWN_MENU << NativeWindowObject::T_POPUP_MENU \
<< NativeWindowObject::T_NOTIFICATION << NativeWindowObject::T_COMBO << NativeWindowObject::T_DND;
for(int i=0; i<types.length(); i++){
if(badtypes.contains(types[i])){ return false; }
}
return true;
}
//QML Window States
bool NativeWindowObject::isSticky(){
return (this->property(NativeWindowObject::Workspace).toInt()<0 || this->property(NativeWindowObject::States).value<QList<NativeWindowObject::State> >().contains(NativeWindowObject::S_STICKY) );
}
int NativeWindowObject::workspace(){
return this->property(NativeWindowObject::Workspace).toInt();
}
//QML Geometry reporting
QRect NativeWindowObject::frameGeometry(){
return geometry();
}
QRect NativeWindowObject::imageGeometry(){
QRect geom( this->property(NativeWindowObject::GlobalPos).toPoint(), this->property(NativeWindowObject::Size).toSize() );
return geom;
}
// ==== PUBLIC SLOTS ===
void NativeWindowObject::toggleVisibility(){
setProperty(NativeWindowObject::Visible, !property(NativeWindowObject::Visible).toBool() );
}
void NativeWindowObject::requestClose(){
emit RequestClose(winid);
}
void NativeWindowObject::requestKill(){
emit RequestKill(winid);
}
void NativeWindowObject::requestPing(){
emit RequestPing(winid);
}
// ==== PRIVATE ====
void NativeWindowObject::emitSinglePropChanged(NativeWindowObject::Property prop){
//Simple switch to emit the QML-usable signals as properties are changed
switch(prop){
case NativeWindowObject::Name:
emit nameChanged(); break;
case NativeWindowObject::Title:
emit titleChanged(); break;
case NativeWindowObject::ShortTitle:
emit shortTitleChanged(); break;
case NativeWindowObject::Icon:
emit iconChanged(); break;
case NativeWindowObject::Workspace:
case NativeWindowObject::States:
emit stickyChanged(); break;
case NativeWindowObject::WinImage:
emit winImageChanged(); break;
case NativeWindowObject::WinTypes:
emit winTypeChanged(); break;
default:
break; //do nothing otherwise
}
}
<|endoftext|> |
<commit_before>/*
* RandomConn.cpp
*
* Created on: Apr 27, 2009
* Author: rasmussn
*/
#include "RandomConn.hpp"
#include <assert.h>
#include <string.h>
namespace PV {
RandomConn::RandomConn(const char * name,
HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel)
{
this->connId = hc->numberOfConnections();
this->name = strdup(name);
this->parent = hc;
this->numAxonalArborLists = 1;
initialize(NULL, pre, post, channel);
hc->addConnection(this);
}
int RandomConn::initializeWeights(const char * filename)
{
assert(filename == NULL);
return initializeRandomWeights(0);
}
}
<commit_msg>Simplified constructors and unified initialization.<commit_after>/*
* RandomConn.cpp
*
* Created on: Apr 27, 2009
* Author: rasmussn
*/
#include "RandomConn.hpp"
#include <assert.h>
#include <string.h>
namespace PV {
RandomConn::RandomConn(const char * name,
HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel)
: HyPerConn(name, hc, pre, post, channel, PROTECTED_NUMBER)
{
this->numAxonalArborLists = 1;
initialize();
hc->addConnection(this);
}
int RandomConn::initializeWeights(const char * filename)
{
assert(filename == NULL);
return initializeRandomWeights(0);
}
} // namespace PV
<|endoftext|> |
<commit_before>#include "helper_methods.h"
#include <iostream>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#define MAX_THRESHOLD 255
#define MIN_THRESHOLD 0
using namespace std;
using namespace cv;
typedef struct {
int canny_low;
int canny_high;
double threshold;
} slider_options;
void on_canny_low(int pos, void *options_){
slider_options * options = (slider_options *)options_;
options->canny_low = pos;
}
void on_canny_high(int pos, void *options_){
slider_options * options = (slider_options *)options_;
options->canny_high = pos;
}
void on_threshold(int pos, void *options_){
slider_options * options = (slider_options *)options_;
options->threshold = map_range(pos, MIN_THRESHOLD, MAX_THRESHOLD, 0.0, 1.0);
}
void createOptions(const string window_name, slider_options * options){
int low = 5;
int high = 100;
int threshold = 5;
createTrackbar("Canny low", window_name, &low, 255, &on_canny_low, options);
options->canny_high = high;
createTrackbar("Canny high", window_name, &high, 255, &on_canny_high, options);
options->canny_low = low;
createTrackbar("Threshold", window_name, &threshold, MAX_THRESHOLD, &on_threshold, options);
options->threshold = threshold;
}
int main(int argc, char * argv[]){
const string window_name = "main";
const string results_window_name = "results";
const int exit_key = 27;
const int pause_key = 32;
VideoCapture video;
if (argc < 2){
video = VideoCapture(0);
cout << "Using camera.." << endl;
}
else {
video = VideoCapture(argv[1]);
cout << "Using file " << argv[1] << endl;
}
if (!video.isOpened()){
cout << "Failed to open video." << endl;
return -1;
}
slider_options options;
namedWindow(window_name, CV_WINDOW_NORMAL);
namedWindow(results_window_name, CV_WINDOW_NORMAL);
createOptions(window_name, &options);
Mat frame;
bool has_read_correctly;
bool paused = false;
while (true){
int key = waitKey(1);
if (key == exit_key){
return 0;
}
else if (key == pause_key){
paused = !paused;
}
if (paused){
continue;
}
has_read_correctly = video.read(frame);
if (!has_read_correctly){
cout << "A reading error occured." << endl;
return -1;
}
Mat canny;
Canny(frame, canny, options.canny_low, options.canny_high);
imshow(window_name, frame);
imshow(results_window_name, canny);
}
return 0;
}
<commit_msg>Updated to draw circles<commit_after>#include "helper_methods.h"
#include <iostream>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#define MAX_THRESHOLD 255
#define MIN_THRESHOLD 0
using namespace std;
using namespace cv;
typedef struct {
int canny_low;
int canny_high;
double threshold;
} slider_options;
void on_canny_low(int pos, void *options_){
slider_options * options = (slider_options *)options_;
options->canny_low = pos;
}
void on_canny_high(int pos, void *options_){
slider_options * options = (slider_options *)options_;
options->canny_high = pos;
}
void on_threshold(int pos, void *options_){
slider_options * options = (slider_options *)options_;
options->threshold = map_range(pos, MIN_THRESHOLD, MAX_THRESHOLD, 0.0, 1.0);
}
void createOptions(const string window_name, slider_options * options){
int low = 5;
int high = 100;
int threshold = 5;
createTrackbar("Canny low", window_name, &low, 255, &on_canny_low, options);
options->canny_high = high;
createTrackbar("Canny high", window_name, &high, 255, &on_canny_high, options);
options->canny_low = low;
createTrackbar("Threshold", window_name, &threshold, MAX_THRESHOLD, &on_threshold, options);
options->threshold = threshold;
}
int main(int argc, char * argv[]){
const string window_name = "main";
const string results_window_name = "results";
const int exit_key = 27;
const int pause_key = 32;
VideoCapture video;
if (argc < 2){
video = VideoCapture(0);
cout << "Using camera.." << endl;
}
else {
video = VideoCapture(argv[1]);
cout << "Using file " << argv[1] << endl;
}
if (!video.isOpened()){
cout << "Failed to open video." << endl;
return -1;
}
slider_options options;
namedWindow(window_name, CV_WINDOW_NORMAL);
namedWindow(results_window_name, CV_WINDOW_NORMAL);
createOptions(window_name, &options);
Mat frame;
bool has_read_correctly;
bool paused = false;
while (true){
int key = waitKey(1);
if (key == exit_key){
return 0;
}
else if (key == pause_key){
paused = !paused;
}
if (paused){
continue;
}
has_read_correctly = video.read(frame);
if (!has_read_correctly){
cout << "A reading error occured." << endl;
return -1;
}
Mat canny;
Canny(frame, canny, options.canny_low, options.canny_high);
vector<Vec3f> circles;
medianBlur(canny, canny, 5);
HoughCircles(canny, circles, CV_HOUGH_GRADIENT,
canny.rows / 4, 200, 100);
for( size_t i = 0; i < circles.size(); i++ ) {
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
// circle center
circle(frame, center, 3, Scalar(0,255,0), -1, 8, 0 );
// circle outline
circle(frame, center, radius, Scalar(0,0,255), 3, 8, 0 );
}
imshow(window_name, frame);
imshow(results_window_name, canny);
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unoviewcontainer.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-17 08:29:46 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
#include <canvas/debug.hxx>
#include <unoviewcontainer.hxx>
#ifndef BOOST_BIND_HPP_INCLUDED
#include <boost/bind.hpp>
#endif
#include <algorithm>
using namespace ::com::sun::star;
// -----------------------------------------------------------------------------
namespace presentation
{
namespace internal
{
UnoViewContainer::UnoViewContainer() :
maViews()
{
}
bool UnoViewContainer::addView( const UnoViewSharedPtr& rView )
{
// check whether same view is already added
const UnoViewVector::iterator aEnd( maViews.end() );
// already added?
if( ::std::find_if( maViews.begin(),
aEnd,
::boost::bind(
::std::equal_to< uno::Reference< ::com::sun::star::presentation::XSlideShowView > >(),
::boost::cref( rView->getUnoView() ),
::boost::bind(
&UnoView::getUnoView,
_1 ) ) ) != aEnd )
{
// yes, nothing to do
return false;
}
// add locally
maViews.push_back( rView );
return true;
}
UnoViewSharedPtr UnoViewContainer::removeView( const uno::Reference< ::com::sun::star::presentation::XSlideShowView >& xView )
{
// check whether same view is already added
const UnoViewVector::iterator aEnd( maViews.end() );
UnoViewVector::iterator aIter;
// added in the first place?
if( (aIter=::std::remove_if( maViews.begin(),
aEnd,
::boost::bind(
::std::equal_to< uno::Reference< ::com::sun::star::presentation::XSlideShowView > >(),
::boost::cref( xView ),
::boost::bind(
&UnoView::getUnoView,
_1 ) ) ) ) == aEnd )
{
// nope, nothing to do
return UnoViewSharedPtr();
}
OSL_ENSURE( ::std::distance( aIter, aEnd ) == 1,
"UnoViewContainer::removeView(): View was added multiple times" );
UnoViewSharedPtr pView( *aIter );
// actually erase from container
maViews.erase( aIter, aEnd );
return pView;
}
bool UnoViewContainer::removeView( const UnoViewSharedPtr& rView )
{
// remove locally
const UnoViewVector::iterator aEnd( maViews.end() );
UnoViewVector::iterator aIter;
if( (aIter=::std::remove( maViews.begin(),
aEnd,
rView )) == aEnd )
{
// view seemingly was not added, failed
return false;
}
OSL_ENSURE( ::std::distance( aIter, aEnd ) == 1,
"UnoViewContainer::removeView(): View was added multiple times" );
// actually erase from container
maViews.erase( aIter, aEnd );
return true;
}
bool UnoViewContainer::empty() const
{
return maViews.empty();
}
void UnoViewContainer::clear()
{
maViews.clear();
}
UnoViewVector::iterator UnoViewContainer::begin()
{
return maViews.begin();
}
UnoViewVector::const_iterator UnoViewContainer::begin() const
{
return maViews.begin();
}
UnoViewVector::iterator UnoViewContainer::end()
{
return maViews.end();
}
UnoViewVector::const_iterator UnoViewContainer::end() const
{
return maViews.end();
}
}
}
<commit_msg>INTEGRATION: CWS presfixes09 (1.5.18); FILE MERGED 2006/10/18 19:51:40 thb 1.5.18.4: RESYNC: (1.5-1.6); FILE MERGED 2006/04/03 16:18:58 thb 1.5.18.3: #i37778# Now passing down ComponentContext to all interested parties; building a second, all-exports version of the slideshow component (to facilitate unit testing also for internal classes) - this made necessary renaming ImportFailedException to ShapeLoadFailedException (because of silly i63703); applied relevant parts of #i63770# (const-correctness); reworked view handling in such a way that views are now kept in one central repository (and are not duplicated across all interested objects); moved code from namespace presentation to namespace slideshow 2006/03/24 18:23:10 thb 1.5.18.2: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow 2006/03/06 22:14:30 thb 1.5.18.1: #i53194# #i55294# #i59324# Overhauled IntrinsicAnimationActivity; fixes GIF animation import; corrected rehearse timings sprite size; several cosmetic changes (removed external header guards); prepared scene for sprite prio<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unoviewcontainer.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2006-12-13 15:21:35 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"
#include <canvas/debug.hxx>
#include <unoviewcontainer.hxx>
#include <boost/bind.hpp>
#include <algorithm>
using namespace ::com::sun::star;
// -----------------------------------------------------------------------------
namespace slideshow
{
namespace internal
{
UnoViewContainer::UnoViewContainer() :
maViews()
{
}
bool UnoViewContainer::addView( const UnoViewSharedPtr& rView )
{
// check whether same view is already added
const UnoViewVector::iterator aEnd( maViews.end() );
// already added?
if( ::std::find_if( maViews.begin(),
aEnd,
::boost::bind(
::std::equal_to< uno::Reference< presentation::XSlideShowView > >(),
::boost::cref( rView->getUnoView() ),
::boost::bind(
&UnoView::getUnoView,
_1 ) ) ) != aEnd )
{
// yes, nothing to do
return false;
}
// add locally
maViews.push_back( rView );
return true;
}
UnoViewSharedPtr UnoViewContainer::removeView( const uno::Reference< presentation::XSlideShowView >& xView )
{
// check whether same view is already added
const UnoViewVector::iterator aEnd( maViews.end() );
UnoViewVector::iterator aIter;
// added in the first place?
if( (aIter=::std::remove_if( maViews.begin(),
aEnd,
::boost::bind(
::std::equal_to< uno::Reference< presentation::XSlideShowView > >(),
::boost::cref( xView ),
::boost::bind(
&UnoView::getUnoView,
_1 ) ) ) ) == aEnd )
{
// nope, nothing to do
return UnoViewSharedPtr();
}
OSL_ENSURE( ::std::distance( aIter, aEnd ) == 1,
"UnoViewContainer::removeView(): View was added multiple times" );
UnoViewSharedPtr pView( *aIter );
// actually erase from container
maViews.erase( aIter, aEnd );
return pView;
}
bool UnoViewContainer::removeView( const UnoViewSharedPtr& rView )
{
// remove locally
const UnoViewVector::iterator aEnd( maViews.end() );
UnoViewVector::iterator aIter;
if( (aIter=::std::remove( maViews.begin(),
aEnd,
rView )) == aEnd )
{
// view seemingly was not added, failed
return false;
}
OSL_ENSURE( ::std::distance( aIter, aEnd ) == 1,
"UnoViewContainer::removeView(): View was added multiple times" );
// actually erase from container
maViews.erase( aIter, aEnd );
return true;
}
void UnoViewContainer::dispose()
{
::std::for_each( maViews.begin(),
maViews.end(),
::boost::mem_fn(&UnoView::_dispose) );
maViews.clear();
}
}
}
<|endoftext|> |
<commit_before>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2022, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <gtest/gtest.h>
#include <mrpt/config.h>
#include <mrpt/core/exceptions.h>
#include <algorithm> // count()
#include <sstream>
TEST(exception, stackedExceptionBasic)
{
EXPECT_THROW({ THROW_EXCEPTION("wtf"); }, mrpt::ExceptionWithCallBackBase);
}
template <typename T>
void test_except_3rd_lvl(T val)
{
MRPT_START
THROW_EXCEPTION("Aw!");
val++;
MRPT_END
}
void test_except_2nd_lvl()
{
MRPT_START
test_except_3rd_lvl<int>(10);
MRPT_END
}
void test_except_toplevel()
{
MRPT_START
test_except_2nd_lvl();
MRPT_END
}
#if !MRPT_IN_EMSCRIPTEN
TEST(exception, stackedExceptionComplex)
{
try
{
test_except_toplevel();
GTEST_FAIL() << "Shouldn't reach here.";
}
catch (const std::exception& e)
{
const auto sExc = mrpt::exception_to_str(e);
#if !defined(MRPT_EXCEPTIONS_WITH_CALL_STACK)
EXPECT_TRUE(sExc.find("Aw!") != std::string::npos) << sExc;
#else
const auto num_lines = std::count(sExc.begin(), sExc.end(), '\n');
EXPECT_GT(num_lines, 10) << sExc;
EXPECT_TRUE(sExc.find("Message: Aw!") != std::string::npos) << sExc;
#endif
// This test doesn't pass in Windows if building w/o debug symbols:
#if defined(MRPT_EXCEPTIONS_WITH_CALL_STACK) && \
(!defined(_WIN32) || defined(_DEBUG))
EXPECT_TRUE(sExc.find("test_except_toplevel") != std::string::npos)
<< sExc;
#endif
}
}
#endif
TEST(exception, assertException)
{
bool trueValue = true;
bool falseValue = false;
EXPECT_THROW(
{ ASSERT_EQUAL_(trueValue, falseValue); },
mrpt::ExceptionWithCallBackBase);
}
static std::string testFoo()
{
try
{
std::vector<int> dummy;
ASSERTMSG_(!dummy.empty(), "Check it");
return {};
}
catch (std::exception& e)
{
const auto err = mrpt::exception_to_str(e);
return err;
}
}
TEST(exception, infiniteRecurseBug)
{
// Should not crash:
const auto s = testFoo();
EXPECT_TRUE(s.find("Check it") != std::string::npos);
}
TEST(exception, assertMacros)
{
// ASSERT_EQUAL_
EXPECT_NO_THROW(ASSERT_EQUAL_(1, 1));
EXPECT_NO_THROW(ASSERT_EQUAL_(1 + 3, 1 + 1 + 1 + 1));
EXPECT_ANY_THROW(ASSERT_EQUAL_(1, 2));
EXPECT_ANY_THROW(ASSERT_EQUAL_(1 + 3, 3 + 2));
// ASSERT_NOT_EQUAL_
EXPECT_ANY_THROW(ASSERT_NOT_EQUAL_(1, 1));
EXPECT_ANY_THROW(ASSERT_NOT_EQUAL_(1 + 3, 1 + 1 + 1 + 1));
EXPECT_NO_THROW(ASSERT_NOT_EQUAL_(1, 2));
EXPECT_NO_THROW(ASSERT_NOT_EQUAL_(1 + 3, 3 + 2));
// ASSERT_NEAR_
EXPECT_NO_THROW(ASSERT_NEAR_(10.0, 10.01, 0.2));
EXPECT_NO_THROW(ASSERT_NEAR_(10.0 + 1.0, 10.0 + 1.01, 0.2));
EXPECT_NO_THROW(ASSERT_NEAR_(1, 1, 0));
EXPECT_ANY_THROW(ASSERT_NEAR_(1, 2, 0));
EXPECT_ANY_THROW(ASSERT_NEAR_(10.0, 10.01, 0.001));
EXPECT_ANY_THROW(ASSERT_NEAR_(10.0, 10.01f, 0.001));
EXPECT_ANY_THROW(ASSERT_NEAR_(10.0, 10.01f, 0.001f));
EXPECT_ANY_THROW(ASSERT_NEAR_(10.0f, 10.01, 0.001f));
EXPECT_NO_THROW(ASSERT_NEAR_(10.0, 10.01f, 0.1));
EXPECT_NO_THROW(ASSERT_NEAR_(10.0f, 10.01f, 0.1));
EXPECT_NO_THROW(ASSERT_NEAR_(10.0f, 10.01, 0.1));
EXPECT_NO_THROW(ASSERT_NEAR_(10.0, 10.01f, 0.1f));
const std::array<double, 2> arr_dc = {10.0, 10.01};
std::array<double, 2> arr_dnc = {10.0, 10.01};
EXPECT_NO_THROW(ASSERT_NEAR_(arr_dc[0], arr_dc[1], 0.1));
EXPECT_NO_THROW(ASSERT_NEAR_(arr_dc[0], arr_dnc[1], 0.1));
EXPECT_NO_THROW(ASSERT_NEAR_(arr_dnc[0], arr_dc[1], 0.1));
EXPECT_NO_THROW(ASSERT_NEAR_(arr_dnc[0], arr_dnc[1], 0.1));
// ASSERT_LT_
EXPECT_NO_THROW(ASSERT_LT_(1.0, 2.0));
EXPECT_ANY_THROW(ASSERT_LT_(3, 2));
EXPECT_ANY_THROW(ASSERT_LT_(-1, -3));
// ASSERT_LE_
EXPECT_NO_THROW(ASSERT_LE_(1.0, 2.0));
EXPECT_NO_THROW(ASSERT_LE_(1.0, 1.0));
// ASSERT_GT_
EXPECT_ANY_THROW(ASSERT_GT_(1.0, 2.0));
EXPECT_NO_THROW(ASSERT_GT_(3, 2));
EXPECT_NO_THROW(ASSERT_GT_(-1, -3));
// ASSERT_GE_
EXPECT_NO_THROW(ASSERT_GE_(2.0, 1.0));
EXPECT_NO_THROW(ASSERT_GE_(1.0, 1.0));
}
<commit_msg>fix build in msvc<commit_after>/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| https://www.mrpt.org/ |
| |
| Copyright (c) 2005-2022, Individual contributors, see AUTHORS file |
| See: https://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See: https://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include <gtest/gtest.h>
#include <mrpt/config.h>
#include <mrpt/core/exceptions.h>
#include <algorithm> // count()
#include <array>
#include <sstream>
TEST(exception, stackedExceptionBasic)
{
EXPECT_THROW({ THROW_EXCEPTION("wtf"); }, mrpt::ExceptionWithCallBackBase);
}
template <typename T>
void test_except_3rd_lvl(T val)
{
MRPT_START
THROW_EXCEPTION("Aw!");
val++;
MRPT_END
}
void test_except_2nd_lvl()
{
MRPT_START
test_except_3rd_lvl<int>(10);
MRPT_END
}
void test_except_toplevel()
{
MRPT_START
test_except_2nd_lvl();
MRPT_END
}
#if !MRPT_IN_EMSCRIPTEN
TEST(exception, stackedExceptionComplex)
{
try
{
test_except_toplevel();
GTEST_FAIL() << "Shouldn't reach here.";
}
catch (const std::exception& e)
{
const auto sExc = mrpt::exception_to_str(e);
#if !defined(MRPT_EXCEPTIONS_WITH_CALL_STACK)
EXPECT_TRUE(sExc.find("Aw!") != std::string::npos) << sExc;
#else
const auto num_lines = std::count(sExc.begin(), sExc.end(), '\n');
EXPECT_GT(num_lines, 10) << sExc;
EXPECT_TRUE(sExc.find("Message: Aw!") != std::string::npos) << sExc;
#endif
// This test doesn't pass in Windows if building w/o debug symbols:
#if defined(MRPT_EXCEPTIONS_WITH_CALL_STACK) && \
(!defined(_WIN32) || defined(_DEBUG))
EXPECT_TRUE(sExc.find("test_except_toplevel") != std::string::npos)
<< sExc;
#endif
}
}
#endif
TEST(exception, assertException)
{
bool trueValue = true;
bool falseValue = false;
EXPECT_THROW(
{ ASSERT_EQUAL_(trueValue, falseValue); },
mrpt::ExceptionWithCallBackBase);
}
static std::string testFoo()
{
try
{
std::vector<int> dummy;
ASSERTMSG_(!dummy.empty(), "Check it");
return {};
}
catch (std::exception& e)
{
const auto err = mrpt::exception_to_str(e);
return err;
}
}
TEST(exception, infiniteRecurseBug)
{
// Should not crash:
const auto s = testFoo();
EXPECT_TRUE(s.find("Check it") != std::string::npos);
}
TEST(exception, assertMacros)
{
// ASSERT_EQUAL_
EXPECT_NO_THROW(ASSERT_EQUAL_(1, 1));
EXPECT_NO_THROW(ASSERT_EQUAL_(1 + 3, 1 + 1 + 1 + 1));
EXPECT_ANY_THROW(ASSERT_EQUAL_(1, 2));
EXPECT_ANY_THROW(ASSERT_EQUAL_(1 + 3, 3 + 2));
// ASSERT_NOT_EQUAL_
EXPECT_ANY_THROW(ASSERT_NOT_EQUAL_(1, 1));
EXPECT_ANY_THROW(ASSERT_NOT_EQUAL_(1 + 3, 1 + 1 + 1 + 1));
EXPECT_NO_THROW(ASSERT_NOT_EQUAL_(1, 2));
EXPECT_NO_THROW(ASSERT_NOT_EQUAL_(1 + 3, 3 + 2));
// ASSERT_NEAR_
EXPECT_NO_THROW(ASSERT_NEAR_(10.0, 10.01, 0.2));
EXPECT_NO_THROW(ASSERT_NEAR_(10.0 + 1.0, 10.0 + 1.01, 0.2));
EXPECT_NO_THROW(ASSERT_NEAR_(1, 1, 0));
EXPECT_ANY_THROW(ASSERT_NEAR_(1, 2, 0));
EXPECT_ANY_THROW(ASSERT_NEAR_(10.0, 10.01, 0.001));
EXPECT_ANY_THROW(ASSERT_NEAR_(10.0, 10.01f, 0.001));
EXPECT_ANY_THROW(ASSERT_NEAR_(10.0, 10.01f, 0.001f));
EXPECT_ANY_THROW(ASSERT_NEAR_(10.0f, 10.01, 0.001f));
EXPECT_NO_THROW(ASSERT_NEAR_(10.0, 10.01f, 0.1));
EXPECT_NO_THROW(ASSERT_NEAR_(10.0f, 10.01f, 0.1));
EXPECT_NO_THROW(ASSERT_NEAR_(10.0f, 10.01, 0.1));
EXPECT_NO_THROW(ASSERT_NEAR_(10.0, 10.01f, 0.1f));
const std::array<double, 2> arr_dc = {10.0, 10.01};
std::array<double, 2> arr_dnc = {10.0, 10.01};
EXPECT_NO_THROW(ASSERT_NEAR_(arr_dc[0], arr_dc[1], 0.1));
EXPECT_NO_THROW(ASSERT_NEAR_(arr_dc[0], arr_dnc[1], 0.1));
EXPECT_NO_THROW(ASSERT_NEAR_(arr_dnc[0], arr_dc[1], 0.1));
EXPECT_NO_THROW(ASSERT_NEAR_(arr_dnc[0], arr_dnc[1], 0.1));
// ASSERT_LT_
EXPECT_NO_THROW(ASSERT_LT_(1.0, 2.0));
EXPECT_ANY_THROW(ASSERT_LT_(3, 2));
EXPECT_ANY_THROW(ASSERT_LT_(-1, -3));
// ASSERT_LE_
EXPECT_NO_THROW(ASSERT_LE_(1.0, 2.0));
EXPECT_NO_THROW(ASSERT_LE_(1.0, 1.0));
// ASSERT_GT_
EXPECT_ANY_THROW(ASSERT_GT_(1.0, 2.0));
EXPECT_NO_THROW(ASSERT_GT_(3, 2));
EXPECT_NO_THROW(ASSERT_GT_(-1, -3));
// ASSERT_GE_
EXPECT_NO_THROW(ASSERT_GE_(2.0, 1.0));
EXPECT_NO_THROW(ASSERT_GE_(1.0, 1.0));
}
<|endoftext|> |
<commit_before>#pragma once
#include <map>
#include <vector>
#include <unordered_set>
#include "tatum/util/tatum_linear_map.hpp"
#include "tatum/util/tatum_range.hpp"
#include "tatum/base/ArrivalType.hpp"
#include "tatum/base/DelayType.hpp"
#include "tatum/TimingConstraintsFwd.hpp"
#include "tatum/TimingGraphFwd.hpp"
#include "tatum/Time.hpp"
namespace tatum {
/**
* The TimingConstraints class stores all the timing constraints applied during timing analysis.
*/
class TimingConstraints {
public: //Types
typedef tatum::util::linear_map<DomainId,DomainId>::const_iterator domain_iterator;
typedef std::map<DomainPair,Time>::const_iterator clock_constraint_iterator;
typedef std::map<DomainPair,Time>::const_iterator clock_uncertainty_iterator;
typedef std::multimap<NodeId,IoConstraint>::const_iterator io_constraint_iterator;
typedef std::map<DomainId,Time>::const_iterator source_latency_iterator;
typedef std::unordered_set<NodeId>::const_iterator constant_generator_iterator;
typedef tatum::util::Range<domain_iterator> domain_range;
typedef tatum::util::Range<clock_constraint_iterator> clock_constraint_range;
typedef tatum::util::Range<clock_uncertainty_iterator> clock_uncertainty_range;
typedef tatum::util::Range<io_constraint_iterator> io_constraint_range;
typedef tatum::util::Range<source_latency_iterator> source_latency_range;
typedef tatum::util::Range<constant_generator_iterator> constant_generator_range;
public: //Accessors
///\returns A range containing all defined clock domains
domain_range clock_domains() const;
///\returns The name of a clock domain
std::string clock_domain_name(const DomainId id) const;
///\returns The source NodeId of the specified domain
NodeId clock_domain_source_node(const DomainId id) const;
//\returns whether the specified domain id corresponds to a virtual lcock
bool is_virtual_clock(const DomainId id) const;
///\returns The domain of the specified node id if it is a clock source
DomainId node_clock_domain(const NodeId id) const;
///\returns True if the node id is a clock source
bool node_is_clock_source(const NodeId id) const;
///\returns True if the node id is a constant generator
bool node_is_constant_generator(const NodeId id) const;
///\returns A valid DomainId if a clock domain with the specified name exists, DomainId::INVALID() otherwise
DomainId find_clock_domain(const std::string& name) const;
///Indicates whether the paths between src_domain and sink_domain should be analyzed
///\param src_domain The ID of the source (launch) clock domain
///\param sink_domain The ID of the sink (capture) clock domain
bool should_analyze(const DomainId src_domain, const DomainId sink_domain) const;
///\returns The setup (max) constraint between src_domain and sink_domain
Time setup_constraint(const DomainId src_domain, const DomainId sink_domain) const;
///\returns The hold (min) constraint between src_domain and sink_domain
Time hold_constraint(const DomainId src_domain, const DomainId sink_domain) const;
///\returns The setup clock uncertainty between src_domain and sink_domain (defaults to zero if unspecified)
Time setup_clock_uncertainty(const DomainId src_domain, const DomainId sink_domain) const;
///\returns The hold clock uncertainty between src_domain and sink_domain (defaults to zero if unspecified)
Time hold_clock_uncertainty(const DomainId src_domain, const DomainId sink_domain) const;
///\returns The input delay constraint on node_id
Time input_constraint(const NodeId node_id, const DomainId domain_id, const DelayType delay_type) const;
///\returns The output delay constraint on node_id
Time output_constraint(const NodeId node_id, const DomainId domain_id, const DelayType delay_type) const;
///\returns The external (e.g. off-chip) source latency of a particular clock domain
//
//Corresponds to the delay from the clock's true source to it's definition point on-chip
Time source_latency(const DomainId domain_id, ArrivalType arrival_type) const;
///\returns A range of all constant generator nodes
constant_generator_range constant_generators() const;
///\returns A range of all setup constraints
clock_constraint_range setup_constraints() const;
///\returns A range of all setup constraints
clock_constraint_range hold_constraints() const;
///\returns A range of all setup clock uncertainties
clock_uncertainty_range setup_clock_uncertainties() const;
///\returns A range of all hold clock uncertainties
clock_uncertainty_range hold_clock_uncertainties() const;
///\returns A range of all input constraints
io_constraint_range input_constraints(const DelayType delay_type) const;
///\returns A range of all output constraints
io_constraint_range output_constraints(const DelayType delay_type) const;
///\returns A range of output constraints for the node id
io_constraint_range input_constraints(const NodeId id, const DelayType delay_type) const;
///\returns A range of input constraints for the node id
io_constraint_range output_constraints(const NodeId id, const DelayType delay_type) const;
///\returns A range of all clock source latencies
source_latency_range source_latencies(ArrivalType arrival_type) const;
///Prints out the timing constraints for debug purposes
void print_constraints() const;
public: //Mutators
///\returns The DomainId of the clock with the specified name (will be created if it doesn not exist)
DomainId create_clock_domain(const std::string name);
///Sets the setup constraint between src_domain and sink_domain with value constraint
void set_setup_constraint(const DomainId src_domain, const DomainId sink_domain, const Time constraint);
///Sets the hold constraint between src_domain and sink_domain with value constraint
void set_hold_constraint(const DomainId src_domain, const DomainId sink_domain, const Time constraint);
///Sets the setup clock uncertainty between src_domain and sink_domain with value uncertainty
void set_setup_clock_uncertainty(const DomainId src_domain, const DomainId sink_domain, const Time uncertainty);
///Sets the hold clock uncertainty between src_domain and sink_domain with value uncertainty
void set_hold_clock_uncertainty(const DomainId src_domain, const DomainId sink_domain, const Time uncertainty);
///Sets the input delay constraint on node_id with value constraint
void set_input_constraint(const NodeId node_id, const DomainId domain_id, const DelayType delay_type, const Time constraint);
///Sets the output delay constraint on node_id with value constraint
void set_output_constraint(const NodeId node_id, const DomainId domain_id, const DelayType delay_type, const Time constraint);
///Sets the source latency of the specified clock domain
void set_source_latency(const DomainId domain_id, const ArrivalType arrival_type, const Time latency);
///Sets the source node for the specified clock domain
void set_clock_domain_source(const NodeId node_id, const DomainId domain_id);
///Sets whether the specified node is a constant generator
void set_constant_generator(const NodeId node_id, bool is_constant_generator=true);
///Update node IDs if they have changed
///\param node_map A vector mapping from old to new node ids
void remap_nodes(const tatum::util::linear_map<NodeId,NodeId>& node_map);
private:
typedef std::multimap<NodeId,IoConstraint>::iterator mutable_io_constraint_iterator;
private:
///\returns A valid domain id if the node is a clock source
DomainId find_node_source_clock_domain(const NodeId node_id) const;
io_constraint_iterator find_io_constraint(const NodeId node_id, const DomainId domain_id, const std::multimap<NodeId,IoConstraint>& io_constraints) const;
mutable_io_constraint_iterator find_io_constraint(const NodeId node_id, const DomainId domain_id, std::multimap<NodeId,IoConstraint>& io_constraints);
private: //Data
tatum::util::linear_map<DomainId,DomainId> domain_ids_;
tatum::util::linear_map<DomainId,std::string> domain_names_;
tatum::util::linear_map<DomainId,NodeId> domain_sources_;
std::unordered_set<NodeId> constant_generators_;
std::map<DomainPair,Time> setup_constraints_;
std::map<DomainPair,Time> hold_constraints_;
std::map<DomainPair,Time> setup_clock_uncertainties_;
std::map<DomainPair,Time> hold_clock_uncertainties_;
std::multimap<NodeId,IoConstraint> max_input_constraints_;
std::multimap<NodeId,IoConstraint> min_input_constraints_;
std::multimap<NodeId,IoConstraint> max_output_constraints_;
std::multimap<NodeId,IoConstraint> min_output_constraints_;
std::map<DomainId,Time> source_latencies_early_;
std::map<DomainId,Time> source_latencies_late_;
};
/*
* Utility classes
*/
struct DomainPair {
DomainPair(DomainId src, DomainId sink): src_domain_id(src), sink_domain_id(sink) {}
friend bool operator<(const DomainPair& lhs, const DomainPair& rhs) {
if(lhs.src_domain_id < rhs.src_domain_id) {
return true;
} else if(lhs.src_domain_id == rhs.src_domain_id
&& lhs.sink_domain_id < rhs.sink_domain_id) {
return true;
}
return false;
}
DomainId src_domain_id;
DomainId sink_domain_id;
};
struct IoConstraint {
IoConstraint(DomainId domain_id, Time constraint_val): domain(domain_id), constraint(constraint_val) {}
DomainId domain;
Time constraint;
};
} //namepsace
<commit_msg>Simplify comparison operator<commit_after>#pragma once
#include <map>
#include <vector>
#include <unordered_set>
#include "tatum/util/tatum_linear_map.hpp"
#include "tatum/util/tatum_range.hpp"
#include "tatum/base/ArrivalType.hpp"
#include "tatum/base/DelayType.hpp"
#include "tatum/TimingConstraintsFwd.hpp"
#include "tatum/TimingGraphFwd.hpp"
#include "tatum/Time.hpp"
namespace tatum {
/**
* The TimingConstraints class stores all the timing constraints applied during timing analysis.
*/
class TimingConstraints {
public: //Types
typedef tatum::util::linear_map<DomainId,DomainId>::const_iterator domain_iterator;
typedef std::map<DomainPair,Time>::const_iterator clock_constraint_iterator;
typedef std::map<DomainPair,Time>::const_iterator clock_uncertainty_iterator;
typedef std::multimap<NodeId,IoConstraint>::const_iterator io_constraint_iterator;
typedef std::map<DomainId,Time>::const_iterator source_latency_iterator;
typedef std::unordered_set<NodeId>::const_iterator constant_generator_iterator;
typedef tatum::util::Range<domain_iterator> domain_range;
typedef tatum::util::Range<clock_constraint_iterator> clock_constraint_range;
typedef tatum::util::Range<clock_uncertainty_iterator> clock_uncertainty_range;
typedef tatum::util::Range<io_constraint_iterator> io_constraint_range;
typedef tatum::util::Range<source_latency_iterator> source_latency_range;
typedef tatum::util::Range<constant_generator_iterator> constant_generator_range;
public: //Accessors
///\returns A range containing all defined clock domains
domain_range clock_domains() const;
///\returns The name of a clock domain
std::string clock_domain_name(const DomainId id) const;
///\returns The source NodeId of the specified domain
NodeId clock_domain_source_node(const DomainId id) const;
//\returns whether the specified domain id corresponds to a virtual lcock
bool is_virtual_clock(const DomainId id) const;
///\returns The domain of the specified node id if it is a clock source
DomainId node_clock_domain(const NodeId id) const;
///\returns True if the node id is a clock source
bool node_is_clock_source(const NodeId id) const;
///\returns True if the node id is a constant generator
bool node_is_constant_generator(const NodeId id) const;
///\returns A valid DomainId if a clock domain with the specified name exists, DomainId::INVALID() otherwise
DomainId find_clock_domain(const std::string& name) const;
///Indicates whether the paths between src_domain and sink_domain should be analyzed
///\param src_domain The ID of the source (launch) clock domain
///\param sink_domain The ID of the sink (capture) clock domain
bool should_analyze(const DomainId src_domain, const DomainId sink_domain) const;
///\returns The setup (max) constraint between src_domain and sink_domain
Time setup_constraint(const DomainId src_domain, const DomainId sink_domain) const;
///\returns The hold (min) constraint between src_domain and sink_domain
Time hold_constraint(const DomainId src_domain, const DomainId sink_domain) const;
///\returns The setup clock uncertainty between src_domain and sink_domain (defaults to zero if unspecified)
Time setup_clock_uncertainty(const DomainId src_domain, const DomainId sink_domain) const;
///\returns The hold clock uncertainty between src_domain and sink_domain (defaults to zero if unspecified)
Time hold_clock_uncertainty(const DomainId src_domain, const DomainId sink_domain) const;
///\returns The input delay constraint on node_id
Time input_constraint(const NodeId node_id, const DomainId domain_id, const DelayType delay_type) const;
///\returns The output delay constraint on node_id
Time output_constraint(const NodeId node_id, const DomainId domain_id, const DelayType delay_type) const;
///\returns The external (e.g. off-chip) source latency of a particular clock domain
//
//Corresponds to the delay from the clock's true source to it's definition point on-chip
Time source_latency(const DomainId domain_id, ArrivalType arrival_type) const;
///\returns A range of all constant generator nodes
constant_generator_range constant_generators() const;
///\returns A range of all setup constraints
clock_constraint_range setup_constraints() const;
///\returns A range of all setup constraints
clock_constraint_range hold_constraints() const;
///\returns A range of all setup clock uncertainties
clock_uncertainty_range setup_clock_uncertainties() const;
///\returns A range of all hold clock uncertainties
clock_uncertainty_range hold_clock_uncertainties() const;
///\returns A range of all input constraints
io_constraint_range input_constraints(const DelayType delay_type) const;
///\returns A range of all output constraints
io_constraint_range output_constraints(const DelayType delay_type) const;
///\returns A range of output constraints for the node id
io_constraint_range input_constraints(const NodeId id, const DelayType delay_type) const;
///\returns A range of input constraints for the node id
io_constraint_range output_constraints(const NodeId id, const DelayType delay_type) const;
///\returns A range of all clock source latencies
source_latency_range source_latencies(ArrivalType arrival_type) const;
///Prints out the timing constraints for debug purposes
void print_constraints() const;
public: //Mutators
///\returns The DomainId of the clock with the specified name (will be created if it doesn not exist)
DomainId create_clock_domain(const std::string name);
///Sets the setup constraint between src_domain and sink_domain with value constraint
void set_setup_constraint(const DomainId src_domain, const DomainId sink_domain, const Time constraint);
///Sets the hold constraint between src_domain and sink_domain with value constraint
void set_hold_constraint(const DomainId src_domain, const DomainId sink_domain, const Time constraint);
///Sets the setup clock uncertainty between src_domain and sink_domain with value uncertainty
void set_setup_clock_uncertainty(const DomainId src_domain, const DomainId sink_domain, const Time uncertainty);
///Sets the hold clock uncertainty between src_domain and sink_domain with value uncertainty
void set_hold_clock_uncertainty(const DomainId src_domain, const DomainId sink_domain, const Time uncertainty);
///Sets the input delay constraint on node_id with value constraint
void set_input_constraint(const NodeId node_id, const DomainId domain_id, const DelayType delay_type, const Time constraint);
///Sets the output delay constraint on node_id with value constraint
void set_output_constraint(const NodeId node_id, const DomainId domain_id, const DelayType delay_type, const Time constraint);
///Sets the source latency of the specified clock domain
void set_source_latency(const DomainId domain_id, const ArrivalType arrival_type, const Time latency);
///Sets the source node for the specified clock domain
void set_clock_domain_source(const NodeId node_id, const DomainId domain_id);
///Sets whether the specified node is a constant generator
void set_constant_generator(const NodeId node_id, bool is_constant_generator=true);
///Update node IDs if they have changed
///\param node_map A vector mapping from old to new node ids
void remap_nodes(const tatum::util::linear_map<NodeId,NodeId>& node_map);
private:
typedef std::multimap<NodeId,IoConstraint>::iterator mutable_io_constraint_iterator;
private:
///\returns A valid domain id if the node is a clock source
DomainId find_node_source_clock_domain(const NodeId node_id) const;
io_constraint_iterator find_io_constraint(const NodeId node_id, const DomainId domain_id, const std::multimap<NodeId,IoConstraint>& io_constraints) const;
mutable_io_constraint_iterator find_io_constraint(const NodeId node_id, const DomainId domain_id, std::multimap<NodeId,IoConstraint>& io_constraints);
private: //Data
tatum::util::linear_map<DomainId,DomainId> domain_ids_;
tatum::util::linear_map<DomainId,std::string> domain_names_;
tatum::util::linear_map<DomainId,NodeId> domain_sources_;
std::unordered_set<NodeId> constant_generators_;
std::map<DomainPair,Time> setup_constraints_;
std::map<DomainPair,Time> hold_constraints_;
std::map<DomainPair,Time> setup_clock_uncertainties_;
std::map<DomainPair,Time> hold_clock_uncertainties_;
std::multimap<NodeId,IoConstraint> max_input_constraints_;
std::multimap<NodeId,IoConstraint> min_input_constraints_;
std::multimap<NodeId,IoConstraint> max_output_constraints_;
std::multimap<NodeId,IoConstraint> min_output_constraints_;
std::map<DomainId,Time> source_latencies_early_;
std::map<DomainId,Time> source_latencies_late_;
};
/*
* Utility classes
*/
struct DomainPair {
DomainPair(DomainId src, DomainId sink): src_domain_id(src), sink_domain_id(sink) {}
friend bool operator<(const DomainPair& lhs, const DomainPair& rhs) {
return std::tie(lhs.src_domain_id, lhs.sink_domain_id) < std::tie(rhs.src_domain_id, rhs.sink_domain_id);
}
DomainId src_domain_id;
DomainId sink_domain_id;
};
struct IoConstraint {
IoConstraint(DomainId domain_id, Time constraint_val): domain(domain_id), constraint(constraint_val) {}
DomainId domain;
Time constraint;
};
} //namepsace
<|endoftext|> |
<commit_before>//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code dealing with C++ code generation of classes
//
//===----------------------------------------------------------------------===//
#include "CodeGenFunction.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/RecordLayout.h"
using namespace clang;
using namespace CodeGen;
static uint64_t
ComputeNonVirtualBaseClassOffset(ASTContext &Context, CXXBasePaths &Paths,
unsigned Start) {
uint64_t Offset = 0;
const CXXBasePath &Path = Paths.front();
for (unsigned i = Start, e = Path.size(); i != e; ++i) {
const CXXBasePathElement& Element = Path[i];
// Get the layout.
const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
const CXXBaseSpecifier *BS = Element.Base;
// FIXME: enable test3 from virt.cc to not abort.
if (BS->isVirtual())
return 0;
assert(!BS->isVirtual() && "Should not see virtual bases here!");
const CXXRecordDecl *Base =
cast<CXXRecordDecl>(BS->getType()->getAs<RecordType>()->getDecl());
// Add the offset.
Offset += Layout.getBaseClassOffset(Base) / 8;
}
return Offset;
}
llvm::Constant *
CodeGenModule::GetCXXBaseClassOffset(const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl) {
if (ClassDecl == BaseClassDecl)
return 0;
CXXBasePaths Paths(/*FindAmbiguities=*/false,
/*RecordPaths=*/true, /*DetectVirtual=*/false);
if (!const_cast<CXXRecordDecl *>(ClassDecl)->
isDerivedFrom(const_cast<CXXRecordDecl *>(BaseClassDecl), Paths)) {
assert(false && "Class must be derived from the passed in base class!");
return 0;
}
uint64_t Offset = ComputeNonVirtualBaseClassOffset(getContext(), Paths, 0);
if (!Offset)
return 0;
const llvm::Type *PtrDiffTy =
Types.ConvertType(getContext().getPointerDiffType());
return llvm::ConstantInt::get(PtrDiffTy, Offset);
}
static llvm::Value *GetCXXBaseClassOffset(CodeGenFunction &CGF,
llvm::Value *BaseValue,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl) {
CXXBasePaths Paths(/*FindAmbiguities=*/false,
/*RecordPaths=*/true, /*DetectVirtual=*/false);
if (!const_cast<CXXRecordDecl *>(ClassDecl)->
isDerivedFrom(const_cast<CXXRecordDecl *>(BaseClassDecl), Paths)) {
assert(false && "Class must be derived from the passed in base class!");
return 0;
}
unsigned Start = 0;
llvm::Value *VirtualOffset = 0;
const CXXBasePath &Path = Paths.front();
const CXXRecordDecl *VBase = 0;
for (unsigned i = 0, e = Path.size(); i != e; ++i) {
const CXXBasePathElement& Element = Path[i];
if (Element.Base->isVirtual()) {
Start = i+1;
QualType VBaseType = Element.Base->getType();
VBase = cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
}
}
if (VBase)
VirtualOffset =
CGF.GetVirtualCXXBaseClassOffset(BaseValue, ClassDecl, VBase);
uint64_t Offset =
ComputeNonVirtualBaseClassOffset(CGF.getContext(), Paths, Start);
if (!Offset)
return VirtualOffset;
const llvm::Type *PtrDiffTy =
CGF.ConvertType(CGF.getContext().getPointerDiffType());
llvm::Value *NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, Offset);
if (VirtualOffset)
return CGF.Builder.CreateAdd(VirtualOffset, NonVirtualOffset);
return NonVirtualOffset;
}
llvm::Value *
CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl,
bool NullCheckValue) {
QualType BTy =
getContext().getCanonicalType(
getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
const llvm::Type *BasePtrTy = llvm::PointerType::getUnqual(ConvertType(BTy));
if (ClassDecl == BaseClassDecl) {
// Just cast back.
return Builder.CreateBitCast(Value, BasePtrTy);
}
llvm::BasicBlock *CastNull = 0;
llvm::BasicBlock *CastNotNull = 0;
llvm::BasicBlock *CastEnd = 0;
if (NullCheckValue) {
CastNull = createBasicBlock("cast.null");
CastNotNull = createBasicBlock("cast.notnull");
CastEnd = createBasicBlock("cast.end");
llvm::Value *IsNull =
Builder.CreateICmpEQ(Value,
llvm::Constant::getNullValue(Value->getType()));
Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
EmitBlock(CastNotNull);
}
const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
llvm::Value *Offset =
GetCXXBaseClassOffset(*this, Value, ClassDecl, BaseClassDecl);
if (Offset) {
// Apply the offset.
Value = Builder.CreateBitCast(Value, Int8PtrTy);
Value = Builder.CreateGEP(Value, Offset, "add.ptr");
}
// Cast back.
Value = Builder.CreateBitCast(Value, BasePtrTy);
if (NullCheckValue) {
Builder.CreateBr(CastEnd);
EmitBlock(CastNull);
Builder.CreateBr(CastEnd);
EmitBlock(CastEnd);
llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
PHI->reserveOperandSpace(2);
PHI->addIncoming(Value, CastNotNull);
PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
CastNull);
Value = PHI;
}
return Value;
}
llvm::Value *
CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *DerivedClassDecl,
bool NullCheckValue) {
QualType DerivedTy =
getContext().getCanonicalType(
getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(DerivedClassDecl)));
const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
if (ClassDecl == DerivedClassDecl) {
// Just cast back.
return Builder.CreateBitCast(Value, DerivedPtrTy);
}
llvm::BasicBlock *CastNull = 0;
llvm::BasicBlock *CastNotNull = 0;
llvm::BasicBlock *CastEnd = 0;
if (NullCheckValue) {
CastNull = createBasicBlock("cast.null");
CastNotNull = createBasicBlock("cast.notnull");
CastEnd = createBasicBlock("cast.end");
llvm::Value *IsNull =
Builder.CreateICmpEQ(Value,
llvm::Constant::getNullValue(Value->getType()));
Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
EmitBlock(CastNotNull);
}
llvm::Value *Offset = GetCXXBaseClassOffset(*this, Value, DerivedClassDecl,
ClassDecl);
if (Offset) {
// Apply the offset.
Value = Builder.CreatePtrToInt(Value, Offset->getType());
Value = Builder.CreateSub(Value, Offset);
Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
} else {
// Just cast.
Value = Builder.CreateBitCast(Value, DerivedPtrTy);
}
if (NullCheckValue) {
Builder.CreateBr(CastEnd);
EmitBlock(CastNull);
Builder.CreateBr(CastEnd);
EmitBlock(CastEnd);
llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
PHI->reserveOperandSpace(2);
PHI->addIncoming(Value, CastNotNull);
PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
CastNull);
Value = PHI;
}
return Value;
}
<commit_msg>Tests now pass with the assertion.<commit_after>//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code dealing with C++ code generation of classes
//
//===----------------------------------------------------------------------===//
#include "CodeGenFunction.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/RecordLayout.h"
using namespace clang;
using namespace CodeGen;
static uint64_t
ComputeNonVirtualBaseClassOffset(ASTContext &Context, CXXBasePaths &Paths,
unsigned Start) {
uint64_t Offset = 0;
const CXXBasePath &Path = Paths.front();
for (unsigned i = Start, e = Path.size(); i != e; ++i) {
const CXXBasePathElement& Element = Path[i];
// Get the layout.
const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
const CXXBaseSpecifier *BS = Element.Base;
assert(!BS->isVirtual() && "Should not see virtual bases here!");
const CXXRecordDecl *Base =
cast<CXXRecordDecl>(BS->getType()->getAs<RecordType>()->getDecl());
// Add the offset.
Offset += Layout.getBaseClassOffset(Base) / 8;
}
return Offset;
}
llvm::Constant *
CodeGenModule::GetCXXBaseClassOffset(const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl) {
if (ClassDecl == BaseClassDecl)
return 0;
CXXBasePaths Paths(/*FindAmbiguities=*/false,
/*RecordPaths=*/true, /*DetectVirtual=*/false);
if (!const_cast<CXXRecordDecl *>(ClassDecl)->
isDerivedFrom(const_cast<CXXRecordDecl *>(BaseClassDecl), Paths)) {
assert(false && "Class must be derived from the passed in base class!");
return 0;
}
uint64_t Offset = ComputeNonVirtualBaseClassOffset(getContext(), Paths, 0);
if (!Offset)
return 0;
const llvm::Type *PtrDiffTy =
Types.ConvertType(getContext().getPointerDiffType());
return llvm::ConstantInt::get(PtrDiffTy, Offset);
}
static llvm::Value *GetCXXBaseClassOffset(CodeGenFunction &CGF,
llvm::Value *BaseValue,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl) {
CXXBasePaths Paths(/*FindAmbiguities=*/false,
/*RecordPaths=*/true, /*DetectVirtual=*/false);
if (!const_cast<CXXRecordDecl *>(ClassDecl)->
isDerivedFrom(const_cast<CXXRecordDecl *>(BaseClassDecl), Paths)) {
assert(false && "Class must be derived from the passed in base class!");
return 0;
}
unsigned Start = 0;
llvm::Value *VirtualOffset = 0;
const CXXBasePath &Path = Paths.front();
const CXXRecordDecl *VBase = 0;
for (unsigned i = 0, e = Path.size(); i != e; ++i) {
const CXXBasePathElement& Element = Path[i];
if (Element.Base->isVirtual()) {
Start = i+1;
QualType VBaseType = Element.Base->getType();
VBase = cast<CXXRecordDecl>(VBaseType->getAs<RecordType>()->getDecl());
}
}
if (VBase)
VirtualOffset =
CGF.GetVirtualCXXBaseClassOffset(BaseValue, ClassDecl, VBase);
uint64_t Offset =
ComputeNonVirtualBaseClassOffset(CGF.getContext(), Paths, Start);
if (!Offset)
return VirtualOffset;
const llvm::Type *PtrDiffTy =
CGF.ConvertType(CGF.getContext().getPointerDiffType());
llvm::Value *NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, Offset);
if (VirtualOffset)
return CGF.Builder.CreateAdd(VirtualOffset, NonVirtualOffset);
return NonVirtualOffset;
}
llvm::Value *
CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl,
bool NullCheckValue) {
QualType BTy =
getContext().getCanonicalType(
getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(BaseClassDecl)));
const llvm::Type *BasePtrTy = llvm::PointerType::getUnqual(ConvertType(BTy));
if (ClassDecl == BaseClassDecl) {
// Just cast back.
return Builder.CreateBitCast(Value, BasePtrTy);
}
llvm::BasicBlock *CastNull = 0;
llvm::BasicBlock *CastNotNull = 0;
llvm::BasicBlock *CastEnd = 0;
if (NullCheckValue) {
CastNull = createBasicBlock("cast.null");
CastNotNull = createBasicBlock("cast.notnull");
CastEnd = createBasicBlock("cast.end");
llvm::Value *IsNull =
Builder.CreateICmpEQ(Value,
llvm::Constant::getNullValue(Value->getType()));
Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
EmitBlock(CastNotNull);
}
const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
llvm::Value *Offset =
GetCXXBaseClassOffset(*this, Value, ClassDecl, BaseClassDecl);
if (Offset) {
// Apply the offset.
Value = Builder.CreateBitCast(Value, Int8PtrTy);
Value = Builder.CreateGEP(Value, Offset, "add.ptr");
}
// Cast back.
Value = Builder.CreateBitCast(Value, BasePtrTy);
if (NullCheckValue) {
Builder.CreateBr(CastEnd);
EmitBlock(CastNull);
Builder.CreateBr(CastEnd);
EmitBlock(CastEnd);
llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
PHI->reserveOperandSpace(2);
PHI->addIncoming(Value, CastNotNull);
PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
CastNull);
Value = PHI;
}
return Value;
}
llvm::Value *
CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *DerivedClassDecl,
bool NullCheckValue) {
QualType DerivedTy =
getContext().getCanonicalType(
getContext().getTypeDeclType(const_cast<CXXRecordDecl*>(DerivedClassDecl)));
const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
if (ClassDecl == DerivedClassDecl) {
// Just cast back.
return Builder.CreateBitCast(Value, DerivedPtrTy);
}
llvm::BasicBlock *CastNull = 0;
llvm::BasicBlock *CastNotNull = 0;
llvm::BasicBlock *CastEnd = 0;
if (NullCheckValue) {
CastNull = createBasicBlock("cast.null");
CastNotNull = createBasicBlock("cast.notnull");
CastEnd = createBasicBlock("cast.end");
llvm::Value *IsNull =
Builder.CreateICmpEQ(Value,
llvm::Constant::getNullValue(Value->getType()));
Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
EmitBlock(CastNotNull);
}
llvm::Value *Offset = GetCXXBaseClassOffset(*this, Value, DerivedClassDecl,
ClassDecl);
if (Offset) {
// Apply the offset.
Value = Builder.CreatePtrToInt(Value, Offset->getType());
Value = Builder.CreateSub(Value, Offset);
Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
} else {
// Just cast.
Value = Builder.CreateBitCast(Value, DerivedPtrTy);
}
if (NullCheckValue) {
Builder.CreateBr(CastEnd);
EmitBlock(CastNull);
Builder.CreateBr(CastEnd);
EmitBlock(CastEnd);
llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
PHI->reserveOperandSpace(2);
PHI->addIncoming(Value, CastNotNull);
PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
CastNull);
Value = PHI;
}
return Value;
}
<|endoftext|> |
<commit_before>#include <string.h>
#include "frogboy.h"
#include "game.h"
#include "entity.h"
#include "bullet.h"
#include "critter.h"
#include "player.h"
#include "particle.h"
#include "sprite.h"
#include "sprites_bitmap.h"
#include "map.h"
#include "camera.h"
#include "door.h"
#include "spawn.h"
#include "text.h"
#include "save.h"
bool pausePressed;
bool resetPressed;
GameMode gameMode;
bool saveFound;
bool titleCursorPressed;
uint8_t titleCursor;
uint8_t wipeProgress;
const uint8_t wipeMasks[] FROGBOY_ROM_DATA = {0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x11, 0x51, 0x55, 0xD5, 0xDD, 0xDF, 0xFF};
typedef void (*GameModeHandler)();
extern const GameModeHandler gameModeUpdateHandlers[] FROGBOY_ROM_DATA;
extern const GameModeHandler gameModeDrawHandlers[] FROGBOY_ROM_DATA;
void gameInit() {
gameMode = GAME_MODE_TITLE;
resetPressed = pausePressed = titleCursorPressed = true;
saveFound = save::exists();
titleCursor = saveFound ? 1 : 0;
}
void gameDraw() {
frogboy::readRom<GameModeHandler>(&gameModeDrawHandlers[gameMode])();
}
void gameUpdate() {
if(frogboy::isPressed(frogboy::BUTTON_RESET)) {
if(!resetPressed) {
gameInit();
return;
}
} else {
if(!frogboy::anyPressed(frogboy::BUTTON_MASK_PAUSE | frogboy::BUTTON_MASK_JUMP | frogboy::BUTTON_MASK_SHOOT)) {
resetPressed = false;
}
}
frogboy::readRom<GameModeHandler>(&gameModeUpdateHandlers[gameMode])();
}
void gameEnterDoor(DoorType door) {
frogboy::playTone(390, 10);
Entity::initSystem();
Critter::initSystem();
Bullet::initSystem();
Particle::initSystem();
spawn::init();
int16_t x = 0;
int16_t y = 0;
door::read(door, x, y, map.currentIndex);
player.add(x, y);
wipeProgress = 0;
camera.reset(camera.x = Entity::data[ENT_OFFSET_PLAYER].x / 16 + 8 - frogboy::SCREEN_WIDTH / 2, 0, map.getWidth(), map.getHeight());
Critter::updateAll();
}
void gameCheckPauseToggle(GameMode nextMode) {
if(frogboy::isPressed(frogboy::BUTTON_PAUSE)) {
if(!pausePressed) {
pausePressed = true;
gameMode = nextMode;
frogboy::playTone(1500, 50);
}
} else {
pausePressed = false;
}
}
void gameModeTitleDraw() {
text::printCenter(64, 8, TEXT_TYPE_TITLE, 1);
text::print(40, 24, TEXT_TYPE_NEW_GAME, 1);
if(saveFound) {
text::print(40, 32, TEXT_TYPE_CONTINUE, 1);
}
sprite::draw(8, 24, player.instance.moveTimer % 32 < 16 ? SPRITE_TYPE_PLAYER_1 : SPRITE_TYPE_PLAYER_2, SPRITE_FLAG_HFLIP);
frogboy::drawTile(31, 24 + titleCursor * 8, spritesBitmap, 0x40, 1, false, false);
text::printCenter(64, 48, TEXT_TYPE_AUTHOR, 1);
}
void gameModeTitleUpdate() {
player.instance.moveTimer++;
if(frogboy::anyPressed(frogboy::BUTTON_MASK_UP | frogboy::BUTTON_MASK_DOWN)) {
if(!titleCursorPressed && saveFound) {
titleCursor ^= 1;
titleCursorPressed = true;
frogboy::playTone(3000, 50);
}
} else {
titleCursorPressed = false;
}
if(!resetPressed && frogboy::isPressed(frogboy::BUTTON_JUMP)) {
gameMode = GAME_MODE_ACTIVE;
// Initialize state before loading the player's save.
player.initSystem();
if(titleCursor == 1) {
// If we fail to load, reset to new game anyways.
if(!save::load()) {
player.initSystem();
}
}
Map::initSystem();
gameEnterDoor(static_cast<DoorType>(player.status.lastDoor));
player.instance.shootPressed = player.instance.jumpPressed = true;
player.update();
}
}
void gameModeActiveDraw() {
map.draw(camera);
Critter::drawAll();
player.draw();
Bullet::drawAll();
Particle::drawAll();
uint8_t mask = frogboy::readRom<uint8_t>(&wipeMasks[wipeProgress >> 2]);
uint8_t* buffer = frogboy::getScreenBuffer();
for(uint16_t i = 0; i != frogboy::SCREEN_WIDTH * (frogboy::SCREEN_HEIGHT / 8); ++i) {
*buffer = *buffer & mask;
buffer++;
}
player.drawHUD();
}
void gameModeActiveUpdate() {
gameCheckPauseToggle(GAME_MODE_PAUSE);
if(wipeProgress < 48) {
wipeProgress++;
if(wipeProgress == 20 && player.status.usedDoor) {
frogboy::playTone(300, 4);
}
}
if(wipeProgress >= 36) {
spawn::check();
Particle::updateAll();
Critter::updateAll();
Bullet::updateAll();
player.update();
camera.update(Entity::data[ENT_OFFSET_PLAYER].x / 16 + 8, 0, map.getWidth(), map.getHeight());
}
if(player.status.nextDoor != 0xFF) {
gameEnterDoor(static_cast<DoorType>(player.status.nextDoor));
player.status.lastDoor = player.status.nextDoor;
player.status.nextDoor = 0xFF;
save::save();
}
}
void gameModePauseDraw() {
gameModeActiveDraw();
for(uint8_t i = 0; i != text::length(TEXT_TYPE_PAUSED) + 1; ++i) {
frogboy::drawTile(32 + i * 8, 24, spritesBitmap, 0x4A, 0, false, false);
}
text::printCenter(64, 24, TEXT_TYPE_PAUSED, 1);
}
void gameModePauseUpdate() {
gameCheckPauseToggle(GAME_MODE_ACTIVE);
}
const GameModeHandler gameModeDrawHandlers[] = {
gameModeTitleDraw,
gameModeActiveDraw,
gameModePauseDraw,
};
const GameModeHandler gameModeUpdateHandlers[] = {
gameModeTitleUpdate,
gameModeActiveUpdate,
gameModePauseUpdate,
};<commit_msg>Fix black box around PAUSED text to add one more character. (the length calculation for the black box used to use sizeof() which included the zero terminator, now it uses the actual length, so we need to add one more)<commit_after>#include <string.h>
#include "frogboy.h"
#include "game.h"
#include "entity.h"
#include "bullet.h"
#include "critter.h"
#include "player.h"
#include "particle.h"
#include "sprite.h"
#include "sprites_bitmap.h"
#include "map.h"
#include "camera.h"
#include "door.h"
#include "spawn.h"
#include "text.h"
#include "save.h"
bool pausePressed;
bool resetPressed;
GameMode gameMode;
bool saveFound;
bool titleCursorPressed;
uint8_t titleCursor;
uint8_t wipeProgress;
const uint8_t wipeMasks[] FROGBOY_ROM_DATA = {0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x11, 0x51, 0x55, 0xD5, 0xDD, 0xDF, 0xFF};
typedef void (*GameModeHandler)();
extern const GameModeHandler gameModeUpdateHandlers[] FROGBOY_ROM_DATA;
extern const GameModeHandler gameModeDrawHandlers[] FROGBOY_ROM_DATA;
void gameInit() {
gameMode = GAME_MODE_TITLE;
resetPressed = pausePressed = titleCursorPressed = true;
saveFound = save::exists();
titleCursor = saveFound ? 1 : 0;
}
void gameDraw() {
frogboy::readRom<GameModeHandler>(&gameModeDrawHandlers[gameMode])();
}
void gameUpdate() {
if(frogboy::isPressed(frogboy::BUTTON_RESET)) {
if(!resetPressed) {
gameInit();
return;
}
} else {
if(!frogboy::anyPressed(frogboy::BUTTON_MASK_PAUSE | frogboy::BUTTON_MASK_JUMP | frogboy::BUTTON_MASK_SHOOT)) {
resetPressed = false;
}
}
frogboy::readRom<GameModeHandler>(&gameModeUpdateHandlers[gameMode])();
}
void gameEnterDoor(DoorType door) {
frogboy::playTone(390, 10);
Entity::initSystem();
Critter::initSystem();
Bullet::initSystem();
Particle::initSystem();
spawn::init();
int16_t x = 0;
int16_t y = 0;
door::read(door, x, y, map.currentIndex);
player.add(x, y);
wipeProgress = 0;
camera.reset(camera.x = Entity::data[ENT_OFFSET_PLAYER].x / 16 + 8 - frogboy::SCREEN_WIDTH / 2, 0, map.getWidth(), map.getHeight());
Critter::updateAll();
}
void gameCheckPauseToggle(GameMode nextMode) {
if(frogboy::isPressed(frogboy::BUTTON_PAUSE)) {
if(!pausePressed) {
pausePressed = true;
gameMode = nextMode;
frogboy::playTone(1500, 50);
}
} else {
pausePressed = false;
}
}
void gameModeTitleDraw() {
text::printCenter(64, 8, TEXT_TYPE_TITLE, 1);
text::print(40, 24, TEXT_TYPE_NEW_GAME, 1);
if(saveFound) {
text::print(40, 32, TEXT_TYPE_CONTINUE, 1);
}
sprite::draw(8, 24, player.instance.moveTimer % 32 < 16 ? SPRITE_TYPE_PLAYER_1 : SPRITE_TYPE_PLAYER_2, SPRITE_FLAG_HFLIP);
frogboy::drawTile(31, 24 + titleCursor * 8, spritesBitmap, 0x40, 1, false, false);
text::printCenter(64, 48, TEXT_TYPE_AUTHOR, 1);
}
void gameModeTitleUpdate() {
player.instance.moveTimer++;
if(frogboy::anyPressed(frogboy::BUTTON_MASK_UP | frogboy::BUTTON_MASK_DOWN)) {
if(!titleCursorPressed && saveFound) {
titleCursor ^= 1;
titleCursorPressed = true;
frogboy::playTone(3000, 50);
}
} else {
titleCursorPressed = false;
}
if(!resetPressed && frogboy::isPressed(frogboy::BUTTON_JUMP)) {
gameMode = GAME_MODE_ACTIVE;
// Initialize state before loading the player's save.
player.initSystem();
if(titleCursor == 1) {
// If we fail to load, reset to new game anyways.
if(!save::load()) {
player.initSystem();
}
}
Map::initSystem();
gameEnterDoor(static_cast<DoorType>(player.status.lastDoor));
player.instance.shootPressed = player.instance.jumpPressed = true;
player.update();
}
}
void gameModeActiveDraw() {
map.draw(camera);
Critter::drawAll();
player.draw();
Bullet::drawAll();
Particle::drawAll();
uint8_t mask = frogboy::readRom<uint8_t>(&wipeMasks[wipeProgress >> 2]);
uint8_t* buffer = frogboy::getScreenBuffer();
for(uint16_t i = 0; i != frogboy::SCREEN_WIDTH * (frogboy::SCREEN_HEIGHT / 8); ++i) {
*buffer = *buffer & mask;
buffer++;
}
player.drawHUD();
}
void gameModeActiveUpdate() {
gameCheckPauseToggle(GAME_MODE_PAUSE);
if(wipeProgress < 48) {
wipeProgress++;
if(wipeProgress == 20 && player.status.usedDoor) {
frogboy::playTone(300, 4);
}
}
if(wipeProgress >= 36) {
spawn::check();
Particle::updateAll();
Critter::updateAll();
Bullet::updateAll();
player.update();
camera.update(Entity::data[ENT_OFFSET_PLAYER].x / 16 + 8, 0, map.getWidth(), map.getHeight());
}
if(player.status.nextDoor != 0xFF) {
gameEnterDoor(static_cast<DoorType>(player.status.nextDoor));
player.status.lastDoor = player.status.nextDoor;
player.status.nextDoor = 0xFF;
save::save();
}
}
void gameModePauseDraw() {
gameModeActiveDraw();
for(uint8_t i = 0; i != text::length(TEXT_TYPE_PAUSED) + 2; ++i) {
frogboy::drawTile(32 + i * 8, 24, spritesBitmap, 0x4A, 0, false, false);
}
text::printCenter(64, 24, TEXT_TYPE_PAUSED, 1);
}
void gameModePauseUpdate() {
gameCheckPauseToggle(GAME_MODE_ACTIVE);
}
const GameModeHandler gameModeDrawHandlers[] = {
gameModeTitleDraw,
gameModeActiveDraw,
gameModePauseDraw,
};
const GameModeHandler gameModeUpdateHandlers[] = {
gameModeTitleUpdate,
gameModeActiveUpdate,
gameModePauseUpdate,
};<|endoftext|> |
<commit_before>#ifndef RPT_XMLHELPER_HXX
#define RPT_XMLHELPER_HXX
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlHelper.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2008-01-29 13:46:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include <xmloff/xmlprmap.hxx>
#endif
#ifndef _XMLOFF_CONTEXTID_HXX_
#include <xmloff/contextid.hxx>
#endif
#ifndef _XMLOFF_FORMS_CONTROLPROPERTYHDL_HXX_
#include <xmloff/controlpropertyhdl.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_REPORT_XREPORTDEFINITION_HPP_
#include <com/sun/star/report/XReportDefinition.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif
#include <memory>
#define CTF_RPT_NUMBERFORMAT (XML_DB_CTF_START + 1)
#define CTF_RPT_PARAVERTALIGNMENT (XML_DB_CTF_START + 2)
#define XML_STYLE_FAMILY_REPORT_ID 700
#define XML_STYLE_FAMILY_REPORT_NAME "report-element"
#define XML_STYLE_FAMILY_REPORT_PREFIX "rptelem"
class SvXMLImport;
class SvXMLExport;
class SvXMLStylesContext;
namespace rptxml
{
class OPropertyHandlerFactory : public ::xmloff::OControlPropertyHandlerFactory
{
OPropertyHandlerFactory(const OPropertyHandlerFactory&);
void operator =(const OPropertyHandlerFactory&);
protected:
mutable ::std::auto_ptr<XMLConstantsPropertyHandler> m_pDisplayHandler;
mutable ::std::auto_ptr<XMLPropertyHandler> m_pTextAlignHandler;
public:
OPropertyHandlerFactory();
virtual ~OPropertyHandlerFactory();
virtual const XMLPropertyHandler* GetPropertyHandler(sal_Int32 _nType) const;
};
class OXMLHelper
{
public:
static UniReference < XMLPropertySetMapper > GetCellStylePropertyMap(bool _bOldFormat = false);
static const SvXMLEnumMapEntry* GetReportPrintOptions();
static const SvXMLEnumMapEntry* GetForceNewPageOptions();
static const SvXMLEnumMapEntry* GetKeepTogetherOptions();
static const SvXMLEnumMapEntry* GetImagePositionOptions();
static const SvXMLEnumMapEntry* GetImageAlignOptions();
static const SvXMLEnumMapEntry* GetCommandTypeOptions();
static const XMLPropertyMapEntry* GetTableStyleProps();
static const XMLPropertyMapEntry* GetColumnStyleProps();
static const XMLPropertyMapEntry* GetRowStyleProps();
static com::sun::star::uno::Reference< com::sun::star::util::XNumberFormatsSupplier > GetNumberFormatsSupplier(const com::sun::star::uno::Reference< com::sun::star::report::XReportDefinition>& _xReportDefinition);
static void copyStyleElements(const ::rtl::OUString& _sStyleName,const SvXMLStylesContext* _pAutoStyles,const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet>& _xProp);
static com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet> createBorderPropertySet();
};
// -----------------------------------------------------------------------------
} // rptxml
// -----------------------------------------------------------------------------
#endif // RPT_XMLHELPER_HXX
<commit_msg>INTEGRATION: CWS rptchart01_DEV300 (1.2.70); FILE MERGED 2008/02/19 09:22:40 oj 1.2.70.3: RESYNC: (1.2-1.3); FILE MERGED 2008/01/25 13:56:00 oj 1.2.70.2: #i85225# export master detail different now 2008/01/24 12:39:32 oj 1.2.70.1: #i85225# changes for chart<commit_after>#ifndef RPT_XMLHELPER_HXX
#define RPT_XMLHELPER_HXX
/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlHelper.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2008-03-05 18:03:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include <xmloff/xmlprmap.hxx>
#endif
#ifndef _XMLOFF_CONTEXTID_HXX_
#include <xmloff/contextid.hxx>
#endif
#ifndef _XMLOFF_FORMS_CONTROLPROPERTYHDL_HXX_
#include <xmloff/controlpropertyhdl.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_REPORT_XREPORTDEFINITION_HPP_
#include <com/sun/star/report/XReportDefinition.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif
#include <memory>
#define CTF_RPT_NUMBERFORMAT (XML_DB_CTF_START + 1)
#define CTF_RPT_PARAVERTALIGNMENT (XML_DB_CTF_START + 2)
#define XML_STYLE_FAMILY_REPORT_ID 700
#define XML_STYLE_FAMILY_REPORT_NAME "report-element"
#define XML_STYLE_FAMILY_REPORT_PREFIX "rptelem"
class SvXMLImport;
class SvXMLExport;
class SvXMLStylesContext;
class SvXMLTokenMap;
namespace rptxml
{
class OPropertyHandlerFactory : public ::xmloff::OControlPropertyHandlerFactory
{
OPropertyHandlerFactory(const OPropertyHandlerFactory&);
void operator =(const OPropertyHandlerFactory&);
protected:
mutable ::std::auto_ptr<XMLConstantsPropertyHandler> m_pDisplayHandler;
mutable ::std::auto_ptr<XMLPropertyHandler> m_pTextAlignHandler;
public:
OPropertyHandlerFactory();
virtual ~OPropertyHandlerFactory();
virtual const XMLPropertyHandler* GetPropertyHandler(sal_Int32 _nType) const;
};
class OXMLHelper
{
public:
static UniReference < XMLPropertySetMapper > GetCellStylePropertyMap(bool _bOldFormat = false);
static const SvXMLEnumMapEntry* GetReportPrintOptions();
static const SvXMLEnumMapEntry* GetForceNewPageOptions();
static const SvXMLEnumMapEntry* GetKeepTogetherOptions();
static const SvXMLEnumMapEntry* GetImagePositionOptions();
static const SvXMLEnumMapEntry* GetImageAlignOptions();
static const SvXMLEnumMapEntry* GetCommandTypeOptions();
static const XMLPropertyMapEntry* GetTableStyleProps();
static const XMLPropertyMapEntry* GetColumnStyleProps();
static const XMLPropertyMapEntry* GetRowStyleProps();
static com::sun::star::uno::Reference< com::sun::star::util::XNumberFormatsSupplier > GetNumberFormatsSupplier(const com::sun::star::uno::Reference< com::sun::star::report::XReportDefinition>& _xReportDefinition);
static void copyStyleElements(const ::rtl::OUString& _sStyleName,const SvXMLStylesContext* _pAutoStyles,const com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet>& _xProp);
static com::sun::star::uno::Reference< com::sun::star::beans::XPropertySet> createBorderPropertySet();
static SvXMLTokenMap* GetReportElemTokenMap();
static SvXMLTokenMap* GetSubDocumentElemTokenMap();
};
// -----------------------------------------------------------------------------
} // rptxml
// -----------------------------------------------------------------------------
#endif // RPT_XMLHELPER_HXX
<|endoftext|> |
<commit_before>/**
* @file
* @brief Implementation of detector
*
* @copyright MIT License
*/
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <Math/Rotation3D.h>
#include <Math/Translation3D.h>
#include "Detector.hpp"
#include "core/module/exceptions.h"
using namespace allpix;
/**
* @throws InvalidModuleActionException If the detector model pointer is a null pointer
*
* Creates a detector without any electric field in the sensor.
*/
Detector::Detector(std::string name,
std::shared_ptr<DetectorModel> model,
ROOT::Math::XYZPoint position,
ROOT::Math::EulerAngles orientation)
: name_(std::move(name)), model_(std::move(model)), position_(std::move(position)), orientation_(orientation),
electric_field_sizes_{{0, 0, 0}}, electric_field_(nullptr) {
// Check if valid model is supplied
if(model_ == nullptr) {
throw InvalidModuleActionException("Detector model cannot be a null pointer");
}
// Build the transformation matrix
build_transform();
}
/**
* This constructor can only be called directly by the \ref GeometryManager to
* instantiate incomplete detectors where the model is added later. It is ensured
* that these detectors can never be accessed by modules before the detector
* model is added.
*/
Detector::Detector(std::string name, ROOT::Math::XYZPoint position, ROOT::Math::EulerAngles orientation)
: name_(std::move(name)), position_(std::move(position)), orientation_(orientation), electric_field_sizes_{{0, 0, 0}},
electric_field_(nullptr) {}
void Detector::set_model(std::shared_ptr<DetectorModel> model) {
model_ = model;
build_transform();
}
void Detector::build_transform() {
// Transform from center to local coordinate
ROOT::Math::Translation3D translation_center(static_cast<ROOT::Math::XYZVector>(position_));
ROOT::Math::Rotation3D rotation_center(orientation_);
ROOT::Math::Transform3D transform_center(rotation_center.Inverse(), translation_center);
// Transform from global to center
ROOT::Math::Translation3D translation_local(static_cast<ROOT::Math::XYZVector>(model_->getCenter()));
ROOT::Math::Transform3D transform_local(translation_local);
// Compute total transform
transform_ = transform_center * transform_local.Inverse();
}
std::string Detector::getName() const {
return name_;
}
std::string Detector::getType() const {
return model_->getType();
}
const std::shared_ptr<DetectorModel> Detector::getModel() const {
return model_;
}
ROOT::Math::XYZPoint Detector::getPosition() const {
return position_;
}
ROOT::Math::EulerAngles Detector::getOrientation() const {
return orientation_;
}
/**
* @warning The local coordinate position does normally not have its origin at the center of rotation
*
* The origin of the local frame is at the center of the first pixel in the middle of the sensor
*/
ROOT::Math::XYZPoint Detector::getLocalPosition(const ROOT::Math::XYZPoint& global_pos) const {
return transform_.Inverse()(global_pos);
}
ROOT::Math::XYZPoint Detector::getGlobalPosition(const ROOT::Math::XYZPoint& local_pos) const {
return transform_(local_pos);
}
/**
* The definition of inside the sensor is determined by the detector model
*/
bool Detector::isWithinSensor(const ROOT::Math::XYZPoint& local_pos) const {
return (
(local_pos.x() >= model_->getSensorMinX() && local_pos.x() <= model_->getSensorMinX() + model_->getSensorSizeX()) &&
(local_pos.y() >= model_->getSensorMinY() && local_pos.y() <= model_->getSensorMinY() + model_->getSensorSizeY()) &&
(local_pos.z() >= model_->getSensorMinZ() && local_pos.z() <= model_->getSensorMinZ() + model_->getSensorSizeZ()));
}
/**
* The electric field is replicated for all pixels and uses flipping at each boundary (side effects are not modeled in this
* stage). Outside of the sensor the electric field is strictly zero by definition.
*/
bool Detector::hasElectricField() const {
return electric_field_sizes_[0] != 0 && electric_field_sizes_[1] != 0 && electric_field_sizes_[2] != 0;
}
/**
* The electric field is replicated for all pixels and uses flipping at each boundary (side effects are not modeled in this
* stage). Outside of the sensor the electric field is strictly zero by definition.
*/
ROOT::Math::XYZVector Detector::getElectricField(const ROOT::Math::XYZPoint& pos) const {
double* field = get_electric_field_raw(pos.x(), pos.y(), pos.z());
if(field == nullptr) {
// FIXME: Determine what we should do if we have no external electric field...
return ROOT::Math::XYZVector(0, 0, 0);
}
return ROOT::Math::XYZVector(*(field), *(field + 1), *(field + 2));
}
/**
* The local position is first converted to pixel coordinates. The stored electric field if the index is odd.
*/
double* Detector::get_electric_field_raw(double x, double y, double z) const {
// FIXME: We need to revisit this to be faster and not too specific
// Compute corresponding pixel indices
auto pixel_x = static_cast<int>(std::round(x / model_->getPixelSizeX()));
auto pixel_y = static_cast<int>(std::round(y / model_->getPixelSizeY()));
// Convert to the pixel frame
x -= pixel_x * model_->getPixelSizeX();
y -= pixel_y * model_->getPixelSizeY();
// Do flipping if necessary
if((pixel_x % 2) == 1) {
x *= -1;
}
if((pixel_y % 2) == 1) {
y *= -1;
}
// Compute indices
auto x_ind = static_cast<int>(std::floor(static_cast<double>(electric_field_sizes_[0]) *
(x + model_->getPixelSizeX() / 2.0) / model_->getPixelSizeX()));
auto y_ind = static_cast<int>(std::floor(static_cast<double>(electric_field_sizes_[1]) *
(y + model_->getPixelSizeY() / 2.0) / model_->getPixelSizeY()));
auto z_ind = static_cast<int>(std::floor(static_cast<double>(electric_field_sizes_[2]) * (z - model_->getSensorMinZ()) /
model_->getSensorSizeZ()));
// Check for indices within the sensor
if(x_ind < 0 || x_ind >= static_cast<int>(electric_field_sizes_[0]) || y_ind < 0 ||
y_ind >= static_cast<int>(electric_field_sizes_[1]) || z_ind < 0 ||
z_ind >= static_cast<int>(electric_field_sizes_[2])) {
return nullptr;
}
// Compute total index
size_t tot_ind = static_cast<size_t>(x_ind) * electric_field_sizes_[1] * electric_field_sizes_[2] * 3 +
static_cast<size_t>(y_ind) * electric_field_sizes_[2] * 3 + static_cast<size_t>(z_ind) * 3;
return &(*electric_field_)[tot_ind];
}
/**
* The electric field is stored as a large flat array. If the sizes are denoted as respectively X_SIZE, Y_ SIZE and Z_SIZE,
* each position (x, y, z) has three indices:
* - x*Y_SIZE*Z_SIZE*3+y*Z_SIZE*3+z*3: the x-component of the electric field
* - x*Y_SIZE*Z_SIZE*3+y*Z_SIZE*3+z*3+1: the y-component of the electric field
* - x*Y_SIZE*Z_SIZE*3+y*Z_SIZE*3+z*3+2: the z-component of the electric field
*/
void Detector::setElectricField(std::shared_ptr<std::vector<double>> field, std::array<size_t, 3> sizes) {
if(sizes[0] * sizes[1] * sizes[2] * 3 != field->size()) {
throw std::invalid_argument("electric field does not match the given sizes");
}
electric_field_ = std::move(field);
electric_field_sizes_ = sizes;
}
<commit_msg>repaired wrong merged conflicts.<commit_after>/**
* @file
* @brief Implementation of detector
*
* @copyright MIT License
*/
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <Math/Rotation3D.h>
#include <Math/Translation3D.h>
#include "Detector.hpp"
#include "core/module/exceptions.h"
using namespace allpix;
/**
* @throws InvalidModuleActionException If the detector model pointer is a null pointer
*
* Creates a detector without any electric field in the sensor.
*/
Detector::Detector(std::string name,
std::shared_ptr<DetectorModel> model,
ROOT::Math::XYZPoint position,
ROOT::Math::EulerAngles orientation)
: Detector(std::move(name), std::move(position), std::move(orientation)) {
model_ = std::move(model);
// Check if valid model is supplied
if(model_ == nullptr) {
throw InvalidModuleActionException("Detector model cannot be a null pointer");
}
// Build the transformation matrix
build_transform();
}
/**
* This constructor can only be called directly by the \ref GeometryManager to
* instantiate incomplete detectors where the model is added later. It is ensured
* that these detectors can never be accessed by modules before the detector
* model is added.
*/
Detector::Detector(std::string name, ROOT::Math::XYZPoint position, ROOT::Math::EulerAngles orientation)
: name_(std::move(name)), position_(std::move(position)), orientation_(orientation), electric_field_sizes_{{0, 0, 0}},
electric_field_(nullptr) {}
void Detector::set_model(std::shared_ptr<DetectorModel> model) {
model_ = model;
build_transform();
}
void Detector::build_transform() {
// Transform from center to local coordinate
ROOT::Math::Translation3D translation_center(static_cast<ROOT::Math::XYZVector>(position_));
ROOT::Math::Rotation3D rotation_center(orientation_);
ROOT::Math::Transform3D transform_center(rotation_center.Inverse(), translation_center);
// Transform from global to center
ROOT::Math::Translation3D translation_local(static_cast<ROOT::Math::XYZVector>(model_->getCenter()));
ROOT::Math::Transform3D transform_local(translation_local);
// Compute total transform
transform_ = transform_center * transform_local.Inverse();
}
std::string Detector::getName() const {
return name_;
}
std::string Detector::getType() const {
return model_->getType();
}
const std::shared_ptr<DetectorModel> Detector::getModel() const {
return model_;
}
ROOT::Math::XYZPoint Detector::getPosition() const {
return position_;
}
ROOT::Math::EulerAngles Detector::getOrientation() const {
return orientation_;
}
/**
* @warning The local coordinate position does normally not have its origin at the center of rotation
*
* The origin of the local frame is at the center of the first pixel in the middle of the sensor
*/
ROOT::Math::XYZPoint Detector::getLocalPosition(const ROOT::Math::XYZPoint& global_pos) const {
return transform_.Inverse()(global_pos);
}
ROOT::Math::XYZPoint Detector::getGlobalPosition(const ROOT::Math::XYZPoint& local_pos) const {
return transform_(local_pos);
}
/**
* The definition of inside the sensor is determined by the detector model
*/
bool Detector::isWithinSensor(const ROOT::Math::XYZPoint& local_pos) const {
return (
(local_pos.x() >= model_->getSensorMinX() && local_pos.x() <= model_->getSensorMinX() + model_->getSensorSizeX()) &&
(local_pos.y() >= model_->getSensorMinY() && local_pos.y() <= model_->getSensorMinY() + model_->getSensorSizeY()) &&
(local_pos.z() >= model_->getSensorMinZ() && local_pos.z() <= model_->getSensorMinZ() + model_->getSensorSizeZ()));
}
/**
* The electric field is replicated for all pixels and uses flipping at each boundary (side effects are not modeled in this
* stage). Outside of the sensor the electric field is strictly zero by definition.
*/
bool Detector::hasElectricField() const {
return electric_field_sizes_[0] != 0 && electric_field_sizes_[1] != 0 && electric_field_sizes_[2] != 0;
}
/**
* The electric field is replicated for all pixels and uses flipping at each boundary (side effects are not modeled in this
* stage). Outside of the sensor the electric field is strictly zero by definition.
*/
ROOT::Math::XYZVector Detector::getElectricField(const ROOT::Math::XYZPoint& pos) const {
double* field = get_electric_field_raw(pos.x(), pos.y(), pos.z());
if(field == nullptr) {
// FIXME: Determine what we should do if we have no external electric field...
return ROOT::Math::XYZVector(0, 0, 0);
}
return ROOT::Math::XYZVector(*(field), *(field + 1), *(field + 2));
}
/**
* The local position is first converted to pixel coordinates. The stored electric field if the index is odd.
*/
double* Detector::get_electric_field_raw(double x, double y, double z) const {
// FIXME: We need to revisit this to be faster and not too specific
// Compute corresponding pixel indices
auto pixel_x = static_cast<int>(std::round(x / model_->getPixelSizeX()));
auto pixel_y = static_cast<int>(std::round(y / model_->getPixelSizeY()));
// Convert to the pixel frame
x -= pixel_x * model_->getPixelSizeX();
y -= pixel_y * model_->getPixelSizeY();
// Do flipping if necessary
if((pixel_x % 2) == 1) {
x *= -1;
}
if((pixel_y % 2) == 1) {
y *= -1;
}
// Compute indices
auto x_ind = static_cast<int>(std::floor(static_cast<double>(electric_field_sizes_[0]) *
(x + model_->getPixelSizeX() / 2.0) / model_->getPixelSizeX()));
auto y_ind = static_cast<int>(std::floor(static_cast<double>(electric_field_sizes_[1]) *
(y + model_->getPixelSizeY() / 2.0) / model_->getPixelSizeY()));
auto z_ind = static_cast<int>(std::floor(static_cast<double>(electric_field_sizes_[2]) * (z - model_->getSensorMinZ()) /
model_->getSensorSizeZ()));
// Check for indices within the sensor
if(x_ind < 0 || x_ind >= static_cast<int>(electric_field_sizes_[0]) || y_ind < 0 ||
y_ind >= static_cast<int>(electric_field_sizes_[1]) || z_ind < 0 ||
z_ind >= static_cast<int>(electric_field_sizes_[2])) {
return nullptr;
}
// Compute total index
size_t tot_ind = static_cast<size_t>(x_ind) * electric_field_sizes_[1] * electric_field_sizes_[2] * 3 +
static_cast<size_t>(y_ind) * electric_field_sizes_[2] * 3 + static_cast<size_t>(z_ind) * 3;
return &(*electric_field_)[tot_ind];
}
/**
* The electric field is stored as a large flat array. If the sizes are denoted as respectively X_SIZE, Y_ SIZE and Z_SIZE,
* each position (x, y, z) has three indices:
* - x*Y_SIZE*Z_SIZE*3+y*Z_SIZE*3+z*3: the x-component of the electric field
* - x*Y_SIZE*Z_SIZE*3+y*Z_SIZE*3+z*3+1: the y-component of the electric field
* - x*Y_SIZE*Z_SIZE*3+y*Z_SIZE*3+z*3+2: the z-component of the electric field
*/
void Detector::setElectricField(std::shared_ptr<std::vector<double>> field, std::array<size_t, 3> sizes) {
if(sizes[0] * sizes[1] * sizes[2] * 3 != field->size()) {
throw std::invalid_argument("electric field does not match the given sizes");
}
electric_field_ = std::move(field);
electric_field_sizes_ = sizes;
}
<|endoftext|> |
<commit_before>#include "LaserRecommend.h"
#include "LaserModel.h"
#include "LaserModelFactory.h"
#include "LaserManager.h"
#include <glog/logging.h>
#include <boost/date_time/posix_time/posix_time.hpp>
namespace sf1r { namespace laser {
LaserRecommend::LaserRecommend(const LaserManager* laserManager)
: laserManager_(laserManager)
, factory_(NULL)
, model_(NULL)
{
factory_ = new LaserModelFactory(*laserManager_);
model_ = factory_->createModel(laserManager_->para_,
laserManager_->workdir_ + "/model/");
}
LaserRecommend::~LaserRecommend()
{
if (NULL != factory_)
{
delete factory_;
factory_ = NULL;
}
if (NULL != model_)
{
delete model_;
model_ = NULL;
}
}
void LaserRecommend::updateAdDimension(const std::size_t adDimension)
{
boost::unique_lock<boost::shared_mutex> uniqueLock(mutex_);
model_->updateAdDimension(adDimension);
}
bool LaserRecommend::recommend(const std::string& text,
std::vector<docid_t>& itemList,
std::vector<float>& itemScoreList,
const std::size_t num) const
{
{
boost::shared_lock<boost::shared_mutex> sharedLock(mutex_, boost::try_to_lock);
if (!sharedLock)
return false;
}
std::vector<std::pair<int, float> > context;
if (!model_->context(text, context))
{
return false;
}
boost::posix_time::ptime stime = boost::posix_time::microsec_clock::local_time();
std::vector<std::pair<docid_t, std::vector<std::pair<int, float> > > > ad;
std::vector<float> score;
if (!model_->candidate(text, 1000, context, ad, score))
{
return false;
}
boost::posix_time::ptime etime = boost::posix_time::microsec_clock::local_time();
LOG(INFO)<<"candidate time = "<<(etime-stime).total_milliseconds()<<"\t ad size = "<<ad.size();
priority_queue queue;
stime = boost::posix_time::microsec_clock::local_time();
for (std::size_t i = 0; i < ad.size(); ++i)
{
topn(ad[i].first, model_->score(text, context, ad[i], score[i]), num, queue);
//model_->score(text, context, ad[i], score[i]);
}
etime = boost::posix_time::microsec_clock::local_time();
LOG(INFO)<<"score time = "<<(etime-stime).total_milliseconds();
{
while (!queue.empty())
{
itemList.push_back(queue.top().first);
itemScoreList.push_back(queue.top().second);
queue.pop();
}
}
return true;
}
void LaserRecommend::topn(const docid_t& docid, const float score, const std::size_t n, priority_queue& queue) const
{
if(queue.size() >= n)
{
if(score > queue.top().second)
{
queue.pop();
queue.push(std::make_pair(docid, score));
}
}
else
{
queue.push(std::make_pair(docid, score));
}
}
void LaserRecommend::dispatch(const std::string& method, msgpack::rpc::request& req)
{
model_->dispatch(method, req);
}
} }
<commit_msg>add final step to ctr: 1 / (1 + exp(-1 x)), reverse result to make first the most ctr<commit_after>#include "LaserRecommend.h"
#include "LaserModel.h"
#include "LaserModelFactory.h"
#include "LaserManager.h"
#include <glog/logging.h>
#include <boost/date_time/posix_time/posix_time.hpp>
namespace sf1r { namespace laser {
LaserRecommend::LaserRecommend(const LaserManager* laserManager)
: laserManager_(laserManager)
, factory_(NULL)
, model_(NULL)
{
factory_ = new LaserModelFactory(*laserManager_);
model_ = factory_->createModel(laserManager_->para_,
laserManager_->workdir_ + "/model/");
}
LaserRecommend::~LaserRecommend()
{
if (NULL != factory_)
{
delete factory_;
factory_ = NULL;
}
if (NULL != model_)
{
delete model_;
model_ = NULL;
}
}
void LaserRecommend::updateAdDimension(const std::size_t adDimension)
{
boost::unique_lock<boost::shared_mutex> uniqueLock(mutex_);
model_->updateAdDimension(adDimension);
}
bool LaserRecommend::recommend(const std::string& text,
std::vector<docid_t>& itemList,
std::vector<float>& itemScoreList,
const std::size_t num) const
{
{
boost::shared_lock<boost::shared_mutex> sharedLock(mutex_, boost::try_to_lock);
if (!sharedLock)
return false;
}
std::vector<std::pair<int, float> > context;
if (!model_->context(text, context))
{
return false;
}
boost::posix_time::ptime stime = boost::posix_time::microsec_clock::local_time();
std::vector<std::pair<docid_t, std::vector<std::pair<int, float> > > > ad;
std::vector<float> score;
if (!model_->candidate(text, 1000, context, ad, score))
{
return false;
}
boost::posix_time::ptime etime = boost::posix_time::microsec_clock::local_time();
LOG(INFO)<<"candidate time = "<<(etime-stime).total_milliseconds()<<"\t ad size = "<<ad.size();
priority_queue queue;
stime = boost::posix_time::microsec_clock::local_time();
for (std::size_t i = 0; i < ad.size(); ++i)
{
topn(ad[i].first, model_->score(text, context, ad[i], score[i]), num, queue);
//model_->score(text, context, ad[i], score[i]);
}
etime = boost::posix_time::microsec_clock::local_time();
LOG(INFO)<<"score time = "<<(etime-stime).total_milliseconds();
{
while (!queue.empty())
{
itemList.push_back(queue.top().first);
itemScoreList.push_back(1.0 / (1 + exp(-1 * queue.top().second)));
//itemScoreList.push_back(queue.top().second);
queue.pop();
}
}
std::reverse(itemList.begin(), itemList.end());
std::reverse(itemScoreList.begin(), itemScoreList.end());
return true;
}
void LaserRecommend::topn(const docid_t& docid, const float score, const std::size_t n, priority_queue& queue) const
{
if(queue.size() >= n)
{
if(score > queue.top().second)
{
queue.pop();
queue.push(std::make_pair(docid, score));
}
}
else
{
queue.push(std::make_pair(docid, score));
}
}
void LaserRecommend::dispatch(const std::string& method, msgpack::rpc::request& req)
{
model_->dispatch(method, req);
}
} }
<|endoftext|> |
<commit_before>#include "defs.h"
#include "search.h"
#include "eval.h"
#include "movegen.h"
#include "transptable.h"
#include <string>
#include <algorithm>
#include <time.h>
#include <iostream>
Search::Search(const Board& board, int depth, int maxTime, bool logUci) {
_logUci = logUci;
_iterDeep(board, depth, maxTime);
}
void Search::_iterDeep(const Board& board, int maxDepth, int maxTime) {
_tt.clear();
int timeRemaining = maxTime;
clock_t startTime;
MoveBoardList pv;
for(int currDepth=1;currDepth<=maxDepth;currDepth++) {
startTime = clock();
_rootMax(board, currDepth);
clock_t timeTaken = clock() - startTime;
timeRemaining -= (float(timeTaken) / CLOCKS_PER_SEC)*1000;
pv = _getPv(board);
if (_logUci) {
_logUciInfo(pv, currDepth, _bestMove, _bestScore);
}
if (timeRemaining < 0) {
return;
}
}
}
void Search::_logUciInfo(const MoveBoardList& pv, int depth, CMove bestMove, int bestScore) {
std::string pvString;
for(auto moveBoard : pv) {
pvString += moveBoard.first.getNotation() + " ";
}
std::string scoreString;
if (bestScore == INF) {
scoreString = "mate " + std::to_string(pv.size());
} else if (_bestScore == -INF) {
scoreString = "mate -" + std::to_string(pv.size());
} else {
scoreString = "cp " + std::to_string(bestScore);
}
std::cout << "info depth " + std::to_string(depth) + " ";
std::cout << "score " + scoreString + " ";
std::cout << "pv " + pvString;
std::cout << std::endl;
}
MoveBoardList Search::_getPv(const Board& board) {
if (!_tt.contains(board.getZKey())) {
return MoveBoardList();
}
int scoreToFind = -_tt.getScore(board.getZKey());
ZKey movedZKey;
for (auto moveBoard : MoveGen(board).getLegalMoves()) {
Board movedBoard = moveBoard.second;
movedZKey = movedBoard.getZKey();
if (_tt.contains(movedZKey) && _tt.getScore(movedZKey) == scoreToFind) {
MoveBoardList pvList = _getPv(moveBoard.second);
pvList.insert(pvList.begin(), moveBoard);
return pvList;
}
}
return MoveBoardList();
}
CMove Search::getBestMove() {
return _bestMove;
}
void Search::_rootMax(const Board& board, int depth) {
MoveGen movegen(board);
MoveBoardList legalMoves = movegen.getLegalMoves();
_orderMoves(legalMoves);
int bestScore = -INF;
int currScore;
CMove bestMove;
for (auto moveBoard : legalMoves) {
CMove move = moveBoard.first;
Board movedBoard = moveBoard.second;
currScore = -_negaMax(movedBoard, depth-1, bestScore, INF);
if (currScore > bestScore) {
bestMove = move;
bestScore = currScore;
}
}
// If we couldn't find a path other than checkmate, just pick the first legal move
if (bestMove.getFlags() & CMove::NULL_MOVE) {
bestMove = legalMoves.at(0).first;
}
_tt.set(board.getZKey(), bestScore, depth, TranspTable::EXACT);
_bestMove = bestMove;
_bestScore = bestScore;
}
void Search::_orderMoves(MoveBoardList& moveBoardList) {
std::sort(moveBoardList.begin(), moveBoardList.end(), [this](MoveBoard a, MoveBoard b) {
ZKey aKey = a.second.getZKey();
ZKey bKey = b.second.getZKey();
int aScore = _tt.contains(aKey) ? _tt.getScore(aKey) : -INF;
int bScore = _tt.contains(bKey) ? _tt.getScore(bKey) : -INF;
return aScore < bScore;
});
}
void Search::_orderMovesQSearch(MoveBoardList & moveBoardList) {
std::sort(moveBoardList.begin(), moveBoardList.end(), [this](MoveBoard a, MoveBoard b) {
bool aIsCapture = a.first.getFlags() & CMove::CAPTURE;
bool bIsCapture = b.first.getFlags() & CMove::CAPTURE;
if (aIsCapture && !bIsCapture) {
return true;
} else if (bIsCapture && !aIsCapture) {
return false;
} else { // Both captures
// MVV/LVA
int aPieceValue = _getPieceValue(a.first.getPieceType());
int bPieceValue = _getPieceValue(b.first.getPieceType());
int aCaptureValue = _getPieceValue(a.first.getCapturedPieceType());
int bCaptureValue = _getPieceValue(b.first.getCapturedPieceType());
return (aCaptureValue - aPieceValue) > (bCaptureValue - bPieceValue);
}
});
}
int Search::_getPieceValue(PieceType pieceType) {
int score = 0;
switch(pieceType) {
case PAWN: score = 1;
break;
case KNIGHT: score = 3;
break;
case BISHOP: score = 3;
break;
case ROOK: score = 5;
break;
case QUEEN: score = 9;
break;
default: break;
}
return score;
}
int Search::_negaMax(const Board& board, int depth, int alpha, int beta) {
int alphaOrig = alpha;
ZKey zKey = board.getZKey();
// Check transposition table cache
if (_tt.contains(zKey) && (_tt.getDepth(zKey) >= depth)) {
switch(_tt.getFlag(zKey)) {
case TranspTable::EXACT:
return _tt.getScore(zKey);
case TranspTable::UPPER_BOUND:
alpha = std::max(alpha, _tt.getScore(zKey));
break;
case TranspTable::LOWER_BOUND:
beta = std::min(beta, _tt.getScore(zKey));
break;
}
if (alpha > beta) {
return _tt.getScore(zKey);
}
}
// Transposition table lookups are inconclusive, generate moves and recurse
MoveGen movegen(board);
MoveBoardList legalMoves = movegen.getLegalMoves();
_orderMoves(legalMoves);
// Check for checkmate
if (legalMoves.size() == 0 && board.colorIsInCheck(board.getActivePlayer())) {
_tt.set(board.getZKey(), -INF, depth, TranspTable::EXACT);
return -INF;
}
// Eval if depth is 0
if (depth == 0) {
int score = _qSearch(board, -INF, INF);
_tt.set(board.getZKey(), score, 0, TranspTable::EXACT);
return score;
}
int bestScore = -INF;
for (auto moveBoard : legalMoves) {
Board movedBoard = moveBoard.second;
bestScore = std::max(bestScore, -_negaMax(movedBoard, depth-1, -beta, -alpha));
alpha = std::max(alpha, bestScore);
if (alpha > beta) {
break;
}
}
// Store bestScore in transposition table
TranspTable::Flag flag;
if (bestScore < alphaOrig) {
flag = TranspTable::UPPER_BOUND;
} else if (bestScore >= beta) {
flag = TranspTable::LOWER_BOUND;
} else {
flag = TranspTable::EXACT;
}
_tt.set(zKey, bestScore, depth, flag);
return bestScore;
}
int Search::_qSearch(const Board& board, int alpha, int beta) {
int standPat = Eval(board, board.getActivePlayer()).getScore();
if (standPat >= beta) {
return beta;
}
if (alpha < standPat) {
alpha = standPat;
}
MoveGen movegen(board);
MoveBoardList legalMoves = movegen.getLegalMoves();
_orderMovesQSearch(legalMoves);
for (auto moveBoard : legalMoves) {
CMove move = moveBoard.first;
Board movedBoard = moveBoard.second;
if ((move.getFlags() & CMove::CAPTURE) == 0) {
break;
}
int score = -_qSearch(movedBoard, -beta, -alpha);
if (score >= beta) {
return beta;
}
if (score > alpha) {
alpha = score;
}
}
return alpha;
}
<commit_msg>Check for checkmate in _qSearch<commit_after>#include "defs.h"
#include "search.h"
#include "eval.h"
#include "movegen.h"
#include "transptable.h"
#include <string>
#include <algorithm>
#include <time.h>
#include <iostream>
Search::Search(const Board& board, int depth, int maxTime, bool logUci) {
_logUci = logUci;
_iterDeep(board, depth, maxTime);
}
void Search::_iterDeep(const Board& board, int maxDepth, int maxTime) {
_tt.clear();
int timeRemaining = maxTime;
clock_t startTime;
MoveBoardList pv;
for(int currDepth=1;currDepth<=maxDepth;currDepth++) {
startTime = clock();
_rootMax(board, currDepth);
clock_t timeTaken = clock() - startTime;
timeRemaining -= (float(timeTaken) / CLOCKS_PER_SEC)*1000;
pv = _getPv(board);
if (_logUci) {
_logUciInfo(pv, currDepth, _bestMove, _bestScore);
}
if (timeRemaining < 0) {
return;
}
}
}
void Search::_logUciInfo(const MoveBoardList& pv, int depth, CMove bestMove, int bestScore) {
std::string pvString;
for(auto moveBoard : pv) {
pvString += moveBoard.first.getNotation() + " ";
}
std::string scoreString;
if (bestScore == INF) {
scoreString = "mate " + std::to_string(pv.size());
} else if (_bestScore == -INF) {
scoreString = "mate -" + std::to_string(pv.size());
} else {
scoreString = "cp " + std::to_string(bestScore);
}
std::cout << "info depth " + std::to_string(depth) + " ";
std::cout << "score " + scoreString + " ";
std::cout << "pv " + pvString;
std::cout << std::endl;
}
MoveBoardList Search::_getPv(const Board& board) {
if (!_tt.contains(board.getZKey())) {
return MoveBoardList();
}
int scoreToFind = -_tt.getScore(board.getZKey());
ZKey movedZKey;
for (auto moveBoard : MoveGen(board).getLegalMoves()) {
Board movedBoard = moveBoard.second;
movedZKey = movedBoard.getZKey();
if (_tt.contains(movedZKey) && _tt.getScore(movedZKey) == scoreToFind) {
MoveBoardList pvList = _getPv(moveBoard.second);
pvList.insert(pvList.begin(), moveBoard);
return pvList;
}
}
return MoveBoardList();
}
CMove Search::getBestMove() {
return _bestMove;
}
void Search::_rootMax(const Board& board, int depth) {
MoveGen movegen(board);
MoveBoardList legalMoves = movegen.getLegalMoves();
_orderMoves(legalMoves);
int bestScore = -INF;
int currScore;
CMove bestMove;
for (auto moveBoard : legalMoves) {
CMove move = moveBoard.first;
Board movedBoard = moveBoard.second;
currScore = -_negaMax(movedBoard, depth-1, bestScore, INF);
if (currScore > bestScore) {
bestMove = move;
bestScore = currScore;
}
}
// If we couldn't find a path other than checkmate, just pick the first legal move
if (bestMove.getFlags() & CMove::NULL_MOVE) {
bestMove = legalMoves.at(0).first;
}
_tt.set(board.getZKey(), bestScore, depth, TranspTable::EXACT);
_bestMove = bestMove;
_bestScore = bestScore;
}
void Search::_orderMoves(MoveBoardList& moveBoardList) {
std::sort(moveBoardList.begin(), moveBoardList.end(), [this](MoveBoard a, MoveBoard b) {
ZKey aKey = a.second.getZKey();
ZKey bKey = b.second.getZKey();
int aScore = _tt.contains(aKey) ? _tt.getScore(aKey) : -INF;
int bScore = _tt.contains(bKey) ? _tt.getScore(bKey) : -INF;
return aScore < bScore;
});
}
void Search::_orderMovesQSearch(MoveBoardList & moveBoardList) {
std::sort(moveBoardList.begin(), moveBoardList.end(), [this](MoveBoard a, MoveBoard b) {
bool aIsCapture = a.first.getFlags() & CMove::CAPTURE;
bool bIsCapture = b.first.getFlags() & CMove::CAPTURE;
if (aIsCapture && !bIsCapture) {
return true;
} else if (bIsCapture && !aIsCapture) {
return false;
} else { // Both captures
// MVV/LVA
int aPieceValue = _getPieceValue(a.first.getPieceType());
int bPieceValue = _getPieceValue(b.first.getPieceType());
int aCaptureValue = _getPieceValue(a.first.getCapturedPieceType());
int bCaptureValue = _getPieceValue(b.first.getCapturedPieceType());
return (aCaptureValue - aPieceValue) > (bCaptureValue - bPieceValue);
}
});
}
int Search::_getPieceValue(PieceType pieceType) {
int score = 0;
switch(pieceType) {
case PAWN: score = 1;
break;
case KNIGHT: score = 3;
break;
case BISHOP: score = 3;
break;
case ROOK: score = 5;
break;
case QUEEN: score = 9;
break;
default: break;
}
return score;
}
int Search::_negaMax(const Board& board, int depth, int alpha, int beta) {
int alphaOrig = alpha;
ZKey zKey = board.getZKey();
// Check transposition table cache
if (_tt.contains(zKey) && (_tt.getDepth(zKey) >= depth)) {
switch(_tt.getFlag(zKey)) {
case TranspTable::EXACT:
return _tt.getScore(zKey);
case TranspTable::UPPER_BOUND:
alpha = std::max(alpha, _tt.getScore(zKey));
break;
case TranspTable::LOWER_BOUND:
beta = std::min(beta, _tt.getScore(zKey));
break;
}
if (alpha > beta) {
return _tt.getScore(zKey);
}
}
// Transposition table lookups are inconclusive, generate moves and recurse
MoveGen movegen(board);
MoveBoardList legalMoves = movegen.getLegalMoves();
_orderMoves(legalMoves);
// Check for checkmate
if (legalMoves.size() == 0 && board.colorIsInCheck(board.getActivePlayer())) {
_tt.set(board.getZKey(), -INF, depth, TranspTable::EXACT);
return -INF;
}
// Eval if depth is 0
if (depth == 0) {
int score = _qSearch(board, -INF, INF);
_tt.set(board.getZKey(), score, 0, TranspTable::EXACT);
return score;
}
int bestScore = -INF;
for (auto moveBoard : legalMoves) {
Board movedBoard = moveBoard.second;
bestScore = std::max(bestScore, -_negaMax(movedBoard, depth-1, -beta, -alpha));
alpha = std::max(alpha, bestScore);
if (alpha > beta) {
break;
}
}
// Store bestScore in transposition table
TranspTable::Flag flag;
if (bestScore < alphaOrig) {
flag = TranspTable::UPPER_BOUND;
} else if (bestScore >= beta) {
flag = TranspTable::LOWER_BOUND;
} else {
flag = TranspTable::EXACT;
}
_tt.set(zKey, bestScore, depth, flag);
return bestScore;
}
int Search::_qSearch(const Board& board, int alpha, int beta) {
MoveGen movegen(board);
MoveBoardList legalMoves = movegen.getLegalMoves();
// Check for checkmate
if (legalMoves.size() == 0 && board.colorIsInCheck(board.getActivePlayer())) {
return -INF;
}
int standPat = Eval(board, board.getActivePlayer()).getScore();
if (standPat >= beta) {
return beta;
}
if (alpha < standPat) {
alpha = standPat;
}
_orderMovesQSearch(legalMoves);
for (auto moveBoard : legalMoves) {
CMove move = moveBoard.first;
Board movedBoard = moveBoard.second;
if ((move.getFlags() & CMove::CAPTURE) == 0) {
break;
}
int score = -_qSearch(movedBoard, -beta, -alpha);
if (score >= beta) {
return beta;
}
if (score > alpha) {
alpha = score;
}
}
return alpha;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* moon.cxx
* Written by Durk Talsma. Originally started October 1997, for distribution
* with the FlightGear project. Version 2 was written in August and
* September 1998. This code is based upon algorithms and data kindly
* provided by Mr. Paul Schlyter. (pausch@saaf.se).
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
* (Log is kept at end of this file)
**************************************************************************/
#include <FDM/flight.hxx>
#include <string.h>
#include "moon.hxx"
#include <Debug/logstream.hxx>
#include <Objects/texload.h>
#ifdef __BORLANDC__
# define exception c_exception
#endif
#include <math.h>
static GLuint moon_texid;
static GLubyte *moon_texbuf;
/*************************************************************************
* Moon::Moon(fgTIME *t)
* Public constructor for class Moon. Initializes the orbital elements and
* sets up the moon texture.
* Argument: The current time.
* the hard coded orbital elements for Moon are passed to
* CelestialBody::CelestialBody();
************************************************************************/
Moon::Moon(fgTIME *t) :
CelestialBody(125.1228, -0.0529538083,
5.1454, 0.00000,
318.0634, 0.1643573223,
60.266600, 0.000000,
0.054900, 0.000000,
115.3654, 13.0649929509, t)
{
string tpath, fg_tpath;
int width, height;
FG_LOG( FG_GENERAL, FG_INFO, "Initializing Moon Texture");
#ifdef GL_VERSION_1_1
xglGenTextures(1, &moon_texid);
xglBindTexture(GL_TEXTURE_2D, moon_texid);
#elif GL_EXT_texture_object
xglGenTexturesEXT(1, &moon_texid);
xglBindTextureEXT(GL_TEXTURE_2D, moon_texid);
#else
# error port me
#endif
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load in the texture data
tpath = current_options.get_fg_root() + "/Textures/" + "moon.rgb";
if ( (moon_texbuf = read_rgb_texture(tpath.c_str(), &width, &height))
== NULL )
{
// Try compressed
fg_tpath = tpath + ".gz";
if ( (moon_texbuf = read_rgb_texture(fg_tpath.c_str(), &width, &height))
== NULL )
{
FG_LOG( FG_GENERAL, FG_ALERT,
"Error in loading moon texture " << tpath );
exit(-1);
}
}
glTexImage2D( GL_TEXTURE_2D,
0,
GL_RGB,
256, 256,
0,
GL_RGB, GL_UNSIGNED_BYTE,
moon_texbuf);
}
/*****************************************************************************
* void Moon::updatePosition(fgTIME *t, Star *ourSun)
* this member function calculates the actual topocentric position (i.e.)
* the position of the moon as seen from the current position on the surface
* of the moon.
****************************************************************************/
void Moon::updatePosition(fgTIME *t, Star *ourSun)
{
double
eccAnom, ecl, lonecl, latecl, actTime,
xv, yv, v, r, xh, yh, zh, xg, yg, zg, xe, ye, ze,
Ls, Lm, D, F, mpar, gclat, rho, HA, g,
geoRa, geoDec;
fgAIRCRAFT *air;
FGInterface *f;
air = ¤t_aircraft;
f = air->fdm_state;
updateOrbElements(t);
actTime = fgCalcActTime(t);
// calculate the angle between ecliptic and equatorial coordinate system
// in Radians
ecl = ((DEG_TO_RAD * 23.4393) - (DEG_TO_RAD * 3.563E-7) * actTime);
eccAnom = fgCalcEccAnom(M, e); // Calculate the eccentric anomaly
xv = a * (cos(eccAnom) - e);
yv = a * (sqrt(1.0 - e*e) * sin(eccAnom));
v = atan2(yv, xv); // the moon's true anomaly
r = sqrt (xv*xv + yv*yv); // and its distance
// estimate the geocentric rectangular coordinates here
xh = r * (cos(N) * cos (v+w) - sin (N) * sin(v+w) * cos(i));
yh = r * (sin(N) * cos (v+w) + cos (N) * sin(v+w) * cos(i));
zh = r * (sin(v+w) * sin(i));
// calculate the ecliptic latitude and longitude here
lonecl = atan2 (yh, xh);
latecl = atan2(zh, sqrt(xh*xh + yh*yh));
/* Calculate a number of perturbatioin, i.e. disturbances caused by the
* gravitational infuence of the sun and the other major planets.
* The largest of these even have a name */
Ls = ourSun->getM() + ourSun->getw();
Lm = M + w + N;
D = Lm - Ls;
F = Lm - N;
lonecl += DEG_TO_RAD * (-1.274 * sin (M - 2*D)
+0.658 * sin (2*D)
-0.186 * sin(ourSun->getM())
-0.059 * sin(2*M - 2*D)
-0.057 * sin(M - 2*D + ourSun->getM())
+0.053 * sin(M + 2*D)
+0.046 * sin(2*D - ourSun->getM())
+0.041 * sin(M - ourSun->getM())
-0.035 * sin(D)
-0.031 * sin(M + ourSun->getM())
-0.015 * sin(2*F - 2*D)
+0.011 * sin(M - 4*D)
);
latecl += DEG_TO_RAD * (-0.173 * sin(F-2*D)
-0.055 * sin(M - F - 2*D)
-0.046 * sin(M + F - 2*D)
+0.033 * sin(F + 2*D)
+0.017 * sin(2*M + F)
);
r += (-0.58 * cos(M - 2*D)
-0.46 * cos(2*D)
);
FG_LOG(FG_GENERAL, FG_INFO, "Running moon update");
xg = r * cos(lonecl) * cos(latecl);
yg = r * sin(lonecl) * cos(latecl);
zg = r * sin(latecl);
xe = xg;
ye = yg * cos(ecl) -zg * sin(ecl);
ze = yg * sin(ecl) +zg * cos(ecl);
geoRa = atan2(ye, xe);
geoDec = atan2(ze, sqrt(xe*xe + ye*ye));
// Given the moon's geocentric ra and dec, calculate its
// topocentric ra and dec. i.e. the position as seen from the
// surface of the earth, instead of the center of the earth
// First calculates the moon's parrallax, that is, the apparent size of the
// (equatorial) radius of the earth, as seen from the moon
mpar = asin ( 1 / r);
gclat = f->get_Latitude() - 0.003358 *
sin (2 * DEG_TO_RAD * f->get_Latitude() );
rho = 0.99883 + 0.00167 * cos(2 * DEG_TO_RAD * f->get_Latitude());
if (geoRa < 0)
geoRa += (2*FG_PI);
HA = t->lst - (3.8197186 * geoRa);
g = atan (tan(gclat) / cos ((HA / 3.8197186)));
rightAscension = geoRa - mpar * rho * cos(gclat) * sin(HA) / cos (geoDec);
declination = geoDec - mpar * rho * sin (gclat) * sin (g - geoDec) / sin(g);
}
/************************************************************************
* void Moon::newImage(float ra, float dec)
*
* This function regenerates a new visual image of the moon, which is added to
* solarSystem display list.
*
* Arguments: Right Ascension and declination
*
* return value: none
**************************************************************************/
void Moon::newImage(float ra, float dec)
{
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBindTexture(GL_TEXTURE_2D, moon_texid);
//xglRotatef(-90, 0.0, 0.0, 1.0);
xglRotatef(((RAD_TO_DEG * ra)- 90.0), 0.0, 0.0, 1.0);
xglRotatef((RAD_TO_DEG * dec), 1.0, 0.0, 0.0);
FG_LOG( FG_GENERAL, FG_INFO,
"Ra = (" << (RAD_TO_DEG *ra)
<< "), Dec= (" << (RAD_TO_DEG *dec) << ")" );
xglTranslatef(0.0, 58600.0, 0.0);
Object = gluNewQuadric();
gluQuadricTexture( Object, GL_TRUE );
gluSphere( Object, 1367, 12, 12 );
glDisable(GL_TEXTURE_2D);
}
<commit_msg>Added initial support for native SGI compilers.<commit_after>/**************************************************************************
* moon.cxx
* Written by Durk Talsma. Originally started October 1997, for distribution
* with the FlightGear project. Version 2 was written in August and
* September 1998. This code is based upon algorithms and data kindly
* provided by Mr. Paul Schlyter. (pausch@saaf.se).
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
* (Log is kept at end of this file)
**************************************************************************/
#include <string.h>
#include <Debug/logstream.hxx>
#include <Objects/texload.h>
#include <FDM/flight.hxx>
#ifdef __BORLANDC__
# define exception c_exception
#endif
#include <math.h>
#include "moon.hxx"
static GLuint moon_texid;
static GLubyte *moon_texbuf;
/*************************************************************************
* Moon::Moon(fgTIME *t)
* Public constructor for class Moon. Initializes the orbital elements and
* sets up the moon texture.
* Argument: The current time.
* the hard coded orbital elements for Moon are passed to
* CelestialBody::CelestialBody();
************************************************************************/
Moon::Moon(fgTIME *t) :
CelestialBody(125.1228, -0.0529538083,
5.1454, 0.00000,
318.0634, 0.1643573223,
60.266600, 0.000000,
0.054900, 0.000000,
115.3654, 13.0649929509, t)
{
string tpath, fg_tpath;
int width, height;
FG_LOG( FG_GENERAL, FG_INFO, "Initializing Moon Texture");
#ifdef GL_VERSION_1_1
xglGenTextures(1, &moon_texid);
xglBindTexture(GL_TEXTURE_2D, moon_texid);
#elif GL_EXT_texture_object
xglGenTexturesEXT(1, &moon_texid);
xglBindTextureEXT(GL_TEXTURE_2D, moon_texid);
#else
# error port me
#endif
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load in the texture data
tpath = current_options.get_fg_root() + "/Textures/" + "moon.rgb";
if ( (moon_texbuf = read_rgb_texture(tpath.c_str(), &width, &height))
== NULL )
{
// Try compressed
fg_tpath = tpath + ".gz";
if ( (moon_texbuf = read_rgb_texture(fg_tpath.c_str(), &width, &height))
== NULL )
{
FG_LOG( FG_GENERAL, FG_ALERT,
"Error in loading moon texture " << tpath );
exit(-1);
}
}
glTexImage2D( GL_TEXTURE_2D,
0,
GL_RGB,
256, 256,
0,
GL_RGB, GL_UNSIGNED_BYTE,
moon_texbuf);
}
/*****************************************************************************
* void Moon::updatePosition(fgTIME *t, Star *ourSun)
* this member function calculates the actual topocentric position (i.e.)
* the position of the moon as seen from the current position on the surface
* of the moon.
****************************************************************************/
void Moon::updatePosition(fgTIME *t, Star *ourSun)
{
double
eccAnom, ecl, lonecl, latecl, actTime,
xv, yv, v, r, xh, yh, zh, xg, yg, zg, xe, ye, ze,
Ls, Lm, D, F, mpar, gclat, rho, HA, g,
geoRa, geoDec;
fgAIRCRAFT *air;
FGInterface *f;
air = ¤t_aircraft;
f = air->fdm_state;
updateOrbElements(t);
actTime = fgCalcActTime(t);
// calculate the angle between ecliptic and equatorial coordinate system
// in Radians
ecl = ((DEG_TO_RAD * 23.4393) - (DEG_TO_RAD * 3.563E-7) * actTime);
eccAnom = fgCalcEccAnom(M, e); // Calculate the eccentric anomaly
xv = a * (cos(eccAnom) - e);
yv = a * (sqrt(1.0 - e*e) * sin(eccAnom));
v = atan2(yv, xv); // the moon's true anomaly
r = sqrt (xv*xv + yv*yv); // and its distance
// estimate the geocentric rectangular coordinates here
xh = r * (cos(N) * cos (v+w) - sin (N) * sin(v+w) * cos(i));
yh = r * (sin(N) * cos (v+w) + cos (N) * sin(v+w) * cos(i));
zh = r * (sin(v+w) * sin(i));
// calculate the ecliptic latitude and longitude here
lonecl = atan2 (yh, xh);
latecl = atan2(zh, sqrt(xh*xh + yh*yh));
/* Calculate a number of perturbatioin, i.e. disturbances caused by the
* gravitational infuence of the sun and the other major planets.
* The largest of these even have a name */
Ls = ourSun->getM() + ourSun->getw();
Lm = M + w + N;
D = Lm - Ls;
F = Lm - N;
lonecl += DEG_TO_RAD * (-1.274 * sin (M - 2*D)
+0.658 * sin (2*D)
-0.186 * sin(ourSun->getM())
-0.059 * sin(2*M - 2*D)
-0.057 * sin(M - 2*D + ourSun->getM())
+0.053 * sin(M + 2*D)
+0.046 * sin(2*D - ourSun->getM())
+0.041 * sin(M - ourSun->getM())
-0.035 * sin(D)
-0.031 * sin(M + ourSun->getM())
-0.015 * sin(2*F - 2*D)
+0.011 * sin(M - 4*D)
);
latecl += DEG_TO_RAD * (-0.173 * sin(F-2*D)
-0.055 * sin(M - F - 2*D)
-0.046 * sin(M + F - 2*D)
+0.033 * sin(F + 2*D)
+0.017 * sin(2*M + F)
);
r += (-0.58 * cos(M - 2*D)
-0.46 * cos(2*D)
);
FG_LOG(FG_GENERAL, FG_INFO, "Running moon update");
xg = r * cos(lonecl) * cos(latecl);
yg = r * sin(lonecl) * cos(latecl);
zg = r * sin(latecl);
xe = xg;
ye = yg * cos(ecl) -zg * sin(ecl);
ze = yg * sin(ecl) +zg * cos(ecl);
geoRa = atan2(ye, xe);
geoDec = atan2(ze, sqrt(xe*xe + ye*ye));
// Given the moon's geocentric ra and dec, calculate its
// topocentric ra and dec. i.e. the position as seen from the
// surface of the earth, instead of the center of the earth
// First calculates the moon's parrallax, that is, the apparent size of the
// (equatorial) radius of the earth, as seen from the moon
mpar = asin ( 1 / r);
gclat = f->get_Latitude() - 0.003358 *
sin (2 * DEG_TO_RAD * f->get_Latitude() );
rho = 0.99883 + 0.00167 * cos(2 * DEG_TO_RAD * f->get_Latitude());
if (geoRa < 0)
geoRa += (2*FG_PI);
HA = t->lst - (3.8197186 * geoRa);
g = atan (tan(gclat) / cos ((HA / 3.8197186)));
rightAscension = geoRa - mpar * rho * cos(gclat) * sin(HA) / cos (geoDec);
declination = geoDec - mpar * rho * sin (gclat) * sin (g - geoDec) / sin(g);
}
/************************************************************************
* void Moon::newImage(float ra, float dec)
*
* This function regenerates a new visual image of the moon, which is added to
* solarSystem display list.
*
* Arguments: Right Ascension and declination
*
* return value: none
**************************************************************************/
void Moon::newImage(float ra, float dec)
{
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBindTexture(GL_TEXTURE_2D, moon_texid);
//xglRotatef(-90, 0.0, 0.0, 1.0);
xglRotatef(((RAD_TO_DEG * ra)- 90.0), 0.0, 0.0, 1.0);
xglRotatef((RAD_TO_DEG * dec), 1.0, 0.0, 0.0);
FG_LOG( FG_GENERAL, FG_INFO,
"Ra = (" << (RAD_TO_DEG *ra)
<< "), Dec= (" << (RAD_TO_DEG *dec) << ")" );
xglTranslatef(0.0, 58600.0, 0.0);
Object = gluNewQuadric();
gluQuadricTexture( Object, GL_TRUE );
gluSphere( Object, 1367, 12, 12 );
glDisable(GL_TEXTURE_2D);
}
<|endoftext|> |
<commit_before>#include "displaywidget.h"
#include "dcpdisplay.h"
#include <duitheme.h>
#include <duibutton.h>
#include <duilinearlayout.h>
#include <duilabel.h>
#include <duislider.h>
const QString cssDir = "/usr/share/themes/dui/duicontrolpanel/";
const int widgetWidth = 100;
DisplayWidget::DisplayWidget(QGraphicsWidget *parent)
:DcpWidget(parent)
{
DuiTheme::loadCSS(cssDir + "displayapplet.css");
setReferer(DcpDisplay::NoReferer);
initWidget();
}
DisplayWidget::~DisplayWidget()
{
}
void DisplayWidget::paint(QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
QPen pen(QColor(120, 120, 120, 240));
QBrush brush(QColor(20, 20, 20, 240));
painter->setPen(pen);
painter->setBrush(brush);
painter->drawRect(QRectF(0.0, 0.0,
size().width(),
size().height()));
}
void DisplayWidget::initWidget()
{
DuiLinearLayout *mainLayout = new DuiLinearLayout(Qt::Horizontal, this);
// leftWidget
DuiWidget *leftWidget = new DuiWidget(this);
leftWidget->setMinimumWidth(widgetWidth);
leftWidget->setMaximumWidth(widgetWidth);
leftWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
// centralLayout
DuiLinearLayout *centralLayout = new DuiLinearLayout(Qt::Vertical, 0);
m_brightnessLabel = new DuiLabel(QString("Brightness: %1 %").arg(0));
m_brightnessLabel->setObjectName("LabelBrightness");
centralLayout->addItem(m_brightnessLabel);
DuiSlider *sliderBrightness = new DuiSlider(this);
sliderBrightness->setOrientation(Qt::Horizontal);
sliderBrightness->setRange(0, 100);
sliderBrightness->setValue(50);
sliderBrightness->setMaximumHeight(20);
connect(sliderBrightness, SIGNAL(valueChanged(int )),
this, SLOT(setBrightnessLabel(int)));
centralLayout->addItem(sliderBrightness);
m_screenLabel = new DuiLabel(QString("Screen lights on: %1 sec").arg(0));
m_screenLabel->setObjectName("LabelScreen");
centralLayout->addItem(m_screenLabel);
DuiSlider *sliderScreen = new DuiSlider(this);
sliderScreen->setOrientation(Qt::Horizontal);
sliderScreen->setRange(0, 100);
sliderScreen->setValue(50);
sliderScreen->setMaximumHeight(20);
connect(sliderScreen, SIGNAL(valueChanged(int )),
this, SLOT(setScreenLabel(int )));
centralLayout->addItem(sliderScreen);
DuiWidget *spacerItem = new DuiWidget(this);
spacerItem->setMinimumHeight(40);
spacerItem->setMaximumHeight(40);
centralLayout->addItem(spacerItem);
// screenHLayout
DuiLinearLayout *screenHLayout = new DuiLinearLayout(Qt::Horizontal, 0);
screenHLayout->setSpacing(20);
DuiLabel *screenLightLabel = new DuiLabel("While charging keep screen lights", this);
screenLightLabel->setObjectName("LabelScreenLight");
screenHLayout->addItem(screenLightLabel);
m_screenToggleButton = new DuiButton(this);
m_screenToggleButton->setObjectName("ScreenToggleButton");
m_screenToggleButton->setCheckable(true);
connect(m_screenToggleButton, SIGNAL(clicked()), this, SLOT(nextPage()));
screenHLayout->addItem(m_screenToggleButton);
DuiWidget *spacerItem2 = new DuiWidget(this);
spacerItem2->setMaximumHeight(20);
spacerItem2->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
screenHLayout->addItem(spacerItem2);
screenHLayout->setAlignment(screenLightLabel, Qt::AlignLeft | Qt::AlignVCenter);
screenHLayout->setAlignment(m_screenToggleButton, Qt::AlignLeft | Qt::AlignVCenter);
centralLayout->addItem(screenHLayout);
DuiWidget *spacerItem3 = new DuiWidget(this);
spacerItem3->setMinimumHeight(30);
spacerItem3->setMaximumHeight(30);
centralLayout->addItem(spacerItem3);
centralLayout->addItem(new DuiLabel("Note! Display settings depend on the user power profile."));
DuiWidget *spacerItem4 = new DuiWidget(this);
spacerItem4->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
centralLayout->addItem(spacerItem4);
centralLayout->setAlignment(m_brightnessLabel, Qt::AlignLeft | Qt::AlignVCenter);
// rigthWidget
DuiWidget *rightWidget = new DuiWidget(this);
rightWidget->setMinimumWidth(widgetWidth);
rightWidget->setMaximumWidth(widgetWidth);
rightWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
mainLayout->addItem(leftWidget);
mainLayout->addItem(centralLayout);
mainLayout->addItem(rightWidget);
mainLayout->setAlignment(leftWidget, Qt::AlignLeft);
mainLayout->setAlignment(centralLayout, Qt::AlignHCenter);
mainLayout->setAlignment(rightWidget, Qt::AlignRight);
}
void DisplayWidget::setBrightnessLabel(int value)
{
m_brightnessLabel->setText(QString("Brightness: %1 %").arg(value));
}
void DisplayWidget::setScreenLabel(int value)
{
m_screenLabel->setText(QString("Screen lights on: %1 sec").arg(value));
}
void DisplayWidget::nextPage()
{
emit changeWidget(DcpDisplay::Page1);
}
<commit_msg>Changed: DuiAbstractLayout to DuiLayout in DisplayWidget (DisplayApplet). Solved the DuiSlider bug.<commit_after>#include "displaywidget.h"
#include "dcpdisplay.h"
#include <duitheme.h>
#include <duibutton.h>
#include <duilayout.h>
#include <duilinearlayoutpolicy.h>
#include <duilabel.h>
#include <duislider.h>
const QString cssDir = "/usr/share/themes/dui/duicontrolpanel/";
const int widgetWidth = 100;
DisplayWidget::DisplayWidget(QGraphicsWidget *parent)
:DcpWidget(parent)
{
DuiTheme::loadCSS(cssDir + "displayapplet.css");
setReferer(DcpDisplay::NoReferer);
initWidget();
}
DisplayWidget::~DisplayWidget()
{
}
void DisplayWidget::paint(QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
QPen pen(QColor(120, 120, 120, 240));
QBrush brush(QColor(20, 20, 20, 240));
painter->setPen(pen);
painter->setBrush(brush);
painter->drawRect(QRectF(0.0, 0.0,
size().width(),
size().height()));
}
void DisplayWidget::initWidget()
{
DuiLayout *mainLayout = new DuiLayout(this);
DuiLinearLayoutPolicy *mainLayoutPolicy =
new DuiLinearLayoutPolicy(mainLayout, Qt::Horizontal);
mainLayout->setPolicy(mainLayoutPolicy);
// leftWidget
DuiWidget *leftWidget = new DuiWidget(this);
leftWidget->setMinimumWidth(widgetWidth);
leftWidget->setMaximumWidth(widgetWidth);
leftWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
// centralLayout
DuiLayout *centralLayout = new DuiLayout(0);
DuiLinearLayoutPolicy *centralLayoutPolicy =
new DuiLinearLayoutPolicy(centralLayout, Qt::Vertical);
centralLayout->setPolicy(centralLayoutPolicy);
centralLayoutPolicy->setContentsMargins(5.0, 20.0, 5.0, 20.0);
m_brightnessLabel = new DuiLabel(QString("Brightness: %1 %").arg(50));
m_brightnessLabel->setObjectName("LabelBrightness");
centralLayoutPolicy->addItemAtPosition(m_brightnessLabel, 0, Qt::AlignLeft);
DuiSlider *sliderBrightness = new DuiSlider(this, "continuous");
sliderBrightness->setOrientation(Qt::Horizontal);
sliderBrightness->setRange(0, 100);
sliderBrightness->setValue(50);
sliderBrightness->setMaximumHeight(20);
connect(sliderBrightness, SIGNAL(valueChanged(int )),
this, SLOT(setBrightnessLabel(int)));
centralLayoutPolicy->addItemAtPosition(sliderBrightness, 1, Qt::AlignLeft);
m_screenLabel = new DuiLabel(QString("Screen lights on: %1 sec").arg(50));
m_screenLabel->setObjectName("LabelScreen");
centralLayoutPolicy->addItemAtPosition(m_screenLabel, 2, Qt::AlignLeft);
DuiSlider *sliderScreen = new DuiSlider(this, "continuous");
sliderScreen->setOrientation(Qt::Horizontal);
sliderScreen->setRange(0, 100);
sliderScreen->setValue(50);
sliderScreen->setMaximumHeight(20);
connect(sliderScreen, SIGNAL(valueChanged(int )),
this, SLOT(setScreenLabel(int )));
centralLayoutPolicy->addItemAtPosition(sliderScreen, 3, Qt::AlignLeft);
DuiWidget *spacerItem = new DuiWidget(this);
spacerItem->setMinimumHeight(40);
spacerItem->setMaximumHeight(40);
centralLayoutPolicy->addItemAtPosition(spacerItem, 4, Qt::AlignCenter);
// screenHLayout
DuiLayout *screenHLayout = new DuiLayout(0);
DuiLinearLayoutPolicy *screenHLayoutPolicy =
new DuiLinearLayoutPolicy(screenHLayout, Qt::Horizontal);
screenHLayout->setPolicy(screenHLayoutPolicy);
screenHLayoutPolicy->setSpacing(20);
DuiLabel *screenLightLabel = new DuiLabel("While charging keep screen lights", this);
screenLightLabel->setObjectName("LabelScreenLight");
screenHLayoutPolicy->addItemAtPosition(screenLightLabel, 0, Qt::AlignLeft);
m_screenToggleButton = new DuiButton(this);
m_screenToggleButton->setObjectName("ScreenToggleButton");
m_screenToggleButton->setCheckable(true);
// connect(m_screenToggleButton, SIGNAL(clicked()), this, SLOT(nextPage()));
screenHLayoutPolicy->addItemAtPosition(m_screenToggleButton, 1, Qt::AlignLeft);
DuiWidget *spacerItem2 = new DuiWidget(this);
spacerItem2->setMaximumHeight(20);
spacerItem2->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
screenHLayoutPolicy->addItemAtPosition(spacerItem2, 2, Qt::AlignLeft);
centralLayoutPolicy->addItemAtPosition(screenHLayout, 5, Qt::AlignLeft);
DuiWidget *spacerItem3 = new DuiWidget(this);
spacerItem3->setMinimumHeight(30);
spacerItem3->setMaximumHeight(30);
centralLayoutPolicy->addItemAtPosition(spacerItem3, 6, Qt::AlignCenter);
centralLayoutPolicy->addItemAtPosition(
new DuiLabel("Note! Display settings depend on the user power profile."),
7, Qt::AlignLeft);
DuiWidget *spacerItem4 = new DuiWidget(this);
spacerItem4->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
centralLayoutPolicy->addItemAtPosition(spacerItem4, 8, Qt::AlignCenter);
// rigthWidget
DuiWidget *rightWidget = new DuiWidget(this);
rightWidget->setMinimumWidth(widgetWidth);
rightWidget->setMaximumWidth(widgetWidth);
rightWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
mainLayoutPolicy->addItemAtPosition(leftWidget, 0, Qt::AlignLeft);
mainLayoutPolicy->addItemAtPosition(centralLayout, 1, Qt::AlignHCenter);
mainLayoutPolicy->addItemAtPosition(rightWidget, 2, Qt::AlignRight);
}
void DisplayWidget::setBrightnessLabel(int value)
{
m_brightnessLabel->setText(QString("Brightness: %1 %").arg(value));
}
void DisplayWidget::setScreenLabel(int value)
{
m_screenLabel->setText(QString("Screen lights on: %1 sec").arg(value));
}
void DisplayWidget::nextPage()
{
emit changeWidget(DcpDisplay::Page1);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
*/
#pragma once
#include <uavcan_stm32/build_config.hpp>
#if UAVCAN_STM32_CHIBIOS
# include <hal.h>
#elif UAVCAN_STM32_NUTTX
# include <nuttx/arch.h>
# include <arch/board/board.h>
# include <chip/stm32_tim.h>
# include <syslog.h>
#elif UAVCAN_STM32_BAREMETAL
# include <chip.h>
#else
# error "Unknown OS"
#endif
/**
* Debug output
*/
#ifndef UAVCAN_STM32_LOG
// lowsyslog() crashes the system in this context
// # if UAVCAN_STM32_NUTTX && CONFIG_ARCH_LOWPUTC
# if 0
# define UAVCAN_STM32_LOG(fmt, ...) lowsyslog("uavcan_stm32: " fmt "\n", ##__VA_ARGS__)
# else
# define UAVCAN_STM32_LOG(...) ((void)0)
# endif
#endif
/**
* IRQ handler macros
*/
#if UAVCAN_STM32_CHIBIOS
# define UAVCAN_STM32_IRQ_HANDLER(id) CH_IRQ_HANDLER(id)
# define UAVCAN_STM32_IRQ_PROLOGUE() CH_IRQ_PROLOGUE()
# define UAVCAN_STM32_IRQ_EPILOGUE() CH_IRQ_EPILOGUE()
#elif UAVCAN_STM32_NUTTX
# define UAVCAN_STM32_IRQ_HANDLER(id) int id(int irq, FAR void* context)
# define UAVCAN_STM32_IRQ_PROLOGUE()
# define UAVCAN_STM32_IRQ_EPILOGUE() return 0;
#else
# define UAVCAN_STM32_IRQ_HANDLER(id) void id(void)
# define UAVCAN_STM32_IRQ_PROLOGUE()
# define UAVCAN_STM32_IRQ_EPILOGUE()
#endif
#if UAVCAN_STM32_CHIBIOS
/**
* Priority mask for timer and CAN interrupts.
*/
# ifndef UAVCAN_STM32_IRQ_PRIORITY_MASK
# define UAVCAN_STM32_IRQ_PRIORITY_MASK CORTEX_PRIO_MASK(CORTEX_MAX_KERNEL_PRIORITY)
# endif
#endif
#if UAVCAN_STM32_BAREMETAL
/**
* Priority mask for timer and CAN interrupts.
*/
# ifndef UAVCAN_STM32_IRQ_PRIORITY_MASK
# define UAVCAN_STM32_IRQ_PRIORITY_MASK 0
# endif
#endif
/**
* Glue macros
*/
#define UAVCAN_STM32_GLUE2_(A, B) A##B
#define UAVCAN_STM32_GLUE2(A, B) UAVCAN_STM32_GLUE2_(A, B)
#define UAVCAN_STM32_GLUE3_(A, B, C) A##B##C
#define UAVCAN_STM32_GLUE3(A, B, C) UAVCAN_STM32_GLUE3_(A, B, C)
namespace uavcan_stm32
{
#if UAVCAN_STM32_CHIBIOS
struct CriticalSectionLocker
{
CriticalSectionLocker() { chSysSuspend(); }
~CriticalSectionLocker() { chSysEnable(); }
};
#elif UAVCAN_STM32_NUTTX
struct CriticalSectionLocker
{
const irqstate_t flags_;
CriticalSectionLocker()
: flags_(irqsave())
{ }
~CriticalSectionLocker()
{
irqrestore(flags_);
}
};
#elif UAVCAN_STM32_BAREMETAL
struct CriticalSectionLocker
{
CriticalSectionLocker()
{
__disable_irq();
}
~CriticalSectionLocker()
{
__enable_irq();
}
};
#endif
namespace clock
{
uavcan::uint64_t getUtcUSecFromCanInterrupt();
}
}
<commit_msg>Correct CORTEX_MAX_KERNEL_PRIORITY use<commit_after>/*
* Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
*/
#pragma once
#include <uavcan_stm32/build_config.hpp>
#if UAVCAN_STM32_CHIBIOS
# include <hal.h>
#elif UAVCAN_STM32_NUTTX
# include <nuttx/arch.h>
# include <arch/board/board.h>
# include <chip/stm32_tim.h>
# include <syslog.h>
#elif UAVCAN_STM32_BAREMETAL
# include <chip.h>
#else
# error "Unknown OS"
#endif
/**
* Debug output
*/
#ifndef UAVCAN_STM32_LOG
// lowsyslog() crashes the system in this context
// # if UAVCAN_STM32_NUTTX && CONFIG_ARCH_LOWPUTC
# if 0
# define UAVCAN_STM32_LOG(fmt, ...) lowsyslog("uavcan_stm32: " fmt "\n", ##__VA_ARGS__)
# else
# define UAVCAN_STM32_LOG(...) ((void)0)
# endif
#endif
/**
* IRQ handler macros
*/
#if UAVCAN_STM32_CHIBIOS
# define UAVCAN_STM32_IRQ_HANDLER(id) CH_IRQ_HANDLER(id)
# define UAVCAN_STM32_IRQ_PROLOGUE() CH_IRQ_PROLOGUE()
# define UAVCAN_STM32_IRQ_EPILOGUE() CH_IRQ_EPILOGUE()
#elif UAVCAN_STM32_NUTTX
# define UAVCAN_STM32_IRQ_HANDLER(id) int id(int irq, FAR void* context)
# define UAVCAN_STM32_IRQ_PROLOGUE()
# define UAVCAN_STM32_IRQ_EPILOGUE() return 0;
#else
# define UAVCAN_STM32_IRQ_HANDLER(id) void id(void)
# define UAVCAN_STM32_IRQ_PROLOGUE()
# define UAVCAN_STM32_IRQ_EPILOGUE()
#endif
#if UAVCAN_STM32_CHIBIOS
/**
* Priority mask for timer and CAN interrupts.
*/
# ifndef UAVCAN_STM32_IRQ_PRIORITY_MASK
# define UAVCAN_STM32_IRQ_PRIORITY_MASK CORTEX_MAX_KERNEL_PRIORITY
# endif
#endif
#if UAVCAN_STM32_BAREMETAL
/**
* Priority mask for timer and CAN interrupts.
*/
# ifndef UAVCAN_STM32_IRQ_PRIORITY_MASK
# define UAVCAN_STM32_IRQ_PRIORITY_MASK 0
# endif
#endif
/**
* Glue macros
*/
#define UAVCAN_STM32_GLUE2_(A, B) A##B
#define UAVCAN_STM32_GLUE2(A, B) UAVCAN_STM32_GLUE2_(A, B)
#define UAVCAN_STM32_GLUE3_(A, B, C) A##B##C
#define UAVCAN_STM32_GLUE3(A, B, C) UAVCAN_STM32_GLUE3_(A, B, C)
namespace uavcan_stm32
{
#if UAVCAN_STM32_CHIBIOS
struct CriticalSectionLocker
{
CriticalSectionLocker() { chSysSuspend(); }
~CriticalSectionLocker() { chSysEnable(); }
};
#elif UAVCAN_STM32_NUTTX
struct CriticalSectionLocker
{
const irqstate_t flags_;
CriticalSectionLocker()
: flags_(irqsave())
{ }
~CriticalSectionLocker()
{
irqrestore(flags_);
}
};
#elif UAVCAN_STM32_BAREMETAL
struct CriticalSectionLocker
{
CriticalSectionLocker()
{
__disable_irq();
}
~CriticalSectionLocker()
{
__enable_irq();
}
};
#endif
namespace clock
{
uavcan::uint64_t getUtcUSecFromCanInterrupt();
}
}
<|endoftext|> |
<commit_before>#ifdef COSMOLOGY
#include <iostream>
#include <fstream>
#include "cosmology.h"
#include "../io.h"
using namespace std;
void Cosmology::Load_Scale_Outputs( struct parameters *P ) {
char filename_1[100];
// create the filename to read from
strcpy(filename_1, P->scale_outputs_file);
chprintf( " Loading Scale_Factor Outpus: %s\n", filename_1);
ifstream file_out ( filename_1 );
string line;
Real a_value;
if (file_out.is_open()){
while ( getline (file_out,line) ){
a_value = atof( line.c_str() );
scale_outputs.push_back( a_value );
n_outputs += 1;
// chprintf("%f\n", a_value);
}
file_out.close();
n_outputs = scale_outputs.size();
next_output_indx = 0;
chprintf(" Loaded %d scale outputs \n", n_outputs);
}
else{
chprintf(" Error: Unable to open cosmology outputs file\n");
exit(1);
}
chprintf(" Setting next snapshot output\n");
int scale_indx = next_output_indx;
a_value = scale_outputs[scale_indx];
while ( (current_a - a_value) > 1e-3 ){
// chprintf( "%f %f\n", a_value, current_a);
scale_indx += 1;
a_value = scale_outputs[scale_indx];
}
next_output_indx = scale_indx;
next_output = a_value;
chprintf(" Next output index: %d \n", next_output_indx );
chprintf(" Next output z value: %f \n", 1./next_output - 1 );
exit_now = false;
}
void Cosmology::Set_Scale_Outputs( struct parameters *P ){
if ( P->scale_outputs_file[0] == '\0' ){
chprintf( " Output every %d timesteps.\n", P->n_steps_output );
Real scale_end = 1 / ( P->End_redshift + 1);
scale_outputs.push_back( current_a );
scale_outputs.push_back( scale_end );
n_outputs = scale_outputs.size();
next_output_indx = 0;
next_output = current_a;
chprintf(" Next output index: %d \n", next_output_indx );
chprintf(" Next output z value: %f \n", 1./next_output - 1 );
}
else Load_Scale_Outputs( P );
}
void Cosmology::Set_Next_Scale_Output( ){
int scale_indx = next_output_indx;
Real a_value = scale_outputs[scale_indx];
if ( ( scale_indx == 0 ) && ( abs(a_value - current_a )<1e-5 ) )scale_indx = 1;
else scale_indx += 1;
if ( scale_indx < n_outputs ){
a_value = scale_outputs[scale_indx];
next_output_indx = scale_indx;
next_output = a_value;
}
else{
exit_now = true;
}
}
#endif<commit_msg>print setting new index<commit_after>#ifdef COSMOLOGY
#include <iostream>
#include <fstream>
#include "cosmology.h"
#include "../io.h"
using namespace std;
void Cosmology::Load_Scale_Outputs( struct parameters *P ) {
char filename_1[100];
// create the filename to read from
strcpy(filename_1, P->scale_outputs_file);
chprintf( " Loading Scale_Factor Outpus: %s\n", filename_1);
ifstream file_out ( filename_1 );
string line;
Real a_value;
if (file_out.is_open()){
while ( getline (file_out,line) ){
a_value = atof( line.c_str() );
scale_outputs.push_back( a_value );
n_outputs += 1;
// chprintf("%f\n", a_value);
}
file_out.close();
n_outputs = scale_outputs.size();
next_output_indx = 0;
chprintf(" Loaded %d scale outputs \n", n_outputs);
}
else{
chprintf(" Error: Unable to open cosmology outputs file\n");
exit(1);
}
chprintf(" Setting next snapshot output\n");
int scale_indx = next_output_indx;
a_value = scale_outputs[scale_indx];
while ( (current_a - a_value) > 1e-3 ){
// chprintf( "%f %f\n", a_value, current_a);
scale_indx += 1;
a_value = scale_outputs[scale_indx];
}
next_output_indx = scale_indx;
next_output = a_value;
chprintf(" Next output index: %d \n", next_output_indx );
chprintf(" Next output z value: %f \n", 1./next_output - 1 );
exit_now = false;
}
void Cosmology::Set_Scale_Outputs( struct parameters *P ){
if ( P->scale_outputs_file[0] == '\0' ){
chprintf( " Output every %d timesteps.\n", P->n_steps_output );
Real scale_end = 1 / ( P->End_redshift + 1);
scale_outputs.push_back( current_a );
scale_outputs.push_back( scale_end );
n_outputs = scale_outputs.size();
next_output_indx = 0;
next_output = current_a;
chprintf(" Next output index: %d \n", next_output_indx );
chprintf(" Next output z value: %f \n", 1./next_output - 1 );
}
else Load_Scale_Outputs( P );
}
void Cosmology::Set_Next_Scale_Output( ){
chprintf("Setting next output index. Current index: %d n_outputs: %d ", scale_indx, n_outputs);
int scale_indx = next_output_indx;
Real a_value = scale_outputs[scale_indx];
if ( ( scale_indx == 0 ) && ( abs(a_value - current_a )<1e-5 ) )scale_indx = 1;
else scale_indx += 1;
if ( scale_indx < n_outputs ){
a_value = scale_outputs[scale_indx];
next_output_indx = scale_indx;
next_output = a_value;
}
else{
exit_now = true;
}
}
#endif<|endoftext|> |
<commit_before>#ifdef COSMOLOGY
#include <iostream>
#include <fstream>
#include "cosmology.h"
#include "../io.h"
using namespace std;
void Cosmology::Load_Scale_Outputs( struct parameters *P ) {
char filename_1[100];
// create the filename to read from
strcpy(filename_1, P->scale_outputs_file);
chprintf( " Loading Scale_Factor Outpus: %s\n", filename_1);
ifstream file_out ( filename_1 );
string line;
Real a_value;
if (file_out.is_open()){
while ( getline (file_out,line) ){
a_value = atof( line.c_str() );
scale_outputs.push_back( a_value );
n_outputs += 1;
// chprintf("%f\n", a_value);
}
file_out.close();
n_outputs = scale_outputs.size();
next_output_indx = 0;
chprintf(" Loaded %d scale outputs \n", n_outputs);
}
else{
chprintf(" Error: Unable to open cosmology outputs file\n");
exit(1);
}
chprintf(" Setting next snapshot output\n");
int scale_indx = next_output_indx;
a_value = scale_outputs[scale_indx];
while ( (current_a - a_value) > 1e-3 ){
// chprintf( "%f %f\n", a_value, current_a);
scale_indx += 1;
a_value = scale_outputs[scale_indx];
}
next_output_indx = scale_indx;
next_output = a_value;
chprintf(" Next output index: %d \n", next_output_indx );
chprintf(" Next output z value: %f \n", 1./next_output - 1 );
exit_now = false;
}
void Cosmology::Set_Scale_Outputs( struct parameters *P ){
if ( P->scale_outputs_file[0] == '\0' ){
chprintf( " Output every %d timesteps.\n", P->n_steps_output );
Real scale_end = 1 / ( P->End_redshift + 1);
scale_outputs.push_back( current_a );
scale_outputs.push_back( scale_end );
n_outputs = scale_outputs.size();
next_output_indx = 0;
next_output = current_a;
chprintf(" Next output index: %d \n", next_output_indx );
chprintf(" Next output z value: %f \n", 1./next_output - 1 );
}
else Load_Scale_Outputs( P );
}
void Cosmology::Set_Next_Scale_Output( ){
int scale_indx = next_output_indx;
Real a_value = scale_outputs[scale_indx];
chprintf("Setting next output index. Current index: %d n_outputs: %d ", scale_indx, n_outputs);
// if ( ( scale_indx == 0 ) && ( abs(a_value - current_a )<1e-5 ) )scale_indx = 1;
scale_indx += 1;
if ( scale_indx < n_outputs ){
a_value = scale_outputs[scale_indx];
next_output_indx = scale_indx;
next_output = a_value;
}
else{
exit_now = true;
}
}
#endif<commit_msg>exit_now = true<commit_after>#ifdef COSMOLOGY
#include <iostream>
#include <fstream>
#include "cosmology.h"
#include "../io.h"
using namespace std;
void Cosmology::Load_Scale_Outputs( struct parameters *P ) {
char filename_1[100];
// create the filename to read from
strcpy(filename_1, P->scale_outputs_file);
chprintf( " Loading Scale_Factor Outpus: %s\n", filename_1);
ifstream file_out ( filename_1 );
string line;
Real a_value;
if (file_out.is_open()){
while ( getline (file_out,line) ){
a_value = atof( line.c_str() );
scale_outputs.push_back( a_value );
n_outputs += 1;
// chprintf("%f\n", a_value);
}
file_out.close();
n_outputs = scale_outputs.size();
next_output_indx = 0;
chprintf(" Loaded %d scale outputs \n", n_outputs);
}
else{
chprintf(" Error: Unable to open cosmology outputs file\n");
exit(1);
}
chprintf(" Setting next snapshot output\n");
int scale_indx = next_output_indx;
a_value = scale_outputs[scale_indx];
while ( (current_a - a_value) > 1e-3 ){
// chprintf( "%f %f\n", a_value, current_a);
scale_indx += 1;
a_value = scale_outputs[scale_indx];
}
next_output_indx = scale_indx;
next_output = a_value;
chprintf(" Next output index: %d \n", next_output_indx );
chprintf(" Next output z value: %f \n", 1./next_output - 1 );
exit_now = false;
}
void Cosmology::Set_Scale_Outputs( struct parameters *P ){
if ( P->scale_outputs_file[0] == '\0' ){
chprintf( " Output every %d timesteps.\n", P->n_steps_output );
Real scale_end = 1 / ( P->End_redshift + 1);
scale_outputs.push_back( current_a );
scale_outputs.push_back( scale_end );
n_outputs = scale_outputs.size();
next_output_indx = 0;
next_output = current_a;
chprintf(" Next output index: %d \n", next_output_indx );
chprintf(" Next output z value: %f \n", 1./next_output - 1 );
}
else Load_Scale_Outputs( P );
}
void Cosmology::Set_Next_Scale_Output( ){
int scale_indx = next_output_indx;
Real a_value = scale_outputs[scale_indx];
chprintf("Setting next output index. Current index: %d n_outputs: %d ", scale_indx, n_outputs);
// if ( ( scale_indx == 0 ) && ( abs(a_value - current_a )<1e-5 ) )scale_indx = 1;
scale_indx += 1;
// if ( scale_indx < n_outputs ){
// a_value = scale_outputs[scale_indx];
// next_output_indx = scale_indx;
// next_output = a_value;
// }
// else{
// exit_now = true;
// }
exit_now = true;
}
#endif<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.