text
stringlengths 54
60.6k
|
---|
<commit_before>#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include "Neural_Networks.h"
using namespace std;
void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {
ifstream file(training_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
}
file.open(training_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
}
file.open(test_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
}
file.open(test_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
}
}
int main() {
int batch_size = 128;
int epochs = 100;
int number_threads = 6;
int number_training = 60000;
int number_test = 10000;
int number_nodes[] = { 784, 10 };
int time_step = 28;
float **x_data = new float*[number_training + number_test];
float **y_data = new float*[number_training + number_test];
float **x_train = x_data;
float **y_train = y_data;
float **x_test = &x_data[number_training];
float **y_test = &y_data[number_training];
double decay = 0.000001;
double learning_rate = 0.03;
string path;
Neural_Networks NN = Neural_Networks();
cout << "path where MNIST handwritten digits dataset is : ";
getline(cin, path);
for (int h = 0; h < number_training + number_test; h++) {
x_data[h] = new float[number_nodes[0]];
y_data[h] = new float[number_nodes[1]];
}
Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, x_data, y_data);
omp_set_num_threads(number_threads);
srand(1);
NN.Add(Layer(time_step, number_nodes[0] / time_step));
NN.Add(RNN(time_step, 128))->Activation(Activation::relu)->Direction(+1);
NN.Add(RNN(time_step, 128))->Activation(Activation::relu)->Direction(-1);
NN.Add(Layer(2, 128));
NN.Add(Layer(1, 256));
NN.Add(number_nodes[1])->Activation(Activation::softmax);
NN.Connect(1, 0, "W");
NN.Connect(1, 1, "W,recurrent");
NN.Connect(2, 0, "W");
NN.Connect(2, 2, "W,recurrent");
{
unordered_multimap<int, int> time_connection;
time_connection.insert(pair<int, int>(0, time_step - 1));
NN.Connect(3, 1, "copy", &time_connection);
time_connection.clear();
time_connection.insert(pair<int, int>(1, 0));
NN.Connect(3, 2, "copy", &time_connection);
}
NN.Connect(4, 3, "copy");
NN.Connect(5, 4, "W");
NN.Compile(Loss::cross_entropy, new Optimizer(SGD(learning_rate, decay)));
for (int e = 0, time = clock(); e < epochs; e++) {
int score[2] = { 0, };
float **_input = new float*[batch_size];
float **output = new float*[batch_size];
double loss[2] = { NN.Fit(NN.Shuffle(x_train, number_training), NN.Shuffle(y_train, number_training), number_training, batch_size), NN.Evaluate(x_test, y_test, number_test, batch_size) };
for (int h = 0; h < batch_size; h++) {
output[h] = new float[number_nodes[1]];
}
for (int h = 0, i = 0; i < number_training + number_test; i++) {
_input[h] = x_data[i];
if (++h == batch_size || i == number_training + number_test - 1) {
NN.Predict(_input, output, h);
for (int argmax, index = i - h + 1; --h >= 0;) {
double max = 0;
for (int j = 0; j < number_nodes[1]; j++) {
if (j == 0 || max < output[h][j]) {
max = output[h][argmax = j];
}
}
score[(index + h < number_training) ? (0) : (1)] += (int)y_data[index + h][argmax];
}
h = 0;
}
}
printf("loss: %.4f / %.4f accuracy: %.4f / %.4f step %d %.2f sec\n", loss[0], loss[1], 1.0 * score[0] / number_training, 1.0 * score[1] / number_test, e + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
for (int h = 0; h < batch_size; h++) {
delete[] output[h];
}
delete[] _input;
delete[] output;
}
for (int i = 0; i < number_training + number_test; i++) {
delete[] x_data[i];
delete[] y_data[i];
}
delete[] x_data;
delete[] y_data;
}
<commit_msg>Update main.cpp<commit_after>#include <fstream>
#include <iostream>
#include <omp.h>
#include <stdio.h>
#include <string>
#include <time.h>
#include "Neural_Networks.h"
using namespace std;
void Read_MNIST(string training_set_images, string training_set_labels, string test_set_images, string test_set_labels, int number_training, int number_test, float **input, float **output) {
ifstream file(training_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_images + " not found" << endl;
}
file.open(training_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = 0; h < number_training; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + training_set_labels + " not found" << endl;
}
file.open(test_set_images, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 4; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char pixel;
for (int j = 0; j < 28 * 28; j++) {
file.read((char*)(&pixel), 1);
input[h][j] = pixel / 255.0;
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_images + " not found" << endl;
}
file.open(test_set_labels, ifstream::binary);
if (file.is_open()) {
for (int h = 0, value; h < 2; h++) {
file.read((char*)(&value), sizeof(int));
}
for (int h = number_training; h < number_training + number_test; h++) {
unsigned char label;
file.read((char*)(&label), 1);
for (int j = 0; j < 10; j++) {
output[h][j] = (j == label);
}
}
file.close();
}
else {
cerr << "[Read_MNIST], " + test_set_labels + " not found" << endl;
}
}
int main() {
int batch_size = 128;
int epochs = 100;
int number_threads = 6;
int number_training = 60000;
int number_test = 10000;
int number_nodes[] = { 784, 10 };
int time_step = 28;
float **x_data = new float*[number_training + number_test];
float **y_data = new float*[number_training + number_test];
float **x_train = x_data;
float **y_train = y_data;
float **x_test = &x_data[number_training];
float **y_test = &y_data[number_training];
double decay = 0.000001;
double learning_rate = 0.03;
string path;
Neural_Networks NN = Neural_Networks();
cout << "path where MNIST handwritten digits dataset is : ";
getline(cin, path);
for (int h = 0; h < number_training + number_test; h++) {
x_data[h] = new float[number_nodes[0]];
memset(y_data[h] = new float[time_step * number_nodes[1]], 0, sizeof(float) * time_step * number_nodes[1]);
}
Read_MNIST(path + "train-images.idx3-ubyte", path + "train-labels.idx1-ubyte", path + "t10k-images.idx3-ubyte", path + "t10k-labels.idx1-ubyte", number_training, number_test, x_data, y_data);
omp_set_num_threads(number_threads);
srand(2);
NN.Add(Layer(time_step, number_nodes[0] / time_step));
NN.Add(RNN(time_step, 128))->Activation(Activation::relu)->Direction(+1);
NN.Add(RNN(time_step, 128))->Activation(Activation::relu)->Direction(-1);
NN.Add(Layer(2, 128));
NN.Add(Layer(1, 256));
NN.Add(number_nodes[1])->Activation(Activation::softmax);
NN.Connect(1, 0, "W");
NN.Connect(1, 1, "W,recurrent");
NN.Connect(2, 0, "W");
NN.Connect(2, 2, "W,recurrent");
{
unordered_multimap<int, int> time_connection;
time_connection.insert(pair<int, int>(0, time_step - 1));
NN.Connect(3, 1, "copy", &time_connection);
time_connection.clear();
time_connection.insert(pair<int, int>(1, 0));
NN.Connect(3, 2, "copy", &time_connection);
}
NN.Connect(4, 3, "copy");
NN.Connect(5, 4, "W");
NN.Compile(Loss::cross_entropy, Optimizer(SGD(learning_rate, decay)));
for (int e = 0, time = clock(); e < epochs; e++) {
int score[2] = { 0, };
float **_input = new float*[batch_size];
float **output = new float*[batch_size];
double loss[2] = { NN.Fit(NN.Shuffle(x_train, number_training), NN.Shuffle(y_train, number_training), number_training, batch_size), NN.Evaluate(x_test, y_test, number_test, batch_size) };
for (int h = 0; h < batch_size; h++) {
output[h] = new float[time_step * number_nodes[1]];
}
for (int h = 0, i = 0; i < number_training + number_test; i++) {
_input[h] = x_data[i];
if (++h == batch_size || i == number_training + number_test - 1) {
NN.Predict(_input, output, h);
for (int argmax, index = i - h + 1; --h >= 0;) {
double max = 0;
for (int j = 0; j < number_nodes[1]; j++) {
if (j == 0 || max < output[h][j]) {
max = output[h][argmax = j];
}
}
score[(index + h < number_training) ? (0) : (1)] += (int)y_data[index + h][argmax];
}
h = 0;
}
}
printf("loss: %.4f / %.4f accuracy: %.4f / %.4f step %d %.2f sec\n", loss[0], loss[1], 1.0 * score[0] / number_training, 1.0 * score[1] / number_test, e + 1, (double)(clock() - time) / CLOCKS_PER_SEC);
for (int h = 0; h < batch_size; h++) {
delete[] output[h];
}
delete[] _input;
delete[] output;
}
for (int i = 0; i < number_training + number_test; i++) {
delete[] x_data[i];
delete[] y_data[i];
}
delete[] x_data;
delete[] y_data;
}
<|endoftext|> |
<commit_before>#include "match.h"
#include <vector>
#include "globalsettings.h"
Match::Match(Read* r, int pos, int distance, bool reversed){
mRead = r;
mSequence = NULL;
mDistance = distance;
mPos = pos;
mReversed = reversed;
}
Match::Match(char* seq, char meanQual, int pos, int distance, bool reversed){
mRead = NULL;
mSequence = seq;
mMeanQual = meanQual;
mDistance = distance;
mPos = pos;
mReversed = reversed;
}
Match::~Match(){
// we don't delete mRead or mSequence here since they are shared by different objects
// and will be deleted in other places
for(int i=0;i<mOriginalReads.size();i++){
delete mOriginalReads[i];
mOriginalReads[i] = NULL;
}
}
int Match::readlength() const {
if(GlobalSettings::simplifiedMode)
return strlen(mSequence);
else
return mRead->length();
}
void Match::addOriginalRead(Read* r){
mOriginalReads.push_back(new Read(*r));
}
void Match::addOriginalPair(ReadPair* pair){
mOriginalReads.push_back(new Read(*pair->mLeft));
mOriginalReads.push_back(new Read(*pair->mRight));
}
void Match::print(int leftlen, int centerlen, int rightlen){
if(GlobalSettings::simplifiedMode)
mRead = new Read(mSequence, mMeanQual);
cout<<"pos: "<<mPos<<", distance: "<<mDistance;
if(mReversed)
cout<<", reverse";
else
cout<<", forward";
cout<<endl;
vector<int> breaks;
breaks.push_back(max(mPos-leftlen, 0));
breaks.push_back( mPos );
breaks.push_back( mPos+centerlen );
breaks.push_back( min(mPos+centerlen+rightlen, mRead->length()));
mRead->printWithBreaks(breaks);
if(GlobalSettings::simplifiedMode) {
delete mRead;
mRead = NULL;
}
}
void Match::printHtmlTD(ofstream& file, int leftlen, int centerlen, int rightlen, int mutid, int matchid){
if(GlobalSettings::simplifiedMode)
mRead = new Read(mSequence, mMeanQual);
file<<"<a title='"<<mRead->mName<<"'>";
file<<"d:" << mDistance;
if(mReversed)
file<<", <--";
else
file<<", -->";
file<<"</a></span>";
vector<int> breaks;
breaks.push_back(max(mPos-leftlen, 0));
breaks.push_back( mPos );
breaks.push_back( mPos+centerlen );
breaks.push_back( min(mPos+centerlen+rightlen, mRead->length()));
mRead->printHtmlTDWithBreaks(file, breaks, mutid, matchid);
if(GlobalSettings::simplifiedMode) {
delete mRead;
mRead = NULL;
}
}
void Match::printJS(ofstream& file, int leftlen, int centerlen, int rightlen) {
if(GlobalSettings::simplifiedMode)
mRead = new Read(mSequence, mMeanQual);
vector<int> breaks;
breaks.push_back(max(mPos-leftlen, 0));
breaks.push_back( mPos );
breaks.push_back( mPos+centerlen );
breaks.push_back( min(mPos+centerlen+rightlen, mRead->length()));
mRead->printJSWithBreaks(file, breaks);
if(GlobalSettings::simplifiedMode) {
delete mRead;
mRead = NULL;
}
}
void Match::printReadsToFile(ofstream& file){
for(int i=0;i<mOriginalReads.size();i++){
mOriginalReads[i]->printFile(file);
}
}
void Match::setReversed(bool flag){
mReversed = flag;
}
int Match::countUnique(vector<Match*>& matches) {
if(matches.size()==0)
return 0;
int count = 1;
Match* cur = matches[0];
for(int i=1;i<matches.size();i++){
Match* m = matches[i];
if( *m > *cur || *m < *cur) {
cur = m;
count++;
}
}
return count;
}
<commit_msg>fix Linux compile<commit_after>#include "match.h"
#include <vector>
#include "globalsettings.h"
#include <memory.h>
Match::Match(Read* r, int pos, int distance, bool reversed){
mRead = r;
mSequence = NULL;
mDistance = distance;
mPos = pos;
mReversed = reversed;
}
Match::Match(char* seq, char meanQual, int pos, int distance, bool reversed){
mRead = NULL;
mSequence = seq;
mMeanQual = meanQual;
mDistance = distance;
mPos = pos;
mReversed = reversed;
}
Match::~Match(){
// we don't delete mRead or mSequence here since they are shared by different objects
// and will be deleted in other places
for(int i=0;i<mOriginalReads.size();i++){
delete mOriginalReads[i];
mOriginalReads[i] = NULL;
}
}
int Match::readlength() const {
if(GlobalSettings::simplifiedMode)
return strlen(mSequence);
else
return mRead->length();
}
void Match::addOriginalRead(Read* r){
mOriginalReads.push_back(new Read(*r));
}
void Match::addOriginalPair(ReadPair* pair){
mOriginalReads.push_back(new Read(*pair->mLeft));
mOriginalReads.push_back(new Read(*pair->mRight));
}
void Match::print(int leftlen, int centerlen, int rightlen){
if(GlobalSettings::simplifiedMode)
mRead = new Read(mSequence, mMeanQual);
cout<<"pos: "<<mPos<<", distance: "<<mDistance;
if(mReversed)
cout<<", reverse";
else
cout<<", forward";
cout<<endl;
vector<int> breaks;
breaks.push_back(max(mPos-leftlen, 0));
breaks.push_back( mPos );
breaks.push_back( mPos+centerlen );
breaks.push_back( min(mPos+centerlen+rightlen, mRead->length()));
mRead->printWithBreaks(breaks);
if(GlobalSettings::simplifiedMode) {
delete mRead;
mRead = NULL;
}
}
void Match::printHtmlTD(ofstream& file, int leftlen, int centerlen, int rightlen, int mutid, int matchid){
if(GlobalSettings::simplifiedMode)
mRead = new Read(mSequence, mMeanQual);
file<<"<a title='"<<mRead->mName<<"'>";
file<<"d:" << mDistance;
if(mReversed)
file<<", <--";
else
file<<", -->";
file<<"</a></span>";
vector<int> breaks;
breaks.push_back(max(mPos-leftlen, 0));
breaks.push_back( mPos );
breaks.push_back( mPos+centerlen );
breaks.push_back( min(mPos+centerlen+rightlen, mRead->length()));
mRead->printHtmlTDWithBreaks(file, breaks, mutid, matchid);
if(GlobalSettings::simplifiedMode) {
delete mRead;
mRead = NULL;
}
}
void Match::printJS(ofstream& file, int leftlen, int centerlen, int rightlen) {
if(GlobalSettings::simplifiedMode)
mRead = new Read(mSequence, mMeanQual);
vector<int> breaks;
breaks.push_back(max(mPos-leftlen, 0));
breaks.push_back( mPos );
breaks.push_back( mPos+centerlen );
breaks.push_back( min(mPos+centerlen+rightlen, mRead->length()));
mRead->printJSWithBreaks(file, breaks);
if(GlobalSettings::simplifiedMode) {
delete mRead;
mRead = NULL;
}
}
void Match::printReadsToFile(ofstream& file){
for(int i=0;i<mOriginalReads.size();i++){
mOriginalReads[i]->printFile(file);
}
}
void Match::setReversed(bool flag){
mReversed = flag;
}
int Match::countUnique(vector<Match*>& matches) {
if(matches.size()==0)
return 0;
int count = 1;
Match* cur = matches[0];
for(int i=1;i<matches.size();i++){
Match* m = matches[i];
if( *m > *cur || *m < *cur) {
cur = m;
count++;
}
}
return count;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009 Stephen Liu
* For license terms, see the file COPYING along with this library.
*/
#ifndef __spprotobuf_hpp__
#define __spprotobuf_hpp__
#include <stdint.h>
class SP_ProtoBufEncoder
{
public:
SP_ProtoBufEncoder( int initLen = 0 );
~SP_ProtoBufEncoder();
int addVarint( int fieldNumber, uint64_t value );
int addZigZagInt( int fieldNumber, int64_t value );
int addDouble( int fieldNumber, double value );
int addFloat( int fieldNumber, float value );
int add64Bit( int fieldNumber, uint64_t value );
int addBinary( int fieldNumber, const char * buffer, int len );
int add32Bit( int fieldNumber, uint32_t value );
int addPacked( int fieldNumber, uint16_t * array, int size );
int addPacked( int fieldNumber, uint32_t * array, int size );
int addPacked( int fieldNumber, uint64_t * array, int size );
int addPacked( int fieldNumber, float * array, int size );
int addPacked( int fieldNumber, double * array, int size );
const char * getBuffer();
int getSize();
void reset();
private:
static int encodeVarint( uint64_t value, char *buffer );
static int encode32Bit( uint32_t value, char * buffer );
static int encode64Bit( uint64_t value, char * buffer );
int ensureSpace( int space );
private:
char * mBuffer;
int mTotal, mSize;
};
/**
* a simple decoder for protobuf
*/
class SP_ProtoBufDecoder
{
public:
enum {
eWireVarint = 0,
eWire64Bit = 1,
eWireBinary = 2,
eWire32Bit = 5
};
typedef struct tagKeyValPair {
int mFieldNumber;
int mWireType;
union { // wire type 0
uint64_t u;
int64_t s;
} mVarint;
int64_t mZigZagInt; // wire type 0
union { // wire type 1
uint64_t u;
int64_t s;
} m64Bit;
struct { // wire type 2
const char * mBuffer;
int mLen;
} mBinary;
union { // wire type 5
uint32_t u;
int32_t s;
} m32Bit;
} KeyValPair_t;
public:
SP_ProtoBufDecoder( const char * buffer, int len );
~SP_ProtoBufDecoder();
bool getNext( KeyValPair_t * pair );
bool find( int fieldNumber, KeyValPair_t * pair, int index = 0 );
void rewind();
static char * dup( const char * buffer, int len );
static int getPacked( const char * buffer, int len, uint16_t * array, int size );
static int getPacked( const char * buffer, int len, uint32_t * array, int size );
static int getPacked( const char * buffer, int len, uint64_t * array, int size );
static int getPacked( const char * buffer, int len, float * array, int size );
static int getPacked( const char * buffer, int len, double * array, int size );
private:
// @return > 0 : parse ok, consume how many bytes, -1 : unknown type
static int decodeVarint( uint64_t *value, const char *buffer );
static uint32_t decode32Bit( const char * buffer );
// @return > 0 : parse ok, consume how many bytes, -1 : unknown type
static int getPair( const char * buffer, KeyValPair_t * pair );
private:
const char * mBuffer, * mEnd;
const char * mCurr;
};
#endif
<commit_msg>support to read double/float<commit_after>/*
* Copyright 2009 Stephen Liu
* For license terms, see the file COPYING along with this library.
*/
#ifndef __spprotobuf_hpp__
#define __spprotobuf_hpp__
#include <stdint.h>
class SP_ProtoBufEncoder
{
public:
SP_ProtoBufEncoder( int initLen = 0 );
~SP_ProtoBufEncoder();
int addVarint( int fieldNumber, uint64_t value );
int addZigZagInt( int fieldNumber, int64_t value );
int addDouble( int fieldNumber, double value );
int addFloat( int fieldNumber, float value );
int add64Bit( int fieldNumber, uint64_t value );
int addBinary( int fieldNumber, const char * buffer, int len );
int add32Bit( int fieldNumber, uint32_t value );
int addPacked( int fieldNumber, uint16_t * array, int size );
int addPacked( int fieldNumber, uint32_t * array, int size );
int addPacked( int fieldNumber, uint64_t * array, int size );
int addPacked( int fieldNumber, float * array, int size );
int addPacked( int fieldNumber, double * array, int size );
const char * getBuffer();
int getSize();
void reset();
private:
static int encodeVarint( uint64_t value, char *buffer );
static int encode32Bit( uint32_t value, char * buffer );
static int encode64Bit( uint64_t value, char * buffer );
int ensureSpace( int space );
private:
char * mBuffer;
int mTotal, mSize;
};
/**
* a simple decoder for protobuf
*/
class SP_ProtoBufDecoder
{
public:
enum {
eWireVarint = 0,
eWire64Bit = 1,
eWireBinary = 2,
eWire32Bit = 5
};
typedef struct tagKeyValPair {
int mFieldNumber;
int mWireType;
union { // wire type 0
uint64_t u;
int64_t s;
} mVarint;
int64_t mZigZagInt; // wire type 0
union { // wire type 1
uint64_t u;
int64_t s;
double d;
} m64Bit;
struct { // wire type 2
const char * mBuffer;
int mLen;
} mBinary;
union { // wire type 5
uint32_t u;
int32_t s;
float f;
} m32Bit;
} KeyValPair_t;
public:
SP_ProtoBufDecoder( const char * buffer, int len );
~SP_ProtoBufDecoder();
bool getNext( KeyValPair_t * pair );
bool find( int fieldNumber, KeyValPair_t * pair, int index = 0 );
void rewind();
static char * dup( const char * buffer, int len );
static int getPacked( const char * buffer, int len, uint16_t * array, int size );
static int getPacked( const char * buffer, int len, uint32_t * array, int size );
static int getPacked( const char * buffer, int len, uint64_t * array, int size );
static int getPacked( const char * buffer, int len, float * array, int size );
static int getPacked( const char * buffer, int len, double * array, int size );
private:
// @return > 0 : parse ok, consume how many bytes, -1 : unknown type
static int decodeVarint( uint64_t *value, const char *buffer );
static uint32_t decode32Bit( const char * buffer );
// @return > 0 : parse ok, consume how many bytes, -1 : unknown type
static int getPair( const char * buffer, KeyValPair_t * pair );
private:
const char * mBuffer, * mEnd;
const char * mCurr;
};
#endif
<|endoftext|> |
<commit_before>#include "infer.hpp"
#include "ast.hpp"
#include "package.hpp"
#include <sstream>
namespace type {
template<class Func>
static void iter_rows(mono self, Func func) {
assert(self.kind() == kind::row());
self.match
([&](const app& self) {
const auto e = extension::unpack(self);
func(e.attr, e.head);
iter_rows(e.tail, func);
}, [](const mono& ) { });
}
struct let {
const ::list<ast::bind> defs;
const ast::expr body;
static symbol fix() { return "__fix__"; }
// rewrite let as non-recursive let + fix **when defining functions**
static let rewrite(const ast::let& self) {
using ::list;
const list<ast::bind> defs = map(self.defs, [](ast::bind self) {
return self.value.match<ast::bind>
([&](const ast::abs& abs) {
return ast::bind{self.name,
ast::app{ast::var{fix()},
ast::abs{self.name >>= list<ast::abs::arg>(),
self.value}
>>= list<ast::expr>()}};
},
[&](const ast::expr& expr) { return self; });
});
return {defs, *self.body};
}
};
// rewrite app as nested unary applications
static ast::app rewrite(const ast::app& self) {
const ast::expr& init = *self.func;
return foldl(init, self.args, [](ast::expr func, ast::expr arg) {
return ast::app(func, arg >>= list<ast::expr>());
}).cast<ast::app>();
}
// reconstruct actual type from reified type: ... -> (type 'a) yields 'a
// note: t must be substituted
static mono reconstruct(ref<state> s, mono t) {
// std::clog << "reconstructing: " << s->generalize(t) << std::endl;
if(auto self = t.get<app>()) {
// std::clog << "ctor: " << s->generalize((*self)->ctor) << std::endl;
if((*self)->ctor == ty) {
return (*self)->arg;
}
}
auto from = s->fresh();
auto to = s->fresh();
s->unify(from >>= to, t);
return reconstruct(s, s->substitute(to));
}
static cst constructor(mono t) {
if(auto self = t.get<app>()) {
return constructor((*self)->ctor);
}
if(auto self = t.get<cst>()) {
return *self;
}
// TODO restrictive?
throw error("constructor must be a constant");
}
struct infer_visitor {
using type = mono;
template<class T>
mono operator()(const T& self, const ref<state>&) const {
throw std::logic_error("infer unimplemented: " + tool::type_name(typeid(T)));
}
// var
mono operator()(const ast::var& self, const ref<state>& s) const {
try {
return s->instantiate(s->vars->find(self.name));
} catch(std::out_of_range& e) {
throw error("unbound variable " + tool::quote(self.name.get()));
}
}
// abs
mono operator()(const ast::abs& self, const ref<state>& s) const {
// function scope
const auto sub = scope(s);
// construct function type
const mono result = s->fresh();
const mono res = foldr(result, self.args, [&](ast::abs::arg arg, mono tail) {
const mono sig = arg.match<mono>
([&](symbol self) {
// untyped arguments: trivial signature
const mono a = sub->fresh();
return a;
},
[&](ast::abs::typed self) {
// obtain reified type from annoatation
const mono t = infer(s, self.type);
// extract actual type from reified
const mono r = reconstruct(s, s->substitute(t));
// obtain type constructor from type
const cst c = constructor(r);
try {
// fetch associated signature, if any
const auto sig = s->sigs->at(c);
// instantiate signature
return sub->instantiate(sig);
} catch(std::out_of_range&) {
throw error("unknown signature " + tool::quote(c->name.get()));
}
});
const mono outer = s->fresh();
const mono inner = sub->fresh();
sub->unify(outer >>= inner, sig);
sub->def(arg.name(), outer);
// std::clog << "inner: " << sub->vars->find(arg.name()) << std::endl;
return outer >>= tail;
});
// infer lambda body with augmented environment
s->unify(result, infer(sub, *self.body));
return res;
}
// app
mono operator()(const ast::app& self, const ref<state>& s) const {
// normalize application as unary
const ast::app rw = rewrite(self);
assert(size(rw.args) == 1);
// infer func/arg types for application
const auto with_inferred = [&](auto cont) {
const mono func = infer(s, *rw.func);
const mono arg = infer(s, rw.args->head);
return cont(func, arg);
};
// obtain inner type from a type with associated signature
const auto inner_type = [&](mono t) {
// obtain type constructor from argument type
const cst c = constructor(s->substitute(t));
try {
auto sig = s->sigs->at(c);
const mono inner = s->fresh();
s->unify(t >>= inner, s->instantiate(sig));
return inner;
} catch(std::out_of_range&) {
throw error("unknown signature");
}
};
// check if application works with given func/arg type
const auto check = [&](mono func, mono arg) {
const mono ret = s->fresh();
s->unify(func , arg >>= ret);
return ret;
};
// TODO find a less stupid way of trying all cases?
try {
// normal case
return with_inferred([&](mono func, mono arg) {
return check(func, arg);
});
} catch(error& e) {
try {
// open func type and retry
return with_inferred([&](mono func, mono arg) {
const mono inner_func = inner_type(func);
return check(inner_func, arg);
});
}
catch(error& ) { }
try {
// open arg type and retry
return with_inferred([&](mono func, mono arg) {
const mono inner_arg = inner_type(arg);
return check(func, inner_arg);
});
}
catch(error& ) { }
try {
// open both func and arg types and retry
return with_inferred([&](mono func, mono arg) {
const mono inner_func = inner_type(func);
const mono inner_arg = inner_type(arg);
return check(inner_func, inner_arg);
});
}
catch(error& ) { }
throw e;
}
}
// non-recursive let
mono operator()(const let& self, const ref<state>& s) const {
auto sub = scope(s);
for(ast::bind def : self.defs) {
sub->vars->locals.emplace(def.name, s->generalize(infer(s, def.value)));
}
return infer(sub, self.body);
}
// recursive let
mono operator()(const ast::let& self, const ref<state>& s) const {
auto sub = scope(s);
const mono a = sub->fresh();
sub->def(let::fix(), (a >>= a) >>= a);
return operator()(let::rewrite(self), sub);
}
// sel
mono operator()(const ast::sel& self, const ref<state>& s) const {
const mono tail = s->fresh(kind::row());
const mono head = s->fresh(kind::term());
const mono row = ext(self.name)(head)(tail);
return record(row) >>= head;
}
// record
mono operator()(const ast::record& self, const ref<state>& s) const {
const mono init = empty;
const mono row = foldr(init, self.attrs, [&](ast::record::attr attr, mono tail) {
return ext(attr.name)(infer(s, attr.value))(tail);
});
return record(row);
}
// make
mono operator()(const ast::make& self, const ref<state>& s) const {
// get signature type
const poly sig = s->vars->find(self.type);
auto sub = scope(s);
const mono outer = s->fresh();
const mono inner = sub->fresh();
// instantiate signature at sub level prevents generalization of
// contravariant side (variables only appearing in the covariant side will
// be generalized)
s->unify(ty(outer) >>= ty(inner), sub->instantiate(sig));
// vanilla covariant type
const poly reference = sub->generalize(inner);
// build provided type
const mono init = empty;
const mono provided =
record(foldr(init, self.attrs,
[&](const ast::record::attr attr, mono tail) {
return row(attr.name, infer(sub, attr.value)) |= tail;
}));
// now also unify inner with provided type
s->unify(inner, provided);
// now generalize the provided type
const poly gen = sub->generalize(inner);
// generalization check: quantified variables in reference/gen should
// substitute to the same variables
std::set<var> quantified;
for(const var& v : gen.forall) {
assert(sub->substitute(v) == v);
quantified.insert(v);
}
// make sure all reference quantified references substitute to quantified
// variables
for(const var& v : reference.forall) {
const mono vs = sub->substitute(v);
if(auto u = vs.get<var>()) {
auto it = quantified.find(*u);
if(it != quantified.end()) {
continue;
}
}
std::stringstream ss;
logger(ss) << "failed to generalize " << gen
<< " as " << reference;
throw error(ss.str());
}
return outer;
}
// cond
mono operator()(const ast::cond& self, const ref<state>& s) const {
const mono test = infer(s, *self.test);
s->unify(test, boolean);
const mono conseq = infer(s, *self.conseq);
const mono alt = infer(s, *self.alt);
const mono result = s->fresh();
s->unify(result, conseq);
s->unify(result, alt);
return result;
}
// def
mono operator()(const ast::def& self, const ref<state>& s) const {
using ::list;
const mono value =
infer(s, ast::let(ast::bind{self.name, *self.value} >>= list<ast::bind>(),
ast::var{self.name}));
try {
s->def(self.name, value);
return io(unit);
} catch(std::runtime_error& e) {
throw error(e.what());
}
}
// use
mono operator()(const ast::use& self, const ref<state>& s) const {
// infer value type
const mono value = infer(s, *self.env);
// make sure value type is a record
const mono row = s->fresh(kind::row());
s->unify(value, record(row));
auto sub = scope(s);
// fill sub scope with record contents
iter_rows(s->substitute(row), [&](symbol attr, mono t) {
// TODO generalization issue?
sub->def(attr, t);
});
return infer(sub, *self.body);
}
// import
mono operator()(const ast::import& self, const ref<state>& s) const {
auto it = s->vars->locals.find(self.package);
if(it != s->vars->locals.end()) {
throw error("variable " + tool::quote(self.package.get()) + " already defined");
}
const package pkg = package::import(self.package);
s->vars->locals.emplace(self.package, pkg.sig());
return io(unit);
}
// lit
mono operator()(const ast::lit<::unit>& self, const ref<state>&) const {
return unit;
}
mono operator()(const ast::lit<::boolean>& self, const ref<state>&) const {
return boolean;
}
mono operator()(const ast::lit<::integer>& self, const ref<state>&) const {
return integer;
}
mono operator()(const ast::lit<::real>& self, const ref<state>&) const {
return real;
}
};
mono infer(const ref<state>& s, const ast::expr& self) {
return self.visit(infer_visitor(), s);
}
}
<commit_msg>refactor a bit<commit_after>#include "infer.hpp"
#include "ast.hpp"
#include "package.hpp"
#include <sstream>
namespace type {
template<class Func>
static void iter_rows(mono self, Func func) {
assert(self.kind() == kind::row());
self.match
([&](const app& self) {
const auto e = extension::unpack(self);
func(e.attr, e.head);
iter_rows(e.tail, func);
}, [](const mono& ) { });
}
struct let {
const ::list<ast::bind> defs;
const ast::expr body;
static symbol fix() { return "__fix__"; }
// rewrite let as non-recursive let + fix **when defining functions**
static let rewrite(const ast::let& self) {
using ::list;
const list<ast::bind> defs = map(self.defs, [](ast::bind self) {
return self.value.match<ast::bind>
([&](const ast::abs& abs) {
return ast::bind{self.name,
ast::app{ast::var{fix()},
ast::abs{self.name >>= list<ast::abs::arg>(),
self.value}
>>= list<ast::expr>()}};
},
[&](const ast::expr& expr) { return self; });
});
return {defs, *self.body};
}
};
// rewrite app as nested unary applications
static ast::app rewrite(const ast::app& self) {
const ast::expr& init = *self.func;
return foldl(init, self.args, [](ast::expr func, ast::expr arg) {
return ast::app(func, arg >>= list<ast::expr>());
}).cast<ast::app>();
}
// reconstruct actual type from reified type: ... -> (type 'a) yields 'a
// note: t must be substituted
static mono reconstruct(ref<state> s, mono t) {
// std::clog << "reconstructing: " << s->generalize(t) << std::endl;
if(auto self = t.get<app>()) {
// std::clog << "ctor: " << s->generalize((*self)->ctor) << std::endl;
if((*self)->ctor == ty) {
return (*self)->arg;
}
}
auto from = s->fresh();
auto to = s->fresh();
s->unify(from >>= to, t);
return reconstruct(s, s->substitute(to));
}
// obtain constructor for a monotype
static cst constructor(mono t) {
if(auto self = t.get<app>()) {
return constructor((*self)->ctor);
}
if(auto self = t.get<cst>()) {
return *self;
}
// TODO restrictive?
throw error("constructor must be a constant");
}
template<class T>
static mono infer(const ref<T>& s, const T& self) {
throw std::logic_error("infer unimplemented: " + tool::type_name(typeid(T)));
}
// var
static mono infer(const ref<state>& s, const ast::var& self) {
try {
return s->instantiate(s->vars->find(self.name));
} catch(std::out_of_range& e) {
throw error("unbound variable " + tool::quote(self.name.get()));
}
}
// abs
static mono infer(const ref<state>& s, const ast::abs& self) {
// function scope
const auto sub = scope(s);
// construct function type
const mono result = s->fresh();
const mono res = foldr(result, self.args, [&](ast::abs::arg arg, mono tail) {
const mono sig = arg.match<mono>([&](symbol self) {
// untyped arguments: trivial signature
const mono a = sub->fresh();
return a;
},
[&](ast::abs::typed self) {
// obtain reified type from annoatation
const mono t = infer(s, self.type);
// extract actual type from reified
const mono r = reconstruct(s, s->substitute(t));
// obtain type constructor from type
const cst c = constructor(r);
try {
// fetch associated signature, if any
const auto sig = s->sigs->at(c);
// instantiate signature
return sub->instantiate(sig);
} catch(std::out_of_range&) {
throw error("unknown signature " + tool::quote(c->name.get()));
}
});
const mono outer = s->fresh();
const mono inner = sub->fresh();
sub->unify(outer >>= inner, sig);
sub->def(arg.name(), outer);
// std::clog << "inner: " << sub->vars->find(arg.name()) << std::endl;
return outer >>= tail;
});
// infer lambda body with augmented environment
s->unify(result, infer(sub, *self.body));
return res;
}
// app
static mono infer(const ref<state>& s, const ast::app& self) {
// normalize application as unary
const ast::app rw = rewrite(self);
assert(size(rw.args) == 1);
// infer func/arg types for application
const auto with_inferred = [&](auto cont) {
const mono func = infer(s, *rw.func);
const mono arg = infer(s, rw.args->head);
return cont(func, arg);
};
// obtain inner type from a type with associated signature
const auto inner_type = [&](mono t) {
// obtain type constructor from argument type
const cst c = constructor(s->substitute(t));
try {
auto sig = s->sigs->at(c);
const mono inner = s->fresh();
s->unify(t >>= inner, s->instantiate(sig));
return inner;
} catch(std::out_of_range&) {
throw error("unknown signature");
}
};
// check if application works with given func/arg type
const auto check = [&](mono func, mono arg) {
const mono ret = s->fresh();
s->unify(func , arg >>= ret);
return ret;
};
// TODO find a less stupid way of trying all cases?
try {
// normal case
return with_inferred([&](mono func, mono arg) {
return check(func, arg);
});
} catch(error& e) {
try {
// open func type and retry
return with_inferred([&](mono func, mono arg) {
const mono inner_func = inner_type(func);
return check(inner_func, arg);
});
}
catch(error& ) { }
try {
// open arg type and retry
return with_inferred([&](mono func, mono arg) {
const mono inner_arg = inner_type(arg);
return check(func, inner_arg);
});
}
catch(error& ) { }
try {
// open both func and arg types and retry
return with_inferred([&](mono func, mono arg) {
const mono inner_func = inner_type(func);
const mono inner_arg = inner_type(arg);
return check(inner_func, inner_arg);
});
}
catch(error& ) { }
throw e;
}
}
// non-recursive let
static mono infer(const ref<state>& s, const let& self) {
auto sub = scope(s);
for(ast::bind def : self.defs) {
sub->vars->locals.emplace(def.name, s->generalize(infer(s, def.value)));
}
return infer(sub, self.body);
}
// recursive let
static mono infer(const ref<state>& s, const ast::let& self) {
auto sub = scope(s);
const mono a = sub->fresh();
sub->def(let::fix(), (a >>= a) >>= a);
return infer(sub, let::rewrite(self));
}
// sel
static mono infer(const ref<state>& s, const ast::sel& self) {
const mono tail = s->fresh(kind::row());
const mono head = s->fresh(kind::term());
const mono row = ext(self.name)(head)(tail);
return record(row) >>= head;
}
// record
static mono infer(const ref<state>& s, const ast::record& self) {
const mono init = empty;
const mono row = foldr(init, self.attrs, [&](ast::record::attr attr, mono tail) {
return ext(attr.name)(infer(s, attr.value))(tail);
});
return record(row);
}
// make
static mono infer(const ref<state>& s, const ast::make& self) {
// get signature type
const poly sig = s->vars->find(self.type);
auto sub = scope(s);
const mono outer = s->fresh();
const mono inner = sub->fresh();
// instantiate signature at sub level prevents generalization of
// contravariant side (variables only appearing in the covariant side will
// be generalized)
s->unify(ty(outer) >>= ty(inner), sub->instantiate(sig));
// vanilla covariant type
const poly reference = sub->generalize(inner);
// build provided type
const mono init = empty;
const mono provided =
record(foldr(init, self.attrs,
[&](const ast::record::attr attr, mono tail) {
return row(attr.name, infer(sub, attr.value)) |= tail;
}));
// now also unify inner with provided type
s->unify(inner, provided);
// now generalize the provided type
const poly gen = sub->generalize(inner);
// generalization check: quantified variables in reference/gen should
// substitute to the same variables
std::set<var> quantified;
for(const var& v : gen.forall) {
assert(sub->substitute(v) == v);
quantified.insert(v);
}
// make sure all reference quantified references substitute to quantified
// variables
for(const var& v : reference.forall) {
const mono vs = sub->substitute(v);
if(auto u = vs.get<var>()) {
auto it = quantified.find(*u);
if(it != quantified.end()) {
continue;
}
}
std::stringstream ss;
logger(ss) << "failed to generalize " << gen
<< " as " << reference;
throw error(ss.str());
}
return outer;
}
// cond
static mono infer(const ref<state>& s, const ast::cond& self) {
const mono test = infer(s, *self.test);
s->unify(test, boolean);
const mono conseq = infer(s, *self.conseq);
const mono alt = infer(s, *self.alt);
const mono result = s->fresh();
s->unify(result, conseq);
s->unify(result, alt);
return result;
}
// def
static mono infer(const ref<state>& s, const ast::def& self) {
const mono value =
infer(s, ast::let(ast::bind{self.name, *self.value} >>= list<ast::bind>(),
ast::var{self.name}));
try {
s->def(self.name, value);
return io(unit);
} catch(std::runtime_error& e) {
throw error(e.what());
}
}
// use
static mono infer(const ref<state>& s, const ast::use& self) {
// infer value type
const mono value = infer(s, *self.env);
// make sure value type is a record
const mono row = s->fresh(kind::row());
s->unify(value, record(row));
auto sub = scope(s);
// fill sub scope with record contents
iter_rows(s->substitute(row), [&](symbol attr, mono t) {
// TODO generalization issue?
sub->def(attr, t);
});
return infer(sub, *self.body);
}
// import
static mono infer(const ref<state>& s, const ast::import& self) {
auto it = s->vars->locals.find(self.package);
if(it != s->vars->locals.end()) {
throw error("variable " + tool::quote(self.package.get()) + " already defined");
}
const package pkg = package::import(self.package);
s->vars->locals.emplace(self.package, pkg.sig());
return io(unit);
}
// lit
static mono infer(const ref<state>&, const ast::lit<::boolean>& self) {
return boolean;
}
static mono infer(const ref<state>&, const ast::lit<::integer>& self) {
return integer;
}
static mono infer(const ref<state>&, const ast::lit<::real>& self) {
return real;
}
struct infer_visitor {
using type = mono;
template<class T>
mono operator()(const T& self, const ref<state>& s) const {
return infer(s, self);
}
};
mono infer(const ref<state>& s, const ast::expr& self) {
return self.visit(infer_visitor(), s);
}
}
<|endoftext|> |
<commit_before>
#include <Beard/detail/gr_ceformat.hpp>
#include <Beard/tty/TerminalInfo.hpp>
#include <duct/EndianUtils.hpp>
#include <duct/IO/arithmetic.hpp>
#include <duct/IO/unicode.hpp>
#include <istream>
namespace Beard {
namespace tty {
// class TerminalInfo implementation
#define BEARD_SCOPE_CLASS tty::TerminalInfo
TerminalInfo::~TerminalInfo() noexcept = default;
TerminalInfo::TerminalInfo() noexcept
: m_initialized(false)
, m_names()
, m_cap_flags()
, m_cap_numbers()
, m_cap_strings()
{}
TerminalInfo::TerminalInfo(TerminalInfo&&) noexcept = default;
TerminalInfo::TerminalInfo(TerminalInfo const&) = default;
TerminalInfo& TerminalInfo::operator=(TerminalInfo&&) noexcept = default;
// serialization
// TODO: <tic.h> specifies some differences:
// 1. max names field size is 512 (XSI);
// 2. there are two different "signed" values specifying
// different meanings for capabilities;
// terminfo format:
/*
uint16_t magic = 0x011a
uint16_t names_size
uint16_t flag_count
uint16_t number_count
uint16_t string_offset_count
uint16_t string_table_size
// Names for terminal type, separated by '|'
char names[names_size]
// Boolean flags
uint8_t flags[flag_count]
// Seek ahead to align to 2-byte word (ergo: possible dead byte)
uint16_t numbers[number_count]
// Offsets are relative to string_table
uint16_t string_offsets[string_offset_count]
char string_table[string_table_size]
*/
namespace {
enum : unsigned {
terminfo_magic = 0x011a,
terminfo_max_names_size = 128u,
terminfo_table_offset_empty = 0xFFFFu,
mask_offset_signbit = 0x8000,
};
constexpr auto const
terminfo_endian = duct::Endian::LITTLE;
struct terminfo_header {
uint16_t magic{0};
uint16_t names_size{0};
uint16_t flag_count{0};
uint16_t number_count{0};
uint16_t string_offset_count{0};
uint16_t string_table_size{0};
};
} // anonymous namespace
#define BEARD_TERMINFO_CHECK_IO_ERROR_(m_) \
if (stream.fail()) { \
BEARD_THROW_FQN( \
ErrorCode::serialization_io_failed, \
m_ \
); \
}
//
#define BEARD_SCOPE_FUNC deserialize
namespace {
BEARD_DEF_FMT_FQN(
s_err_bad_magic,
"bad magic encountered: expected %-#04x, got %-#04x"
);
BEARD_DEF_FMT_FQN(
s_err_name_too_large,
"names section too large: expected s <= %u, got s = %u"
);
BEARD_DEF_FMT_FQN(
s_err_string_offset_invalid,
"index %u offset %u overflows string table (size = %u)"
);
} // anonymous namespace
void
TerminalInfo::deserialize(
std::istream& stream
) {
m_initialized = false;
m_names.clear();
m_cap_flags.clear();
m_cap_numbers.clear();
m_cap_strings.clear();
terminfo_header hdr{};
// header
duct::IO::read_arithmetic(stream, hdr.magic, terminfo_endian);
duct::IO::read_arithmetic(stream, hdr.names_size, terminfo_endian);
duct::IO::read_arithmetic(stream, hdr.flag_count, terminfo_endian);
duct::IO::read_arithmetic(stream, hdr.number_count, terminfo_endian);
duct::IO::read_arithmetic(stream, hdr.string_offset_count, terminfo_endian);
duct::IO::read_arithmetic(stream, hdr.string_table_size, terminfo_endian);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read header"
);
if (terminfo_magic != hdr.magic) {
BEARD_THROW_FMT(
ErrorCode::serialization_data_malformed,
s_err_bad_magic,
static_cast<unsigned>(terminfo_magic),
static_cast<unsigned>(hdr.magic)
);
}
if (terminfo_max_names_size < hdr.names_size) {
BEARD_THROW_FMT(
ErrorCode::serialization_data_malformed,
s_err_name_too_large,
static_cast<unsigned>(terminfo_max_names_size),
static_cast<unsigned>(hdr.names_size)
);
}
// names
// Assuming ASCII encoding -- compatible with UTF-8, so no
// decoding necessary.
String names_glob{};
duct::IO::read_string_copy(
stream,
names_glob,
static_cast<std::size_t>(hdr.names_size),
terminfo_endian
);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read names field"
);
if (0u < names_glob.size() && '\0' == *names_glob.crbegin()) {
names_glob.pop_back();
}
String::size_type pos = 0u, next = String::npos;
for (;;) {
next = names_glob.find('|', pos + 1u);
if (String::npos == next) {
m_names.emplace_back(names_glob.substr(pos, String::npos));
break;
} else if (next > (pos + 1u)) {
m_names.emplace_back(names_glob.substr(pos, next - pos));
pos = next + 1u;
} else {
// next <= pos (empty block)
++pos;
continue;
}
}
// flags
m_cap_flags.resize(static_cast<std::size_t>(hdr.flag_count));
duct::IO::read_arithmetic_array(
stream,
m_cap_flags.data(),
m_cap_flags.size(),
terminfo_endian
);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read flag section"
);
// align
// names_size and flag_count will indicate unalignment if
// their sum is uneven because their respective elements are
// bytes.
if ((hdr.names_size + hdr.flag_count) % 2) {
char dead_byte;
stream.read(&dead_byte, 1u);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read dead byte for alignment"
);
}
// numbers
m_cap_numbers.resize(static_cast<std::size_t>(hdr.number_count));
duct::IO::read_arithmetic_array(
stream,
m_cap_numbers.data(),
m_cap_numbers.size(),
terminfo_endian
);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read number section"
);
// string offsets
aux::vector<uint16_t> string_offsets(
static_cast<std::size_t>(hdr.string_offset_count)
);
duct::IO::read_arithmetic_array(
stream,
string_offsets.data(),
string_offsets.size(),
terminfo_endian
);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read string offsets section"
);
// string table
// Again assuming ASCII.
aux::vector<char> string_table(
static_cast<std::size_t>(hdr.string_table_size)
);
duct::IO::read(
stream,
string_table.data(),
string_table.size()
);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read string table"
);
unsigned index = 0u, offset = 0u;
auto
it_start = string_table.cend(),
it_cnull = it_start
;
for (
auto it = string_offsets.cbegin();
string_offsets.cend() != it;
++it, ++index
) {
offset = static_cast<unsigned>(*it);
// -1 means terminal does not support capability, and
// "other negative values are illegal".
// And in Unix fashion, /you will get illegal values/.
if (
terminfo_table_offset_empty == offset
|| (mask_offset_signbit & offset)
) {
continue;
}
if (string_table.size() <= offset) {
BEARD_THROW_FMT(
ErrorCode::serialization_data_malformed,
s_err_string_offset_invalid,
index,
offset,
string_table.size()
);
}
it_start = string_table.cbegin() + offset;
it_cnull = std::find(
it_start,
string_table.cend(),
'\0'
);
m_cap_strings.emplace(
index,
String{it_start, it_cnull}
);
}
m_initialized = true;
}
#undef BEARD_SCOPE_FUNC
#undef BEARD_SCOPE_CLASS
} // namespace tty
} // namespace Beard
<commit_msg>Corrected references to duct::Endian members.¹<commit_after>
#include <Beard/detail/gr_ceformat.hpp>
#include <Beard/tty/TerminalInfo.hpp>
#include <duct/EndianUtils.hpp>
#include <duct/IO/arithmetic.hpp>
#include <duct/IO/unicode.hpp>
#include <istream>
namespace Beard {
namespace tty {
// class TerminalInfo implementation
#define BEARD_SCOPE_CLASS tty::TerminalInfo
TerminalInfo::~TerminalInfo() noexcept = default;
TerminalInfo::TerminalInfo() noexcept
: m_initialized(false)
, m_names()
, m_cap_flags()
, m_cap_numbers()
, m_cap_strings()
{}
TerminalInfo::TerminalInfo(TerminalInfo&&) noexcept = default;
TerminalInfo::TerminalInfo(TerminalInfo const&) = default;
TerminalInfo& TerminalInfo::operator=(TerminalInfo&&) noexcept = default;
// serialization
// TODO: <tic.h> specifies some differences:
// 1. max names field size is 512 (XSI);
// 2. there are two different "signed" values specifying
// different meanings for capabilities;
// terminfo format:
/*
uint16_t magic = 0x011a
uint16_t names_size
uint16_t flag_count
uint16_t number_count
uint16_t string_offset_count
uint16_t string_table_size
// Names for terminal type, separated by '|'
char names[names_size]
// Boolean flags
uint8_t flags[flag_count]
// Seek ahead to align to 2-byte word (ergo: possible dead byte)
uint16_t numbers[number_count]
// Offsets are relative to string_table
uint16_t string_offsets[string_offset_count]
char string_table[string_table_size]
*/
namespace {
enum : unsigned {
terminfo_magic = 0x011a,
terminfo_max_names_size = 128u,
terminfo_table_offset_empty = 0xFFFFu,
mask_offset_signbit = 0x8000,
};
constexpr auto const
terminfo_endian = duct::Endian::little;
struct terminfo_header {
uint16_t magic{0};
uint16_t names_size{0};
uint16_t flag_count{0};
uint16_t number_count{0};
uint16_t string_offset_count{0};
uint16_t string_table_size{0};
};
} // anonymous namespace
#define BEARD_TERMINFO_CHECK_IO_ERROR_(m_) \
if (stream.fail()) { \
BEARD_THROW_FQN( \
ErrorCode::serialization_io_failed, \
m_ \
); \
}
//
#define BEARD_SCOPE_FUNC deserialize
namespace {
BEARD_DEF_FMT_FQN(
s_err_bad_magic,
"bad magic encountered: expected %-#04x, got %-#04x"
);
BEARD_DEF_FMT_FQN(
s_err_name_too_large,
"names section too large: expected s <= %u, got s = %u"
);
BEARD_DEF_FMT_FQN(
s_err_string_offset_invalid,
"index %u offset %u overflows string table (size = %u)"
);
} // anonymous namespace
void
TerminalInfo::deserialize(
std::istream& stream
) {
m_initialized = false;
m_names.clear();
m_cap_flags.clear();
m_cap_numbers.clear();
m_cap_strings.clear();
terminfo_header hdr{};
// header
duct::IO::read_arithmetic(stream, hdr.magic, terminfo_endian);
duct::IO::read_arithmetic(stream, hdr.names_size, terminfo_endian);
duct::IO::read_arithmetic(stream, hdr.flag_count, terminfo_endian);
duct::IO::read_arithmetic(stream, hdr.number_count, terminfo_endian);
duct::IO::read_arithmetic(stream, hdr.string_offset_count, terminfo_endian);
duct::IO::read_arithmetic(stream, hdr.string_table_size, terminfo_endian);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read header"
);
if (terminfo_magic != hdr.magic) {
BEARD_THROW_FMT(
ErrorCode::serialization_data_malformed,
s_err_bad_magic,
static_cast<unsigned>(terminfo_magic),
static_cast<unsigned>(hdr.magic)
);
}
if (terminfo_max_names_size < hdr.names_size) {
BEARD_THROW_FMT(
ErrorCode::serialization_data_malformed,
s_err_name_too_large,
static_cast<unsigned>(terminfo_max_names_size),
static_cast<unsigned>(hdr.names_size)
);
}
// names
// Assuming ASCII encoding -- compatible with UTF-8, so no
// decoding necessary.
String names_glob{};
duct::IO::read_string_copy(
stream,
names_glob,
static_cast<std::size_t>(hdr.names_size),
terminfo_endian
);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read names field"
);
if (0u < names_glob.size() && '\0' == *names_glob.crbegin()) {
names_glob.pop_back();
}
String::size_type pos = 0u, next = String::npos;
for (;;) {
next = names_glob.find('|', pos + 1u);
if (String::npos == next) {
m_names.emplace_back(names_glob.substr(pos, String::npos));
break;
} else if (next > (pos + 1u)) {
m_names.emplace_back(names_glob.substr(pos, next - pos));
pos = next + 1u;
} else {
// next <= pos (empty block)
++pos;
continue;
}
}
// flags
m_cap_flags.resize(static_cast<std::size_t>(hdr.flag_count));
duct::IO::read_arithmetic_array(
stream,
m_cap_flags.data(),
m_cap_flags.size(),
terminfo_endian
);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read flag section"
);
// align
// names_size and flag_count will indicate unalignment if
// their sum is uneven because their respective elements are
// bytes.
if ((hdr.names_size + hdr.flag_count) % 2) {
char dead_byte;
stream.read(&dead_byte, 1u);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read dead byte for alignment"
);
}
// numbers
m_cap_numbers.resize(static_cast<std::size_t>(hdr.number_count));
duct::IO::read_arithmetic_array(
stream,
m_cap_numbers.data(),
m_cap_numbers.size(),
terminfo_endian
);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read number section"
);
// string offsets
aux::vector<uint16_t> string_offsets(
static_cast<std::size_t>(hdr.string_offset_count)
);
duct::IO::read_arithmetic_array(
stream,
string_offsets.data(),
string_offsets.size(),
terminfo_endian
);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read string offsets section"
);
// string table
// Again assuming ASCII.
aux::vector<char> string_table(
static_cast<std::size_t>(hdr.string_table_size)
);
duct::IO::read(
stream,
string_table.data(),
string_table.size()
);
BEARD_TERMINFO_CHECK_IO_ERROR_(
"failed to read string table"
);
unsigned index = 0u, offset = 0u;
auto
it_start = string_table.cend(),
it_cnull = it_start
;
for (
auto it = string_offsets.cbegin();
string_offsets.cend() != it;
++it, ++index
) {
offset = static_cast<unsigned>(*it);
// -1 means terminal does not support capability, and
// "other negative values are illegal".
// And in Unix fashion, /you will get illegal values/.
if (
terminfo_table_offset_empty == offset
|| (mask_offset_signbit & offset)
) {
continue;
}
if (string_table.size() <= offset) {
BEARD_THROW_FMT(
ErrorCode::serialization_data_malformed,
s_err_string_offset_invalid,
index,
offset,
string_table.size()
);
}
it_start = string_table.cbegin() + offset;
it_cnull = std::find(
it_start,
string_table.cend(),
'\0'
);
m_cap_strings.emplace(
index,
String{it_start, it_cnull}
);
}
m_initialized = true;
}
#undef BEARD_SCOPE_FUNC
#undef BEARD_SCOPE_CLASS
} // namespace tty
} // namespace Beard
<|endoftext|> |
<commit_before><commit_msg>coverity#1079279 Uninitialized scalar field<commit_after><|endoftext|> |
<commit_before><commit_msg>Send the V8 histograms to UMA<commit_after><|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkSurfaceToImageFilter.h"
#include "mitkDataTreeNodeFactory.h"
#include "mitkPicFileWriter.h"
#include <vtkPolyData.h>
#include <fstream>
int mitkSurfaceToImageFilterTest(int argc, char* argv[])
{
mitk::SurfaceToImageFilter::Pointer s2iFilter;
std::cout << "Testing mitk::Surface::New(): " << std::flush;
s2iFilter = mitk::SurfaceToImageFilter::New();
if (s2iFilter.IsNull())
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
else
{
std::cout<<"[PASSED]"<<std::endl;
}
std::cout << "Loading file: " << std::flush;
if(argc==0)
{
std::cout<<"no file specified [FAILED]"<<std::endl;
return EXIT_FAILURE;
}
mitk::Surface::Pointer surface = NULL;
mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New();
try
{
std::cout<<argv[1]<<std::endl;
factory->SetFileName( argv[1] );
factory->Update();
if(factory->GetNumberOfOutputs()<1)
{
std::cout<<"file could not be loaded [FAILED]"<<std::endl;
return EXIT_FAILURE;
}
mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 );
surface = dynamic_cast<mitk::Surface*>(node->GetData());
if(surface.IsNull())
{
std::cout<<"file not a surface - test will not be applied [PASSED]"<<std::endl;
std::cout<<"[TEST DONE]"<<std::endl;
return EXIT_SUCCESS;
}
}
catch ( itk::ExceptionObject & ex )
{
std::cout << "Exception: " << ex << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Testing number of points of surface: " << std::flush;
if(surface->GetVtkPolyData()->GetNumberOfPoints() == 0)
{
std::cout<<"number of points is 0 - test will not be applied [PASSED]"<<std::endl;
std::cout<<"[TEST DONE]"<<std::endl;
return EXIT_SUCCESS;
}
std::cout << "Testing creation of mitk::Image with same Geometry as Surface: " << std::flush;
mitk::Image::Pointer image = mitk::Image::New();
surface->UpdateOutputInformation(); //should not be necessary, bug #1536
image->Initialize(typeid(unsigned char), *surface->GetGeometry());
std::cout << "Testing mitk::SurfaceToImageFilter::MakeOutputBinaryOn(): " << std::flush;
s2iFilter->MakeOutputBinaryOn();
std::cout<<"[PASSED]"<<std::endl;
std::cout << "Testing mitk::SurfaceToImageFilter::SetInput(): " << std::flush;
s2iFilter->SetInput(surface);
std::cout<<"[PASSED]"<<std::endl;
std::cout << "Testing mitk::SurfaceToImageFilter::SetImage(): " << std::flush;
s2iFilter->SetImage(image);
std::cout<<"[PASSED]"<<std::endl;
std::cout << "Testing mitk::SurfaceToImageFilter::Update(): " << std::flush;
s2iFilter->Update();
std::cout<<"[PASSED]"<<std::endl;
//mitk::PicFileWriter::Pointer picWriter = mitk::PicFileWriter::New();
//picWriter->SetInput(s2iFilter->GetOutput());
//picWriter->SetFileName("SurfaceToImageFilterTestOutput.pic");
//picWriter->Write();
std::cout<<"[TEST DONE]"<<std::endl;
return EXIT_SUCCESS;
}
<commit_msg>FIX (#1536): BoundingBox of Surface objects sometimes not initialized<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkSurfaceToImageFilter.h"
#include "mitkDataTreeNodeFactory.h"
#include "mitkPicFileWriter.h"
#include <vtkPolyData.h>
#include <fstream>
int mitkSurfaceToImageFilterTest(int argc, char* argv[])
{
mitk::SurfaceToImageFilter::Pointer s2iFilter;
std::cout << "Testing mitk::Surface::New(): " << std::flush;
s2iFilter = mitk::SurfaceToImageFilter::New();
if (s2iFilter.IsNull())
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
else
{
std::cout<<"[PASSED]"<<std::endl;
}
std::cout << "Loading file: " << std::flush;
if(argc==0)
{
std::cout<<"no file specified [FAILED]"<<std::endl;
return EXIT_FAILURE;
}
mitk::Surface::Pointer surface = NULL;
mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New();
try
{
std::cout<<argv[1]<<std::endl;
factory->SetFileName( argv[1] );
factory->Update();
if(factory->GetNumberOfOutputs()<1)
{
std::cout<<"file could not be loaded [FAILED]"<<std::endl;
return EXIT_FAILURE;
}
mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 );
surface = dynamic_cast<mitk::Surface*>(node->GetData());
if(surface.IsNull())
{
std::cout<<"file not a surface - test will not be applied [PASSED]"<<std::endl;
std::cout<<"[TEST DONE]"<<std::endl;
return EXIT_SUCCESS;
}
}
catch ( itk::ExceptionObject & ex )
{
std::cout << "Exception: " << ex << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Testing number of points of surface: " << std::flush;
if(surface->GetVtkPolyData()->GetNumberOfPoints() == 0)
{
std::cout<<"number of points is 0 - test will not be applied [PASSED]"<<std::endl;
std::cout<<"[TEST DONE]"<<std::endl;
return EXIT_SUCCESS;
}
std::cout << "Testing creation of mitk::Image with same Geometry as Surface: " << std::flush;
mitk::Image::Pointer image = mitk::Image::New();
//surface->UpdateOutputInformation(); //is not necessary anymore (bug #1536), should never be neccessary
image->Initialize(typeid(unsigned char), *surface->GetGeometry());
std::cout << "Testing mitk::SurfaceToImageFilter::MakeOutputBinaryOn(): " << std::flush;
s2iFilter->MakeOutputBinaryOn();
std::cout<<"[PASSED]"<<std::endl;
std::cout << "Testing mitk::SurfaceToImageFilter::SetInput(): " << std::flush;
s2iFilter->SetInput(surface);
std::cout<<"[PASSED]"<<std::endl;
std::cout << "Testing mitk::SurfaceToImageFilter::SetImage(): " << std::flush;
s2iFilter->SetImage(image);
std::cout<<"[PASSED]"<<std::endl;
std::cout << "Testing mitk::SurfaceToImageFilter::Update(): " << std::flush;
s2iFilter->Update();
std::cout<<"[PASSED]"<<std::endl;
//mitk::PicFileWriter::Pointer picWriter = mitk::PicFileWriter::New();
//picWriter->SetInput(s2iFilter->GetOutput());
//picWriter->SetFileName("SurfaceToImageFilterTestOutput.pic");
//picWriter->Write();
std::cout<<"[TEST DONE]"<<std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <actionlib/client/terminal_state.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <move_basic/queued_action_server.h>
#include <queue>
#include <memory>
#include <mutex>
#include <condition_variable>
class GoalQueueSuite : public ::testing::Test {
protected:
virtual void SetUp() {
resetFlags();
ros::NodeHandle actionNh("");
qserv.reset(new actionlib::QueuedActionServer<move_base_msgs::MoveBaseAction> (actionNh, "queue_server", boost::bind(&GoalQueueSuite::executeCallback, this, _1)));
cli.reset(new actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> ("queue_server", true)); // true -> don't need ros::spin()
qserv->start();
}
virtual void TearDown() {
// Kill the executeCallback if it is running
// New Scope so that lock_guard destructs and unlocks
{
std::lock_guard<std::mutex> lk1(execute_lock);
finish_executing = true;
execute_cv.notify_one(); // Releases one waiting thread
}
qserv->shutdown();
}
// TODO: Making sure it gets called at the right time (flags!) - in its own thread
void executeCallback(const move_base_msgs::MoveBaseGoalConstPtr &msg) {
resetFlags();
got_goal = true;
received_goal = msg;
while (true) {
if (qserv->isPreemptRequested()) {
goal_preempted = true;
} else {
goal_preempted = false;
}
if (qserv->isNewGoalAvailable()) {
next_goal_available = true;
} else {
next_goal_available = false;
}
// Wait until signalled to end
std::unique_lock<std::mutex> lk(execute_lock);
execute_cv.wait(lk,
//lambda function to wait on our bool variables
[this](){return finish_executing || resume_executing;} // blocks only if lambda returns false
);
// We were requested to stop, so we stop
if (finish_executing) {
break;
}
}
// Signal that we are done here
std::lock_guard<std::mutex> lk(execute_done_lock);
execute_done = true;
execute_done_cv.notify_all(); // Releases all waiting thread
}
// Helper function to signal the executeCallback to end
void finishExecuting() {
// New Scope so that lock_guard destructs and unlocks
{
std::lock_guard<std::mutex> lk1(execute_lock);
finish_executing = true;
execute_cv.notify_one(); //unlocks lambda waiting function in ExecuteCallback
}
// Wait for execute callback to actually finish
std::unique_lock<std::mutex> lk2(execute_done_lock);
execute_done_cv.wait(lk2, [this]() {return execute_done;}); // at the end of ExecuteCallback
}
// Helper function to signal the executeCallback to resume
// This is useful for seeing if the callback code sees a preempt
void resumeExecuting() {
std::lock_guard<std::mutex> lk(execute_lock);
resume_executing = true;
execute_cv.notify_one();
}
void resetFlags() {
got_goal = false;
goal_preempted = false;
next_goal_available = false;
received_goal = nullptr;
// Signal flags
finish_executing = false;
resume_executing = false;
execute_done = false;
}
// Flags for assertions
bool got_goal;
bool goal_preempted;
bool next_goal_available;
move_base_msgs::MoveBaseGoalConstPtr received_goal;
// Signaling variables
bool finish_executing;
bool resume_executing;
bool execute_done;
std::mutex execute_lock;
std::mutex execute_done_lock;
std::condition_variable execute_cv;
std::condition_variable execute_done_cv;
std::unique_ptr<actionlib::QueuedActionServer<move_base_msgs::MoveBaseAction>> qserv;
std::unique_ptr<actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>> cli;
};
// IMPORTANT: Time delays and ros::spinOnce() sequence should stay the same, otherwise, strange things happen
TEST_F(GoalQueueSuite, establishDuplex) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
finishExecuting();
ASSERT_TRUE(got_goal);
ASSERT_FALSE(goal_preempted);
ASSERT_FALSE(next_goal_available);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
}
TEST_F(GoalQueueSuite, addGoalWhileExecuting) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
// First goal
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Cancelling the first goal - PITFALL
resumeExecuting();
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
ASSERT_TRUE(goal_preempted);
// Finish the preempted goal
finishExecuting();
// "Second" goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(7.0, received_goal->target_pose.pose.position.x);
// Third goal
goal.target_pose.pose.position.x = 13.0;
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
resumeExecuting();
// Make sure that the "second" goal is still executing, but a new goal is seen
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(7.0, received_goal->target_pose.pose.position.x);
ASSERT_FALSE(goal_preempted);
//ASSERT_TRUE(next_goal_available); // TODO: Fails when changing other code???
// Finish the "second" goal, then the 3nd goal should start executing
finishExecuting();
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_FALSE(goal_preempted);
ASSERT_FALSE(next_goal_available);
ASSERT_EQ(13.0, received_goal->target_pose.pose.position.x);
finishExecuting(); // Finish the 3nd goal
/*
- if another goal is received add it to the queue (DONE)
- if the queue full, set the current goal as preempted - explicitly called! - so cancelling the current goal and start executing the next one
- start executing the next goal in queue (the one after the preempted)
*/
}
TEST_F(GoalQueueSuite, goalPreempting) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
// One goal -> Cancel request -> Stop
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(1.0).sleep(); // TODO: Make this disappear
ASSERT_TRUE(got_goal);
ASSERT_TRUE(qserv->isActive());
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
resumeExecuting();
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
ASSERT_TRUE(goal_preempted);
finishExecuting(); // Finish the goal
ros::spinOnce();
ros::Duration(1.0).sleep();
ASSERT_FALSE(qserv->isActive());
// Two goals -> Cancel current goal -> Start executing the second
// First goal
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Cancelling the first goal - PITFALL
resumeExecuting();
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
ASSERT_TRUE(goal_preempted);
// Finish the preempted goal
finishExecuting(); // Finish 1st goal
// "Second" goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(7.0, received_goal->target_pose.pose.position.x); // call FINISH!
finishExecuting(); // Finish 2nd goal
// - if a cancel request is received for the current goal, set it as preempted (DONE)
// - if there another goal, start executing it
// - if no goal, stop (DONE)
}
TEST_F(GoalQueueSuite, goalCancelling) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
// Two goals -> Cancel current goal -> Start executing the second
// First goal
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Second goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ros::spinOnce();
// Cancelling the second goal
cli->cancelGoal();
ros::Duration(1.0).sleep();
ros::spinOnce();
//ASSERT_TRUE(goal_preempted); // TODO: Why is this failling?
resumeExecuting();
ASSERT_TRUE(qserv->isActive());
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
finishExecuting();
//ASSERT_FALSE(qserv->isActive()); // TODO: Why is this failling?
// - if a cancel request on the "next_goal" received, remove it from the queue and set it as cancelled
}
// Two more TEST_F missing and a pitfall
int main(int argc, char **argv) {
ros::init(argc, argv, "goal_queueing_test");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Chronologic ExecuteCallback looping.<commit_after>#include <gtest/gtest.h>
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <actionlib/client/terminal_state.h>
#include <move_base_msgs/MoveBaseAction.h>
#include <move_basic/queued_action_server.h>
#include <queue>
#include <memory>
#include <mutex>
#include <condition_variable>
class GoalQueueSuite : public ::testing::Test {
protected:
virtual void SetUp() {
resetFlags();
ros::NodeHandle actionNh("");
qserv.reset(new actionlib::QueuedActionServer<move_base_msgs::MoveBaseAction> (actionNh, "queue_server", boost::bind(&GoalQueueSuite::executeCallback, this, _1)));
cli.reset(new actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> ("queue_server", true)); // true -> don't need ros::spin()
qserv->start();
}
virtual void TearDown() {
// Kill the executeCallback if it is running
// New Scope so that lock_guard destructs and unlocks
{
std::lock_guard<std::mutex> lk1(execute_lock);
finish_executing = true;
execute_cv.notify_one(); // Releases one waiting thread
}
qserv->shutdown();
}
// TODO: Making sure it gets called at the right time (flags!) - in its own thread
void executeCallback(const move_base_msgs::MoveBaseGoalConstPtr &msg) {
resetFlags();
got_goal = true;
received_goal = msg;
while (true) {
if (qserv->isPreemptRequested()) {
goal_preempted = true;
} else {
goal_preempted = false;
}
if (qserv->isNewGoalAvailable()) {
next_goal_available = true;
} else {
next_goal_available = false;
}
// Wait until signalled to end
std::unique_lock<std::mutex> lk(execute_lock);
execute_cv.wait(lk,
//lambda function to wait on our bool variables
[this](){return finish_executing || resume_executing;} // blocks only if lambda returns false
);
// We were requested to stop, so we stop
if (finish_executing) {
break;
}
}
// Signal that we are done here
std::lock_guard<std::mutex> lk(execute_done_lock);
execute_done = true;
execute_done_cv.notify_all(); // Releases all waiting thread
}
// Helper function to signal the executeCallback to end
void finishExecuting() {
// New Scope so that lock_guard destructs and unlocks
{
std::lock_guard<std::mutex> lk1(execute_lock);
finish_executing = true;
execute_cv.notify_one(); //unlocks lambda waiting function in ExecuteCallback
}
// Wait for execute callback to actually finish
std::unique_lock<std::mutex> lk2(execute_done_lock);
execute_done_cv.wait(lk2, [this]() {return execute_done;}); // at the end of ExecuteCallback
}
// Helper function to signal the executeCallback to resume
// This is useful for seeing if the callback code sees a preempt
void resumeExecuting() {
std::lock_guard<std::mutex> lk(execute_lock);
resume_executing = true;
execute_cv.notify_one();
}
void resetFlags() {
got_goal = false;
goal_preempted = false;
next_goal_available = false;
received_goal = nullptr;
// Signal flags
finish_executing = false;
resume_executing = false;
execute_done = false;
}
// Flags for assertions
bool got_goal;
bool goal_preempted;
bool next_goal_available;
move_base_msgs::MoveBaseGoalConstPtr received_goal;
// Signaling variables
bool finish_executing;
bool resume_executing;
bool execute_done;
std::mutex execute_lock;
std::mutex execute_done_lock;
std::condition_variable execute_cv;
std::condition_variable execute_done_cv;
std::unique_ptr<actionlib::QueuedActionServer<move_base_msgs::MoveBaseAction>> qserv;
std::unique_ptr<actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction>> cli;
};
// IMPORTANT: Time delays and ros::spinOnce() sequence should stay the same, otherwise, strange things happen
TEST_F(GoalQueueSuite, establishDuplex) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
finishExecuting();
ASSERT_TRUE(got_goal);
ASSERT_FALSE(goal_preempted);
ASSERT_FALSE(next_goal_available);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
}
TEST_F(GoalQueueSuite, addGoalWhileExecuting) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
// First goal
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Cancelling the first goal - PITFALL
cli->cancelGoal();
resumeExecuting();
ros::Duration(1.0).sleep();
ros::spinOnce();
ASSERT_TRUE(goal_preempted);
// Finish the preempted goal
finishExecuting();
// "Second" goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(7.0, received_goal->target_pose.pose.position.x);
// Third goal
goal.target_pose.pose.position.x = 13.0;
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
resumeExecuting();
// Make sure that the "second" goal is still executing, but a new goal is seen
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(7.0, received_goal->target_pose.pose.position.x);
ASSERT_FALSE(goal_preempted);
//ASSERT_TRUE(next_goal_available); // TODO: Fails when changing other code???
// Finish the "second" goal, then the 3nd goal should start executing
finishExecuting();
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_FALSE(goal_preempted);
ASSERT_FALSE(next_goal_available);
ASSERT_EQ(13.0, received_goal->target_pose.pose.position.x);
finishExecuting(); // Finish the 3nd goal
/*
- if another goal is received add it to the queue (DONE)
- if the queue full, set the current goal as preempted - explicitly called! - so cancelling the current goal and start executing the next one
- start executing the next goal in queue (the one after the preempted)
*/
}
TEST_F(GoalQueueSuite, goalPreempting) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
// One goal -> Cancel request -> Stop
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(1.0).sleep(); // TODO: Make this disappear
ASSERT_TRUE(got_goal);
ASSERT_TRUE(qserv->isActive());
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
cli->cancelGoal();
resumeExecuting();
ros::Duration(1.0).sleep();
ros::spinOnce();
ASSERT_TRUE(goal_preempted);
finishExecuting(); // Finish the goal
ros::spinOnce();
ros::Duration(1.0).sleep();
ASSERT_FALSE(qserv->isActive());
// Two goals -> Cancel current goal -> Start executing the second
// First goal
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Cancelling the first goal - PITFALL
cli->cancelGoal();
resumeExecuting();
ros::Duration(1.0).sleep();
ros::spinOnce();
ASSERT_TRUE(goal_preempted);
// Finish the preempted goal
finishExecuting(); // Finish 1st goal
// "Second" goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(7.0, received_goal->target_pose.pose.position.x); // call FINISH!
finishExecuting(); // Finish 2nd goal
// - if a cancel request is received for the current goal, set it as preempted (DONE)
// - if there another goal, start executing it
// - if no goal, stop (DONE)
}
TEST_F(GoalQueueSuite, goalCancelling) {
move_base_msgs::MoveBaseGoal goal;
goal.target_pose.pose.position.x = 3.0;
// Two goals -> Cancel current goal -> Start executing the second
// First goal
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ASSERT_TRUE(qserv->isActive());
ASSERT_TRUE(got_goal);
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
// Second goal
goal.target_pose.pose.position.x = 7.0;
cli->sendGoal(goal);
ros::spinOnce();
ros::Duration(0.5).sleep(); // TODO: Make this disappear
ros::spinOnce();
// Cancelling the second goal
cli->cancelGoal();
resumeExecuting();
ros::Duration(1.0).sleep();
ros::spinOnce();
//ASSERT_TRUE(goal_preempted); // TODO: Why is this failling?
ASSERT_TRUE(qserv->isActive());
ASSERT_EQ(3.0, received_goal->target_pose.pose.position.x);
finishExecuting();
//ASSERT_FALSE(qserv->isActive()); // TODO: Why is this failling?
// - if a cancel request on the "next_goal" received, remove it from the queue and set it as cancelled
}
// Two more TEST_F missing and a pitfall
int main(int argc, char **argv) {
ros::init(argc, argv, "goal_queueing_test");
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010, Nikhil Marathe <[email protected]> All rights reserved.
* See LICENSE for details.
*/
#include "sasljs.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace v8;
using namespace node;
/*
* Macro from the sqlite3 bindings
* http://github.com/grumdrig/node-sqlite/blob/master/sqlite3_bindings.cc
* by Eric Fredricksen
*/
#define REQ_STR_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsString()) \
return ThrowException(Exception::TypeError( \
String::New("Argument " #I " must be a string"))); \
String::Utf8Value VAR(args[I]->ToString());
#define ENSURE_STARTED( session_obj )\
if( !session_obj->m_session )\
std::cerr << "sasljs: Session is not started!\n";\
assert( session_obj->m_session != NULL )
namespace sasljs {
v8::Local<v8::FunctionTemplate> Session::Initialize ( Handle<Object> target )
{
v8::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
// error codes
NODE_DEFINE_CONSTANT( target, GSASL_OK );
NODE_DEFINE_CONSTANT( target, GSASL_NEEDS_MORE );
NODE_DEFINE_CONSTANT( target, GSASL_UNKNOWN_MECHANISM );
NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_CALLED_TOO_MANY_TIMES );
NODE_DEFINE_CONSTANT( target, GSASL_MALLOC_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_BASE64_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_CRYPTO_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_SASLPREP_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_PARSE_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_AUTHENTICATION_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_INTEGRITY_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_NO_CLIENT_CODE );
NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVER_CODE );
NODE_DEFINE_CONSTANT( target, GSASL_NO_CALLBACK );
NODE_DEFINE_CONSTANT( target, GSASL_NO_ANONYMOUS_TOKEN );
NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHID );
NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHZID );
NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSWORD );
NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSCODE );
NODE_DEFINE_CONSTANT( target, GSASL_NO_PIN );
NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVICE );
NODE_DEFINE_CONSTANT( target, GSASL_NO_HOSTNAME );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_RELEASE_BUFFER_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_IMPORT_NAME_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_INIT_SEC_CONTEXT_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACCEPT_SEC_CONTEXT_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNWRAP_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_WRAP_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACQUIRE_CRED_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNSUPPORTED_PROTECTION_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INIT_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INTERNAL_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_SHISHI_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_ADDITIONAL_PASSCODE );
NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_NEW_PIN );
// property constants
NODE_DEFINE_CONSTANT( target, GSASL_AUTHID );
NODE_DEFINE_CONSTANT( target, GSASL_AUTHZID );
NODE_DEFINE_CONSTANT( target, GSASL_PASSWORD );
NODE_DEFINE_CONSTANT( target, GSASL_ANONYMOUS_TOKEN );
NODE_DEFINE_CONSTANT( target, GSASL_SERVICE );
NODE_DEFINE_CONSTANT( target, GSASL_HOSTNAME );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME );
NODE_DEFINE_CONSTANT( target, GSASL_PASSCODE );
NODE_DEFINE_CONSTANT( target, GSASL_SUGGESTED_PIN );
NODE_DEFINE_CONSTANT( target, GSASL_PIN );
NODE_DEFINE_CONSTANT( target, GSASL_REALM );
NODE_DEFINE_CONSTANT( target, GSASL_DIGEST_MD5_HASHED_PASSWORD );
NODE_DEFINE_CONSTANT( target, GSASL_QOPS );
NODE_DEFINE_CONSTANT( target, GSASL_QOP );
NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_ITER );
NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALT );
NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALTED_PASSWORD );
NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SIMPLE );
NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_EXTERNAL );
NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_ANONYMOUS );
NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_GSSAPI );
NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SECURID );
NODE_SET_PROTOTYPE_METHOD( t, "_mechanisms", GetMechanisms );
NODE_SET_PROTOTYPE_METHOD( t, "step", Step );
NODE_SET_PROTOTYPE_METHOD( t, "property", GetSaslProperty );
NODE_SET_PROTOTYPE_METHOD( t, "setProperty", SetSaslProperty );
return scope.Close(t);
}
void ServerSession::Initialize ( Handle<Object> target ) {
v8::Handle<v8::FunctionTemplate> t = Session::Initialize(target);
NODE_SET_PROTOTYPE_METHOD( t, "start", Start );
target->Set( v8::String::NewSymbol("ServerSession"), t->GetFunction() );
}
void ClientSession::Initialize ( Handle<Object> target ) {
v8::Handle<v8::FunctionTemplate> t = Session::Initialize(target);
NODE_SET_PROTOTYPE_METHOD( t, "start", Start );
target->Set( v8::String::NewSymbol("ClientSession"), t->GetFunction() );
}
/*
* Call in JS
* new Session( "service name" );
* All other options default to NULL for now
*/
v8::Handle<v8::Value>
Session::New (const v8::Arguments& args)
{
HandleScope scope;
if( args.Length() < 1 || !args[0]->IsFunction() ) {
return ThrowException(Exception::TypeError(
String::New("Argument 0 must be a callback")));
}
Session *sc = new Session( cb_persist( args[0] ) );
sc->Wrap( args.This() );
return args.This();
}
Session::Session( Persistent<Function> *cb )
: ObjectWrap()
, m_session( NULL )
, m_callback( cb )
{
}
Session::~Session()
{
if (m_session)
gsasl_finish(m_session);
m_callback->Dispose();
}
Handle<Value>
Session::GetMechanisms( const v8::Arguments &args )
{
Session *sc = Unwrap<Session>( args.This() );
char *result;
int mechres = gsasl_server_mechlist( ctx, &result );
if( mechres != GSASL_OK ) {
return String::New( "" );
}
Handle<String> ret = String::New( result, strlen( result ) );
free( result );
return ret;
}
int
Session::Callback( Gsasl *ctx, Gsasl_session *sctx, Gsasl_property prop )
{
Session *sc = static_cast<Session*>(gsasl_session_hook_get( sctx ));
ENSURE_STARTED( sc );
std::map<Gsasl_property, const char *>::iterator it = property_codes.find( prop );
Local<Value> propValue;
if( it != property_codes.end() ) {
propValue = String::NewSymbol(it->second);
} else {
propValue = Integer::New(prop);
}
Local<Value> argv[] = { propValue, Local<Object>::New(sc->handle_) };
Local<Value> ret = (*sc->m_callback)->Call( sc->handle_, 2, argv );
if( !ret->IsNumber() )
return GSASL_NO_CALLBACK;
return ret->ToInteger()->Value();
}
/**
* Returns a map
* { status: integer_error_code,
* data : data to send to client if error == GSASL_OK }
*/
v8::Handle<v8::Value>
ServerSession::Start( const v8::Arguments &args )
{
REQ_STR_ARG( 0, mechanismString );
int res;
ServerSession *sc = Unwrap<ServerSession>( args.This() );
if( sc->m_session != NULL ) {
return ThrowException( Exception::Error( String::New( "sasljs: This session is already started!" ) ) );
}
res = gsasl_server_start( ctx, *mechanismString, &sc->m_session );
gsasl_session_hook_set( sc->m_session, sc );
gsasl_callback_set( ctx, sc->Callback );
return Integer::New( res );
}
v8::Handle<v8::Value>
ClientSession::Start( const v8::Arguments &args )
{
REQ_STR_ARG( 0, mechanismString );
int res;
ClientSession *sc = Unwrap<ClientSession>( args.This() );
if( sc->m_session != NULL ) {
return ThrowException( Exception::Error( String::New( "sasljs: This session is already started!" ) ) );
}
res = gsasl_client_start( ctx, *mechanismString, &sc->m_session );
gsasl_session_hook_set( sc->m_session, sc );
gsasl_callback_set( ctx, sc->Callback );
return Integer::New( res );
}
v8::Handle<v8::Value>
Session::Step( const v8::Arguments &args )
{
REQ_STR_ARG( 0, clientinString );
Session *sc = Unwrap<Session>( args.This() );
char *reply;
int res = gsasl_step64( sc->m_session, *clientinString, &reply );
Handle<Object> obj = Object::New();
Local<String> status = String::NewSymbol( "status" );
obj->Set( status, Integer::New( res ) );
if( res == GSASL_OK || res == GSASL_NEEDS_MORE ) {
obj->Set( String::NewSymbol( "data" ), String::New( reply, strlen( reply ) ) );
}
else {
obj->Set( String::NewSymbol( "data" ), String::New( gsasl_strerror( res ) ) );
}
return obj;
}
Handle<Value>
Session::GetSaslProperty( const Arguments &args )
{
Session *sc = Unwrap<Session>( args.This() );
ENSURE_STARTED( sc );
if( args.Length() < 1 || !args[0]->IsString() ) {
return ThrowException( Exception::TypeError( String::New( "Expect property name as first argument" ) ) );
}
String::AsciiValue key( args[0]->ToString() );
std::map<std::string, Gsasl_property>::iterator it = property_strings.find( *key );
if( it != property_strings.end() ) {
const char *prop = gsasl_property_fast( sc->m_session, it->second );
if( prop == NULL )
return Null();
return String::New( prop );
}
return Null();
}
Handle<Value>
Session::SetSaslProperty( const Arguments &args )
{
Session *sc = Unwrap<Session>( args.This() );
ENSURE_STARTED( sc );
if( args.Length() < 1 || !args[0]->IsString() ) {
return ThrowException( Exception::TypeError( String::New( "Expect property name as first argument" ) ) );
}
String::AsciiValue key( args[0]->ToString() );
if( args.Length() < 2 || !args[1]->IsString() ) {
return ThrowException( Exception::TypeError( String::New( "Expect property value as second argument" ) ) );
}
String::AsciiValue val( args[1]->ToString() );
std::map<std::string, Gsasl_property>::iterator it = property_strings.find( *key );
if( it != property_strings.end() ) {
gsasl_property_set( sc->m_session, it->second, *val );
}
return Null();
}
static void register_property(const char *name, Gsasl_property prop)
{
property_strings[name] = prop;
property_codes[prop] = name;
}
}
extern "C" void
init (Handle<Object> target)
{
HandleScope scope;
sasljs::ctx = NULL;
int initres = gsasl_init( &sasljs::ctx );
if( initres != GSASL_OK ) {
fprintf( stderr, "Could not initialize gsasl: %s\n", gsasl_strerror( initres ) );
abort();
}
sasljs::register_property("authid", GSASL_AUTHID);
sasljs::register_property("authzid", GSASL_AUTHZID);
sasljs::register_property("password", GSASL_PASSWORD);
sasljs::register_property("anonymous_token", GSASL_ANONYMOUS_TOKEN);
sasljs::register_property("service", GSASL_SERVICE);
sasljs::register_property("hostname", GSASL_HOSTNAME);
sasljs::register_property("gssapi_display_name", GSASL_GSSAPI_DISPLAY_NAME);
sasljs::register_property("passcode", GSASL_PASSCODE);
sasljs::register_property("suggested_pin", GSASL_SUGGESTED_PIN);
sasljs::register_property("pin", GSASL_PIN);
sasljs::register_property("realm", GSASL_REALM);
sasljs::register_property("digest_md5_hashed_password", GSASL_DIGEST_MD5_HASHED_PASSWORD);
sasljs::register_property("qops", GSASL_QOPS);
sasljs::register_property("qop", GSASL_QOP);
sasljs::register_property("scram_iter", GSASL_SCRAM_ITER);
sasljs::register_property("scram_salt", GSASL_SCRAM_SALT);
sasljs::register_property("scram_salted_password", GSASL_SCRAM_SALTED_PASSWORD);
sasljs::register_property("validate_simple", GSASL_VALIDATE_SIMPLE);
sasljs::register_property("validate_external", GSASL_VALIDATE_EXTERNAL);
sasljs::register_property("validate_anonymous", GSASL_VALIDATE_ANONYMOUS);
sasljs::register_property("validate_gssapi", GSASL_VALIDATE_GSSAPI);
sasljs::register_property("validate_securid", GSASL_VALIDATE_SECURID);
sasljs::ServerSession::Initialize(target);
sasljs::ClientSession::Initialize(target);
}
<commit_msg>add cb_tls_unique property<commit_after>/*
* Copyright 2010, Nikhil Marathe <[email protected]> All rights reserved.
* See LICENSE for details.
*/
#include "sasljs.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
using namespace v8;
using namespace node;
/*
* Macro from the sqlite3 bindings
* http://github.com/grumdrig/node-sqlite/blob/master/sqlite3_bindings.cc
* by Eric Fredricksen
*/
#define REQ_STR_ARG(I, VAR) \
if (args.Length() <= (I) || !args[I]->IsString()) \
return ThrowException(Exception::TypeError( \
String::New("Argument " #I " must be a string"))); \
String::Utf8Value VAR(args[I]->ToString());
#define ENSURE_STARTED( session_obj )\
if( !session_obj->m_session )\
std::cerr << "sasljs: Session is not started!\n";\
assert( session_obj->m_session != NULL )
namespace sasljs {
v8::Local<v8::FunctionTemplate> Session::Initialize ( Handle<Object> target )
{
v8::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
// error codes
NODE_DEFINE_CONSTANT( target, GSASL_OK );
NODE_DEFINE_CONSTANT( target, GSASL_NEEDS_MORE );
NODE_DEFINE_CONSTANT( target, GSASL_UNKNOWN_MECHANISM );
NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_CALLED_TOO_MANY_TIMES );
NODE_DEFINE_CONSTANT( target, GSASL_MALLOC_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_BASE64_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_CRYPTO_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_SASLPREP_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_MECHANISM_PARSE_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_AUTHENTICATION_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_INTEGRITY_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_NO_CLIENT_CODE );
NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVER_CODE );
NODE_DEFINE_CONSTANT( target, GSASL_NO_CALLBACK );
NODE_DEFINE_CONSTANT( target, GSASL_NO_ANONYMOUS_TOKEN );
NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHID );
NODE_DEFINE_CONSTANT( target, GSASL_NO_AUTHZID );
NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSWORD );
NODE_DEFINE_CONSTANT( target, GSASL_NO_PASSCODE );
NODE_DEFINE_CONSTANT( target, GSASL_NO_PIN );
NODE_DEFINE_CONSTANT( target, GSASL_NO_SERVICE );
NODE_DEFINE_CONSTANT( target, GSASL_NO_HOSTNAME );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_RELEASE_BUFFER_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_IMPORT_NAME_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_INIT_SEC_CONTEXT_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACCEPT_SEC_CONTEXT_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNWRAP_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_WRAP_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_ACQUIRE_CRED_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_UNSUPPORTED_PROTECTION_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INIT_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_KERBEROS_V5_INTERNAL_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_SHISHI_ERROR );
NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_ADDITIONAL_PASSCODE );
NODE_DEFINE_CONSTANT( target, GSASL_SECURID_SERVER_NEED_NEW_PIN );
// property constants
NODE_DEFINE_CONSTANT( target, GSASL_AUTHID );
NODE_DEFINE_CONSTANT( target, GSASL_AUTHZID );
NODE_DEFINE_CONSTANT( target, GSASL_PASSWORD );
NODE_DEFINE_CONSTANT( target, GSASL_ANONYMOUS_TOKEN );
NODE_DEFINE_CONSTANT( target, GSASL_SERVICE );
NODE_DEFINE_CONSTANT( target, GSASL_HOSTNAME );
NODE_DEFINE_CONSTANT( target, GSASL_GSSAPI_DISPLAY_NAME );
NODE_DEFINE_CONSTANT( target, GSASL_PASSCODE );
NODE_DEFINE_CONSTANT( target, GSASL_SUGGESTED_PIN );
NODE_DEFINE_CONSTANT( target, GSASL_PIN );
NODE_DEFINE_CONSTANT( target, GSASL_REALM );
NODE_DEFINE_CONSTANT( target, GSASL_DIGEST_MD5_HASHED_PASSWORD );
NODE_DEFINE_CONSTANT( target, GSASL_QOPS );
NODE_DEFINE_CONSTANT( target, GSASL_QOP );
NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_ITER );
NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALT );
NODE_DEFINE_CONSTANT( target, GSASL_SCRAM_SALTED_PASSWORD );
NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SIMPLE );
NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_EXTERNAL );
NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_ANONYMOUS );
NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_GSSAPI );
NODE_DEFINE_CONSTANT( target, GSASL_VALIDATE_SECURID );
NODE_SET_PROTOTYPE_METHOD( t, "_mechanisms", GetMechanisms );
NODE_SET_PROTOTYPE_METHOD( t, "step", Step );
NODE_SET_PROTOTYPE_METHOD( t, "property", GetSaslProperty );
NODE_SET_PROTOTYPE_METHOD( t, "setProperty", SetSaslProperty );
return scope.Close(t);
}
void ServerSession::Initialize ( Handle<Object> target ) {
v8::Handle<v8::FunctionTemplate> t = Session::Initialize(target);
NODE_SET_PROTOTYPE_METHOD( t, "start", Start );
target->Set( v8::String::NewSymbol("ServerSession"), t->GetFunction() );
}
void ClientSession::Initialize ( Handle<Object> target ) {
v8::Handle<v8::FunctionTemplate> t = Session::Initialize(target);
NODE_SET_PROTOTYPE_METHOD( t, "start", Start );
target->Set( v8::String::NewSymbol("ClientSession"), t->GetFunction() );
}
/*
* Call in JS
* new Session( "service name" );
* All other options default to NULL for now
*/
v8::Handle<v8::Value>
Session::New (const v8::Arguments& args)
{
HandleScope scope;
if( args.Length() < 1 || !args[0]->IsFunction() ) {
return ThrowException(Exception::TypeError(
String::New("Argument 0 must be a callback")));
}
Session *sc = new Session( cb_persist( args[0] ) );
sc->Wrap( args.This() );
return args.This();
}
Session::Session( Persistent<Function> *cb )
: ObjectWrap()
, m_session( NULL )
, m_callback( cb )
{
}
Session::~Session()
{
if (m_session)
gsasl_finish(m_session);
m_callback->Dispose();
}
Handle<Value>
Session::GetMechanisms( const v8::Arguments &args )
{
Session *sc = Unwrap<Session>( args.This() );
char *result;
int mechres = gsasl_server_mechlist( ctx, &result );
if( mechres != GSASL_OK ) {
return String::New( "" );
}
Handle<String> ret = String::New( result, strlen( result ) );
free( result );
return ret;
}
int
Session::Callback( Gsasl *ctx, Gsasl_session *sctx, Gsasl_property prop )
{
Session *sc = static_cast<Session*>(gsasl_session_hook_get( sctx ));
ENSURE_STARTED( sc );
std::map<Gsasl_property, const char *>::iterator it = property_codes.find( prop );
Local<Value> propValue;
if( it != property_codes.end() ) {
propValue = String::NewSymbol(it->second);
} else {
propValue = Integer::New(prop);
}
Local<Value> argv[] = { propValue, Local<Object>::New(sc->handle_) };
Local<Value> ret = (*sc->m_callback)->Call( sc->handle_, 2, argv );
if( !ret->IsNumber() )
return GSASL_NO_CALLBACK;
return ret->ToInteger()->Value();
}
/**
* Returns a map
* { status: integer_error_code,
* data : data to send to client if error == GSASL_OK }
*/
v8::Handle<v8::Value>
ServerSession::Start( const v8::Arguments &args )
{
REQ_STR_ARG( 0, mechanismString );
int res;
ServerSession *sc = Unwrap<ServerSession>( args.This() );
if( sc->m_session != NULL ) {
return ThrowException( Exception::Error( String::New( "sasljs: This session is already started!" ) ) );
}
res = gsasl_server_start( ctx, *mechanismString, &sc->m_session );
gsasl_session_hook_set( sc->m_session, sc );
gsasl_callback_set( ctx, sc->Callback );
return Integer::New( res );
}
v8::Handle<v8::Value>
ClientSession::Start( const v8::Arguments &args )
{
REQ_STR_ARG( 0, mechanismString );
int res;
ClientSession *sc = Unwrap<ClientSession>( args.This() );
if( sc->m_session != NULL ) {
return ThrowException( Exception::Error( String::New( "sasljs: This session is already started!" ) ) );
}
res = gsasl_client_start( ctx, *mechanismString, &sc->m_session );
gsasl_session_hook_set( sc->m_session, sc );
gsasl_callback_set( ctx, sc->Callback );
return Integer::New( res );
}
v8::Handle<v8::Value>
Session::Step( const v8::Arguments &args )
{
REQ_STR_ARG( 0, clientinString );
Session *sc = Unwrap<Session>( args.This() );
char *reply;
int res = gsasl_step64( sc->m_session, *clientinString, &reply );
Handle<Object> obj = Object::New();
Local<String> status = String::NewSymbol( "status" );
obj->Set( status, Integer::New( res ) );
if( res == GSASL_OK || res == GSASL_NEEDS_MORE ) {
obj->Set( String::NewSymbol( "data" ), String::New( reply, strlen( reply ) ) );
}
else {
obj->Set( String::NewSymbol( "data" ), String::New( gsasl_strerror( res ) ) );
}
return obj;
}
Handle<Value>
Session::GetSaslProperty( const Arguments &args )
{
Session *sc = Unwrap<Session>( args.This() );
ENSURE_STARTED( sc );
if( args.Length() < 1 || !args[0]->IsString() ) {
return ThrowException( Exception::TypeError( String::New( "Expect property name as first argument" ) ) );
}
String::AsciiValue key( args[0]->ToString() );
std::map<std::string, Gsasl_property>::iterator it = property_strings.find( *key );
if( it != property_strings.end() ) {
const char *prop = gsasl_property_fast( sc->m_session, it->second );
if( prop == NULL )
return Null();
return String::New( prop );
}
return Null();
}
Handle<Value>
Session::SetSaslProperty( const Arguments &args )
{
Session *sc = Unwrap<Session>( args.This() );
ENSURE_STARTED( sc );
if( args.Length() < 1 || !args[0]->IsString() ) {
return ThrowException( Exception::TypeError( String::New( "Expect property name as first argument" ) ) );
}
String::AsciiValue key( args[0]->ToString() );
if( args.Length() < 2 || !args[1]->IsString() ) {
return ThrowException( Exception::TypeError( String::New( "Expect property value as second argument" ) ) );
}
String::AsciiValue val( args[1]->ToString() );
std::map<std::string, Gsasl_property>::iterator it = property_strings.find( *key );
if( it != property_strings.end() ) {
gsasl_property_set( sc->m_session, it->second, *val );
}
return Null();
}
static void register_property(const char *name, Gsasl_property prop)
{
property_strings[name] = prop;
property_codes[prop] = name;
}
}
extern "C" void
init (Handle<Object> target)
{
HandleScope scope;
sasljs::ctx = NULL;
int initres = gsasl_init( &sasljs::ctx );
if( initres != GSASL_OK ) {
fprintf( stderr, "Could not initialize gsasl: %s\n", gsasl_strerror( initres ) );
abort();
}
sasljs::register_property("authid", GSASL_AUTHID);
sasljs::register_property("authzid", GSASL_AUTHZID);
sasljs::register_property("password", GSASL_PASSWORD);
sasljs::register_property("anonymous_token", GSASL_ANONYMOUS_TOKEN);
sasljs::register_property("service", GSASL_SERVICE);
sasljs::register_property("hostname", GSASL_HOSTNAME);
sasljs::register_property("gssapi_display_name", GSASL_GSSAPI_DISPLAY_NAME);
sasljs::register_property("passcode", GSASL_PASSCODE);
sasljs::register_property("suggested_pin", GSASL_SUGGESTED_PIN);
sasljs::register_property("pin", GSASL_PIN);
sasljs::register_property("realm", GSASL_REALM);
sasljs::register_property("digest_md5_hashed_password", GSASL_DIGEST_MD5_HASHED_PASSWORD);
sasljs::register_property("qops", GSASL_QOPS);
sasljs::register_property("qop", GSASL_QOP);
sasljs::register_property("scram_iter", GSASL_SCRAM_ITER);
sasljs::register_property("scram_salt", GSASL_SCRAM_SALT);
sasljs::register_property("scram_salted_password", GSASL_SCRAM_SALTED_PASSWORD);
sasljs::register_property("cb_tls_unique", GSASL_CB_TLS_UNIQUE);
sasljs::register_property("validate_simple", GSASL_VALIDATE_SIMPLE);
sasljs::register_property("validate_external", GSASL_VALIDATE_EXTERNAL);
sasljs::register_property("validate_anonymous", GSASL_VALIDATE_ANONYMOUS);
sasljs::register_property("validate_gssapi", GSASL_VALIDATE_GSSAPI);
sasljs::register_property("validate_securid", GSASL_VALIDATE_SECURID);
sasljs::ServerSession::Initialize(target);
sasljs::ClientSession::Initialize(target);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: source.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2004-10-22 07:55:11 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SOURCE_HXX_
#define _SOURCE_HXX_
#ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDRAGSOURCE_HPP_
#include <com/sun/star/datatransfer/dnd/XDragSource.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDRAGSOURCECONTEXT_HPP_
#include <com/sun/star/datatransfer/dnd/XDragSourceContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _OSL_MUTEX_H_
#include <osl/mutex.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#include "../../inc/DtObjFactory.hxx"
#include "globals.hxx"
#include <oleidl.h>
#include <systools/win32/comtools.hxx>
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::dnd;
class SourceContext;
// RIGHT MOUSE BUTTON drag and drop not supportet currently.
// ALT modifier is considered to effect a user selection of effects
class DragSource:
public MutexDummy,
public WeakComponentImplHelper3<XDragSource, XInitialization, XServiceInfo>,
public IDropSource
{
Reference<XMultiServiceFactory> m_serviceFactory;
HWND m_hAppWindow;
// The mouse button that set off the drag and drop operation
short m_MouseButton;
// Converts XTransferable objects to IDataObject objects.
CDTransObjFactory m_aDataConverter;
DragSource();
DragSource(const DragSource&);
DragSource &operator= ( const DragSource&);
// First starting a new drag and drop thread if
// the last one has finished
void StartDragImpl(
const DragGestureEvent& trigger,
sal_Int8 sourceActions,
sal_Int32 cursor,
sal_Int32 image,
const Reference<XTransferable >& trans,
const Reference<XDragSourceListener >& listener);
public:
long m_RunningDndOperationCount;
public:
// only valid for one dnd operation
// the thread ID of the thread which created the window
DWORD m_threadIdWindow;
// The context notifies the XDragSourceListener s
Reference<XDragSourceContext> m_currentContext;
// the wrapper for the Transferable ( startDrag)
IDataObjectPtr m_spDataObject;
sal_Int8 m_sourceActions;
public:
DragSource(const Reference<XMultiServiceFactory>& sf);
virtual ~DragSource();
#if OSL_DEBUG_LEVEL > 1
virtual void SAL_CALL release();
#endif
// XInitialization
virtual void SAL_CALL initialize( const Sequence< Any >& aArguments )
throw(Exception, RuntimeException);
// XDragSource
virtual sal_Bool SAL_CALL isDragImageSupported( ) throw(RuntimeException);
virtual sal_Int32 SAL_CALL getDefaultCursor( sal_Int8 dragAction )
throw( IllegalArgumentException, RuntimeException);
virtual void SAL_CALL startDrag( const DragGestureEvent& trigger,
sal_Int8 sourceActions,
sal_Int32 cursor,
sal_Int32 image,
const Reference<XTransferable >& trans,
const Reference<XDragSourceListener >& listener )
throw( RuntimeException);
// XServiceInfo
virtual OUString SAL_CALL getImplementationName( ) throw (RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw (RuntimeException);
virtual Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw (RuntimeException);
virtual HRESULT STDMETHODCALLTYPE QueryInterface(
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
virtual ULONG STDMETHODCALLTYPE AddRef( );
virtual ULONG STDMETHODCALLTYPE Release( );
// IDropSource
virtual HRESULT STDMETHODCALLTYPE QueryContinueDrag(
/* [in] */ BOOL fEscapePressed,
/* [in] */ DWORD grfKeyState);
virtual HRESULT STDMETHODCALLTYPE GiveFeedback(
/* [in] */ DWORD dwEffect);
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.11.12); FILE MERGED 2005/09/05 18:48:18 rt 1.11.12.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: source.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:18:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SOURCE_HXX_
#define _SOURCE_HXX_
#ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDRAGSOURCE_HPP_
#include <com/sun/star/datatransfer/dnd/XDragSource.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDRAGSOURCECONTEXT_HPP_
#include <com/sun/star/datatransfer/dnd/XDragSourceContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _OSL_MUTEX_H_
#include <osl/mutex.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#include "../../inc/DtObjFactory.hxx"
#include "globals.hxx"
#include <oleidl.h>
#include <systools/win32/comtools.hxx>
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::dnd;
class SourceContext;
// RIGHT MOUSE BUTTON drag and drop not supportet currently.
// ALT modifier is considered to effect a user selection of effects
class DragSource:
public MutexDummy,
public WeakComponentImplHelper3<XDragSource, XInitialization, XServiceInfo>,
public IDropSource
{
Reference<XMultiServiceFactory> m_serviceFactory;
HWND m_hAppWindow;
// The mouse button that set off the drag and drop operation
short m_MouseButton;
// Converts XTransferable objects to IDataObject objects.
CDTransObjFactory m_aDataConverter;
DragSource();
DragSource(const DragSource&);
DragSource &operator= ( const DragSource&);
// First starting a new drag and drop thread if
// the last one has finished
void StartDragImpl(
const DragGestureEvent& trigger,
sal_Int8 sourceActions,
sal_Int32 cursor,
sal_Int32 image,
const Reference<XTransferable >& trans,
const Reference<XDragSourceListener >& listener);
public:
long m_RunningDndOperationCount;
public:
// only valid for one dnd operation
// the thread ID of the thread which created the window
DWORD m_threadIdWindow;
// The context notifies the XDragSourceListener s
Reference<XDragSourceContext> m_currentContext;
// the wrapper for the Transferable ( startDrag)
IDataObjectPtr m_spDataObject;
sal_Int8 m_sourceActions;
public:
DragSource(const Reference<XMultiServiceFactory>& sf);
virtual ~DragSource();
#if OSL_DEBUG_LEVEL > 1
virtual void SAL_CALL release();
#endif
// XInitialization
virtual void SAL_CALL initialize( const Sequence< Any >& aArguments )
throw(Exception, RuntimeException);
// XDragSource
virtual sal_Bool SAL_CALL isDragImageSupported( ) throw(RuntimeException);
virtual sal_Int32 SAL_CALL getDefaultCursor( sal_Int8 dragAction )
throw( IllegalArgumentException, RuntimeException);
virtual void SAL_CALL startDrag( const DragGestureEvent& trigger,
sal_Int8 sourceActions,
sal_Int32 cursor,
sal_Int32 image,
const Reference<XTransferable >& trans,
const Reference<XDragSourceListener >& listener )
throw( RuntimeException);
// XServiceInfo
virtual OUString SAL_CALL getImplementationName( ) throw (RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw (RuntimeException);
virtual Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw (RuntimeException);
virtual HRESULT STDMETHODCALLTYPE QueryInterface(
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
virtual ULONG STDMETHODCALLTYPE AddRef( );
virtual ULONG STDMETHODCALLTYPE Release( );
// IDropSource
virtual HRESULT STDMETHODCALLTYPE QueryContinueDrag(
/* [in] */ BOOL fEscapePressed,
/* [in] */ DWORD grfKeyState);
virtual HRESULT STDMETHODCALLTYPE GiveFeedback(
/* [in] */ DWORD dwEffect);
};
#endif
<|endoftext|> |
<commit_before><commit_msg>Use FilePath::BaseName instead of the deprecated file_util::GetFilenameFromPath. Part 2.<commit_after><|endoftext|> |
<commit_before> #include "Terminal.h"
Terminal::Terminal(int width, int height, uint8_t dir, int fontSize){
this->w = width;
this->h = height;
this->fontSize = fontSize;
bgColor = BLACK;
fgColor = GRAY1;
borderColor = GRAY1;
direction = dir;
keepColors = true;
borderWidth = 1;
horizontalBleed = horizontalBleed * fontSize*FONT_X;
verticalBleed = verticalBleed * fontSize*FONT_Y / 2;
lineSpace = fontSize*FONT_Y / 2;
lines = (this->h-2*borderWidth-2*verticalBleed)/(fontSize*FONT_Y+lineSpace);
lines = (lines > MAX_LINES) ? MAX_LINES : lines;
memset(linesBuffer, 0, MAX_LINES * sizeof(char*));
// Allocate memory for lines
//if(linesBuffer = (char**)malloc(this->lines)){
//memset(linesBuffer,0,sizeof(char*)*this->lines);
//}
// Calculate characters based on fontSize and width
maxCharacters = (this->w - 2*borderWidth - 2*horizontalBleed)/(fontSize*FONT_X);
// Allocate memory for characters
for(int i = 0; i < lines; i++){
if(linesBuffer[i] = (char*) malloc((maxCharacters+1) * sizeof(char))){
memset(linesBuffer[i],0,(maxCharacters+1)*sizeof(char));
}
}
}
Terminal::~Terminal(){}
void Terminal::print(char* string,uint16_t highColor){
highlightColor = highColor;
int length = Widget::getTextLength(string);
length = (length > maxCharacters) ? maxCharacters : length;
char lineIndex = (direction == TERMINAL_SCROLL_DOWN) ? 0 : lines - 1;
// Only scroll if:
if(direction==TERMINAL_SCROLL_UP && linesIndex <= lines -1){
lineIndex = linesIndex++;
}else{
scroll();
}
linesColors[lineIndex] = (highlightColor == NULL) ? fgColor : highlightColor;
for(int i=0; i<length; i++){
linesBuffer[lineIndex][i] = string[i];
}
linesBuffer[lineIndex][length] = 0;
update();
}
// Trying to implement a print("some %d characters",4)
void Terminal::print(char* string, int num, uint16_t highColor){
uint8_t num_size = Widget::getIntLength(num);
uint8_t str_size = Widget::getTextLength(string);
char num_string[num_size];
memset(num_string,0,num_size);
char new_string[str_size + num_size - 2];
memset(new_string,0,str_size+num_size-1);
uint8_t j = 0;
for(uint8_t i=0; i<str_size; i++){
if(string[i] == '%' && string[i+1] == 'd'){
Widget::convert_str(num,num_string);
//Invert the characters
for(uint8_t k=num_size; k!=0; k--){
new_string[j+(num_size-k)] = num_string[k-1];
}
j += num_size-1;
i++;
}else{
new_string[j] = string[i];
}
j++;
}
this->print(new_string,highColor);
}
/*
void Terminal::print(char* string, int num, uint16_t highColor){
highlightColor = highColor;
char numChar[DISPLAY_SIZE];
char numStr[DISPLAY_SIZE];
char chars = 0;
while(num >= 10)
{
numChar[chars++] = num%10;
num /= 10;
}
numChar[chars++] = num;
for(int j = 0; j < chars; j++)
{
numStr[chars-1-j] = '0'+numChar[j];
}
numStr[chars]=0;
int numLength = Widget::getTextLength(numStr);
int strLength = Widget::getTextLength(string);
int length = strLength + numLength;
length = (length > maxCharacters) ? maxCharacters : length;
scroll();
char lineIndex = (direction) ? 0 : lines - 1;
for(int i=0; i<length; i++){
if(i >= strLength){
linesBuffer[lineIndex][i] = numStr[i-strLength];
}else{
linesBuffer[lineIndex][i] = string[i];
}
}
linesBuffer[lineIndex][length] = 0;
update();
}
void Terminal::print(int num, uint16_t highColor){
highlightColor = highColor;
char numChar[DISPLAY_SIZE];
char chars = 0;
// Extract characters representing the powers of ten
while(num >= 10)
{
numChar[chars++] = num%10;
num /= 10;
}
numChar[chars++] = num;
scroll();
char lineIndex = (direction) ? 0 : lines - 1;
for(int j = 0; j < chars; j++)
{
linesBuffer[lineIndex][chars-1-j] = '0'+numChar[j];
}
linesBuffer[lineIndex][chars]=0;
update();
}
*/
void Terminal::scroll(){
myCanvas->tft->fillRect(this->x+borderWidth,this->y+borderWidth,this->w-2*borderWidth,this->h-2*borderWidth,this->bgColor);
if(direction){
scrollDown();
}else{
scrollUp();
}
}
void Terminal::scrollDown(){
// Scroll Down
for(int line = lines-1; line!=0; line--){
for(int i=0; i<maxCharacters; i++){
linesBuffer[line][i] = linesBuffer[line-1][i];
}
linesColors[line] = linesColors[line-1];
}
}
void Terminal::scrollUp(){
// Scroll Up
for(int line = 0; line<lines-1; line++){
for(int i=0; i<maxCharacters; i++){
linesBuffer[line][i] = linesBuffer[line+1][i];
}
linesColors[line] = linesColors[line+1];
}
}
/*
* Clears the terminal and all lines text are cleared
*/
void Terminal::clear(){
for(int i=0;i<lines;i++){
linesBuffer[i][0]=0;
}
linesIndex = 0;
myCanvas->tft->fillRect(this->x+borderWidth,this->y+borderWidth,this->w-2*borderWidth,this->h-2*borderWidth,this->bgColor);
}
void Terminal::drawFrame(){
int xPos = x;
int width = w;
int yPos = y;
int height = h;
for(int i=borderWidth; i!=0;i--){
myCanvas->tft->drawRect(xPos++,yPos++,width--,height--,borderColor);
width--;
height--;
}
}
void Terminal::show(){
drawFrame();
myCanvas->tft->fillRect(this->x+borderWidth,this->y+borderWidth,this->w-2*borderWidth,this->h-2*borderWidth,this->bgColor);
update();
}
void Terminal::update(){
uint16_t color;
//Calculate position for first line
int lineX = this->x + borderWidth + horizontalBleed;
int lineY = this->y + borderWidth + verticalBleed;
char lineIndex = (direction) ? 0 : lines - 1;
for(int i=0; i<lines; i++){
if(i==lineIndex){
color = linesColors[i];
}else{
color = (keepColors)?linesColors[i]:fgColor;
}
myCanvas->tft->drawString(linesBuffer[i], lineX, lineY+(i*(fontSize*FONT_Y+lineSpace)), this->fontSize, color);//color);
}
}
<commit_msg>Cleanup of code and comments in Terminal.cpp<commit_after> #include "Terminal.h"
Terminal::Terminal(int width, int height, uint8_t dir, int fontSize){
this->w = width;
this->h = height;
this->fontSize = fontSize;
bgColor = BLACK;
fgColor = GRAY1;
borderColor = GRAY1;
direction = dir;
keepColors = true;
borderWidth = 1;
horizontalBleed = horizontalBleed * fontSize*FONT_X;
verticalBleed = verticalBleed * fontSize*FONT_Y / 2;
lineSpace = fontSize*FONT_Y / 2;
lines = (this->h-2*borderWidth-2*verticalBleed)/(fontSize*FONT_Y+lineSpace);
lines = (lines > MAX_LINES) ? MAX_LINES : lines;
memset(linesBuffer, 0, MAX_LINES * sizeof(char*));
// Calculate characters based on fontSize and width
maxCharacters = (this->w - 2*borderWidth - 2*horizontalBleed)/(fontSize*FONT_X);
// Allocate memory for characters
for(int i = 0; i < lines; i++){
if(linesBuffer[i] = (char*) malloc((maxCharacters+1) * sizeof(char))){
memset(linesBuffer[i],0,(maxCharacters+1)*sizeof(char));
}
}
}
Terminal::~Terminal(){}
/*
* Main print function.
* Prints a char array, given by a pointer with the highlight color
* specified.
*/
void Terminal::print(char* string,uint16_t highColor){
highlightColor = highColor;
int length = Widget::getTextLength(string);
length = (length > maxCharacters) ? maxCharacters : length;
char lineIndex = (direction == TERMINAL_SCROLL_DOWN) ? 0 : lines - 1;
// Only scroll if:
if(direction==TERMINAL_SCROLL_UP && linesIndex <= lines -1){
lineIndex = linesIndex++;
}else{
scroll();
}
linesColors[lineIndex] = (highlightColor == NULL) ? fgColor : highlightColor;
for(int i=0; i<length; i++){
linesBuffer[lineIndex][i] = string[i];
}
linesBuffer[lineIndex][length] = 0;
update();
}
/*
* Implementation of print("some %d characters",4)
* similar to C++ printf function. Only %d is recognized here.
* First searches for the position of the % symbol in the string.
* Then if the next character is d then convert the number to
* a character array in num_string using Widget's convert_str
* and copy them into the new_string in the inverted order.
* Then update the indexes and keep copying the rest of the characters
* into the new_string array.
*
* At the end call the main print function with the new_string
* characters array.
*/
void Terminal::print(char* string, int num, uint16_t highColor){
uint8_t str_size = Widget::getTextLength(string);
uint8_t num_size = Widget::getIntLength(num);
char new_string[str_size + num_size - 2];
memset(new_string,0,str_size+num_size-1);
char num_string[num_size];
memset(num_string,0,num_size);
uint8_t j = 0;
for(uint8_t i=0; i<str_size; i++){
if(string[i] == '%' && string[i+1] == 'd'){
Widget::convert_str(num,num_string);
for(uint8_t k=num_size; k!=0; k--){
new_string[j+(num_size-k)] = num_string[k-1];
}
j += num_size-1;
i++;
}else{
new_string[j] = string[i];
}
j++;
}
//Call the main print function
this->print(new_string,highColor);
}
/*
* Calls the corresponding scroll function based on the
* direction property.
*/
void Terminal::scroll(){
myCanvas->tft->fillRect(this->x+borderWidth,this->y+borderWidth,this->w-2*borderWidth,this->h-2*borderWidth,this->bgColor);
if(direction){
scrollDown();
}else{
scrollUp();
}
}
void Terminal::scrollDown(){
// Scroll Down
for(int line = lines-1; line!=0; line--){
for(int i=0; i<maxCharacters; i++){
linesBuffer[line][i] = linesBuffer[line-1][i];
}
linesColors[line] = linesColors[line-1];
}
}
void Terminal::scrollUp(){
// Scroll Up
for(int line = 0; line<lines-1; line++){
for(int i=0; i<maxCharacters; i++){
linesBuffer[line][i] = linesBuffer[line+1][i];
}
linesColors[line] = linesColors[line+1];
}
}
/*
* Clears the terminal and all lines text are cleared
*/
void Terminal::clear(){
for(int i=0;i<lines;i++){
linesBuffer[i][0]=0;
}
linesIndex = 0;
myCanvas->tft->fillRect(this->x+borderWidth,this->y+borderWidth,this->w-2*borderWidth,this->h-2*borderWidth,this->bgColor);
}
void Terminal::drawFrame(){
int xPos = x;
int width = w;
int yPos = y;
int height = h;
for(int i=borderWidth; i!=0;i--){
myCanvas->tft->drawRect(xPos++,yPos++,width--,height--,borderColor);
width--;
height--;
}
}
void Terminal::show(){
drawFrame();
myCanvas->tft->fillRect(this->x+borderWidth,this->y+borderWidth,this->w-2*borderWidth,this->h-2*borderWidth,this->bgColor);
update();
}
void Terminal::update(){
uint16_t color;
//Calculate position for first line
int lineX = this->x + borderWidth + horizontalBleed;
int lineY = this->y + borderWidth + verticalBleed;
char lineIndex = (direction) ? 0 : lines - 1;
for(int i=0; i<lines; i++){
if(i==lineIndex){
color = linesColors[i];
}else{
color = (keepColors)?linesColors[i]:fgColor;
}
myCanvas->tft->drawString(linesBuffer[i], lineX, lineY+(i*(fontSize*FONT_Y+lineSpace)), this->fontSize, color);//color);
}
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <ostream>
#include <unordered_map> // TODO: consider changing.
#include <unordered_set> // TODO: consider changing.
#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/IFileManager.h"
#include "BitFunnel/Index/DocumentHandle.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/IDocument.h"
#include "BitFunnel/Index/IDocumentCache.h"
#include "BitFunnel/Index/IDocumentFrequencyTable.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Index/RowId.h"
#include "BitFunnel/Index/RowIdSequence.h"
#include "BitFunnel/Index/Token.h"
#include "Correlate.h"
#include "CsvTsv/Csv.h"
#include "DocumentHandleInternal.h"
#include "LoggerInterfaces/Check.h"
#include "NativeJIT/TypeConverter.h"
#include "RowTableAnalyzer.h"
#include "RowTableDescriptor.h"
#include "Shard.h"
#include "Slice.h"
#include "Term.h"
// Define hash of RowId to allow use of map/set.
// TODO: remove this when we stop using map/set.
namespace std
{
template<>
struct hash<BitFunnel::RowId>
{
std::size_t operator()(BitFunnel::RowId const & row) const
{
// TODO: do we need to hash this?
return NativeJIT::convertType<BitFunnel::RowId, size_t>(row);
}
};
}
namespace BitFunnel
{
void Factories::CreateCorrelate(ISimpleIndex const & index,
char const * outDir,
std::vector<std::string> const & terms)
{
CHECK_NE(*outDir, '\0')
<< "Output directory not set. ";
Correlate correlate(index, terms);
// TODO: call methods here.
}
Correlate::Correlate(ISimpleIndex const & index,
std::vector<std::string> const & terms)
: m_index(index),
m_terms(terms)
{
}
void Correlate::CorrelateRows(char const * outDir) const
{
auto & fileManager = m_index.GetFileManager();
auto & ingestor = m_index.GetIngestor();
// // TODO: Create with factory?
// TermToText termToText(*fileManager.TermToText().OpenForRead());
for (ShardId shardId = 0; shardId < ingestor.GetShardCount(); ++shardId)
{
auto terms(Factories::CreateDocumentFrequencyTable(
*fileManager.DocFreqTable(shardId).OpenForRead()));
auto fileSystem = Factories::CreateFileSystem();
auto outFileManager =
Factories::CreateFileManager(outDir,
outDir,
outDir,
*fileSystem);
// TODO: hoist this read out of loop?
CorrelateShard(shardId,
// termToText,
*outFileManager->RowDensities(shardId).OpenForWrite());
}
}
void Correlate::CorrelateShard(
ShardId const & shardId,
// ITermToText const & termToText,
std::ostream& /*out*/) const
{
const Term::StreamId c_TODOStreamId = 0;
std::unordered_map<Term::Hash, std::unordered_set<RowId>> hashToRowId;
// auto & fileManager = m_index.GetFileManager();
for (auto const & termText : m_terms)
{
Term term(termText.c_str(), c_TODOStreamId, m_index.GetConfiguration());
RowIdSequence rows(term, m_index.GetTermTable(shardId));
for (RowId row : rows)
{
hashToRowId[term.GetRawHash()].insert(row);
}
}
// for (auto const & outerTermText : m_terms)
// {
// Term outerTerm(outerTermText.c_str(), c_TODOStreamId, m_index.GetConfiguration());
// for (auto const & innerTermText : m_terms)
// {
// RowIdSequence outerRows(outerTerm, m_index.GetTermTable(shardId));
// }
// }
}
}
<commit_msg>Fix include path.<commit_after>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 <ostream>
#include <unordered_map> // TODO: consider changing.
#include <unordered_set> // TODO: consider changing.
#include "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Configuration/IFileSystem.h"
#include "BitFunnel/IFileManager.h"
#include "BitFunnel/Index/DocumentHandle.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/IDocument.h"
#include "BitFunnel/Index/IDocumentCache.h"
#include "BitFunnel/Index/IDocumentFrequencyTable.h"
#include "BitFunnel/Index/IIngestor.h"
#include "BitFunnel/Index/ISimpleIndex.h"
#include "BitFunnel/Index/RowId.h"
#include "BitFunnel/Index/RowIdSequence.h"
#include "BitFunnel/Index/Token.h"
#include "BitFunnel/Term.h"
#include "Correlate.h"
#include "CsvTsv/Csv.h"
#include "DocumentHandleInternal.h"
#include "LoggerInterfaces/Check.h"
#include "NativeJIT/TypeConverter.h"
#include "RowTableAnalyzer.h"
#include "RowTableDescriptor.h"
#include "Shard.h"
#include "Slice.h"
// Define hash of RowId to allow use of map/set.
// TODO: remove this when we stop using map/set.
namespace std
{
template<>
struct hash<BitFunnel::RowId>
{
std::size_t operator()(BitFunnel::RowId const & row) const
{
// TODO: do we need to hash this?
return NativeJIT::convertType<BitFunnel::RowId, size_t>(row);
}
};
}
namespace BitFunnel
{
void Factories::CreateCorrelate(ISimpleIndex const & index,
char const * outDir,
std::vector<std::string> const & terms)
{
CHECK_NE(*outDir, '\0')
<< "Output directory not set. ";
Correlate correlate(index, terms);
// TODO: call methods here.
}
Correlate::Correlate(ISimpleIndex const & index,
std::vector<std::string> const & terms)
: m_index(index),
m_terms(terms)
{
}
void Correlate::CorrelateRows(char const * outDir) const
{
auto & fileManager = m_index.GetFileManager();
auto & ingestor = m_index.GetIngestor();
// // TODO: Create with factory?
// TermToText termToText(*fileManager.TermToText().OpenForRead());
for (ShardId shardId = 0; shardId < ingestor.GetShardCount(); ++shardId)
{
auto terms(Factories::CreateDocumentFrequencyTable(
*fileManager.DocFreqTable(shardId).OpenForRead()));
auto fileSystem = Factories::CreateFileSystem();
auto outFileManager =
Factories::CreateFileManager(outDir,
outDir,
outDir,
*fileSystem);
// TODO: hoist this read out of loop?
CorrelateShard(shardId,
// termToText,
*outFileManager->RowDensities(shardId).OpenForWrite());
}
}
void Correlate::CorrelateShard(
ShardId const & shardId,
// ITermToText const & termToText,
std::ostream& /*out*/) const
{
const Term::StreamId c_TODOStreamId = 0;
std::unordered_map<Term::Hash, std::unordered_set<RowId>> hashToRowId;
// auto & fileManager = m_index.GetFileManager();
for (auto const & termText : m_terms)
{
Term term(termText.c_str(), c_TODOStreamId, m_index.GetConfiguration());
RowIdSequence rows(term, m_index.GetTermTable(shardId));
for (RowId row : rows)
{
hashToRowId[term.GetRawHash()].insert(row);
}
}
// for (auto const & outerTermText : m_terms)
// {
// Term outerTerm(outerTermText.c_str(), c_TODOStreamId, m_index.GetConfiguration());
// for (auto const & innerTermText : m_terms)
// {
// RowIdSequence outerRows(outerTerm, m_index.GetTermTable(shardId));
// }
// }
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2010-08-13 Markus Litz <[email protected]>
* Changed: $Id$
*
* Version: $Revision$
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* @brief Implementation of CPACS configuration handling routines.
*/
#include "CCPACSConfiguration.h"
#include "TopoDS_Shape.hxx"
#include "Standard_CString.hxx"
#include "BRepOffsetAPI_ThruSections.hxx"
#include "BRepAlgoAPI_Fuse.hxx"
#include "BRepAlgo_Fuse.hxx"
#include "ShapeFix_Shape.hxx"
#include "TopoDS_Compound.hxx"
#include "BRepFeat_Gluer.hxx"
#include "BRep_Builder.hxx"
#include "BRepMesh.hxx"
#include "IGESControl_Controller.hxx"
#include "IGESControl_Writer.hxx"
#include "StlAPI_Writer.hxx"
#include "Interface_Static.hxx"
#include "StlAPI.hxx"
#include "BRepTools.hxx"
#include <BRepBndLib.hxx>
#include <Bnd_Box.hxx>
#include <cfloat>
namespace tigl {
// Constructor
CCPACSConfiguration::CCPACSConfiguration(TixiDocumentHandle tixiHandle)
: tixiDocumentHandle(tixiHandle)
, header()
, wings(this)
, fuselages(this)
, uidManager()
{
}
// Destructor
CCPACSConfiguration::~CCPACSConfiguration(void)
{
}
// Invalidates the internal state of the configuration and forces
// recalculation of wires, lofts etc.
void CCPACSConfiguration::Invalidate(void)
{
wings.Invalidate();
fuselages.Invalidate();
fusedAirplane.Nullify();
configUID = "";
}
// Build up memory structure for whole CPACS file
void CCPACSConfiguration::ReadCPACS(const char* configurationUID)
{
if(!configurationUID) return;
header.ReadCPACS(tixiDocumentHandle);
wings.ReadCPACS(tixiDocumentHandle, configurationUID);
fuselages.ReadCPACS(tixiDocumentHandle, configurationUID);
configUID = configurationUID;
// Now do parent <-> child transformations. Child should use the
// parent coordinate system as root.
try {
transformAllComponents(uidManager.GetRootComponent());
}
catch (tigl::CTiglError& ex) {
LOG(ERROR) << ex.getError() << std::endl;
}
}
// transform all components relative to their parents
void CCPACSConfiguration::transformAllComponents(CTiglAbstractPhysicalComponent* parent)
{
CTiglAbstractPhysicalComponent::ChildContainerType& children = parent->GetChildren(false);
CTiglAbstractPhysicalComponent::ChildContainerType::iterator pIter;
CTiglPoint parentTranslation = parent->GetTranslation();
for (pIter = children.begin(); pIter != children.end(); pIter++) {
CTiglAbstractPhysicalComponent* child = *pIter;
child->Translate(parentTranslation);
transformAllComponents(child);
}
}
// Returns the boolean fused airplane as TopoDS_Shape
TopoDS_Shape& CCPACSConfiguration::GetFusedAirplane(void)
{
if(fusedAirplane.IsNull()){
CTiglAbstractPhysicalComponent* rootComponent = uidManager.GetRootComponent();
fusedAirplane = rootComponent->GetLoft();
OutputComponentTree(rootComponent);
}
return(fusedAirplane);
}
// This function does the boolean fusing
void CCPACSConfiguration::OutputComponentTree(CTiglAbstractPhysicalComponent *parent)
{
if(!parent)
throw CTiglError("Null Pointer argument in CCPACSConfiguration::OutputComponentTree", TIGL_NULL_POINTER);
bool calcFullModel = true;
TopoDS_Shape tmpShape = parent->GetMirroredLoft();
if(!tmpShape.IsNull() && calcFullModel && (parent->GetComponentType()& TIGL_COMPONENT_WING)){
try{
fusedAirplane = BRepAlgoAPI_Fuse(fusedAirplane, tmpShape);
}
catch(...){
throw CTiglError( "Error fusing " + parent->GetUID() + " mirrored component!", TIGL_ERROR);
}
}
CTiglAbstractPhysicalComponent::ChildContainerType& children = parent->GetChildren(false);
CTiglAbstractPhysicalComponent::ChildContainerType::iterator pIter;
for (pIter = children.begin(); pIter != children.end(); pIter++) {
CTiglAbstractPhysicalComponent* child = *pIter;
tmpShape = child->GetLoft();
try{
fusedAirplane = BRepAlgoAPI_Fuse(fusedAirplane, tmpShape);
}
catch(...){
throw CTiglError( "Error fusing " + parent->GetUID() + " with " + child->GetUID(), TIGL_ERROR);
}
tmpShape = child->GetMirroredLoft();
if(tmpShape.IsNull() || !calcFullModel)
continue;
try{
fusedAirplane = BRepAlgoAPI_Fuse(fusedAirplane, tmpShape);
}
catch(...){
throw CTiglError( "Error fusing " + parent->GetUID() + " with mirrored component " + child->GetUID(), TIGL_ERROR);
}
}
}
// Returns the underlying tixi document handle used by a CPACS configuration
TixiDocumentHandle CCPACSConfiguration::GetTixiDocumentHandle(void) const
{
return tixiDocumentHandle;
}
// Returns the total count of wing profiles in this configuration
int CCPACSConfiguration::GetWingProfileCount(void) const
{
return wings.GetProfileCount();
}
// Returns the wing profile for a given uid.
CCPACSWingProfile& CCPACSConfiguration::GetWingProfile(std::string uid) const
{
return wings.GetProfile(uid);
}
// Returns the wing profile for a given index - TODO: depricated function!
CCPACSWingProfile& CCPACSConfiguration::GetWingProfile(int index) const
{
return wings.GetProfile(index);
}
// Returns the total count of wings in a configuration
int CCPACSConfiguration::GetWingCount(void) const
{
return wings.GetWingCount();
}
// Returns the wing for a given index.
CCPACSWing& CCPACSConfiguration::GetWing(int index) const
{
return wings.GetWing(index);
}
// Returns the wing for a given UID.
CCPACSWing& CCPACSConfiguration::GetWing(const std::string UID) const
{
return wings.GetWing(UID);
}
TopoDS_Shape CCPACSConfiguration::GetParentLoft(const std::string UID)
{
return uidManager.GetParentComponent(UID)->GetLoft();
}
// Returns the total count of fuselage profiles in this configuration
int CCPACSConfiguration::GetFuselageProfileCount(void) const
{
return fuselages.GetProfileCount();
}
// Returns the fuselage profile for a given index.
CCPACSFuselageProfile& CCPACSConfiguration::GetFuselageProfile(int index) const
{
return fuselages.GetProfile(index);
}
// Returns the fuselage profile for a given uid.
CCPACSFuselageProfile& CCPACSConfiguration::GetFuselageProfile(std::string uid) const
{
return fuselages.GetProfile(uid);
}
// Returns the total count of fuselages in a configuration
int CCPACSConfiguration::GetFuselageCount(void) const
{
return fuselages.GetFuselageCount();
}
// Returns the fuselage for a given index.
CCPACSFuselage& CCPACSConfiguration::GetFuselage(int index) const
{
return fuselages.GetFuselage(index);
}
// Returns the fuselage for a given UID.
CCPACSFuselage& CCPACSConfiguration::GetFuselage(const std::string UID) const
{
return fuselages.GetFuselage(UID);
}
// Returns the uid manager
CTiglUIDManager& CCPACSConfiguration::GetUIDManager(void)
{
return uidManager;
}
double CCPACSConfiguration::GetAirplaneLenth(void){
Bnd_Box boundingBox;
// Draw all wings
for (int w = 1; w <= GetWingCount(); w++)
{
tigl::CCPACSWing& wing = GetWing(w);
for (int i = 1; i <= wing.GetSegmentCount(); i++)
{
tigl::CCPACSWingSegment& segment = (tigl::CCPACSWingSegment &) wing.GetSegment(i);
BRepBndLib::Add(segment.GetLoft(), boundingBox);
}
if(wing.GetSymmetryAxis() == TIGL_NO_SYMMETRY)
continue;
for (int i = 1; i <= wing.GetSegmentCount(); i++)
{
tigl::CCPACSWingSegment& segment = (tigl::CCPACSWingSegment &) wing.GetSegment(i);
BRepBndLib::Add(segment.GetLoft(), boundingBox);
}
}
for (int f = 1; f <= GetFuselageCount(); f++)
{
tigl::CCPACSFuselage& fuselage = GetFuselage(f);
for (int i = 1; i <= fuselage.GetSegmentCount(); i++)
{
tigl::CCPACSFuselageSegment& segment = (tigl::CCPACSFuselageSegment &) fuselage.GetSegment(i);
TopoDS_Shape loft = segment.GetLoft();
// Transform by fuselage transformation
loft = fuselage.GetFuselageTransformation().Transform(loft);
BRepBndLib::Add(segment.GetLoft(), boundingBox);
}
}
Standard_Real xmin, xmax, ymin, ymax, zmin, zmax;
boundingBox.Get(xmin, ymin, zmin, xmax, ymax, zmax);
return xmax-xmin;
}
// Returns the uid manager
std::string CCPACSConfiguration::GetUID(void)
{
return configUID;
}
} // end namespace tigl
<commit_msg>Fixed linux build (hopefully)<commit_after>/*
* Copyright (C) 2007-2013 German Aerospace Center (DLR/SC)
*
* Created: 2010-08-13 Markus Litz <[email protected]>
* Changed: $Id$
*
* Version: $Revision$
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* @brief Implementation of CPACS configuration handling routines.
*/
#include "CCPACSConfiguration.h"
#include "TopoDS_Shape.hxx"
#include "Standard_CString.hxx"
#include "BRepOffsetAPI_ThruSections.hxx"
#include "BRepAlgoAPI_Fuse.hxx"
#include "BRepAlgo_Fuse.hxx"
#include "ShapeFix_Shape.hxx"
#include "TopoDS_Compound.hxx"
#include "BRepFeat_Gluer.hxx"
#include "BRep_Builder.hxx"
#include "BRepMesh.hxx"
#include "IGESControl_Controller.hxx"
#include "IGESControl_Writer.hxx"
#include "StlAPI_Writer.hxx"
#include "Interface_Static.hxx"
#include "StlAPI.hxx"
#include "BRepTools.hxx"
#include <BRepBndLib.hxx>
#include <Bnd_Box.hxx>
#include <cfloat>
namespace tigl {
// Constructor
CCPACSConfiguration::CCPACSConfiguration(TixiDocumentHandle tixiHandle)
: tixiDocumentHandle(tixiHandle)
, header()
, wings(this)
, fuselages(this)
, uidManager()
{
}
// Destructor
CCPACSConfiguration::~CCPACSConfiguration(void)
{
}
// Invalidates the internal state of the configuration and forces
// recalculation of wires, lofts etc.
void CCPACSConfiguration::Invalidate(void)
{
wings.Invalidate();
fuselages.Invalidate();
fusedAirplane.Nullify();
configUID = "";
}
// Build up memory structure for whole CPACS file
void CCPACSConfiguration::ReadCPACS(const char* configurationUID)
{
if(!configurationUID) return;
header.ReadCPACS(tixiDocumentHandle);
wings.ReadCPACS(tixiDocumentHandle, configurationUID);
fuselages.ReadCPACS(tixiDocumentHandle, configurationUID);
configUID = configurationUID;
// Now do parent <-> child transformations. Child should use the
// parent coordinate system as root.
try {
transformAllComponents(uidManager.GetRootComponent());
}
catch (tigl::CTiglError& ex) {
LOG(ERROR) << ex.getError() << std::endl;
}
}
// transform all components relative to their parents
void CCPACSConfiguration::transformAllComponents(CTiglAbstractPhysicalComponent* parent)
{
CTiglAbstractPhysicalComponent::ChildContainerType children = parent->GetChildren(false);
CTiglAbstractPhysicalComponent::ChildContainerType::iterator pIter;
CTiglPoint parentTranslation = parent->GetTranslation();
for (pIter = children.begin(); pIter != children.end(); pIter++) {
CTiglAbstractPhysicalComponent* child = *pIter;
child->Translate(parentTranslation);
transformAllComponents(child);
}
}
// Returns the boolean fused airplane as TopoDS_Shape
TopoDS_Shape& CCPACSConfiguration::GetFusedAirplane(void)
{
if(fusedAirplane.IsNull()){
CTiglAbstractPhysicalComponent* rootComponent = uidManager.GetRootComponent();
fusedAirplane = rootComponent->GetLoft();
OutputComponentTree(rootComponent);
}
return(fusedAirplane);
}
// This function does the boolean fusing
void CCPACSConfiguration::OutputComponentTree(CTiglAbstractPhysicalComponent *parent)
{
if(!parent)
throw CTiglError("Null Pointer argument in CCPACSConfiguration::OutputComponentTree", TIGL_NULL_POINTER);
bool calcFullModel = true;
TopoDS_Shape tmpShape = parent->GetMirroredLoft();
if(!tmpShape.IsNull() && calcFullModel && (parent->GetComponentType()& TIGL_COMPONENT_WING)){
try{
fusedAirplane = BRepAlgoAPI_Fuse(fusedAirplane, tmpShape);
}
catch(...){
throw CTiglError( "Error fusing " + parent->GetUID() + " mirrored component!", TIGL_ERROR);
}
}
CTiglAbstractPhysicalComponent::ChildContainerType children = parent->GetChildren(false);
CTiglAbstractPhysicalComponent::ChildContainerType::iterator pIter;
for (pIter = children.begin(); pIter != children.end(); pIter++) {
CTiglAbstractPhysicalComponent* child = *pIter;
tmpShape = child->GetLoft();
try{
fusedAirplane = BRepAlgoAPI_Fuse(fusedAirplane, tmpShape);
}
catch(...){
throw CTiglError( "Error fusing " + parent->GetUID() + " with " + child->GetUID(), TIGL_ERROR);
}
tmpShape = child->GetMirroredLoft();
if(tmpShape.IsNull() || !calcFullModel)
continue;
try{
fusedAirplane = BRepAlgoAPI_Fuse(fusedAirplane, tmpShape);
}
catch(...){
throw CTiglError( "Error fusing " + parent->GetUID() + " with mirrored component " + child->GetUID(), TIGL_ERROR);
}
}
}
// Returns the underlying tixi document handle used by a CPACS configuration
TixiDocumentHandle CCPACSConfiguration::GetTixiDocumentHandle(void) const
{
return tixiDocumentHandle;
}
// Returns the total count of wing profiles in this configuration
int CCPACSConfiguration::GetWingProfileCount(void) const
{
return wings.GetProfileCount();
}
// Returns the wing profile for a given uid.
CCPACSWingProfile& CCPACSConfiguration::GetWingProfile(std::string uid) const
{
return wings.GetProfile(uid);
}
// Returns the wing profile for a given index - TODO: depricated function!
CCPACSWingProfile& CCPACSConfiguration::GetWingProfile(int index) const
{
return wings.GetProfile(index);
}
// Returns the total count of wings in a configuration
int CCPACSConfiguration::GetWingCount(void) const
{
return wings.GetWingCount();
}
// Returns the wing for a given index.
CCPACSWing& CCPACSConfiguration::GetWing(int index) const
{
return wings.GetWing(index);
}
// Returns the wing for a given UID.
CCPACSWing& CCPACSConfiguration::GetWing(const std::string UID) const
{
return wings.GetWing(UID);
}
TopoDS_Shape CCPACSConfiguration::GetParentLoft(const std::string UID)
{
return uidManager.GetParentComponent(UID)->GetLoft();
}
// Returns the total count of fuselage profiles in this configuration
int CCPACSConfiguration::GetFuselageProfileCount(void) const
{
return fuselages.GetProfileCount();
}
// Returns the fuselage profile for a given index.
CCPACSFuselageProfile& CCPACSConfiguration::GetFuselageProfile(int index) const
{
return fuselages.GetProfile(index);
}
// Returns the fuselage profile for a given uid.
CCPACSFuselageProfile& CCPACSConfiguration::GetFuselageProfile(std::string uid) const
{
return fuselages.GetProfile(uid);
}
// Returns the total count of fuselages in a configuration
int CCPACSConfiguration::GetFuselageCount(void) const
{
return fuselages.GetFuselageCount();
}
// Returns the fuselage for a given index.
CCPACSFuselage& CCPACSConfiguration::GetFuselage(int index) const
{
return fuselages.GetFuselage(index);
}
// Returns the fuselage for a given UID.
CCPACSFuselage& CCPACSConfiguration::GetFuselage(const std::string UID) const
{
return fuselages.GetFuselage(UID);
}
// Returns the uid manager
CTiglUIDManager& CCPACSConfiguration::GetUIDManager(void)
{
return uidManager;
}
double CCPACSConfiguration::GetAirplaneLenth(void){
Bnd_Box boundingBox;
// Draw all wings
for (int w = 1; w <= GetWingCount(); w++)
{
tigl::CCPACSWing& wing = GetWing(w);
for (int i = 1; i <= wing.GetSegmentCount(); i++)
{
tigl::CCPACSWingSegment& segment = (tigl::CCPACSWingSegment &) wing.GetSegment(i);
BRepBndLib::Add(segment.GetLoft(), boundingBox);
}
if(wing.GetSymmetryAxis() == TIGL_NO_SYMMETRY)
continue;
for (int i = 1; i <= wing.GetSegmentCount(); i++)
{
tigl::CCPACSWingSegment& segment = (tigl::CCPACSWingSegment &) wing.GetSegment(i);
BRepBndLib::Add(segment.GetLoft(), boundingBox);
}
}
for (int f = 1; f <= GetFuselageCount(); f++)
{
tigl::CCPACSFuselage& fuselage = GetFuselage(f);
for (int i = 1; i <= fuselage.GetSegmentCount(); i++)
{
tigl::CCPACSFuselageSegment& segment = (tigl::CCPACSFuselageSegment &) fuselage.GetSegment(i);
TopoDS_Shape loft = segment.GetLoft();
// Transform by fuselage transformation
loft = fuselage.GetFuselageTransformation().Transform(loft);
BRepBndLib::Add(segment.GetLoft(), boundingBox);
}
}
Standard_Real xmin, xmax, ymin, ymax, zmin, zmax;
boundingBox.Get(xmin, ymin, zmin, xmax, ymax, zmax);
return xmax-xmin;
}
// Returns the uid manager
std::string CCPACSConfiguration::GetUID(void)
{
return configUID;
}
} // end namespace tigl
<|endoftext|> |
<commit_before>/*
* Copyright 2010-2011 PathScale, 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
* IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* memory.cc - Contains stub definition of C++ new/delete operators.
*
* These definitions are intended to be used for testing and are weak symbols
* to allow them to be replaced by definitions from a STL implementation.
* These versions simply wrap malloc() and free(), they do not provide a
* C++-specific allocator.
*/
#include <stddef.h>
#include <stdlib.h>
#include "stdexcept.h"
#include "atomic.h"
namespace std
{
struct nothrow_t {};
}
/// The type of the function called when allocation fails.
typedef void (*new_handler)();
/**
* The function to call when allocation fails. By default, there is no
* handler and a bad allocation exception is thrown if an allocation fails.
*/
static new_handler new_handl;
namespace std
{
/**
* Sets a function to be called when there is a failure in new.
*/
__attribute__((weak))
new_handler set_new_handler(new_handler handler)
{
return ATOMIC_SWAP(&new_handl, handler);
}
__attribute__((weak))
new_handler get_new_handler(void)
{
return ATOMIC_LOAD(&new_handl);
}
}
__attribute__((weak))
void* operator new(size_t size)
{
if (0 == size)
{
size = 1;
}
void * mem = malloc(size);
while (0 == mem)
{
new_handler h = std::get_new_handler();
if (0 != h)
{
h();
}
else
{
throw std::bad_alloc();
}
mem = malloc(size);
}
return mem;
}
__attribute__((weak))
void* operator new(size_t size, const std::nothrow_t &) throw()
{
if (0 == size)
{
size = 1;
}
void *mem = malloc(size);
while (0 == mem)
{
new_handler h = std::get_new_handler();
if (0 != h)
{
try
{
h();
}
catch (...)
{
// nothrow operator new should return NULL in case of
// std::bad_alloc exception in new handler
return NULL;
}
}
else
{
return NULL;
}
mem = malloc(size);
}
return mem;
}
__attribute__((weak))
void operator delete(void * ptr)
{
free(ptr);
}
__attribute__((weak))
void * operator new[](size_t size)
{
return ::operator new(size);
}
__attribute__((weak))
void operator delete[](void * ptr) throw()
{
::operator delete(ptr);
}
<commit_msg>Ensure that the no-throw variants of new and new[] have the same behaviour as the throw variants in case of overrides.<commit_after>/*
* Copyright 2010-2011 PathScale, 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
* IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* memory.cc - Contains stub definition of C++ new/delete operators.
*
* These definitions are intended to be used for testing and are weak symbols
* to allow them to be replaced by definitions from a STL implementation.
* These versions simply wrap malloc() and free(), they do not provide a
* C++-specific allocator.
*/
#include <stddef.h>
#include <stdlib.h>
#include "stdexcept.h"
#include "atomic.h"
namespace std
{
struct nothrow_t {};
}
/// The type of the function called when allocation fails.
typedef void (*new_handler)();
/**
* The function to call when allocation fails. By default, there is no
* handler and a bad allocation exception is thrown if an allocation fails.
*/
static new_handler new_handl;
namespace std
{
/**
* Sets a function to be called when there is a failure in new.
*/
__attribute__((weak))
new_handler set_new_handler(new_handler handler)
{
return ATOMIC_SWAP(&new_handl, handler);
}
__attribute__((weak))
new_handler get_new_handler(void)
{
return ATOMIC_LOAD(&new_handl);
}
}
__attribute__((weak))
void* operator new(size_t size)
{
if (0 == size)
{
size = 1;
}
void * mem = malloc(size);
while (0 == mem)
{
new_handler h = std::get_new_handler();
if (0 != h)
{
h();
}
else
{
throw std::bad_alloc();
}
mem = malloc(size);
}
return mem;
}
__attribute__((weak))
void* operator new(size_t size, const std::nothrow_t &) throw()
{
try {
return :: operator new(size);
} catch (...) {
// nothrow operator new should return NULL in case of
// std::bad_alloc exception in new handler
return NULL;
}
}
__attribute__((weak))
void operator delete(void * ptr)
{
free(ptr);
}
__attribute__((weak))
void * operator new[](size_t size)
{
return ::operator new(size);
}
__attribute__((weak))
void * operator new[](size_t size, const std::nothrow_t &) throw()
{
try {
return ::operator new[](size);
} catch (...) {
// nothrow operator new should return NULL in case of
// std::bad_alloc exception in new handler
return NULL;
}
}
__attribute__((weak))
void operator delete[](void * ptr) throw()
{
::operator delete(ptr);
}
<|endoftext|> |
<commit_before><commit_msg>- Enable V8 histograming support - All V8 measurements that had been stats timers will now be histogramed instead<commit_after><|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*
* spiral_reference_line_smoother.cc
*/
#include "modules/planning/reference_line/spiral_reference_line_smoother.h"
#include <algorithm>
#include <iomanip>
#include <utility>
#include "IpIpoptApplication.hpp"
#include "IpSolveStatistics.hpp"
#include "glog/logging.h"
#include "modules/common/time/time.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/math/curve1d/quintic_spiral_path.h"
#include "modules/planning/reference_line/spiral_problem_interface.h"
namespace apollo {
namespace planning {
using apollo::common::time::Clock;
SpiralReferenceLineSmoother::SpiralReferenceLineSmoother(
const double max_point_deviation)
: default_max_point_deviation_(max_point_deviation) {
CHECK(max_point_deviation >= 0.0);
}
bool SpiralReferenceLineSmoother::Smooth(
const ReferenceLine& raw_reference_line,
ReferenceLine* const smoothed_reference_line) {
const double start_timestamp = Clock::NowInSecond();
std::vector<double> opt_x;
std::vector<double> opt_y;
std::vector<double> opt_theta;
std::vector<double> opt_kappa;
std::vector<double> opt_dkappa;
std::vector<double> opt_s;
if (anchor_points_.empty()) {
const double piecewise_length = FLAGS_spiral_smoother_piecewise_length;
const double length = raw_reference_line.Length();
ADEBUG << "Length = " << length;
uint32_t num_of_pieces =
std::max(1u, static_cast<uint32_t>(length / piecewise_length));
const double delta_s = length / num_of_pieces;
double s = 0.0;
std::vector<Eigen::Vector2d> raw_point2d;
for (std::uint32_t i = 0; i <= num_of_pieces;
++i, s = std::fmin(s + delta_s, length)) {
ReferencePoint rlp = raw_reference_line.GetReferencePoint(s);
raw_point2d.emplace_back(rlp.x(), rlp.y());
}
Smooth(raw_point2d, &opt_theta, &opt_kappa, &opt_dkappa, &opt_s, &opt_x,
&opt_y);
} else {
std::size_t start_index = 0;
for (const auto& anchor_point : anchor_points_) {
if (anchor_point.enforced) {
start_index++;
}
}
std::vector<Eigen::Vector2d> raw_point2d;
if (start_index == 0) {
for (const auto& anchor_point : anchor_points_) {
raw_point2d.emplace_back(anchor_point.path_point.x(),
anchor_point.path_point.y());
}
} else {
std::vector<double> overhead_s;
for (std::size_t i = 0; i + 1 < start_index; ++i) {
const auto& p0 = anchor_points_[i];
const auto& p1 = anchor_points_[i + 1];
overhead_s.push_back(p1.path_point.s() - p0.path_point.s());
}
std::vector<double> overhead_theta;
std::vector<double> overhead_kappa;
std::vector<double> overhead_dkappa;
std::vector<double> overhead_x;
std::vector<double> overhead_y;
for (std::size_t i = 0; i < anchor_points_.size(); ++i) {
const auto& p = anchor_points_[i];
if (i + 1 < start_index) {
overhead_theta.push_back(p.path_point.theta());
overhead_kappa.push_back(p.path_point.kappa());
overhead_dkappa.push_back(p.path_point.dkappa());
overhead_x.push_back(p.path_point.x());
overhead_y.push_back(p.path_point.y());
} else {
raw_point2d.emplace_back(p.path_point.x(), p.path_point.y());
}
}
fixed_start_point_ = true;
fixed_start_x_ = anchor_points_[start_index - 1].path_point.x();
fixed_start_y_ = anchor_points_[start_index - 1].path_point.y();
fixed_start_theta_ = common::math::NormalizeAngle(
anchor_points_[start_index - 1].path_point.theta());
fixed_start_kappa_ = anchor_points_[start_index - 1].path_point.kappa();
fixed_start_dkappa_ = anchor_points_[start_index - 1].path_point.dkappa();
Smooth(raw_point2d, &opt_theta, &opt_kappa, &opt_dkappa, &opt_s, &opt_x,
&opt_y);
opt_theta.insert(opt_theta.begin(), overhead_theta.begin(),
overhead_theta.end());
opt_kappa.insert(opt_kappa.begin(), overhead_kappa.begin(),
overhead_kappa.end());
opt_dkappa.insert(opt_dkappa.begin(), overhead_dkappa.begin(),
overhead_dkappa.end());
opt_s.insert(opt_s.begin(), overhead_s.begin(), overhead_s.end());
opt_x.insert(opt_x.begin(), overhead_x.begin(), overhead_x.end());
opt_y.insert(opt_y.begin(), overhead_y.begin(), overhead_y.end());
std::for_each(opt_x.begin(), opt_x.end(), [this](double& x){
x += zero_x_;
});
std::for_each(opt_y.begin(), opt_y.end(), [this](double& y){
y += zero_y_;
});
}
}
std::vector<common::PathPoint> smoothed_point2d =
Interpolate(opt_theta, opt_kappa, opt_dkappa, opt_s, opt_x, opt_y,
FLAGS_spiral_reference_line_resolution);
std::vector<ReferencePoint> ref_points;
for (const auto& p : smoothed_point2d) {
const double heading = p.theta();
const double kappa = p.kappa();
const double dkappa = p.dkappa();
common::SLPoint ref_sl_point;
if (!raw_reference_line.XYToSL({p.x(), p.y()}, &ref_sl_point)) {
return false;
}
if (ref_sl_point.s() < 0 ||
ref_sl_point.s() > raw_reference_line.Length()) {
continue;
}
ReferencePoint rlp = raw_reference_line.GetReferencePoint(ref_sl_point.s());
ref_points.emplace_back(
ReferencePoint(hdmap::MapPathPoint(common::math::Vec2d(p.x(), p.y()),
heading, rlp.lane_waypoints()),
kappa, dkappa, 0.0, 0.0));
}
ReferencePoint::RemoveDuplicates(&ref_points);
if (ref_points.size() < 2) {
AERROR << "Fail to generate smoothed reference line.";
return false;
}
*smoothed_reference_line = ReferenceLine(ref_points);
const double end_timestamp = Clock::NowInSecond();
ADEBUG << "Spiral reference line smoother time: "
<< (end_timestamp - start_timestamp) * 1000 << " ms.";
return true;
}
bool SpiralReferenceLineSmoother::Smooth(std::vector<Eigen::Vector2d> point2d,
std::vector<double>* ptr_theta,
std::vector<double>* ptr_kappa,
std::vector<double>* ptr_dkappa,
std::vector<double>* ptr_s,
std::vector<double>* ptr_x,
std::vector<double>* ptr_y) const {
CHECK_GT(point2d.size(), 1);
SpiralProblemInterface* ptop = new SpiralProblemInterface(point2d);
ptop->set_default_max_point_deviation(default_max_point_deviation_);
if (fixed_start_point_) {
ptop->set_start_point(fixed_start_x_, fixed_start_y_, fixed_start_theta_,
fixed_start_kappa_, fixed_start_dkappa_);
}
Ipopt::SmartPtr<Ipopt::TNLP> problem = ptop;
// Create an instance of the IpoptApplication
Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory();
// app->Options()->SetStringValue("jacobian_approximation",
// "finite-difference-values");
app->Options()->SetStringValue("hessian_approximation", "limited-memory");
// app->Options()->SetStringValue("derivative_test", "first-order");
// app->Options()->SetNumericValue("derivative_test_perturbation", 1.0e-7);
// app->Options()->SetStringValue("derivative_test", "second-order");
app->Options()->SetIntegerValue("print_level", 0);
int num_iterations = FLAGS_spiral_smoother_num_iteration;
app->Options()->SetIntegerValue("max_iter", num_iterations);
// app->Options()->SetNumericValue("acceptable_tol", 0.5);
// app->Options()->SetNumericValue("acceptable_obj_change_tol", 0.5);
// app->Options()->SetNumericValue("constr_viol_tol", 0.01);
// app->Options()->SetIntegerValue("acceptable_iter", 10);
// app->Options()->SetIntegerValue("print_level", 0);
// app->Options()->SetStringValue("fast_step_computation", "yes");
Ipopt::ApplicationReturnStatus status = app->Initialize();
if (status != Ipopt::Solve_Succeeded) {
ADEBUG << "*** Error during initialization!";
return static_cast<int>(status);
}
status = app->OptimizeTNLP(problem);
if (status == Ipopt::Solve_Succeeded ||
status == Ipopt::Solved_To_Acceptable_Level) {
// Retrieve some statistics about the solve
Ipopt::Index iter_count = app->Statistics()->IterationCount();
ADEBUG << "*** The problem solved in " << iter_count << " iterations!";
Ipopt::Number final_obj = app->Statistics()->FinalObjective();
ADEBUG << "*** The final value of the objective function is " << final_obj
<< '.';
} else {
ADEBUG << "Return status: " << int(status);
}
ptop->get_optimization_results(ptr_theta, ptr_kappa, ptr_dkappa, ptr_s, ptr_x,
ptr_y);
return status == Ipopt::Solve_Succeeded ||
status == Ipopt::Solved_To_Acceptable_Level;
}
std::vector<common::PathPoint> SpiralReferenceLineSmoother::Interpolate(
const std::vector<double>& theta, const std::vector<double>& kappa,
const std::vector<double>& dkappa, const std::vector<double>& s,
const std::vector<double>& x, const std::vector<double>& y,
const double resolution) const {
std::vector<common::PathPoint> smoothed_point2d;
double start_s = 0.0;
common::PathPoint first_point =
to_path_point(x.front(), y.front(), start_s, theta.front(), kappa.front(),
dkappa.front());
smoothed_point2d.push_back(first_point);
for (std::size_t i = 0; i + 1 < theta.size(); ++i) {
double start_x = x[i];
double start_y = y[i];
auto path_point_seg = Interpolate(
start_x, start_y, start_s, theta[i], kappa[i], dkappa[i], theta[i + 1],
kappa[i + 1], dkappa[i + 1], s[i], resolution);
smoothed_point2d.insert(smoothed_point2d.end(), path_point_seg.begin(),
path_point_seg.end());
start_s = smoothed_point2d.back().s();
}
return smoothed_point2d;
}
std::vector<common::PathPoint> SpiralReferenceLineSmoother::Interpolate(
const double start_x, const double start_y, const double start_s,
const double theta0, const double kappa0, const double dkappa0,
const double theta1, const double kappa1, const double dkappa1,
const double delta_s, const double resolution) const {
std::vector<common::PathPoint> path_points;
QuinticSpiralPath spiral_curve(theta0, kappa0, dkappa0, theta1, kappa1,
dkappa1, delta_s);
std::size_t num_of_points = std::ceil(delta_s / resolution) + 1;
for (std::size_t i = 1; i <= num_of_points; ++i) {
const double inter_s = delta_s / num_of_points * i;
const double dx = spiral_curve.ComputeCartesianDeviationX<10>(inter_s);
const double dy = spiral_curve.ComputeCartesianDeviationY<10>(inter_s);
const double theta =
common::math::NormalizeAngle(spiral_curve.Evaluate(0, inter_s));
const double kappa = spiral_curve.Evaluate(1, inter_s);
const double dkappa = spiral_curve.Evaluate(2, inter_s);
auto path_point = to_path_point(start_x + dx, start_y + dy,
start_s + inter_s, theta, kappa, dkappa);
path_points.push_back(std::move(path_point));
}
return path_points;
}
common::PathPoint SpiralReferenceLineSmoother::to_path_point(
const double x, const double y, const double s, const double theta,
const double kappa, const double dkappa) const {
common::PathPoint point;
point.set_x(x);
point.set_y(y);
point.set_s(s);
point.set_theta(theta);
point.set_kappa(kappa);
point.set_dkappa(dkappa);
return point;
}
void SpiralReferenceLineSmoother::SetAnchorPoints(
const std::vector<AnchorPoint>& anchor_points) {
anchor_points_ = std::move(anchor_points);
CHECK_GT(anchor_points_.size(), 1);
zero_x_ = anchor_points_.front().path_point.x();
zero_y_ = anchor_points_.front().path_point.y();
std::for_each(anchor_points_.begin(), anchor_points_.end(),
[this](AnchorPoint& p) {
auto curr_x = p.path_point.x();
auto curr_y = p.path_point.y();
p.path_point.set_x(curr_x - zero_x_);
p.path_point.set_y(curr_y - zero_y_);});
}
} // namespace planning
} // namespace apollo
<commit_msg>planning: bug fix for spiral reference line smoother to determine starting constrained anchor point<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/*
* spiral_reference_line_smoother.cc
*/
#include "modules/planning/reference_line/spiral_reference_line_smoother.h"
#include <algorithm>
#include <iomanip>
#include <utility>
#include "IpIpoptApplication.hpp"
#include "IpSolveStatistics.hpp"
#include "glog/logging.h"
#include "modules/common/time/time.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/math/curve1d/quintic_spiral_path.h"
#include "modules/planning/reference_line/spiral_problem_interface.h"
namespace apollo {
namespace planning {
using apollo::common::time::Clock;
SpiralReferenceLineSmoother::SpiralReferenceLineSmoother(
const double max_point_deviation)
: default_max_point_deviation_(max_point_deviation) {
CHECK(max_point_deviation >= 0.0);
}
bool SpiralReferenceLineSmoother::Smooth(
const ReferenceLine& raw_reference_line,
ReferenceLine* const smoothed_reference_line) {
const double start_timestamp = Clock::NowInSecond();
std::vector<double> opt_x;
std::vector<double> opt_y;
std::vector<double> opt_theta;
std::vector<double> opt_kappa;
std::vector<double> opt_dkappa;
std::vector<double> opt_s;
if (anchor_points_.empty()) {
const double piecewise_length = FLAGS_spiral_smoother_piecewise_length;
const double length = raw_reference_line.Length();
ADEBUG << "Length = " << length;
uint32_t num_of_pieces =
std::max(1u, static_cast<uint32_t>(length / piecewise_length));
const double delta_s = length / num_of_pieces;
double s = 0.0;
std::vector<Eigen::Vector2d> raw_point2d;
for (std::uint32_t i = 0; i <= num_of_pieces;
++i, s = std::fmin(s + delta_s, length)) {
ReferencePoint rlp = raw_reference_line.GetReferencePoint(s);
raw_point2d.emplace_back(rlp.x(), rlp.y());
}
Smooth(raw_point2d, &opt_theta, &opt_kappa, &opt_dkappa, &opt_s, &opt_x,
&opt_y);
} else {
std::size_t start_index = 0;
for (const auto& anchor_point : anchor_points_) {
if (anchor_point.enforced) {
start_index++;
} else {
break;
}
}
std::vector<Eigen::Vector2d> raw_point2d;
if (start_index == 0) {
for (const auto& anchor_point : anchor_points_) {
raw_point2d.emplace_back(anchor_point.path_point.x(),
anchor_point.path_point.y());
}
} else {
std::vector<double> overhead_s;
for (std::size_t i = 0; i + 1 < start_index; ++i) {
const auto& p0 = anchor_points_[i];
const auto& p1 = anchor_points_[i + 1];
overhead_s.push_back(p1.path_point.s() - p0.path_point.s());
}
std::vector<double> overhead_theta;
std::vector<double> overhead_kappa;
std::vector<double> overhead_dkappa;
std::vector<double> overhead_x;
std::vector<double> overhead_y;
for (std::size_t i = 0; i < anchor_points_.size(); ++i) {
const auto& p = anchor_points_[i];
if (i + 1 < start_index) {
overhead_theta.push_back(p.path_point.theta());
overhead_kappa.push_back(p.path_point.kappa());
overhead_dkappa.push_back(p.path_point.dkappa());
overhead_x.push_back(p.path_point.x());
overhead_y.push_back(p.path_point.y());
} else {
raw_point2d.emplace_back(p.path_point.x(), p.path_point.y());
}
}
fixed_start_point_ = true;
fixed_start_x_ = anchor_points_[start_index - 1].path_point.x();
fixed_start_y_ = anchor_points_[start_index - 1].path_point.y();
fixed_start_theta_ = common::math::NormalizeAngle(
anchor_points_[start_index - 1].path_point.theta());
fixed_start_kappa_ = anchor_points_[start_index - 1].path_point.kappa();
fixed_start_dkappa_ = anchor_points_[start_index - 1].path_point.dkappa();
Smooth(raw_point2d, &opt_theta, &opt_kappa, &opt_dkappa, &opt_s, &opt_x,
&opt_y);
opt_theta.insert(opt_theta.begin(), overhead_theta.begin(),
overhead_theta.end());
opt_kappa.insert(opt_kappa.begin(), overhead_kappa.begin(),
overhead_kappa.end());
opt_dkappa.insert(opt_dkappa.begin(), overhead_dkappa.begin(),
overhead_dkappa.end());
opt_s.insert(opt_s.begin(), overhead_s.begin(), overhead_s.end());
opt_x.insert(opt_x.begin(), overhead_x.begin(), overhead_x.end());
opt_y.insert(opt_y.begin(), overhead_y.begin(), overhead_y.end());
std::for_each(opt_x.begin(), opt_x.end(), [this](double& x){
x += zero_x_;
});
std::for_each(opt_y.begin(), opt_y.end(), [this](double& y){
y += zero_y_;
});
}
}
std::vector<common::PathPoint> smoothed_point2d =
Interpolate(opt_theta, opt_kappa, opt_dkappa, opt_s, opt_x, opt_y,
FLAGS_spiral_reference_line_resolution);
std::vector<ReferencePoint> ref_points;
for (const auto& p : smoothed_point2d) {
const double heading = p.theta();
const double kappa = p.kappa();
const double dkappa = p.dkappa();
common::SLPoint ref_sl_point;
if (!raw_reference_line.XYToSL({p.x(), p.y()}, &ref_sl_point)) {
return false;
}
if (ref_sl_point.s() < 0 ||
ref_sl_point.s() > raw_reference_line.Length()) {
continue;
}
ReferencePoint rlp = raw_reference_line.GetReferencePoint(ref_sl_point.s());
ref_points.emplace_back(
ReferencePoint(hdmap::MapPathPoint(common::math::Vec2d(p.x(), p.y()),
heading, rlp.lane_waypoints()),
kappa, dkappa, 0.0, 0.0));
}
ReferencePoint::RemoveDuplicates(&ref_points);
if (ref_points.size() < 2) {
AERROR << "Fail to generate smoothed reference line.";
return false;
}
*smoothed_reference_line = ReferenceLine(ref_points);
const double end_timestamp = Clock::NowInSecond();
ADEBUG << "Spiral reference line smoother time: "
<< (end_timestamp - start_timestamp) * 1000 << " ms.";
return true;
}
bool SpiralReferenceLineSmoother::Smooth(std::vector<Eigen::Vector2d> point2d,
std::vector<double>* ptr_theta,
std::vector<double>* ptr_kappa,
std::vector<double>* ptr_dkappa,
std::vector<double>* ptr_s,
std::vector<double>* ptr_x,
std::vector<double>* ptr_y) const {
CHECK_GT(point2d.size(), 1);
SpiralProblemInterface* ptop = new SpiralProblemInterface(point2d);
ptop->set_default_max_point_deviation(default_max_point_deviation_);
if (fixed_start_point_) {
ptop->set_start_point(fixed_start_x_, fixed_start_y_, fixed_start_theta_,
fixed_start_kappa_, fixed_start_dkappa_);
}
Ipopt::SmartPtr<Ipopt::TNLP> problem = ptop;
// Create an instance of the IpoptApplication
Ipopt::SmartPtr<Ipopt::IpoptApplication> app = IpoptApplicationFactory();
// app->Options()->SetStringValue("jacobian_approximation",
// "finite-difference-values");
app->Options()->SetStringValue("hessian_approximation", "limited-memory");
// app->Options()->SetStringValue("derivative_test", "first-order");
// app->Options()->SetNumericValue("derivative_test_perturbation", 1.0e-7);
// app->Options()->SetStringValue("derivative_test", "second-order");
app->Options()->SetIntegerValue("print_level", 0);
int num_iterations = FLAGS_spiral_smoother_num_iteration;
app->Options()->SetIntegerValue("max_iter", num_iterations);
// app->Options()->SetNumericValue("acceptable_tol", 0.5);
// app->Options()->SetNumericValue("acceptable_obj_change_tol", 0.5);
// app->Options()->SetNumericValue("constr_viol_tol", 0.01);
// app->Options()->SetIntegerValue("acceptable_iter", 10);
// app->Options()->SetIntegerValue("print_level", 0);
// app->Options()->SetStringValue("fast_step_computation", "yes");
Ipopt::ApplicationReturnStatus status = app->Initialize();
if (status != Ipopt::Solve_Succeeded) {
ADEBUG << "*** Error during initialization!";
return static_cast<int>(status);
}
status = app->OptimizeTNLP(problem);
if (status == Ipopt::Solve_Succeeded ||
status == Ipopt::Solved_To_Acceptable_Level) {
// Retrieve some statistics about the solve
Ipopt::Index iter_count = app->Statistics()->IterationCount();
ADEBUG << "*** The problem solved in " << iter_count << " iterations!";
Ipopt::Number final_obj = app->Statistics()->FinalObjective();
ADEBUG << "*** The final value of the objective function is " << final_obj
<< '.';
} else {
ADEBUG << "Return status: " << int(status);
}
ptop->get_optimization_results(ptr_theta, ptr_kappa, ptr_dkappa, ptr_s, ptr_x,
ptr_y);
return status == Ipopt::Solve_Succeeded ||
status == Ipopt::Solved_To_Acceptable_Level;
}
std::vector<common::PathPoint> SpiralReferenceLineSmoother::Interpolate(
const std::vector<double>& theta, const std::vector<double>& kappa,
const std::vector<double>& dkappa, const std::vector<double>& s,
const std::vector<double>& x, const std::vector<double>& y,
const double resolution) const {
std::vector<common::PathPoint> smoothed_point2d;
double start_s = 0.0;
common::PathPoint first_point =
to_path_point(x.front(), y.front(), start_s, theta.front(), kappa.front(),
dkappa.front());
smoothed_point2d.push_back(first_point);
for (std::size_t i = 0; i + 1 < theta.size(); ++i) {
double start_x = x[i];
double start_y = y[i];
auto path_point_seg = Interpolate(
start_x, start_y, start_s, theta[i], kappa[i], dkappa[i], theta[i + 1],
kappa[i + 1], dkappa[i + 1], s[i], resolution);
smoothed_point2d.insert(smoothed_point2d.end(), path_point_seg.begin(),
path_point_seg.end());
start_s = smoothed_point2d.back().s();
}
return smoothed_point2d;
}
std::vector<common::PathPoint> SpiralReferenceLineSmoother::Interpolate(
const double start_x, const double start_y, const double start_s,
const double theta0, const double kappa0, const double dkappa0,
const double theta1, const double kappa1, const double dkappa1,
const double delta_s, const double resolution) const {
std::vector<common::PathPoint> path_points;
QuinticSpiralPath spiral_curve(theta0, kappa0, dkappa0, theta1, kappa1,
dkappa1, delta_s);
std::size_t num_of_points = std::ceil(delta_s / resolution) + 1;
for (std::size_t i = 1; i <= num_of_points; ++i) {
const double inter_s = delta_s / num_of_points * i;
const double dx = spiral_curve.ComputeCartesianDeviationX<10>(inter_s);
const double dy = spiral_curve.ComputeCartesianDeviationY<10>(inter_s);
const double theta =
common::math::NormalizeAngle(spiral_curve.Evaluate(0, inter_s));
const double kappa = spiral_curve.Evaluate(1, inter_s);
const double dkappa = spiral_curve.Evaluate(2, inter_s);
auto path_point = to_path_point(start_x + dx, start_y + dy,
start_s + inter_s, theta, kappa, dkappa);
path_points.push_back(std::move(path_point));
}
return path_points;
}
common::PathPoint SpiralReferenceLineSmoother::to_path_point(
const double x, const double y, const double s, const double theta,
const double kappa, const double dkappa) const {
common::PathPoint point;
point.set_x(x);
point.set_y(y);
point.set_s(s);
point.set_theta(theta);
point.set_kappa(kappa);
point.set_dkappa(dkappa);
return point;
}
void SpiralReferenceLineSmoother::SetAnchorPoints(
const std::vector<AnchorPoint>& anchor_points) {
anchor_points_ = std::move(anchor_points);
CHECK_GT(anchor_points_.size(), 1);
zero_x_ = anchor_points_.front().path_point.x();
zero_y_ = anchor_points_.front().path_point.y();
std::for_each(anchor_points_.begin(), anchor_points_.end(),
[this](AnchorPoint& p) {
auto curr_x = p.path_point.x();
auto curr_y = p.path_point.y();
p.path_point.set_x(curr_x - zero_x_);
p.path_point.set_y(curr_y - zero_y_);});
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>#include <stan/math/prim/scal/fun/squared_distance.hpp>
#include <gtest/gtest.h>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/scal/fun/value_of.hpp>
#include <stan/math/rev/scal/fun/value_of_rec.hpp>
TEST(MathRev, squared_distance) {
double x1 = 1;
double x2 = 4;
stan::math::var v1, v2, f;
std::vector<stan::math::var> vars;
std::vector<double> grad_f;
v1 = 1;
v2 = 4;
vars.push_back(v1);
vars.push_back(v2);
f = stan::math::squared_distance(v1, v2);
f.grad(vars, grad_f);
EXPECT_FLOAT_EQ(9, f.val());
ASSERT_EQ(2, grad_f.size());
EXPECT_FLOAT_EQ(-6, grad_f[0]);
EXPECT_FLOAT_EQ(6, grad_f[1]);
stan::math::set_zero_all_adjoints();
vars.clear();
v1 = 1;
vars.push_back(v1);
f = stan::math::squared_distance(v1, x2);
f.grad(vars, grad_f);
EXPECT_FLOAT_EQ(9, f.val());
ASSERT_EQ(1, grad_f.size());
EXPECT_FLOAT_EQ(-6, grad_f[0]);
stan::math::set_zero_all_adjoints();
vars.clear();
v2 = 4;
vars.push_back(v2);
f = stan::math::squared_distance(x1, v2);
f.grad(vars, grad_f);
EXPECT_FLOAT_EQ(9, f.val());
ASSERT_EQ(1, grad_f.size());
EXPECT_FLOAT_EQ(6, grad_f[0]);
stan::math::set_zero_all_adjoints();
vars.clear();
}
TEST(MathRev, squared_distance_nan) {
double x = 1;
stan::math::var x_v = 1;
double nan = std::numeric_limits<double>::quiet_NaN();
stan::math::var nan_v = std::numeric_limits<double>::quiet_NaN();
EXPECT_THROW(stan::math::squared_distance(x_v, nan_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(nan_v, x_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(nan_v, nan_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(x, nan_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(nan, x_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(nan, nan_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(x_v, nan),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(nan_v, x),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(nan_v, nan),
std::domain_error);
}
TEST(MathRev, squared_distance_inf) {
double x = 1;
stan::math::var x_v = 1;
double inf = std::numeric_limits<double>::infinity();
stan::math::var inf_v = std::numeric_limits<double>::infinity();
EXPECT_THROW(stan::math::squared_distance(x_v, inf_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(inf_v, x_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(inf_v, inf_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(x_v, inf),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(inf_v, x),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(inf_v, inf),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(x, inf_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(inf, x_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(inf, inf_v),
std::domain_error);
}
<commit_msg>Updating test<commit_after>#include <stan/math/prim/scal/fun/squared_distance.hpp>
#include <gtest/gtest.h>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/scal/fun/value_of.hpp>
#include <stan/math/rev/scal/fun/value_of_rec.hpp>
TEST(MathRev, squared_distance) {
double x1 = 1;
double x2 = 4;
stan::math::var v1, v2, f;
std::vector<stan::math::var> vars;
std::vector<double> grad_f;
v1 = 1;
v2 = 4;
vars.push_back(v1);
vars.push_back(v2);
f = stan::math::squared_distance(v1, v2);
f.grad(vars, grad_f);
EXPECT_FLOAT_EQ(9, f.val());
ASSERT_EQ(2, grad_f.size());
EXPECT_FLOAT_EQ(-6, grad_f[0]);
EXPECT_FLOAT_EQ(6, grad_f[1]);
stan::math::recover_memory();
vars.clear();
v1 = 1;
vars.push_back(v1);
f = stan::math::squared_distance(v1, x2);
f.grad(vars, grad_f);
EXPECT_FLOAT_EQ(9, f.val());
ASSERT_EQ(1, grad_f.size());
EXPECT_FLOAT_EQ(-6, grad_f[0]);
stan::math::recover_memory();
vars.clear();
v2 = 4;
vars.push_back(v2);
f = stan::math::squared_distance(x1, v2);
f.grad(vars, grad_f);
EXPECT_FLOAT_EQ(9, f.val());
ASSERT_EQ(1, grad_f.size());
EXPECT_FLOAT_EQ(6, grad_f[0]);
stan::math::recover_memory();
vars.clear();
}
TEST(MathRev, squared_distance_nan) {
double x = 1;
stan::math::var x_v = 1;
double nan = std::numeric_limits<double>::quiet_NaN();
stan::math::var nan_v = std::numeric_limits<double>::quiet_NaN();
EXPECT_THROW(stan::math::squared_distance(x_v, nan_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(nan_v, x_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(nan_v, nan_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(x, nan_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(nan, x_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(nan, nan_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(x_v, nan),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(nan_v, x),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(nan_v, nan),
std::domain_error);
}
TEST(MathRev, squared_distance_inf) {
double x = 1;
stan::math::var x_v = 1;
double inf = std::numeric_limits<double>::infinity();
stan::math::var inf_v = std::numeric_limits<double>::infinity();
EXPECT_THROW(stan::math::squared_distance(x_v, inf_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(inf_v, x_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(inf_v, inf_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(x_v, inf),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(inf_v, x),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(inf_v, inf),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(x, inf_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(inf, x_v),
std::domain_error);
EXPECT_THROW(stan::math::squared_distance(inf, inf_v),
std::domain_error);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 Roman Neuhauser
// Distributed under the MIT license (see LICENSE file)
// vim: sw=4 sts=4 et fdm=marker cms=\ //\ %s
#ifndef INIPHILE_INCLUDE_INPUT_HPP
#define INIPHILE_INCLUDE_INPUT_HPP
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include "metagram.hpp"
namespace iniphile
{
namespace ascii = boost::spirit::ascii;
using ascii::alnum;
using ascii::alpha;
using ascii::blank;
using ascii::char_;
using ascii::digit;
using ascii::no_case;
using ascii::space;
using ascii::string;
using boost::optional;
namespace qi = boost::spirit::qi;
namespace phx = boost::phoenix;
using qi::lexeme;
using qi::skip;
using qi::eoi;
using qi::eol;
using qi::omit;
using phx::val;
using phx::construct;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_4;
using qi::on_error;
using qi::fail;
// public type
typedef metagram::config config;
template<class Iter>
struct
grammar
: qi::grammar<Iter, metagram::config()>
{
template<class T>
struct my
{
typedef qi::rule<Iter, T> rule;
};
grammar(std::ostream & erros)
: grammar::base_type(start)
{ // {{{
start
%= *section
>> eoi
;
optionline
%= optname
> omit[*blank]
> '='
> omit[*space]
> optval
> eol
;
section
%= headerline
> *optionline
;
headerline
%= lexeme['[' > sectionname > ']']
> eol
;
sectionname %= lexeme[+~char_(']')];
optname %= bareword;
optval %= (qstring | bareword) % +blank;
bareword %= lexeme[+(alnum | char_("-.,_$"))];
qstring %= lexeme['"' > *~char_('"') > '"'];
on_error<fail>
(
start
, erros
<< val("Error! Expecting ")
<< _4
<< val(" here: \"")
<< construct<std::string>(_3, _2)
<< val("\"")
<< std::endl
);
start.name("start");
commentline.name("commentline");
optionline.name("optionline");
section.name("section");
headerline.name("headerline");
sectionname.name("sectionname");
optname.name("optname");
optval.name("optval");
bareword.name("bareword");
qstring.name("qstring");
comment.name("comment");
} // }}}
typename my<metagram::config()>::rule start;
typename my<void()>::rule commentline;
typename my<metagram::assignment()>::rule optionline;
typename my<metagram::section()>::rule section;
typename my<metagram::sectionname()>::rule headerline;
typename my<metagram::sectionname()>::rule sectionname;
typename my<metagram::optname()>::rule optname;
typename my<metagram::optval()>::rule optval;
typename my<metagram::qstring()>::rule qstring;
typename my<metagram::bareword()>::rule bareword;
typename my<void()>::rule comment;
};
template<class Iter>
optional<metagram::config>
parse(Iter & first, Iter last, std::ostream & erros) // {{{
{
grammar<Iter> g(erros);
metagram::config cfg;
optional<metagram::config> rv;
bool ok = qi::parse(
first
, last
, g
, cfg
);
if (ok && first == last)
rv = cfg;
return rv;
} // }}}
} // namespace iniphile
#endif
<commit_msg>sectionname: must not span lines<commit_after>// Copyright (c) 2009 Roman Neuhauser
// Distributed under the MIT license (see LICENSE file)
// vim: sw=4 sts=4 et fdm=marker cms=\ //\ %s
#ifndef INIPHILE_INCLUDE_INPUT_HPP
#define INIPHILE_INCLUDE_INPUT_HPP
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include "metagram.hpp"
namespace iniphile
{
namespace ascii = boost::spirit::ascii;
using ascii::alnum;
using ascii::alpha;
using ascii::blank;
using ascii::char_;
using ascii::digit;
using ascii::no_case;
using ascii::space;
using ascii::string;
using boost::optional;
namespace qi = boost::spirit::qi;
namespace phx = boost::phoenix;
using qi::lexeme;
using qi::skip;
using qi::eoi;
using qi::eol;
using qi::omit;
using phx::val;
using phx::construct;
using qi::_1;
using qi::_2;
using qi::_3;
using qi::_4;
using qi::on_error;
using qi::fail;
// public type
typedef metagram::config config;
template<class Iter>
struct
grammar
: qi::grammar<Iter, metagram::config()>
{
template<class T>
struct my
{
typedef qi::rule<Iter, T> rule;
};
grammar(std::ostream & erros)
: grammar::base_type(start)
{ // {{{
start
%= *section
>> eoi
;
optionline
%= optname
> omit[*blank]
> '='
> omit[*space]
> optval
> eol
;
section
%= headerline
> *optionline
;
headerline
%= lexeme['[' > sectionname > ']']
> eol
;
sectionname %= lexeme[+~char_("\n\r]")];
optname %= bareword;
optval %= (qstring | bareword) % +blank;
bareword %= lexeme[+(alnum | char_("-.,_$"))];
qstring %= lexeme['"' > *~char_('"') > '"'];
on_error<fail>
(
start
, erros
<< val("Error! Expecting ")
<< _4
<< val(" here: \"")
<< construct<std::string>(_3, _2)
<< val("\"")
<< std::endl
);
start.name("start");
commentline.name("commentline");
optionline.name("optionline");
section.name("section");
headerline.name("headerline");
sectionname.name("sectionname");
optname.name("optname");
optval.name("optval");
bareword.name("bareword");
qstring.name("qstring");
comment.name("comment");
} // }}}
typename my<metagram::config()>::rule start;
typename my<void()>::rule commentline;
typename my<metagram::assignment()>::rule optionline;
typename my<metagram::section()>::rule section;
typename my<metagram::sectionname()>::rule headerline;
typename my<metagram::sectionname()>::rule sectionname;
typename my<metagram::optname()>::rule optname;
typename my<metagram::optval()>::rule optval;
typename my<metagram::qstring()>::rule qstring;
typename my<metagram::bareword()>::rule bareword;
typename my<void()>::rule comment;
};
template<class Iter>
optional<metagram::config>
parse(Iter & first, Iter last, std::ostream & erros) // {{{
{
grammar<Iter> g(erros);
metagram::config cfg;
optional<metagram::config> rv;
bool ok = qi::parse(
first
, last
, g
, cfg
);
if (ok && first == last)
rv = cfg;
return rv;
} // }}}
} // namespace iniphile
#endif
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#ifndef _Stroika_Foundation_Containers_Private_PatchingDataStructures_PatchableContainerHelper_inl_
#define _Stroika_Foundation_Containers_Private_PatchingDataStructures_PatchableContainerHelper_inl_ 1
#include "../../../Debug/Assertions.h"
namespace Stroika {
namespace Foundation {
namespace Containers {
namespace Private {
namespace PatchingDataStructures {
/*
********************************************************************************
********* PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS> ***********
********************************************************************************
*/
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableContainerHelper (PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>* rhs, IteratorOwnerID newOwnerID)
: inherited (*rhs)
, fActiveIteratorsListHead (nullptr)
{
Require (not HasActiveIterators ());
Again:
for (auto v = rhs->fActiveIteratorsListHead; v != nullptr; v = v->fNextActiveIterator) {
if (v->fOwnerID == newOwnerID) {
// must move it
rhs->RemoveIterator (v);
this->AddIterator (v);
goto Again;
}
}
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::~PatchableContainerHelper ()
{
Require (not HasActiveIterators ()); // cannot destroy container with active iterators
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
template <typename ACTUAL_ITERATOR_TYPE>
inline ACTUAL_ITERATOR_TYPE* PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::GetFirstActiveIterator () const
{
return static_cast<ACTUAL_ITERATOR_TYPE*> (fActiveIteratorsListHead);
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline void PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::AssertNoIteratorsReferenceOwner (IteratorOwnerID oBeingDeleted)
{
#if qDebug
AssertNoIteratorsReferenceOwner_ (oBeingDeleted);
#endif
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline bool PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::HasActiveIterators () const
{
return bool (fActiveIteratorsListHead != nullptr);
}
#if qDebug
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
void PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::AssertNoIteratorsReferenceOwner_ (IteratorOwnerID oBeingDeleted)
{
for (auto v = fActiveIteratorsListHead; v != nullptr; v = v->fNextActiveIterator) {
Assert (v->fOwnerID != oBeingDeleted);
}
}
#endif
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline void PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::AddIterator (PatchableIteratorMinIn* pi)
{
RequireNotNull (pi);
Assert (pi->fNextActiveIterator == nullptr);
pi->fNextActiveIterator = fActiveIteratorsListHead;
fActiveIteratorsListHead = pi;
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline void PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::RemoveIterator (PatchableIteratorMinIn* pi)
{
RequireNotNull (pi);
if (fActiveIteratorsListHead == pi) {
fActiveIteratorsListHead = pi->fNextActiveIterator;
}
else {
PatchableIteratorMinIn* v = fActiveIteratorsListHead;
for (; v->fNextActiveIterator != pi; v = v->fNextActiveIterator) {
AssertNotNull (v);
AssertNotNull (v->fNextActiveIterator);
}
AssertNotNull (v);
Assert (v->fNextActiveIterator == pi);
v->fNextActiveIterator = pi->fNextActiveIterator;
}
pi->fNextActiveIterator = nullptr; // unlink
}
/*
********************************************************************************
* PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableIteratorMinIn *
********************************************************************************
*/
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
template <typename ACTUAL_ITERATOR_TYPE>
inline ACTUAL_ITERATOR_TYPE* PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableIteratorMinIn::GetNextActiveIterator () const
{
return static_cast<ACTUAL_ITERATOR_TYPE*> (fNextActiveIterator);
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline IteratorOwnerID PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableIteratorMinIn::GetOwner () const
{
return fOwnerID;
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableIteratorMinIn::PatchableIteratorMinIn (PatchableContainerHelper* containerHelper, IteratorOwnerID ownerID)
: fPatchableContainer (containerHelper)
, fOwnerID (ownerID)
, fNextActiveIterator (containerHelper->fActiveIteratorsListHead)
{
RequireNotNull (containerHelper);
containerHelper->fActiveIteratorsListHead = this;
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableIteratorMinIn::PatchableIteratorMinIn (const PatchableIteratorMinIn& from)
: fPatchableContainer (from.fPatchableContainer)
, fOwnerID (from.fOwnerID)
, fNextActiveIterator (from.fPatchableContainer->fActiveIteratorsListHead)
{
RequireNotNull (fPatchableContainer);
fPatchableContainer->fActiveIteratorsListHead = this;
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableIteratorMinIn::~PatchableIteratorMinIn ()
{
AssertNotNull (fPatchableContainer);
fPatchableContainer->RemoveIterator (this);
}
}
}
}
}
}
#endif /* _Stroika_Foundation_Containers_Private_PatchingDataStructures_PatchableContainerHelper_inl_ */
<commit_msg>Assertions and disable new movement of iterators feature in PatchableContainerHelper.inl to stablize recent changes and amke sure no regressions except that<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#ifndef _Stroika_Foundation_Containers_Private_PatchingDataStructures_PatchableContainerHelper_inl_
#define _Stroika_Foundation_Containers_Private_PatchingDataStructures_PatchableContainerHelper_inl_ 1
#include "../../../Debug/Assertions.h"
namespace Stroika {
namespace Foundation {
namespace Containers {
namespace Private {
namespace PatchingDataStructures {
/*
********************************************************************************
********* PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS> ***********
********************************************************************************
*/
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableContainerHelper (PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>* rhs, IteratorOwnerID newOwnerID)
: inherited (*rhs)
, fActiveIteratorsListHead (nullptr)
{
Require (not HasActiveIterators ());
#if 0
// See if this is buggy...
Again:
for (auto v = rhs->fActiveIteratorsListHead; v != nullptr; v = v->fNextActiveIterator) {
if (v->fOwnerID == newOwnerID) {
// must move it
rhs->RemoveIterator (v);
this->AddIterator (v);
goto Again;
}
}
#endif
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::~PatchableContainerHelper ()
{
Require (not HasActiveIterators ()); // cannot destroy container with active iterators
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
template <typename ACTUAL_ITERATOR_TYPE>
inline ACTUAL_ITERATOR_TYPE* PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::GetFirstActiveIterator () const
{
return static_cast<ACTUAL_ITERATOR_TYPE*> (fActiveIteratorsListHead);
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline void PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::AssertNoIteratorsReferenceOwner (IteratorOwnerID oBeingDeleted)
{
#if qDebug
AssertNoIteratorsReferenceOwner_ (oBeingDeleted);
#endif
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline bool PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::HasActiveIterators () const
{
return bool (fActiveIteratorsListHead != nullptr);
}
#if qDebug
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
void PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::AssertNoIteratorsReferenceOwner_ (IteratorOwnerID oBeingDeleted)
{
for (auto v = fActiveIteratorsListHead; v != nullptr; v = v->fNextActiveIterator) {
Assert (v->fOwnerID != oBeingDeleted);
}
}
#endif
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline void PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::AddIterator (PatchableIteratorMinIn* pi)
{
RequireNotNull (pi);
Assert (pi->fNextActiveIterator == nullptr);
pi->fNextActiveIterator = fActiveIteratorsListHead;
fActiveIteratorsListHead = pi;
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline void PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::RemoveIterator (PatchableIteratorMinIn* pi)
{
RequireNotNull (pi);
if (fActiveIteratorsListHead == pi) {
fActiveIteratorsListHead = pi->fNextActiveIterator;
}
else {
PatchableIteratorMinIn* v = fActiveIteratorsListHead;
for (; v->fNextActiveIterator != pi; v = v->fNextActiveIterator) {
AssertNotNull (v);
AssertNotNull (v->fNextActiveIterator);
}
AssertNotNull (v);
Assert (v->fNextActiveIterator == pi);
v->fNextActiveIterator = pi->fNextActiveIterator;
}
pi->fNextActiveIterator = nullptr; // unlink
}
/*
********************************************************************************
* PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableIteratorMinIn *
********************************************************************************
*/
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
template <typename ACTUAL_ITERATOR_TYPE>
inline ACTUAL_ITERATOR_TYPE* PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableIteratorMinIn::GetNextActiveIterator () const
{
return static_cast<ACTUAL_ITERATOR_TYPE*> (fNextActiveIterator);
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline IteratorOwnerID PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableIteratorMinIn::GetOwner () const
{
return fOwnerID;
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableIteratorMinIn::PatchableIteratorMinIn (PatchableContainerHelper* containerHelper, IteratorOwnerID ownerID)
: fPatchableContainer (containerHelper)
, fOwnerID (ownerID)
, fNextActiveIterator (containerHelper->fActiveIteratorsListHead)
{
RequireNotNull (containerHelper);
containerHelper->fActiveIteratorsListHead = this;
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableIteratorMinIn::PatchableIteratorMinIn (const PatchableIteratorMinIn& from)
: fPatchableContainer (from.fPatchableContainer)
, fOwnerID (from.fOwnerID)
, fNextActiveIterator (from.fPatchableContainer->fActiveIteratorsListHead)
{
RequireNotNull (fPatchableContainer);
fPatchableContainer->fActiveIteratorsListHead = this;
}
template <typename NON_PATCHED_DATA_STRUCTURE_CLASS>
inline PatchableContainerHelper<NON_PATCHED_DATA_STRUCTURE_CLASS>::PatchableIteratorMinIn::~PatchableIteratorMinIn ()
{
AssertNotNull (fPatchableContainer);
fPatchableContainer->RemoveIterator (this);
Assert (fNextActiveIterator == nullptr);
// could assert owner - fPatchableContainer - doenst contian us in list
}
}
}
}
}
}
#endif /* _Stroika_Foundation_Containers_Private_PatchingDataStructures_PatchableContainerHelper_inl_ */
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/policy.hpp"
#include "libtorrent/hasher.hpp"
#include "test.hpp"
using namespace libtorrent;
boost::uint32_t hash_buffer(char const* buf, int len)
{
hasher h;
h.update(buf, len);
sha1_hash digest = h.final();
boost::uint32_t ret;
memcpy(&ret, &digest[0], 4);
return ntohl(ret);
}
int test_main()
{
// when the IP is the same, we hash the ports, sorted
boost::uint32_t p = peer_priority(
tcp::endpoint(address::from_string("230.12.123.3"), 0x4d2)
, tcp::endpoint(address::from_string("230.12.123.3"), 0x12c));
TEST_EQUAL(p, hash_buffer("\x01\x2c\x04\xd2", 4));
// when we're in the same /24, we just hash the IPs
p = peer_priority(
tcp::endpoint(address::from_string("230.12.123.1"), 0x4d2)
, tcp::endpoint(address::from_string("230.12.123.3"), 0x12c));
TEST_EQUAL(p, hash_buffer("\xe6\x0c\x7b\x01\xe6\x0c\x7b\x03", 8));
// when we're in the same /16, we just hash the IPs masked by
// 0xffffff55
p = peer_priority(
tcp::endpoint(address::from_string("230.12.23.1"), 0x4d2)
, tcp::endpoint(address::from_string("230.12.123.3"), 0x12c));
TEST_EQUAL(p, hash_buffer("\xe6\x0c\x17\x01\xe6\x0c\x7b\x01", 8));
// when we're in different /16, we just hash the IPs masked by
// 0xffff5555
p = peer_priority(
tcp::endpoint(address::from_string("230.120.23.1"), 0x4d2)
, tcp::endpoint(address::from_string("230.12.123.3"), 0x12c));
TEST_EQUAL(p, hash_buffer("\xe6\x0c\x51\x01\xe6\x78\x15\x01", 8));
// IPv6 has a twice as wide mask, and we only care about the top 64 bits
// when the IPs are the same, just hash the ports
p = peer_priority(
tcp::endpoint(address::from_string("ffff:ffff:ffff:ffff::1"), 0x4d2)
, tcp::endpoint(address::from_string("ffff:ffff:ffff:ffff::1"), 0x12c));
TEST_EQUAL(p, hash_buffer("\x01\x2c\x04\xd2", 4));
// these IPs don't belong to the same /32, so apply the full mask
// 0xffffffff55555555
p = peer_priority(
tcp::endpoint(address::from_string("ffff:ffff:ffff:ffff::1"), 0x4d2)
, tcp::endpoint(address::from_string("ffff:0fff:ffff:ffff::1"), 0x12c));
TEST_EQUAL(p, hash_buffer(
"\xff\xff\x0f\xff\x55\x55\x55\x55\x00\x00\x00\x00\x00\x00\x00\x01"
"\xff\xff\xff\xff\x55\x55\x55\x55\x00\x00\x00\x00\x00\x00\x00\x01", 32));
return 0;
}
<commit_msg>fix test support for platforms not supporting IPv6<commit_after>/*
Copyright (c) 2012, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/policy.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/broadcast_socket.hpp" // for supports_ipv6()
#include "test.hpp"
using namespace libtorrent;
boost::uint32_t hash_buffer(char const* buf, int len)
{
hasher h;
h.update(buf, len);
sha1_hash digest = h.final();
boost::uint32_t ret;
memcpy(&ret, &digest[0], 4);
return ntohl(ret);
}
int test_main()
{
// when the IP is the same, we hash the ports, sorted
boost::uint32_t p = peer_priority(
tcp::endpoint(address::from_string("230.12.123.3"), 0x4d2)
, tcp::endpoint(address::from_string("230.12.123.3"), 0x12c));
TEST_EQUAL(p, hash_buffer("\x01\x2c\x04\xd2", 4));
// when we're in the same /24, we just hash the IPs
p = peer_priority(
tcp::endpoint(address::from_string("230.12.123.1"), 0x4d2)
, tcp::endpoint(address::from_string("230.12.123.3"), 0x12c));
TEST_EQUAL(p, hash_buffer("\xe6\x0c\x7b\x01\xe6\x0c\x7b\x03", 8));
// when we're in the same /16, we just hash the IPs masked by
// 0xffffff55
p = peer_priority(
tcp::endpoint(address::from_string("230.12.23.1"), 0x4d2)
, tcp::endpoint(address::from_string("230.12.123.3"), 0x12c));
TEST_EQUAL(p, hash_buffer("\xe6\x0c\x17\x01\xe6\x0c\x7b\x01", 8));
// when we're in different /16, we just hash the IPs masked by
// 0xffff5555
p = peer_priority(
tcp::endpoint(address::from_string("230.120.23.1"), 0x4d2)
, tcp::endpoint(address::from_string("230.12.123.3"), 0x12c));
TEST_EQUAL(p, hash_buffer("\xe6\x0c\x51\x01\xe6\x78\x15\x01", 8));
if (supports_ipv6())
{
// IPv6 has a twice as wide mask, and we only care about the top 64 bits
// when the IPs are the same, just hash the ports
p = peer_priority(
tcp::endpoint(address::from_string("ffff:ffff:ffff:ffff::1"), 0x4d2)
, tcp::endpoint(address::from_string("ffff:ffff:ffff:ffff::1"), 0x12c));
TEST_EQUAL(p, hash_buffer("\x01\x2c\x04\xd2", 4));
// these IPs don't belong to the same /32, so apply the full mask
// 0xffffffff55555555
p = peer_priority(
tcp::endpoint(address::from_string("ffff:ffff:ffff:ffff::1"), 0x4d2)
, tcp::endpoint(address::from_string("ffff:0fff:ffff:ffff::1"), 0x12c));
TEST_EQUAL(p, hash_buffer(
"\xff\xff\x0f\xff\x55\x55\x55\x55\x00\x00\x00\x00\x00\x00\x00\x01"
"\xff\xff\xff\xff\x55\x55\x55\x55\x00\x00\x00\x00\x00\x00\x00\x01", 32));
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/web_notification/ash_popup_alignment_delegate.h"
#include "ash/display/display_controller.h"
#include "ash/shelf/shelf_constants.h"
#include "ash/shelf/shelf_layout_manager.h"
#include "ash/shelf/shelf_types.h"
#include "ash/shelf/shelf_widget.h"
#include "ash/shell.h"
#include "base/i18n/rtl.h"
#include "ui/aura/window.h"
#include "ui/gfx/display.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/screen.h"
#include "ui/message_center/message_center_style.h"
#include "ui/message_center/views/message_popup_collection.h"
namespace ash {
namespace {
const int kToastMarginX = 3;
// If there should be no margin for the first item, this value needs to be
// substracted to flush the message to the shelf (the width of the border +
// shadow).
const int kNoToastMarginBorderAndShadowOffset = 2;
}
AshPopupAlignmentDelegate::AshPopupAlignmentDelegate()
: display_id_(gfx::Display::kInvalidDisplayID),
screen_(NULL),
root_window_(NULL),
shelf_(NULL),
system_tray_height_(0) {
}
AshPopupAlignmentDelegate::~AshPopupAlignmentDelegate() {
if (screen_)
screen_->RemoveObserver(this);
Shell::GetInstance()->RemoveShellObserver(this);
if (shelf_)
shelf_->RemoveObserver(this);
}
void AshPopupAlignmentDelegate::StartObserving(gfx::Screen* screen,
const gfx::Display& display) {
screen_ = screen;
display_id_ = display.id();
root_window_ = ash::Shell::GetInstance()->display_controller()->
GetRootWindowForDisplayId(display_id_);
UpdateShelf();
screen->AddObserver(this);
Shell::GetInstance()->AddShellObserver(this);
if (system_tray_height_ > 0)
OnAutoHideStateChanged(shelf_->auto_hide_state());
}
void AshPopupAlignmentDelegate::SetSystemTrayHeight(int height) {
system_tray_height_ = height;
// If the shelf is shown during auto-hide state, the distance from the edge
// should be reduced by the height of shelf's shown height.
if (shelf_ && shelf_->visibility_state() == SHELF_AUTO_HIDE &&
shelf_->auto_hide_state() == SHELF_AUTO_HIDE_SHOWN) {
system_tray_height_ -= kShelfSize - ShelfLayoutManager::kAutoHideSize;
}
if (system_tray_height_ > 0)
system_tray_height_ += message_center::kMarginBetweenItems;
else
system_tray_height_ = 0;
if (!shelf_)
return;
DoUpdateIfPossible();
}
int AshPopupAlignmentDelegate::GetToastOriginX(
const gfx::Rect& toast_bounds) const {
// In Ash, RTL UI language mirrors the whole ash layout, so the toast
// widgets should be at the bottom-left instead of bottom right.
if (base::i18n::IsRTL())
return work_area_.x() + kToastMarginX;
if (IsFromLeft())
return work_area_.x() + kToastMarginX;
return work_area_.right() - kToastMarginX - toast_bounds.width();
}
int AshPopupAlignmentDelegate::GetBaseLine() const {
return IsTopDown()
? work_area_.y() + kNoToastMarginBorderAndShadowOffset +
system_tray_height_
: work_area_.bottom() - kNoToastMarginBorderAndShadowOffset -
system_tray_height_;
}
int AshPopupAlignmentDelegate::GetWorkAreaBottom() const {
return work_area_.bottom() - system_tray_height_;
}
bool AshPopupAlignmentDelegate::IsTopDown() const {
return GetAlignment() == SHELF_ALIGNMENT_TOP;
}
bool AshPopupAlignmentDelegate::IsFromLeft() const {
return GetAlignment() == SHELF_ALIGNMENT_LEFT;
}
void AshPopupAlignmentDelegate::RecomputeAlignment(
const gfx::Display& display) {
// Nothing needs to be done.
}
ShelfAlignment AshPopupAlignmentDelegate::GetAlignment() const {
return shelf_ ? shelf_->GetAlignment() : SHELF_ALIGNMENT_BOTTOM;
}
void AshPopupAlignmentDelegate::UpdateShelf() {
if (shelf_)
return;
shelf_ = ShelfLayoutManager::ForShelf(root_window_);
if (shelf_)
shelf_->AddObserver(this);
}
void AshPopupAlignmentDelegate::OnDisplayWorkAreaInsetsChanged() {
UpdateShelf();
work_area_ = Shell::GetScreen()->GetDisplayNearestWindow(
shelf_->shelf_widget()->GetNativeView()).work_area();
}
void AshPopupAlignmentDelegate::OnAutoHideStateChanged(
ShelfAutoHideState new_state) {
work_area_ = Shell::GetScreen()->GetDisplayNearestWindow(
shelf_->shelf_widget()->GetNativeView()).work_area();
int width = 0;
if ((shelf_->visibility_state() == SHELF_AUTO_HIDE) &&
new_state == SHELF_AUTO_HIDE_SHOWN) {
// Since the work_area is already reduced by kAutoHideSize, the inset width
// should be just the difference.
width = kShelfSize - ShelfLayoutManager::kAutoHideSize;
}
work_area_.Inset(shelf_->SelectValueForShelfAlignment(
gfx::Insets(0, 0, width, 0),
gfx::Insets(0, width, 0, 0),
gfx::Insets(0, 0, 0, width),
gfx::Insets(width, 0, 0, 0)));
DoUpdateIfPossible();
}
void AshPopupAlignmentDelegate::OnDisplayAdded(
const gfx::Display& new_display) {
}
void AshPopupAlignmentDelegate::OnDisplayRemoved(
const gfx::Display& old_display) {
}
void AshPopupAlignmentDelegate::OnDisplayMetricsChanged(
const gfx::Display& display,
uint32_t metrics) {
if (display.id() == display_id_ && shelf_)
OnAutoHideStateChanged(shelf_->auto_hide_state());
}
} // namespace ash
<commit_msg>Reset the default work_area when start observing.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/web_notification/ash_popup_alignment_delegate.h"
#include "ash/display/display_controller.h"
#include "ash/shelf/shelf_constants.h"
#include "ash/shelf/shelf_layout_manager.h"
#include "ash/shelf/shelf_types.h"
#include "ash/shelf/shelf_widget.h"
#include "ash/shell.h"
#include "base/i18n/rtl.h"
#include "ui/aura/window.h"
#include "ui/gfx/display.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/screen.h"
#include "ui/message_center/message_center_style.h"
#include "ui/message_center/views/message_popup_collection.h"
namespace ash {
namespace {
const int kToastMarginX = 3;
// If there should be no margin for the first item, this value needs to be
// substracted to flush the message to the shelf (the width of the border +
// shadow).
const int kNoToastMarginBorderAndShadowOffset = 2;
}
AshPopupAlignmentDelegate::AshPopupAlignmentDelegate()
: display_id_(gfx::Display::kInvalidDisplayID),
screen_(NULL),
root_window_(NULL),
shelf_(NULL),
system_tray_height_(0) {
}
AshPopupAlignmentDelegate::~AshPopupAlignmentDelegate() {
if (screen_)
screen_->RemoveObserver(this);
Shell::GetInstance()->RemoveShellObserver(this);
if (shelf_)
shelf_->RemoveObserver(this);
}
void AshPopupAlignmentDelegate::StartObserving(gfx::Screen* screen,
const gfx::Display& display) {
screen_ = screen;
display_id_ = display.id();
work_area_ = display.work_area();
root_window_ = ash::Shell::GetInstance()->display_controller()->
GetRootWindowForDisplayId(display_id_);
UpdateShelf();
screen->AddObserver(this);
Shell::GetInstance()->AddShellObserver(this);
if (system_tray_height_ > 0)
OnAutoHideStateChanged(shelf_->auto_hide_state());
}
void AshPopupAlignmentDelegate::SetSystemTrayHeight(int height) {
system_tray_height_ = height;
// If the shelf is shown during auto-hide state, the distance from the edge
// should be reduced by the height of shelf's shown height.
if (shelf_ && shelf_->visibility_state() == SHELF_AUTO_HIDE &&
shelf_->auto_hide_state() == SHELF_AUTO_HIDE_SHOWN) {
system_tray_height_ -= kShelfSize - ShelfLayoutManager::kAutoHideSize;
}
if (system_tray_height_ > 0)
system_tray_height_ += message_center::kMarginBetweenItems;
else
system_tray_height_ = 0;
if (!shelf_)
return;
DoUpdateIfPossible();
}
int AshPopupAlignmentDelegate::GetToastOriginX(
const gfx::Rect& toast_bounds) const {
// In Ash, RTL UI language mirrors the whole ash layout, so the toast
// widgets should be at the bottom-left instead of bottom right.
if (base::i18n::IsRTL())
return work_area_.x() + kToastMarginX;
if (IsFromLeft())
return work_area_.x() + kToastMarginX;
return work_area_.right() - kToastMarginX - toast_bounds.width();
}
int AshPopupAlignmentDelegate::GetBaseLine() const {
return IsTopDown()
? work_area_.y() + kNoToastMarginBorderAndShadowOffset +
system_tray_height_
: work_area_.bottom() - kNoToastMarginBorderAndShadowOffset -
system_tray_height_;
}
int AshPopupAlignmentDelegate::GetWorkAreaBottom() const {
return work_area_.bottom() - system_tray_height_;
}
bool AshPopupAlignmentDelegate::IsTopDown() const {
return GetAlignment() == SHELF_ALIGNMENT_TOP;
}
bool AshPopupAlignmentDelegate::IsFromLeft() const {
return GetAlignment() == SHELF_ALIGNMENT_LEFT;
}
void AshPopupAlignmentDelegate::RecomputeAlignment(
const gfx::Display& display) {
// Nothing needs to be done.
}
ShelfAlignment AshPopupAlignmentDelegate::GetAlignment() const {
return shelf_ ? shelf_->GetAlignment() : SHELF_ALIGNMENT_BOTTOM;
}
void AshPopupAlignmentDelegate::UpdateShelf() {
if (shelf_)
return;
shelf_ = ShelfLayoutManager::ForShelf(root_window_);
if (shelf_)
shelf_->AddObserver(this);
}
void AshPopupAlignmentDelegate::OnDisplayWorkAreaInsetsChanged() {
UpdateShelf();
work_area_ = Shell::GetScreen()->GetDisplayNearestWindow(
shelf_->shelf_widget()->GetNativeView()).work_area();
}
void AshPopupAlignmentDelegate::OnAutoHideStateChanged(
ShelfAutoHideState new_state) {
work_area_ = Shell::GetScreen()->GetDisplayNearestWindow(
shelf_->shelf_widget()->GetNativeView()).work_area();
int width = 0;
if ((shelf_->visibility_state() == SHELF_AUTO_HIDE) &&
new_state == SHELF_AUTO_HIDE_SHOWN) {
// Since the work_area is already reduced by kAutoHideSize, the inset width
// should be just the difference.
width = kShelfSize - ShelfLayoutManager::kAutoHideSize;
}
work_area_.Inset(shelf_->SelectValueForShelfAlignment(
gfx::Insets(0, 0, width, 0),
gfx::Insets(0, width, 0, 0),
gfx::Insets(0, 0, 0, width),
gfx::Insets(width, 0, 0, 0)));
DoUpdateIfPossible();
}
void AshPopupAlignmentDelegate::OnDisplayAdded(
const gfx::Display& new_display) {
}
void AshPopupAlignmentDelegate::OnDisplayRemoved(
const gfx::Display& old_display) {
}
void AshPopupAlignmentDelegate::OnDisplayMetricsChanged(
const gfx::Display& display,
uint32_t metrics) {
if (display.id() == display_id_ && shelf_)
OnAutoHideStateChanged(shelf_->auto_hide_state());
}
} // namespace ash
<|endoftext|> |
<commit_before>// https://oj.leetcode.com/problems/maximum-subarray/
namespace MaximumSubarray {
class Solution {
public:
int maxSubArray(int A[], int n) {
int sum = 0;
int max = INT_MIN;
for (int i = 0; i < n; i++) {
if (sum < 0) {
sum = A[i];
} else {
sum += A[i];
}
if (sum > max) {
max = sum;
}
}
return max;
}
};
}
<commit_msg>Update MaximumSubarray.cc<commit_after>// https://oj.leetcode.com/problems/maximum-subarray/
namespace MaximumSubarray {
// O(n) solution
class Solution {
public:
int maxSubArray(int A[], int n) {
int sum = 0;
int max = INT_MIN;
for (int i = 0; i < n; i++) {
if (sum < 0) {
sum = A[i];
} else {
sum += A[i];
}
if (sum > max) {
max = sum;
}
}
return max;
}
};
// Divide & Conquer Solution, O(nLog(n))
class Solution1 {
public:
int maxCrossSubArray(int A[], int left, int mid, int right) {
int maxLeftSum = INT_MIN;
int maxRightSum = INT_MIN;
// calc left sum
int sum = 0;
for (int i = mid; i >= left; i--) {
sum += A[i];
if (sum > maxLeftSum) {
maxLeftSum = sum;
}
}
// calc right sum
sum = 0;
for (int i = mid + 1; i <= right; i++) {
sum += A[i];
if (sum > maxRightSum) {
maxRightSum = sum;
}
}
return maxLeftSum + maxRightSum;
}
int maxOneSideSubArray(int A[], int left, int right) {
if (left == right) {
return A[left];
}
int mid = (left + right) / 2;
return max(maxCrossSubArray(A, left, mid, right),
max(maxOneSideSubArray(A, left, mid), maxOneSideSubArray(A, mid + 1, right)));
}
int maxSubArray(int A[], int n) {
if (n == 0) {
return 0;
}
return maxOneSideSubArray(A, 0, n - 1);
}
};
}
<|endoftext|> |
<commit_before>//=============================================================================================================
/**
* @file test_fiff_anonymize.cpp
* @author Lorenz Esch <[email protected]>;
* @version 1.0
* @date September, 2019
*
* @section LICENSE
*
* Copyright (C) 2019, Lorenz Esch. 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 MNE-CPP 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 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.
*
*
* @brief Test for anonymizing a fiff raw file
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <fiff/fiff.h>
#include <iostream>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtTest>
#include <QProcess>
#include <QScopedPointer>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace FIFFLIB;
//=============================================================================================================
/**
* DECLARE CLASS TestFiffAnonyimze
*
* @brief The TestFiffAnonyimze class provides fiff anonymizing verification tests
*
*/
class TestFiffAnonyimze: public QObject
{
Q_OBJECT
public:
TestFiffAnonyimze();
private slots:
void initTestCase();
void compareData();
void cleanupTestCase();
private:
double epsilon;
MatrixXd second_in_times;
};
//*************************************************************************************************************
TestFiffAnonyimze::TestFiffAnonyimze()
: epsilon(0.000001)
{
}
//*************************************************************************************************************
void TestFiffAnonyimze::initTestCase()
{
qInfo() << "TestFiffAnonyimze::initTestCase - Epsilon" << epsilon;
// Init testing arguments
QString sFileIn("/mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif");
QString sFileOut("/mne-cpp-test-data/MEG/sample/sample_audvis_raw_short_anonymized.fif");
qInfo() << "TestFiffAnonyimze::initTestCase - sFileIn" << sFileIn;
qInfo() << "TestFiffAnonyimze::initTestCase - sFileOut" << sFileOut;
QString program = "./mne_anonymize";
QStringList arguments;
arguments << "--in" << sFileIn;
arguments << "--out" << sFileOut;
// Pass arguments to application and anaonyimze the fiff file
QScopedPointer<QProcess> myProcess (new QProcess);
myProcess->start(program, arguments);
myProcess->waitForFinished();
}
//*************************************************************************************************************
void TestFiffAnonyimze::compareData()
{
// Open ./mne-cpp-test-data/MEG/sample/sample_audvis_raw_anonymized.fif
// ToDo: Implement function which reads sensitive tags and checks if they were anaonymized. Use Q_VERIFY().
}
//*************************************************************************************************************
void TestFiffAnonyimze::cleanupTestCase()
{
}
//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================
QTEST_APPLESS_MAIN(TestFiffAnonyimze)
#include "test_fiff_anonymize.moc"
<commit_msg>Rename TestFiffAnonymize and remove second_in_times<commit_after>//=============================================================================================================
/**
* @file test_fiff_anonymize.cpp
* @author Lorenz Esch <[email protected]>;
* @version 1.0
* @date September, 2019
*
* @section LICENSE
*
* Copyright (C) 2019, Lorenz Esch. 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 MNE-CPP 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 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.
*
*
* @brief Test for anonymizing a fiff raw file
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include <fiff/fiff.h>
#include <iostream>
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtTest>
#include <QProcess>
#include <QScopedPointer>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace FIFFLIB;
//=============================================================================================================
/**
* DECLARE CLASS TestFiffAnonymize
*
* @brief The TestFiffAnonymize class provides fiff anonymizing verification tests
*
*/
class TestFiffAnonymize: public QObject
{
Q_OBJECT
public:
TestFiffAnonymize();
private slots:
void initTestCase();
void compareData();
void cleanupTestCase();
private:
double epsilon;
};
//*************************************************************************************************************
TestFiffAnonymize::TestFiffAnonymize()
: epsilon(0.000001)
{
}
//*************************************************************************************************************
void TestFiffAnonymize::initTestCase()
{
qInfo() << "TestFiffAnonymize::initTestCase - Epsilon" << epsilon;
// Init testing arguments
QString sFileIn("/mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif");
QString sFileOut("/mne-cpp-test-data/MEG/sample/sample_audvis_raw_short_anonymized.fif");
qInfo() << "TestFiffAnonymize::initTestCase - sFileIn" << sFileIn;
qInfo() << "TestFiffAnonymize::initTestCase - sFileOut" << sFileOut;
QString program = "./mne_anonymize";
QStringList arguments;
arguments << "--in" << sFileIn;
arguments << "--out" << sFileOut;
// Pass arguments to application and anaonyimze the fiff file
QScopedPointer<QProcess> myProcess (new QProcess);
myProcess->start(program, arguments);
myProcess->waitForFinished();
}
//*************************************************************************************************************
void TestFiffAnonymize::compareData()
{
// Open ./mne-cpp-test-data/MEG/sample/sample_audvis_raw_anonymized.fif
// ToDo: Implement function which reads sensitive tags and checks if they were anaonymized. Use Q_VERIFY().
}
//*************************************************************************************************************
void TestFiffAnonymize::cleanupTestCase()
{
}
//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================
QTEST_APPLESS_MAIN(TestFiffAnonymize)
#include "test_fiff_anonymize.moc"
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_ASSEMBLER_SYSTEM_HH
#define DUNE_GDT_ASSEMBLER_SYSTEM_HH
#include <type_traits>
//#include <vector>
#include <memory>
#include <dune/common/dynmatrix.hh>
#include <dune/common/dynvector.hh>
//#include <dune/common/static_assert.hh>
//#include <dune/common/typetraits.hh>
//#include <dune/stuff/la/container/interfaces.hh>
//#include <dune/stuff/la/container/pattern.hh>
//#ifdef DUNE_STUFF_PROFILER_ENABLED
//# include <dune/stuff/common/profiler.hh>
//#endif
#include <dune/gdt/space/interface.hh>
#include <dune/gdt/space/constraints.hh>
#include "local/codim0.hh"
#include "local/codim1.hh"
#include "gridwalker.hh"
namespace Dune {
namespace GDT {
template< class TestSpaceImp,
class GridViewImp = typename TestSpaceImp::GridViewType,
class AnsatzSpaceImp = TestSpaceImp >
class SystemAssembler
: public GridWalker< GridViewImp >
{
static_assert(std::is_base_of< SpaceInterface< typename TestSpaceImp::Traits >, TestSpaceImp >::value,
"TestSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of< SpaceInterface< typename AnsatzSpaceImp::Traits >, AnsatzSpaceImp >::value,
"AnsatzSpaceImp has to be derived from SpaceInterface!");
typedef GridWalker< GridViewImp > BaseType;
public:
typedef TestSpaceImp TestSpaceType;
typedef AnsatzSpaceImp AnsatzSpaceType;
typedef typename BaseType::GridViewType GridViewType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::IntersectionType IntersectionType;
typedef typename BaseType::BoundaryInfoType BoundaryInfoType;
private:
typedef typename TestSpaceType::RangeFieldType RangeFieldType;
typedef Dune::DynamicMatrix< RangeFieldType > LocalMatrixType;
typedef Dune::DynamicVector< RangeFieldType > LocalVectorType;
public:
SystemAssembler(const TestSpaceType& test, const AnsatzSpaceType& ansatz, const GridViewType& grid_view)
: BaseType(grid_view)
, test_space_(test)
, ansatz_space_(ansatz)
{}
SystemAssembler(const TestSpaceType& test, const AnsatzSpaceType& ansatz)
: BaseType(*(test.grid_view()))
, test_space_(test)
, ansatz_space_(ansatz)
{}
SystemAssembler(const TestSpaceType& test)
: BaseType(*(test.grid_view()))
, test_space_(test)
, ansatz_space_(test_space_)
{}
SystemAssembler(const TestSpaceType& test, const GridViewType& grid_view)
: BaseType(grid_view)
, test_space_(test)
, ansatz_space_(test_space_)
{}
const TestSpaceType& test_space() const
{
return test_space_;
}
const AnsatzSpaceType& ansatz_space() const
{
return ansatz_space_;
}
using BaseType::add;
private:
template< class ConstraintsType, class MatrixType >
class LocalMatrixConstraintsWrapper
: public BaseType::Codim0Object
{
public:
LocalMatrixConstraintsWrapper(const TestSpaceType& t_space,
const AnsatzSpaceType& a_space,
const ApplyOn::WhichEntity< GridViewType >* where,
ConstraintsType& constraints,
MatrixType& matrix)
: t_space_(t_space)
, a_space_(a_space)
, where_(where)
, constraints_(constraints)
, matrix_(matrix)
{}
virtual ~LocalMatrixConstraintsWrapper() {}
virtual bool apply_on(const GridViewType& gv, const EntityType& entity) const DS_FINAL
{
return where_->apply_on(gv, entity);
}
virtual void apply_local(const EntityType& entity) DS_FINAL
{
t_space_.local_constraints(a_space_, entity, constraints_);
for (size_t ii = 0; ii < constraints_.rows(); ++ii) {
const size_t row = constraints_.globalRow(ii);
for (size_t jj = 0; jj < constraints_.cols(); ++jj) {
matrix_.set_entry(row, constraints_.globalCol(jj), constraints_.value(ii, jj));
}
}
} // ... apply_local(...)
private:
const TestSpaceType& t_space_;
const AnsatzSpaceType& a_space_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
ConstraintsType& constraints_;
MatrixType& matrix_;
}; // class LocalMatrixConstraintsWrapper
template< class ConstraintsType, class VectorType >
class LocalVectorConstraintsWrapper
: public BaseType::Codim0Object
{
public:
LocalVectorConstraintsWrapper(const TestSpaceType& t_space,
const ApplyOn::WhichEntity< GridViewType >* where,
ConstraintsType& constraints,
VectorType& vector)
: t_space_(t_space)
, where_(where)
, constraints_(constraints)
, vector_(vector)
{}
virtual ~LocalVectorConstraintsWrapper() {}
virtual bool apply_on(const GridViewType& gv, const EntityType& entity) const DS_FINAL
{
return where_->apply_on(gv, entity);
}
virtual void apply_local(const EntityType& entity) DS_FINAL
{
t_space_.local_constraints(entity, constraints_);
for (size_t ii = 0; ii < constraints_.rows(); ++ii) {
vector_.set_entry(constraints_.globalRow(ii), RangeFieldType(0));
}
}
private:
const TestSpaceType& t_space_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
ConstraintsType& constraints_;
VectorType& vector_;
}; // class LocalVectorConstraintsWrapper
class NeedsTmpMatrixStorage
{
public:
static size_t safely_get(const std::vector< size_t >& vec, const size_t ii)
{
assert(ii < vec.size());
return vec[ii];
}
NeedsTmpMatrixStorage(const std::vector< size_t >& num_tmp_objects,
const size_t max_rows,
const size_t max_cols)
: matrices_({ std::vector< LocalMatrixType >(safely_get(num_tmp_objects, 0),
LocalMatrixType(max_rows, max_cols, RangeFieldType(0)))
, std::vector< LocalMatrixType >(safely_get(num_tmp_objects, 1),
LocalMatrixType(max_rows, max_cols, RangeFieldType(0))) })
, indices_(4, Dune::DynamicVector< size_t >(std::max(max_rows, max_cols)))
{}
virtual ~NeedsTmpMatrixStorage() {}
std::vector< std::vector< LocalMatrixType > >& matrices()
{
return matrices_;
}
std::vector< Dune::DynamicVector< size_t > >& indices()
{
return indices_;
}
protected:
std::vector< std::vector< LocalMatrixType > > matrices_;
std::vector< Dune::DynamicVector< size_t > > indices_;
}; // class NeedsTmpMatrixStorage
class NeedsTmpVectorStorage
{
public:
static size_t safely_get(const std::vector< size_t >& vec, const size_t ii)
{
assert(ii < vec.size());
return vec[ii];
}
NeedsTmpVectorStorage(const std::vector< size_t >& num_tmp_objects,
const size_t max_size)
: vectors_({ std::vector< LocalVectorType >(safely_get(num_tmp_objects, 0),
LocalVectorType(max_size, RangeFieldType(0)))
, std::vector< LocalVectorType >(safely_get(num_tmp_objects, 1),
LocalVectorType(max_size, RangeFieldType(0))) })
, indices_(max_size)
{}
virtual ~NeedsTmpVectorStorage() {}
std::vector< std::vector< LocalVectorType > >& vectors()
{
return vectors_;
}
Dune::DynamicVector< size_t >& indices()
{
return indices_;
}
protected:
std::vector< std::vector< LocalVectorType > > vectors_;
Dune::DynamicVector< size_t > indices_;
}; // class NeedsTmpVectorStorage
template< class LocalVolumeMatrixAssembler, class MatrixType >
class LocalVolumeMatrixAssemblerWrapper
: public BaseType::Codim0Object
, NeedsTmpMatrixStorage
{
public:
LocalVolumeMatrixAssemblerWrapper(const TestSpaceType& t_space,
const AnsatzSpaceType& a_space,
const ApplyOn::WhichEntity< GridViewType >* where,
const LocalVolumeMatrixAssembler& localAssembler,
MatrixType& matrix)
: NeedsTmpMatrixStorage(localAssembler.numTmpObjectsRequired(),
t_space.mapper().maxNumDofs(),
a_space.mapper().maxNumDofs())
, t_space_(t_space)
, a_space_(a_space)
, where_(where)
, localMatrixAssembler_(localAssembler)
, matrix_(matrix)
{}
virtual ~LocalVolumeMatrixAssemblerWrapper() {}
virtual bool apply_on(const GridViewType& gv, const EntityType& entity) const DS_FINAL
{
return where_->apply_on(gv, entity);
}
virtual void apply_local(const EntityType& entity) DS_FINAL
{
localMatrixAssembler_.assembleLocal(t_space_, a_space_, entity, matrix_, this->matrices(), this->indices());
}
private:
const TestSpaceType& t_space_;
const AnsatzSpaceType& a_space_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
const LocalVolumeMatrixAssembler& localMatrixAssembler_;
MatrixType& matrix_;
}; // class LocalVolumeMatrixAssemblerWrapper
template< class LocalVolumeVectorAssembler, class VectorType >
class LocalVolumeVectorAssemblerWrapper
: public BaseType::Codim0Object
, NeedsTmpVectorStorage
{
public:
LocalVolumeVectorAssemblerWrapper(const TestSpaceType& space,
const ApplyOn::WhichEntity< GridViewType >* where,
const LocalVolumeVectorAssembler& localAssembler,
VectorType& vector)
: NeedsTmpVectorStorage(localAssembler.numTmpObjectsRequired(), space.mapper().maxNumDofs())
, space_(space)
, where_(where)
, localVectorAssembler_(localAssembler)
, vector_(vector)
{}
virtual ~LocalVolumeVectorAssemblerWrapper() {}
virtual bool apply_on(const GridViewType& gv, const EntityType& entity) const DS_FINAL
{
return where_->apply_on(gv, entity);
}
virtual void apply_local(const EntityType& entity) DS_FINAL
{
localVectorAssembler_.assembleLocal(space_, entity, vector_, this->vectors(), this->indices());
}
private:
const TestSpaceType& space_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
const LocalVolumeVectorAssembler& localVectorAssembler_;
VectorType& vector_;
}; // class LocalVolumeVectorAssemblerWrapper
template< class LocalFaceVectorAssembler, class VectorType >
class LocalFaceVectorAssemblerWrapper
: public BaseType::Codim1Object
, NeedsTmpVectorStorage
{
public:
LocalFaceVectorAssemblerWrapper(const TestSpaceType& space,
const ApplyOn::WhichIntersection< GridViewType >* where,
const LocalFaceVectorAssembler& localAssembler,
VectorType& vector)
: NeedsTmpVectorStorage(localAssembler.numTmpObjectsRequired(), space.mapper().maxNumDofs())
, space_(space)
, where_(where)
, localVectorAssembler_(localAssembler)
, vector_(vector)
{}
virtual ~LocalFaceVectorAssemblerWrapper() {}
virtual bool apply_on(const GridViewType& gv, const IntersectionType& intersection) const DS_FINAL
{
return where_->apply_on(gv, intersection);
}
virtual void apply_local(const IntersectionType& intersection) DS_FINAL
{
localVectorAssembler_.assembleLocal(space_, intersection, vector_, this->vectors(), this->indices());
}
private:
const TestSpaceType& space_;
std::unique_ptr< const ApplyOn::WhichIntersection< GridViewType > > where_;
const LocalFaceVectorAssembler& localVectorAssembler_;
VectorType& vector_;
}; // class LocalFaceVectorAssemblerWrapper
public:
template< class ConstraintsType, class M >
void add(ConstraintsType& constraints,
Dune::Stuff::LA::MatrixInterface< M >& matrix,
const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
{
typedef typename M::derived_type MatrixType;
MatrixType& matrix_imp = static_cast< MatrixType& >(matrix);
assert(matrix_imp.rows() == test_space_.mapper().size());
assert(matrix_imp.cols() == ansatz_space_.mapper().size());
typedef LocalMatrixConstraintsWrapper< ConstraintsType, MatrixType > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, ansatz_space_, where, constraints, matrix_imp));
} // ... add(...)
template< class ConstraintsType, class V >
void add(ConstraintsType& constraints,
Dune::Stuff::LA::VectorInterface< V >& vector,
const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = static_cast< VectorType& >(vector);
assert(vector_imp.size() == test_space_.mapper().size());
typedef LocalVectorConstraintsWrapper< ConstraintsType, VectorType > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, constraints, vector_imp));
} // ... add(...)
template< class L, class M >
void add(const LocalAssembler::Codim0Matrix< L >& local_assembler,
Dune::Stuff::LA::MatrixInterface< M >& matrix,
const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
{
typedef typename M::derived_type MatrixType;
MatrixType& matrix_imp = static_cast< MatrixType& >(matrix);
assert(matrix_imp.rows() == test_space_.mapper().size());
assert(matrix_imp.cols() == ansatz_space_.mapper().size());
typedef LocalVolumeMatrixAssemblerWrapper< LocalAssembler::Codim0Matrix< L >, MatrixType > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
} // ... add(...)
template< class L, class V >
void add(const LocalAssembler::Codim0Vector< L >& local_assembler,
Dune::Stuff::LA::VectorInterface< V >& vector,
const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = static_cast< VectorType& >(vector);
assert(vector_imp.size() == test_space_.mapper().size());
typedef LocalVolumeVectorAssemblerWrapper< LocalAssembler::Codim0Vector< L >, VectorType > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
} // ... add(...)
template< class L, class V >
void add(const LocalAssembler::Codim1Vector< L >& local_assembler,
Dune::Stuff::LA::VectorInterface< V >& vector,
const ApplyOn::WhichIntersection< GridViewType >* where = new ApplyOn::AllIntersections< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = static_cast< VectorType& >(vector);
assert(vector_imp.size() == test_space_.mapper().size());
typedef LocalFaceVectorAssemblerWrapper< LocalAssembler::Codim1Vector< L >, VectorType > WrapperType;
this->codim1_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
} // ... add(...)
void assemble()
{
this->walk();
}
private:
const TestSpaceType& test_space_;
const AnsatzSpaceType& ansatz_space_;
}; // class SystemAssembler
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_ASSEMBLER_SYSTEM_HH
<commit_msg>[assembler.system] update * moved moved TmpStorageProvider to tmp-storage.hh * add override and final keywords * assemble() now takes an optional clear_stack, just as walk()<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_ASSEMBLER_SYSTEM_HH
#define DUNE_GDT_ASSEMBLER_SYSTEM_HH
#include <type_traits>
#include <memory>
#include <dune/gdt/space/interface.hh>
#include <dune/gdt/space/constraints.hh>
#include "local/codim0.hh"
#include "local/codim1.hh"
#include "gridwalker.hh"
#include "tmp-storage.hh"
namespace Dune {
namespace GDT {
template< class TestSpaceImp,
class GridViewImp = typename TestSpaceImp::GridViewType,
class AnsatzSpaceImp = TestSpaceImp >
class SystemAssembler
: public GridWalker< GridViewImp >
{
static_assert(std::is_base_of< SpaceInterface< typename TestSpaceImp::Traits >, TestSpaceImp >::value,
"TestSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of< SpaceInterface< typename AnsatzSpaceImp::Traits >, AnsatzSpaceImp >::value,
"AnsatzSpaceImp has to be derived from SpaceInterface!");
typedef GridWalker< GridViewImp > BaseType;
public:
typedef TestSpaceImp TestSpaceType;
typedef AnsatzSpaceImp AnsatzSpaceType;
typedef typename BaseType::GridViewType GridViewType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::IntersectionType IntersectionType;
typedef typename BaseType::BoundaryInfoType BoundaryInfoType;
private:
typedef typename TestSpaceType::RangeFieldType RangeFieldType;
public:
SystemAssembler(const TestSpaceType& test, const AnsatzSpaceType& ansatz, const GridViewType& grid_view)
: BaseType(grid_view)
, test_space_(test)
, ansatz_space_(ansatz)
{}
SystemAssembler(const TestSpaceType& test, const AnsatzSpaceType& ansatz)
: BaseType(*(test.grid_view()))
, test_space_(test)
, ansatz_space_(ansatz)
{}
SystemAssembler(const TestSpaceType& test)
: BaseType(*(test.grid_view()))
, test_space_(test)
, ansatz_space_(test_space_)
{}
SystemAssembler(const TestSpaceType& test, const GridViewType& grid_view)
: BaseType(grid_view)
, test_space_(test)
, ansatz_space_(test_space_)
{}
const TestSpaceType& test_space() const
{
return test_space_;
}
const AnsatzSpaceType& ansatz_space() const
{
return ansatz_space_;
}
using BaseType::add;
private:
template< class ConstraintsType, class MatrixType >
class LocalMatrixConstraintsWrapper
: public BaseType::Codim0Object
{
public:
LocalMatrixConstraintsWrapper(const TestSpaceType& t_space,
const AnsatzSpaceType& a_space,
const ApplyOn::WhichEntity< GridViewType >* where,
ConstraintsType& constraints,
MatrixType& matrix)
: t_space_(t_space)
, a_space_(a_space)
, where_(where)
, constraints_(constraints)
, matrix_(matrix)
{}
virtual ~LocalMatrixConstraintsWrapper() {}
virtual bool apply_on(const GridViewType& gv, const EntityType& entity) const DS_OVERRIDE DS_FINAL
{
return where_->apply_on(gv, entity);
}
virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
{
t_space_.local_constraints(a_space_, entity, constraints_);
for (size_t ii = 0; ii < constraints_.rows(); ++ii) {
const size_t row = constraints_.globalRow(ii);
for (size_t jj = 0; jj < constraints_.cols(); ++jj) {
matrix_.set_entry(row, constraints_.globalCol(jj), constraints_.value(ii, jj));
}
}
} // ... apply_local(...)
private:
const TestSpaceType& t_space_;
const AnsatzSpaceType& a_space_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
ConstraintsType& constraints_;
MatrixType& matrix_;
}; // class LocalMatrixConstraintsWrapper
template< class ConstraintsType, class VectorType >
class LocalVectorConstraintsWrapper
: public BaseType::Codim0Object
{
public:
LocalVectorConstraintsWrapper(const TestSpaceType& t_space,
const ApplyOn::WhichEntity< GridViewType >* where,
ConstraintsType& constraints,
VectorType& vector)
: t_space_(t_space)
, where_(where)
, constraints_(constraints)
, vector_(vector)
{}
virtual ~LocalVectorConstraintsWrapper() {}
virtual bool apply_on(const GridViewType& gv, const EntityType& entity) const DS_OVERRIDE DS_FINAL
{
return where_->apply_on(gv, entity);
}
virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
{
t_space_.local_constraints(entity, constraints_);
for (size_t ii = 0; ii < constraints_.rows(); ++ii) {
vector_.set_entry(constraints_.globalRow(ii), RangeFieldType(0));
}
}
private:
const TestSpaceType& t_space_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
ConstraintsType& constraints_;
VectorType& vector_;
}; // class LocalVectorConstraintsWrapper
template< class LocalVolumeMatrixAssembler, class MatrixType >
class LocalVolumeMatrixAssemblerWrapper
: public BaseType::Codim0Object
, TmpStorageProvider::Matrices< RangeFieldType >
{
typedef TmpStorageProvider::Matrices< RangeFieldType > TmpMatricesProvider;
public:
LocalVolumeMatrixAssemblerWrapper(const TestSpaceType& t_space,
const AnsatzSpaceType& a_space,
const ApplyOn::WhichEntity< GridViewType >* where,
const LocalVolumeMatrixAssembler& localAssembler,
MatrixType& matrix)
: TmpMatricesProvider(localAssembler.numTmpObjectsRequired(),
t_space.mapper().maxNumDofs(),
a_space.mapper().maxNumDofs())
, t_space_(t_space)
, a_space_(a_space)
, where_(where)
, localMatrixAssembler_(localAssembler)
, matrix_(matrix)
{}
virtual ~LocalVolumeMatrixAssemblerWrapper() {}
virtual bool apply_on(const GridViewType& gv, const EntityType& entity) const DS_OVERRIDE DS_FINAL
{
return where_->apply_on(gv, entity);
}
virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
{
localMatrixAssembler_.assembleLocal(t_space_, a_space_, entity, matrix_, this->matrices(), this->indices());
}
private:
const TestSpaceType& t_space_;
const AnsatzSpaceType& a_space_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
const LocalVolumeMatrixAssembler& localMatrixAssembler_;
MatrixType& matrix_;
}; // class LocalVolumeMatrixAssemblerWrapper
template< class LocalVolumeVectorAssembler, class VectorType >
class LocalVolumeVectorAssemblerWrapper
: public BaseType::Codim0Object
, TmpStorageProvider::Vectors< RangeFieldType >
{
typedef TmpStorageProvider::Vectors< RangeFieldType > TmpVectorsProvider;
public:
LocalVolumeVectorAssemblerWrapper(const TestSpaceType& space,
const ApplyOn::WhichEntity< GridViewType >* where,
const LocalVolumeVectorAssembler& localAssembler,
VectorType& vector)
: TmpVectorsProvider(localAssembler.numTmpObjectsRequired(), space.mapper().maxNumDofs())
, space_(space)
, where_(where)
, localVectorAssembler_(localAssembler)
, vector_(vector)
{}
virtual ~LocalVolumeVectorAssemblerWrapper() {}
virtual bool apply_on(const GridViewType& gv, const EntityType& entity) const DS_OVERRIDE DS_FINAL
{
return where_->apply_on(gv, entity);
}
virtual void apply_local(const EntityType& entity) DS_OVERRIDE DS_FINAL
{
localVectorAssembler_.assembleLocal(space_, entity, vector_, this->vectors(), this->indices());
}
private:
const TestSpaceType& space_;
std::unique_ptr< const ApplyOn::WhichEntity< GridViewType > > where_;
const LocalVolumeVectorAssembler& localVectorAssembler_;
VectorType& vector_;
}; // class LocalVolumeVectorAssemblerWrapper
template< class LocalFaceVectorAssembler, class VectorType >
class LocalFaceVectorAssemblerWrapper
: public BaseType::Codim1Object
, TmpStorageProvider::Vectors< RangeFieldType >
{
typedef TmpStorageProvider::Vectors< RangeFieldType > TmpVectorsProvider;
public:
LocalFaceVectorAssemblerWrapper(const TestSpaceType& space,
const ApplyOn::WhichIntersection< GridViewType >* where,
const LocalFaceVectorAssembler& localAssembler,
VectorType& vector)
: TmpVectorsProvider(localAssembler.numTmpObjectsRequired(), space.mapper().maxNumDofs())
, space_(space)
, where_(where)
, localVectorAssembler_(localAssembler)
, vector_(vector)
{}
virtual ~LocalFaceVectorAssemblerWrapper() {}
virtual bool apply_on(const GridViewType& gv, const IntersectionType& intersection) const DS_OVERRIDE DS_FINAL
{
return where_->apply_on(gv, intersection);
}
virtual void apply_local(const IntersectionType& intersection) DS_OVERRIDE DS_FINAL
{
localVectorAssembler_.assembleLocal(space_, intersection, vector_, this->vectors(), this->indices());
}
private:
const TestSpaceType& space_;
std::unique_ptr< const ApplyOn::WhichIntersection< GridViewType > > where_;
const LocalFaceVectorAssembler& localVectorAssembler_;
VectorType& vector_;
}; // class LocalFaceVectorAssemblerWrapper
public:
template< class ConstraintsType, class M >
void add(ConstraintsType& constraints,
Dune::Stuff::LA::MatrixInterface< M >& matrix,
const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
{
typedef typename M::derived_type MatrixType;
MatrixType& matrix_imp = static_cast< MatrixType& >(matrix);
assert(matrix_imp.rows() == test_space_.mapper().size());
assert(matrix_imp.cols() == ansatz_space_.mapper().size());
typedef LocalMatrixConstraintsWrapper< ConstraintsType, MatrixType > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, ansatz_space_, where, constraints, matrix_imp));
} // ... add(...)
template< class ConstraintsType, class V >
void add(ConstraintsType& constraints,
Dune::Stuff::LA::VectorInterface< V >& vector,
const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = static_cast< VectorType& >(vector);
assert(vector_imp.size() == test_space_.mapper().size());
typedef LocalVectorConstraintsWrapper< ConstraintsType, VectorType > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, constraints, vector_imp));
} // ... add(...)
template< class L, class M >
void add(const LocalAssembler::Codim0Matrix< L >& local_assembler,
Dune::Stuff::LA::MatrixInterface< M >& matrix,
const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
{
typedef typename M::derived_type MatrixType;
MatrixType& matrix_imp = static_cast< MatrixType& >(matrix);
assert(matrix_imp.rows() == test_space_.mapper().size());
assert(matrix_imp.cols() == ansatz_space_.mapper().size());
typedef LocalVolumeMatrixAssemblerWrapper< LocalAssembler::Codim0Matrix< L >, MatrixType > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
} // ... add(...)
template< class L, class V >
void add(const LocalAssembler::Codim0Vector< L >& local_assembler,
Dune::Stuff::LA::VectorInterface< V >& vector,
const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = static_cast< VectorType& >(vector);
assert(vector_imp.size() == test_space_.mapper().size());
typedef LocalVolumeVectorAssemblerWrapper< LocalAssembler::Codim0Vector< L >, VectorType > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
} // ... add(...)
template< class L, class V >
void add(const LocalAssembler::Codim1Vector< L >& local_assembler,
Dune::Stuff::LA::VectorInterface< V >& vector,
const ApplyOn::WhichIntersection< GridViewType >* where = new ApplyOn::AllIntersections< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = static_cast< VectorType& >(vector);
assert(vector_imp.size() == test_space_.mapper().size());
typedef LocalFaceVectorAssemblerWrapper< LocalAssembler::Codim1Vector< L >, VectorType > WrapperType;
this->codim1_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
} // ... add(...)
void assemble(const bool clear_stack = true)
{
this->walk(clear_stack);
}
private:
const TestSpaceType& test_space_;
const AnsatzSpaceType& ansatz_space_;
}; // class SystemAssembler
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_ASSEMBLER_SYSTEM_HH
<|endoftext|> |
<commit_before>#include "pb_sls.h"
#include "smt_literal.h"
#include "ast_pp.h"
#include "uint_set.h"
namespace smt {
struct pb_sls::imp {
struct clause {
literal_vector m_lits;
scoped_mpz_vector m_weights;
scoped_mpz m_k;
scoped_mpz m_value;
bool m_eq;
clause(unsynch_mpz_manager& m):
m_weights(m),
m_k(m),
m_value(m),
m_eq(true)
{}
clause(clause const& cls):
m_lits(cls.m_lits),
m_weights(cls.m_weights.m()),
m_k(cls.m_k),
m_value(cls.m_value),
m_eq(cls.m_eq) {
for (unsigned i = 0; i < cls.m_weights.size(); ++i) {
m_weights.push_back(cls.m_weights[i]);
}
}
};
struct stats {
stats() { reset(); }
void reset() { memset(this, 0, sizeof(*this)); }
};
ast_manager& m;
pb_util pb;
unsynch_mpz_manager mgr;
volatile bool m_cancel;
vector<clause> m_clauses; // clauses to be satisfied
vector<clause> m_soft; // soft constraints
vector<rational> m_weights; // weights of soft constraints
rational m_penalty; // current penalty of soft constraints
vector<unsigned_vector> m_hard_occ, m_soft_occ; // variable occurrence
svector<bool> m_assignment; // current assignment.
obj_map<expr, unsigned> m_expr2var; // map expressions to Boolean variables.
ptr_vector<expr> m_var2expr; // reverse map
uint_set m_hard_false; // list of hard clauses that are false.
uint_set m_soft_false; // list of soft clauses that are false.
unsigned m_max_flips;
imp(ast_manager& m):
m(m),
pb(m),
m_cancel(false)
{
m_max_flips = 100;
}
~imp() {
}
unsigned max_flips() {
return m_max_flips;
}
void add(expr* f) {
clause cls(mgr);
if (compile_clause(f, cls)) {
m_clauses.push_back(cls);
}
}
void add(expr* f, rational const& w) {
clause cls(mgr);
if (compile_clause(f, cls)) {
m_clauses.push_back(cls);
}
}
void init_value(expr* f, bool b) {
literal lit = mk_literal(f);
SASSERT(!lit.sign());
m_assignment[lit.var()] = b;
}
lbool operator()() {
init();
for (unsigned i = 0; i < max_flips(); ++i) {
flip();
if (m_cancel) {
return l_undef;
}
}
return l_undef;
}
bool get_value(expr* f) {
unsigned var;
if (m_expr2var.find(f, var)) {
return m_assignment[var];
}
UNREACHABLE();
return true;
}
bool get_value(literal l) {
return l.sign() ^ m_assignment[l.var()];
}
void set_cancel(bool f) {
m_cancel = f;
}
void collect_statistics(statistics& st) const {
}
void get_model(model_ref& mdl) {
}
void updt_params(params_ref& p) {
}
bool eval(clause& cls) {
unsigned sz = cls.m_lits.size();
cls.m_value.reset();
for (unsigned i = 0; i < sz; ++i) {
if (get_value(cls.m_lits[i])) {
cls.m_value += cls.m_weights[i];
}
}
if (cls.m_eq) {
return cls.m_value == cls.m_k;
}
else {
return cls.m_value >= cls.m_k;
}
}
void init_occ(vector<clause> const& clauses, vector<unsigned_vector> & occ) {
for (unsigned i = 0; i < clauses.size(); ++i) {
clause const& cls = clauses[i];
for (unsigned j = 0; j < cls.m_lits.size(); ++j) {
literal lit = cls.m_lits[j];
occ[lit.var()].push_back(i);
}
}
}
void init() {
// initialize the occurs vectors.
init_occ(m_clauses, m_hard_occ);
init_occ(m_soft, m_soft_occ);
// add clauses that are false.
for (unsigned i = 0; i < m_clauses.size(); ++i) {
if (!eval(m_clauses[i])) {
m_hard_false.insert(i);
}
}
m_penalty.reset();
for (unsigned i = 0; i < m_soft.size(); ++i) {
if (!eval(m_soft[i])) {
m_soft_false.insert(i);
m_penalty += m_weights[i];
}
}
}
void flip() {
if (m_hard_false.empty()) {
flip_soft();
}
else {
flip_hard();
}
}
void flip_hard() {
SASSERT(!m_hard_false.empty());
clause const& cls = pick_hard_clause();
int break_count;
int min_bc = INT_MAX;
unsigned min_bc_index = 0;
for (unsigned i = 0; i < cls.m_lits.size(); ++i) {
literal lit = cls.m_lits[i];
break_count = flip(lit);
if (break_count <= 0) {
return;
}
if (break_count < min_bc) {
min_bc = break_count;
min_bc_index = i;
}
VERIFY(-break_count == flip(~lit));
}
// just do a greedy move:
flip(cls.m_lits[min_bc_index]);
}
void flip_soft() {
NOT_IMPLEMENTED_YET();
}
// crude selection strategy.
clause const& pick_hard_clause() {
SASSERT(!m_hard_false.empty());
uint_set::iterator it = m_hard_false.begin();
uint_set::iterator end = m_hard_false.end();
SASSERT(it != end);
return m_clauses[*it];
}
clause const& pick_soft_clause() {
SASSERT(!m_soft_false.empty());
uint_set::iterator it = m_soft_false.begin();
uint_set::iterator end = m_soft_false.end();
SASSERT(it != end);
unsigned index = *it;
rational penalty = m_weights[index];
++it;
for (; it != end; ++it) {
if (m_weights[*it] > penalty) {
index = *it;
penalty = m_weights[*it];
}
}
return m_soft[index];
}
int flip(literal l) {
SASSERT(get_value(l));
m_assignment[l.var()] = !m_assignment[l.var()];
int break_count = 0;
{
unsigned_vector const& occ = m_hard_occ[l.var()];
for (unsigned i = 0; i < occ.size(); ++i) {
unsigned j = occ[i];
if (eval(m_clauses[j])) {
if (m_hard_false.contains(j)) {
break_count--;
m_hard_false.remove(j);
}
}
else {
if (!m_hard_false.contains(j)) {
break_count++;
m_hard_false.insert(j);
}
}
}
}
{
unsigned_vector const& occ = m_soft_occ[l.var()];
for (unsigned i = 0; i < occ.size(); ++i) {
unsigned j = occ[i];
if (eval(m_soft[j])) {
if (m_soft_false.contains(j)) {
m_penalty -= m_weights[j];
m_soft_false.remove(j);
}
}
else {
if (!m_soft_false.contains(j)) {
m_penalty += m_weights[j];
m_soft_false.insert(j);
}
}
}
}
SASSERT(get_value(~l));
return break_count;
}
literal mk_literal(expr* f) {
literal result;
bool sign = false;
while (m.is_not(f, f)) {
sign = !sign;
}
if (m.is_true(f)) {
result = true_literal;
}
else if (m.is_false(f)) {
result = false_literal;
}
else {
unsigned var;
if (!m_expr2var.find(f, var)) {
var = m_hard_occ.size();
SASSERT(m_expr2var.size() == var);
m_hard_occ.push_back(unsigned_vector());
m_soft_occ.push_back(unsigned_vector());
m_assignment.push_back(false);
m_expr2var.insert(f, var);
m_var2expr.push_back(f);
}
result = literal(var);
}
if (sign) {
result.neg();
}
return result;
}
bool compile_clause(expr* _f, clause& cls) {
if (!is_app(_f)) return false;
app* f = to_app(_f);
unsigned sz = f->get_num_args();
expr* const* args = f->get_args();
literal lit;
rational coeff;
if (pb.is_ge(f) || pb.is_eq(f)) {
for (unsigned i = 0; i < sz; ++i) {
coeff = pb.get_coeff(f, i);
SASSERT(coeff.is_int());
lit = mk_literal(args[i]);
if (lit == null_literal) return false;
SASSERT(lit != false_literal && lit != true_literal);
cls.m_lits.push_back(lit);
cls.m_weights.push_back(coeff.to_mpq().numerator());
if (get_value(lit)) {
cls.m_value += coeff.to_mpq().numerator();
}
}
cls.m_eq = pb.is_eq(f);
coeff = pb.get_k(f);
SASSERT(coeff.is_int());
cls.m_k = coeff.to_mpq().numerator();
}
else if (m.is_or(f)) {
for (unsigned i = 0; i < sz; ++i) {
lit = mk_literal(args[i]);
if (lit == null_literal) return false;
SASSERT(lit != false_literal && lit != true_literal);
cls.m_lits.push_back(lit);
cls.m_weights.push_back(mpz(1));
if (get_value(lit)) {
cls.m_value += mpz(1);
}
}
cls.m_eq = false;
cls.m_k = mpz(1);
}
else {
lit = mk_literal(f);
if (lit == null_literal) return false;
SASSERT(lit != false_literal && lit != true_literal);
cls.m_lits.push_back(lit);
cls.m_weights.push_back(mpz(1));
cls.m_eq = true;
cls.m_k = mpz(1);
}
return true;
}
};
pb_sls::pb_sls(ast_manager& m) {
m_imp = alloc(imp, m);
}
pb_sls::~pb_sls() {
dealloc(m_imp);
}
void pb_sls::add(expr* f) {
m_imp->add(f);
}
void pb_sls::add(expr* f, rational const& w) {
m_imp->add(f, w);
}
void pb_sls::init_value(expr* f, bool b) {
m_imp->init_value(f, b);
}
lbool pb_sls::operator()() {
return (*m_imp)();
}
bool pb_sls::get_value(expr* f) {
return m_imp->get_value(f);
}
void pb_sls::set_cancel(bool f) {
m_imp->set_cancel(f);
}
void pb_sls::collect_statistics(statistics& st) const {
m_imp->collect_statistics(st);
}
void pb_sls::get_model(model_ref& mdl) {
m_imp->get_model(mdl);
}
void pb_sls::updt_params(params_ref& p) {
m_imp->updt_params(p);
}
}
<commit_msg>working on pb sls<commit_after>/*++
Copyright (c) 2014 Microsoft Corporation
Module Name:
pb_sls.cpp
Abstract:
SLS for PB optimization.
Author:
Nikolaj Bjorner (nbjorner) 2014-03-18
Notes:
--*/
#include "pb_sls.h"
#include "smt_literal.h"
#include "ast_pp.h"
#include "uint_set.h"
namespace smt {
struct pb_sls::imp {
struct clause {
literal_vector m_lits;
scoped_mpz_vector m_weights;
scoped_mpz m_k;
scoped_mpz m_value;
bool m_eq;
clause(unsynch_mpz_manager& m):
m_weights(m),
m_k(m),
m_value(m),
m_eq(true)
{}
clause(clause const& cls):
m_lits(cls.m_lits),
m_weights(cls.m_weights.m()),
m_k(cls.m_k),
m_value(cls.m_value),
m_eq(cls.m_eq) {
for (unsigned i = 0; i < cls.m_weights.size(); ++i) {
m_weights.push_back(cls.m_weights[i]);
}
}
};
struct stats {
stats() { reset(); }
void reset() { memset(this, 0, sizeof(*this)); }
};
ast_manager& m;
pb_util pb;
unsynch_mpz_manager mgr;
volatile bool m_cancel;
vector<clause> m_clauses; // clauses to be satisfied
vector<clause> m_soft; // soft constraints
vector<rational> m_weights; // weights of soft constraints
rational m_penalty; // current penalty of soft constraints
vector<unsigned_vector> m_hard_occ, m_soft_occ; // variable occurrence
svector<bool> m_assignment; // current assignment.
obj_map<expr, unsigned> m_expr2var; // map expressions to Boolean variables.
ptr_vector<expr> m_var2expr; // reverse map
uint_set m_hard_false; // list of hard clauses that are false.
uint_set m_soft_false; // list of soft clauses that are false.
unsigned m_max_flips;
imp(ast_manager& m):
m(m),
pb(m),
m_cancel(false)
{
m_max_flips = 100;
}
~imp() {
}
unsigned max_flips() {
return m_max_flips;
}
void add(expr* f) {
clause cls(mgr);
if (compile_clause(f, cls)) {
m_clauses.push_back(cls);
}
}
void add(expr* f, rational const& w) {
clause cls(mgr);
if (compile_clause(f, cls)) {
m_clauses.push_back(cls);
m_weights.push_back(w);
}
}
void init_value(expr* f, bool b) {
literal lit = mk_literal(f);
SASSERT(!lit.sign());
m_assignment[lit.var()] = b;
}
lbool operator()() {
init();
for (unsigned i = 0; i < max_flips(); ++i) {
flip();
if (m_cancel) {
return l_undef;
}
}
return l_undef;
}
bool get_value(expr* f) {
unsigned var;
if (m_expr2var.find(f, var)) {
return m_assignment[var];
}
UNREACHABLE();
return true;
}
bool get_value(literal l) {
return l.sign() ^ m_assignment[l.var()];
}
void set_cancel(bool f) {
m_cancel = f;
}
void collect_statistics(statistics& st) const {
}
void get_model(model_ref& mdl) {
NOT_IMPLEMENTED_YET();
}
void updt_params(params_ref& p) {
}
bool eval(clause& cls) {
unsigned sz = cls.m_lits.size();
cls.m_value.reset();
for (unsigned i = 0; i < sz; ++i) {
if (get_value(cls.m_lits[i])) {
cls.m_value += cls.m_weights[i];
}
}
if (cls.m_eq) {
return cls.m_value == cls.m_k;
}
else {
return cls.m_value >= cls.m_k;
}
}
void init_occ(vector<clause> const& clauses, vector<unsigned_vector> & occ) {
for (unsigned i = 0; i < clauses.size(); ++i) {
clause const& cls = clauses[i];
for (unsigned j = 0; j < cls.m_lits.size(); ++j) {
literal lit = cls.m_lits[j];
occ[lit.var()].push_back(i);
}
}
}
void init() {
// initialize the occurs vectors.
init_occ(m_clauses, m_hard_occ);
init_occ(m_soft, m_soft_occ);
// add clauses that are false.
for (unsigned i = 0; i < m_clauses.size(); ++i) {
if (!eval(m_clauses[i])) {
m_hard_false.insert(i);
}
}
m_penalty.reset();
for (unsigned i = 0; i < m_soft.size(); ++i) {
if (!eval(m_soft[i])) {
m_soft_false.insert(i);
m_penalty += m_weights[i];
}
}
}
void flip() {
if (m_hard_false.empty()) {
flip_soft();
}
else {
flip_hard();
}
}
void flip_hard() {
SASSERT(!m_hard_false.empty());
clause const& cls = pick_hard_clause();
int break_count;
int min_bc = INT_MAX;
unsigned min_bc_index = 0;
for (unsigned i = 0; i < cls.m_lits.size(); ++i) {
literal lit = cls.m_lits[i];
break_count = flip(lit);
if (break_count <= 0) {
return;
}
if (break_count < min_bc) {
min_bc = break_count;
min_bc_index = i;
}
VERIFY(-break_count == flip(~lit));
}
// just do a greedy move:
flip(cls.m_lits[min_bc_index]);
}
void flip_soft() {
clause const& cls = pick_soft_clause();
int break_count;
int min_bc = INT_MAX;
unsigned min_bc_index = 0;
rational penalty = m_penalty;
rational min_penalty = penalty;
for (unsigned i = 0; i < cls.m_lits.size(); ++i) {
literal lit = cls.m_lits[i];
break_count = flip(lit);
SASSERT(break_count >= 0);
if (break_count == 0 && penalty > m_penalty) {
// TODO: save into best so far if this qualifies.
return;
}
if ((break_count < min_bc) ||
(break_count == min_bc && m_penalty < min_penalty)) {
min_bc = break_count;
min_bc_index = i;
min_penality = m_penalty;
}
VERIFY(-break_count == flip(~lit));
}
// just do a greedy move:
flip(cls.m_lits[min_bc_index]);
}
//
// TODO: alternate version: loop over soft clauses and see if there is a flip that
// reduces the penalty while preserving the hard constraints.
//
// crude selection strategy.
clause const& pick_hard_clause() {
SASSERT(!m_hard_false.empty());
uint_set::iterator it = m_hard_false.begin();
uint_set::iterator end = m_hard_false.end();
SASSERT(it != end);
return m_clauses[*it];
}
clause const& pick_soft_clause() {
SASSERT(!m_soft_false.empty());
uint_set::iterator it = m_soft_false.begin();
uint_set::iterator end = m_soft_false.end();
SASSERT(it != end);
unsigned index = *it;
rational penalty = m_weights[index];
++it;
for (; it != end; ++it) {
if (m_weights[*it] > penalty) {
index = *it;
penalty = m_weights[*it];
}
}
return m_soft[index];
}
int flip(literal l) {
SASSERT(get_value(l));
m_assignment[l.var()] = !m_assignment[l.var()];
int break_count = 0;
{
unsigned_vector const& occ = m_hard_occ[l.var()];
for (unsigned i = 0; i < occ.size(); ++i) {
unsigned j = occ[i];
if (eval(m_clauses[j])) {
if (m_hard_false.contains(j)) {
break_count--;
m_hard_false.remove(j);
}
}
else {
if (!m_hard_false.contains(j)) {
break_count++;
m_hard_false.insert(j);
}
}
}
}
{
unsigned_vector const& occ = m_soft_occ[l.var()];
for (unsigned i = 0; i < occ.size(); ++i) {
unsigned j = occ[i];
if (eval(m_soft[j])) {
if (m_soft_false.contains(j)) {
m_penalty -= m_weights[j];
m_soft_false.remove(j);
}
}
else {
if (!m_soft_false.contains(j)) {
m_penalty += m_weights[j];
m_soft_false.insert(j);
}
}
}
}
SASSERT(get_value(~l));
return break_count;
}
literal mk_literal(expr* f) {
literal result;
bool sign = false;
while (m.is_not(f, f)) {
sign = !sign;
}
if (m.is_true(f)) {
result = true_literal;
}
else if (m.is_false(f)) {
result = false_literal;
}
else {
unsigned var;
if (!m_expr2var.find(f, var)) {
var = m_hard_occ.size();
SASSERT(m_expr2var.size() == var);
m_hard_occ.push_back(unsigned_vector());
m_soft_occ.push_back(unsigned_vector());
m_assignment.push_back(false);
m_expr2var.insert(f, var);
m_var2expr.push_back(f);
}
result = literal(var);
}
if (sign) {
result.neg();
}
return result;
}
bool compile_clause(expr* _f, clause& cls) {
if (!is_app(_f)) return false;
app* f = to_app(_f);
unsigned sz = f->get_num_args();
expr* const* args = f->get_args();
literal lit;
rational coeff;
if (pb.is_ge(f) || pb.is_eq(f)) {
for (unsigned i = 0; i < sz; ++i) {
coeff = pb.get_coeff(f, i);
SASSERT(coeff.is_int());
lit = mk_literal(args[i]);
if (lit == null_literal) return false;
SASSERT(lit != false_literal && lit != true_literal);
cls.m_lits.push_back(lit);
cls.m_weights.push_back(coeff.to_mpq().numerator());
if (get_value(lit)) {
cls.m_value += coeff.to_mpq().numerator();
}
}
cls.m_eq = pb.is_eq(f);
coeff = pb.get_k(f);
SASSERT(coeff.is_int());
cls.m_k = coeff.to_mpq().numerator();
}
else if (m.is_or(f)) {
for (unsigned i = 0; i < sz; ++i) {
lit = mk_literal(args[i]);
if (lit == null_literal) return false;
SASSERT(lit != false_literal && lit != true_literal);
cls.m_lits.push_back(lit);
cls.m_weights.push_back(mpz(1));
if (get_value(lit)) {
cls.m_value += mpz(1);
}
}
cls.m_eq = false;
cls.m_k = mpz(1);
}
else {
lit = mk_literal(f);
if (lit == null_literal) return false;
SASSERT(lit != false_literal && lit != true_literal);
cls.m_lits.push_back(lit);
cls.m_weights.push_back(mpz(1));
cls.m_eq = true;
cls.m_k = mpz(1);
}
return true;
}
};
pb_sls::pb_sls(ast_manager& m) {
m_imp = alloc(imp, m);
}
pb_sls::~pb_sls() {
dealloc(m_imp);
}
void pb_sls::add(expr* f) {
m_imp->add(f);
}
void pb_sls::add(expr* f, rational const& w) {
m_imp->add(f, w);
}
void pb_sls::init_value(expr* f, bool b) {
m_imp->init_value(f, b);
}
lbool pb_sls::operator()() {
return (*m_imp)();
}
bool pb_sls::get_value(expr* f) {
return m_imp->get_value(f);
}
void pb_sls::set_cancel(bool f) {
m_imp->set_cancel(f);
}
void pb_sls::collect_statistics(statistics& st) const {
m_imp->collect_statistics(st);
}
void pb_sls::get_model(model_ref& mdl) {
m_imp->get_model(mdl);
}
void pb_sls::updt_params(params_ref& p) {
m_imp->updt_params(p);
}
}
<|endoftext|> |
<commit_before><commit_msg>cc: Workaround resourceless draw crash<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include "sockets/SocketW.h"
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include "buffer.h"
#include "user.h"
#include "string.h"
#define BUFLEN 1000000
int get_empty( user ** list, int amount ) {
for (int i = 0; i < amount; i++ ){
if (!list[i]->is_connected){return i;}
}
return -1;
}
int main( int argc, char * argv[] ) {
if (argc < 4) {
std::cout << "usage: " << argv[0] << " buffers_count total_buffersize max_clients" << std::endl;
return 1;
}
int buffers = atoi(argv[1]);
int total_buffersize = atoi(argv[2]);
int connections = atoi(argv[3]);
int size_per_buffer = total_buffersize/buffers;
std::cout << "Size per buffer: " << size_per_buffer << std::endl;
buffer ** ringbuf = (buffer**) calloc (buffers,sizeof(buffer*));
for (int i = 0; i < buffers; i ++ ) {
ringbuf[i] = new buffer;
ringbuf[i]->data = (char*) malloc(size_per_buffer);
}
std::cout << "Successfully allocated " << total_buffersize << " bytes total buffer." << std::endl;
user ** connectionList = (user**) calloc (connections,sizeof(user*));
for (int i = 0; i < connections; i++) { connectionList[i] = new user; }
char header[13];//FLV header is always 13 bytes
int ret = 0;
int frame_bodylength = 0;
int current_buffer = 0;
int open_connection = -1;
int lastproper = 0;//last properly finished buffer number
unsigned int loopcount = 0;
SWUnixSocket listener;
SWBaseSocket * incoming = 0;
SWBaseSocket::SWBaseError BError;
//read FLV header - 13 bytes
ret = fread(&header,1,13,stdin);
//TODO: check ret?
listener.bind("/tmp/socketfile");
listener.listen();
listener.set_timeout(0,50000);
//TODO: not while true, but while running - set running to false when kill signal is received!
while(true) {
loopcount ++;
//invalidate the current buffer
ringbuf[current_buffer]->size = 0;
ringbuf[current_buffer]->number = -1;
//read FLV frame header - 11 bytes
ret = fread(ringbuf[current_buffer]->data,1,11,stdin);
//TODO: Check ret?
//if video frame? (id 9) check for incoming connections
if (ringbuf[current_buffer]->data[0] == 9) {
incoming = listener.accept(&BError);
if (incoming){
open_connection = get_empty(connectionList,connections);
if (open_connection != -1) {
connectionList[open_connection]->connect(incoming);
//send the FLV header
std::cout << "Client " << open_connection << " connected." << std::endl;
connectionList[open_connection]->MyBuffer = lastproper;
connectionList[open_connection]->MyBuffer_num = ringbuf[lastproper]->number;
//TODO: Do this more nicely?
if (connectionList[open_connection]->Conn->send(&header[0],13,NULL) != 13){
connectionList[open_connection]->disconnect();
std::cout << "Client " << open_connection << " failed to receive the header!" << std::endl;
}
std::cout << "Client " << open_connection << " received header!" << std::endl;
}else{
std::cout << "New client not connected: no more connections!" << std::endl;
}
}
}
//calculate body length of frame
frame_bodylength = 4;
frame_bodylength += ringbuf[current_buffer]->data[3];
frame_bodylength += (ringbuf[current_buffer]->data[2] << 8);
frame_bodylength += (ringbuf[current_buffer]->data[1] << 16);
//read the rest of the frame
ret = fread(&ringbuf[current_buffer]->data[11],1,frame_bodylength,stdin);
//TODO: Check ret?
ringbuf[current_buffer]->size = frame_bodylength + 11;
ringbuf[current_buffer]->number = loopcount;
//send all connections what they need, if and when they need it
for (int i = 0; i < connections; i++) {connectionList[i]->Send(ringbuf, buffers);}
//keep track of buffers
lastproper = current_buffer;
current_buffer++;
current_buffer %= buffers;
}
// disconnect listener
listener.disconnect();
//TODO: cleanup
return 0;
}
<commit_msg>Loop support<commit_after>#include <iostream>
#include "sockets/SocketW.h"
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include "buffer.h"
#include "user.h"
#include "string.h"
#define BUFLEN 1000000
int get_empty( user ** list, int amount ) {
for (int i = 0; i < amount; i++ ){
if (!list[i]->is_connected){return i;}
}
return -1;
}
int main( int argc, char * argv[] ) {
if (argc < 4) {
std::cout << "usage: " << argv[0] << " buffers_count total_buffersize max_clients" << std::endl;
return 1;
}
int buffers = atoi(argv[1]);
int total_buffersize = atoi(argv[2]);
int connections = atoi(argv[3]);
int size_per_buffer = total_buffersize/buffers;
std::cout << "Size per buffer: " << size_per_buffer << std::endl;
buffer ** ringbuf = (buffer**) calloc (buffers,sizeof(buffer*));
for (int i = 0; i < buffers; i ++ ) {
ringbuf[i] = new buffer;
ringbuf[i]->data = (char*) malloc(size_per_buffer);
}
std::cout << "Successfully allocated " << total_buffersize << " bytes total buffer." << std::endl;
user ** connectionList = (user**) calloc (connections,sizeof(user*));
for (int i = 0; i < connections; i++) { connectionList[i] = new user; }
char header[13];//FLV header is always 13 bytes
int ret = 0;
int frame_bodylength = 0;
int current_buffer = 0;
int open_connection = -1;
int lastproper = 0;//last properly finished buffer number
unsigned int loopcount = 0;
SWUnixSocket listener;
SWBaseSocket * incoming = 0;
SWBaseSocket::SWBaseError BError;
//read FLV header - 13 bytes
ret = fread(&header,1,13,stdin);
//TODO: check ret?
listener.bind("/tmp/socketfile");
listener.listen();
listener.set_timeout(0,50000);
//TODO: not while true, but while running - set running to false when kill signal is received!
while(true) {
loopcount ++;
//invalidate the current buffer
ringbuf[current_buffer]->size = 0;
ringbuf[current_buffer]->number = -1;
if (std::cin.peek() == 'F') {
//new FLV file, read the file head again.
ret = fread(&header,1,13,stdin);
} else {
//read FLV frame header - 11 bytes
ret = fread(ringbuf[current_buffer]->data,1,11,stdin);
//TODO: Check ret?
//if video frame? (id 9) check for incoming connections
if (ringbuf[current_buffer]->data[0] == 9) {
incoming = listener.accept(&BError);
if (incoming){
open_connection = get_empty(connectionList,connections);
if (open_connection != -1) {
connectionList[open_connection]->connect(incoming);
//send the FLV header
std::cout << "Client " << open_connection << " connected." << std::endl;
connectionList[open_connection]->MyBuffer = lastproper;
connectionList[open_connection]->MyBuffer_num = ringbuf[lastproper]->number;
//TODO: Do this more nicely?
if (connectionList[open_connection]->Conn->send(&header[0],13,NULL) != 13){
connectionList[open_connection]->disconnect();
std::cout << "Client " << open_connection << " failed to receive the header!" << std::endl;
}
std::cout << "Client " << open_connection << " received header!" << std::endl;
}else{
std::cout << "New client not connected: no more connections!" << std::endl;
}
}
}
//calculate body length of frame
frame_bodylength = 4;
frame_bodylength += ringbuf[current_buffer]->data[3];
frame_bodylength += (ringbuf[current_buffer]->data[2] << 8);
frame_bodylength += (ringbuf[current_buffer]->data[1] << 16);
//read the rest of the frame
ret = fread(&ringbuf[current_buffer]->data[11],1,frame_bodylength,stdin);
//TODO: Check ret?
ringbuf[current_buffer]->size = frame_bodylength + 11;
ringbuf[current_buffer]->number = loopcount;
//send all connections what they need, if and when they need it
for (int i = 0; i < connections; i++) {connectionList[i]->Send(ringbuf, buffers);}
//keep track of buffers
lastproper = current_buffer;
current_buffer++;
current_buffer %= buffers;
}
}
// disconnect listener
listener.disconnect();
//TODO: cleanup
return 0;
}
<|endoftext|> |
<commit_before>/*
* This file is part of the Camera Streaming Daemon
*
* Copyright (C) 2017 Intel Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <fcntl.h>
#include <gst/app/gstappsrc.h>
#include <librealsense/rs.h>
#include <sstream>
#include <sys/ioctl.h>
#include <unistd.h>
#include "log.h"
#include "samples/stream_realsense.h"
#define WIDTH (640)
#define HEIGHT (480)
#define SIZE (WIDTH * HEIGHT * 3)
#define ONE_METER (999)
struct rgb {
uint8_t r;
uint8_t g;
uint8_t b;
};
struct Context {
rs_device *dev;
rs_context *rs_ctx;
struct rgb rgb_data[];
};
static void rainbow_scale(double value, uint8_t rgb[])
{
rgb[0] = rgb[1] = rgb[2] = 0;
if (value <= 0.0)
return;
if (value < 0.25) { // RED to YELLOW
rgb[0] = 255;
rgb[1] = (uint8_t)255 * (value / 0.25);
} else if (value < 0.5) { // YELLOW to GREEN
rgb[0] = (uint8_t)255 * (1 - ((value - 0.25) / 0.25));
rgb[1] = 255;
} else if (value < 0.75) { // GREEN to CYAN
rgb[1] = 255;
rgb[2] = (uint8_t)255 * (value - 0.5 / 0.25);
} else if (value < 1.0) { // CYAN to BLUE
rgb[1] = (uint8_t)255 * (1 - ((value - 0.75) / 0.25));
rgb[2] = 255;
} else { // BLUE
rgb[2] = 255;
}
}
static void cb_need_data(GstAppSrc *appsrc, guint unused_size, gpointer user_data)
{
GstFlowReturn ret;
Context *ctx = (Context *)user_data;
rs_wait_for_frames(ctx->dev, NULL);
uint16_t *depth = (uint16_t *)rs_get_frame_data(ctx->dev, RS_STREAM_DEPTH, NULL);
if (!depth) {
log_error("No depth data. Not building frame");
return;
}
GstBuffer *buffer
= gst_buffer_new_wrapped_full((GstMemoryFlags)0, ctx->rgb_data, SIZE, 0, SIZE, NULL, NULL);
assert(buffer);
for (int i = 0, end = WIDTH * HEIGHT; i < end; ++i) {
uint8_t rainbow[3];
rainbow_scale((double)depth[i] * 0.001, rainbow);
ctx->rgb_data[i].r = rainbow[0];
ctx->rgb_data[i].g = rainbow[1];
ctx->rgb_data[i].b = rainbow[2];
}
g_signal_emit_by_name(appsrc, "push-buffer", buffer, &ret);
}
static void cb_enough_data(GstAppSrc *src, gpointer user_data)
{
}
static gboolean cb_seek_data(GstAppSrc *src, guint64 offset, gpointer user_data)
{
return TRUE;
}
StreamRealSense::StreamRealSense()
: Stream()
{
}
const std::string StreamRealSense::get_path() const
{
return "/RealSense";
}
const std::string StreamRealSense::get_name() const
{
return "RealSense Sample Stream";
}
const std::vector<Stream::PixelFormat> &StreamRealSense::get_formats() const
{
static std::vector<Stream::PixelFormat> formats;
return formats;
}
GstElement *
StreamRealSense::create_gstreamer_pipeline(std::map<std::string, std::string> ¶ms) const
{
Context *ctx = (Context *)malloc(sizeof(Context) + SIZE);
assert(ctx);
/* librealsense */
rs_error *e = 0;
ctx->rs_ctx = rs_create_context(RS_API_VERSION, &e);
if (e) {
log_error("rs_error was raised when calling %s(%s): %s", rs_get_failed_function(e),
rs_get_failed_args(e), rs_get_error_message(e));
log_error("Current librealsense api version %d", rs_get_api_version(NULL));
log_error("Compiled for librealsense api version %d", RS_API_VERSION);
return nullptr;
}
ctx->dev = rs_get_device(ctx->rs_ctx, 0, NULL);
if (!ctx->dev) {
log_error("Unable to access realsense device");
return nullptr;
}
/* Configure all streams to run at VGA resolution at 60 frames per second */
rs_enable_stream(ctx->dev, RS_STREAM_DEPTH, WIDTH, HEIGHT, RS_FORMAT_Z16, 60, NULL);
rs_start_device(ctx->dev, NULL);
/* gstreamer */
GError *error = nullptr;
GstElement *pipeline;
pipeline = gst_parse_launch("appsrc name=mysource ! videoconvert ! "
"video/x-raw,width=640,height=480,format=NV12 ! vaapih264enc ! "
"rtph264pay name=pay0",
&error);
if (!pipeline) {
log_error("Error processing pipeline for RealSense stream device: %s\n",
error ? error->message : "unknown error");
g_clear_error(&error);
return nullptr;
}
GstElement *appsrc = gst_bin_get_by_name(GST_BIN(pipeline), "mysource");
/* setup */
gst_app_src_set_caps(GST_APP_SRC(appsrc),
gst_caps_new_simple("video/x-raw", "format", G_TYPE_STRING, "RGB", "width",
G_TYPE_INT, WIDTH, "height", G_TYPE_INT, HEIGHT,
NULL));
/* setup appsrc */
g_object_set(G_OBJECT(appsrc), "is-live", TRUE, "format", GST_FORMAT_TIME, NULL);
/* connect signals */
GstAppSrcCallbacks cbs;
cbs.need_data = cb_need_data;
cbs.enough_data = cb_enough_data;
cbs.seek_data = cb_seek_data;
gst_app_src_set_callbacks(GST_APP_SRC_CAST(appsrc), &cbs, ctx, NULL);
g_object_set_data(G_OBJECT(pipeline), "context", ctx);
return pipeline;
}
void StreamRealSense::finalize_gstreamer_pipeline(GstElement *pipeline)
{
Context *ctx = (Context *)g_object_get_data(G_OBJECT(pipeline), "context");
if (!ctx) {
log_error("Media not created by stream_realsense is being cleared with stream_realsense");
return;
}
rs_delete_context(ctx->rs_ctx, NULL);
free(ctx);
}
<commit_msg>realsense: Turn on auto exposure and always on IR<commit_after>/*
* This file is part of the Camera Streaming Daemon
*
* Copyright (C) 2017 Intel Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <fcntl.h>
#include <gst/app/gstappsrc.h>
#include <librealsense/rs.h>
#include <sstream>
#include <sys/ioctl.h>
#include <unistd.h>
#include "log.h"
#include "samples/stream_realsense.h"
#define WIDTH (640)
#define HEIGHT (480)
#define SIZE (WIDTH * HEIGHT * 3)
#define ONE_METER (999)
struct rgb {
uint8_t r;
uint8_t g;
uint8_t b;
};
struct Context {
rs_device *dev;
rs_context *rs_ctx;
struct rgb rgb_data[];
};
static void rainbow_scale(double value, uint8_t rgb[])
{
rgb[0] = rgb[1] = rgb[2] = 0;
if (value <= 0.0)
return;
if (value < 0.25) { // RED to YELLOW
rgb[0] = 255;
rgb[1] = (uint8_t)255 * (value / 0.25);
} else if (value < 0.5) { // YELLOW to GREEN
rgb[0] = (uint8_t)255 * (1 - ((value - 0.25) / 0.25));
rgb[1] = 255;
} else if (value < 0.75) { // GREEN to CYAN
rgb[1] = 255;
rgb[2] = (uint8_t)255 * (value - 0.5 / 0.25);
} else if (value < 1.0) { // CYAN to BLUE
rgb[1] = (uint8_t)255 * (1 - ((value - 0.75) / 0.25));
rgb[2] = 255;
} else { // BLUE
rgb[2] = 255;
}
}
static void cb_need_data(GstAppSrc *appsrc, guint unused_size, gpointer user_data)
{
GstFlowReturn ret;
Context *ctx = (Context *)user_data;
rs_wait_for_frames(ctx->dev, NULL);
uint16_t *depth = (uint16_t *)rs_get_frame_data(ctx->dev, RS_STREAM_DEPTH, NULL);
if (!depth) {
log_error("No depth data. Not building frame");
return;
}
GstBuffer *buffer
= gst_buffer_new_wrapped_full((GstMemoryFlags)0, ctx->rgb_data, SIZE, 0, SIZE, NULL, NULL);
assert(buffer);
for (int i = 0, end = WIDTH * HEIGHT; i < end; ++i) {
uint8_t rainbow[3];
rainbow_scale((double)depth[i] * 0.001, rainbow);
ctx->rgb_data[i].r = rainbow[0];
ctx->rgb_data[i].g = rainbow[1];
ctx->rgb_data[i].b = rainbow[2];
}
g_signal_emit_by_name(appsrc, "push-buffer", buffer, &ret);
}
static void cb_enough_data(GstAppSrc *src, gpointer user_data)
{
}
static gboolean cb_seek_data(GstAppSrc *src, guint64 offset, gpointer user_data)
{
return TRUE;
}
StreamRealSense::StreamRealSense()
: Stream()
{
}
const std::string StreamRealSense::get_path() const
{
return "/RealSense";
}
const std::string StreamRealSense::get_name() const
{
return "RealSense Sample Stream";
}
const std::vector<Stream::PixelFormat> &StreamRealSense::get_formats() const
{
static std::vector<Stream::PixelFormat> formats;
return formats;
}
GstElement *
StreamRealSense::create_gstreamer_pipeline(std::map<std::string, std::string> ¶ms) const
{
Context *ctx = (Context *)malloc(sizeof(Context) + SIZE);
assert(ctx);
/* librealsense */
rs_error *e = 0;
ctx->rs_ctx = rs_create_context(RS_API_VERSION, &e);
if (e) {
log_error("rs_error was raised when calling %s(%s): %s", rs_get_failed_function(e),
rs_get_failed_args(e), rs_get_error_message(e));
log_error("Current librealsense api version %d", rs_get_api_version(NULL));
log_error("Compiled for librealsense api version %d", RS_API_VERSION);
return nullptr;
}
ctx->dev = rs_get_device(ctx->rs_ctx, 0, NULL);
if (!ctx->dev) {
log_error("Unable to access realsense device");
return nullptr;
}
/* Configure all streams to run at VGA resolution at 60 frames per second */
rs_enable_stream(ctx->dev, RS_STREAM_DEPTH, WIDTH, HEIGHT, RS_FORMAT_Z16, 60, NULL);
rs_start_device(ctx->dev, NULL);
if (rs_device_supports_option(ctx->dev, RS_OPTION_R200_EMITTER_ENABLED, NULL))
rs_set_device_option(ctx->dev, RS_OPTION_R200_EMITTER_ENABLED, 1, NULL);
if (rs_device_supports_option(ctx->dev, RS_OPTION_R200_LR_AUTO_EXPOSURE_ENABLED, NULL))
rs_set_device_option(ctx->dev, RS_OPTION_R200_LR_AUTO_EXPOSURE_ENABLED, 1, NULL);
/* gstreamer */
GError *error = nullptr;
GstElement *pipeline;
pipeline = gst_parse_launch("appsrc name=mysource ! videoconvert ! "
"video/x-raw,width=640,height=480,format=NV12 ! vaapih264enc ! "
"rtph264pay name=pay0",
&error);
if (!pipeline) {
log_error("Error processing pipeline for RealSense stream device: %s\n",
error ? error->message : "unknown error");
g_clear_error(&error);
return nullptr;
}
GstElement *appsrc = gst_bin_get_by_name(GST_BIN(pipeline), "mysource");
/* setup */
gst_app_src_set_caps(GST_APP_SRC(appsrc),
gst_caps_new_simple("video/x-raw", "format", G_TYPE_STRING, "RGB", "width",
G_TYPE_INT, WIDTH, "height", G_TYPE_INT, HEIGHT,
NULL));
/* setup appsrc */
g_object_set(G_OBJECT(appsrc), "is-live", TRUE, "format", GST_FORMAT_TIME, NULL);
/* connect signals */
GstAppSrcCallbacks cbs;
cbs.need_data = cb_need_data;
cbs.enough_data = cb_enough_data;
cbs.seek_data = cb_seek_data;
gst_app_src_set_callbacks(GST_APP_SRC_CAST(appsrc), &cbs, ctx, NULL);
g_object_set_data(G_OBJECT(pipeline), "context", ctx);
return pipeline;
}
void StreamRealSense::finalize_gstreamer_pipeline(GstElement *pipeline)
{
Context *ctx = (Context *)g_object_get_data(G_OBJECT(pipeline), "context");
if (!ctx) {
log_error("Media not created by stream_realsense is being cleared with stream_realsense");
return;
}
rs_delete_context(ctx->rs_ctx, NULL);
free(ctx);
}
<|endoftext|> |
<commit_before>#include <babylon/samples/mesh/rotation_and_scaling_scene.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/mesh/mesh.h>
namespace BABYLON {
namespace Samples {
RotationAndScalingScene::RotationAndScalingScene(ICanvas* iCanvas)
: IRenderableScene(iCanvas)
{
}
RotationAndScalingScene::~RotationAndScalingScene()
{
}
const char* RotationAndScalingScene::getName()
{
return "Rotation and Scaling Scene";
}
void RotationAndScalingScene::initializeScene(ICanvas* canvas, Scene* scene)
{
// Create a camera
auto camera = ArcRotateCamera::New("Camera", Math::PI, Math::PI / 8.f, 150.f,
Vector3::Zero(), scene);
// Attach the camera to the canvas
camera->attachControl(canvas, true);
// Create a basic light, aiming 0,1,0 - meaning, to the sky
HemisphericLight::New("Hemi", Vector3(0, 1, 0), scene);
// Creation of boxes
auto box1 = Mesh::CreateBox("Box1", 6.f, scene);
auto box2 = Mesh::CreateBox("Box2", 6.f, scene);
auto box3 = Mesh::CreateBox("Box3", 6.f, scene);
auto box4 = Mesh::CreateBox("Box4", 6.f, scene);
auto box5 = Mesh::CreateBox("Box5", 6.f, scene);
auto box6 = Mesh::CreateBox("Box6", 6.f, scene);
auto box7 = Mesh::CreateBox("Box7", 6.f, scene);
// Moving boxes on the x axis
box1->position().x = -20.f;
box2->position().x = -10.f;
box3->position().x = 0.f;
box4->position().x = 15.f;
box5->position().x = 30.f;
box6->position().x = 45.f;
// Rotate box around the x axis
box1->rotation().x = Math::PI / 6.f;
// Rotate box around the y axis
box2->rotation().y = Math::PI / 3.f;
// Scaling on the x axis
box4->scaling().x = 2.f;
// Scaling on the y axis
box5->scaling().y = 2.f;
// Scaling on the z axis
box6->scaling().z = 2.f;
// Moving box7 relatively to box1
box7->setParent(box1);
box7->position().z = -10.f;
}
} // end of namespace Samples
} // end of namespace BABYLON
<commit_msg>Changed light color in rotate and scaling example<commit_after>#include <babylon/samples/mesh/rotation_and_scaling_scene.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/mesh/mesh.h>
namespace BABYLON {
namespace Samples {
RotationAndScalingScene::RotationAndScalingScene(ICanvas* iCanvas)
: IRenderableScene(iCanvas)
{
}
RotationAndScalingScene::~RotationAndScalingScene()
{
}
const char* RotationAndScalingScene::getName()
{
return "Rotation and Scaling Scene";
}
void RotationAndScalingScene::initializeScene(ICanvas* canvas, Scene* scene)
{
// Create a camera
auto camera = ArcRotateCamera::New("Camera", Math::PI, Math::PI / 8.f, 150.f,
Vector3::Zero(), scene);
// Attach the camera to the canvas
camera->attachControl(canvas, true);
// Create a basic light, aiming 0,1,0 - meaning, to the sky
auto light = HemisphericLight::New("Hemi", Vector3(0, 1, 0), scene);
light->diffuse = Color3::FromInt(0xf68712);
light->specular = Color3::FromInt(0xf1471d);
// Creation of boxes
auto box1 = Mesh::CreateBox("Box1", 6.f, scene);
auto box2 = Mesh::CreateBox("Box2", 6.f, scene);
auto box3 = Mesh::CreateBox("Box3", 6.f, scene);
auto box4 = Mesh::CreateBox("Box4", 6.f, scene);
auto box5 = Mesh::CreateBox("Box5", 6.f, scene);
auto box6 = Mesh::CreateBox("Box6", 6.f, scene);
auto box7 = Mesh::CreateBox("Box7", 6.f, scene);
// Moving boxes on the x axis
box1->position().x = -20.f;
box2->position().x = -10.f;
box3->position().x = 0.f;
box4->position().x = 15.f;
box5->position().x = 30.f;
box6->position().x = 45.f;
// Rotate box around the x axis
box1->rotation().x = Math::PI / 6.f;
// Rotate box around the y axis
box2->rotation().y = Math::PI / 3.f;
// Scaling on the x axis
box4->scaling().x = 2.f;
// Scaling on the y axis
box5->scaling().y = 2.f;
// Scaling on the z axis
box6->scaling().z = 2.f;
// Moving box7 relatively to box1
box7->setParent(box1);
box7->position().z = -10.f;
}
} // end of namespace Samples
} // end of namespace BABYLON
<|endoftext|> |
<commit_before>#include "BrainStdAfx.h"
#include "HAL.h"
#include "Comms.h"
#include <sys/time.h>
#include <sys/resource.h>
#include <boost/program_options.hpp>
#include <thread>
#include <iostream>
#ifdef RASPBERRY_PI
extern auto shutdown_bcm() -> bool;
#endif
size_t s_test = 0;
bool s_exit = false;
boost::asio::io_service s_async_io_service;
namespace boost
{
void throw_exception(std::exception const & e)
{
QLOGE("boost::exception {}", e.what());
throw e;
}
}
// Define the function to be called when ctrl-c (SIGINT) signal is sent to process
void signal_handler(int signum)
{
if (s_exit)
{
QLOGI("Forcing an exit due to signal {}", signum);
abort();
}
s_exit = true;
QLOGI("Exitting due to signal {}", signum);
}
void out_of_memory_handler()
{
QLOGE("Out of memory");
std::abort();
}
int main(int argc, char const* argv[])
{
signal(SIGINT, signal_handler); // Trap basic signals (exit cleanly)
signal(SIGKILL, signal_handler);
signal(SIGUSR1, signal_handler);
signal(SIGQUIT, signal_handler);
// signal(SIGABRT, signal_handler);
signal(SIGTERM, signal_handler);
//set the new_handler
std::set_new_handler(out_of_memory_handler);
q::logging::add_logger(q::logging::Logger_uptr(new q::logging::Console_Logger()));
q::logging::set_decorations(q::logging::Decorations(q::logging::Decoration::TIMESTAMP, q::logging::Decoration::LEVEL, q::logging::Decoration::TOPIC));
QLOG_TOPIC("silk");
// q::util::Rand rnd;
// while (true)
// {
// math::vec3f target(rnd.get_float() * 40.0, rnd.get_float() * 40.0, rnd.get_float() * 10.0);
// test_mm(target, 0.01);
// test_mm(target, 0.1);
// test_mm(target, 0.5);
// }
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help", "produce help message")
("blind", "no camera")
("test", po::value<size_t>(), "test");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
return 1;
}
s_test = vm.count("test") ? vm["test"].as<size_t>() : size_t(0);
//bool blind = vm.count("blind") != 0;
QLOGI("Creating io_service thread");
boost::shared_ptr<boost::asio::io_service::work> async_work(new boost::asio::io_service::work(s_async_io_service));
auto async_thread = std::thread([]() { s_async_io_service.run(); });
#if defined RASPBERRY_PI
{
int policy = SCHED_FIFO;
struct sched_param param;
param.sched_priority = sched_get_priority_max(policy);
if (pthread_setschedparam(pthread_self(), policy, ¶m) != 0)
{
perror("main sched_setscheduler");
exit(EXIT_FAILURE);
}
policy = SCHED_IDLE;
param.sched_priority = sched_get_priority_min(policy);
if (pthread_setschedparam(async_thread.native_handle(), policy, ¶m) != 0)
{
perror("async_thread sched_setscheduler");
exit(EXIT_FAILURE);
}
}
#endif
try
{
silk::HAL hal;
silk::Comms comms(hal);
if (!hal.init(comms))
{
QLOGE("Hardware failure! Aborting");
goto exit;
}
#if defined RASPBERRY_PI
if (!comms.start_rfmon("mon0", 5))
{
QLOGE("Cannot start communication channel! Aborting");
goto exit;
}
#else
if (!comms.start_udp(8000, 8001))
{
QLOGE("Cannot start communication channel! Aborting");
goto exit;
}
#endif
// while (!s_exit)
// {
// std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// QLOGI("Waiting for comms to connect...");
// if (comms.is_connected())
// {
// break;
// }
// }
QLOGI("All systems up. Ready to fly...");
{
constexpr std::chrono::milliseconds PERIOD(5);
auto last = q::Clock::now();
while (!s_exit)
{
auto start = q::Clock::now();
if (start - last >= PERIOD)
{
last = start;
comms.process();
hal.process();
}
//don't sleep too much if we're late
if (q::Clock::now() - start < PERIOD)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
else
{
std::this_thread::yield();
}
}
}
exit:
QLOGI("Stopping everything");
//stop threads
async_work.reset();
s_async_io_service.stop();
if (async_thread.joinable())
{
std::this_thread::yield();
async_thread.join();
}
hal.shutdown();
#ifdef RASPBERRY_PI
shutdown_bcm();
#endif
}
catch (std::exception const& e)
{
QLOGE("exception: {}", e.what());
abort();
}
QLOGI("Closing");
}
<commit_msg>Removed sleeping to allow dependent nodes in the wrong order to propagate faster the stream data<commit_after>#include "BrainStdAfx.h"
#include "HAL.h"
#include "Comms.h"
#include <sys/time.h>
#include <sys/resource.h>
#include <boost/program_options.hpp>
#include <thread>
#include <iostream>
#ifdef RASPBERRY_PI
extern auto shutdown_bcm() -> bool;
#endif
size_t s_test = 0;
bool s_exit = false;
boost::asio::io_service s_async_io_service;
namespace boost
{
void throw_exception(std::exception const & e)
{
QLOGE("boost::exception {}", e.what());
throw e;
}
}
// Define the function to be called when ctrl-c (SIGINT) signal is sent to process
void signal_handler(int signum)
{
if (s_exit)
{
QLOGI("Forcing an exit due to signal {}", signum);
abort();
}
s_exit = true;
QLOGI("Exitting due to signal {}", signum);
}
void out_of_memory_handler()
{
QLOGE("Out of memory");
std::abort();
}
int main(int argc, char const* argv[])
{
signal(SIGINT, signal_handler); // Trap basic signals (exit cleanly)
signal(SIGKILL, signal_handler);
signal(SIGUSR1, signal_handler);
signal(SIGQUIT, signal_handler);
// signal(SIGABRT, signal_handler);
signal(SIGTERM, signal_handler);
//set the new_handler
std::set_new_handler(out_of_memory_handler);
q::logging::add_logger(q::logging::Logger_uptr(new q::logging::Console_Logger()));
q::logging::set_decorations(q::logging::Decorations(q::logging::Decoration::TIMESTAMP, q::logging::Decoration::LEVEL, q::logging::Decoration::TOPIC));
QLOG_TOPIC("silk");
// q::util::Rand rnd;
// while (true)
// {
// math::vec3f target(rnd.get_float() * 40.0, rnd.get_float() * 40.0, rnd.get_float() * 10.0);
// test_mm(target, 0.01);
// test_mm(target, 0.1);
// test_mm(target, 0.5);
// }
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help", "produce help message")
("blind", "no camera")
("test", po::value<size_t>(), "test");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << desc << "\n";
return 1;
}
s_test = vm.count("test") ? vm["test"].as<size_t>() : size_t(0);
//bool blind = vm.count("blind") != 0;
QLOGI("Creating io_service thread");
boost::shared_ptr<boost::asio::io_service::work> async_work(new boost::asio::io_service::work(s_async_io_service));
auto async_thread = std::thread([]() { s_async_io_service.run(); });
#if defined RASPBERRY_PI
{
int policy = SCHED_FIFO;
struct sched_param param;
param.sched_priority = sched_get_priority_max(policy);
if (pthread_setschedparam(pthread_self(), policy, ¶m) != 0)
{
perror("main sched_setscheduler");
exit(EXIT_FAILURE);
}
policy = SCHED_IDLE;
param.sched_priority = sched_get_priority_min(policy);
if (pthread_setschedparam(async_thread.native_handle(), policy, ¶m) != 0)
{
perror("async_thread sched_setscheduler");
exit(EXIT_FAILURE);
}
}
#endif
try
{
silk::HAL hal;
silk::Comms comms(hal);
if (!hal.init(comms))
{
QLOGE("Hardware failure! Aborting");
goto exit;
}
#if defined RASPBERRY_PI
if (!comms.start_rfmon("mon0", 5))
{
QLOGE("Cannot start communication channel! Aborting");
goto exit;
}
#else
if (!comms.start_udp(8000, 8001))
{
QLOGE("Cannot start communication channel! Aborting");
goto exit;
}
#endif
// while (!s_exit)
// {
// std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// QLOGI("Waiting for comms to connect...");
// if (comms.is_connected())
// {
// break;
// }
// }
QLOGI("All systems up. Ready to fly...");
{
constexpr std::chrono::microseconds PERIOD(5000);
auto last = q::Clock::now();
while (!s_exit)
{
auto start = q::Clock::now();
auto dt = start - last;
if (dt > std::chrono::milliseconds(10))
{
QLOGW("Process Latency of {}!!!!!", dt);
}
//if (dt >= PERIOD)
{
last = start;
//QLOGI("---- LOOP -----");
comms.process();
hal.process();
}
//No sleeping here!!! process as fast as possible as the nodes are not always in the ideal order
// and out of order nodes will be processes next 'frame'. So the quicker the frames, the smaller the lag between nodes
//don't sleep too much if we're late
// if (q::Clock::now() - start < PERIOD)
// {
// //std::this_thread::sleep_for(std::chrono::milliseconds(1));
// for (volatile int i = 0; i < 10000; i++)
// {
// ;
// }
// }
// else
// {
//// std::this_thread::yield();
// }
}
}
exit:
QLOGI("Stopping everything");
//stop threads
async_work.reset();
s_async_io_service.stop();
if (async_thread.joinable())
{
std::this_thread::yield();
async_thread.join();
}
hal.shutdown();
#ifdef RASPBERRY_PI
shutdown_bcm();
#endif
}
catch (std::exception const& e)
{
QLOGE("exception: {}", e.what());
abort();
}
QLOGI("Closing");
}
<|endoftext|> |
<commit_before>/**
\description The is the main for the new version of the mert algorithm develloppped during the 2nd MT marathon
*/
#include <limits>
#include "Data.h"
#include "Point.h"
#include "Scorer.h"
#include "ScoreData.h"
#include "FeatureData.h"
#include "Optimizer.h"
#include "getopt.h"
#include "Types.h"
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cmath>
#include "Timer.h"
#include "Util.h"
float min_interval = 1e-3;
using namespace std;
void usage(void) {
cerr<<"usage: mert -d <dimensions> (mandatory )"<<endl;
cerr<<"[-n retry ntimes (default 1)]"<<endl;
cerr<<"[-o\tthe indexes to optimize(default all)]"<<endl;
cerr<<"[-t\tthe optimizer(default powell)]"<<endl;
cerr<<"[--sctype|-s] the scorer type (default BLEU)"<<endl;
cerr<<"[--scfile|-S] the scorer data file (default score.data)"<<endl;
cerr<<"[--ffile|-F] the feature data file data file (default feature.data)"<<endl;
cerr<<"[-v] verbose level"<<endl;
exit(1);
}
static struct option long_options[] =
{
{"pdim", 1, 0, 'd'},
{"ntry",1,0,'n'},
{"optimize",1,0,'o'},
{"type",1,0,'t'},
{"sctype",1,0,'s'},
{"scfile",1,0,'S'},
{"ffile",1,0,'F'},
{"verbose",1,0,'v'},
{0, 0, 0, 0}
};
int option_index;
int main (int argc, char **argv) {
int c,pdim,i;
pdim=-1;
int ntry=1;
string type("powell");
string scorertype("BLEU");
string scorerfile("statscore.data");
string featurefile("features.data");
vector<unsigned> tooptimize;
vector<parameter_t> start;
while ((c=getopt_long (argc, argv, "d:n:t:s:S:F:v:", long_options, &option_index)) != -1) {
switch (c) {
case 'd':
pdim = strtol(optarg, NULL, 10);
break;
case 'n':
ntry=strtol(optarg, NULL, 10);
break;
case 't':
type=string(optarg);
break;
case's':
scorertype=string(optarg);
break;
case 'S':
scorerfile=string(optarg);
case 'F':
featurefile=string(optarg);
break;
case 'v':
setverboselevel(strtol(optarg,NULL,10));
break;
default:
usage();
}
}
if (pdim < 0)
usage();
Timer timer;
timer.start("Starting...");
if(tooptimize.empty()){
tooptimize.resize(pdim);//We'll optimize on everything
for(i=0;i<pdim;i++)
tooptimize[i]=i;
}
ifstream opt("init.opt");
if(opt.fail()){
cerr<<"could not open init.opt"<<endl;
exit(3);
}
start.resize(pdim);//to do:read from file
int j;
for( j=0;j<pdim&&!opt.fail();j++)
opt>>start[j];
if(j<pdim){
cerr<<"error could not initialize start point with init.opt"<<endl;
exit(3);
}
opt.close();
//it make sense to know what parameter set were used to generate the nbest
ScorerFactory SF;
Scorer *TheScorer=SF.getScorer(scorertype);
ScoreData *SD=new ScoreData(*TheScorer);
SD->load(scorerfile);
FeatureData *FD=new FeatureData();
FD->load(featurefile);
Optimizer *O=OptimizerFactory::BuildOptimizer(pdim,tooptimize,start,type);
O->SetScorer(TheScorer);
O->SetFData(FD);
Point P(start);//Generate from the full feature set. Warning: must ne done after Optimiezr initialiazation
statscore_t best=O->Run(P);
Point bestP=P;
statscore_t mean=best;
statscore_t var=best*best;
vector<parameter_t> min(Point::getdim());
vector<parameter_t> max(Point::getdim());
for(int d=0;d<Point::getdim();d++){
min[d]=0.0;
max[d]=1.0;
}
//note: those mins and max are the bound for the starting points of the algorithm, not strict bound on the result!
for(int i=1;i<ntry;i++){
P.Randomize(min,max);
statscore_t score=O->Run(P);
if(score>best){
best=score;
bestP=P;
}
mean+=score;
var+=(score*score);
}
mean/=(float)ntry;
var/=(float)ntry;
var=sqrt(abs(var-mean*mean));
if(ntry>1)
cerr<<"variance of the score (for "<<ntry<<" try):"<<var<<endl;
cerr<<"best score"<<best<<endl;
ofstream res("weights.txt");
res<<bestP<<endl;
timer.stop("Stopping...");
}
<commit_msg>I fixed a small bug when reading parameters<commit_after>/**
\description The is the main for the new version of the mert algorithm develloppped during the 2nd MT marathon
*/
#include <limits>
#include "Data.h"
#include "Point.h"
#include "Scorer.h"
#include "ScoreData.h"
#include "FeatureData.h"
#include "Optimizer.h"
#include "getopt.h"
#include "Types.h"
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cmath>
#include "Timer.h"
#include "Util.h"
float min_interval = 1e-3;
using namespace std;
void usage(void) {
cerr<<"usage: mert -d <dimensions> (mandatory )"<<endl;
cerr<<"[-n retry ntimes (default 1)]"<<endl;
cerr<<"[-o\tthe indexes to optimize(default all)]"<<endl;
cerr<<"[-t\tthe optimizer(default powell)]"<<endl;
cerr<<"[--sctype|-s] the scorer type (default BLEU)"<<endl;
cerr<<"[--scfile|-S] the scorer data file (default score.data)"<<endl;
cerr<<"[--ffile|-F] the feature data file data file (default feature.data)"<<endl;
cerr<<"[-v] verbose level"<<endl;
exit(1);
}
static struct option long_options[] =
{
{"pdim", 1, 0, 'd'},
{"ntry",1,0,'n'},
{"optimize",1,0,'o'},
{"type",1,0,'t'},
{"sctype",1,0,'s'},
{"scfile",1,0,'S'},
{"ffile",1,0,'F'},
{"verbose",1,0,'v'},
{0, 0, 0, 0}
};
int option_index;
int main (int argc, char **argv) {
int c,pdim,i;
pdim=-1;
int ntry=1;
string type("powell");
string scorertype("BLEU");
string scorerfile("statscore.data");
string featurefile("features.data");
vector<unsigned> tooptimize;
vector<parameter_t> start;
while ((c=getopt_long (argc, argv, "d:n:t:s:S:F:v:", long_options, &option_index)) != -1) {
switch (c) {
case 'd':
pdim = strtol(optarg, NULL, 10);
break;
case 'n':
ntry=strtol(optarg, NULL, 10);
break;
case 't':
type=string(optarg);
break;
case's':
scorertype=string(optarg);
break;
case 'S':
scorerfile=string(optarg);
break;
case 'F':
featurefile=string(optarg);
break;
case 'v':
setverboselevel(strtol(optarg,NULL,10));
break;
default:
usage();
}
}
if (pdim < 0)
usage();
Timer timer;
timer.start("Starting...");
if(tooptimize.empty()){
tooptimize.resize(pdim);//We'll optimize on everything
for(i=0;i<pdim;i++)
tooptimize[i]=i;
}
ifstream opt("init.opt");
if(opt.fail()){
cerr<<"could not open init.opt"<<endl;
exit(3);
}
start.resize(pdim);//to do:read from file
int j;
for( j=0;j<pdim&&!opt.fail();j++)
opt>>start[j];
if(j<pdim){
cerr<<"error could not initialize start point with init.opt"<<endl;
exit(3);
}
opt.close();
//it make sense to know what parameter set were used to generate the nbest
ScorerFactory SF;
Scorer *TheScorer=SF.getScorer(scorertype);
cerr<<"Loading ScoreData from: "<< scorerfile << endl;
ScoreData *SD=new ScoreData(*TheScorer);
SD->load(scorerfile);
cerr<<"Loading FeatureData from: "<< featurefile << endl;
FeatureData *FD=new FeatureData();
FD->load(featurefile);
Optimizer *O=OptimizerFactory::BuildOptimizer(pdim,tooptimize,start,type);
O->SetScorer(TheScorer);
O->SetFData(FD);
Point P(start);//Generate from the full feature set. Warning: must ne done after Optimiezr initialiazation
statscore_t best=O->Run(P);
Point bestP=P;
statscore_t mean=best;
statscore_t var=best*best;
vector<parameter_t> min(Point::getdim());
vector<parameter_t> max(Point::getdim());
for(int d=0;d<Point::getdim();d++){
min[d]=0.0;
max[d]=1.0;
}
//note: those mins and max are the bound for the starting points of the algorithm, not strict bound on the result!
for(int i=1;i<ntry;i++){
P.Randomize(min,max);
statscore_t score=O->Run(P);
if(score>best){
best=score;
bestP=P;
}
mean+=score;
var+=(score*score);
}
mean/=(float)ntry;
var/=(float)ntry;
var=sqrt(abs(var-mean*mean));
if(ntry>1)
cerr<<"variance of the score (for "<<ntry<<" try):"<<var<<endl;
cerr<<"best score"<<best<<endl;
ofstream res("weights.txt");
res<<bestP<<endl;
timer.stop("Stopping...");
}
<|endoftext|> |
<commit_before>/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2014 Steven Lovegrove
*
* 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 <pangolin/video/drivers/join.h>
namespace pangolin
{
VideoJoiner::VideoJoiner(const std::vector<VideoInterface*>& src)
: src(src), size_bytes(0), sync_attempts_to_go(-1), sync_continuously(false)
{
// Add individual streams
for(size_t s=0; s< src.size(); ++s)
{
VideoInterface& vid = *src[s];
for(size_t i=0; i < vid.Streams().size(); ++i)
{
const StreamInfo si = vid.Streams()[i];
const VideoPixelFormat fmt = si.PixFormat();
const Image<unsigned char> img_offset = si.StreamImage((unsigned char*)size_bytes);
streams.push_back(StreamInfo(fmt, img_offset));
}
size_bytes += src[s]->SizeBytes();
}
}
VideoJoiner::~VideoJoiner()
{
for(size_t s=0; s< src.size(); ++s) {
src[s]->Stop();
delete src[s];
}
}
size_t VideoJoiner::SizeBytes() const
{
return size_bytes;
}
const std::vector<StreamInfo>& VideoJoiner::Streams() const
{
return streams;
}
void VideoJoiner::Start()
{
for(size_t s=0; s< src.size(); ++s) {
src[s]->Start();
}
}
void VideoJoiner::Stop()
{
for(size_t s=0; s< src.size(); ++s) {
src[s]->Stop();
}
}
bool VideoJoiner::Sync(int64_t tolerance_us, bool continuous)
{
for(size_t s=0; s< src.size(); ++s)
{
VideoPropertiesInterface* vpi = dynamic_cast<VideoPropertiesInterface*>(src[s]);
if(!vpi)
return false;
}
sync_attempts_to_go = MAX_SYNC_ATTEMPTS;
sync_tolerance_us = tolerance_us;
sync_continuously = continuous;
return true;
}
bool VideoJoiner::GrabNext( unsigned char* image, bool wait )
{
size_t offset = 0;
std::vector<size_t> offsets;
std::vector<int64_t> reception_times;
int64_t newest = std::numeric_limits<int64_t>::min();
int64_t oldest = std::numeric_limits<int64_t>::max();
bool grabbed_any = false;
for(size_t s=0; s<src.size(); ++s) {
VideoInterface& vid = *src[s];
grabbed_any |= vid.GrabNext(image+offset,wait);
offsets.push_back(offset);
offset += vid.SizeBytes();
if(sync_attempts_to_go >= 0) {
VideoPropertiesInterface* vidpi = dynamic_cast<VideoPropertiesInterface*>(src[s]);
if(vidpi->FrameProperties().contains(PANGO_HOST_RECEPTION_TIME_US)) {
int64_t rt = vidpi->FrameProperties()[PANGO_HOST_RECEPTION_TIME_US].get<int64_t>();
reception_times.push_back(rt);
if(newest < rt) newest = rt;
if(oldest > rt) oldest = rt;
} else {
sync_attempts_to_go = -1;
pango_print_error("Stream %lu in join does not support startup_sync_us option.\n", s);
}
}
}
if((sync_continuously || (sync_attempts_to_go == 0)) && ((newest - oldest) > sync_tolerance_us) ){
pango_print_warn("Join error, unable to sync streams within %lu us\n", (unsigned long)sync_tolerance_us);
}
if(sync_attempts_to_go >= 0) {
for(size_t s=0; s<src.size(); ++s) {
if(reception_times[s] < (newest - sync_tolerance_us)) {
VideoInterface& vid = *src[s];
vid.GrabNewest(image+offsets[s],false);
}
}
if(!sync_continuously) --sync_attempts_to_go;
}
return grabbed_any;
}
bool VideoJoiner::GrabNewest( unsigned char* image, bool wait )
{
// Simply calling GrabNewest on the child streams might cause loss of sync,
// instead we perform as many GrabNext as possible on the first stream and
// then pull the same number of frames from every other stream.
size_t offset = 0;
std::vector<size_t> offsets;
std::vector<int64_t> reception_times;
int64_t newest = std::numeric_limits<int64_t>::min();
int64_t oldest = std::numeric_limits<int64_t>::max();
bool grabbed_any = false;
int first_stream_backlog = 0;
int64_t rt = 0;
bool got_frame = false;
do {
got_frame = src[0]->GrabNext(image+offset,false);
if(got_frame) {
if(sync_attempts_to_go >= 0) {
VideoPropertiesInterface* vidpi = dynamic_cast<VideoPropertiesInterface*>(src[0]);
if(vidpi->FrameProperties().contains(PANGO_HOST_RECEPTION_TIME_US)) {
rt = vidpi->FrameProperties()[PANGO_HOST_RECEPTION_TIME_US].get<int64_t>();
} else {
sync_attempts_to_go = -1;
pango_print_error("Stream %u in join does not support startup_sync_us option.\n", 0);
}
}
first_stream_backlog++;
grabbed_any = true;
}
} while(got_frame);
offsets.push_back(offset);
offset += src[0]->SizeBytes();
if(sync_attempts_to_go >= 0) {
reception_times.push_back(rt);
if(newest < rt) newest = rt;
if(oldest > rt) oldest = rt;
}
for(size_t s=1; s<src.size(); ++s) {
for (int i=0; i<first_stream_backlog; i++){
grabbed_any |= src[s]->GrabNext(image+offset,true);
if(sync_attempts_to_go >= 0) {
VideoPropertiesInterface* vidpi = dynamic_cast<VideoPropertiesInterface*>(src[s]);
if(vidpi->FrameProperties().contains(PANGO_HOST_RECEPTION_TIME_US)) {
rt = vidpi->FrameProperties()[PANGO_HOST_RECEPTION_TIME_US].get<int64_t>();
} else {
sync_attempts_to_go = -1;
pango_print_error("Stream %lu in join does not support startup_sync_us option.\n", s);
}
}
}
offsets.push_back(offset);
offset += src[s]->SizeBytes();
if(sync_attempts_to_go >= 0) {
reception_times.push_back(rt);
if(newest < rt) newest = rt;
if(oldest > rt) oldest = rt;
}
}
if((sync_continuously || (sync_attempts_to_go == 0)) && ((newest - oldest) > sync_tolerance_us) ){
pango_print_warn("Join error, unable to sync streams within %lu us\n", (unsigned long)sync_tolerance_us);
}
if(sync_attempts_to_go >= 0) {
for(size_t s=0; s<src.size(); ++s) {
if(reception_times[s] < (newest - sync_tolerance_us)) {
VideoInterface& vid = *src[s];
vid.GrabNewest(image+offsets[s],false);
}
}
if(!sync_continuously) --sync_attempts_to_go;
}
return grabbed_any;
}
std::vector<VideoInterface*>& VideoJoiner::InputStreams()
{
return src;
}
}
<commit_msg>Join timing<commit_after>/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) 2014 Steven Lovegrove
*
* 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 <pangolin/video/drivers/join.h>
#include <pangolin/utils/timer.h>
namespace pangolin
{
VideoJoiner::VideoJoiner(const std::vector<VideoInterface*>& src)
: src(src), size_bytes(0), sync_attempts_to_go(-1), sync_continuously(false)
{
// Add individual streams
for(size_t s=0; s< src.size(); ++s)
{
VideoInterface& vid = *src[s];
for(size_t i=0; i < vid.Streams().size(); ++i)
{
const StreamInfo si = vid.Streams()[i];
const VideoPixelFormat fmt = si.PixFormat();
const Image<unsigned char> img_offset = si.StreamImage((unsigned char*)size_bytes);
streams.push_back(StreamInfo(fmt, img_offset));
}
size_bytes += src[s]->SizeBytes();
}
}
VideoJoiner::~VideoJoiner()
{
for(size_t s=0; s< src.size(); ++s) {
src[s]->Stop();
delete src[s];
}
}
size_t VideoJoiner::SizeBytes() const
{
return size_bytes;
}
const std::vector<StreamInfo>& VideoJoiner::Streams() const
{
return streams;
}
void VideoJoiner::Start()
{
for(size_t s=0; s< src.size(); ++s) {
src[s]->Start();
}
}
void VideoJoiner::Stop()
{
for(size_t s=0; s< src.size(); ++s) {
src[s]->Stop();
}
}
bool VideoJoiner::Sync(int64_t tolerance_us, bool continuous)
{
for(size_t s=0; s< src.size(); ++s)
{
VideoPropertiesInterface* vpi = dynamic_cast<VideoPropertiesInterface*>(src[s]);
if(!vpi)
return false;
}
sync_attempts_to_go = MAX_SYNC_ATTEMPTS;
sync_tolerance_us = tolerance_us;
sync_continuously = continuous;
return true;
}
bool VideoJoiner::GrabNext( unsigned char* image, bool wait )
{
size_t offset = 0;
std::vector<size_t> offsets;
std::vector<int64_t> reception_times;
int64_t newest = std::numeric_limits<int64_t>::min();
int64_t oldest = std::numeric_limits<int64_t>::max();
bool grabbed_any = false;
for(size_t s=0; s<src.size(); ++s) {
VideoInterface& vid = *src[s];
grabbed_any |= vid.GrabNext(image+offset,wait);
offsets.push_back(offset);
offset += vid.SizeBytes();
if(sync_attempts_to_go >= 0) {
VideoPropertiesInterface* vidpi = dynamic_cast<VideoPropertiesInterface*>(src[s]);
if(vidpi->FrameProperties().contains(PANGO_HOST_RECEPTION_TIME_US)) {
int64_t rt = vidpi->FrameProperties()[PANGO_HOST_RECEPTION_TIME_US].get<int64_t>();
reception_times.push_back(rt);
if(newest < rt) newest = rt;
if(oldest > rt) oldest = rt;
} else {
sync_attempts_to_go = -1;
pango_print_error("Stream %lu in join does not support startup_sync_us option.\n", s);
}
}
}
if((sync_continuously || (sync_attempts_to_go == 0)) && ((newest - oldest) > sync_tolerance_us) ){
pango_print_warn("Join error, unable to sync streams within %lu us\n", (unsigned long)sync_tolerance_us);
}
if(sync_attempts_to_go >= 0) {
for(size_t s=0; s<src.size(); ++s) {
if(reception_times[s] < (newest - sync_tolerance_us)) {
VideoInterface& vid = *src[s];
vid.GrabNewest(image+offsets[s],false);
}
}
if(!sync_continuously) --sync_attempts_to_go;
}
return grabbed_any;
}
bool VideoJoiner::GrabNewest( unsigned char* image, bool wait )
{
// Simply calling GrabNewest on the child streams might cause loss of sync,
// instead we perform as many GrabNext as possible on the first stream and
// then pull the same number of frames from every other stream.
size_t offset = 0;
std::vector<size_t> offsets;
std::vector<int64_t> reception_times;
int64_t newest = std::numeric_limits<int64_t>::min();
int64_t oldest = std::numeric_limits<int64_t>::max();
bool grabbed_any = false;
int first_stream_backlog = 0;
int64_t rt = 0;
pangolin::basetime start,last,now;
start = pangolin::TimeNow();
last = start;
bool got_frame = false;
do {
got_frame = src[0]->GrabNext(image+offset,false);
if(got_frame) {
if(sync_attempts_to_go >= 0) {
VideoPropertiesInterface* vidpi = dynamic_cast<VideoPropertiesInterface*>(src[0]);
if(vidpi->FrameProperties().contains(PANGO_HOST_RECEPTION_TIME_US)) {
rt = vidpi->FrameProperties()[PANGO_HOST_RECEPTION_TIME_US].get<int64_t>();
} else {
sync_attempts_to_go = -1;
pango_print_error("Stream %u in join does not support startup_sync_us option.\n", 0);
}
}
first_stream_backlog++;
grabbed_any = true;
}
} while(got_frame);
offsets.push_back(offset);
offset += src[0]->SizeBytes();
if(sync_attempts_to_go >= 0) {
reception_times.push_back(rt);
if(newest < rt) newest = rt;
if(oldest > rt) oldest = rt;
}
now = pangolin::TimeNow();
std::cout << "JOIN: Stream 1 grab: " << 1000*pangolin::TimeDiff_s(last, now) << "ms" << std::endl;
last = now;
for(size_t s=1; s<src.size(); ++s) {
for (int i=0; i<first_stream_backlog; i++){
grabbed_any |= src[s]->GrabNext(image+offset,true);
if(sync_attempts_to_go >= 0) {
VideoPropertiesInterface* vidpi = dynamic_cast<VideoPropertiesInterface*>(src[s]);
if(vidpi->FrameProperties().contains(PANGO_HOST_RECEPTION_TIME_US)) {
rt = vidpi->FrameProperties()[PANGO_HOST_RECEPTION_TIME_US].get<int64_t>();
} else {
sync_attempts_to_go = -1;
pango_print_error("Stream %lu in join does not support startup_sync_us option.\n", s);
}
}
}
offsets.push_back(offset);
offset += src[s]->SizeBytes();
if(sync_attempts_to_go >= 0) {
reception_times.push_back(rt);
if(newest < rt) newest = rt;
if(oldest > rt) oldest = rt;
}
}
now = pangolin::TimeNow();
std::cout << "JOIN: Stream 2 grab: " << 1000*pangolin::TimeDiff_s(last, now) << "ms" << std::endl;
last = now;
if((sync_continuously || (sync_attempts_to_go == 0)) && ((newest - oldest) > sync_tolerance_us) ){
pango_print_warn("Join error, unable to sync streams within %lu us\n", (unsigned long)sync_tolerance_us);
}
if(sync_attempts_to_go >= 0) {
for(size_t s=0; s<src.size(); ++s) {
if(reception_times[s] < (newest - sync_tolerance_us)) {
VideoInterface& vid = *src[s];
vid.GrabNewest(image+offsets[s],false);
}
}
if(!sync_continuously) --sync_attempts_to_go;
}
now = pangolin::TimeNow();
std::cout << "JOIN: Sync: " << 1000*pangolin::TimeDiff_s(last, now) << "ms" << std::endl;
last = now;
return grabbed_any;
}
std::vector<VideoInterface*>& VideoJoiner::InputStreams()
{
return src;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/ui/ui_layout_test.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/test/test_file_util.h"
#include "base/test/test_timeouts.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "net/base/escape.h"
#include "net/base/net_util.h"
#if defined(OS_WIN)
static const char kPlatformName[] = "chromium-win";
#elif defined(OS_MACOSX)
static const char kPlatformName[] = "chromium-mac";
#elif defined(OS_LINUX)
static const char kPlatformName[] = "chromium-linux";
#else
#error No known OS defined
#endif
static const char kTestCompleteCookie[] = "status";
UILayoutTest::UILayoutTest()
: initialized_for_layout_test_(false),
test_count_(0) {
}
UILayoutTest::~UILayoutTest() {
if (!temp_test_dir_.empty()) {
// The deletion might fail because HTTP server process might not been
// completely shut down yet and is still holding certain handle to it.
// To work around this problem, we try to repeat the deletion several
// times.
EXPECT_TRUE(file_util::DieFileDie(temp_test_dir_, true));
}
}
void UILayoutTest::InitializeForLayoutTest(const FilePath& test_parent_dir,
const FilePath& test_case_dir,
int port) {
FilePath src_dir;
PathService::Get(base::DIR_SOURCE_ROOT, &src_dir);
src_dir = src_dir.AppendASCII("chrome");
src_dir = src_dir.AppendASCII("test");
src_dir = src_dir.AppendASCII("data");
src_dir = src_dir.AppendASCII("layout_tests");
src_dir = src_dir.AppendASCII("LayoutTests");
// Gets the file path to WebKit ui layout tests, that is,
// chrome/test/data/ui_tests/LayoutTests/...
// Note that we have to use our own copy of WebKit layout tests because our
// build machines do not have WebKit layout tests added.
layout_test_dir_ = src_dir.Append(test_parent_dir);
layout_test_dir_ = layout_test_dir_.Append(test_case_dir);
ASSERT_TRUE(file_util::DirectoryExists(layout_test_dir_));
// Gets the file path to rebased expected result directory for the current
// platform.
// chrome/test/data/layout_tests/LayoutTests/platform/chromium_***/...
rebase_result_dir_ = src_dir.AppendASCII("platform");
rebase_result_dir_ = rebase_result_dir_.AppendASCII(kPlatformName);
rebase_result_dir_ = rebase_result_dir_.Append(test_parent_dir);
rebase_result_dir_ = rebase_result_dir_.Append(test_case_dir);
// Generic chromium expected results. Not OS-specific. For example,
// v8-specific differences go here.
// chrome/test/data/layout_tests/LayoutTests/platform/chromium/...
rebase_result_chromium_dir_ = src_dir.AppendASCII("platform")
.AppendASCII("chromium")
.Append(test_parent_dir)
.Append(test_case_dir);
// Gets the file path to rebased expected result directory under the
// win32 platform. This is used by other non-win32 platform to use the same
// rebased expected results.
#if !defined(OS_WIN)
rebase_result_win_dir_ = src_dir.AppendASCII("platform")
.AppendASCII("chromium-win")
.Append(test_parent_dir)
.Append(test_case_dir);
#endif
// Creates the temporary directory.
ASSERT_TRUE(file_util::CreateNewTempDirectory(
FILE_PATH_LITERAL("chrome_ui_layout_tests_"), &temp_test_dir_));
// Creates the new layout test subdirectory under the temp directory.
// Note that we have to mimic the same layout test directory structure,
// like .../LayoutTests/fast/workers/.... Otherwise those layout tests
// dealing with location property, like worker-location.html, could fail.
new_layout_test_dir_ = temp_test_dir_;
new_layout_test_dir_ = new_layout_test_dir_.AppendASCII("LayoutTests");
new_layout_test_dir_ = new_layout_test_dir_.Append(test_parent_dir);
if (port == kHttpPort) {
new_http_root_dir_ = new_layout_test_dir_;
test_case_dir_ = test_case_dir;
}
new_layout_test_dir_ = new_layout_test_dir_.Append(test_case_dir);
ASSERT_TRUE(file_util::CreateDirectory(new_layout_test_dir_));
// Copy the resource subdirectory if it exists.
FilePath layout_test_resource_path(layout_test_dir_);
layout_test_resource_path =
layout_test_resource_path.AppendASCII("resources");
FilePath new_layout_test_resource_path(new_layout_test_dir_);
new_layout_test_resource_path =
new_layout_test_resource_path.AppendASCII("resources");
file_util::CopyDirectory(layout_test_resource_path,
new_layout_test_resource_path, true);
// Copies the parent resource subdirectory. This is needed in order to run
// http layout tests.
if (port == kHttpPort) {
FilePath parent_resource_path(layout_test_dir_.DirName());
parent_resource_path = parent_resource_path.AppendASCII("resources");
FilePath new_parent_resource_path(new_layout_test_dir_.DirName());
new_parent_resource_path =
new_parent_resource_path.AppendASCII("resources");
ASSERT_TRUE(file_util::CopyDirectory(
parent_resource_path, new_parent_resource_path, true));
}
// Reads the layout test controller simulation script.
FilePath path;
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.AppendASCII("layout_tests");
path = path.AppendASCII("layout_test_controller.html");
ASSERT_TRUE(file_util::ReadFileToString(path, &layout_test_controller_));
}
void UILayoutTest::AddResourceForLayoutTest(const FilePath& parent_dir,
const FilePath& resource_name) {
FilePath root_dir;
PathService::Get(base::DIR_SOURCE_ROOT, &root_dir);
FilePath source = root_dir.AppendASCII("chrome");
source = source.AppendASCII("test");
source = source.AppendASCII("data");
source = source.AppendASCII("layout_tests");
source = source.AppendASCII("LayoutTests");
source = source.Append(parent_dir);
source = source.Append(resource_name);
ASSERT_TRUE(file_util::PathExists(source));
FilePath dest_parent_dir = temp_test_dir_.
AppendASCII("LayoutTests").Append(parent_dir);
ASSERT_TRUE(file_util::CreateDirectory(dest_parent_dir));
FilePath dest = dest_parent_dir.Append(resource_name);
if (file_util::DirectoryExists(source)) {
ASSERT_TRUE(file_util::CopyDirectory(source, dest, true));
} else {
ASSERT_TRUE(file_util::CopyFile(source, dest));
}
}
static size_t FindInsertPosition(const std::string& html) {
size_t tag_start = html.find("<html");
if (tag_start == std::string::npos)
return 0;
size_t tag_end = html.find(">", tag_start);
if (tag_end == std::string::npos)
return 0;
return tag_end + 1;
}
void UILayoutTest::RunLayoutTest(const std::string& test_case_file_name,
int port) {
base::Time start = base::Time::Now();
SCOPED_TRACE(test_case_file_name.c_str());
ASSERT_TRUE(!layout_test_controller_.empty());
// Creates a new cookie name. We will have to use a new cookie because
// this function could be called multiple times.
std::string status_cookie(kTestCompleteCookie);
status_cookie += base::IntToString(test_count_);
test_count_++;
// Reads the layout test HTML file.
FilePath test_file_path(layout_test_dir_);
test_file_path = test_file_path.AppendASCII(test_case_file_name);
std::string test_html;
ASSERT_TRUE(file_util::ReadFileToString(test_file_path, &test_html));
// Injects the layout test controller into the test HTML.
size_t insertion_position = FindInsertPosition(test_html);
test_html.insert(insertion_position, layout_test_controller_);
ReplaceFirstSubstringAfterOffset(
&test_html, insertion_position, "%COOKIE%", status_cookie.c_str());
// Creates the new layout test HTML file.
FilePath new_test_file_path(new_layout_test_dir_);
new_test_file_path = new_test_file_path.AppendASCII(test_case_file_name);
ASSERT_TRUE(file_util::WriteFile(new_test_file_path,
&test_html.at(0),
static_cast<int>(test_html.size())));
scoped_ptr<GURL> new_test_url;
if (port != kNoHttpPort)
new_test_url.reset(new GURL(
StringPrintf("http://localhost:%d/", port) +
WideToUTF8(test_case_dir_.ToWStringHack()) +
"/" +
test_case_file_name));
else
new_test_url.reset(new GURL(net::FilePathToFileURL(new_test_file_path)));
// Runs the new layout test.
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(*new_test_url.get()));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), *new_test_url.get(),
status_cookie.c_str(), TestTimeouts::action_max_timeout_ms());
// Unescapes and normalizes the actual result.
std::string value = UnescapeURLComponent(escaped_value,
UnescapeRule::NORMAL | UnescapeRule::SPACES |
UnescapeRule::URL_SPECIAL_CHARS | UnescapeRule::CONTROL_CHARS);
value += "\n";
ReplaceSubstringsAfterOffset(&value, 0, "\r", "");
// Reads the expected result. First try to read from rebase directory.
// If failed, read from original directory.
std::string expected_result_value;
if (!ReadExpectedResult(rebase_result_dir_,
test_case_file_name,
&expected_result_value) &&
!ReadExpectedResult(rebase_result_chromium_dir_,
test_case_file_name,
&expected_result_value)) {
if (rebase_result_win_dir_.empty() ||
!ReadExpectedResult(rebase_result_win_dir_,
test_case_file_name,
&expected_result_value))
ReadExpectedResult(layout_test_dir_,
test_case_file_name,
&expected_result_value);
}
ASSERT_TRUE(!expected_result_value.empty());
// Normalizes the expected result.
ReplaceSubstringsAfterOffset(&expected_result_value, 0, "\r", "");
// Compares the results.
EXPECT_STREQ(expected_result_value.c_str(), value.c_str());
VLOG(1) << "Test " << test_case_file_name
<< " took " << (base::Time::Now() - start).InMilliseconds() << "ms";
}
bool UILayoutTest::ReadExpectedResult(const FilePath& result_dir_path,
const std::string test_case_file_name,
std::string* expected_result_value) {
FilePath expected_result_path(result_dir_path);
expected_result_path = expected_result_path.AppendASCII(test_case_file_name);
expected_result_path = expected_result_path.InsertBeforeExtension(
FILE_PATH_LITERAL("-expected"));
expected_result_path =
expected_result_path.ReplaceExtension(FILE_PATH_LITERAL("txt"));
return file_util::ReadFileToString(expected_result_path,
expected_result_value);
}
<commit_msg>wstring: text case dirs are always ASCII<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/ui/ui_layout_test.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/test/test_file_util.h"
#include "base/test/test_timeouts.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "net/base/escape.h"
#include "net/base/net_util.h"
#if defined(OS_WIN)
static const char kPlatformName[] = "chromium-win";
#elif defined(OS_MACOSX)
static const char kPlatformName[] = "chromium-mac";
#elif defined(OS_LINUX)
static const char kPlatformName[] = "chromium-linux";
#else
#error No known OS defined
#endif
static const char kTestCompleteCookie[] = "status";
UILayoutTest::UILayoutTest()
: initialized_for_layout_test_(false),
test_count_(0) {
}
UILayoutTest::~UILayoutTest() {
if (!temp_test_dir_.empty()) {
// The deletion might fail because HTTP server process might not been
// completely shut down yet and is still holding certain handle to it.
// To work around this problem, we try to repeat the deletion several
// times.
EXPECT_TRUE(file_util::DieFileDie(temp_test_dir_, true));
}
}
void UILayoutTest::InitializeForLayoutTest(const FilePath& test_parent_dir,
const FilePath& test_case_dir,
int port) {
FilePath src_dir;
PathService::Get(base::DIR_SOURCE_ROOT, &src_dir);
src_dir = src_dir.AppendASCII("chrome");
src_dir = src_dir.AppendASCII("test");
src_dir = src_dir.AppendASCII("data");
src_dir = src_dir.AppendASCII("layout_tests");
src_dir = src_dir.AppendASCII("LayoutTests");
// Gets the file path to WebKit ui layout tests, that is,
// chrome/test/data/ui_tests/LayoutTests/...
// Note that we have to use our own copy of WebKit layout tests because our
// build machines do not have WebKit layout tests added.
layout_test_dir_ = src_dir.Append(test_parent_dir);
layout_test_dir_ = layout_test_dir_.Append(test_case_dir);
ASSERT_TRUE(file_util::DirectoryExists(layout_test_dir_));
// Gets the file path to rebased expected result directory for the current
// platform.
// chrome/test/data/layout_tests/LayoutTests/platform/chromium_***/...
rebase_result_dir_ = src_dir.AppendASCII("platform");
rebase_result_dir_ = rebase_result_dir_.AppendASCII(kPlatformName);
rebase_result_dir_ = rebase_result_dir_.Append(test_parent_dir);
rebase_result_dir_ = rebase_result_dir_.Append(test_case_dir);
// Generic chromium expected results. Not OS-specific. For example,
// v8-specific differences go here.
// chrome/test/data/layout_tests/LayoutTests/platform/chromium/...
rebase_result_chromium_dir_ = src_dir.AppendASCII("platform")
.AppendASCII("chromium")
.Append(test_parent_dir)
.Append(test_case_dir);
// Gets the file path to rebased expected result directory under the
// win32 platform. This is used by other non-win32 platform to use the same
// rebased expected results.
#if !defined(OS_WIN)
rebase_result_win_dir_ = src_dir.AppendASCII("platform")
.AppendASCII("chromium-win")
.Append(test_parent_dir)
.Append(test_case_dir);
#endif
// Creates the temporary directory.
ASSERT_TRUE(file_util::CreateNewTempDirectory(
FILE_PATH_LITERAL("chrome_ui_layout_tests_"), &temp_test_dir_));
// Creates the new layout test subdirectory under the temp directory.
// Note that we have to mimic the same layout test directory structure,
// like .../LayoutTests/fast/workers/.... Otherwise those layout tests
// dealing with location property, like worker-location.html, could fail.
new_layout_test_dir_ = temp_test_dir_;
new_layout_test_dir_ = new_layout_test_dir_.AppendASCII("LayoutTests");
new_layout_test_dir_ = new_layout_test_dir_.Append(test_parent_dir);
if (port == kHttpPort) {
new_http_root_dir_ = new_layout_test_dir_;
test_case_dir_ = test_case_dir;
}
new_layout_test_dir_ = new_layout_test_dir_.Append(test_case_dir);
ASSERT_TRUE(file_util::CreateDirectory(new_layout_test_dir_));
// Copy the resource subdirectory if it exists.
FilePath layout_test_resource_path(layout_test_dir_);
layout_test_resource_path =
layout_test_resource_path.AppendASCII("resources");
FilePath new_layout_test_resource_path(new_layout_test_dir_);
new_layout_test_resource_path =
new_layout_test_resource_path.AppendASCII("resources");
file_util::CopyDirectory(layout_test_resource_path,
new_layout_test_resource_path, true);
// Copies the parent resource subdirectory. This is needed in order to run
// http layout tests.
if (port == kHttpPort) {
FilePath parent_resource_path(layout_test_dir_.DirName());
parent_resource_path = parent_resource_path.AppendASCII("resources");
FilePath new_parent_resource_path(new_layout_test_dir_.DirName());
new_parent_resource_path =
new_parent_resource_path.AppendASCII("resources");
ASSERT_TRUE(file_util::CopyDirectory(
parent_resource_path, new_parent_resource_path, true));
}
// Reads the layout test controller simulation script.
FilePath path;
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.AppendASCII("layout_tests");
path = path.AppendASCII("layout_test_controller.html");
ASSERT_TRUE(file_util::ReadFileToString(path, &layout_test_controller_));
}
void UILayoutTest::AddResourceForLayoutTest(const FilePath& parent_dir,
const FilePath& resource_name) {
FilePath root_dir;
PathService::Get(base::DIR_SOURCE_ROOT, &root_dir);
FilePath source = root_dir.AppendASCII("chrome");
source = source.AppendASCII("test");
source = source.AppendASCII("data");
source = source.AppendASCII("layout_tests");
source = source.AppendASCII("LayoutTests");
source = source.Append(parent_dir);
source = source.Append(resource_name);
ASSERT_TRUE(file_util::PathExists(source));
FilePath dest_parent_dir = temp_test_dir_.
AppendASCII("LayoutTests").Append(parent_dir);
ASSERT_TRUE(file_util::CreateDirectory(dest_parent_dir));
FilePath dest = dest_parent_dir.Append(resource_name);
if (file_util::DirectoryExists(source)) {
ASSERT_TRUE(file_util::CopyDirectory(source, dest, true));
} else {
ASSERT_TRUE(file_util::CopyFile(source, dest));
}
}
static size_t FindInsertPosition(const std::string& html) {
size_t tag_start = html.find("<html");
if (tag_start == std::string::npos)
return 0;
size_t tag_end = html.find(">", tag_start);
if (tag_end == std::string::npos)
return 0;
return tag_end + 1;
}
void UILayoutTest::RunLayoutTest(const std::string& test_case_file_name,
int port) {
base::Time start = base::Time::Now();
SCOPED_TRACE(test_case_file_name.c_str());
ASSERT_TRUE(!layout_test_controller_.empty());
// Creates a new cookie name. We will have to use a new cookie because
// this function could be called multiple times.
std::string status_cookie(kTestCompleteCookie);
status_cookie += base::IntToString(test_count_);
test_count_++;
// Reads the layout test HTML file.
FilePath test_file_path(layout_test_dir_);
test_file_path = test_file_path.AppendASCII(test_case_file_name);
std::string test_html;
ASSERT_TRUE(file_util::ReadFileToString(test_file_path, &test_html));
// Injects the layout test controller into the test HTML.
size_t insertion_position = FindInsertPosition(test_html);
test_html.insert(insertion_position, layout_test_controller_);
ReplaceFirstSubstringAfterOffset(
&test_html, insertion_position, "%COOKIE%", status_cookie.c_str());
// Creates the new layout test HTML file.
FilePath new_test_file_path(new_layout_test_dir_);
new_test_file_path = new_test_file_path.AppendASCII(test_case_file_name);
ASSERT_TRUE(file_util::WriteFile(new_test_file_path,
&test_html.at(0),
static_cast<int>(test_html.size())));
// We expect the test case dir to be ASCII. It might be empty, so we
// can't test whether MaybeAsASCII succeeded, but the tests will fail
// loudly in that case anyway.
std::string url_path = test_case_dir_.MaybeAsASCII();
scoped_ptr<GURL> new_test_url;
if (port != kNoHttpPort)
new_test_url.reset(new GURL(
StringPrintf("http://localhost:%d/", port) +
url_path + "/" + test_case_file_name));
else
new_test_url.reset(new GURL(net::FilePathToFileURL(new_test_file_path)));
// Runs the new layout test.
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
ASSERT_TRUE(tab->NavigateToURL(*new_test_url.get()));
std::string escaped_value =
WaitUntilCookieNonEmpty(tab.get(), *new_test_url.get(),
status_cookie.c_str(), TestTimeouts::action_max_timeout_ms());
// Unescapes and normalizes the actual result.
std::string value = UnescapeURLComponent(escaped_value,
UnescapeRule::NORMAL | UnescapeRule::SPACES |
UnescapeRule::URL_SPECIAL_CHARS | UnescapeRule::CONTROL_CHARS);
value += "\n";
ReplaceSubstringsAfterOffset(&value, 0, "\r", "");
// Reads the expected result. First try to read from rebase directory.
// If failed, read from original directory.
std::string expected_result_value;
if (!ReadExpectedResult(rebase_result_dir_,
test_case_file_name,
&expected_result_value) &&
!ReadExpectedResult(rebase_result_chromium_dir_,
test_case_file_name,
&expected_result_value)) {
if (rebase_result_win_dir_.empty() ||
!ReadExpectedResult(rebase_result_win_dir_,
test_case_file_name,
&expected_result_value))
ReadExpectedResult(layout_test_dir_,
test_case_file_name,
&expected_result_value);
}
ASSERT_TRUE(!expected_result_value.empty());
// Normalizes the expected result.
ReplaceSubstringsAfterOffset(&expected_result_value, 0, "\r", "");
// Compares the results.
EXPECT_STREQ(expected_result_value.c_str(), value.c_str());
VLOG(1) << "Test " << test_case_file_name
<< " took " << (base::Time::Now() - start).InMilliseconds() << "ms";
}
bool UILayoutTest::ReadExpectedResult(const FilePath& result_dir_path,
const std::string test_case_file_name,
std::string* expected_result_value) {
FilePath expected_result_path(result_dir_path);
expected_result_path = expected_result_path.AppendASCII(test_case_file_name);
expected_result_path = expected_result_path.InsertBeforeExtension(
FILE_PATH_LITERAL("-expected"));
expected_result_path =
expected_result_path.ReplaceExtension(FILE_PATH_LITERAL("txt"));
return file_util::ReadFileToString(expected_result_path,
expected_result_value);
}
<|endoftext|> |
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2016 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "runtimes/libjoynr-runtime/LibJoynrRuntime.h"
#include <cassert>
#include <vector>
#include "joynr/Dispatcher.h"
#include "joynr/InProcessDispatcher.h"
#include "joynr/system/RoutingTypes/CommonApiDbusAddress.h"
#include "joynr/PublicationManager.h"
#include "joynr/SubscriptionManager.h"
#include "joynr/InProcessPublicationSender.h"
#include "joynr/JoynrMessageSender.h"
#include "joynr/MessageRouter.h"
#include "libjoynr/in-process/InProcessLibJoynrMessagingSkeleton.h"
#include "joynr/InProcessMessagingAddress.h"
#include "joynr/MessagingStubFactory.h"
#include "libjoynr/in-process/InProcessMessagingStubFactory.h"
#include "joynr/system/DiscoveryProxy.h"
#include "joynr/TypeUtil.h"
#include "joynr/Util.h"
#include "joynr/Settings.h"
#include "joynr/SingleThreadedIOService.h"
namespace joynr
{
LibJoynrRuntime::LibJoynrRuntime(Settings* settings)
: JoynrRuntime(*settings),
subscriptionManager(nullptr),
inProcessPublicationSender(nullptr),
inProcessConnectorFactory(nullptr),
joynrMessagingConnectorFactory(nullptr),
joynrMessagingSendStub(nullptr),
joynrMessageSender(nullptr),
joynrDispatcher(nullptr),
inProcessDispatcher(nullptr),
settings(settings),
libjoynrSettings(new LibjoynrSettings(*settings)),
dispatcherMessagingSkeleton(nullptr),
runtimeExecutor(nullptr)
{
libjoynrSettings->printSettings();
}
LibJoynrRuntime::~LibJoynrRuntime()
{
delete proxyFactory;
delete inProcessDispatcher;
delete joynrMessageSender;
delete joynrDispatcher;
delete libjoynrSettings;
libjoynrSettings = nullptr;
delete settings;
}
void LibJoynrRuntime::init(
std::shared_ptr<IMiddlewareMessagingStubFactory> middlewareMessagingStubFactory,
std::shared_ptr<const joynr::system::RoutingTypes::Address> libjoynrMessagingAddress,
std::shared_ptr<const joynr::system::RoutingTypes::Address> ccMessagingAddress)
{
// create messaging stub factory
auto messagingStubFactory = std::make_shared<MessagingStubFactory>();
middlewareMessagingStubFactory->registerOnMessagingStubClosedCallback([messagingStubFactory](
const std::shared_ptr<const joynr::system::RoutingTypes::Address>& destinationAddress) {
messagingStubFactory->remove(destinationAddress);
});
messagingStubFactory->registerStubFactory(middlewareMessagingStubFactory);
messagingStubFactory->registerStubFactory(std::make_shared<InProcessMessagingStubFactory>());
// create message router
messageRouter = std::make_shared<MessageRouter>(std::move(messagingStubFactory),
libjoynrMessagingAddress,
singleThreadIOService->getIOService());
messageRouter->loadRoutingTable(libjoynrSettings->getMessageRouterPersistenceFilename());
startLibJoynrMessagingSkeleton(messageRouter);
joynrMessageSender = new JoynrMessageSender(messageRouter);
joynrDispatcher = new Dispatcher(joynrMessageSender, singleThreadIOService->getIOService());
joynrMessageSender->registerDispatcher(joynrDispatcher);
// create the inprocess skeleton for the dispatcher
dispatcherMessagingSkeleton =
std::make_shared<InProcessLibJoynrMessagingSkeleton>(joynrDispatcher);
dispatcherAddress = std::make_shared<InProcessMessagingAddress>(dispatcherMessagingSkeleton);
publicationManager = new PublicationManager(singleThreadIOService->getIOService());
publicationManager->loadSavedAttributeSubscriptionRequestsMap(
libjoynrSettings->getSubscriptionRequestPersistenceFilename());
publicationManager->loadSavedBroadcastSubscriptionRequestsMap(
libjoynrSettings->getBroadcastSubscriptionRequestPersistenceFilename());
subscriptionManager = new SubscriptionManager(singleThreadIOService->getIOService());
inProcessDispatcher = new InProcessDispatcher(singleThreadIOService->getIOService());
inProcessPublicationSender = new InProcessPublicationSender(subscriptionManager);
inProcessConnectorFactory = new InProcessConnectorFactory(
subscriptionManager,
publicationManager,
inProcessPublicationSender,
dynamic_cast<IRequestCallerDirectory*>(inProcessDispatcher));
joynrMessagingConnectorFactory =
new JoynrMessagingConnectorFactory(joynrMessageSender, subscriptionManager);
auto connectorFactory = std::make_unique<ConnectorFactory>(
inProcessConnectorFactory, joynrMessagingConnectorFactory);
proxyFactory = new ProxyFactory(libjoynrMessagingAddress, std::move(connectorFactory), nullptr);
// Set up the persistence file for storing provider participant ids
std::string persistenceFilename = libjoynrSettings->getParticipantIdsPersistenceFilename();
participantIdStorage = std::make_shared<ParticipantIdStorage>(persistenceFilename);
// initialize the dispatchers
std::vector<IDispatcher*> dispatcherList;
dispatcherList.push_back(inProcessDispatcher);
dispatcherList.push_back(joynrDispatcher);
joynrDispatcher->registerPublicationManager(publicationManager);
joynrDispatcher->registerSubscriptionManager(subscriptionManager);
discoveryProxy = std::make_unique<LocalDiscoveryAggregator>(systemServicesSettings);
requestCallerDirectory = dynamic_cast<IRequestCallerDirectory*>(inProcessDispatcher);
std::string systemServicesDomain = systemServicesSettings.getDomain();
std::string routingProviderParticipantId =
systemServicesSettings.getCcRoutingProviderParticipantId();
DiscoveryQos routingProviderDiscoveryQos;
routingProviderDiscoveryQos.setCacheMaxAgeMs(1000);
routingProviderDiscoveryQos.setArbitrationStrategy(
DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT);
routingProviderDiscoveryQos.addCustomParameter(
"fixedParticipantId", routingProviderParticipantId);
routingProviderDiscoveryQos.setDiscoveryTimeoutMs(50);
std::unique_ptr<ProxyBuilder<joynr::system::RoutingProxy>> routingProxyBuilder(
createProxyBuilder<joynr::system::RoutingProxy>(systemServicesDomain));
auto routingProxy = routingProxyBuilder->setMessagingQos(MessagingQos(10000))
->setCached(false)
->setDiscoveryQos(routingProviderDiscoveryQos)
->build();
messageRouter->setParentRouter(std::unique_ptr<system::RoutingProxy>(routingProxy),
ccMessagingAddress,
routingProviderParticipantId);
// setup discovery
std::string discoveryProviderParticipantId =
systemServicesSettings.getCcDiscoveryProviderParticipantId();
DiscoveryQos discoveryProviderDiscoveryQos;
discoveryProviderDiscoveryQos.setCacheMaxAgeMs(1000);
discoveryProviderDiscoveryQos.setArbitrationStrategy(
DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT);
discoveryProviderDiscoveryQos.addCustomParameter(
"fixedParticipantId", discoveryProviderParticipantId);
discoveryProviderDiscoveryQos.setDiscoveryTimeoutMs(1000);
std::unique_ptr<ProxyBuilder<joynr::system::DiscoveryProxy>> discoveryProxyBuilder(
createProxyBuilder<joynr::system::DiscoveryProxy>(systemServicesDomain));
joynr::system::IDiscoverySync* proxy =
discoveryProxyBuilder->setMessagingQos(MessagingQos(40000))
->setCached(false)
->setDiscoveryQos(discoveryProviderDiscoveryQos)
->build();
discoveryProxy->setDiscoveryProxy(std::unique_ptr<joynr::system::IDiscoverySync>(proxy));
capabilitiesRegistrar = std::make_unique<CapabilitiesRegistrar>(
dispatcherList,
*discoveryProxy,
participantIdStorage,
dispatcherAddress,
messageRouter,
messagingSettings.getDiscoveryEntryExpiryIntervalMs());
}
void LibJoynrRuntime::unregisterProvider(const std::string& participantId)
{
assert(capabilitiesRegistrar);
capabilitiesRegistrar->remove(participantId);
}
void LibJoynrRuntime::setRuntimeExecutor(JoynrRuntimeExecutor* runtimeExecutor)
{
this->runtimeExecutor = std::unique_ptr<JoynrRuntimeExecutor>(runtimeExecutor);
}
LibJoynrRuntime* LibJoynrRuntime::create(JoynrRuntimeExecutor* runtimeExecutor)
{
LibJoynrRuntime* runtime = runtimeExecutor->getRuntime();
runtime->setRuntimeExecutor(runtimeExecutor);
return runtime;
}
} // namespace joynr
<commit_msg>[C++] Avoid duplicate delete of settings object<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2016 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "runtimes/libjoynr-runtime/LibJoynrRuntime.h"
#include <cassert>
#include <vector>
#include "joynr/Dispatcher.h"
#include "joynr/InProcessDispatcher.h"
#include "joynr/system/RoutingTypes/CommonApiDbusAddress.h"
#include "joynr/PublicationManager.h"
#include "joynr/SubscriptionManager.h"
#include "joynr/InProcessPublicationSender.h"
#include "joynr/JoynrMessageSender.h"
#include "joynr/MessageRouter.h"
#include "libjoynr/in-process/InProcessLibJoynrMessagingSkeleton.h"
#include "joynr/InProcessMessagingAddress.h"
#include "joynr/MessagingStubFactory.h"
#include "libjoynr/in-process/InProcessMessagingStubFactory.h"
#include "joynr/system/DiscoveryProxy.h"
#include "joynr/TypeUtil.h"
#include "joynr/Util.h"
#include "joynr/Settings.h"
#include "joynr/SingleThreadedIOService.h"
namespace joynr
{
LibJoynrRuntime::LibJoynrRuntime(Settings* settings)
: JoynrRuntime(*settings),
subscriptionManager(nullptr),
inProcessPublicationSender(nullptr),
inProcessConnectorFactory(nullptr),
joynrMessagingConnectorFactory(nullptr),
joynrMessagingSendStub(nullptr),
joynrMessageSender(nullptr),
joynrDispatcher(nullptr),
inProcessDispatcher(nullptr),
settings(settings),
libjoynrSettings(new LibjoynrSettings(*settings)),
dispatcherMessagingSkeleton(nullptr),
runtimeExecutor(nullptr)
{
libjoynrSettings->printSettings();
}
LibJoynrRuntime::~LibJoynrRuntime()
{
delete proxyFactory;
delete inProcessDispatcher;
delete joynrMessageSender;
delete joynrDispatcher;
delete libjoynrSettings;
libjoynrSettings = nullptr;
}
void LibJoynrRuntime::init(
std::shared_ptr<IMiddlewareMessagingStubFactory> middlewareMessagingStubFactory,
std::shared_ptr<const joynr::system::RoutingTypes::Address> libjoynrMessagingAddress,
std::shared_ptr<const joynr::system::RoutingTypes::Address> ccMessagingAddress)
{
// create messaging stub factory
auto messagingStubFactory = std::make_shared<MessagingStubFactory>();
middlewareMessagingStubFactory->registerOnMessagingStubClosedCallback([messagingStubFactory](
const std::shared_ptr<const joynr::system::RoutingTypes::Address>& destinationAddress) {
messagingStubFactory->remove(destinationAddress);
});
messagingStubFactory->registerStubFactory(middlewareMessagingStubFactory);
messagingStubFactory->registerStubFactory(std::make_shared<InProcessMessagingStubFactory>());
// create message router
messageRouter = std::make_shared<MessageRouter>(std::move(messagingStubFactory),
libjoynrMessagingAddress,
singleThreadIOService->getIOService());
messageRouter->loadRoutingTable(libjoynrSettings->getMessageRouterPersistenceFilename());
startLibJoynrMessagingSkeleton(messageRouter);
joynrMessageSender = new JoynrMessageSender(messageRouter);
joynrDispatcher = new Dispatcher(joynrMessageSender, singleThreadIOService->getIOService());
joynrMessageSender->registerDispatcher(joynrDispatcher);
// create the inprocess skeleton for the dispatcher
dispatcherMessagingSkeleton =
std::make_shared<InProcessLibJoynrMessagingSkeleton>(joynrDispatcher);
dispatcherAddress = std::make_shared<InProcessMessagingAddress>(dispatcherMessagingSkeleton);
publicationManager = new PublicationManager(singleThreadIOService->getIOService());
publicationManager->loadSavedAttributeSubscriptionRequestsMap(
libjoynrSettings->getSubscriptionRequestPersistenceFilename());
publicationManager->loadSavedBroadcastSubscriptionRequestsMap(
libjoynrSettings->getBroadcastSubscriptionRequestPersistenceFilename());
subscriptionManager = new SubscriptionManager(singleThreadIOService->getIOService());
inProcessDispatcher = new InProcessDispatcher(singleThreadIOService->getIOService());
inProcessPublicationSender = new InProcessPublicationSender(subscriptionManager);
inProcessConnectorFactory = new InProcessConnectorFactory(
subscriptionManager,
publicationManager,
inProcessPublicationSender,
dynamic_cast<IRequestCallerDirectory*>(inProcessDispatcher));
joynrMessagingConnectorFactory =
new JoynrMessagingConnectorFactory(joynrMessageSender, subscriptionManager);
auto connectorFactory = std::make_unique<ConnectorFactory>(
inProcessConnectorFactory, joynrMessagingConnectorFactory);
proxyFactory = new ProxyFactory(libjoynrMessagingAddress, std::move(connectorFactory), nullptr);
// Set up the persistence file for storing provider participant ids
std::string persistenceFilename = libjoynrSettings->getParticipantIdsPersistenceFilename();
participantIdStorage = std::make_shared<ParticipantIdStorage>(persistenceFilename);
// initialize the dispatchers
std::vector<IDispatcher*> dispatcherList;
dispatcherList.push_back(inProcessDispatcher);
dispatcherList.push_back(joynrDispatcher);
joynrDispatcher->registerPublicationManager(publicationManager);
joynrDispatcher->registerSubscriptionManager(subscriptionManager);
discoveryProxy = std::make_unique<LocalDiscoveryAggregator>(systemServicesSettings);
requestCallerDirectory = dynamic_cast<IRequestCallerDirectory*>(inProcessDispatcher);
std::string systemServicesDomain = systemServicesSettings.getDomain();
std::string routingProviderParticipantId =
systemServicesSettings.getCcRoutingProviderParticipantId();
DiscoveryQos routingProviderDiscoveryQos;
routingProviderDiscoveryQos.setCacheMaxAgeMs(1000);
routingProviderDiscoveryQos.setArbitrationStrategy(
DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT);
routingProviderDiscoveryQos.addCustomParameter(
"fixedParticipantId", routingProviderParticipantId);
routingProviderDiscoveryQos.setDiscoveryTimeoutMs(50);
std::unique_ptr<ProxyBuilder<joynr::system::RoutingProxy>> routingProxyBuilder(
createProxyBuilder<joynr::system::RoutingProxy>(systemServicesDomain));
auto routingProxy = routingProxyBuilder->setMessagingQos(MessagingQos(10000))
->setCached(false)
->setDiscoveryQos(routingProviderDiscoveryQos)
->build();
messageRouter->setParentRouter(std::unique_ptr<system::RoutingProxy>(routingProxy),
ccMessagingAddress,
routingProviderParticipantId);
// setup discovery
std::string discoveryProviderParticipantId =
systemServicesSettings.getCcDiscoveryProviderParticipantId();
DiscoveryQos discoveryProviderDiscoveryQos;
discoveryProviderDiscoveryQos.setCacheMaxAgeMs(1000);
discoveryProviderDiscoveryQos.setArbitrationStrategy(
DiscoveryQos::ArbitrationStrategy::FIXED_PARTICIPANT);
discoveryProviderDiscoveryQos.addCustomParameter(
"fixedParticipantId", discoveryProviderParticipantId);
discoveryProviderDiscoveryQos.setDiscoveryTimeoutMs(1000);
std::unique_ptr<ProxyBuilder<joynr::system::DiscoveryProxy>> discoveryProxyBuilder(
createProxyBuilder<joynr::system::DiscoveryProxy>(systemServicesDomain));
joynr::system::IDiscoverySync* proxy =
discoveryProxyBuilder->setMessagingQos(MessagingQos(40000))
->setCached(false)
->setDiscoveryQos(discoveryProviderDiscoveryQos)
->build();
discoveryProxy->setDiscoveryProxy(std::unique_ptr<joynr::system::IDiscoverySync>(proxy));
capabilitiesRegistrar = std::make_unique<CapabilitiesRegistrar>(
dispatcherList,
*discoveryProxy,
participantIdStorage,
dispatcherAddress,
messageRouter,
messagingSettings.getDiscoveryEntryExpiryIntervalMs());
}
void LibJoynrRuntime::unregisterProvider(const std::string& participantId)
{
assert(capabilitiesRegistrar);
capabilitiesRegistrar->remove(participantId);
}
void LibJoynrRuntime::setRuntimeExecutor(JoynrRuntimeExecutor* runtimeExecutor)
{
this->runtimeExecutor = std::unique_ptr<JoynrRuntimeExecutor>(runtimeExecutor);
}
LibJoynrRuntime* LibJoynrRuntime::create(JoynrRuntimeExecutor* runtimeExecutor)
{
LibJoynrRuntime* runtime = runtimeExecutor->getRuntime();
runtime->setRuntimeExecutor(runtimeExecutor);
return runtime;
}
} // namespace joynr
<|endoftext|> |
<commit_before>/*********************************************************************************
* Copyright (c) 2013 David D. Marshall <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David D. Marshall - initial code and implementation
********************************************************************************/
#ifndef piecewise_four_digit_creator_test_suite_hpp
#define piecewise_four_digit_creator_test_suite_hpp
#include "eli/code_eli.hpp"
#include "eli/constants/math.hpp"
#include "eli/mutil/fd/d1o2.hpp"
#include "eli/mutil/fd/d2o2.hpp"
#include "eli/geom/curve/piecewise.hpp"
#include "eli/geom/curve/piecewise_four_digit_creator.hpp"
#include <cmath> // std::pow, std::exp
#include <cassert> // assert()
#include <typeinfo> // typeid
#include <string> // std::string
#include <sstream> // std::stringstream
#include <iomanip> // std::setw
#include <limits> // std::numeric_limits
template<typename data__>
class piecewise_four_digit_creator_test_suite : public Test::Suite
{
private:
typedef eli::geom::curve::piecewise<eli::geom::curve::bezier, data__, 3> piecewise_curve_type;
typedef typename piecewise_curve_type::curve_type curve_type;
typedef typename piecewise_curve_type::point_type point_type;
typedef typename piecewise_curve_type::data_type data_type;
typedef typename piecewise_curve_type::index_type index_type;
typedef typename piecewise_curve_type::tolerance_type tolerance_type;
typedef eli::geom::curve::piecewise_four_digit_creator<data__, 3, tolerance_type> point_creator_type;
tolerance_type tol;
protected:
void AddTests(const float &)
{
// add the tests
TEST_ADD(piecewise_four_digit_creator_test_suite<float>::create_airfoil_test);
}
void AddTests(const double &)
{
// add the tests
TEST_ADD(piecewise_four_digit_creator_test_suite<double>::create_airfoil_test);
}
void AddTests(const long double &)
{
// add the tests
TEST_ADD(piecewise_four_digit_creator_test_suite<long double>::create_airfoil_test);
}
public:
piecewise_four_digit_creator_test_suite() : tol()
{
AddTests(data__());
}
~piecewise_four_digit_creator_test_suite()
{
}
private:
void octave_print(int figno, const piecewise_curve_type &pc) const
{
index_type i, pp, ns;
data_type tmin, tmax;
ns=pc.number_segments();
pc.get_parameter_min(tmin);
pc.get_parameter_max(tmax);
std::cout << "figure(" << figno << ");" << std::endl;
// get control points and print
std::cout << "cp_x=[";
for (pp=0; pp<ns; ++pp)
{
curve_type bez;
pc.get(bez, pp);
for (i=0; i<=bez.degree(); ++i)
{
std::cout << bez.get_control_point(i).x();
if (i<bez.degree())
std::cout << ", ";
else if (pp<ns-1)
std::cout << "; ";
}
std::cout << std::endl;
}
std::cout << "];" << std::endl;
std::cout << "cp_y=[";
for (pp=0; pp<ns; ++pp)
{
curve_type bez;
pc.get(bez, pp);
for (i=0; i<=bez.degree(); ++i)
{
std::cout << bez.get_control_point(i).y();
if (i<bez.degree())
std::cout << ", ";
else if (pp<ns-1)
std::cout << "; ";
}
std::cout << std::endl;
}
std::cout << "];" << std::endl;
std::cout << "cp_z=[";
for (pp=0; pp<ns; ++pp)
{
curve_type bez;
pc.get(bez, pp);
for (i=0; i<=bez.degree(); ++i)
{
std::cout << bez.get_control_point(i).z();
if (i<bez.degree())
std::cout << ", ";
else if (pp<ns-1)
std::cout << "; ";
}
std::cout << std::endl;
}
std::cout << "];" << std::endl;
// initialize the t parameters
std::vector<data__> t(129);
for (i=0; i<static_cast<index_type>(t.size()); ++i)
{
t[i]=tmin+(tmax-tmin)*static_cast<data__>(i)/(t.size()-1);
}
// set the surface points
std::cout << "surf_x=[";
for (i=0; i<static_cast<index_type>(t.size()); ++i)
{
std::cout << pc.f(t[i]).x();
if (i<static_cast<index_type>(t.size()-1))
std::cout << ", ";
}
std::cout << "];" << std::endl;
std::cout << "surf_y=[";
for (i=0; i<static_cast<index_type>(t.size()); ++i)
{
std::cout << pc.f(t[i]).y();
if (i<static_cast<index_type>(t.size()-1))
std::cout << ", ";
}
std::cout << "];" << std::endl;
std::cout << "surf_z=[";
for (i=0; i<static_cast<index_type>(t.size()); ++i)
{
std::cout << pc.f(t[i]).z();
if (i<static_cast<index_type>(t.size()-1))
std::cout << ", ";
}
std::cout << "];" << std::endl;
std::cout << "setenv('GNUTERM', 'x11');" << std::endl;
std::cout << "plot3(surf_x, surf_y, surf_z, '-k');" << std::endl;
std::cout << "hold on;" << std::endl;
std::cout << "plot3(cp_x', cp_y', cp_z', '-ok', 'MarkerFaceColor', [0 0 0]);" << std::endl;
std::cout << "hold off;" << std::endl;
}
void create_airfoil_test()
{
#if 0
airfoil_type af;
data_type th, cam, cam_loc;
bool rtn;
// set airfoil thickness
th=24;
rtn=af.set_thickness(th);
TEST_ASSERT(rtn);
TEST_ASSERT(af.get_thickness()==th);
// set airfoil camber
cam=2;
cam_loc=3;
rtn=af.set_camber(cam, cam_loc);
TEST_ASSERT(rtn);
TEST_ASSERT(af.get_maximum_camber()==cam);
TEST_ASSERT(af.get_maximum_camber_location()==cam_loc);
// test the name
std::string name, name_ref;
name_ref="NACA "+std::to_string((int)round(cam))+std::to_string((int)round(cam_loc))+std::to_string((int)round(th));
name=af.get_name();
TEST_ASSERT(name==name_ref);
#endif
}
};
#endif
<commit_msg>Make 4-digit airfoil test plots in 2D<commit_after>/*********************************************************************************
* Copyright (c) 2013 David D. Marshall <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David D. Marshall - initial code and implementation
********************************************************************************/
#ifndef piecewise_four_digit_creator_test_suite_hpp
#define piecewise_four_digit_creator_test_suite_hpp
#include "eli/code_eli.hpp"
#include "eli/constants/math.hpp"
#include "eli/mutil/fd/d1o2.hpp"
#include "eli/mutil/fd/d2o2.hpp"
#include "eli/geom/curve/piecewise.hpp"
#include "eli/geom/curve/piecewise_four_digit_creator.hpp"
#include <cmath> // std::pow, std::exp
#include <cassert> // assert()
#include <typeinfo> // typeid
#include <string> // std::string
#include <sstream> // std::stringstream
#include <iomanip> // std::setw
#include <limits> // std::numeric_limits
template<typename data__>
class piecewise_four_digit_creator_test_suite : public Test::Suite
{
private:
typedef eli::geom::curve::piecewise<eli::geom::curve::bezier, data__, 3> piecewise_curve_type;
typedef typename piecewise_curve_type::curve_type curve_type;
typedef typename piecewise_curve_type::point_type point_type;
typedef typename piecewise_curve_type::data_type data_type;
typedef typename piecewise_curve_type::index_type index_type;
typedef typename piecewise_curve_type::tolerance_type tolerance_type;
typedef eli::geom::curve::piecewise_four_digit_creator<data__, 3, tolerance_type> point_creator_type;
tolerance_type tol;
protected:
void AddTests(const float &)
{
// add the tests
TEST_ADD(piecewise_four_digit_creator_test_suite<float>::create_airfoil_test);
}
void AddTests(const double &)
{
// add the tests
TEST_ADD(piecewise_four_digit_creator_test_suite<double>::create_airfoil_test);
}
void AddTests(const long double &)
{
// add the tests
TEST_ADD(piecewise_four_digit_creator_test_suite<long double>::create_airfoil_test);
}
public:
piecewise_four_digit_creator_test_suite() : tol()
{
AddTests(data__());
}
~piecewise_four_digit_creator_test_suite()
{
}
private:
void octave_print(int figno, const piecewise_curve_type &pc) const
{
index_type i, pp, ns;
data_type tmin, tmax;
ns=pc.number_segments();
pc.get_parameter_min(tmin);
pc.get_parameter_max(tmax);
std::cout << "figure(" << figno << ");" << std::endl;
// get control points and print
std::cout << "cp_x=[";
for (pp=0; pp<ns; ++pp)
{
curve_type bez;
pc.get(bez, pp);
for (i=0; i<=bez.degree(); ++i)
{
std::cout << bez.get_control_point(i).x();
if (i<bez.degree())
std::cout << ", ";
else if (pp<ns-1)
std::cout << "; ";
}
std::cout << std::endl;
}
std::cout << "];" << std::endl;
std::cout << "cp_y=[";
for (pp=0; pp<ns; ++pp)
{
curve_type bez;
pc.get(bez, pp);
for (i=0; i<=bez.degree(); ++i)
{
std::cout << bez.get_control_point(i).y();
if (i<bez.degree())
std::cout << ", ";
else if (pp<ns-1)
std::cout << "; ";
}
std::cout << std::endl;
}
std::cout << "];" << std::endl;
std::cout << "cp_z=[";
for (pp=0; pp<ns; ++pp)
{
curve_type bez;
pc.get(bez, pp);
for (i=0; i<=bez.degree(); ++i)
{
std::cout << bez.get_control_point(i).z();
if (i<bez.degree())
std::cout << ", ";
else if (pp<ns-1)
std::cout << "; ";
}
std::cout << std::endl;
}
std::cout << "];" << std::endl;
// initialize the t parameters
std::vector<data__> t(129);
for (i=0; i<static_cast<index_type>(t.size()); ++i)
{
t[i]=tmin+(tmax-tmin)*static_cast<data__>(i)/(t.size()-1);
}
// set the surface points
std::cout << "surf_x=[";
for (i=0; i<static_cast<index_type>(t.size()); ++i)
{
std::cout << pc.f(t[i]).x();
if (i<static_cast<index_type>(t.size()-1))
std::cout << ", ";
}
std::cout << "];" << std::endl;
std::cout << "surf_y=[";
for (i=0; i<static_cast<index_type>(t.size()); ++i)
{
std::cout << pc.f(t[i]).y();
if (i<static_cast<index_type>(t.size()-1))
std::cout << ", ";
}
std::cout << "];" << std::endl;
std::cout << "surf_z=[";
for (i=0; i<static_cast<index_type>(t.size()); ++i)
{
std::cout << pc.f(t[i]).z();
if (i<static_cast<index_type>(t.size()-1))
std::cout << ", ";
}
std::cout << "];" << std::endl;
std::cout << "setenv('GNUTERM', 'x11');" << std::endl;
std::cout << "plot(surf_x, surf_y, '-k');" << std::endl;
std::cout << "hold on;" << std::endl;
std::cout << "plot(cp_x', cp_y', '-ok', 'MarkerFaceColor', [0 0 0]);" << std::endl;
std::cout << "hold off;" << std::endl;
std::cout << "axis equal;" << std::endl;
}
void create_airfoil_test()
{
#if 0
airfoil_type af;
data_type th, cam, cam_loc;
bool rtn;
// set airfoil thickness
th=24;
rtn=af.set_thickness(th);
TEST_ASSERT(rtn);
TEST_ASSERT(af.get_thickness()==th);
// set airfoil camber
cam=2;
cam_loc=3;
rtn=af.set_camber(cam, cam_loc);
TEST_ASSERT(rtn);
TEST_ASSERT(af.get_maximum_camber()==cam);
TEST_ASSERT(af.get_maximum_camber_location()==cam_loc);
// test the name
std::string name, name_ref;
name_ref="NACA "+std::to_string((int)round(cam))+std::to_string((int)round(cam_loc))+std::to_string((int)round(th));
name=af.get_name();
TEST_ASSERT(name==name_ref);
#endif
}
};
#endif
<|endoftext|> |
<commit_before>#include <botan/botan.h>
#include <botan/tls_server.h>
#include <botan/rsa.h>
#include <botan/dsa.h>
#include <botan/x509self.h>
#include <botan/secqueue.h>
#include "socket.h"
using namespace Botan;
#include <stdio.h>
#include <string>
#include <iostream>
#include <memory>
class Blocking_TLS_Server
{
public:
Blocking_TLS_Server(std::tr1::function<void (const byte[], size_t)> output_fn,
std::tr1::function<size_t (byte[], size_t)> input_fn,
TLS_Session_Manager& sessions,
TLS_Policy& policy,
RandomNumberGenerator& rng,
const X509_Certificate& cert,
const Private_Key& key) :
input_fn(input_fn),
server(
output_fn,
std::tr1::bind(&Blocking_TLS_Server::reader_fn, std::tr1::ref(*this), _1, _2, _3),
sessions,
policy,
rng,
cert,
key),
exit(false)
{
read_loop();
}
size_t read(byte buf[], size_t buf_len)
{
size_t got = read_queue.read(buf, buf_len);
while(!exit && !got)
{
read_loop(5); // header size
got = read_queue.read(buf, buf_len);
}
return got;
}
void write(const byte buf[], size_t buf_len)
{
server.queue_for_sending(buf, buf_len);
}
void close() { server.close(); }
bool is_active() const { return server.is_active(); }
TLS_Server& underlying() { return server; }
private:
void read_loop(size_t init_desired = 0)
{
size_t desired = init_desired;
byte buf[4096];
while(!exit && (!server.is_active() || desired))
{
const size_t asking = std::max(sizeof(buf), std::min(desired, static_cast<size_t>(1)));
const size_t socket_got = input_fn(&buf[0], asking);
if(socket_got == 0) // eof?
{
close();
exit = true;
}
desired = server.received_data(&buf[0], socket_got);
}
}
void reader_fn(const byte buf[], size_t buf_len, u16bit alert_code)
{
if(buf_len == 0 && alert_code != NULL_ALERT)
{
printf("Alert: %d, quitting\n", alert_code);
exit = true;
}
printf("Got %d bytes: ", (int)buf_len);
for(size_t i = 0; i != buf_len; ++i)
{
if(isprint(buf[i]))
printf("%c", buf[i]);
else
printf("0x%02X", buf[i]);
}
printf("\n");
read_queue.write(buf, buf_len);
}
std::tr1::function<size_t (byte[], size_t)> input_fn;
TLS_Server server;
SecureQueue read_queue;
bool exit;
};
class Server_TLS_Policy : public TLS_Policy
{
public:
bool require_client_auth() const { return true; }
bool check_cert(const std::vector<X509_Certificate>& certs) const
{
for(size_t i = 0; i != certs.size(); ++i)
{
std::cout << certs[i].to_string();
}
std::cout << "Warning: not checking cert signatures\n";
return true;
}
};
int main(int argc, char* argv[])
{
int port = 4433;
if(argc == 2)
port = to_u32bit(argv[1]);
try
{
LibraryInitializer botan_init;
//SocketInitializer socket_init;
AutoSeeded_RNG rng;
//RSA_PrivateKey key(rng, 1024);
DSA_PrivateKey key(rng, DL_Group("dsa/jce/1024"));
X509_Cert_Options options(
"localhost/US/Syn Ack Labs/Mathematical Munitions Dept");
X509_Certificate cert =
X509::create_self_signed_cert(options, key, "SHA-1", rng);
Server_Socket listener(port);
Server_TLS_Policy policy;
TLS_Session_Manager_In_Memory sessions;
while(true)
{
try {
printf("Listening for new connection on port %d\n", port);
Socket* sock = listener.accept();
printf("Got new connection\n");
Blocking_TLS_Server tls(
std::tr1::bind(&Socket::write, std::tr1::ref(sock), _1, _2),
std::tr1::bind(&Socket::read, std::tr1::ref(sock), _1, _2, true),
sessions,
policy,
rng,
cert,
key);
const char* msg = "Welcome to the best echo server evar\n";
tls.write((const Botan::byte*)msg, strlen(msg));
std::string line;
while(tls.is_active())
{
byte b;
size_t got = tls.read(&b, 1);
if(got == 0)
break;
line += (char)b;
if(b == '\n')
{
tls.write(reinterpret_cast<const byte*>(line.data()), line.size());
if(line == "quit\n")
{
tls.close();
break;
}
line.clear();
}
}
}
catch(std::exception& e) { printf("Connection problem: %s\n", e.what()); }
}
}
catch(std::exception& e)
{
printf("%s\n", e.what());
return 1;
}
return 0;
}
<commit_msg>Just print printable<commit_after>#include <botan/botan.h>
#include <botan/tls_server.h>
#include <botan/rsa.h>
#include <botan/dsa.h>
#include <botan/x509self.h>
#include <botan/secqueue.h>
#include "socket.h"
using namespace Botan;
#include <stdio.h>
#include <string>
#include <iostream>
#include <memory>
class Blocking_TLS_Server
{
public:
Blocking_TLS_Server(std::tr1::function<void (const byte[], size_t)> output_fn,
std::tr1::function<size_t (byte[], size_t)> input_fn,
TLS_Session_Manager& sessions,
TLS_Policy& policy,
RandomNumberGenerator& rng,
const X509_Certificate& cert,
const Private_Key& key) :
input_fn(input_fn),
server(
output_fn,
std::tr1::bind(&Blocking_TLS_Server::reader_fn, std::tr1::ref(*this), _1, _2, _3),
sessions,
policy,
rng,
cert,
key),
exit(false)
{
read_loop();
}
size_t read(byte buf[], size_t buf_len)
{
size_t got = read_queue.read(buf, buf_len);
while(!exit && !got)
{
read_loop(5); // header size
got = read_queue.read(buf, buf_len);
}
return got;
}
void write(const byte buf[], size_t buf_len)
{
server.queue_for_sending(buf, buf_len);
}
void close() { server.close(); }
bool is_active() const { return server.is_active(); }
TLS_Server& underlying() { return server; }
private:
void read_loop(size_t init_desired = 0)
{
size_t desired = init_desired;
byte buf[4096];
while(!exit && (!server.is_active() || desired))
{
const size_t asking = std::max(sizeof(buf), std::min(desired, static_cast<size_t>(1)));
const size_t socket_got = input_fn(&buf[0], asking);
if(socket_got == 0) // eof?
{
close();
exit = true;
}
desired = server.received_data(&buf[0], socket_got);
}
}
void reader_fn(const byte buf[], size_t buf_len, u16bit alert_code)
{
if(buf_len == 0 && alert_code != NULL_ALERT)
{
printf("Alert: %d, quitting\n", alert_code);
exit = true;
}
printf("Got %d bytes: ", (int)buf_len);
for(size_t i = 0; i != buf_len; ++i)
{
if(isprint(buf[i]))
printf("%c", buf[i]);
}
printf("\n");
read_queue.write(buf, buf_len);
}
std::tr1::function<size_t (byte[], size_t)> input_fn;
TLS_Server server;
SecureQueue read_queue;
bool exit;
};
class Server_TLS_Policy : public TLS_Policy
{
public:
bool require_client_auth() const { return true; }
bool check_cert(const std::vector<X509_Certificate>& certs) const
{
for(size_t i = 0; i != certs.size(); ++i)
{
std::cout << certs[i].to_string();
}
std::cout << "Warning: not checking cert signatures\n";
return true;
}
};
int main(int argc, char* argv[])
{
int port = 4433;
if(argc == 2)
port = to_u32bit(argv[1]);
try
{
LibraryInitializer botan_init;
//SocketInitializer socket_init;
AutoSeeded_RNG rng;
//RSA_PrivateKey key(rng, 1024);
DSA_PrivateKey key(rng, DL_Group("dsa/jce/1024"));
X509_Cert_Options options(
"localhost/US/Syn Ack Labs/Mathematical Munitions Dept");
X509_Certificate cert =
X509::create_self_signed_cert(options, key, "SHA-1", rng);
Server_Socket listener(port);
Server_TLS_Policy policy;
TLS_Session_Manager_In_Memory sessions;
while(true)
{
try {
printf("Listening for new connection on port %d\n", port);
Socket* sock = listener.accept();
printf("Got new connection\n");
Blocking_TLS_Server tls(
std::tr1::bind(&Socket::write, std::tr1::ref(sock), _1, _2),
std::tr1::bind(&Socket::read, std::tr1::ref(sock), _1, _2, true),
sessions,
policy,
rng,
cert,
key);
const char* msg = "Welcome to the best echo server evar\n";
tls.write((const Botan::byte*)msg, strlen(msg));
std::string line;
while(tls.is_active())
{
byte b;
size_t got = tls.read(&b, 1);
if(got == 0)
break;
line += (char)b;
if(b == '\n')
{
tls.write(reinterpret_cast<const byte*>(line.data()), line.size());
if(line == "quit\n")
{
tls.close();
break;
}
line.clear();
}
}
}
catch(std::exception& e) { printf("Connection problem: %s\n", e.what()); }
}
}
catch(std::exception& e)
{
printf("%s\n", e.what());
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "command.h"
#include "events.h"
#include <iostream>
void Command::run(Bot *bot, IRCMessageEvent *ev)
{
try
{
auto t = Command::parse(bot, ev);
CommandInfo *i = std::get<0>(t);
std::vector<CommandBase*> &v = std::get<1>(t);
CommandInfo* curr = i;
for(auto cmd: v)
{
cmd->run(bot, curr);
if(curr != NULL)
{
curr = curr-> next;
}
}
while(curr->in.size() != 0)
{
// todo: clean
bot->conn->send_privmsg(ev->target, curr->pop()->to_string());
}
delete i;
}
catch(CommandNotFoundException e)
{
bot->conn->send_privmsg(ev->target, "Command '" + e.command + "' not found!");
}
catch(PermissionDeniedException e)
{
bot->conn->send_privmsg(ev->target, "Permission denied for '" + e.command + "'!");
}
catch(CommandErrorException e)
{
bot->conn->send_privmsg(ev->target, "Command '" + e.command + "' threw error '" + e.err + "'!");
}
}
bool check_permissions(Bot *bot, User *u, std::string target, std::string command);
std::tuple<CommandInfo*, std::vector<CommandBase*>> Command::parse(Bot *bot, IRCMessageEvent *ev)
{
CommandInfo *info = new CommandInfo();
CommandInfo *curr = info;
std::vector<CommandBase*> v;
std::string &s = ev->message;
const int type_str = 0;
const int type_delim = 1;
std::vector<std::pair<int, std::string>> tokens;
std::string tmp;
size_t i = 0;
bool quote = false;
bool ignore = false;
for(; i < s.length() ; i++)
{
char c = s[i];
switch(c)
{
case '\"':
if(quote)
{
tokens.push_back(std::make_pair(type_str, tmp));
tmp.clear();
ignore = true;
quote = false;
}
else
{
quote = true;
}
break;
case '|':
tokens.push_back(std::make_pair(type_delim, ""));
tmp.clear();
ignore = true;
break;
case ' ':
if(!ignore)
{
if(!quote && tmp != "")
{
tokens.push_back(std::make_pair(type_str, tmp));
tmp.clear();
ignore = true;
}
else
{
tmp += c;
}
}
break;
default:
if(ignore) { ignore = false; }
tmp += c;
break;
}
}
if(tmp != "")
{
tokens.push_back(std::make_pair(type_str, tmp));
}
bool cmd = true;
for(auto a: tokens)
{
if(a.first == type_str)
{
if(cmd)
{
cmd = false;
if(!check_permissions(bot, ev->sender, ev->target, a.second))
{
throw PermissionDeniedException(a.second);
}
CommandBase *b = bot->get_command(a.second);
if(b == NULL)
{
delete info;
throw CommandNotFoundException(a.second);
}
v.push_back(b);
}
else
{
curr->in.push_back(new StringData(a.second));
}
}
else if(a.first == type_delim)
{
cmd = true;
curr->sender = ev->sender;
curr->target = ev->target;
curr->cmd = v.back();
curr->next = new CommandInfo();
curr = curr->next;
}
}
curr->cmd = v.back();
curr->sender = ev->sender;
curr->target = ev->target;
curr->next = new CommandInfo();
curr->next->sender = ev->sender;
curr->next->target = ev->target;
return std::make_tuple(info, v);
}
bool check_permissions(Bot *bot, User *u, std::string target, std::string command)
{
if(!u->synced || u->account == "*")
{
return false;
}
std::shared_ptr<ConfigNode> v = bot->config->get("permissions." + command);
if(v->type() == NodeType::List)
{
for(auto a : v->as_list())
{
std::string b = a;
if(b == u->account)
{
return true;
}
else if(b.substr(0, 6) == "group/")
{
b = b.substr(6);
if(b == "special/all")
{
return true;
}
else if(b == "special/none")
{
return false;
}
else if(b == "special/ops")
{
if(target[0] == '#')
{
Channel &c = bot->conn->get_channel(target);
return c.users[u->nick].modes['o'];
}
else
{
return false;
}
}
else if(b == "special/voice")
{
if(target[0] == '#')
{
Channel &c = bot->conn->get_channel(target);
return c.users[u->nick].modes['v'];
}
else
{
return false;
}
}
std::shared_ptr<ConfigNode> v2 = bot->config->get("groups." + b);
if(v2->type() == NodeType::List)
{
for(auto c : v2->as_list())
{
if(c == u->account)
{
return true;
}
}
}
}
}
}
return false;
}
CommandBase *Command::get_ptr(std::string n)
{
std::cout << "Trying to get command " << n << std::endl;
return NULL;
}<commit_msg>check perms after existence of commands<commit_after>#include "command.h"
#include "events.h"
#include <iostream>
void Command::run(Bot *bot, IRCMessageEvent *ev)
{
try
{
auto t = Command::parse(bot, ev);
CommandInfo *i = std::get<0>(t);
std::vector<CommandBase*> &v = std::get<1>(t);
CommandInfo* curr = i;
for(auto cmd: v)
{
cmd->run(bot, curr);
if(curr != NULL)
{
curr = curr-> next;
}
}
while(curr->in.size() != 0)
{
// todo: clean
bot->conn->send_privmsg(ev->target, curr->pop()->to_string());
}
delete i;
}
catch(CommandNotFoundException e)
{
bot->conn->send_privmsg(ev->target, "Command '" + e.command + "' not found!");
}
catch(PermissionDeniedException e)
{
bot->conn->send_privmsg(ev->target, "Permission denied for '" + e.command + "'!");
}
catch(CommandErrorException e)
{
bot->conn->send_privmsg(ev->target, "Command '" + e.command + "' threw error '" + e.err + "'!");
}
}
bool check_permissions(Bot *bot, User *u, std::string target, std::string command);
std::tuple<CommandInfo*, std::vector<CommandBase*>> Command::parse(Bot *bot, IRCMessageEvent *ev)
{
CommandInfo *info = new CommandInfo();
CommandInfo *curr = info;
std::vector<CommandBase*> v;
std::string &s = ev->message;
const int type_str = 0;
const int type_delim = 1;
std::vector<std::pair<int, std::string>> tokens;
std::string tmp;
size_t i = 0;
bool quote = false;
bool ignore = false;
for(; i < s.length() ; i++)
{
char c = s[i];
switch(c)
{
case '\"':
if(quote)
{
tokens.push_back(std::make_pair(type_str, tmp));
tmp.clear();
ignore = true;
quote = false;
}
else
{
quote = true;
}
break;
case '|':
tokens.push_back(std::make_pair(type_delim, ""));
tmp.clear();
ignore = true;
break;
case ' ':
if(!ignore)
{
if(!quote && tmp != "")
{
tokens.push_back(std::make_pair(type_str, tmp));
tmp.clear();
ignore = true;
}
else
{
tmp += c;
}
}
break;
default:
if(ignore) { ignore = false; }
tmp += c;
break;
}
}
if(tmp != "")
{
tokens.push_back(std::make_pair(type_str, tmp));
}
bool cmd = true;
for(auto a: tokens)
{
if(a.first == type_str)
{
if(cmd)
{
cmd = false;
CommandBase *b = bot->get_command(a.second);
if(b == NULL)
{
delete info;
throw CommandNotFoundException(a.second);
}
if(!check_permissions(bot, ev->sender, ev->target, a.second))
{
throw PermissionDeniedException(a.second);
}
v.push_back(b);
}
else
{
curr->in.push_back(new StringData(a.second));
}
}
else if(a.first == type_delim)
{
cmd = true;
curr->sender = ev->sender;
curr->target = ev->target;
curr->cmd = v.back();
curr->next = new CommandInfo();
curr = curr->next;
}
}
curr->cmd = v.back();
curr->sender = ev->sender;
curr->target = ev->target;
curr->next = new CommandInfo();
curr->next->sender = ev->sender;
curr->next->target = ev->target;
return std::make_tuple(info, v);
}
bool check_permissions(Bot *bot, User *u, std::string target, std::string command)
{
if(!u->synced || u->account == "*")
{
return false;
}
std::shared_ptr<ConfigNode> v = bot->config->get("permissions." + command);
if(v->type() == NodeType::List)
{
for(auto a : v->as_list())
{
std::string b = a;
if(b == u->account)
{
return true;
}
else if(b.substr(0, 6) == "group/")
{
b = b.substr(6);
if(b == "special/all")
{
return true;
}
else if(b == "special/none")
{
return false;
}
else if(b == "special/ops")
{
if(target[0] == '#')
{
Channel &c = bot->conn->get_channel(target);
return c.users[u->nick].modes['o'];
}
else
{
return false;
}
}
else if(b == "special/voice")
{
if(target[0] == '#')
{
Channel &c = bot->conn->get_channel(target);
return c.users[u->nick].modes['v'];
}
else
{
return false;
}
}
std::shared_ptr<ConfigNode> v2 = bot->config->get("groups." + b);
if(v2->type() == NodeType::List)
{
for(auto c : v2->as_list())
{
if(c == u->account)
{
return true;
}
}
}
}
}
}
return false;
}
CommandBase *Command::get_ptr(std::string n)
{
std::cout << "Trying to get command " << n << std::endl;
return NULL;
}<|endoftext|> |
<commit_before>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/storage/client.h"
#include "google/cloud/storage/testing/storage_integration_test.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/testing_util/scoped_environment.h"
#include "google/cloud/testing_util/status_matchers.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace {
using ::google::cloud::internal::GetEnv;
using ::google::cloud::testing_util::IsOk;
class ObjectReadRangeIntegrationTest
: public ::google::cloud::storage::testing::StorageIntegrationTest {
public:
ObjectReadRangeIntegrationTest() = default;
protected:
void SetUp() override {
bucket_name_ =
GetEnv("GOOGLE_CLOUD_CPP_STORAGE_TEST_BUCKET_NAME").value_or("");
ASSERT_FALSE(bucket_name_.empty());
}
std::string const& bucket_name() const { return bucket_name_; }
private:
std::string bucket_name_;
};
TEST_F(ObjectReadRangeIntegrationTest, ReadRangeSmall) {
StatusOr<Client> client = MakeIntegrationTestClient();
ASSERT_STATUS_OK(client);
auto const contents = LoremIpsum();
auto const object_name = MakeRandomObjectName();
auto insert = client->InsertObject(bucket_name(), object_name, contents,
IfGenerationMatch(0));
ASSERT_THAT(insert, IsOk());
EXPECT_THAT(contents.size(), insert->size());
auto size = static_cast<std::int64_t>(insert->size());
// Read several small portions of the object, expecting specific results.
struct Test {
std::int64_t begin;
std::int64_t end;
std::string expected;
} cases[] = {
{0, 1, contents.substr(0, 1)},
{4, 8, contents.substr(4, 4)},
{0, size, contents},
};
for (auto const& test : cases) {
SCOPED_TRACE("Testing range [" + std::to_string(test.begin) + "," +
std::to_string(test.end) + ")");
auto reader = client->ReadObject(bucket_name(), object_name,
ReadRange(test.begin, test.end));
auto actual = std::string{std::istreambuf_iterator<char>(reader), {}};
EXPECT_THAT(reader.status(), IsOk());
EXPECT_EQ(test.expected, actual);
}
(void)client->DeleteObject(bucket_name(), object_name);
}
TEST_F(ObjectReadRangeIntegrationTest, ReadFromOffset) {
StatusOr<Client> client = MakeIntegrationTestClient();
ASSERT_STATUS_OK(client);
auto const contents = LoremIpsum();
auto const object_name = MakeRandomObjectName();
auto insert = client->InsertObject(bucket_name(), object_name, contents,
IfGenerationMatch(0));
ASSERT_THAT(insert, IsOk());
EXPECT_THAT(contents.size(), insert->size());
auto size = static_cast<std::int64_t>(insert->size());
// Read several small portions of the object, expecting specific results.
struct Test {
std::int64_t offset;
std::string expected;
} cases[] = {
{0, contents.substr(0)},
{4, contents.substr(4)},
{size - 1, contents.substr(size - 1)},
};
for (auto const& test : cases) {
SCOPED_TRACE("Testing range [" + std::to_string(test.offset) + ",end)");
auto reader = client->ReadObject(bucket_name(), object_name,
ReadFromOffset(test.offset));
auto actual = std::string{std::istreambuf_iterator<char>(reader), {}};
EXPECT_THAT(reader.status(), IsOk());
EXPECT_EQ(test.expected, actual);
}
(void)client->DeleteObject(bucket_name(), object_name);
}
TEST_F(ObjectReadRangeIntegrationTest, ReadLast) {
StatusOr<Client> client = MakeIntegrationTestClient();
ASSERT_STATUS_OK(client);
auto const contents = LoremIpsum();
auto const object_name = MakeRandomObjectName();
auto insert = client->InsertObject(bucket_name(), object_name, contents,
IfGenerationMatch(0));
ASSERT_THAT(insert, IsOk());
EXPECT_THAT(contents.size(), insert->size());
auto size = static_cast<std::int64_t>(insert->size());
// Read several small portions of the object, expecting specific results.
struct Test {
std::int64_t offset;
std::string expected;
} cases[] = {
{1, contents.substr(size - 1)},
{4, contents.substr(size - 4)},
{size, contents},
};
for (auto const& test : cases) {
SCOPED_TRACE("Testing range [-" + std::to_string(test.offset) + ",end)");
auto reader =
client->ReadObject(bucket_name(), object_name, ReadLast(test.offset));
auto actual = std::string{std::istreambuf_iterator<char>(reader), {}};
EXPECT_THAT(reader.status(), IsOk());
EXPECT_EQ(test.expected, actual);
}
(void)client->DeleteObject(bucket_name(), object_name);
}
} // namespace
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
<commit_msg>test(storage): fix build for Windows+x86 (#6555)<commit_after>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/storage/client.h"
#include "google/cloud/storage/testing/storage_integration_test.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/testing_util/scoped_environment.h"
#include "google/cloud/testing_util/status_matchers.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace {
using ::google::cloud::internal::GetEnv;
using ::google::cloud::testing_util::IsOk;
class ObjectReadRangeIntegrationTest
: public ::google::cloud::storage::testing::StorageIntegrationTest {
public:
ObjectReadRangeIntegrationTest() = default;
protected:
void SetUp() override {
bucket_name_ =
GetEnv("GOOGLE_CLOUD_CPP_STORAGE_TEST_BUCKET_NAME").value_or("");
ASSERT_FALSE(bucket_name_.empty());
}
std::string const& bucket_name() const { return bucket_name_; }
private:
std::string bucket_name_;
};
TEST_F(ObjectReadRangeIntegrationTest, ReadRangeSmall) {
StatusOr<Client> client = MakeIntegrationTestClient();
ASSERT_STATUS_OK(client);
auto const contents = LoremIpsum();
auto const object_name = MakeRandomObjectName();
auto insert = client->InsertObject(bucket_name(), object_name, contents,
IfGenerationMatch(0));
ASSERT_THAT(insert, IsOk());
EXPECT_THAT(contents.size(), insert->size());
auto const size = static_cast<std::int64_t>(insert->size());
// Read several small portions of the object, expecting specific results.
struct Test {
std::int64_t begin;
std::int64_t end;
std::string expected;
} cases[] = {
{0, 1, contents.substr(0, 1)},
{4, 8, contents.substr(4, 4)},
{0, size, contents},
};
for (auto const& test : cases) {
SCOPED_TRACE("Testing range [" + std::to_string(test.begin) + "," +
std::to_string(test.end) + ")");
auto reader = client->ReadObject(bucket_name(), object_name,
ReadRange(test.begin, test.end));
auto actual = std::string{std::istreambuf_iterator<char>(reader), {}};
EXPECT_THAT(reader.status(), IsOk());
EXPECT_EQ(test.expected, actual);
}
(void)client->DeleteObject(bucket_name(), object_name);
}
TEST_F(ObjectReadRangeIntegrationTest, ReadFromOffset) {
StatusOr<Client> client = MakeIntegrationTestClient();
ASSERT_STATUS_OK(client);
auto const contents = LoremIpsum();
auto const object_name = MakeRandomObjectName();
auto insert = client->InsertObject(bucket_name(), object_name, contents,
IfGenerationMatch(0));
ASSERT_THAT(insert, IsOk());
EXPECT_THAT(contents.size(), insert->size());
auto const size = static_cast<std::int64_t>(insert->size());
// Read several small portions of the object, expecting specific results.
struct Test {
std::int64_t offset;
std::string expected;
} cases[] = {
{0, contents.substr(0)},
{4, contents.substr(4)},
{size - 1, contents.substr(contents.size() - 1)},
};
for (auto const& test : cases) {
SCOPED_TRACE("Testing range [" + std::to_string(test.offset) + ",end)");
auto reader = client->ReadObject(bucket_name(), object_name,
ReadFromOffset(test.offset));
auto actual = std::string{std::istreambuf_iterator<char>(reader), {}};
EXPECT_THAT(reader.status(), IsOk());
EXPECT_EQ(test.expected, actual);
}
(void)client->DeleteObject(bucket_name(), object_name);
}
TEST_F(ObjectReadRangeIntegrationTest, ReadLast) {
StatusOr<Client> client = MakeIntegrationTestClient();
ASSERT_STATUS_OK(client);
auto const contents = LoremIpsum();
auto const object_name = MakeRandomObjectName();
auto insert = client->InsertObject(bucket_name(), object_name, contents,
IfGenerationMatch(0));
ASSERT_THAT(insert, IsOk());
EXPECT_THAT(contents.size(), insert->size());
auto const size = static_cast<std::int64_t>(insert->size());
// Read several small portions of the object, expecting specific results.
struct Test {
std::int64_t offset;
std::string expected;
} cases[] = {
{1, contents.substr(contents.size() - 1)},
{4, contents.substr(contents.size() - 4)},
{size, contents},
};
for (auto const& test : cases) {
SCOPED_TRACE("Testing range [-" + std::to_string(test.offset) + ",end)");
auto reader =
client->ReadObject(bucket_name(), object_name, ReadLast(test.offset));
auto actual = std::string{std::istreambuf_iterator<char>(reader), {}};
EXPECT_THAT(reader.status(), IsOk());
EXPECT_EQ(test.expected, actual);
}
(void)client->DeleteObject(bucket_name(), object_name);
}
} // namespace
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2015 Dato, Inc.
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#include <cassert>
#include <sstream>
#include <zmq.h>
#include <boost/algorithm/string.hpp>
#include <boost/integer_traits.hpp>
#include <util/md5.hpp>
#include <globals/globals.hpp>
#include <logger/logger.hpp>
#include <export.hpp>
#ifndef _WIN32
#include <sys/socket.h>
#include <sys/un.h>
#endif
namespace libfault {
int SEND_TIMEOUT = 3000;
int RECV_TIMEOUT = 7000;
void set_send_timeout(int ms) {
SEND_TIMEOUT = ms;
}
void set_recv_timeout(int ms) {
RECV_TIMEOUT = ms;
}
void set_conservative_socket_parameters(void* z_socket) {
int lingerval = 500;
int timeoutms = 500;
int hwm = 0;
int rc = zmq_setsockopt(z_socket, ZMQ_LINGER, &lingerval, sizeof(lingerval));
assert(rc == 0);
rc = zmq_setsockopt(z_socket, ZMQ_RCVTIMEO, &timeoutms, sizeof(timeoutms));
assert(rc == 0);
rc = zmq_setsockopt(z_socket, ZMQ_SNDTIMEO, &timeoutms, sizeof(timeoutms));
assert(rc == 0);
rc = zmq_setsockopt(z_socket, ZMQ_SNDHWM, &hwm, sizeof(hwm));
assert(rc == 0);
rc = zmq_setsockopt(z_socket, ZMQ_RCVHWM, &hwm, sizeof(hwm));
assert(rc == 0);
}
/**
* Given a string, returns a zeromq localhost tcp address (ex:
* tcp://127.15.21.22:11111).
*
* On windows we don't get zeromq IPC sockets. Hence, the easiest thing to do
* is to remap ipc sockets to tcp addresses.
*
* When the server is started with address=default mode, on *nix systems we
* map to ipc://something or order. Instead, on windows systems
* we must map to tcp://[arbitrary local IP] where there is optimally,
* a 1-1 correspondence between the local IP and the PID.
*
* So, here are the rules:
* - We cannot generate any port number <= 1024
* - Lets about 127.0.0.1 because too many stuff like to live there
* - 127.0.0.0 is invalid. (network address)
* - 127.255.255.255 is invalid (broadcast address)
*/
std::string hash_string_to_tcp_address(const std::string& s) {
std::string md5sum = graphlab::md5_raw(s);
// we get approximately 5 bytes of entropy (yes really somewhat less)
unsigned char addr[4];
addr[0] = 127;
addr[1] = md5sum[0];
addr[2] = md5sum[1];
addr[3] = md5sum[2];
uint16_t port = (uint16_t)(md5sum[3]) * 256 + md5sum[4];
// validate
if ((addr[1] == 0 && addr[2] == 0 && addr[3] == 0) || // network address
(addr[1] == 0 && addr[2] == 0 && addr[3] == 1) || // common address
(addr[1] == 255 && addr[2] == 255 && addr[3] == 255) || // broadcast
(port <= 1024)) { // bad port
// bad. this is network name
// rehash
return hash_string_to_tcp_address(md5sum);
}
// ok generate the string
std::stringstream strm;
strm << "tcp://" << (int)(addr[0]) << "."
<< (int)(addr[1]) << "."
<< (int)(addr[2]) << "."
<< (int)(addr[3]) << ":"
<< (int)(port);
std::string s_out = strm.str();
logstream(LOG_INFO) << "normalize_address: Hashed ipc address '" << s << "' to '"
<< s_out << "'." << std::endl;
return s_out;
}
EXPORT int64_t FORCE_IPC_TO_TCP_FALLBACK = 0;
REGISTER_GLOBAL(int64_t, FORCE_IPC_TO_TCP_FALLBACK, true);
std::string normalize_address(const std::string& address) {
bool use_tcp_fallback = (FORCE_IPC_TO_TCP_FALLBACK != 0);
std::string address_out;
#ifdef _WIN32
use_tcp_fallback = true;
#endif
if(use_tcp_fallback) {
logstream(LOG_INFO) << "normalize_address: Using TCP fallback mode." << std::endl;
if (boost::starts_with(address, "ipc://")) {
address_out = hash_string_to_tcp_address(address);
} else {
address_out = address;
}
} else {
/*
*
ipc sockets on Linux and Mac use Unix domain sockets which have a maximum
length defined by
#include <iostream>
#include <sys/socket.h>
#include <sys/un.h>
int main() {
struct sockaddr_un my_addr;
std::cout << sizeof(my_addr.sun_path) << std::endl;
}
This appears to be 104 on Mac OS X 10.11 and 108 on a Ubuntu machine
(length includes the null terminator).
See http://man7.org/linux/man-pages/man7/unix.7.html
*/
struct sockaddr_un un_addr;
size_t max_length = sizeof(un_addr.sun_path) - 1; // null terminator
if (boost::starts_with(address, "ipc://") &&
address.length() > max_length) { // strictly this leaves a 5 char buffer
// since we didn't strip the ipc://
// we hash it to a file we put in /tmp
// we could use $TMPDIR but that might be a bad idea.
// since $TMPDIR could bump the length much bigger again.
// with /tmp the length is bounded to strlen("/tmp") + md5 length.
std::string md5_hash = graphlab::md5(address);
address_out = "ipc:///tmp/" + md5_hash;
} else {
address_out = address;
}
}
if(address_out == address) {
logstream(LOG_INFO) << "normalize_address: kept '" << address_out << "'." << std::endl;
} else {
logstream(LOG_INFO) << "normalize_address: '" << address << "' --> '"
<< address_out << "'." << std::endl;
}
return address_out;
}
};
<commit_msg>sockaddr_un not defined on windows<commit_after>/**
* Copyright (C) 2015 Dato, Inc.
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#include <cassert>
#include <sstream>
#include <zmq.h>
#include <boost/algorithm/string.hpp>
#include <boost/integer_traits.hpp>
#include <util/md5.hpp>
#include <globals/globals.hpp>
#include <logger/logger.hpp>
#include <export.hpp>
#ifndef _WIN32
#include <sys/socket.h>
#include <sys/un.h>
#endif
namespace libfault {
int SEND_TIMEOUT = 3000;
int RECV_TIMEOUT = 7000;
void set_send_timeout(int ms) {
SEND_TIMEOUT = ms;
}
void set_recv_timeout(int ms) {
RECV_TIMEOUT = ms;
}
void set_conservative_socket_parameters(void* z_socket) {
int lingerval = 500;
int timeoutms = 500;
int hwm = 0;
int rc = zmq_setsockopt(z_socket, ZMQ_LINGER, &lingerval, sizeof(lingerval));
assert(rc == 0);
rc = zmq_setsockopt(z_socket, ZMQ_RCVTIMEO, &timeoutms, sizeof(timeoutms));
assert(rc == 0);
rc = zmq_setsockopt(z_socket, ZMQ_SNDTIMEO, &timeoutms, sizeof(timeoutms));
assert(rc == 0);
rc = zmq_setsockopt(z_socket, ZMQ_SNDHWM, &hwm, sizeof(hwm));
assert(rc == 0);
rc = zmq_setsockopt(z_socket, ZMQ_RCVHWM, &hwm, sizeof(hwm));
assert(rc == 0);
}
/**
* Given a string, returns a zeromq localhost tcp address (ex:
* tcp://127.15.21.22:11111).
*
* On windows we don't get zeromq IPC sockets. Hence, the easiest thing to do
* is to remap ipc sockets to tcp addresses.
*
* When the server is started with address=default mode, on *nix systems we
* map to ipc://something or order. Instead, on windows systems
* we must map to tcp://[arbitrary local IP] where there is optimally,
* a 1-1 correspondence between the local IP and the PID.
*
* So, here are the rules:
* - We cannot generate any port number <= 1024
* - Lets about 127.0.0.1 because too many stuff like to live there
* - 127.0.0.0 is invalid. (network address)
* - 127.255.255.255 is invalid (broadcast address)
*/
std::string hash_string_to_tcp_address(const std::string& s) {
std::string md5sum = graphlab::md5_raw(s);
// we get approximately 5 bytes of entropy (yes really somewhat less)
unsigned char addr[4];
addr[0] = 127;
addr[1] = md5sum[0];
addr[2] = md5sum[1];
addr[3] = md5sum[2];
uint16_t port = (uint16_t)(md5sum[3]) * 256 + md5sum[4];
// validate
if ((addr[1] == 0 && addr[2] == 0 && addr[3] == 0) || // network address
(addr[1] == 0 && addr[2] == 0 && addr[3] == 1) || // common address
(addr[1] == 255 && addr[2] == 255 && addr[3] == 255) || // broadcast
(port <= 1024)) { // bad port
// bad. this is network name
// rehash
return hash_string_to_tcp_address(md5sum);
}
// ok generate the string
std::stringstream strm;
strm << "tcp://" << (int)(addr[0]) << "."
<< (int)(addr[1]) << "."
<< (int)(addr[2]) << "."
<< (int)(addr[3]) << ":"
<< (int)(port);
std::string s_out = strm.str();
logstream(LOG_INFO) << "normalize_address: Hashed ipc address '" << s << "' to '"
<< s_out << "'." << std::endl;
return s_out;
}
EXPORT int64_t FORCE_IPC_TO_TCP_FALLBACK = 0;
REGISTER_GLOBAL(int64_t, FORCE_IPC_TO_TCP_FALLBACK, true);
std::string normalize_address(const std::string& address) {
bool use_tcp_fallback = (FORCE_IPC_TO_TCP_FALLBACK != 0);
std::string address_out;
#ifdef _WIN32
use_tcp_fallback = true;
#endif
if(use_tcp_fallback) {
logstream(LOG_INFO) << "normalize_address: Using TCP fallback mode." << std::endl;
if (boost::starts_with(address, "ipc://")) {
address_out = hash_string_to_tcp_address(address);
} else {
address_out = address;
}
}
#ifndef _WIN32
// sockaddr_un not defined on windows.
else {
/*
*
ipc sockets on Linux and Mac use Unix domain sockets which have a maximum
length defined by
#include <iostream>
#include <sys/socket.h>
#include <sys/un.h>
int main() {
struct sockaddr_un my_addr;
std::cout << sizeof(my_addr.sun_path) << std::endl;
}
This appears to be 104 on Mac OS X 10.11 and 108 on a Ubuntu machine
(length includes the null terminator).
See http://man7.org/linux/man-pages/man7/unix.7.html
*/
struct sockaddr_un un_addr;
size_t max_length = sizeof(un_addr.sun_path) - 1; // null terminator
if (boost::starts_with(address, "ipc://") &&
address.length() > max_length) { // strictly this leaves a 5 char buffer
// since we didn't strip the ipc://
// we hash it to a file we put in /tmp
// we could use $TMPDIR but that might be a bad idea.
// since $TMPDIR could bump the length much bigger again.
// with /tmp the length is bounded to strlen("/tmp") + md5 length.
std::string md5_hash = graphlab::md5(address);
address_out = "ipc:///tmp/" + md5_hash;
} else {
address_out = address;
}
}
#else
else {
address_out = address;
}
#endif
if(address_out == address) {
logstream(LOG_INFO) << "normalize_address: kept '" << address_out << "'." << std::endl;
} else {
logstream(LOG_INFO) << "normalize_address: '" << address << "' --> '"
<< address_out << "'." << std::endl;
}
return address_out;
}
};
<|endoftext|> |
<commit_before>#include "Genes/Passed_Pawn_Gene.h"
#include <string>
#include <array>
#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Piece.h"
#include "Game/Color.h"
double Passed_Pawn_Gene::score_board(const Board& board, Piece_Color perspective, size_t) const noexcept
{
double score = 0.0;
auto own_pawn = Piece{perspective, Piece_Type::PAWN};
auto other_pawn = Piece{opposite(perspective), Piece_Type::PAWN};
auto near_rank = (perspective == Piece_Color::WHITE ? 1 : 8);
auto far_rank = (perspective == Piece_Color::WHITE ? 7 : 2);
auto rank_step = (perspective == Piece_Color::WHITE ? 1 : -1);
auto other_pawn_ranks_occupied = std::array<int, 8>{};
for(char file = 'a'; file <= 'h'; ++file)
{
for(int rank = far_rank; rank != near_rank; rank -= rank_step)
{
auto piece = board.piece_on_square({file, rank});
if(piece == own_pawn)
{
score += 1.0;
auto left_file = std::max('a', char(file - 1));
auto right_file = std::min('h', char(file + 1));
auto score_diff = 1.0/(right_file - left_file + 1);
for(char pawn_file = left_file; pawn_file <= right_file; ++pawn_file)
{
auto other_pawn_rank = other_pawn_ranks_occupied[size_t(pawn_file - 'a')];
if(other_pawn_rank != 0 && other_pawn_rank != rank)
{
score -= score_diff;
}
}
}
else if(piece == other_pawn)
{
other_pawn_ranks_occupied[size_t(file - 'a')] = rank;
}
}
}
return score/8; // maximum score == 1
}
std::string Passed_Pawn_Gene::name() const noexcept
{
return "Passed Pawn Gene";
}
<commit_msg>Slight speed increase for Passed Pawn Gene<commit_after>#include "Genes/Passed_Pawn_Gene.h"
#include <string>
#include <array>
#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Piece.h"
#include "Game/Color.h"
double Passed_Pawn_Gene::score_board(const Board& board, Piece_Color perspective, size_t) const noexcept
{
double score = 0.0;
auto own_pawn = Piece{perspective, Piece_Type::PAWN};
auto other_pawn = Piece{opposite(perspective), Piece_Type::PAWN};
auto near_rank = (perspective == Piece_Color::WHITE ? 1 : 8);
auto far_rank = (perspective == Piece_Color::WHITE ? 7 : 2);
auto rank_step = (perspective == Piece_Color::WHITE ? 1 : -1);
auto other_pawn_ranks_occupied = std::array<int, 8>{};
for(char file = 'a'; file <= 'h'; ++file)
{
auto left_file = std::max('a', char(file - 1));
auto right_file = std::min('h', char(file + 1));
auto score_diff = 1.0/(right_file - left_file + 1);
for(int rank = far_rank; rank != near_rank; rank -= rank_step)
{
auto piece = board.piece_on_square({file, rank});
if(piece == own_pawn)
{
score += 1.0;
for(char pawn_file = left_file; pawn_file <= right_file; ++pawn_file)
{
auto other_pawn_rank = other_pawn_ranks_occupied[size_t(pawn_file - 'a')];
if(other_pawn_rank != 0 && other_pawn_rank != rank)
{
score -= score_diff;
}
}
}
else if(piece == other_pawn)
{
other_pawn_ranks_occupied[size_t(file - 'a')] = rank;
}
}
}
return score/8; // maximum score == 1
}
std::string Passed_Pawn_Gene::name() const noexcept
{
return "Passed Pawn Gene";
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/heap/safepoint.h"
#include "vm/heap/heap.h"
#include "vm/thread.h"
#include "vm/thread_registry.h"
namespace dart {
DEFINE_FLAG(bool, trace_safepoint, false, "Trace Safepoint logic.");
SafepointOperationScope::SafepointOperationScope(Thread* T)
: ThreadStackResource(T) {
ASSERT(T != NULL);
Isolate* I = T->isolate();
ASSERT(I != NULL);
SafepointHandler* handler = I->group()->safepoint_handler();
ASSERT(handler != NULL);
// Signal all threads to get to a safepoint and wait for them to
// get to a safepoint.
handler->SafepointThreads(T);
}
SafepointOperationScope::~SafepointOperationScope() {
Thread* T = thread();
ASSERT(T != NULL);
Isolate* I = T->isolate();
ASSERT(I != NULL);
// Resume all threads which are blocked for the safepoint operation.
SafepointHandler* handler = I->safepoint_handler();
ASSERT(handler != NULL);
handler->ResumeThreads(T);
}
ForceGrowthSafepointOperationScope::ForceGrowthSafepointOperationScope(
Thread* T)
: ThreadStackResource(T) {
ASSERT(T != NULL);
Isolate* I = T->isolate();
ASSERT(I != NULL);
Heap* heap = I->heap();
current_growth_controller_state_ = heap->GrowthControlState();
heap->DisableGrowthControl();
SafepointHandler* handler = I->group()->safepoint_handler();
ASSERT(handler != NULL);
// Signal all threads to get to a safepoint and wait for them to
// get to a safepoint.
handler->SafepointThreads(T);
}
ForceGrowthSafepointOperationScope::~ForceGrowthSafepointOperationScope() {
Thread* T = thread();
ASSERT(T != NULL);
Isolate* I = T->isolate();
ASSERT(I != NULL);
// Resume all threads which are blocked for the safepoint operation.
SafepointHandler* handler = I->safepoint_handler();
ASSERT(handler != NULL);
handler->ResumeThreads(T);
Heap* heap = I->heap();
heap->SetGrowthControlState(current_growth_controller_state_);
if (current_growth_controller_state_) {
ASSERT(T->CanCollectGarbage());
// Check if we passed the growth limit during the scope.
if (heap->old_space()->NeedsGarbageCollection()) {
heap->CollectGarbage(Heap::kMarkSweep, Heap::kOldSpace);
} else {
heap->CheckStartConcurrentMarking(T, Heap::kOldSpace);
}
}
}
SafepointHandler::SafepointHandler(IsolateGroup* isolate_group)
: isolate_group_(isolate_group),
safepoint_lock_(),
number_threads_not_at_safepoint_(0),
safepoint_operation_count_(0),
owner_(NULL) {}
SafepointHandler::~SafepointHandler() {
ASSERT(owner_ == NULL);
ASSERT(safepoint_operation_count_ == 0);
isolate_group_ = NULL;
}
void SafepointHandler::SafepointThreads(Thread* T) {
ASSERT(T->no_safepoint_scope_depth() == 0);
ASSERT(T->execution_state() == Thread::kThreadInVM);
{
// First grab the threads list lock for this isolate
// and check if a safepoint is already in progress. This
// ensures that two threads do not start a safepoint operation
// at the same time.
MonitorLocker sl(threads_lock());
// Now check to see if a safepoint operation is already in progress
// for this isolate, block if an operation is in progress.
while (SafepointInProgress()) {
// If we are recursively invoking a Safepoint operation then we
// just increment the count and return, otherwise we wait for the
// safepoint operation to be done.
if (owner_ == T) {
increment_safepoint_operation_count();
return;
}
sl.WaitWithSafepointCheck(T);
}
// Set safepoint in progress state by this thread.
SetSafepointInProgress(T);
// Go over the active thread list and ensure that all threads active
// in the isolate reach a safepoint.
Thread* current = isolate_group()->thread_registry()->active_list();
while (current != NULL) {
MonitorLocker tl(current->thread_lock());
if (!current->BypassSafepoints()) {
if (current == T) {
current->SetAtSafepoint(true);
} else {
uint32_t state = current->SetSafepointRequested(true);
if (!Thread::IsAtSafepoint(state)) {
// Thread is not already at a safepoint so try to
// get it to a safepoint and wait for it to check in.
if (current->IsMutatorThread()) {
ASSERT(T->isolate() != NULL);
current->ScheduleInterruptsLocked(Thread::kVMInterrupt);
}
MonitorLocker sl(&safepoint_lock_);
++number_threads_not_at_safepoint_;
}
}
}
current = current->next();
}
}
// Now wait for all threads that are not already at a safepoint to check-in.
{
MonitorLocker sl(&safepoint_lock_);
intptr_t num_attempts = 0;
while (number_threads_not_at_safepoint_ > 0) {
Monitor::WaitResult retval = sl.Wait(1000);
if (retval == Monitor::kTimedOut) {
num_attempts += 1;
if (FLAG_trace_safepoint && num_attempts > 10) {
// We have been waiting too long, start logging this as we might
// have an issue where a thread is not checking in for a safepoint.
for (Thread* current =
isolate_group()->thread_registry()->active_list();
current != NULL; current = current->next()) {
if (!current->IsAtSafepoint()) {
OS::PrintErr("Attempt:%" Pd
" waiting for thread %s to check in\n",
num_attempts, current->os_thread()->name());
}
}
}
}
}
}
}
void SafepointHandler::ResumeThreads(Thread* T) {
// First resume all the threads which are blocked for the safepoint
// operation.
MonitorLocker sl(threads_lock());
// First check if we are in a recursive safepoint operation, in that case
// we just decrement safepoint_operation_count and return.
ASSERT(SafepointInProgress());
if (safepoint_operation_count() > 1) {
decrement_safepoint_operation_count();
return;
}
Thread* current = isolate_group()->thread_registry()->active_list();
while (current != NULL) {
MonitorLocker tl(current->thread_lock());
if (!current->BypassSafepoints()) {
if (current == T) {
current->SetAtSafepoint(false);
} else {
uint32_t state = current->SetSafepointRequested(false);
if (Thread::IsBlockedForSafepoint(state)) {
tl.Notify();
}
}
}
current = current->next();
}
// Now reset the safepoint_in_progress_ state and notify all threads
// that are waiting to enter the isolate or waiting to start another
// safepoint operation.
ResetSafepointInProgress(T);
sl.NotifyAll();
}
void SafepointHandler::EnterSafepointUsingLock(Thread* T) {
MonitorLocker tl(T->thread_lock());
T->SetAtSafepoint(true);
if (T->IsSafepointRequested()) {
MonitorLocker sl(&safepoint_lock_);
ASSERT(number_threads_not_at_safepoint_ > 0);
number_threads_not_at_safepoint_ -= 1;
sl.Notify();
}
}
void SafepointHandler::ExitSafepointUsingLock(Thread* T) {
MonitorLocker tl(T->thread_lock());
ASSERT(T->IsAtSafepoint());
while (T->IsSafepointRequested()) {
T->SetBlockedForSafepoint(true);
tl.Wait();
T->SetBlockedForSafepoint(false);
}
T->SetAtSafepoint(false);
}
void SafepointHandler::BlockForSafepoint(Thread* T) {
ASSERT(!T->BypassSafepoints());
MonitorLocker tl(T->thread_lock());
if (T->IsSafepointRequested()) {
T->SetAtSafepoint(true);
{
MonitorLocker sl(&safepoint_lock_);
ASSERT(number_threads_not_at_safepoint_ > 0);
number_threads_not_at_safepoint_ -= 1;
sl.Notify();
}
while (T->IsSafepointRequested()) {
T->SetBlockedForSafepoint(true);
tl.Wait();
T->SetBlockedForSafepoint(false);
}
T->SetAtSafepoint(false);
}
}
} // namespace dart
<commit_msg>[vm, gc] Fix racy access to the growth policy in ForceGrowthSafepointOperationScope.<commit_after>// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/heap/safepoint.h"
#include "vm/heap/heap.h"
#include "vm/thread.h"
#include "vm/thread_registry.h"
namespace dart {
DEFINE_FLAG(bool, trace_safepoint, false, "Trace Safepoint logic.");
SafepointOperationScope::SafepointOperationScope(Thread* T)
: ThreadStackResource(T) {
ASSERT(T != NULL);
Isolate* I = T->isolate();
ASSERT(I != NULL);
SafepointHandler* handler = I->group()->safepoint_handler();
ASSERT(handler != NULL);
// Signal all threads to get to a safepoint and wait for them to
// get to a safepoint.
handler->SafepointThreads(T);
}
SafepointOperationScope::~SafepointOperationScope() {
Thread* T = thread();
ASSERT(T != NULL);
Isolate* I = T->isolate();
ASSERT(I != NULL);
// Resume all threads which are blocked for the safepoint operation.
SafepointHandler* handler = I->safepoint_handler();
ASSERT(handler != NULL);
handler->ResumeThreads(T);
}
ForceGrowthSafepointOperationScope::ForceGrowthSafepointOperationScope(
Thread* T)
: ThreadStackResource(T) {
ASSERT(T != NULL);
Isolate* I = T->isolate();
ASSERT(I != NULL);
SafepointHandler* handler = I->group()->safepoint_handler();
ASSERT(handler != NULL);
// Signal all threads to get to a safepoint and wait for them to
// get to a safepoint.
handler->SafepointThreads(T);
// N.B.: Change growth policy inside the safepoint to prevent racy access.
Heap* heap = I->heap();
current_growth_controller_state_ = heap->GrowthControlState();
heap->DisableGrowthControl();
}
ForceGrowthSafepointOperationScope::~ForceGrowthSafepointOperationScope() {
Thread* T = thread();
ASSERT(T != NULL);
Isolate* I = T->isolate();
ASSERT(I != NULL);
// N.B.: Change growth policy inside the safepoint to prevent racy access.
Heap* heap = I->heap();
heap->SetGrowthControlState(current_growth_controller_state_);
// Resume all threads which are blocked for the safepoint operation.
SafepointHandler* handler = I->safepoint_handler();
ASSERT(handler != NULL);
handler->ResumeThreads(T);
if (current_growth_controller_state_) {
ASSERT(T->CanCollectGarbage());
// Check if we passed the growth limit during the scope.
if (heap->old_space()->NeedsGarbageCollection()) {
heap->CollectGarbage(Heap::kMarkSweep, Heap::kOldSpace);
} else {
heap->CheckStartConcurrentMarking(T, Heap::kOldSpace);
}
}
}
SafepointHandler::SafepointHandler(IsolateGroup* isolate_group)
: isolate_group_(isolate_group),
safepoint_lock_(),
number_threads_not_at_safepoint_(0),
safepoint_operation_count_(0),
owner_(NULL) {}
SafepointHandler::~SafepointHandler() {
ASSERT(owner_ == NULL);
ASSERT(safepoint_operation_count_ == 0);
isolate_group_ = NULL;
}
void SafepointHandler::SafepointThreads(Thread* T) {
ASSERT(T->no_safepoint_scope_depth() == 0);
ASSERT(T->execution_state() == Thread::kThreadInVM);
{
// First grab the threads list lock for this isolate
// and check if a safepoint is already in progress. This
// ensures that two threads do not start a safepoint operation
// at the same time.
MonitorLocker sl(threads_lock());
// Now check to see if a safepoint operation is already in progress
// for this isolate, block if an operation is in progress.
while (SafepointInProgress()) {
// If we are recursively invoking a Safepoint operation then we
// just increment the count and return, otherwise we wait for the
// safepoint operation to be done.
if (owner_ == T) {
increment_safepoint_operation_count();
return;
}
sl.WaitWithSafepointCheck(T);
}
// Set safepoint in progress state by this thread.
SetSafepointInProgress(T);
// Go over the active thread list and ensure that all threads active
// in the isolate reach a safepoint.
Thread* current = isolate_group()->thread_registry()->active_list();
while (current != NULL) {
MonitorLocker tl(current->thread_lock());
if (!current->BypassSafepoints()) {
if (current == T) {
current->SetAtSafepoint(true);
} else {
uint32_t state = current->SetSafepointRequested(true);
if (!Thread::IsAtSafepoint(state)) {
// Thread is not already at a safepoint so try to
// get it to a safepoint and wait for it to check in.
if (current->IsMutatorThread()) {
ASSERT(T->isolate() != NULL);
current->ScheduleInterruptsLocked(Thread::kVMInterrupt);
}
MonitorLocker sl(&safepoint_lock_);
++number_threads_not_at_safepoint_;
}
}
}
current = current->next();
}
}
// Now wait for all threads that are not already at a safepoint to check-in.
{
MonitorLocker sl(&safepoint_lock_);
intptr_t num_attempts = 0;
while (number_threads_not_at_safepoint_ > 0) {
Monitor::WaitResult retval = sl.Wait(1000);
if (retval == Monitor::kTimedOut) {
num_attempts += 1;
if (FLAG_trace_safepoint && num_attempts > 10) {
// We have been waiting too long, start logging this as we might
// have an issue where a thread is not checking in for a safepoint.
for (Thread* current =
isolate_group()->thread_registry()->active_list();
current != NULL; current = current->next()) {
if (!current->IsAtSafepoint()) {
OS::PrintErr("Attempt:%" Pd
" waiting for thread %s to check in\n",
num_attempts, current->os_thread()->name());
}
}
}
}
}
}
}
void SafepointHandler::ResumeThreads(Thread* T) {
// First resume all the threads which are blocked for the safepoint
// operation.
MonitorLocker sl(threads_lock());
// First check if we are in a recursive safepoint operation, in that case
// we just decrement safepoint_operation_count and return.
ASSERT(SafepointInProgress());
if (safepoint_operation_count() > 1) {
decrement_safepoint_operation_count();
return;
}
Thread* current = isolate_group()->thread_registry()->active_list();
while (current != NULL) {
MonitorLocker tl(current->thread_lock());
if (!current->BypassSafepoints()) {
if (current == T) {
current->SetAtSafepoint(false);
} else {
uint32_t state = current->SetSafepointRequested(false);
if (Thread::IsBlockedForSafepoint(state)) {
tl.Notify();
}
}
}
current = current->next();
}
// Now reset the safepoint_in_progress_ state and notify all threads
// that are waiting to enter the isolate or waiting to start another
// safepoint operation.
ResetSafepointInProgress(T);
sl.NotifyAll();
}
void SafepointHandler::EnterSafepointUsingLock(Thread* T) {
MonitorLocker tl(T->thread_lock());
T->SetAtSafepoint(true);
if (T->IsSafepointRequested()) {
MonitorLocker sl(&safepoint_lock_);
ASSERT(number_threads_not_at_safepoint_ > 0);
number_threads_not_at_safepoint_ -= 1;
sl.Notify();
}
}
void SafepointHandler::ExitSafepointUsingLock(Thread* T) {
MonitorLocker tl(T->thread_lock());
ASSERT(T->IsAtSafepoint());
while (T->IsSafepointRequested()) {
T->SetBlockedForSafepoint(true);
tl.Wait();
T->SetBlockedForSafepoint(false);
}
T->SetAtSafepoint(false);
}
void SafepointHandler::BlockForSafepoint(Thread* T) {
ASSERT(!T->BypassSafepoints());
MonitorLocker tl(T->thread_lock());
if (T->IsSafepointRequested()) {
T->SetAtSafepoint(true);
{
MonitorLocker sl(&safepoint_lock_);
ASSERT(number_threads_not_at_safepoint_ > 0);
number_threads_not_at_safepoint_ -= 1;
sl.Notify();
}
while (T->IsSafepointRequested()) {
T->SetBlockedForSafepoint(true);
tl.Wait();
T->SetBlockedForSafepoint(false);
}
T->SetAtSafepoint(false);
}
}
} // namespace dart
<|endoftext|> |
<commit_before>#include <iostream>
#include <type_traits>
#include <vector>
#include <agency/future.hpp>
#include <agency/execution/executor/detail/new_executor_traits.hpp>
#include "test_executors.hpp"
template<class Executor>
void test(Executor exec)
{
using namespace agency::detail::new_executor_traits_detail;
auto fut = agency::detail::make_ready_future<int>(7);
int val = 13;
using shape_type = executor_shape_t<Executor>;
using index_type = executor_index_t<Executor>;
auto f = bulk_then_execute(exec,
[](index_type idx, int& past_arg, std::vector<int>& results, std::vector<int>& shared_arg)
{
results[idx] = past_arg + shared_arg[idx];
},
10,
fut,
[](shape_type shape){ return std::vector<int>(shape); }, // results
[](shape_type shape){ return std::vector<int>(shape, 13); } // shared_arg
);
auto result = f.get();
assert(std::vector<int>(10, 7 + 13) == result);
}
int main()
{
test(bulk_synchronous_executor());
test(bulk_asynchronous_executor());
test(bulk_continuation_executor());
test(not_a_bulk_synchronous_executor());
test(not_a_bulk_asynchronous_executor());
test(not_a_bulk_continuation_executor());
test(complete_bulk_executor());
std::cout << "OK" << std::endl;
return 0;
}
<commit_msg>Eliminate unused variable<commit_after>#include <iostream>
#include <type_traits>
#include <vector>
#include <agency/future.hpp>
#include <agency/execution/executor/detail/new_executor_traits.hpp>
#include "test_executors.hpp"
template<class Executor>
void test(Executor exec)
{
using namespace agency::detail::new_executor_traits_detail;
auto fut = agency::detail::make_ready_future<int>(7);
using shape_type = executor_shape_t<Executor>;
using index_type = executor_index_t<Executor>;
auto f = bulk_then_execute(exec,
[](index_type idx, int& past_arg, std::vector<int>& results, std::vector<int>& shared_arg)
{
results[idx] = past_arg + shared_arg[idx];
},
10,
fut,
[](shape_type shape){ return std::vector<int>(shape); }, // results
[](shape_type shape){ return std::vector<int>(shape, 13); } // shared_arg
);
auto result = f.get();
assert(std::vector<int>(10, 7 + 13) == result);
}
int main()
{
test(bulk_synchronous_executor());
test(bulk_asynchronous_executor());
test(bulk_continuation_executor());
test(not_a_bulk_synchronous_executor());
test(not_a_bulk_asynchronous_executor());
test(not_a_bulk_continuation_executor());
test(complete_bulk_executor());
std::cout << "OK" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
// LLVM 'GCCAS' UTILITY
//
// This utility is designed to be used by the GCC frontend for creating
// bytecode files from it's intermediate llvm assembly. The requirements for
// this utility are thus slightly different than that of the standard as util.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Transforms/CleanupGCCOutput.h"
#include "llvm/Transforms/LevelChange.h"
#include "llvm/Transforms/ConstantMerge.h"
#include "llvm/Transforms/ChangeAllocations.h"
#include "llvm/Transforms/Scalar/DCE.h"
#include "llvm/Transforms/Scalar/GCSE.h"
#include "llvm/Transforms/Scalar/IndVarSimplify.h"
#include "llvm/Transforms/Scalar/InstructionCombining.h"
#include "llvm/Transforms/Scalar/PromoteMemoryToRegister.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "Support/CommandLine.h"
#include "Support/Signals.h"
#include <memory>
#include <fstream>
cl::String InputFilename ("", "Parse <arg> file, compile to bytecode",
cl::Required, "");
cl::String OutputFilename("o", "Override output filename", cl::NoFlags, "");
cl::Flag StopAtLevelRaise("stopraise", "Stop optimization before level raise",
cl::Hidden);
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n");
std::auto_ptr<Module> M;
try {
// Parse the file now...
M.reset(ParseAssemblyFile(InputFilename));
} catch (const ParseException &E) {
cerr << E.getMessage() << endl;
return 1;
}
if (M.get() == 0) {
cerr << "assembly didn't read correctly.\n";
return 1;
}
if (OutputFilename == "") { // Didn't specify an output filename?
std::string IFN = InputFilename;
int Len = IFN.length();
if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s?
OutputFilename = std::string(IFN.begin(), IFN.end()-2);
} else {
OutputFilename = IFN; // Append a .o to it
}
OutputFilename += ".o";
}
std::ofstream Out(OutputFilename.c_str(), ios::out);
if (!Out.good()) {
cerr << "Error opening " << OutputFilename << "!\n";
return 1;
}
// Make sure that the Out file gets unlink'd from the disk if we get a SIGINT
RemoveFileOnSignal(OutputFilename);
// In addition to just parsing the input from GCC, we also want to spiff it up
// a little bit. Do this now.
//
PassManager Passes;
Passes.add(createFunctionResolvingPass()); // Resolve (...) functions
Passes.add(createDeadInstEliminationPass()); // Remove Dead code/vars
Passes.add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
Passes.add(createCleanupGCCOutputPass()); // Fix gccisms
Passes.add(createIndVarSimplifyPass()); // Simplify indvars
if (!StopAtLevelRaise) {
Passes.add(createRaisePointerReferencesPass()); // Eliminate casts
Passes.add(createPromoteMemoryToRegister()); // Promote alloca's to regs
Passes.add(createConstantMergePass()); // Merge dup global consts
Passes.add(createInstructionCombiningPass()); // Combine silly seq's
Passes.add(createDeadCodeEliminationPass()); // Remove Dead code/vars
Passes.add(createGCSEPass()); // Remove common subexprs
}
Passes.add(new WriteBytecodePass(&Out)); // Write bytecode to file...
// Run our queue of passes all at once now, efficiently.
Passes.run(M.get());
return 0;
}
<commit_msg>Move constant merging pass earlier Include the SCCP pass in gccas<commit_after>//===----------------------------------------------------------------------===//
// LLVM 'GCCAS' UTILITY
//
// This utility is designed to be used by the GCC frontend for creating
// bytecode files from it's intermediate llvm assembly. The requirements for
// this utility are thus slightly different than that of the standard as util.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Transforms/CleanupGCCOutput.h"
#include "llvm/Transforms/LevelChange.h"
#include "llvm/Transforms/ConstantMerge.h"
#include "llvm/Transforms/ChangeAllocations.h"
#include "llvm/Transforms/Scalar/ConstantProp.h"
#include "llvm/Transforms/Scalar/DCE.h"
#include "llvm/Transforms/Scalar/GCSE.h"
#include "llvm/Transforms/Scalar/IndVarSimplify.h"
#include "llvm/Transforms/Scalar/InstructionCombining.h"
#include "llvm/Transforms/Scalar/PromoteMemoryToRegister.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "Support/CommandLine.h"
#include "Support/Signals.h"
#include <memory>
#include <fstream>
cl::String InputFilename ("", "Parse <arg> file, compile to bytecode",
cl::Required, "");
cl::String OutputFilename("o", "Override output filename", cl::NoFlags, "");
cl::Flag StopAtLevelRaise("stopraise", "Stop optimization before level raise",
cl::Hidden);
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n");
std::auto_ptr<Module> M;
try {
// Parse the file now...
M.reset(ParseAssemblyFile(InputFilename));
} catch (const ParseException &E) {
cerr << E.getMessage() << endl;
return 1;
}
if (M.get() == 0) {
cerr << "assembly didn't read correctly.\n";
return 1;
}
if (OutputFilename == "") { // Didn't specify an output filename?
std::string IFN = InputFilename;
int Len = IFN.length();
if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s?
OutputFilename = std::string(IFN.begin(), IFN.end()-2);
} else {
OutputFilename = IFN; // Append a .o to it
}
OutputFilename += ".o";
}
std::ofstream Out(OutputFilename.c_str(), ios::out);
if (!Out.good()) {
cerr << "Error opening " << OutputFilename << "!\n";
return 1;
}
// Make sure that the Out file gets unlink'd from the disk if we get a SIGINT
RemoveFileOnSignal(OutputFilename);
// In addition to just parsing the input from GCC, we also want to spiff it up
// a little bit. Do this now.
//
PassManager Passes;
Passes.add(createFunctionResolvingPass()); // Resolve (...) functions
Passes.add(createConstantMergePass()); // Merge dup global constants
Passes.add(createDeadInstEliminationPass()); // Remove Dead code/vars
Passes.add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
Passes.add(createCleanupGCCOutputPass()); // Fix gccisms
Passes.add(createIndVarSimplifyPass()); // Simplify indvars
if (!StopAtLevelRaise) {
Passes.add(createRaisePointerReferencesPass()); // Eliminate casts
Passes.add(createPromoteMemoryToRegister()); // Promote alloca's to regs
Passes.add(createInstructionCombiningPass()); // Combine silly seq's
Passes.add(createDeadCodeEliminationPass()); // Remove Dead code/vars
Passes.add(createSCCPPass()); // Constant prop with SCCP
Passes.add(createGCSEPass()); // Remove common subexprs
}
Passes.add(new WriteBytecodePass(&Out)); // Write bytecode to file...
// Run our queue of passes all at once now, efficiently.
Passes.run(M.get());
return 0;
}
<|endoftext|> |
<commit_before>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Authenticator.h"
#include "OSSupport/BlockingTCPLink.h"
#include "Root.h"
#include "Server.h"
#include "../lib/iniFile/iniFile.h"
#include <sstream>
#define DEFAULT_AUTH_SERVER "session.minecraft.net"
#define DEFAULT_AUTH_ADDRESS "/game/checkserver.jsp?user=%USERNAME%&serverId=%SERVERID%"
#define MAX_REDIRECTS 10
cAuthenticator::cAuthenticator(void) :
super("cAuthenticator"),
m_Server(DEFAULT_AUTH_SERVER),
m_Address(DEFAULT_AUTH_ADDRESS),
m_ShouldAuthenticate(true)
{
}
cAuthenticator::~cAuthenticator()
{
Stop();
}
/// Read custom values from INI
void cAuthenticator::ReadINI(cIniFile & IniFile)
{
m_Server = IniFile.GetValueSet("Authentication", "Server", DEFAULT_AUTH_SERVER);
m_Address = IniFile.GetValueSet("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
m_ShouldAuthenticate = IniFile.GetValueSetB("Authentication", "Authenticate", true);
}
/// Queues a request for authenticating a user. If the auth fails, the user is kicked
void cAuthenticator::Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash)
{
if (!m_ShouldAuthenticate)
{
cRoot::Get()->AuthenticateUser(a_ClientID);
return;
}
cCSLock Lock(m_CS);
m_Queue.push_back(cUser(a_ClientID, a_UserName, a_ServerHash));
m_QueueNonempty.Set();
}
void cAuthenticator::Start(cIniFile & IniFile)
{
ReadINI(IniFile);
m_ShouldTerminate = false;
super::Start();
}
void cAuthenticator::Stop(void)
{
m_ShouldTerminate = true;
m_QueueNonempty.Set();
Wait();
}
void cAuthenticator::Execute(void)
{
for (;;)
{
cCSLock Lock(m_CS);
while (!m_ShouldTerminate && (m_Queue.size() == 0))
{
cCSUnlock Unlock(Lock);
m_QueueNonempty.Wait();
}
if (m_ShouldTerminate)
{
return;
}
ASSERT(!m_Queue.empty());
int ClientID = m_Queue.front().m_ClientID;
AString UserName = m_Queue.front().m_Name;
AString ActualAddress = m_Address;
ReplaceString(ActualAddress, "%USERNAME%", UserName);
ReplaceString(ActualAddress, "%SERVERID%", m_Queue.front().m_ServerID);
m_Queue.pop_front();
Lock.Unlock();
if (!AuthFromAddress(m_Server, ActualAddress, UserName))
{
cRoot::Get()->KickUser(ClientID, "Failed to authenticate account!");
}
else
{
cRoot::Get()->AuthenticateUser(ClientID);
}
} // for (-ever)
}
bool cAuthenticator::AuthFromAddress(const AString & a_Server, const AString & a_Address, const AString & a_UserName, int a_Level /* = 1 */)
{
// Returns true if the user authenticated okay, false on error; iLevel is the recursion deptht (bails out if too deep)
cBlockingTCPLink Link;
if (!Link.Connect(a_Server.c_str(), 80))
{
LOGERROR("cAuthenticator: cannot connect to auth server \"%s\", kicking user \"%s\"", a_Server.c_str(), a_Server.c_str());
return false;
}
Link.SendMessage( AString( "GET " + a_Address + " HTTP/1.1\r\n" ).c_str());
Link.SendMessage( AString( "User-Agent: MCServer\r\n" ).c_str());
Link.SendMessage( AString( "Host: " + a_Server + "\r\n" ).c_str());
//Link.SendMessage( AString( "Host: session.minecraft.net\r\n" ).c_str());
Link.SendMessage( AString( "Accept: */*\r\n" ).c_str());
Link.SendMessage( AString( "Connection: close\r\n" ).c_str()); //Close so we dont have to mess with the Content-Length :)
Link.SendMessage( AString( "\r\n" ).c_str());
AString DataRecvd;
Link.ReceiveData(DataRecvd);
Link.CloseSocket();
std::stringstream ss(DataRecvd);
// Parse the data received:
std::string temp;
ss >> temp;
bool bRedirect = false;
bool bOK = false;
if ((temp.compare("HTTP/1.1") == 0) || (temp.compare("HTTP/1.0") == 0))
{
int code;
ss >> code;
if (code == 302)
{
// redirect blabla
LOGINFO("Need to redirect!");
if (a_Level > MAX_REDIRECTS)
{
LOGERROR("cAuthenticator: received too many levels of redirection from auth server \"%s\" for user \"%s\", bailing out and kicking the user", a_Server.c_str(), a_UserName.c_str());
return false;
}
bRedirect = true;
}
else if (code == 200)
{
LOGD("cAuthenticator: Received status 200 OK! :D");
bOK = true;
}
}
else
{
LOGERROR("cAuthenticator: cannot parse auth reply from server \"%s\" for user \"%s\", kicking the user.", a_Server.c_str(), a_UserName.c_str());
return false;
}
if( bRedirect )
{
AString Location;
// Search for "Location:"
bool bFoundLocation = false;
while( !bFoundLocation && ss.good() )
{
char c = 0;
while( c != '\n' )
{
ss.get( c );
}
AString Name;
ss >> Name;
if (Name.compare("Location:") == 0)
{
bFoundLocation = true;
ss >> Location;
}
}
if (!bFoundLocation)
{
LOGERROR("cAuthenticator: received invalid redirection from auth server \"%s\" for user \"%s\", kicking user.", a_Server.c_str(), a_UserName.c_str());
return false;
}
Location = Location.substr(strlen("http://"), std::string::npos); // Strip http://
std::string Server = Location.substr( 0, Location.find( "/" ) ); // Only leave server address
Location = Location.substr( Server.length(), std::string::npos);
return AuthFromAddress(Server, Location, a_UserName, a_Level + 1);
}
if (!bOK)
{
LOGERROR("cAuthenticator: received an error from auth server \"%s\" for user \"%s\", kicking user.", a_Server.c_str(), a_UserName.c_str());
return false;
}
// Header says OK, so receive the rest.
// Go past header, double \n means end of headers
char c = 0;
while (ss.good())
{
while (c != '\n')
{
ss.get(c);
}
ss.get(c);
if( c == '\n' || c == '\r' || ss.peek() == '\r' || ss.peek() == '\n' )
break;
}
if (!ss.good())
{
LOGERROR("cAuthenticator: error while parsing response body from auth server \"%s\" for user \"%s\", kicking user.", a_Server.c_str(), a_UserName.c_str());
return false;
}
std::string Result;
ss >> Result;
LOGD("cAuthenticator: Authentication result was %s", Result.c_str());
if (Result.compare("YES") == 0) //Works well
{
LOGINFO("Authentication result \"YES\", player authentication success!");
return true;
}
LOGINFO("Authentication result was \"%s\", player authentication failure!", Result.c_str());
return false;
}
<commit_msg>And another.<commit_after>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "Authenticator.h"
#include "OSSupport/BlockingTCPLink.h"
#include "Root.h"
#include "Server.h"
#include ".inifile/iniFile.h"
#include <sstream>
#define DEFAULT_AUTH_SERVER "session.minecraft.net"
#define DEFAULT_AUTH_ADDRESS "/game/checkserver.jsp?user=%USERNAME%&serverId=%SERVERID%"
#define MAX_REDIRECTS 10
cAuthenticator::cAuthenticator(void) :
super("cAuthenticator"),
m_Server(DEFAULT_AUTH_SERVER),
m_Address(DEFAULT_AUTH_ADDRESS),
m_ShouldAuthenticate(true)
{
}
cAuthenticator::~cAuthenticator()
{
Stop();
}
/// Read custom values from INI
void cAuthenticator::ReadINI(cIniFile & IniFile)
{
m_Server = IniFile.GetValueSet("Authentication", "Server", DEFAULT_AUTH_SERVER);
m_Address = IniFile.GetValueSet("Authentication", "Address", DEFAULT_AUTH_ADDRESS);
m_ShouldAuthenticate = IniFile.GetValueSetB("Authentication", "Authenticate", true);
}
/// Queues a request for authenticating a user. If the auth fails, the user is kicked
void cAuthenticator::Authenticate(int a_ClientID, const AString & a_UserName, const AString & a_ServerHash)
{
if (!m_ShouldAuthenticate)
{
cRoot::Get()->AuthenticateUser(a_ClientID);
return;
}
cCSLock Lock(m_CS);
m_Queue.push_back(cUser(a_ClientID, a_UserName, a_ServerHash));
m_QueueNonempty.Set();
}
void cAuthenticator::Start(cIniFile & IniFile)
{
ReadINI(IniFile);
m_ShouldTerminate = false;
super::Start();
}
void cAuthenticator::Stop(void)
{
m_ShouldTerminate = true;
m_QueueNonempty.Set();
Wait();
}
void cAuthenticator::Execute(void)
{
for (;;)
{
cCSLock Lock(m_CS);
while (!m_ShouldTerminate && (m_Queue.size() == 0))
{
cCSUnlock Unlock(Lock);
m_QueueNonempty.Wait();
}
if (m_ShouldTerminate)
{
return;
}
ASSERT(!m_Queue.empty());
int ClientID = m_Queue.front().m_ClientID;
AString UserName = m_Queue.front().m_Name;
AString ActualAddress = m_Address;
ReplaceString(ActualAddress, "%USERNAME%", UserName);
ReplaceString(ActualAddress, "%SERVERID%", m_Queue.front().m_ServerID);
m_Queue.pop_front();
Lock.Unlock();
if (!AuthFromAddress(m_Server, ActualAddress, UserName))
{
cRoot::Get()->KickUser(ClientID, "Failed to authenticate account!");
}
else
{
cRoot::Get()->AuthenticateUser(ClientID);
}
} // for (-ever)
}
bool cAuthenticator::AuthFromAddress(const AString & a_Server, const AString & a_Address, const AString & a_UserName, int a_Level /* = 1 */)
{
// Returns true if the user authenticated okay, false on error; iLevel is the recursion deptht (bails out if too deep)
cBlockingTCPLink Link;
if (!Link.Connect(a_Server.c_str(), 80))
{
LOGERROR("cAuthenticator: cannot connect to auth server \"%s\", kicking user \"%s\"", a_Server.c_str(), a_Server.c_str());
return false;
}
Link.SendMessage( AString( "GET " + a_Address + " HTTP/1.1\r\n" ).c_str());
Link.SendMessage( AString( "User-Agent: MCServer\r\n" ).c_str());
Link.SendMessage( AString( "Host: " + a_Server + "\r\n" ).c_str());
//Link.SendMessage( AString( "Host: session.minecraft.net\r\n" ).c_str());
Link.SendMessage( AString( "Accept: */*\r\n" ).c_str());
Link.SendMessage( AString( "Connection: close\r\n" ).c_str()); //Close so we dont have to mess with the Content-Length :)
Link.SendMessage( AString( "\r\n" ).c_str());
AString DataRecvd;
Link.ReceiveData(DataRecvd);
Link.CloseSocket();
std::stringstream ss(DataRecvd);
// Parse the data received:
std::string temp;
ss >> temp;
bool bRedirect = false;
bool bOK = false;
if ((temp.compare("HTTP/1.1") == 0) || (temp.compare("HTTP/1.0") == 0))
{
int code;
ss >> code;
if (code == 302)
{
// redirect blabla
LOGINFO("Need to redirect!");
if (a_Level > MAX_REDIRECTS)
{
LOGERROR("cAuthenticator: received too many levels of redirection from auth server \"%s\" for user \"%s\", bailing out and kicking the user", a_Server.c_str(), a_UserName.c_str());
return false;
}
bRedirect = true;
}
else if (code == 200)
{
LOGD("cAuthenticator: Received status 200 OK! :D");
bOK = true;
}
}
else
{
LOGERROR("cAuthenticator: cannot parse auth reply from server \"%s\" for user \"%s\", kicking the user.", a_Server.c_str(), a_UserName.c_str());
return false;
}
if( bRedirect )
{
AString Location;
// Search for "Location:"
bool bFoundLocation = false;
while( !bFoundLocation && ss.good() )
{
char c = 0;
while( c != '\n' )
{
ss.get( c );
}
AString Name;
ss >> Name;
if (Name.compare("Location:") == 0)
{
bFoundLocation = true;
ss >> Location;
}
}
if (!bFoundLocation)
{
LOGERROR("cAuthenticator: received invalid redirection from auth server \"%s\" for user \"%s\", kicking user.", a_Server.c_str(), a_UserName.c_str());
return false;
}
Location = Location.substr(strlen("http://"), std::string::npos); // Strip http://
std::string Server = Location.substr( 0, Location.find( "/" ) ); // Only leave server address
Location = Location.substr( Server.length(), std::string::npos);
return AuthFromAddress(Server, Location, a_UserName, a_Level + 1);
}
if (!bOK)
{
LOGERROR("cAuthenticator: received an error from auth server \"%s\" for user \"%s\", kicking user.", a_Server.c_str(), a_UserName.c_str());
return false;
}
// Header says OK, so receive the rest.
// Go past header, double \n means end of headers
char c = 0;
while (ss.good())
{
while (c != '\n')
{
ss.get(c);
}
ss.get(c);
if( c == '\n' || c == '\r' || ss.peek() == '\r' || ss.peek() == '\n' )
break;
}
if (!ss.good())
{
LOGERROR("cAuthenticator: error while parsing response body from auth server \"%s\" for user \"%s\", kicking user.", a_Server.c_str(), a_UserName.c_str());
return false;
}
std::string Result;
ss >> Result;
LOGD("cAuthenticator: Authentication result was %s", Result.c_str());
if (Result.compare("YES") == 0) //Works well
{
LOGINFO("Authentication result \"YES\", player authentication success!");
return true;
}
LOGINFO("Authentication result was \"%s\", player authentication failure!", Result.c_str());
return false;
}
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#include <vector>
#include <type_traits>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interface.hh>
#include <dune/gdt/space/interface.hh>
#include <dune/gdt/mapper/interface.hh>
namespace Dune {
namespace GDT {
template <class VectorImp>
class ConstLocalDoFVector
{
static_assert(std::is_base_of<Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
public:
typedef VectorImp VectorType;
typedef typename VectorType::ElementType ElementType;
template <class M, class EntityType>
ConstLocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, const VectorType& vector)
: vector_(vector)
, indices_(mapper.numDofs(entity))
{
mapper.globalIndices(entity, indices_);
}
~ConstLocalDoFVector()
{
}
size_t size() const
{
return indices_.size();
}
ElementType get(const size_t ii) const
{
assert(ii < indices_.size());
return vector_.get(indices_[ii]);
}
private:
const VectorType& vector_;
protected:
mutable Dune::DynamicVector<size_t> indices_;
}; // class ConstLocalDoFVector
template <class VectorImp>
class LocalDoFVector : public ConstLocalDoFVector<VectorImp>
{
typedef ConstLocalDoFVector<VectorImp> BaseType;
public:
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::ElementType ElementType;
template <class M, class EntityType>
LocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, VectorType& vector)
: BaseType(mapper, entity, vector)
, vector_(vector)
{
}
~LocalDoFVector()
{
}
void set(const size_t ii, const ElementType& val)
{
assert(ii < indices_.size());
vector_.set(indices_[ii], val);
}
void add(const size_t ii, const ElementType& val)
{
assert(ii < indices_.size());
vector_.add(indices_[ii], val);
}
private:
using BaseType::indices_;
VectorType& vector_;
}; // class LocalDoFVector
template <class SpaceImp, class VectorImp>
class ConstLocalDiscreteFunction
: public Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
SpaceImp::dimRangeCols>
{
static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
"SpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ElementType>::value,
"Types do not match!");
typedef Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
SpaceImp::dimRangeCols> BaseType;
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef SpaceImp SpaceType;
typedef VectorImp VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const unsigned int dimRangeRows = BaseType::dimRangeCols;
static const unsigned int dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef ConstLocalDoFVector<VectorType> ConstLocalDoFVectorType;
ConstLocalDiscreteFunction(const SpaceType& space, const VectorType& globalVector, const EntityType& ent)
: space_(space)
, entity_(ent)
, base_(new BaseFunctionSetType(space_.baseFunctionSet(entity_)))
, localVector_(new ConstLocalDoFVectorType(space_.mapper(), entity_, globalVector))
, tmpBaseValues_(base_->size(), RangeType(0))
, tmpBaseJacobianValues_(base_->size(), JacobianRangeType(0))
{
assert(localVector_->size() == base_->size());
}
ConstLocalDiscreteFunction(ThisType&& source)
: space_(source.space_)
, entity_(source.entity_)
, base_(std::move(source.base_))
, localVector_(std::move(source.localVector_))
, tmpBaseValues_(std::move(source.tmpBaseValues_))
, tmpBaseJacobianValues_(std::move(source.tmpBaseJacobianValues_))
{
}
ConstLocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
virtual ~ConstLocalDiscreteFunction()
{
}
virtual const EntityType& entity() const override
{
return entity_;
}
const ConstLocalDoFVectorType& vector() const
{
return *localVector_;
}
virtual size_t order() const override
{
return base_->order();
}
virtual void evaluate(const DomainType& xx, RangeType& ret) const override
{
assert(this->is_a_valid_point(xx));
Dune::Stuff::Common::clear(ret);
assert(localVector_->size() == tmpBaseValues_.size());
base_->evaluate(xx, tmpBaseValues_);
for (size_t ii = 0; ii < localVector_->size(); ++ii) {
tmpBaseValues_[ii] *= localVector_->get(ii);
ret += tmpBaseValues_[ii];
}
} // ... evaluate(...)
virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override
{
assert(this->is_a_valid_point(xx));
Dune::Stuff::Common::clear(ret);
assert(localVector_->size() == tmpBaseJacobianValues_.size());
base_->jacobian(xx, tmpBaseJacobianValues_);
for (size_t ii = 0; ii < localVector_->size(); ++ii) {
tmpBaseJacobianValues_[ii] *= localVector_->get(ii);
ret += tmpBaseJacobianValues_[ii];
}
} // ... jacobian(...)
protected:
const SpaceType& space_;
const EntityType& entity_;
std::unique_ptr<const BaseFunctionSetType> base_;
std::unique_ptr<const ConstLocalDoFVectorType> localVector_;
private:
mutable std::vector<RangeType> tmpBaseValues_;
mutable std::vector<JacobianRangeType> tmpBaseJacobianValues_;
}; // class ConstLocalDiscreteFunction
template <class SpaceImp, class VectorImp>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<SpaceImp, VectorImp>
{
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> BaseType;
typedef LocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef typename BaseType::SpaceType SpaceType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const unsigned int dimRangeRows = BaseType::dimRangeCols;
static const unsigned int dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef LocalDoFVector<VectorType> LocalDoFVectorType;
LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent)
: BaseType(space, globalVector, ent)
, localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
{
assert(localVector_->size() == base_->size());
}
LocalDiscreteFunction(ThisType&& source)
: BaseType(std::move(source))
, localVector_(std::move(source.localVector_)) // <- I am not sure if this is valid
{
}
LocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
virtual ~LocalDiscreteFunction()
{
}
LocalDoFVectorType& vector()
{
return *localVector_;
}
private:
using BaseType::space_;
using BaseType::entity_;
using BaseType::base_;
std::unique_ptr<LocalDoFVectorType> localVector_;
}; // class LocalDiscreteFunction
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
<commit_msg>[discretefunction.local] clear by *= 0<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#include <vector>
#include <type_traits>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interface.hh>
#include <dune/gdt/space/interface.hh>
#include <dune/gdt/mapper/interface.hh>
namespace Dune {
namespace GDT {
template <class VectorImp>
class ConstLocalDoFVector
{
static_assert(std::is_base_of<Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
public:
typedef VectorImp VectorType;
typedef typename VectorType::ElementType ElementType;
template <class M, class EntityType>
ConstLocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, const VectorType& vector)
: vector_(vector)
, indices_(mapper.numDofs(entity))
{
mapper.globalIndices(entity, indices_);
}
~ConstLocalDoFVector()
{
}
size_t size() const
{
return indices_.size();
}
ElementType get(const size_t ii) const
{
assert(ii < indices_.size());
return vector_.get(indices_[ii]);
}
private:
const VectorType& vector_;
protected:
mutable Dune::DynamicVector<size_t> indices_;
}; // class ConstLocalDoFVector
template <class VectorImp>
class LocalDoFVector : public ConstLocalDoFVector<VectorImp>
{
typedef ConstLocalDoFVector<VectorImp> BaseType;
public:
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::ElementType ElementType;
template <class M, class EntityType>
LocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, VectorType& vector)
: BaseType(mapper, entity, vector)
, vector_(vector)
{
}
~LocalDoFVector()
{
}
void set(const size_t ii, const ElementType& val)
{
assert(ii < indices_.size());
vector_.set(indices_[ii], val);
}
void add(const size_t ii, const ElementType& val)
{
assert(ii < indices_.size());
vector_.add(indices_[ii], val);
}
private:
using BaseType::indices_;
VectorType& vector_;
}; // class LocalDoFVector
template <class SpaceImp, class VectorImp>
class ConstLocalDiscreteFunction
: public Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
SpaceImp::dimRangeCols>
{
static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits>, SpaceImp>::value,
"SpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>, VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ElementType>::value,
"Types do not match!");
typedef Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
SpaceImp::dimRangeCols> BaseType;
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef SpaceImp SpaceType;
typedef VectorImp VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const unsigned int dimRangeRows = BaseType::dimRangeCols;
static const unsigned int dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef ConstLocalDoFVector<VectorType> ConstLocalDoFVectorType;
ConstLocalDiscreteFunction(const SpaceType& space, const VectorType& globalVector, const EntityType& ent)
: space_(space)
, entity_(ent)
, base_(new BaseFunctionSetType(space_.baseFunctionSet(entity_)))
, localVector_(new ConstLocalDoFVectorType(space_.mapper(), entity_, globalVector))
, tmpBaseValues_(base_->size(), RangeType(0))
, tmpBaseJacobianValues_(base_->size(), JacobianRangeType(0))
{
assert(localVector_->size() == base_->size());
}
ConstLocalDiscreteFunction(ThisType&& source)
: space_(source.space_)
, entity_(source.entity_)
, base_(std::move(source.base_))
, localVector_(std::move(source.localVector_))
, tmpBaseValues_(std::move(source.tmpBaseValues_))
, tmpBaseJacobianValues_(std::move(source.tmpBaseJacobianValues_))
{
}
ConstLocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
virtual ~ConstLocalDiscreteFunction()
{
}
virtual const EntityType& entity() const override
{
return entity_;
}
const ConstLocalDoFVectorType& vector() const
{
return *localVector_;
}
virtual size_t order() const override
{
return base_->order();
}
virtual void evaluate(const DomainType& xx, RangeType& ret) const override
{
assert(this->is_a_valid_point(xx));
Dune::Stuff::Common::clear(ret);
assert(localVector_->size() == tmpBaseValues_.size());
base_->evaluate(xx, tmpBaseValues_);
for (size_t ii = 0; ii < localVector_->size(); ++ii) {
tmpBaseValues_[ii] *= localVector_->get(ii);
ret += tmpBaseValues_[ii];
}
} // ... evaluate(...)
virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override
{
assert(this->is_a_valid_point(xx));
ret *= RangeFieldType(0);
assert(localVector_->size() == tmpBaseJacobianValues_.size());
base_->jacobian(xx, tmpBaseJacobianValues_);
for (size_t ii = 0; ii < localVector_->size(); ++ii) {
tmpBaseJacobianValues_[ii] *= localVector_->get(ii);
ret += tmpBaseJacobianValues_[ii];
}
} // ... jacobian(...)
protected:
const SpaceType& space_;
const EntityType& entity_;
std::unique_ptr<const BaseFunctionSetType> base_;
std::unique_ptr<const ConstLocalDoFVectorType> localVector_;
private:
mutable std::vector<RangeType> tmpBaseValues_;
mutable std::vector<JacobianRangeType> tmpBaseJacobianValues_;
}; // class ConstLocalDiscreteFunction
template <class SpaceImp, class VectorImp>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<SpaceImp, VectorImp>
{
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> BaseType;
typedef LocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef typename BaseType::SpaceType SpaceType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const unsigned int dimRangeRows = BaseType::dimRangeCols;
static const unsigned int dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef LocalDoFVector<VectorType> LocalDoFVectorType;
LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent)
: BaseType(space, globalVector, ent)
, localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
{
assert(localVector_->size() == base_->size());
}
LocalDiscreteFunction(ThisType&& source)
: BaseType(std::move(source))
, localVector_(std::move(source.localVector_)) // <- I am not sure if this is valid
{
}
LocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
virtual ~LocalDiscreteFunction()
{
}
LocalDoFVectorType& vector()
{
return *localVector_;
}
private:
using BaseType::space_;
using BaseType::entity_;
using BaseType::base_;
std::unique_ptr<LocalDoFVectorType> localVector_;
}; // class LocalDiscreteFunction
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
<|endoftext|> |
<commit_before>#include "schedulers/shortest_path_switch_scheduler.h"
DEFINE_bool(overtake, true, "Should car overtake others?");
// TODO refactor whole code here, its copypaste
using game::Position;
namespace schedulers {
ShortestPathSwitchScheduler::ShortestPathSwitchScheduler(
const game::Race& race,
game::RaceTracker& race_tracker,
game::CarTracker& car_tracker)
: race_(race), car_tracker_(car_tracker), race_tracker_(race_tracker),
should_switch_now_(false), waiting_for_switch_(false),
target_switch_(-1) {
//ComputeShortestPaths();
}
// Prepares for overtake
void ShortestPathSwitchScheduler::Overtake(const string& color) {
printf("Feature not implemented\n");
}
// Updates the state and calculates next state
// TODO switch time
void ShortestPathSwitchScheduler::Schedule(const game::CarState& state) {
if (state.position().piece() == target_switch_) {
waiting_for_switch_ = false;
target_switch_ = -1;
}
if (waiting_for_switch_)
return;
// TODO its greedy :D
const Position& position = state.position();
// We evaluate next two switches to decide if we should change the lane.
int from = race_.track().NextSwitch(position.piece());
int to = race_.track().NextSwitch(from);
// Distance between current position and the 'to' switch:
// - if we stay on current lane
// - if we decide to switch to left lane
// - if we decide to switch to right lane
Position end_position;
end_position.set_piece(to);
double current = DistanceBetween(position, end_position, position.end_lane());
double left = DistanceBetween(position, end_position, position.end_lane() - 1);
double right = DistanceBetween(position, end_position, position.end_lane() + 1);
// TODO(tomek) Improve:
// - we should "score" every lane, based on opponents on them
// - even if someone has very good lap, he can crashed and respawned
// - consider instead of distance, trying to estimate how much time
// it will take us to drive through given lanes
// Overtaking
if (FLAGS_overtake) {
int left_score = race_tracker_.ScoreLane(from, to, position.end_lane() - 1);
int right_score = race_tracker_.ScoreLane(from, to, position.end_lane() + 1);
int current_score = race_tracker_.ScoreLane(from, to, position.end_lane());
if (left_score < 0) left = kInf;
if (right_score < 0) right = kInf;
if (current_score < 0) current = kInf;
// Score is <-10, 0), 0 is best
// Nest part of algorithm chooses smallest so we need to reverse it temporarily
if (left_score < 0 && current_score < 0 && right_score < 0) {
left = -left_score;
current = -current_score;
right = -current_score;
}
}
printf("%lf %lf %lf\n",left, current, right);
if (left < current && left < right) {
scheduled_switch_ = game::Switch::kSwitchLeft;
target_switch_ = from;
should_switch_now_ = true;
} else if (right < current && right <= left) {
scheduled_switch_ = game::Switch::kSwitchRight;
target_switch_ = from;
should_switch_now_ = true;
} else {
should_switch_now_ = false;
target_switch_ = -1;
}
}
double ShortestPathSwitchScheduler::DistanceBetween(const Position& position1, const Position& position2, int lane) {
if (!race_.track().IsLaneCorrect(lane)) {
return kInf;
}
Position end_position = position2;
end_position.set_start_lane(lane);
end_position.set_end_lane(lane);
return car_tracker_.DistanceBetween(position1, end_position);
}
void ShortestPathSwitchScheduler::ComputeShortestPaths() {
// TODO
}
void ShortestPathSwitchScheduler::Switched() {
should_switch_now_ = false;
waiting_for_switch_ = true;
}
// Returns scheduled switch
bool ShortestPathSwitchScheduler::ShouldSwitch() {
if (should_switch_now_ &&
!waiting_for_switch_) {
auto s = car_tracker_.current_state();
s = car_tracker_.Predict(s, game::Command(1));
s = car_tracker_.Predict(s, game::Command(1));
if (s.position().piece() != target_switch_)
return false;
if (car_tracker_.current_state().velocity() > 0 &&
car_tracker_.IsSafe(car_tracker_.current_state(), game::Command(scheduled_switch_)))
return true;
}
return false;
}
game::Switch ShortestPathSwitchScheduler::ExpectedSwitch() {
if (should_switch_now_ && !waiting_for_switch_)
return scheduled_switch_;
return game::Switch::kStay;
}
game::Switch ShortestPathSwitchScheduler::SwitchDirection() {
return scheduled_switch_;
}
} // namespace schedulers
<commit_msg>Improve log<commit_after>#include "schedulers/shortest_path_switch_scheduler.h"
DEFINE_bool(overtake, true, "Should car overtake others?");
// TODO refactor whole code here, its copypaste
using game::Position;
namespace schedulers {
ShortestPathSwitchScheduler::ShortestPathSwitchScheduler(
const game::Race& race,
game::RaceTracker& race_tracker,
game::CarTracker& car_tracker)
: race_(race), car_tracker_(car_tracker), race_tracker_(race_tracker),
should_switch_now_(false), waiting_for_switch_(false),
target_switch_(-1) {
//ComputeShortestPaths();
}
// Prepares for overtake
void ShortestPathSwitchScheduler::Overtake(const string& color) {
printf("Feature not implemented\n");
}
// Updates the state and calculates next state
// TODO switch time
void ShortestPathSwitchScheduler::Schedule(const game::CarState& state) {
if (state.position().piece() == target_switch_) {
waiting_for_switch_ = false;
target_switch_ = -1;
}
if (waiting_for_switch_)
return;
// TODO its greedy :D
const Position& position = state.position();
// We evaluate next two switches to decide if we should change the lane.
int from = race_.track().NextSwitch(position.piece());
int to = race_.track().NextSwitch(from);
// Distance between current position and the 'to' switch:
// - if we stay on current lane
// - if we decide to switch to left lane
// - if we decide to switch to right lane
Position end_position;
end_position.set_piece(to);
double current = DistanceBetween(position, end_position, position.end_lane());
double left = DistanceBetween(position, end_position, position.end_lane() - 1);
double right = DistanceBetween(position, end_position, position.end_lane() + 1);
// TODO(tomek) Improve:
// - we should "score" every lane, based on opponents on them
// - even if someone has very good lap, he can crashed and respawned
// - consider instead of distance, trying to estimate how much time
// it will take us to drive through given lanes
// Overtaking
if (FLAGS_overtake) {
int left_score = race_tracker_.ScoreLane(from, to, position.end_lane() - 1);
int right_score = race_tracker_.ScoreLane(from, to, position.end_lane() + 1);
int current_score = race_tracker_.ScoreLane(from, to, position.end_lane());
if (left_score < 0) left = kInf;
if (right_score < 0) right = kInf;
if (current_score < 0) current = kInf;
// Score is <-10, 0), 0 is best
// Nest part of algorithm chooses smallest so we need to reverse it temporarily
if (left_score < 0 && current_score < 0 && right_score < 0) {
left = -left_score;
current = -current_score;
right = -current_score;
}
}
printf("Lane scores (l c r): %lf %lf %lf\n",left, current, right);
if (left < current && left < right) {
scheduled_switch_ = game::Switch::kSwitchLeft;
target_switch_ = from;
should_switch_now_ = true;
} else if (right < current && right <= left) {
scheduled_switch_ = game::Switch::kSwitchRight;
target_switch_ = from;
should_switch_now_ = true;
} else {
should_switch_now_ = false;
target_switch_ = -1;
}
}
double ShortestPathSwitchScheduler::DistanceBetween(const Position& position1, const Position& position2, int lane) {
if (!race_.track().IsLaneCorrect(lane)) {
return kInf;
}
Position end_position = position2;
end_position.set_start_lane(lane);
end_position.set_end_lane(lane);
return car_tracker_.DistanceBetween(position1, end_position);
}
void ShortestPathSwitchScheduler::ComputeShortestPaths() {
// TODO
}
void ShortestPathSwitchScheduler::Switched() {
should_switch_now_ = false;
waiting_for_switch_ = true;
}
// Returns scheduled switch
bool ShortestPathSwitchScheduler::ShouldSwitch() {
if (should_switch_now_ &&
!waiting_for_switch_) {
auto s = car_tracker_.current_state();
s = car_tracker_.Predict(s, game::Command(1));
s = car_tracker_.Predict(s, game::Command(1));
if (s.position().piece() != target_switch_)
return false;
if (car_tracker_.current_state().velocity() > 0 &&
car_tracker_.IsSafe(car_tracker_.current_state(), game::Command(scheduled_switch_)))
return true;
}
return false;
}
game::Switch ShortestPathSwitchScheduler::ExpectedSwitch() {
if (should_switch_now_ && !waiting_for_switch_)
return scheduled_switch_;
return game::Switch::kStay;
}
game::Switch ShortestPathSwitchScheduler::SwitchDirection() {
return scheduled_switch_;
}
} // namespace schedulers
<|endoftext|> |
<commit_before>/** @file propertyeditorproxymodel.cpp
* @brief Модель редактора свойств
* */
#include <QDebug>
#include "propertyeditorproxymodel.h"
#include "realreporoles.h"
PropertyEditorModel::PropertyEditorModel(QObject *parent)
: QAbstractTableModel(parent), type(""), mPseudoAttributesCount(0)
{
}
int PropertyEditorModel::rowCount(const QModelIndex&) const
{
return roleNames.size();
}
int PropertyEditorModel::columnCount(const QModelIndex&) const
{
return 2;
}
Qt::ItemFlags PropertyEditorModel::flags (const QModelIndex &index) const
{
// Property names
if (index.column() == 0)
return Qt::ItemIsEnabled;
// Object id
if (index.row() < mPseudoAttributesCount)
return Qt::NoItemFlags;
// Other properties
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
}
QVariant PropertyEditorModel::headerData(int section, Qt::Orientation orientation, int role) const
{
// if ( ! targetModel )
// return QVariant();
if (role == Qt::DisplayRole && orientation == Qt::Horizontal)
return QString(section ? "value" : "name");
else
return QVariant();
}
QVariant PropertyEditorModel::data(const QModelIndex &index, int role) const
{
// if ( ! targetModel )
// return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
if (index.column() == 0) {
return roleNames.at(index.row());
} else if (index.column() == 1) {
if (index.row() != 0)
return targetObject.data(info.roleByIndex(index.row() - mPseudoAttributesCount));
else
return QVariant(type);
} else
return QVariant();
}
bool PropertyEditorModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
bool ret;
if ( ! targetModel )
return false;
if ( ( role == Qt::DisplayRole || role == Qt::EditRole ) && index.column() == 1 )
if (index.row() != 0)
ret = targetModel->setData(targetObject, value, info.roleByIndex(index.row() - mPseudoAttributesCount));
else
ret = true;
else
ret = false;
if (ret)
dataChanged(index, index);
return ret;
}
void PropertyEditorModel::rereadData()
{
reset();
}
void PropertyEditorModel::setSourceModel(QAbstractItemModel *sourceModel)
{
targetModel = sourceModel;
roleNames.clear();
if ( targetModel )
connect ( targetModel, SIGNAL( dataChanged (const QModelIndex &, const QModelIndex&) ),
this, SLOT( rereadData() ) );
reset();
}
void PropertyEditorModel::setIndex(const QModelIndex &sourceIndex)
{
if ( sourceIndex.model() != targetModel )
return;
targetObject = sourceIndex;
type = targetObject.data(Unreal::TypeRole).toString();
roleNames = info.getColumnNames(type);
roleNames.push_front("metatype");
mPseudoAttributesCount = 1;
reset();
}
<commit_msg>Фикс к #126.<commit_after>/** @file propertyeditorproxymodel.cpp
* @brief Модель редактора свойств
* */
#include <QDebug>
#include "propertyeditorproxymodel.h"
#include "realreporoles.h"
PropertyEditorModel::PropertyEditorModel(QObject *parent)
: QAbstractTableModel(parent), type(""), mPseudoAttributesCount(0)
{
}
int PropertyEditorModel::rowCount(const QModelIndex&) const
{
return roleNames.size();
}
int PropertyEditorModel::columnCount(const QModelIndex&) const
{
return 2;
}
Qt::ItemFlags PropertyEditorModel::flags (const QModelIndex &index) const
{
// Property names
if (index.column() == 0)
return Qt::ItemIsEnabled;
// Object id
if (index.row() < mPseudoAttributesCount)
return Qt::NoItemFlags;
// Other properties
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
}
QVariant PropertyEditorModel::headerData(int section, Qt::Orientation orientation, int role) const
{
// if ( ! targetModel )
// return QVariant();
if (role == Qt::DisplayRole && orientation == Qt::Horizontal)
return QString(section ? "value" : "name");
else
return QVariant();
}
QVariant PropertyEditorModel::data(const QModelIndex &index, int role) const
{
// if ( ! targetModel )
// return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
if (index.column() == 0) {
return roleNames.at(index.row());
} else if (index.column() == 1) {
if (index.row() >= mPseudoAttributesCount)
return targetObject.data(info.roleByIndex(index.row() - mPseudoAttributesCount));
else if (index.row() == 0)
return QVariant(type);
else
return targetObject.data(Unreal::IdRole);
} else
return QVariant();
}
bool PropertyEditorModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
bool ret;
if ( ! targetModel )
return false;
if ( ( role == Qt::DisplayRole || role == Qt::EditRole ) && index.column() == 1 )
if (index.row() != 0)
ret = targetModel->setData(targetObject, value, info.roleByIndex(index.row() - mPseudoAttributesCount));
else
ret = true;
else
ret = false;
if (ret)
dataChanged(index, index);
return ret;
}
void PropertyEditorModel::rereadData()
{
reset();
}
void PropertyEditorModel::setSourceModel(QAbstractItemModel *sourceModel)
{
targetModel = sourceModel;
roleNames.clear();
if ( targetModel )
connect ( targetModel, SIGNAL( dataChanged (const QModelIndex &, const QModelIndex&) ),
this, SLOT( rereadData() ) );
reset();
}
void PropertyEditorModel::setIndex(const QModelIndex &sourceIndex)
{
if ( sourceIndex.model() != targetModel )
return;
targetObject = sourceIndex;
type = targetObject.data(Unreal::TypeRole).toString();
roleNames = info.getColumnNames(type);
roleNames.push_front("repo_id");
roleNames.push_front("metatype");
mPseudoAttributesCount = 2;
reset();
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** 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 [email protected].
**
**************************************************************************/
#include "qmlprofilersummaryview.h"
#include <QtCore/QUrl>
#include <QtCore/QHash>
#include <QtGui/QHeaderView>
#include <QtGui/QStandardItemModel>
using namespace QmlProfiler::Internal;
struct BindingData {
QString displayname;
QString filename;
int line;
qint64 duration;
qint64 calls;
qint64 minTime;
qint64 maxTime;
double tpc;
double percent;
};
class QmlProfilerSummaryView::QmlProfilerSummaryViewPrivate
{
public:
QmlProfilerSummaryViewPrivate(QmlProfilerSummaryView *qq):q(qq) {}
~QmlProfilerSummaryViewPrivate() {}
QmlProfilerSummaryView *q;
QStandardItemModel *m_model;
QHash<QString, BindingData *> m_bindingHash;
enum RangeType {
Painting,
Compiling,
Creating,
Binding,
HandlingSignal,
MaximumRangeType
};
};
class ProfilerItem : public QStandardItem
{
public:
ProfilerItem(const QString &text):QStandardItem ( text ) {}
virtual bool operator< ( const QStandardItem & other ) const
{
if (data().type() == QVariant::String) {
// first column
return data(Qt::UserRole+2).toString() == other.data(Qt::UserRole+2).toString() ?
data(Qt::UserRole+3).toInt() < other.data(Qt::UserRole+3).toInt() :
data(Qt::UserRole+2).toString() < other.data(Qt::UserRole+2).toString();
}
return data().toDouble() < other.data().toDouble();
}
};
QmlProfilerSummaryView::QmlProfilerSummaryView(QWidget *parent) :
QTreeView(parent), d(new QmlProfilerSummaryViewPrivate(this))
{
setRootIsDecorated(false);
header()->setResizeMode(QHeaderView::Interactive);
header()->setMinimumSectionSize(100);
setSortingEnabled(false);
d->m_model = new QStandardItemModel(this);
setModel(d->m_model);
d->m_model->setColumnCount(7);
setHeaderLabels();
connect(this,SIGNAL(clicked(QModelIndex)), this,SLOT(jumpToItem(QModelIndex)));
}
QmlProfilerSummaryView::~QmlProfilerSummaryView()
{
delete d->m_model;
}
void QmlProfilerSummaryView::clean()
{
d->m_model->clear();
d->m_model->setColumnCount(7);
// clean the hash
QHashIterator<QString, BindingData *>it(d->m_bindingHash);
while (it.hasNext()) {
it.next();
delete it.value();
}
d->m_bindingHash.clear();
setHeaderLabels();
setSortingEnabled(false);
}
void QmlProfilerSummaryView::addRangedEvent(int type, qint64 startTime, qint64 length, const QStringList &data, const QString &fileName, int line)
{
Q_UNUSED(startTime);
Q_UNUSED(data);
if (type != QmlProfilerSummaryViewPrivate::Binding && type != QmlProfilerSummaryViewPrivate::HandlingSignal)
return;
if (fileName.isEmpty())
return;
QString localName = QUrl(fileName).toLocalFile();
QString displayName = localName.mid(localName.lastIndexOf(QChar('/'))+1)+QLatin1String(":")+QString::number(line);
QString location = fileName+":"+QString::number(line);
QHash<QString, BindingData *>::iterator it = d->m_bindingHash.find(location);
if (it != d->m_bindingHash.end()) {
BindingData *bindingInfo = it.value();
bindingInfo->duration += length;
bindingInfo->calls++;
if (bindingInfo->maxTime < length)
bindingInfo->maxTime = length;
if (bindingInfo->minTime > length)
bindingInfo->minTime = length;
} else {
BindingData *newBinding = new BindingData;
newBinding->calls = 1;
newBinding->duration = length;
newBinding->displayname = displayName;
newBinding->filename = fileName;
newBinding->line = line;
newBinding->minTime = length;
newBinding->maxTime = length;
d->m_bindingHash.insert(location, newBinding);
}
}
void QmlProfilerSummaryView::complete()
{
// compute percentages
double totalTime = 0;
QHashIterator<QString, BindingData *> it(d->m_bindingHash);
while (it.hasNext()) {
it.next();
totalTime += it.value()->duration;
}
it.toFront();
while (it.hasNext()) {
it.next();
BindingData *binding = it.value();
binding->percent = binding->duration * 100.0 / totalTime;
binding->tpc = binding->calls>0? (double)binding->duration / binding->calls : 0;
appendRow(binding->displayname,
binding->filename,
binding->line,
binding->percent,
binding->duration,
binding->calls,
binding->tpc,
binding->maxTime,
binding->minTime);
}
setSortingEnabled(true);
sortByColumn(1,Qt::DescendingOrder);
resizeColumnToContents(0);
}
void QmlProfilerSummaryView::jumpToItem(const QModelIndex &index)
{
int line = d->m_model->item(index.row(),0)->data(Qt::UserRole+3).toInt();
if (line == -1)
return;
QString fileName = d->m_model->item(index.row(),0)->data(Qt::UserRole+2).toString();
emit gotoSourceLocation(fileName, line);
}
void QmlProfilerSummaryView::appendRow(const QString &displayName,
const QString &fileName,
int line,
double percentTime,
double totalTime,
int nCalls,
double timePerCall,
double maxTime,
double minTime)
{
QString location =fileName+":"+QString::number(line);
ProfilerItem *locationColumn = new ProfilerItem(displayName);
locationColumn->setData(QVariant(location),Qt::UserRole+1);
locationColumn->setData(QVariant(fileName),Qt::UserRole+2);
locationColumn->setData(QVariant(line),Qt::UserRole+3);
locationColumn->setEditable(false);
ProfilerItem *percentColumn = new ProfilerItem(QString::number(percentTime,'f',2)+QLatin1String(" %"));
percentColumn->setData(QVariant(percentTime));
percentColumn->setEditable(false);
ProfilerItem *timeColumn = new ProfilerItem(displayTime(totalTime));
timeColumn->setData(QVariant(totalTime));
timeColumn->setEditable(false);
ProfilerItem *callsColumn = new ProfilerItem(QString::number(nCalls));
callsColumn->setData(QVariant(nCalls));
callsColumn->setEditable(false);
ProfilerItem *tpcColumn = new ProfilerItem(displayTime(timePerCall));
tpcColumn->setData(QVariant(timePerCall));
tpcColumn->setEditable(false);
ProfilerItem *maxTimeColumn = new ProfilerItem(displayTime(maxTime));
maxTimeColumn->setData(QVariant(maxTime));
maxTimeColumn->setEditable(false);
ProfilerItem *minTimeColumn = new ProfilerItem(displayTime(minTime));
minTimeColumn->setData(QVariant(minTime));
minTimeColumn->setEditable(false);
QList<QStandardItem *> newRow;
newRow << locationColumn << percentColumn << timeColumn << callsColumn << tpcColumn << maxTimeColumn << minTimeColumn;
d->m_model->appendRow(newRow);
}
QString QmlProfilerSummaryView::displayTime(double time) const
{
if (time<1e6)
return QString::number(time/1e3,'f',3) + QString::fromUtf8(" \u03BCs");//(" \u03BCs");
if (time<1e9)
return QString::number(time/1e6,'f',3) + QLatin1String(" ms");
return QString::number(time/1e9,'f',3) + QLatin1String(" s");
}
void QmlProfilerSummaryView::setHeaderLabels()
{
d->m_model->setHeaderData(0,Qt::Horizontal,QVariant(tr("location")));
d->m_model->setHeaderData(1,Qt::Horizontal,QVariant(tr("% time")));
d->m_model->setHeaderData(2,Qt::Horizontal,QVariant(tr("total time")));
d->m_model->setHeaderData(3,Qt::Horizontal,QVariant(tr("calls")));
d->m_model->setHeaderData(4,Qt::Horizontal,QVariant(tr("time per call")));
d->m_model->setHeaderData(5,Qt::Horizontal,QVariant(tr("longest time")));
d->m_model->setHeaderData(6,Qt::Horizontal,QVariant(tr("shortest time")));
}
<commit_msg>QmlProfiler: Fix MSVC warning about character encoding<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** 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 [email protected].
**
**************************************************************************/
#include "qmlprofilersummaryview.h"
#include <QtCore/QUrl>
#include <QtCore/QHash>
#include <QtGui/QHeaderView>
#include <QtGui/QStandardItemModel>
using namespace QmlProfiler::Internal;
struct BindingData {
QString displayname;
QString filename;
int line;
qint64 duration;
qint64 calls;
qint64 minTime;
qint64 maxTime;
double tpc;
double percent;
};
class QmlProfilerSummaryView::QmlProfilerSummaryViewPrivate
{
public:
QmlProfilerSummaryViewPrivate(QmlProfilerSummaryView *qq):q(qq) {}
~QmlProfilerSummaryViewPrivate() {}
QmlProfilerSummaryView *q;
QStandardItemModel *m_model;
QHash<QString, BindingData *> m_bindingHash;
enum RangeType {
Painting,
Compiling,
Creating,
Binding,
HandlingSignal,
MaximumRangeType
};
};
class ProfilerItem : public QStandardItem
{
public:
ProfilerItem(const QString &text):QStandardItem ( text ) {}
virtual bool operator< ( const QStandardItem & other ) const
{
if (data().type() == QVariant::String) {
// first column
return data(Qt::UserRole+2).toString() == other.data(Qt::UserRole+2).toString() ?
data(Qt::UserRole+3).toInt() < other.data(Qt::UserRole+3).toInt() :
data(Qt::UserRole+2).toString() < other.data(Qt::UserRole+2).toString();
}
return data().toDouble() < other.data().toDouble();
}
};
QmlProfilerSummaryView::QmlProfilerSummaryView(QWidget *parent) :
QTreeView(parent), d(new QmlProfilerSummaryViewPrivate(this))
{
setRootIsDecorated(false);
header()->setResizeMode(QHeaderView::Interactive);
header()->setMinimumSectionSize(100);
setSortingEnabled(false);
d->m_model = new QStandardItemModel(this);
setModel(d->m_model);
d->m_model->setColumnCount(7);
setHeaderLabels();
connect(this,SIGNAL(clicked(QModelIndex)), this,SLOT(jumpToItem(QModelIndex)));
}
QmlProfilerSummaryView::~QmlProfilerSummaryView()
{
delete d->m_model;
}
void QmlProfilerSummaryView::clean()
{
d->m_model->clear();
d->m_model->setColumnCount(7);
// clean the hash
QHashIterator<QString, BindingData *>it(d->m_bindingHash);
while (it.hasNext()) {
it.next();
delete it.value();
}
d->m_bindingHash.clear();
setHeaderLabels();
setSortingEnabled(false);
}
void QmlProfilerSummaryView::addRangedEvent(int type, qint64 startTime, qint64 length, const QStringList &data, const QString &fileName, int line)
{
Q_UNUSED(startTime);
Q_UNUSED(data);
if (type != QmlProfilerSummaryViewPrivate::Binding && type != QmlProfilerSummaryViewPrivate::HandlingSignal)
return;
if (fileName.isEmpty())
return;
QString localName = QUrl(fileName).toLocalFile();
QString displayName = localName.mid(localName.lastIndexOf(QChar('/'))+1)+QLatin1String(":")+QString::number(line);
QString location = fileName+":"+QString::number(line);
QHash<QString, BindingData *>::iterator it = d->m_bindingHash.find(location);
if (it != d->m_bindingHash.end()) {
BindingData *bindingInfo = it.value();
bindingInfo->duration += length;
bindingInfo->calls++;
if (bindingInfo->maxTime < length)
bindingInfo->maxTime = length;
if (bindingInfo->minTime > length)
bindingInfo->minTime = length;
} else {
BindingData *newBinding = new BindingData;
newBinding->calls = 1;
newBinding->duration = length;
newBinding->displayname = displayName;
newBinding->filename = fileName;
newBinding->line = line;
newBinding->minTime = length;
newBinding->maxTime = length;
d->m_bindingHash.insert(location, newBinding);
}
}
void QmlProfilerSummaryView::complete()
{
// compute percentages
double totalTime = 0;
QHashIterator<QString, BindingData *> it(d->m_bindingHash);
while (it.hasNext()) {
it.next();
totalTime += it.value()->duration;
}
it.toFront();
while (it.hasNext()) {
it.next();
BindingData *binding = it.value();
binding->percent = binding->duration * 100.0 / totalTime;
binding->tpc = binding->calls>0? (double)binding->duration / binding->calls : 0;
appendRow(binding->displayname,
binding->filename,
binding->line,
binding->percent,
binding->duration,
binding->calls,
binding->tpc,
binding->maxTime,
binding->minTime);
}
setSortingEnabled(true);
sortByColumn(1,Qt::DescendingOrder);
resizeColumnToContents(0);
}
void QmlProfilerSummaryView::jumpToItem(const QModelIndex &index)
{
int line = d->m_model->item(index.row(),0)->data(Qt::UserRole+3).toInt();
if (line == -1)
return;
QString fileName = d->m_model->item(index.row(),0)->data(Qt::UserRole+2).toString();
emit gotoSourceLocation(fileName, line);
}
void QmlProfilerSummaryView::appendRow(const QString &displayName,
const QString &fileName,
int line,
double percentTime,
double totalTime,
int nCalls,
double timePerCall,
double maxTime,
double minTime)
{
QString location =fileName+":"+QString::number(line);
ProfilerItem *locationColumn = new ProfilerItem(displayName);
locationColumn->setData(QVariant(location),Qt::UserRole+1);
locationColumn->setData(QVariant(fileName),Qt::UserRole+2);
locationColumn->setData(QVariant(line),Qt::UserRole+3);
locationColumn->setEditable(false);
ProfilerItem *percentColumn = new ProfilerItem(QString::number(percentTime,'f',2)+QLatin1String(" %"));
percentColumn->setData(QVariant(percentTime));
percentColumn->setEditable(false);
ProfilerItem *timeColumn = new ProfilerItem(displayTime(totalTime));
timeColumn->setData(QVariant(totalTime));
timeColumn->setEditable(false);
ProfilerItem *callsColumn = new ProfilerItem(QString::number(nCalls));
callsColumn->setData(QVariant(nCalls));
callsColumn->setEditable(false);
ProfilerItem *tpcColumn = new ProfilerItem(displayTime(timePerCall));
tpcColumn->setData(QVariant(timePerCall));
tpcColumn->setEditable(false);
ProfilerItem *maxTimeColumn = new ProfilerItem(displayTime(maxTime));
maxTimeColumn->setData(QVariant(maxTime));
maxTimeColumn->setEditable(false);
ProfilerItem *minTimeColumn = new ProfilerItem(displayTime(minTime));
minTimeColumn->setData(QVariant(minTime));
minTimeColumn->setEditable(false);
QList<QStandardItem *> newRow;
newRow << locationColumn << percentColumn << timeColumn << callsColumn << tpcColumn << maxTimeColumn << minTimeColumn;
d->m_model->appendRow(newRow);
}
QString QmlProfilerSummaryView::displayTime(double time) const
{
if (time<1e6)
return QString::number(time/1e3,'f',3) + QString::fromWCharArray(L" \u03BCs");
if (time<1e9)
return QString::number(time/1e6,'f',3) + QLatin1String(" ms");
return QString::number(time/1e9,'f',3) + QLatin1String(" s");
}
void QmlProfilerSummaryView::setHeaderLabels()
{
d->m_model->setHeaderData(0,Qt::Horizontal,QVariant(tr("location")));
d->m_model->setHeaderData(1,Qt::Horizontal,QVariant(tr("% time")));
d->m_model->setHeaderData(2,Qt::Horizontal,QVariant(tr("total time")));
d->m_model->setHeaderData(3,Qt::Horizontal,QVariant(tr("calls")));
d->m_model->setHeaderData(4,Qt::Horizontal,QVariant(tr("time per call")));
d->m_model->setHeaderData(5,Qt::Horizontal,QVariant(tr("longest time")));
d->m_model->setHeaderData(6,Qt::Horizontal,QVariant(tr("shortest time")));
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// BZFlag common header
#include "common.h"
// interface header
#include "TextUtils.h"
// system headers
#include <string.h>
#include <string>
#include <algorithm>
#include <sstream>
#include <stdarg.h>
#include <vector>
#include <stdio.h>
#ifndef _TEXT_UTIL_NO_REGEX_
// common headers
#include "bzregex.h"
#endif //_TEXT_UTIL_NO_REGEX_
namespace TextUtils
{
std::string vformat(const char* fmt, va_list args) {
const int fixedbs = 8192;
char buffer[fixedbs];
const int bs = vsnprintf(buffer, fixedbs, fmt, args) + 1;
if (bs > fixedbs) {
char *bufp = new char[bs];
vsnprintf(bufp, bs, fmt, args);
std::string ret = bufp;
delete[] bufp;
return ret;
}
return buffer;
}
std::string format(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
std::string result = vformat(fmt, args);
va_end(args);
return result;
}
std::wstring convert_to_wide(const std::string& string)
{
#ifdef _WIN32 // Get the required size for the new array and allocate the memory for it
int neededSize = MultiByteToWideChar(CP_ACP, 0, string.c_str(), -1, 0, 0);
wchar_t* wideCharString = new wchar_t[neededSize];
MultiByteToWideChar(CP_ACP, 0, string.c_str(), -1, wideCharString, neededSize);
std::wstring wideString(wideCharString);
delete[] wideCharString;
return wideString;
#else
// borrowed from a message by Paul McKenzie at
// http://www.codeguru.com/forum/archive/index.php/t-193852.html
// FIXME: This probably does not perform the desired conversion, but
// at least it compiles cleanly. Probably, mbstowcs() should be used.
std::wstring temp(string.length(),L' ');
std::copy(string.begin(), string.end(), temp.begin());
return temp;
#endif // _WIN32
}
std::string replace_all(const std::string& in, const std::string& replaceMe, const std::string& withMe)
{
std::string result;
std::string::size_type beginPos = 0;
std::string::size_type endPos = 0;
std::ostringstream tempStream;
endPos = in.find(replaceMe);
if (endPos == std::string::npos)
return in; // can't find anything to replace
if (replaceMe.empty()) return in; // can't replace nothing with something -- can do reverse
while (endPos != std::string::npos) {
// push the part up to
tempStream << in.substr(beginPos,endPos-beginPos);
tempStream << withMe;
beginPos = endPos + replaceMe.size();
endPos = in.find(replaceMe,beginPos);
}
tempStream << in.substr(beginPos);
return tempStream.str();
}
std::string no_whitespace(const std::string &s)
{
const int sourcesize = (int)s.size();
int count = 0, i = 0, j = 0;
for (i = 0; i < sourcesize; i++)
if (!isWhitespace(s[i]))
count++;
// create result string of correct size
std::string result(count, ' ');
for (i = 0, j = 0; i < sourcesize; i++)
if (!isWhitespace(s[i]))
result[j++] = s[i];
return result;
}
std::vector<std::string> tokenize(const std::string& in, const std::string &delims, const int maxTokens, const bool useQuotes){
std::vector<std::string> tokens;
int numTokens = 0;
bool inQuote = false;
std::ostringstream currentToken;
const std::string::size_type len = in.size();
std::string::size_type pos = in.find_first_not_of(delims);
int currentChar = (pos == std::string::npos) ? -1 : in[pos];
bool enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));
while (pos < len && pos != std::string::npos && !enoughTokens) {
// get next token
bool tokenDone = false;
bool foundSlash = false;
currentChar = (pos < len) ? in[pos] : -1;
while ((currentChar != -1) && !tokenDone){
tokenDone = false;
if (delims.find(currentChar) != std::string::npos && !inQuote) { // currentChar is a delim
pos ++;
break; // breaks out of inner while loop
}
if (!useQuotes){
currentToken << char(currentChar);
} else {
switch (currentChar){
case '\\' : // found a backslash
if (foundSlash){
currentToken << char(currentChar);
foundSlash = false;
} else {
foundSlash = true;
}
break;
case '\"' : // found a quote
if (foundSlash){ // found \"
currentToken << char(currentChar);
foundSlash = false;
} else { // found unescaped "
if (inQuote){ // exiting a quote
// finish off current token
tokenDone = true;
inQuote = false;
//slurp off one additional delimeter if possible
if (pos+1 < len &&
delims.find(in[pos+1]) != std::string::npos) {
pos++;
}
} else { // entering a quote
// finish off current token
tokenDone = true;
inQuote = true;
}
}
break;
default:
if (foundSlash){ // don't care about slashes except for above cases
currentToken << '\\';
foundSlash = false;
}
currentToken << char(currentChar);
break;
}
}
pos++;
currentChar = (pos < len) ? in[pos] : -1;
} // end of getting a Token
if (currentToken.str().size() > 0){ // if the token is something add to list
tokens.push_back(currentToken.str());
currentToken.str("");
numTokens ++;
}
enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));
if ((pos < len) && (pos != std::string::npos)) {
pos = in.find_first_not_of(delims,pos);
}
} // end of getting all tokens -- either EOL or max tokens reached
if (enoughTokens && pos != std::string::npos) {
std::string lastToken = in.substr(pos);
if (lastToken.size() > 0)
tokens.push_back(lastToken);
}
return tokens;
}
bool parseDuration(const char *duration, int &durationInt)
{
#ifndef _TEXT_UTIL_NO_REGEX_
if (strcasecmp(duration,"short") == 0
|| strcasecmp(duration,"default") == 0) {
durationInt = -1;
return true;
}
if (strcasecmp(duration,"forever") == 0
|| strcasecmp(duration,"max") == 0) {
durationInt = 0;
return true;
}
regex_t preg;
int res = regcomp(&preg, "^([[:digit:]]+[hwdm]?)+$",
REG_ICASE | REG_NOSUB | REG_EXTENDED);
res = regexec(&preg, duration, 0, NULL, 0);
regfree(&preg);
if (res == REG_NOMATCH)
return false;
durationInt = 0;
int t = 0;
int len = (int)strlen(duration);
for (int i = 0; i < len; i++) {
if (isdigit(duration[i])) {
t = t * 10 + (duration[i] - '0');
} else if(duration[i] == 'h' || duration[i] == 'H') {
durationInt += (t * 60);
t = 0;
} else if(duration[i] == 'd' || duration[i] == 'D') {
durationInt += (t * 1440);
t = 0;
} else if(duration[i] == 'w' || duration[i] == 'W') {
durationInt += (t * 10080);
t = 0;
} else if(duration[i] == 'm' || duration[i] == 'M') {
durationInt += (t);
t = 0;
}
}
durationInt += t;
return true;
#else
return false;
#endif //_TEXT_UTIL_NO_REGEX_
}
std::string url_encode(const std::string &text)
{
char hex[5];
std::string destination;
for (size_t i=0; i < text.size(); ++i) {
unsigned char c = text[i];
if (isAlphanumeric(c)) {
destination+=c;
} else if (isWhitespace(c)) {
destination+='+';
} else {
destination+='%';
sprintf(hex, "%-2.2X", c);
destination.append(hex);
}
}
return destination;
}
std::string escape(const std::string &text, char escaper)
{
std::string destination;
for (int i = 0; i < (int) text.size(); i++) {
char c = text[i];
if (!isAlphanumeric(c))
destination += escaper;
destination += c;
}
return destination;
}
std::string unescape(const std::string &text, char escaper)
{
const int len = (int) text.size();
std::string destination;
for (int i = 0; i < len; i++) {
char c = text[i];
if (c == escaper) {
if (i < len - 1)
destination += text[++i];
// Otherwise should print an error
} else {
destination += c;
}
}
return destination;
}
int unescape_lookup(const std::string &text, char escaper, char sep)
{
int position = -1;
for (int i = 0; i < (int) text.size(); i++) {
char c = text[i];
if (c == sep) {
position = i;
break;
}
if (c == escaper)
i++;
}
return position;
}
// return a copy of a string, truncated to specified length,
// make last char a '`' if truncation took place
std::string str_trunc_continued (const std::string &text, int len)
{
std::string retstr = std::string (text, 0, len);
if ( retstr.size() == (unsigned int)len )
retstr[len-1] = '~';
return retstr;
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Implement wide-string-ization on nonwindows platforms<commit_after>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// BZFlag common header
#include "common.h"
// interface header
#include "TextUtils.h"
// system headers
#include <string.h>
#include <string>
#include <algorithm>
#include <sstream>
#include <stdarg.h>
#include <vector>
#include <stdio.h>
#include <functional>
#include <locale>
#ifndef _TEXT_UTIL_NO_REGEX_
// common headers
#include "bzregex.h"
#endif //_TEXT_UTIL_NO_REGEX_
namespace TextUtils
{
std::string vformat(const char* fmt, va_list args) {
const int fixedbs = 8192;
char buffer[fixedbs];
const int bs = vsnprintf(buffer, fixedbs, fmt, args) + 1;
if (bs > fixedbs) {
char *bufp = new char[bs];
vsnprintf(bufp, bs, fmt, args);
std::string ret = bufp;
delete[] bufp;
return ret;
}
return buffer;
}
std::string format(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
std::string result = vformat(fmt, args);
va_end(args);
return result;
}
std::wstring convert_to_wide(const std::string& string)
{
#ifdef _WIN32 // Get the required size for the new array and allocate the memory for it
int neededSize = MultiByteToWideChar(CP_ACP, 0, string.c_str(), -1, 0, 0);
wchar_t* wideCharString = new wchar_t[neededSize];
MultiByteToWideChar(CP_ACP, 0, string.c_str(), -1, wideCharString, neededSize);
std::wstring wideString(wideCharString);
delete[] wideCharString;
return wideString;
#else
std::wstring out;
wchar_t* buf = new wchar_t[string.size() + 1];
mbstowcs(buf, string.c_str(), string.size());
buf[string.size()] = 0;
out = buf;
delete[] buf;
return out;
#endif // _WIN32
}
std::string replace_all(const std::string& in, const std::string& replaceMe, const std::string& withMe)
{
std::string result;
std::string::size_type beginPos = 0;
std::string::size_type endPos = 0;
std::ostringstream tempStream;
endPos = in.find(replaceMe);
if (endPos == std::string::npos)
return in; // can't find anything to replace
if (replaceMe.empty()) return in; // can't replace nothing with something -- can do reverse
while (endPos != std::string::npos) {
// push the part up to
tempStream << in.substr(beginPos,endPos-beginPos);
tempStream << withMe;
beginPos = endPos + replaceMe.size();
endPos = in.find(replaceMe,beginPos);
}
tempStream << in.substr(beginPos);
return tempStream.str();
}
std::string no_whitespace(const std::string &s)
{
const int sourcesize = (int)s.size();
int count = 0, i = 0, j = 0;
for (i = 0; i < sourcesize; i++)
if (!isWhitespace(s[i]))
count++;
// create result string of correct size
std::string result(count, ' ');
for (i = 0, j = 0; i < sourcesize; i++)
if (!isWhitespace(s[i]))
result[j++] = s[i];
return result;
}
std::vector<std::string> tokenize(const std::string& in, const std::string &delims, const int maxTokens, const bool useQuotes){
std::vector<std::string> tokens;
int numTokens = 0;
bool inQuote = false;
std::ostringstream currentToken;
const std::string::size_type len = in.size();
std::string::size_type pos = in.find_first_not_of(delims);
int currentChar = (pos == std::string::npos) ? -1 : in[pos];
bool enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));
while (pos < len && pos != std::string::npos && !enoughTokens) {
// get next token
bool tokenDone = false;
bool foundSlash = false;
currentChar = (pos < len) ? in[pos] : -1;
while ((currentChar != -1) && !tokenDone){
tokenDone = false;
if (delims.find(currentChar) != std::string::npos && !inQuote) { // currentChar is a delim
pos ++;
break; // breaks out of inner while loop
}
if (!useQuotes){
currentToken << char(currentChar);
} else {
switch (currentChar){
case '\\' : // found a backslash
if (foundSlash){
currentToken << char(currentChar);
foundSlash = false;
} else {
foundSlash = true;
}
break;
case '\"' : // found a quote
if (foundSlash){ // found \"
currentToken << char(currentChar);
foundSlash = false;
} else { // found unescaped "
if (inQuote){ // exiting a quote
// finish off current token
tokenDone = true;
inQuote = false;
//slurp off one additional delimeter if possible
if (pos+1 < len &&
delims.find(in[pos+1]) != std::string::npos) {
pos++;
}
} else { // entering a quote
// finish off current token
tokenDone = true;
inQuote = true;
}
}
break;
default:
if (foundSlash){ // don't care about slashes except for above cases
currentToken << '\\';
foundSlash = false;
}
currentToken << char(currentChar);
break;
}
}
pos++;
currentChar = (pos < len) ? in[pos] : -1;
} // end of getting a Token
if (currentToken.str().size() > 0){ // if the token is something add to list
tokens.push_back(currentToken.str());
currentToken.str("");
numTokens ++;
}
enoughTokens = (maxTokens && (numTokens >= (maxTokens-1)));
if ((pos < len) && (pos != std::string::npos)) {
pos = in.find_first_not_of(delims,pos);
}
} // end of getting all tokens -- either EOL or max tokens reached
if (enoughTokens && pos != std::string::npos) {
std::string lastToken = in.substr(pos);
if (lastToken.size() > 0)
tokens.push_back(lastToken);
}
return tokens;
}
bool parseDuration(const char *duration, int &durationInt)
{
#ifndef _TEXT_UTIL_NO_REGEX_
if (strcasecmp(duration,"short") == 0
|| strcasecmp(duration,"default") == 0) {
durationInt = -1;
return true;
}
if (strcasecmp(duration,"forever") == 0
|| strcasecmp(duration,"max") == 0) {
durationInt = 0;
return true;
}
regex_t preg;
int res = regcomp(&preg, "^([[:digit:]]+[hwdm]?)+$",
REG_ICASE | REG_NOSUB | REG_EXTENDED);
res = regexec(&preg, duration, 0, NULL, 0);
regfree(&preg);
if (res == REG_NOMATCH)
return false;
durationInt = 0;
int t = 0;
int len = (int)strlen(duration);
for (int i = 0; i < len; i++) {
if (isdigit(duration[i])) {
t = t * 10 + (duration[i] - '0');
} else if(duration[i] == 'h' || duration[i] == 'H') {
durationInt += (t * 60);
t = 0;
} else if(duration[i] == 'd' || duration[i] == 'D') {
durationInt += (t * 1440);
t = 0;
} else if(duration[i] == 'w' || duration[i] == 'W') {
durationInt += (t * 10080);
t = 0;
} else if(duration[i] == 'm' || duration[i] == 'M') {
durationInt += (t);
t = 0;
}
}
durationInt += t;
return true;
#else
return false;
#endif //_TEXT_UTIL_NO_REGEX_
}
std::string url_encode(const std::string &text)
{
char hex[5];
std::string destination;
for (size_t i=0; i < text.size(); ++i) {
unsigned char c = text[i];
if (isAlphanumeric(c)) {
destination+=c;
} else if (isWhitespace(c)) {
destination+='+';
} else {
destination+='%';
sprintf(hex, "%-2.2X", c);
destination.append(hex);
}
}
return destination;
}
std::string escape(const std::string &text, char escaper)
{
std::string destination;
for (int i = 0; i < (int) text.size(); i++) {
char c = text[i];
if (!isAlphanumeric(c))
destination += escaper;
destination += c;
}
return destination;
}
std::string unescape(const std::string &text, char escaper)
{
const int len = (int) text.size();
std::string destination;
for (int i = 0; i < len; i++) {
char c = text[i];
if (c == escaper) {
if (i < len - 1)
destination += text[++i];
// Otherwise should print an error
} else {
destination += c;
}
}
return destination;
}
int unescape_lookup(const std::string &text, char escaper, char sep)
{
int position = -1;
for (int i = 0; i < (int) text.size(); i++) {
char c = text[i];
if (c == sep) {
position = i;
break;
}
if (c == escaper)
i++;
}
return position;
}
// return a copy of a string, truncated to specified length,
// make last char a '`' if truncation took place
std::string str_trunc_continued (const std::string &text, int len)
{
std::string retstr = std::string (text, 0, len);
if ( retstr.size() == (unsigned int)len )
retstr[len-1] = '~';
return retstr;
}
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// This one has to come first (includes the config.h)!
#include "main.hxx"
#include <tuple>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/la/container.hh>
#include <dune/stuff/la/solver.hh>
#include "la_container.hh"
// toggle output
//std::ostream& out = std::cout;
std::ostream& out = DSC_LOG.devnull();
using namespace Dune::Stuff;
using namespace Dune::Stuff::LA;
typedef testing::Types< std::tuple< CommonDenseMatrix< double >, CommonDenseVector< double >, CommonDenseVector< double > >
, std::tuple< CommonDenseMatrix< std::complex<double> >, CommonDenseVector< std::complex<double> >, CommonDenseVector< std::complex<double> > >
#if HAVE_EIGEN
, std::tuple< EigenDenseMatrix< double >, EigenDenseVector< double >, EigenDenseVector< double > >
, std::tuple< EigenDenseMatrix< std::complex<double> >, EigenDenseVector< std::complex<double> >, EigenDenseVector< std::complex<double> > >
, std::tuple< EigenDenseMatrix< double >, EigenDenseVector< double >, EigenMappedDenseVector< double > >
, std::tuple< EigenDenseMatrix< std::complex<double> >, EigenDenseVector< std::complex<double> >, EigenMappedDenseVector< std::complex<double> > >
, std::tuple< EigenDenseMatrix< double >, EigenMappedDenseVector< double >, EigenDenseVector< double > >
, std::tuple< EigenDenseMatrix< std::complex<double> >, EigenMappedDenseVector< std::complex<double> >, EigenDenseVector< std::complex<double> > >
, std::tuple< EigenDenseMatrix< double >, EigenMappedDenseVector< double >, EigenMappedDenseVector< double > >
, std::tuple< EigenDenseMatrix< std::complex<double> >, EigenMappedDenseVector< std::complex<double> >, EigenMappedDenseVector< std::complex<double> > >
, std::tuple< EigenRowMajorSparseMatrix< double >, EigenDenseVector< double >, EigenDenseVector< double > >
, std::tuple< EigenRowMajorSparseMatrix< std::complex<double> >, EigenDenseVector< std::complex<double> >, EigenDenseVector< std::complex<double> > >
#endif // HAVE_EIGEN
#if HAVE_DUNE_ISTL
, std::tuple< IstlRowMajorSparseMatrix< double >, IstlDenseVector< double >, IstlDenseVector< double > >
#endif
> MatrixVectorCombinations;
template< class MatrixVectorCombination >
struct SolverTest
: public ::testing::Test
{
typedef typename std::tuple_element< 0, MatrixVectorCombination >::type MatrixType;
typedef typename std::tuple_element< 1, MatrixVectorCombination >::type RhsType;
typedef typename std::tuple_element< 2, MatrixVectorCombination >::type SolutionType;
typedef Solver< MatrixType > SolverType;
static void produces_correct_results()
{
const size_t dim = 10;
const MatrixType matrix = ContainerFactory< MatrixType >::create(dim);
const RhsType rhs = ContainerFactory< RhsType >::create(dim);
SolutionType solution = ContainerFactory< SolutionType >::create(dim);
solution.scal(0);
// dynamic test
const SolverType solver(matrix);
solver.apply(rhs, solution);
EXPECT_TRUE(solution.almost_equal(rhs));
solution.scal(0);
// static tests
typedef typename SolverType::MatrixType M;
std::vector< std::string > types = SolverType::types();
if (types.size() == 0) DUNE_THROW(Exceptions::results_are_not_as_expected, "Solver has no types!");
for (auto type : types) {
out << "solving with type '" << type << "' and options" << std::endl;
Common::Configuration options = SolverType::options(type);
options.report(out, " ");
// dynamic tests
solver.apply(rhs, solution, type);
EXPECT_TRUE(solution.almost_equal(rhs));
solution.scal(0);
solver.apply(rhs, solution, options);
EXPECT_TRUE(solution.almost_equal(rhs));
}
} // ... produces_correct_results(...)
}; // struct SolverTest
TYPED_TEST_CASE(SolverTest, MatrixVectorCombinations);
TYPED_TEST(SolverTest, behaves_correctly) {
this->produces_correct_results();
}
<commit_msg>[solver] remove unsopprted vector imps from testing for std::complex compat<commit_after>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// This one has to come first (includes the config.h)!
#include "main.hxx"
#include <tuple>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/la/container.hh>
#include <dune/stuff/la/solver.hh>
#include "la_container.hh"
// toggle output
//std::ostream& out = std::cout;
std::ostream& out = DSC_LOG.devnull();
using namespace Dune::Stuff;
using namespace Dune::Stuff::LA;
typedef testing::Types< std::tuple< CommonDenseMatrix< double >, CommonDenseVector< double >, CommonDenseVector< double > >
, std::tuple< CommonDenseMatrix< std::complex<double> >, CommonDenseVector< std::complex<double> >, CommonDenseVector< std::complex<double> > >
#if HAVE_EIGEN
, std::tuple< EigenDenseMatrix< double >, EigenDenseVector< double >, EigenDenseVector< double > >
, std::tuple< EigenDenseMatrix< std::complex<double> >, EigenDenseVector< std::complex<double> >, EigenDenseVector< std::complex<double> > >
, std::tuple< EigenDenseMatrix< double >, EigenDenseVector< double >, EigenMappedDenseVector< double > >
, std::tuple< EigenDenseMatrix< double >, EigenMappedDenseVector< double >, EigenDenseVector< double > >
, std::tuple< EigenDenseMatrix< double >, EigenMappedDenseVector< double >, EigenMappedDenseVector< double > >
, std::tuple< EigenRowMajorSparseMatrix< double >, EigenDenseVector< double >, EigenDenseVector< double > >
, std::tuple< EigenRowMajorSparseMatrix< std::complex<double> >, EigenDenseVector< std::complex<double> >, EigenDenseVector< std::complex<double> > >
#endif // HAVE_EIGEN
#if HAVE_DUNE_ISTL
, std::tuple< IstlRowMajorSparseMatrix< double >, IstlDenseVector< double >, IstlDenseVector< double > >
#endif
> MatrixVectorCombinations;
template< class MatrixVectorCombination >
struct SolverTest
: public ::testing::Test
{
typedef typename std::tuple_element< 0, MatrixVectorCombination >::type MatrixType;
typedef typename std::tuple_element< 1, MatrixVectorCombination >::type RhsType;
typedef typename std::tuple_element< 2, MatrixVectorCombination >::type SolutionType;
typedef Solver< MatrixType > SolverType;
static void produces_correct_results()
{
const size_t dim = 10;
const MatrixType matrix = ContainerFactory< MatrixType >::create(dim);
const RhsType rhs = ContainerFactory< RhsType >::create(dim);
SolutionType solution = ContainerFactory< SolutionType >::create(dim);
solution.scal(0);
// dynamic test
const SolverType solver(matrix);
solver.apply(rhs, solution);
EXPECT_TRUE(solution.almost_equal(rhs));
solution.scal(0);
// static tests
typedef typename SolverType::MatrixType M;
std::vector< std::string > types = SolverType::types();
if (types.size() == 0) DUNE_THROW(Exceptions::results_are_not_as_expected, "Solver has no types!");
for (auto type : types) {
out << "solving with type '" << type << "' and options" << std::endl;
Common::Configuration options = SolverType::options(type);
options.report(out, " ");
// dynamic tests
solver.apply(rhs, solution, type);
EXPECT_TRUE(solution.almost_equal(rhs));
solution.scal(0);
solver.apply(rhs, solution, options);
EXPECT_TRUE(solution.almost_equal(rhs));
}
} // ... produces_correct_results(...)
}; // struct SolverTest
TYPED_TEST_CASE(SolverTest, MatrixVectorCombinations);
TYPED_TEST(SolverTest, behaves_correctly) {
this->produces_correct_results();
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
// LLVM 'GCCAS' UTILITY
//
// This utility is designed to be used by the GCC frontend for creating
// bytecode files from it's intermediate llvm assembly. The requirements for
// this utility are thus slightly different than that of the standard as util.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Transforms/CleanupGCCOutput.h"
#include "llvm/Transforms/LevelChange.h"
#include "llvm/Transforms/ConstantMerge.h"
#include "llvm/Transforms/ChangeAllocations.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "Support/CommandLine.h"
#include "Support/Signals.h"
#include <memory>
#include <fstream>
using std::cerr;
static cl::String InputFilename ("", "Parse <arg> file, compile to bytecode",
cl::Required, "");
static cl::String OutputFilename ("o", "Override output filename");
static cl::Int RunNPasses ("stopAfterNPasses", "Only run the first N "
"passes of gccas", cl::Hidden);
static cl::Flag StopAtLevelRaise("stopraise", "Stop optimization before "
"level raise", cl::Hidden);
static cl::Flag Verify ("verify", "Verify each pass result");
static inline void addPass(PassManager &PM, Pass *P) {
static int NumPassesCreated = 0;
// If we haven't already created the number of passes that was requested...
if (RunNPasses == 0 || RunNPasses > NumPassesCreated) {
// Add the pass to the pass manager...
PM.add(P);
// If we are verifying all of the intermediate steps, add the verifier...
if (Verify) PM.add(createVerifierPass());
// Keep track of how many passes we made for -stopAfterNPasses
++NumPassesCreated;
}
}
void AddConfiguredTransformationPasses(PassManager &PM) {
if (Verify) PM.add(createVerifierPass());
addPass(PM, createFunctionResolvingPass()); // Resolve (...) functions
addPass(PM, createConstantMergePass()); // Merge dup global constants
addPass(PM, createDeadInstEliminationPass()); // Remove Dead code/vars
addPass(PM, createRaiseAllocationsPass()); // call %malloc -> malloc inst
addPass(PM, createCleanupGCCOutputPass()); // Fix gccisms
addPass(PM, createIndVarSimplifyPass()); // Simplify indvars
// Level raise is eternally buggy/in need of enhancements. Allow
// transformation to stop right before it runs.
if (StopAtLevelRaise) return;
addPass(PM, createRaisePointerReferencesPass());// Eliminate casts
addPass(PM, createPromoteMemoryToRegister()); // Promote alloca's to regs
/* addPass(PM, createReassociatePass());*/ // Reassociate expressions
addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
addPass(PM, createDeadInstEliminationPass()); // Kill InstCombine remnants
addPass(PM, createLICMPass()); // Hoist loop invariants
addPass(PM, createGCSEPass()); // Remove common subexprs
addPass(PM, createSCCPPass()); // Constant prop with SCCP
// Run instcombine after redundancy elimination to exploit opportunities
// opened up by them.
addPass(PM, createInstructionCombiningPass());
addPass(PM, createAggressiveDCEPass()); // SSA based 'Agressive DCE'
addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
}
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n");
std::auto_ptr<Module> M;
try {
// Parse the file now...
M.reset(ParseAssemblyFile(InputFilename));
} catch (const ParseException &E) {
cerr << E.getMessage() << std::endl;
return 1;
}
if (M.get() == 0) {
cerr << "assembly didn't read correctly.\n";
return 1;
}
if (OutputFilename == "") { // Didn't specify an output filename?
std::string IFN = InputFilename;
int Len = IFN.length();
if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s?
OutputFilename = std::string(IFN.begin(), IFN.end()-2);
} else {
OutputFilename = IFN; // Append a .o to it
}
OutputFilename += ".o";
}
std::ofstream Out(OutputFilename.c_str(), std::ios::out);
if (!Out.good()) {
cerr << "Error opening " << OutputFilename << "!\n";
return 1;
}
// Make sure that the Out file gets unlink'd from the disk if we get a SIGINT
RemoveFileOnSignal(OutputFilename);
// In addition to just parsing the input from GCC, we also want to spiff it up
// a little bit. Do this now.
//
PassManager Passes;
// Add all of the transformation passes to the pass manager to do the cleanup
// and optimization of the GCC output.
//
AddConfiguredTransformationPasses(Passes);
// Write bytecode to file...
Passes.add(new WriteBytecodePass(&Out));
// Run our queue of passes all at once now, efficiently.
Passes.run(*M.get());
return 0;
}
<commit_msg>Yes, we REALLY DO want to run the reassociate pass.<commit_after>//===----------------------------------------------------------------------===//
// LLVM 'GCCAS' UTILITY
//
// This utility is designed to be used by the GCC frontend for creating
// bytecode files from it's intermediate llvm assembly. The requirements for
// this utility are thus slightly different than that of the standard as util.
//
//===----------------------------------------------------------------------===//
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/Parser.h"
#include "llvm/Transforms/CleanupGCCOutput.h"
#include "llvm/Transforms/LevelChange.h"
#include "llvm/Transforms/ConstantMerge.h"
#include "llvm/Transforms/ChangeAllocations.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "Support/CommandLine.h"
#include "Support/Signals.h"
#include <memory>
#include <fstream>
using std::cerr;
static cl::String InputFilename ("", "Parse <arg> file, compile to bytecode",
cl::Required, "");
static cl::String OutputFilename ("o", "Override output filename");
static cl::Int RunNPasses ("stopAfterNPasses", "Only run the first N "
"passes of gccas", cl::Hidden);
static cl::Flag StopAtLevelRaise("stopraise", "Stop optimization before "
"level raise", cl::Hidden);
static cl::Flag Verify ("verify", "Verify each pass result");
static inline void addPass(PassManager &PM, Pass *P) {
static int NumPassesCreated = 0;
// If we haven't already created the number of passes that was requested...
if (RunNPasses == 0 || RunNPasses > NumPassesCreated) {
// Add the pass to the pass manager...
PM.add(P);
// If we are verifying all of the intermediate steps, add the verifier...
if (Verify) PM.add(createVerifierPass());
// Keep track of how many passes we made for -stopAfterNPasses
++NumPassesCreated;
}
}
void AddConfiguredTransformationPasses(PassManager &PM) {
if (Verify) PM.add(createVerifierPass());
addPass(PM, createFunctionResolvingPass()); // Resolve (...) functions
addPass(PM, createConstantMergePass()); // Merge dup global constants
addPass(PM, createDeadInstEliminationPass()); // Remove Dead code/vars
addPass(PM, createRaiseAllocationsPass()); // call %malloc -> malloc inst
addPass(PM, createCleanupGCCOutputPass()); // Fix gccisms
addPass(PM, createIndVarSimplifyPass()); // Simplify indvars
// Level raise is eternally buggy/in need of enhancements. Allow
// transformation to stop right before it runs.
if (StopAtLevelRaise) return;
addPass(PM, createRaisePointerReferencesPass());// Eliminate casts
addPass(PM, createPromoteMemoryToRegister()); // Promote alloca's to regs
addPass(PM, createReassociatePass()); // Reassociate expressions
addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
addPass(PM, createDeadInstEliminationPass()); // Kill InstCombine remnants
addPass(PM, createLICMPass()); // Hoist loop invariants
addPass(PM, createGCSEPass()); // Remove common subexprs
addPass(PM, createSCCPPass()); // Constant prop with SCCP
// Run instcombine after redundancy elimination to exploit opportunities
// opened up by them.
addPass(PM, createInstructionCombiningPass());
addPass(PM, createAggressiveDCEPass()); // SSA based 'Agressive DCE'
addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
}
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n");
std::auto_ptr<Module> M;
try {
// Parse the file now...
M.reset(ParseAssemblyFile(InputFilename));
} catch (const ParseException &E) {
cerr << E.getMessage() << "\n";
return 1;
}
if (M.get() == 0) {
cerr << "assembly didn't read correctly.\n";
return 1;
}
if (OutputFilename == "") { // Didn't specify an output filename?
std::string IFN = InputFilename;
int Len = IFN.length();
if (IFN[Len-2] == '.' && IFN[Len-1] == 's') { // Source ends in .s?
OutputFilename = std::string(IFN.begin(), IFN.end()-2);
} else {
OutputFilename = IFN; // Append a .o to it
}
OutputFilename += ".o";
}
std::ofstream Out(OutputFilename.c_str(), std::ios::out);
if (!Out.good()) {
cerr << "Error opening " << OutputFilename << "!\n";
return 1;
}
// Make sure that the Out file gets unlink'd from the disk if we get a SIGINT
RemoveFileOnSignal(OutputFilename);
// In addition to just parsing the input from GCC, we also want to spiff it up
// a little bit. Do this now.
//
PassManager Passes;
// Add all of the transformation passes to the pass manager to do the cleanup
// and optimization of the GCC output.
//
AddConfiguredTransformationPasses(Passes);
// Write bytecode to file...
Passes.add(new WriteBytecodePass(&Out));
// Run our queue of passes all at once now, efficiently.
Passes.run(*M.get());
return 0;
}
<|endoftext|> |
<commit_before>/*
* Raging MIDI (https://github.com/waddlesplash/ragingmidi).
*
* Copyright (c) 2012 WaddleSplash & contributors (see AUTHORS.txt).
*
* 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 "TracksEdit.h"
#include "ui_TracksEdit.h"
#include <QColor>
#include <QtMidi.h>
#include "../Selectors/SelectInstrument.h"
TrackItem::TrackItem(QTreeWidget *tree, int track)
: QTreeWidgetItem(tree)
{
this->setText(TrackNumber,QString::number(track));
volSL = new TrackSlider(this->treeWidget());
volSL->setTracking(false);
volSL->setMinimum(0);
volSL->setValue(100);
volSL->setMaximum(100);
this->treeWidget()->setItemWidget(this,Vol,volSL);
balSL = new TrackSlider(this->treeWidget());
balSL->setTracking(false);
balSL->setMinimum(-50);
balSL->setMaximum(50);
this->treeWidget()->setItemWidget(this,Bal,balSL);
}
TracksEdit::TracksEdit(QWidget *parent) :
QTreeWidget(parent),
ui(new Ui::TracksEdit)
{
ui->setupUi(this);
this->hideColumn(TrackItem::TrackNumber);
colorNames = QColor::colorNames();
colorNames.removeOne("black");
colorNames.removeOne("white");
colorNames.removeOne("azure");
colorNames.removeOne("aliceblue");
connect(this,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),
this,SLOT(tracksEdit_itemDoubleClicked(QTreeWidgetItem*,int)));
connect(this,SIGNAL(itemClicked(QTreeWidgetItem*,int)),
this,SLOT(tracksEdit_itemClicked(QTreeWidgetItem*,int)));
resizeColsToContents();
}
TracksEdit::~TracksEdit()
{
delete ui;
}
void TracksEdit::resizeColsToContents()
{
for(int i = 0;i<this->columnCount();i++)
{ this->resizeColumnToContents(i); }
}
TrackItem* TracksEdit::createTrack(int trackNum)
{
TrackItem* ret = new TrackItem(this,trackNum);
ret->setBackgroundColor(TrackItem::Name,QColor(colorNames.at(trackNum)));
myTrackColors.insert(trackNum,QColor(colorNames.at(trackNum)));
ret->setType(tr("Instrument"));
ret->setOn(tr("on"));
ret->setDevice("<automatic>");
ret->volSlider()->setTrack(trackNum);
ret->balSlider()->setTrack(trackNum);
connect(ret->volSlider(),SIGNAL(valueChanged(int)),this,SLOT(trackItem_volChanged(int)));
connect(ret->balSlider(),SIGNAL(valueChanged(int)),this,SLOT(trackItem_balChanged(int)));
return ret;
}
void TracksEdit::trackItem_volChanged(int v)
{
if(ignoreEvents) { return; }
TrackSlider* sl = qobject_cast<TrackSlider*>(sender());
if(!sl) { return; }
qDebug(QString::number(v).toAscii().constData());
int trk = sl->track();
int vel = 127.0*(v/100.0);
/* TODO: warn if track has velocity different in different notes */
foreach(QtMidiEvent* e, midiFile->eventsForTrack(trk))
{
if(e->type() != QtMidiEvent::NoteOn) { continue; }
e->setVelocity(vel);
}
emit somethingChanged();
}
void TracksEdit::trackItem_balChanged(int b)
{
/* TODO: implement balance change.
if(ignoreEvents) { return; }
TrackSlider* sl = qobject_cast<TrackSlider*>(sender());
if(!sl) { return; }
int trk = sl->track(); */
}
QList<TrackItem*> TracksEdit::tracks()
{
QList<TrackItem*> ret;
QTreeWidgetItem *c;
for(int i = 0;i<this->topLevelItemCount();i++) {
c = this->topLevelItem(i);
ret.append(static_cast<TrackItem*>(c));
}
return ret;
}
void TracksEdit::init(VirtualPiano* p)
{
piano = p;
}
void TracksEdit::setupTracks(QtMidiFile *f)
{
ignoreEvents = true;
midiFile = f;
this->clear();
foreach(int curTrack,midiFile->tracks())
{
TrackItem* i = this->createTrack(curTrack);
bool didInstr = false, didVoice = false, didMeta = false, didVol = false;
foreach(QtMidiEvent* e, midiFile->eventsForTrack(curTrack))
{
if(!didVoice && e->type() == QtMidiEvent::NoteOn)
{
i->setVoice(e->voice());
if(e->voice() == 9) { i->setInst(tr("Drums")); didInstr = true; }
didVoice = true;
}
if(!didVol && e->type() == QtMidiEvent::NoteOn)
{
i->setVol((e->velocity()/127.0)*100);
didVol = true;
}
else if(!didInstr && e->type() == QtMidiEvent::ProgramChange)
{
int instr = e->number();
SelectInstrument sel(this);
sel.setInsNum(instr);
i->setInst(sel.insName());
QtMidi::outSetInstr(e->voice(),e->number());
didInstr = true;
}
else if(!didMeta && (e->type() == QtMidiEvent::Meta) &&
(e->number() == 0x03))
{ i->setName(e->data()); didMeta = true; } // Name
if(didInstr && didVoice && didMeta) { break; }
}
if(!didInstr)
{ i->setInst(tr("(no instrument)")); }
}
ignoreEvents = false;
resizeColsToContents();
}
void TracksEdit::deleteCurTrack()
{
TrackItem* i = static_cast<TrackItem*>(this->selectedItems().at(0));
if(!i) { return; }
int trackNum = i->track();
i->~QTreeWidgetItem();
foreach(QtMidiEvent*e,midiFile->eventsForTrack(trackNum))
{
midiFile->removeEvent(e);
delete e;
}
midiFile->removeTrack(trackNum);
}
void TracksEdit::updateTrackOn()
{
bool isOneSolo = false;
int soloTrack = 0;
foreach(TrackItem* itm,tracks()) {
if((itm->on() == tr("solo")) && !isOneSolo) {
isOneSolo = true;
soloTrack = itm->track();
piano->clearTrackColors(itm->track());
}
bool on = (itm->on() == tr("on"));
myTrackStatus.insert(itm->track(),on);
if(!on) { QtMidi::outStopAll(itm->voice()); }
}
if(!isOneSolo) { return; }
foreach(int i,myTrackStatus.keys()) {
if(i == soloTrack) {
myTrackStatus.insert(i,true);
continue;
}
myTrackStatus.insert(i,false);
}
QtMidi::outStopAll();
piano->clearTrackColors();
}
void TracksEdit::tracksEdit_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
TrackItem* itm = static_cast<TrackItem*>(item);
if(column == TrackItem::Name) {
Qt::ItemFlags oldFlags = itm->flags();
itm->setFlags(oldFlags | Qt::ItemIsEditable);
this->editItem(itm,column);
itm->setFlags(oldFlags);
} else if(column == TrackItem::Inst) {
if(itm->voice() == 9) { return; } // drums, don't change
SelectInstrument* ins = new SelectInstrument(this);
ins->setModal(true);
ins->setInsName(itm->inst());
if(ins->exec() == QDialog::Accepted) {
itm->setInst(ins->insName());
foreach(QtMidiEvent*e,midiFile->eventsForTrack(itm->track())) {
if (e->type() == QtMidiEvent::ProgramChange)
{ e->setNumber(ins->insNum()); }
}
QtMidi::outSetInstr(itm->voice(),ins->insNum());
}
}
}
void TracksEdit::tracksEdit_itemClicked(QTreeWidgetItem *item, int column)
{
TrackItem* itm = static_cast<TrackItem*>(item);
if(column == TrackItem::On) {
if(itm->on() == tr("on")) {
itm->setOn(tr("mute"));
itm->setBackgroundColor(TrackItem::On,QColor("#a52a2a"));
itm->setForeground(TrackItem::On,QColor(Qt::white));
updateTrackOn();
} else if(itm->on() == tr("mute")) {
itm->setOn(tr("solo"));
item->setBackgroundColor(TrackItem::On,QColor(Qt::darkBlue));
updateTrackOn();
} else {
itm->setOn(tr("on"));
itm->setBackgroundColor(TrackItem::On,QColor(Qt::white));
itm->setForeground(TrackItem::On,QColor(Qt::black));
updateTrackOn();
}
}
VirtualPiano::voiceToUse = itm->voice();
}
<commit_msg>Auto-resize the "on?" column when changed.<commit_after>/*
* Raging MIDI (https://github.com/waddlesplash/ragingmidi).
*
* Copyright (c) 2012 WaddleSplash & contributors (see AUTHORS.txt).
*
* 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 "TracksEdit.h"
#include "ui_TracksEdit.h"
#include <QColor>
#include <QtMidi.h>
#include "../Selectors/SelectInstrument.h"
TrackItem::TrackItem(QTreeWidget *tree, int track)
: QTreeWidgetItem(tree)
{
this->setText(TrackNumber,QString::number(track));
volSL = new TrackSlider(this->treeWidget());
volSL->setTracking(false);
volSL->setMinimum(0);
volSL->setValue(100);
volSL->setMaximum(100);
this->treeWidget()->setItemWidget(this,Vol,volSL);
balSL = new TrackSlider(this->treeWidget());
balSL->setTracking(false);
balSL->setMinimum(-50);
balSL->setMaximum(50);
this->treeWidget()->setItemWidget(this,Bal,balSL);
}
TracksEdit::TracksEdit(QWidget *parent) :
QTreeWidget(parent),
ui(new Ui::TracksEdit)
{
ui->setupUi(this);
this->hideColumn(TrackItem::TrackNumber);
colorNames = QColor::colorNames();
colorNames.removeOne("black");
colorNames.removeOne("white");
colorNames.removeOne("azure");
colorNames.removeOne("aliceblue");
connect(this,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),
this,SLOT(tracksEdit_itemDoubleClicked(QTreeWidgetItem*,int)));
connect(this,SIGNAL(itemClicked(QTreeWidgetItem*,int)),
this,SLOT(tracksEdit_itemClicked(QTreeWidgetItem*,int)));
resizeColsToContents();
}
TracksEdit::~TracksEdit()
{
delete ui;
}
void TracksEdit::resizeColsToContents()
{
for(int i = 0;i<this->columnCount();i++)
{ this->resizeColumnToContents(i); }
}
TrackItem* TracksEdit::createTrack(int trackNum)
{
TrackItem* ret = new TrackItem(this,trackNum);
ret->setBackgroundColor(TrackItem::Name,QColor(colorNames.at(trackNum)));
myTrackColors.insert(trackNum,QColor(colorNames.at(trackNum)));
ret->setType(tr("Instrument"));
ret->setOn(tr("on"));
ret->setDevice("<automatic>");
ret->volSlider()->setTrack(trackNum);
ret->balSlider()->setTrack(trackNum);
connect(ret->volSlider(),SIGNAL(valueChanged(int)),this,SLOT(trackItem_volChanged(int)));
connect(ret->balSlider(),SIGNAL(valueChanged(int)),this,SLOT(trackItem_balChanged(int)));
return ret;
}
void TracksEdit::trackItem_volChanged(int v)
{
if(ignoreEvents) { return; }
TrackSlider* sl = qobject_cast<TrackSlider*>(sender());
if(!sl) { return; }
qDebug(QString::number(v).toAscii().constData());
int trk = sl->track();
int vel = 127.0*(v/100.0);
/* TODO: warn if track has velocity different in different notes */
foreach(QtMidiEvent* e, midiFile->eventsForTrack(trk))
{
if(e->type() != QtMidiEvent::NoteOn) { continue; }
e->setVelocity(vel);
}
emit somethingChanged();
}
void TracksEdit::trackItem_balChanged(int b)
{
/* TODO: implement balance change.
if(ignoreEvents) { return; }
TrackSlider* sl = qobject_cast<TrackSlider*>(sender());
if(!sl) { return; }
int trk = sl->track(); */
}
QList<TrackItem*> TracksEdit::tracks()
{
QList<TrackItem*> ret;
QTreeWidgetItem *c;
for(int i = 0;i<this->topLevelItemCount();i++) {
c = this->topLevelItem(i);
ret.append(static_cast<TrackItem*>(c));
}
return ret;
}
void TracksEdit::init(VirtualPiano* p)
{
piano = p;
}
void TracksEdit::setupTracks(QtMidiFile *f)
{
ignoreEvents = true;
midiFile = f;
this->clear();
foreach(int curTrack,midiFile->tracks())
{
TrackItem* i = this->createTrack(curTrack);
bool didInstr = false, didVoice = false, didMeta = false, didVol = false;
foreach(QtMidiEvent* e, midiFile->eventsForTrack(curTrack))
{
if(!didVoice && e->type() == QtMidiEvent::NoteOn)
{
i->setVoice(e->voice());
if(e->voice() == 9) { i->setInst(tr("Drums")); didInstr = true; }
didVoice = true;
}
if(!didVol && e->type() == QtMidiEvent::NoteOn)
{
i->setVol((e->velocity()/127.0)*100);
didVol = true;
}
else if(!didInstr && e->type() == QtMidiEvent::ProgramChange)
{
int instr = e->number();
SelectInstrument sel(this);
sel.setInsNum(instr);
i->setInst(sel.insName());
QtMidi::outSetInstr(e->voice(),e->number());
didInstr = true;
}
else if(!didMeta && (e->type() == QtMidiEvent::Meta) &&
(e->number() == 0x03))
{ i->setName(e->data()); didMeta = true; } // Name
if(didInstr && didVoice && didMeta) { break; }
}
if(!didInstr)
{ i->setInst(tr("(no instrument)")); }
}
ignoreEvents = false;
resizeColsToContents();
}
void TracksEdit::deleteCurTrack()
{
TrackItem* i = static_cast<TrackItem*>(this->selectedItems().at(0));
if(!i) { return; }
int trackNum = i->track();
i->~QTreeWidgetItem();
foreach(QtMidiEvent*e,midiFile->eventsForTrack(trackNum))
{
midiFile->removeEvent(e);
delete e;
}
midiFile->removeTrack(trackNum);
}
void TracksEdit::updateTrackOn()
{
bool isOneSolo = false;
int soloTrack = 0;
foreach(TrackItem* itm,tracks()) {
if((itm->on() == tr("solo")) && !isOneSolo) {
isOneSolo = true;
soloTrack = itm->track();
piano->clearTrackColors(itm->track());
}
bool on = (itm->on() == tr("on"));
myTrackStatus.insert(itm->track(),on);
if(!on) { QtMidi::outStopAll(itm->voice()); }
}
if(!isOneSolo) { return; }
foreach(int i,myTrackStatus.keys()) {
if(i == soloTrack) {
myTrackStatus.insert(i,true);
continue;
}
myTrackStatus.insert(i,false);
}
QtMidi::outStopAll();
piano->clearTrackColors();
}
void TracksEdit::tracksEdit_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
TrackItem* itm = static_cast<TrackItem*>(item);
if(column == TrackItem::Name) {
Qt::ItemFlags oldFlags = itm->flags();
itm->setFlags(oldFlags | Qt::ItemIsEditable);
this->editItem(itm,column);
itm->setFlags(oldFlags);
} else if(column == TrackItem::Inst) {
if(itm->voice() == 9) { return; } // drums, don't change
SelectInstrument* ins = new SelectInstrument(this);
ins->setModal(true);
ins->setInsName(itm->inst());
if(ins->exec() == QDialog::Accepted) {
itm->setInst(ins->insName());
foreach(QtMidiEvent*e,midiFile->eventsForTrack(itm->track())) {
if (e->type() == QtMidiEvent::ProgramChange)
{ e->setNumber(ins->insNum()); }
}
QtMidi::outSetInstr(itm->voice(),ins->insNum());
}
}
}
void TracksEdit::tracksEdit_itemClicked(QTreeWidgetItem *item, int column)
{
TrackItem* itm = static_cast<TrackItem*>(item);
if(column == TrackItem::On) {
if(itm->on() == tr("on")) {
itm->setOn(tr("mute"));
itm->setBackgroundColor(TrackItem::On,QColor("#a52a2a"));
itm->setForeground(TrackItem::On,QColor(Qt::white));
updateTrackOn();
} else if(itm->on() == tr("mute")) {
itm->setOn(tr("solo"));
item->setBackgroundColor(TrackItem::On,QColor(Qt::darkBlue));
updateTrackOn();
} else {
itm->setOn(tr("on"));
itm->setBackgroundColor(TrackItem::On,QColor(Qt::white));
itm->setForeground(TrackItem::On,QColor(Qt::black));
updateTrackOn();
}
this->resizeColumnToContents(TrackItem::On);
}
VirtualPiano::voiceToUse = itm->voice();
}
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015 Esteban Tovagliari, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "oslbssrdf.h"
// appleseed.renderer headers.
#include "renderer/kernel/shading/closures.h"
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/modeling/bssrdf/betterdipolebssrdf.h"
#include "renderer/modeling/bssrdf/bssrdf.h"
#include "renderer/modeling/bssrdf/bssrdfsample.h"
#include "renderer/modeling/bssrdf/directionaldipolebssrdf.h"
#ifdef APPLESEED_WITH_NORMALIZED_DIFFUSION_BSSRDF
#include "renderer/modeling/bssrdf/normalizeddiffusionbssrdf.h"
#endif
#include "renderer/modeling/bssrdf/standarddipolebssrdf.h"
#include "renderer/modeling/input/inputevaluator.h"
// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"
// Standard headers.
#include <cassert>
using namespace foundation;
namespace renderer
{
namespace
{
//
// OSL BSSRDF.
//
class OSLBSSRDF
: public BSSRDF
{
public:
OSLBSSRDF(
const char* name,
const ParamArray& params)
: BSSRDF(name, params)
{
memset(m_all_bssrdfs, 0, sizeof(BSSRDF*) * NumClosuresIDs);
m_better_dipole =
create_and_register_bssrdf<BetterDipoleBSSRDFFactory>(
SubsurfaceBetterDipoleID,
"better_dipole");
m_dir_dipole =
create_and_register_bssrdf<DirectionalDipoleBSSRDFFactory>(
SubsurfaceDirectionalDipoleID,
"dir_dipole");
#ifdef APPLESEED_WITH_NORMALIZED_DIFFUSION_BSSRDF
m_normalized =
create_and_register_bssrdf<NormalizedDiffusionBSSRDFFactory>(
SubsurfaceNormalizedDiffusionID,
"normalized");
#endif
m_std_dipole =
create_and_register_bssrdf<StandardDipoleBSSRDFFactory>(
SubsurfaceStandardDipoleID,
"std_dipole");
}
virtual void release() APPLESEED_OVERRIDE
{
delete this;
}
virtual const char* get_model() const APPLESEED_OVERRIDE
{
return "osl_bssrdf";
}
virtual bool on_frame_begin(
const Project& project,
const Assembly& assembly,
IAbortSwitch* abort_switch = 0) APPLESEED_OVERRIDE
{
if (!BSSRDF::on_frame_begin(project, assembly, abort_switch))
return false;
for (int i = 0; i < NumClosuresIDs; ++i)
{
if (BSSRDF* bsrsdf = m_all_bssrdfs[i])
{
if (!bsrsdf->on_frame_begin(project, assembly))
return false;
}
}
return true;
}
virtual void on_frame_end(
const Project& project,
const Assembly& assembly) APPLESEED_OVERRIDE
{
for (int i = 0; i < NumClosuresIDs; ++i)
{
if (BSSRDF* bsrsdf = m_all_bssrdfs[i])
bsrsdf->on_frame_end(project, assembly);
}
BSSRDF::on_frame_end(project, assembly);
}
virtual size_t compute_input_data_size(
const Assembly& assembly) const
{
return sizeof(CompositeSubsurfaceClosure);
}
virtual void evaluate_inputs(
const ShadingContext& shading_context,
InputEvaluator& input_evaluator,
const ShadingPoint& shading_point,
const size_t offset = 0) const APPLESEED_OVERRIDE
{
CompositeSubsurfaceClosure* c = reinterpret_cast<CompositeSubsurfaceClosure*>(input_evaluator.data());
new (c) CompositeSubsurfaceClosure(
shading_point.get_shading_basis(),
shading_point.get_osl_shader_globals().Ci);
prepare_inputs(input_evaluator.data());
}
virtual void prepare_inputs(void* data) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
for (size_t i = 0, e = c->get_num_closures(); i < e; ++i)
{
bssrdf_from_closure_id(c->get_closure_type(i)).prepare_inputs(
c->get_closure_input_values(i));
}
}
virtual bool sample(
SamplingContext& sampling_context,
const void* data,
BSSRDFSample& sample) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
if (c->get_num_closures() > 0)
{
sampling_context.split_in_place(1, 1);
const double s = sampling_context.next_double2();
const size_t closure_index = c->choose_closure(s);
sample.m_shading_basis =
&c->get_closure_shading_basis(closure_index);
return
bssrdf_from_closure_id(c->get_closure_type(closure_index)).sample(
sampling_context,
c->get_closure_input_values(closure_index),
sample);
}
return false;
}
virtual void evaluate(
const void* data,
const ShadingPoint& outgoing_point,
const Vector3d& outgoing_dir,
const ShadingPoint& incoming_point,
const Vector3d& incoming_dir,
Spectrum& value) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
value.set(0.0f);
for (size_t i = 0, e = c->get_num_closures(); i < e; ++i)
{
Spectrum s;
bssrdf_from_closure_id(c->get_closure_type(i)).evaluate(
c->get_closure_input_values(i),
outgoing_point,
outgoing_dir,
incoming_point,
incoming_dir,
s);
s *= static_cast<float>(c->get_closure_pdf_weight(i));
value += s;
}
}
virtual double evaluate_pdf(
const void* data,
const size_t channel,
const double dist) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
double pdf = 0.0;
for (size_t i = 0, e = c->get_num_closures(); i < e; ++i)
{
pdf +=
bssrdf_from_closure_id(c->get_closure_type(i)).evaluate_pdf(
c->get_closure_input_values(i),
channel,
dist) * c->get_closure_pdf_weight(i);
}
return pdf;
}
private:
template <typename BSSRDFFactory>
auto_release_ptr<BSSRDF> create_and_register_bssrdf(
const ClosureID cid,
const char* name)
{
auto_release_ptr<BSSRDF> bssrdf = BSSRDFFactory().create(name, ParamArray());
m_all_bssrdfs[cid] = bssrdf.get();
return bssrdf;
}
const BSSRDF& bssrdf_from_closure_id(const ClosureID cid) const
{
const BSSRDF* bssrdf = m_all_bssrdfs[cid];
assert(bssrdf);
return *bssrdf;
}
BSSRDF& bssrdf_from_closure_id(const ClosureID cid)
{
BSSRDF* bssrdf = m_all_bssrdfs[cid];
assert(bssrdf);
return *bssrdf;
}
auto_release_ptr<BSSRDF> m_better_dipole;
auto_release_ptr<BSSRDF> m_dir_dipole;
auto_release_ptr<BSSRDF> m_gaussian;
#ifdef APPLESEED_WITH_NORMALIZED_DIFFUSION_BSSRDF
auto_release_ptr<BSSRDF> m_normalized;
#endif
auto_release_ptr<BSSRDF> m_std_dipole;
BSSRDF* m_all_bssrdfs[NumClosuresIDs];
};
}
//
// OSLBSSRDFFactory class implementation.
//
auto_release_ptr<BSSRDF> OSLBSSRDFFactory::create() const
{
return auto_release_ptr<BSSRDF>(new OSLBSSRDF("osl_bssrdf", ParamArray()));
}
} // namespace renderer
<commit_msg>Fixed wrong OSL subsurface closures weights.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015 Esteban Tovagliari, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "oslbssrdf.h"
// appleseed.renderer headers.
#include "renderer/kernel/shading/closures.h"
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/modeling/bssrdf/betterdipolebssrdf.h"
#include "renderer/modeling/bssrdf/bssrdf.h"
#include "renderer/modeling/bssrdf/bssrdfsample.h"
#include "renderer/modeling/bssrdf/directionaldipolebssrdf.h"
#ifdef APPLESEED_WITH_NORMALIZED_DIFFUSION_BSSRDF
#include "renderer/modeling/bssrdf/normalizeddiffusionbssrdf.h"
#endif
#include "renderer/modeling/bssrdf/standarddipolebssrdf.h"
#include "renderer/modeling/input/inputevaluator.h"
// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"
// Standard headers.
#include <cassert>
using namespace foundation;
namespace renderer
{
namespace
{
//
// OSL BSSRDF.
//
class OSLBSSRDF
: public BSSRDF
{
public:
OSLBSSRDF(
const char* name,
const ParamArray& params)
: BSSRDF(name, params)
{
memset(m_all_bssrdfs, 0, sizeof(BSSRDF*) * NumClosuresIDs);
m_better_dipole =
create_and_register_bssrdf<BetterDipoleBSSRDFFactory>(
SubsurfaceBetterDipoleID,
"better_dipole");
m_dir_dipole =
create_and_register_bssrdf<DirectionalDipoleBSSRDFFactory>(
SubsurfaceDirectionalDipoleID,
"dir_dipole");
#ifdef APPLESEED_WITH_NORMALIZED_DIFFUSION_BSSRDF
m_normalized =
create_and_register_bssrdf<NormalizedDiffusionBSSRDFFactory>(
SubsurfaceNormalizedDiffusionID,
"normalized");
#endif
m_std_dipole =
create_and_register_bssrdf<StandardDipoleBSSRDFFactory>(
SubsurfaceStandardDipoleID,
"std_dipole");
}
virtual void release() APPLESEED_OVERRIDE
{
delete this;
}
virtual const char* get_model() const APPLESEED_OVERRIDE
{
return "osl_bssrdf";
}
virtual bool on_frame_begin(
const Project& project,
const Assembly& assembly,
IAbortSwitch* abort_switch = 0) APPLESEED_OVERRIDE
{
if (!BSSRDF::on_frame_begin(project, assembly, abort_switch))
return false;
for (int i = 0; i < NumClosuresIDs; ++i)
{
if (BSSRDF* bsrsdf = m_all_bssrdfs[i])
{
if (!bsrsdf->on_frame_begin(project, assembly))
return false;
}
}
return true;
}
virtual void on_frame_end(
const Project& project,
const Assembly& assembly) APPLESEED_OVERRIDE
{
for (int i = 0; i < NumClosuresIDs; ++i)
{
if (BSSRDF* bsrsdf = m_all_bssrdfs[i])
bsrsdf->on_frame_end(project, assembly);
}
BSSRDF::on_frame_end(project, assembly);
}
virtual size_t compute_input_data_size(
const Assembly& assembly) const
{
return sizeof(CompositeSubsurfaceClosure);
}
virtual void evaluate_inputs(
const ShadingContext& shading_context,
InputEvaluator& input_evaluator,
const ShadingPoint& shading_point,
const size_t offset = 0) const APPLESEED_OVERRIDE
{
CompositeSubsurfaceClosure* c = reinterpret_cast<CompositeSubsurfaceClosure*>(input_evaluator.data());
new (c) CompositeSubsurfaceClosure(
shading_point.get_shading_basis(),
shading_point.get_osl_shader_globals().Ci);
prepare_inputs(input_evaluator.data());
}
virtual void prepare_inputs(void* data) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
for (size_t i = 0, e = c->get_num_closures(); i < e; ++i)
{
bssrdf_from_closure_id(c->get_closure_type(i)).prepare_inputs(
c->get_closure_input_values(i));
}
}
virtual bool sample(
SamplingContext& sampling_context,
const void* data,
BSSRDFSample& sample) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
if (c->get_num_closures() > 0)
{
sampling_context.split_in_place(1, 1);
const double s = sampling_context.next_double2();
const size_t closure_index = c->choose_closure(s);
sample.m_shading_basis =
&c->get_closure_shading_basis(closure_index);
return
bssrdf_from_closure_id(c->get_closure_type(closure_index)).sample(
sampling_context,
c->get_closure_input_values(closure_index),
sample);
}
return false;
}
virtual void evaluate(
const void* data,
const ShadingPoint& outgoing_point,
const Vector3d& outgoing_dir,
const ShadingPoint& incoming_point,
const Vector3d& incoming_dir,
Spectrum& value) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
value.set(0.0f);
for (size_t i = 0, e = c->get_num_closures(); i < e; ++i)
{
Spectrum s;
bssrdf_from_closure_id(c->get_closure_type(i)).evaluate(
c->get_closure_input_values(i),
outgoing_point,
outgoing_dir,
incoming_point,
incoming_dir,
s);
s *= c->get_closure_weight(i);
value += s;
}
}
virtual double evaluate_pdf(
const void* data,
const size_t channel,
const double dist) const APPLESEED_OVERRIDE
{
const CompositeSubsurfaceClosure* c =
reinterpret_cast<const CompositeSubsurfaceClosure*>(data);
double pdf = 0.0;
for (size_t i = 0, e = c->get_num_closures(); i < e; ++i)
{
pdf +=
bssrdf_from_closure_id(c->get_closure_type(i)).evaluate_pdf(
c->get_closure_input_values(i),
channel,
dist) * c->get_closure_pdf_weight(i);
}
return pdf;
}
private:
template <typename BSSRDFFactory>
auto_release_ptr<BSSRDF> create_and_register_bssrdf(
const ClosureID cid,
const char* name)
{
auto_release_ptr<BSSRDF> bssrdf = BSSRDFFactory().create(name, ParamArray());
m_all_bssrdfs[cid] = bssrdf.get();
return bssrdf;
}
const BSSRDF& bssrdf_from_closure_id(const ClosureID cid) const
{
const BSSRDF* bssrdf = m_all_bssrdfs[cid];
assert(bssrdf);
return *bssrdf;
}
BSSRDF& bssrdf_from_closure_id(const ClosureID cid)
{
BSSRDF* bssrdf = m_all_bssrdfs[cid];
assert(bssrdf);
return *bssrdf;
}
auto_release_ptr<BSSRDF> m_better_dipole;
auto_release_ptr<BSSRDF> m_dir_dipole;
auto_release_ptr<BSSRDF> m_gaussian;
#ifdef APPLESEED_WITH_NORMALIZED_DIFFUSION_BSSRDF
auto_release_ptr<BSSRDF> m_normalized;
#endif
auto_release_ptr<BSSRDF> m_std_dipole;
BSSRDF* m_all_bssrdfs[NumClosuresIDs];
};
}
//
// OSLBSSRDFFactory class implementation.
//
auto_release_ptr<BSSRDF> OSLBSSRDFFactory::create() const
{
return auto_release_ptr<BSSRDF>(new OSLBSSRDF("osl_bssrdf", ParamArray()));
}
} // namespace renderer
<|endoftext|> |
<commit_before>/*
* #%L
* %%
* Copyright (C) 2018 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <memory>
#include <string>
#include "tests/utils/Gtest.h"
#include "tests/utils/Gmock.h"
#include "joynr/Logger.h"
#include "joynr/exceptions/SubscriptionException.h"
#include "joynr/Future.h"
#include "joynr/SingleThreadedIOService.h"
#include "joynr/UnicastSubscriptionCallback.h"
#include "joynr/MulticastSubscriptionCallback.h"
#include "joynr/SubscriptionPublication.h"
#include "joynr/SubscriptionReply.h"
#include "tests/JoynrTest.h"
#include "tests/mock/MockSubscriptionManager.h"
#include "tests/mock/MockSubscriptionListener.h"
#include "tests/mock/MockMessageRouter.h"
using namespace joynr;
using namespace testing;
template <typename SubscriptionCallbackType>
class SubscriptionCallbackTest : public testing::Test
{
public:
SubscriptionCallbackTest()
: subscriptionId("testSubscriptionId"),
singleThreadIOService(),
mockMessageRouter(
std::make_shared<MockMessageRouter>(singleThreadIOService.getIOService())),
mockSubscriptionManager(std::make_shared<MockSubscriptionManager>(
singleThreadIOService.getIOService(),
mockMessageRouter)),
subscriptionIdFuture(std::make_shared<Future<std::string>>()),
mockSubscriptionListener(
std::make_shared<MockSubscriptionListenerOneType<std::string>>()),
subscriptionCallback(subscriptionId,
subscriptionIdFuture,
mockSubscriptionManager,
nullptr)
{
ON_CALL(*mockSubscriptionManager, getSubscriptionListener(subscriptionId))
.WillByDefault(Return(mockSubscriptionListener));
ON_CALL(*mockSubscriptionManager, getMulticastSubscriptionListeners(subscriptionId))
.WillByDefault(
Return(std::forward_list<std::shared_ptr<joynr::ISubscriptionListenerBase>>{
mockSubscriptionListener}));
}
protected:
const std::string subscriptionId;
SingleThreadedIOService singleThreadIOService;
std::shared_ptr<MockMessageRouter> mockMessageRouter;
std::shared_ptr<MockSubscriptionManager> mockSubscriptionManager;
std::shared_ptr<Future<std::string>> subscriptionIdFuture;
std::shared_ptr<MockSubscriptionListenerOneType<std::string>> mockSubscriptionListener;
SubscriptionCallbackType subscriptionCallback;
};
typedef ::testing::Types<MulticastSubscriptionCallback<std::string>,
UnicastSubscriptionCallback<std::string>> SubscriptionCallbackTypes;
TYPED_TEST_SUITE(SubscriptionCallbackTest, SubscriptionCallbackTypes,);
TYPED_TEST(SubscriptionCallbackTest, forwardSubscriptionReplyToFutureAndListener)
{
SubscriptionReply reply;
reply.setSubscriptionId(this->subscriptionId);
EXPECT_CALL(*(this->mockSubscriptionListener), onSubscribed(this->subscriptionId));
this->subscriptionCallback.execute(reply);
std::string subscriptionIdFromFuture;
this->subscriptionIdFuture->get(100, subscriptionIdFromFuture);
EXPECT_EQ(subscriptionIdFromFuture, this->subscriptionId);
}
TYPED_TEST(SubscriptionCallbackTest, forwardSubscriptionExceptionToFutureAndListener)
{
SubscriptionReply reply;
reply.setSubscriptionId(this->subscriptionId);
auto expectedException =
std::make_shared<exceptions::SubscriptionException>(this->subscriptionId);
reply.setError(expectedException);
EXPECT_CALL(*(this->mockSubscriptionManager), unregisterSubscription(this->subscriptionId));
EXPECT_CALL(*(this->mockSubscriptionListener), onError(*expectedException)).Times(1);
EXPECT_CALL(*(this->mockSubscriptionListener), onReceive(_)).Times(0);
this->subscriptionCallback.execute(reply);
try {
std::string subscriptionIdFromFuture;
this->subscriptionIdFuture->get(100, subscriptionIdFromFuture);
ADD_FAILURE() << "expected SubscriptionException";
} catch (const exceptions::SubscriptionException& error) {
EXPECT_EQ(error, *expectedException);
}
}
TYPED_TEST(SubscriptionCallbackTest, forwardSubscriptionPublicationToListener)
{
const std::string response = "testResponse";
SubscriptionPublication publication;
publication.setSubscriptionId(this->subscriptionId);
publication.setResponse(response);
EXPECT_CALL(*(this->mockSubscriptionListener), onError(_)).Times(0);
EXPECT_CALL(*(this->mockSubscriptionListener), onReceive(response)).Times(1);
this->subscriptionCallback.execute(std::move(publication));
}
TYPED_TEST(SubscriptionCallbackTest, forwardSubscriptionPublicationErrorToListener)
{
auto error = std::make_shared<exceptions::ProviderRuntimeException>("testException");
SubscriptionPublication publication;
publication.setSubscriptionId(this->subscriptionId);
publication.setError(error);
EXPECT_CALL(*(this->mockSubscriptionListener), onError(*error)).Times(1);
EXPECT_CALL(*(this->mockSubscriptionListener), onReceive(_)).Times(0);
this->subscriptionCallback.execute(std::move(publication));
}
<commit_msg>[C++] Fix UBSAN errors<commit_after>/*
* #%L
* %%
* Copyright (C) 2018 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <memory>
#include <string>
#include "tests/utils/Gtest.h"
#include "tests/utils/Gmock.h"
#include "joynr/Future.h"
#include "joynr/Logger.h"
#include "joynr/MulticastPublication.h"
#include "joynr/MulticastSubscriptionCallback.h"
#include "joynr/SingleThreadedIOService.h"
#include "joynr/SubscriptionReply.h"
#include "joynr/UnicastSubscriptionCallback.h"
#include "joynr/exceptions/SubscriptionException.h"
#include "tests/JoynrTest.h"
#include "tests/mock/MockMessageRouter.h"
#include "tests/mock/MockSubscriptionListener.h"
#include "tests/mock/MockSubscriptionManager.h"
using namespace joynr;
using namespace testing;
template <typename SubscriptionCallbackType>
class SubscriptionCallbackTest : public testing::Test
{
public:
SubscriptionCallbackTest()
: subscriptionId("testSubscriptionId"),
singleThreadIOService(),
mockMessageRouter(
std::make_shared<MockMessageRouter>(singleThreadIOService.getIOService())),
mockSubscriptionManager(std::make_shared<MockSubscriptionManager>(
singleThreadIOService.getIOService(),
mockMessageRouter)),
subscriptionIdFuture(std::make_shared<Future<std::string>>()),
mockSubscriptionListener(
std::make_shared<MockSubscriptionListenerOneType<std::string>>()),
subscriptionCallback(subscriptionId,
subscriptionIdFuture,
mockSubscriptionManager,
nullptr)
{
ON_CALL(*mockSubscriptionManager, getSubscriptionListener(subscriptionId))
.WillByDefault(Return(mockSubscriptionListener));
ON_CALL(*mockSubscriptionManager, getMulticastSubscriptionListeners(subscriptionId))
.WillByDefault(
Return(std::forward_list<std::shared_ptr<joynr::ISubscriptionListenerBase>>{
mockSubscriptionListener}));
}
protected:
const std::string subscriptionId;
SingleThreadedIOService singleThreadIOService;
std::shared_ptr<MockMessageRouter> mockMessageRouter;
std::shared_ptr<MockSubscriptionManager> mockSubscriptionManager;
std::shared_ptr<Future<std::string>> subscriptionIdFuture;
std::shared_ptr<MockSubscriptionListenerOneType<std::string>> mockSubscriptionListener;
SubscriptionCallbackType subscriptionCallback;
};
typedef ::testing::Types<MulticastSubscriptionCallback<std::string>,
UnicastSubscriptionCallback<std::string>> SubscriptionCallbackTypes;
TYPED_TEST_SUITE(SubscriptionCallbackTest, SubscriptionCallbackTypes,);
TYPED_TEST(SubscriptionCallbackTest, forwardSubscriptionReplyToFutureAndListener)
{
SubscriptionReply reply;
reply.setSubscriptionId(this->subscriptionId);
EXPECT_CALL(*(this->mockSubscriptionListener), onSubscribed(this->subscriptionId));
this->subscriptionCallback.execute(reply);
std::string subscriptionIdFromFuture;
this->subscriptionIdFuture->get(100, subscriptionIdFromFuture);
EXPECT_EQ(subscriptionIdFromFuture, this->subscriptionId);
}
TYPED_TEST(SubscriptionCallbackTest, forwardSubscriptionExceptionToFutureAndListener)
{
SubscriptionReply reply;
reply.setSubscriptionId(this->subscriptionId);
auto expectedException =
std::make_shared<exceptions::SubscriptionException>(this->subscriptionId);
reply.setError(expectedException);
EXPECT_CALL(*(this->mockSubscriptionManager), unregisterSubscription(this->subscriptionId));
EXPECT_CALL(*(this->mockSubscriptionListener), onError(*expectedException)).Times(1);
EXPECT_CALL(*(this->mockSubscriptionListener), onReceive(_)).Times(0);
this->subscriptionCallback.execute(reply);
try {
std::string subscriptionIdFromFuture;
this->subscriptionIdFuture->get(100, subscriptionIdFromFuture);
ADD_FAILURE() << "expected SubscriptionException";
} catch (const exceptions::SubscriptionException& error) {
EXPECT_EQ(error, *expectedException);
}
}
TYPED_TEST(SubscriptionCallbackTest, forwardPublicationToListener)
{
const std::string response = "testResponse";
EXPECT_CALL(*(this->mockSubscriptionListener), onError(_)).Times(0);
EXPECT_CALL(*(this->mockSubscriptionListener), onReceive(response)).Times(1);
if (typeid(this->subscriptionCallback) == typeid(MulticastSubscriptionCallback<std::string>)) {
MulticastPublication publication;
publication.setMulticastId(this->subscriptionId);
publication.setResponse(response);
this->subscriptionCallback.execute(std::move(publication));
} else if (typeid(this->subscriptionCallback) ==
typeid(UnicastSubscriptionCallback<std::string>)) {
BasePublication publication;
publication.setResponse(response);
this->subscriptionCallback.execute(std::move(publication));
} else {
FAIL() << "Could not evaluate type";
}
}
TYPED_TEST(SubscriptionCallbackTest, forwardPublicationErrorToListener)
{
auto error = std::make_shared<exceptions::ProviderRuntimeException>("testException");
EXPECT_CALL(*(this->mockSubscriptionListener), onError(*error)).Times(1);
EXPECT_CALL(*(this->mockSubscriptionListener), onReceive(_)).Times(0);
if (typeid(this->subscriptionCallback) == typeid(MulticastSubscriptionCallback<std::string>)) {
MulticastPublication publication;
publication.setMulticastId(this->subscriptionId);
publication.setError(error);
this->subscriptionCallback.execute(std::move(publication));
} else if (typeid(this->subscriptionCallback) ==
typeid(UnicastSubscriptionCallback<std::string>)) {
BasePublication publication;
publication.setError(error);
this->subscriptionCallback.execute(std::move(publication));
} else {
FAIL() << "Could not evaluate type";
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** Copyright (C) 2011 - 2013 Research In Motion
**
** Contact: Research In Motion ([email protected])
** Contact: KDAB ([email protected])
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "blackberryconfigurationmanager.h"
#include "blackberrycertificate.h"
#include "blackberryconfiguration.h"
#include "qnxutils.h"
#include <coreplugin/icore.h>
#include <utils/persistentsettings.h>
#include <utils/hostosinfo.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/toolchainmanager.h>
#include <qtsupport/qtversionmanager.h>
#include <qtsupport/qtkitinformation.h>
#include <QMessageBox>
#include <QFileInfo>
using namespace ProjectExplorer;
namespace Qnx {
namespace Internal {
namespace {
const QLatin1String SettingsGroup("BlackBerryConfiguration");
const QLatin1String NDKLocationKey("NDKLocation"); // For 10.1 NDK support (< QTC 3.0)
const QLatin1String NDKEnvFileKey("NDKEnvFile");
const QLatin1String CertificateGroup("Certificates");
const QLatin1String ManualNDKsGroup("ManualNDKs");
}
BlackBerryConfigurationManager::BlackBerryConfigurationManager(QObject *parent)
:QObject(parent)
{
connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveSettings()));
}
void BlackBerryConfigurationManager::loadCertificates()
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(SettingsGroup);
settings->beginGroup(CertificateGroup);
foreach (const QString &certificateId, settings->childGroups()) {
settings->beginGroup(certificateId);
BlackBerryCertificate *cert =
new BlackBerryCertificate(settings->value(QLatin1String(Qnx::Constants::QNX_KEY_PATH)).toString(),
settings->value(QLatin1String(Qnx::Constants::QNX_KEY_AUTHOR)).toString());
cert->setParent(this);
if (settings->value(QLatin1String(Qnx::Constants::QNX_KEY_ACTIVE)).toBool())
m_activeCertificate = cert;
m_certificates << cert;
settings->endGroup();
}
settings->endGroup();
settings->endGroup();
}
void BlackBerryConfigurationManager::loadManualConfigurations()
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(SettingsGroup);
settings->beginGroup(ManualNDKsGroup);
foreach (const QString &manualNdk, settings->childGroups()) {
settings->beginGroup(manualNdk);
QString ndkEnvPath = settings->value(NDKEnvFileKey).toString();
// For 10.1 NDK support (< QTC 3.0):
// Since QTC 3.0 BBConfigurations are based on the bbndk-env file
// to support multiple targets per NDK
if (ndkEnvPath.isEmpty()) {
QString ndkPath = settings->value(NDKLocationKey).toString();
ndkEnvPath = QnxUtils::envFilePath(ndkPath);
}
BlackBerryConfiguration *config = new BlackBerryConfiguration(Utils::FileName::fromString(ndkEnvPath),
false);
if (!addConfiguration(config))
delete config;
settings->endGroup();
}
settings->endGroup();
settings->endGroup();
}
void BlackBerryConfigurationManager::loadAutoDetectedConfigurations()
{
foreach (const NdkInstallInformation &ndkInfo, QnxUtils::installedNdks()) {
QString envFilePath = QnxUtils::envFilePath(ndkInfo.path, ndkInfo.version);
BlackBerryConfiguration *config = new BlackBerryConfiguration(Utils::FileName::fromString(envFilePath),
true, ndkInfo.name);
if (!addConfiguration(config))
delete config;
}
}
void BlackBerryConfigurationManager::saveCertificates()
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(SettingsGroup);
settings->beginGroup(CertificateGroup);
settings->remove(QString());
foreach (const BlackBerryCertificate *cert, m_certificates) {
settings->beginGroup(cert->id());
settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_PATH), cert->fileName());
settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_AUTHOR), cert->author());
if (cert == m_activeCertificate)
settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_ACTIVE), true);
settings->endGroup();
}
settings->endGroup();
settings->endGroup();
}
void BlackBerryConfigurationManager::saveManualConfigurations()
{
if (manualConfigurations().isEmpty())
return;
QSettings *settings = Core::ICore::settings();
settings->beginGroup(SettingsGroup);
settings->beginGroup(ManualNDKsGroup);
foreach (BlackBerryConfiguration *config, manualConfigurations()) {
settings->beginGroup(config->displayName());
settings->setValue(NDKEnvFileKey, config->ndkEnvFile().toString());
settings->endGroup();
}
settings->endGroup();
settings->endGroup();
}
// Remove no longer available 'auo detected' kits
void BlackBerryConfigurationManager::clearInvalidConfigurations()
{
QList<NdkInstallInformation> autoNdks = QnxUtils::installedNdks();
foreach (Kit *kit, KitManager::kits()) {
if (!kit->isAutoDetected())
continue;
if (kit->displayName().contains(QLatin1String("BlackBerry"))) {
// Check if related target is still installed
bool isValid = false;
foreach (const NdkInstallInformation &ndkInfo, autoNdks) {
if (ndkInfo.target == SysRootKitInformation::sysRoot(kit).toString()) {
isValid = true;
break;
}
}
if (!isValid) {
QtSupport::QtVersionManager::removeVersion(QtSupport::QtKitInformation::qtVersion(kit));
ToolChainManager::deregisterToolChain(ToolChainKitInformation::toolChain(kit));
KitManager::deregisterKit(kit);
}
}
}
}
bool BlackBerryConfigurationManager::addConfiguration(BlackBerryConfiguration *config)
{
foreach (BlackBerryConfiguration *c, m_configs) {
if (c->ndkPath() == config->ndkPath()
&& c->targetName() == config->targetName()) {
if (!config->isAutoDetected())
QMessageBox::warning(0, tr("NDK Already known"),
tr("The NDK already has a configuration."), QMessageBox::Ok);
return false;
}
}
if (config->activate()) {
m_configs.append(config);
return true;
}
return false;
}
void BlackBerryConfigurationManager::removeConfiguration(BlackBerryConfiguration *config)
{
if (!config)
return;
if (config->isActive())
config->deactivate();
clearConfigurationSettings(config);
m_configs.removeAt(m_configs.indexOf(config));
delete config;
}
QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::configurations() const
{
return m_configs;
}
QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::manualConfigurations() const
{
QList<BlackBerryConfiguration*> manuals;
foreach (BlackBerryConfiguration *config, m_configs) {
if (!config->isAutoDetected())
manuals << config;
}
return manuals;
}
BlackBerryConfiguration *BlackBerryConfigurationManager::configurationFromEnvFile(const Utils::FileName &envFile) const
{
foreach (BlackBerryConfiguration *config, m_configs) {
if (config->ndkEnvFile() == envFile)
return config;
}
return 0;
}
void BlackBerryConfigurationManager::syncCertificates(QList<BlackBerryCertificate*> certificates,
BlackBerryCertificate *activeCertificate)
{
m_activeCertificate = activeCertificate;
foreach (BlackBerryCertificate *cert, certificates) {
if (!certificates.contains(cert))
removeCertificate(cert);
}
foreach (BlackBerryCertificate *cert, certificates)
addCertificate(cert);
}
void BlackBerryConfigurationManager::addCertificate(BlackBerryCertificate *certificate)
{
if (m_certificates.contains(certificate))
return;
if (m_certificates.isEmpty())
m_activeCertificate = certificate;
certificate->setParent(this);
m_certificates << certificate;
}
void BlackBerryConfigurationManager::removeCertificate(BlackBerryCertificate *certificate)
{
if (m_activeCertificate == certificate)
m_activeCertificate = 0;
m_certificates.removeAll(certificate);
delete certificate;
}
QList<BlackBerryCertificate*> BlackBerryConfigurationManager::certificates() const
{
return m_certificates;
}
BlackBerryCertificate * BlackBerryConfigurationManager::activeCertificate()
{
return m_activeCertificate;
}
// Returns a valid qnxEnv map from a valid configuration;
// Needed by other classes to get blackberry process path (keys registration, debug token...)
QMultiMap<QString, QString> BlackBerryConfigurationManager::defaultQnxEnv()
{
foreach (BlackBerryConfiguration *config, m_configs) {
if (!config->qnxEnv().isEmpty())
return config->qnxEnv();
}
return QMultiMap<QString, QString>();
}
void BlackBerryConfigurationManager::loadSettings()
{
clearInvalidConfigurations();
loadAutoDetectedConfigurations();
loadManualConfigurations();
loadCertificates();
}
void BlackBerryConfigurationManager::clearConfigurationSettings(BlackBerryConfiguration *config)
{
if (!config)
return;
QSettings *settings = Core::ICore::settings();
settings->beginGroup(SettingsGroup);
settings->beginGroup(ManualNDKsGroup);
foreach (const QString &manualNdk, settings->childGroups()) {
if (manualNdk == config->displayName()) {
settings->remove(manualNdk);
break;
}
}
settings->endGroup();
settings->endGroup();
}
void BlackBerryConfigurationManager::saveSettings()
{
saveManualConfigurations();
saveCertificates();
}
BlackBerryConfigurationManager &BlackBerryConfigurationManager::instance()
{
if (m_instance == 0)
m_instance = new BlackBerryConfigurationManager();
return *m_instance;
}
BlackBerryConfigurationManager::~BlackBerryConfigurationManager()
{
qDeleteAll(m_configs);
}
QString BlackBerryConfigurationManager::barsignerCskPath() const
{
return QnxUtils::dataDirPath() + QLatin1String("/barsigner.csk");
}
QString BlackBerryConfigurationManager::barsignerDbPath() const
{
return QnxUtils::dataDirPath() + QLatin1String("/barsigner.db");
}
QString BlackBerryConfigurationManager::defaultKeystorePath() const
{
return QnxUtils::dataDirPath() + QLatin1String("/author.p12");
}
QString BlackBerryConfigurationManager::defaultDebugTokenPath() const
{
return QnxUtils::dataDirPath() + QLatin1String("/debugtoken.bar");
}
BlackBerryConfigurationManager* BlackBerryConfigurationManager::m_instance = 0;
} // namespace Internal
} // namespace Qnx
<commit_msg>Qnx: Remove invalid auto detected kits/qt versions<commit_after>/**************************************************************************
**
** Copyright (C) 2011 - 2013 Research In Motion
**
** Contact: Research In Motion ([email protected])
** Contact: KDAB ([email protected])
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "blackberryconfigurationmanager.h"
#include "blackberrycertificate.h"
#include "blackberryconfiguration.h"
#include "qnxutils.h"
#include <coreplugin/icore.h>
#include <utils/persistentsettings.h>
#include <utils/hostosinfo.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/toolchainmanager.h>
#include <qtsupport/qtversionmanager.h>
#include <qtsupport/qtkitinformation.h>
#include <QMessageBox>
#include <QFileInfo>
using namespace ProjectExplorer;
namespace Qnx {
namespace Internal {
namespace {
const QLatin1String SettingsGroup("BlackBerryConfiguration");
const QLatin1String NDKLocationKey("NDKLocation"); // For 10.1 NDK support (< QTC 3.0)
const QLatin1String NDKEnvFileKey("NDKEnvFile");
const QLatin1String CertificateGroup("Certificates");
const QLatin1String ManualNDKsGroup("ManualNDKs");
}
BlackBerryConfigurationManager::BlackBerryConfigurationManager(QObject *parent)
:QObject(parent)
{
connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveSettings()));
}
void BlackBerryConfigurationManager::loadCertificates()
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(SettingsGroup);
settings->beginGroup(CertificateGroup);
foreach (const QString &certificateId, settings->childGroups()) {
settings->beginGroup(certificateId);
BlackBerryCertificate *cert =
new BlackBerryCertificate(settings->value(QLatin1String(Qnx::Constants::QNX_KEY_PATH)).toString(),
settings->value(QLatin1String(Qnx::Constants::QNX_KEY_AUTHOR)).toString());
cert->setParent(this);
if (settings->value(QLatin1String(Qnx::Constants::QNX_KEY_ACTIVE)).toBool())
m_activeCertificate = cert;
m_certificates << cert;
settings->endGroup();
}
settings->endGroup();
settings->endGroup();
}
void BlackBerryConfigurationManager::loadManualConfigurations()
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(SettingsGroup);
settings->beginGroup(ManualNDKsGroup);
foreach (const QString &manualNdk, settings->childGroups()) {
settings->beginGroup(manualNdk);
QString ndkEnvPath = settings->value(NDKEnvFileKey).toString();
// For 10.1 NDK support (< QTC 3.0):
// Since QTC 3.0 BBConfigurations are based on the bbndk-env file
// to support multiple targets per NDK
if (ndkEnvPath.isEmpty()) {
QString ndkPath = settings->value(NDKLocationKey).toString();
ndkEnvPath = QnxUtils::envFilePath(ndkPath);
}
BlackBerryConfiguration *config = new BlackBerryConfiguration(Utils::FileName::fromString(ndkEnvPath),
false);
if (!addConfiguration(config))
delete config;
settings->endGroup();
}
settings->endGroup();
settings->endGroup();
}
void BlackBerryConfigurationManager::loadAutoDetectedConfigurations()
{
foreach (const NdkInstallInformation &ndkInfo, QnxUtils::installedNdks()) {
QString envFilePath = QnxUtils::envFilePath(ndkInfo.path, ndkInfo.version);
BlackBerryConfiguration *config = new BlackBerryConfiguration(Utils::FileName::fromString(envFilePath),
true, ndkInfo.name);
if (!addConfiguration(config))
delete config;
}
}
void BlackBerryConfigurationManager::saveCertificates()
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(SettingsGroup);
settings->beginGroup(CertificateGroup);
settings->remove(QString());
foreach (const BlackBerryCertificate *cert, m_certificates) {
settings->beginGroup(cert->id());
settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_PATH), cert->fileName());
settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_AUTHOR), cert->author());
if (cert == m_activeCertificate)
settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_ACTIVE), true);
settings->endGroup();
}
settings->endGroup();
settings->endGroup();
}
void BlackBerryConfigurationManager::saveManualConfigurations()
{
if (manualConfigurations().isEmpty())
return;
QSettings *settings = Core::ICore::settings();
settings->beginGroup(SettingsGroup);
settings->beginGroup(ManualNDKsGroup);
foreach (BlackBerryConfiguration *config, manualConfigurations()) {
settings->beginGroup(config->displayName());
settings->setValue(NDKEnvFileKey, config->ndkEnvFile().toString());
settings->endGroup();
}
settings->endGroup();
settings->endGroup();
}
// Remove no longer available/valid 'auto detected' BlackBerry kits and qt versions
void BlackBerryConfigurationManager::clearInvalidConfigurations()
{
// Deregister invalid auto deteted BlackBerry Kits
foreach (ProjectExplorer::Kit *kit, ProjectExplorer::KitManager::instance()->kits()) {
if (!kit->isAutoDetected())
continue;
if (ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(kit) == Constants::QNX_BB_OS_TYPE
&& !kit->isValid())
ProjectExplorer::KitManager::instance()->deregisterKit(kit);
}
// Remove invalid auto detected BlackBerry qtVerions
foreach (QtSupport::BaseQtVersion *qtVersion, QtSupport::QtVersionManager::versions()) {
if (!qtVersion->isAutodetected())
continue;
if (qtVersion->platformName() == QLatin1String(Constants::QNX_BB_PLATFORM_NAME)
&& !qtVersion->isValid())
QtSupport::QtVersionManager::removeVersion(qtVersion);
}
}
bool BlackBerryConfigurationManager::addConfiguration(BlackBerryConfiguration *config)
{
foreach (BlackBerryConfiguration *c, m_configs) {
if (c->ndkPath() == config->ndkPath()
&& c->targetName() == config->targetName()) {
if (!config->isAutoDetected())
QMessageBox::warning(0, tr("NDK Already known"),
tr("The NDK already has a configuration."), QMessageBox::Ok);
return false;
}
}
if (config->activate()) {
m_configs.append(config);
return true;
}
return false;
}
void BlackBerryConfigurationManager::removeConfiguration(BlackBerryConfiguration *config)
{
if (!config)
return;
if (config->isActive())
config->deactivate();
clearConfigurationSettings(config);
m_configs.removeAt(m_configs.indexOf(config));
delete config;
}
QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::configurations() const
{
return m_configs;
}
QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::manualConfigurations() const
{
QList<BlackBerryConfiguration*> manuals;
foreach (BlackBerryConfiguration *config, m_configs) {
if (!config->isAutoDetected())
manuals << config;
}
return manuals;
}
BlackBerryConfiguration *BlackBerryConfigurationManager::configurationFromEnvFile(const Utils::FileName &envFile) const
{
foreach (BlackBerryConfiguration *config, m_configs) {
if (config->ndkEnvFile() == envFile)
return config;
}
return 0;
}
void BlackBerryConfigurationManager::syncCertificates(QList<BlackBerryCertificate*> certificates,
BlackBerryCertificate *activeCertificate)
{
m_activeCertificate = activeCertificate;
foreach (BlackBerryCertificate *cert, certificates) {
if (!certificates.contains(cert))
removeCertificate(cert);
}
foreach (BlackBerryCertificate *cert, certificates)
addCertificate(cert);
}
void BlackBerryConfigurationManager::addCertificate(BlackBerryCertificate *certificate)
{
if (m_certificates.contains(certificate))
return;
if (m_certificates.isEmpty())
m_activeCertificate = certificate;
certificate->setParent(this);
m_certificates << certificate;
}
void BlackBerryConfigurationManager::removeCertificate(BlackBerryCertificate *certificate)
{
if (m_activeCertificate == certificate)
m_activeCertificate = 0;
m_certificates.removeAll(certificate);
delete certificate;
}
QList<BlackBerryCertificate*> BlackBerryConfigurationManager::certificates() const
{
return m_certificates;
}
BlackBerryCertificate * BlackBerryConfigurationManager::activeCertificate()
{
return m_activeCertificate;
}
// Returns a valid qnxEnv map from a valid configuration;
// Needed by other classes to get blackberry process path (keys registration, debug token...)
QMultiMap<QString, QString> BlackBerryConfigurationManager::defaultQnxEnv()
{
foreach (BlackBerryConfiguration *config, m_configs) {
if (!config->qnxEnv().isEmpty())
return config->qnxEnv();
}
return QMultiMap<QString, QString>();
}
void BlackBerryConfigurationManager::loadSettings()
{
clearInvalidConfigurations();
loadAutoDetectedConfigurations();
loadManualConfigurations();
loadCertificates();
}
void BlackBerryConfigurationManager::clearConfigurationSettings(BlackBerryConfiguration *config)
{
if (!config)
return;
QSettings *settings = Core::ICore::settings();
settings->beginGroup(SettingsGroup);
settings->beginGroup(ManualNDKsGroup);
foreach (const QString &manualNdk, settings->childGroups()) {
if (manualNdk == config->displayName()) {
settings->remove(manualNdk);
break;
}
}
settings->endGroup();
settings->endGroup();
}
void BlackBerryConfigurationManager::saveSettings()
{
saveManualConfigurations();
saveCertificates();
}
BlackBerryConfigurationManager &BlackBerryConfigurationManager::instance()
{
if (m_instance == 0)
m_instance = new BlackBerryConfigurationManager();
return *m_instance;
}
BlackBerryConfigurationManager::~BlackBerryConfigurationManager()
{
qDeleteAll(m_configs);
}
QString BlackBerryConfigurationManager::barsignerCskPath() const
{
return QnxUtils::dataDirPath() + QLatin1String("/barsigner.csk");
}
QString BlackBerryConfigurationManager::barsignerDbPath() const
{
return QnxUtils::dataDirPath() + QLatin1String("/barsigner.db");
}
QString BlackBerryConfigurationManager::defaultKeystorePath() const
{
return QnxUtils::dataDirPath() + QLatin1String("/author.p12");
}
QString BlackBerryConfigurationManager::defaultDebugTokenPath() const
{
return QnxUtils::dataDirPath() + QLatin1String("/debugtoken.bar");
}
BlackBerryConfigurationManager* BlackBerryConfigurationManager::m_instance = 0;
} // namespace Internal
} // namespace Qnx
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
// LLVM 'GCCLD' UTILITY
//
// This utility is intended to be compatible with GCC, and follows standard
// system ld conventions. As such, the default output file is ./a.out.
// Additionally, this program outputs a shell script that is used to invoke LLI
// to execute the program. In this manner, the generated executable (a.out for
// example), is directly executable, whereas the bytecode file actually lives in
// the a.out.bc file generated by this program. Also, Force is on by default.
//
// Note that if someone (or a script) deletes the executable program generated,
// the .bc file will be left around. Considering that this is a temporary hack,
// I'm not to worried about this.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Linker.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Transforms/SymbolStripping.h"
#include "llvm/Transforms/CleanupGCCOutput.h"
#include "llvm/Transforms/ConstantMerge.h"
#include "llvm/Transforms/IPO/GlobalDCE.h"
#include "Support/CommandLine.h"
#include <fstream>
#include <memory>
#include <algorithm>
#include <sys/types.h> // For FileExists
#include <sys/stat.h>
cl::StringList InputFilenames("", "Load <arg> files, linking them together",
cl::OneOrMore);
cl::String OutputFilename("o", "Override output filename", cl::NoFlags,"a.out");
cl::Flag Verbose ("v", "Print information about actions taken");
cl::StringList LibPaths ("L", "Specify a library search path", cl::ZeroOrMore);
cl::StringList Libraries ("l", "Specify libraries to link to", cl::ZeroOrMore);
cl::Flag Strip ("s", "Strip symbol info from executable");
// FileExists - Return true if the specified string is an openable file...
static inline bool FileExists(const std::string &FN) {
struct stat StatBuf;
return stat(FN.c_str(), &StatBuf) != -1;
}
// LoadFile - Read the specified bytecode file in and return it. This routine
// searches the link path for the specified file to try to find it...
//
static inline std::auto_ptr<Module> LoadFile(const std::string &FN) {
std::string Filename = FN;
std::string ErrorMessage;
unsigned NextLibPathIdx = 0;
bool FoundAFile = false;
while (1) {
if (Verbose) cerr << "Loading '" << Filename << "'\n";
if (FileExists(Filename)) FoundAFile = true;
Module *Result = ParseBytecodeFile(Filename, &ErrorMessage);
if (Result) return std::auto_ptr<Module>(Result); // Load successful!
if (Verbose) {
cerr << "Error opening bytecode file: '" << Filename << "'";
if (ErrorMessage.size()) cerr << ": " << ErrorMessage;
cerr << endl;
}
if (NextLibPathIdx == LibPaths.size()) break;
Filename = LibPaths[NextLibPathIdx++] + "/" + FN;
}
if (FoundAFile)
cerr << "Bytecode file '" << FN << "' corrupt! "
<< "Use 'gccld -v ...' for more info.\n";
else
cerr << "Could not locate bytecode file: '" << FN << "'\n";
return std::auto_ptr<Module>();
}
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n",
cl::EnableSingleLetterArgValue |
cl::DisableSingleLetterArgGrouping);
assert(InputFilenames.size() > 0 && "OneOrMore is not working");
unsigned BaseArg = 0;
std::string ErrorMessage;
if (!Libraries.empty()) {
// Sort libraries list...
sort(Libraries.begin(), Libraries.end());
// Remove duplicate libraries entries...
Libraries.erase(unique(Libraries.begin(), Libraries.end()),
Libraries.end());
// Add all of the libraries to the end of the link line...
for (unsigned i = 0; i < Libraries.size(); ++i)
InputFilenames.push_back("lib" + Libraries[i] + ".bc");
}
std::auto_ptr<Module> Composite(LoadFile(InputFilenames[BaseArg]));
if (Composite.get() == 0) return 1;
for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
std::auto_ptr<Module> M(LoadFile(InputFilenames[i]));
if (M.get() == 0) return 1;
if (Verbose) cerr << "Linking in '" << InputFilenames[i] << "'\n";
if (LinkModules(Composite.get(), M.get(), &ErrorMessage)) {
cerr << "Error linking in '" << InputFilenames[i] << "': "
<< ErrorMessage << endl;
return 1;
}
}
// In addition to just parsing the input from GCC, we also want to spiff it up
// a little bit. Do this now.
//
PassManager Passes;
// Linking modules together can lead to duplicated global constants, only keep
// one copy of each constant...
//
Passes.add(createConstantMergePass());
// Often if the programmer does not specify proper prototypes for the
// functions they are calling, they end up calling a vararg version of the
// function that does not get a body filled in (the real function has typed
// arguments). This pass merges the two functions, among other things.
//
Passes.add(createCleanupGCCOutputPass());
// If the -s command line option was specified, strip the symbols out of the
// resulting program to make it smaller. -s is a GCC option that we are
// supporting.
//
if (Strip)
Passes.add(createSymbolStrippingPass());
// Now that composite has been compiled, scan through the module, looking for
// a main function. If main is defined, mark all other functions internal.
//
// TODO:
// Now that we have optimized the program, discard unreachable functions...
//
Passes.add(createGlobalDCEPass());
// Add the pass that writes bytecode to the output file...
std::ofstream Out((OutputFilename+".bc").c_str());
if (!Out.good()) {
cerr << "Error opening '" << OutputFilename << ".bc' for writing!\n";
return 1;
}
Passes.add(new WriteBytecodePass(&Out)); // Write bytecode to file...
// Run our queue of passes all at once now, efficiently.
Passes.run(Composite.get());
Out.close();
// Output the script to start the program...
std::ofstream Out2(OutputFilename.c_str());
if (!Out2.good()) {
cerr << "Error opening '" << OutputFilename << "' for writing!\n";
return 1;
}
Out2 << "#!/bin/sh\nlli -q $0.bc $*\n";
Out2.close();
// Make the script executable...
chmod(OutputFilename.c_str(), 0755);
return 0;
}
<commit_msg>* The cleangcc pass is broken into two parts, we only want to FunctionResolvingPass one. * We run it *after* the symbol stripping pass so that -strip can be pipelined with the constant merging pass or something else if desired.<commit_after>//===----------------------------------------------------------------------===//
// LLVM 'GCCLD' UTILITY
//
// This utility is intended to be compatible with GCC, and follows standard
// system ld conventions. As such, the default output file is ./a.out.
// Additionally, this program outputs a shell script that is used to invoke LLI
// to execute the program. In this manner, the generated executable (a.out for
// example), is directly executable, whereas the bytecode file actually lives in
// the a.out.bc file generated by this program. Also, Force is on by default.
//
// Note that if someone (or a script) deletes the executable program generated,
// the .bc file will be left around. Considering that this is a temporary hack,
// I'm not to worried about this.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Linker.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Bytecode/Reader.h"
#include "llvm/Bytecode/WriteBytecodePass.h"
#include "llvm/Transforms/SymbolStripping.h"
#include "llvm/Transforms/CleanupGCCOutput.h"
#include "llvm/Transforms/ConstantMerge.h"
#include "llvm/Transforms/IPO/GlobalDCE.h"
#include "Support/CommandLine.h"
#include <fstream>
#include <memory>
#include <algorithm>
#include <sys/types.h> // For FileExists
#include <sys/stat.h>
cl::StringList InputFilenames("", "Load <arg> files, linking them together",
cl::OneOrMore);
cl::String OutputFilename("o", "Override output filename", cl::NoFlags,"a.out");
cl::Flag Verbose ("v", "Print information about actions taken");
cl::StringList LibPaths ("L", "Specify a library search path", cl::ZeroOrMore);
cl::StringList Libraries ("l", "Specify libraries to link to", cl::ZeroOrMore);
cl::Flag Strip ("s", "Strip symbol info from executable");
// FileExists - Return true if the specified string is an openable file...
static inline bool FileExists(const std::string &FN) {
struct stat StatBuf;
return stat(FN.c_str(), &StatBuf) != -1;
}
// LoadFile - Read the specified bytecode file in and return it. This routine
// searches the link path for the specified file to try to find it...
//
static inline std::auto_ptr<Module> LoadFile(const std::string &FN) {
std::string Filename = FN;
std::string ErrorMessage;
unsigned NextLibPathIdx = 0;
bool FoundAFile = false;
while (1) {
if (Verbose) cerr << "Loading '" << Filename << "'\n";
if (FileExists(Filename)) FoundAFile = true;
Module *Result = ParseBytecodeFile(Filename, &ErrorMessage);
if (Result) return std::auto_ptr<Module>(Result); // Load successful!
if (Verbose) {
cerr << "Error opening bytecode file: '" << Filename << "'";
if (ErrorMessage.size()) cerr << ": " << ErrorMessage;
cerr << endl;
}
if (NextLibPathIdx == LibPaths.size()) break;
Filename = LibPaths[NextLibPathIdx++] + "/" + FN;
}
if (FoundAFile)
cerr << "Bytecode file '" << FN << "' corrupt! "
<< "Use 'gccld -v ...' for more info.\n";
else
cerr << "Could not locate bytecode file: '" << FN << "'\n";
return std::auto_ptr<Module>();
}
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm linker for GCC\n",
cl::EnableSingleLetterArgValue |
cl::DisableSingleLetterArgGrouping);
assert(InputFilenames.size() > 0 && "OneOrMore is not working");
unsigned BaseArg = 0;
std::string ErrorMessage;
if (!Libraries.empty()) {
// Sort libraries list...
sort(Libraries.begin(), Libraries.end());
// Remove duplicate libraries entries...
Libraries.erase(unique(Libraries.begin(), Libraries.end()),
Libraries.end());
// Add all of the libraries to the end of the link line...
for (unsigned i = 0; i < Libraries.size(); ++i)
InputFilenames.push_back("lib" + Libraries[i] + ".bc");
}
std::auto_ptr<Module> Composite(LoadFile(InputFilenames[BaseArg]));
if (Composite.get() == 0) return 1;
for (unsigned i = BaseArg+1; i < InputFilenames.size(); ++i) {
std::auto_ptr<Module> M(LoadFile(InputFilenames[i]));
if (M.get() == 0) return 1;
if (Verbose) cerr << "Linking in '" << InputFilenames[i] << "'\n";
if (LinkModules(Composite.get(), M.get(), &ErrorMessage)) {
cerr << "Error linking in '" << InputFilenames[i] << "': "
<< ErrorMessage << endl;
return 1;
}
}
// In addition to just linking the input from GCC, we also want to spiff it up
// a little bit. Do this now.
//
PassManager Passes;
// Linking modules together can lead to duplicated global constants, only keep
// one copy of each constant...
//
Passes.add(createConstantMergePass());
// If the -s command line option was specified, strip the symbols out of the
// resulting program to make it smaller. -s is a GCC option that we are
// supporting.
//
if (Strip)
Passes.add(createSymbolStrippingPass());
// Often if the programmer does not specify proper prototypes for the
// functions they are calling, they end up calling a vararg version of the
// function that does not get a body filled in (the real function has typed
// arguments). This pass merges the two functions.
//
Passes.add(createFunctionResolvingPass());
// Now that composite has been compiled, scan through the module, looking for
// a main function. If main is defined, mark all other functions internal.
//
// TODO:
// Now that we have optimized the program, discard unreachable functions...
//
Passes.add(createGlobalDCEPass());
// Add the pass that writes bytecode to the output file...
std::ofstream Out((OutputFilename+".bc").c_str());
if (!Out.good()) {
cerr << "Error opening '" << OutputFilename << ".bc' for writing!\n";
return 1;
}
Passes.add(new WriteBytecodePass(&Out)); // Write bytecode to file...
// Run our queue of passes all at once now, efficiently.
Passes.run(Composite.get());
Out.close();
// Output the script to start the program...
std::ofstream Out2(OutputFilename.c_str());
if (!Out2.good()) {
cerr << "Error opening '" << OutputFilename << "' for writing!\n";
return 1;
}
Out2 << "#!/bin/sh\nlli -q $0.bc $*\n";
Out2.close();
// Make the script executable...
chmod(OutputFilename.c_str(), 0755);
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: popmenu.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:45:00 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_POPMENU_HXX
#define SC_POPMENU_HXX
#ifndef _MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif
class ScPopupMenu : public PopupMenu
{
private:
USHORT nSel;
BOOL bHit;
protected:
virtual void Select();
public:
ScPopupMenu() : nSel(0),bHit(FALSE) {}
ScPopupMenu(const ResId& rRes) : PopupMenu(rRes),nSel(0),bHit(FALSE) {}
USHORT GetSelected() const { return nSel; }
BOOL WasHit() const { return bHit; }
};
#endif
<commit_msg>INTEGRATION: CWS tune03 (1.1.1.1.530); FILE MERGED 2004/07/08 16:45:11 mhu 1.1.1.1.530.1: #i29979# Added SC_DLLPUBLIC/PRIVATE (see scdllapi.h) to exported symbols/classes.<commit_after>/*************************************************************************
*
* $RCSfile: popmenu.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-08-23 09:34:43 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SC_POPMENU_HXX
#define SC_POPMENU_HXX
#ifndef _MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif
#ifndef INCLUDED_SCDLLAPI_H
#include "scdllapi.h"
#endif
class SC_DLLPUBLIC ScPopupMenu : public PopupMenu
{
private:
USHORT nSel;
BOOL bHit;
protected:
virtual void Select();
public:
ScPopupMenu() : nSel(0),bHit(FALSE) {}
ScPopupMenu(const ResId& rRes) : PopupMenu(rRes),nSel(0),bHit(FALSE) {}
USHORT GetSelected() const { return nSel; }
BOOL WasHit() const { return bHit; }
};
#endif
<|endoftext|> |
<commit_before>/*!
* Copyright (c) 2018 by Contributors
* \file alter_op_layout.cc
* \brief Alternate the layouts of operators or replace primitive operators with
other expressions. This pass can be used for computing convolution in
custom layouts or other general weight pre-transformation.
*/
#include <tvm/relay/pass.h>
#include <tvm/relay/op_attr_types.h>
#include <tvm/relay/attrs/transform.h>
#include <tvm/tvm.h>
#include <tuple>
#include <vector>
#include <functional>
#include <string>
#include <utility>
#include <unordered_map>
#include "alter_op_layout.h"
namespace tvm {
namespace relay {
namespace alter_op_layout {
// Make a transform CallNode
Expr TransformLayout(Expr raw, Layout src_layout, Layout dst_layout) {
if (src_layout.Equals(dst_layout)) { return raw; }
CHECK(src_layout.defined() && dst_layout.defined())
<< "Cannot insert layout transform because there are undefined layouts";
CHECK(BijectiveLayoutNode::make(src_layout, dst_layout).defined())
<< "Cannot insert layout transform because there are inconvertible layouts: "
<< src_layout << " v.s. " << dst_layout;
static auto &transform_op = Op::Get("layout_transform");
NodePtr<LayoutTransformAttrs> attrs = make_node<LayoutTransformAttrs>();
attrs->src_layout = src_layout.name();
attrs->dst_layout = dst_layout.name();
Call transform = CallNode::make(transform_op, {raw}, Attrs{attrs});
return std::move(transform);
}
// Memorize layout transform so we can reuse internal transformed nodes
class TransformMemorizerNode : public Node {
public:
// map from (Expr, src_layout, dst_layout) to transformed Expr
using TransformKey = std::tuple<const Node*, std::string, std::string>;
struct key_hash : public std::unary_function<TransformKey , std::size_t> {
std::size_t operator()(const TransformKey& k) const {
return dmlc::HashCombine<std::string>(dmlc::HashCombine<std::string>(
std::hash<const Node*>()(std::get<0>(k)), std::get<1>(k)), (std::get<2>(k)));
}
};
std::unordered_map<TransformKey, Expr, key_hash> memo;
static constexpr const char *_type_key = "relay.alter_op_layout.TransformMemorizerNode";
TVM_DECLARE_NODE_TYPE_INFO(TransformMemorizerNode, Node);
};
class TransformMemorizer : public NodeRef {
public:
TransformMemorizer() {}
explicit TransformMemorizer(NodePtr<Node> n) : NodeRef(n) {}
TransformMemorizerNode* operator->() {
return static_cast<TransformMemorizerNode*>(node_.get());
}
// Transform layout with memorizer
Expr Transform(Expr raw, const Layout& src_layout, const Layout& dst_layout) {
if (src_layout.Equals(dst_layout)) { return raw; }
std::tuple<const Node*, std::string, std::string> key =
std::make_tuple<>(raw.get(), src_layout.name(), dst_layout.name());
auto& memo = operator->()->memo;
auto iter = memo.find(key);
if (iter != memo.end()) {
return iter->second;
} else {
Expr transform = TransformLayout(raw, src_layout, dst_layout);
memo[key] = transform;
return transform;
}
}
using ContainerType = TransformMemorizerNode;
};
// TempExprNode during layout transform
// Instance of this expr will be Realized to normal expr ultimately
class LayoutAlternatedExprNode : public TempExprNode {
public:
Expr value;
Layout old_layout;
Layout new_layout;
TransformMemorizer memorizer;
Expr Realize() const final {
// NOTE: use a copy to discard the "const" qualifier
TransformMemorizer tmp_memorizer = memorizer;
// fallback to old layout
return tmp_memorizer.Transform(value, new_layout, old_layout);
}
void VisitAttrs(AttrVisitor *v) final {
v->Visit("value", &value);
v->Visit("old_layout", &old_layout);
v->Visit("new_layout", &new_layout);
}
static constexpr const char *_type_key = "relay.alter_op_layout.LayoutAlternatedExprNode";
TVM_DECLARE_NODE_TYPE_INFO(LayoutAlternatedExprNode, TempExprNode);
};
RELAY_DEFINE_NODE_REF(LayoutAlternatedExpr, LayoutAlternatedExprNode, TempExpr);
// Call registered FInferCorrectLayout of an op.
// Parameters are the same as the parameters for FInferCorrectLayout
// Returns inferred_input_layout, inferred_output_layout, success
std::tuple<Array<Layout>, Array<Layout>, bool> CallInfer(
const Call& call,
const Array<Layout>& new_in_layouts,
const Array<Layout>& old_in_layouts,
const Array<Array<IndexExpr> > &old_in_shapes) {
static auto finfer_layout = Op::GetAttr<FInferCorrectLayout>("FInferCorrectLayout");
Op op = Downcast<Op>(call->op);
if (finfer_layout.count(op)) {
Array<Array<Layout> > inferred_layouts;
inferred_layouts = finfer_layout[op](call->attrs, new_in_layouts,
old_in_layouts, old_in_shapes);
CHECK_EQ(inferred_layouts.size(), 2)
<< "FInferCorrectLayout should return an array with size of 2";
for (auto x : inferred_layouts) {
for (auto y : x) {
if (!y.defined()) { // inference fails
return std::make_tuple<>(Array<Layout>(nullptr), Array<Layout>(nullptr), false);
}
}
}
return std::make_tuple<>(inferred_layouts[0], inferred_layouts[1], true);
} else {
return std::make_tuple<>(Array<Layout>(nullptr), Array<Layout>(nullptr), false);
}
}
// Call registered FTVMAlterOpLayout of an op
// Returns the altered expression
Call CallAlter(const Call& ref_call,
const std::vector<Expr>& new_args) {
static auto falter_layout = Op::GetAttr<FTVMAlterOpLayout>("FTVMAlterOpLayout");
Op op = Downcast<Op>(ref_call->op);
Expr new_e;
bool modified = false;
if (falter_layout.count(op)) {
tvm::Array<tvm::Tensor> tinfos;
for (auto expr : ref_call->args) {
auto ttype = expr->type_as<TensorTypeNode>();
tinfos.push_back(tvm::placeholder(ttype->shape, ttype->dtype));
}
Expr altered_value = falter_layout[op](ref_call->attrs, new_args, tinfos);
if (altered_value.defined()) {
new_e = altered_value;
modified = true;
}
}
if (!modified) {
new_e = CallNode::make(ref_call->op, new_args,
ref_call->attrs);
}
const CallNode *new_call = new_e.as<CallNode>();
CHECK(new_call) << "Can only replace the original operator with another call node";
return GetRef<Call>(new_call);
}
Expr AlterOpLayoutRewrite(const Call &ref_call,
const Array<Expr> &new_args,
const NodeRef& ctx) {
std::vector<LayoutAlternatedExpr> inputs;
std::vector<Expr> normal_new_args;
Array<Array<IndexExpr> > input_shapes;
// NOTE: discard the "const" qualifier
TransformMemorizer memorizer = Downcast<TransformMemorizer>(ctx);
// fill incomplete state and flatten tuple
auto push_back_one_arg = [&inputs, memorizer](Expr arg) {
// We always expect LayoutAlternatedExpr.
// This is used to convert the normal Expr to LayoutAlternatedExpr.
if (const LayoutAlternatedExprNode *inp = arg.as<LayoutAlternatedExprNode>()) {
inputs.push_back(GetRef<LayoutAlternatedExpr>(inp));
return inp->value;
} else {
auto inode = make_node<LayoutAlternatedExprNode>();
inode->value = arg;
inode->memorizer = memorizer;
inputs.push_back(LayoutAlternatedExpr(inode));
return arg;
}
};
for (auto new_arg : new_args) {
// NOTE: do not support nested tuple
if (new_arg->is_type<TupleNode>()) {
Tuple tuple_new_arg = Downcast<Tuple>(new_arg);
std::vector<Expr> fields;
for (auto x : tuple_new_arg->fields) {
Expr tmp = push_back_one_arg(x);
fields.push_back(tmp);
}
normal_new_args.push_back(TupleNode::make(fields));
} else {
Expr tmp = push_back_one_arg(new_arg);
normal_new_args.push_back(tmp);
}
}
// old_in, new_in = state[inputs]
Array<Layout> old_in, old_out, new_in, new_out, new_in2;
for (auto inp : inputs) {
old_in.push_back(inp->old_layout);
new_in.push_back(inp->new_layout);
}
for (auto arg : ref_call->args) {
if (arg->is_type<TupleNode>()) { // flatten tuple
Tuple tuple_arg = Downcast<Tuple>(arg);
for (auto x : tuple_arg->fields) {
input_shapes.push_back(x->type_as<TensorTypeNode>()->shape);
}
} else {
input_shapes.push_back(arg->type_as<TensorTypeNode>()->shape);
}
}
// old_in, old_out = op.infer(old_in)
bool success = false;
std::tie(old_in, old_out, success) = CallInfer(ref_call,
Array<Layout>(nullptr),
old_in, input_shapes);
if (!success) { return Expr(nullptr); }
CHECK_EQ(old_in.size(), new_in.size());
// if new_in == 'undef': new_in = old_in
for (size_t i = 0; i < new_in.size(); ++i) {
if (!new_in[i].defined()) {
new_in.Set(i, old_in[i]);
}
}
// new_op = alter(op)
Call new_call = CallAlter(ref_call, normal_new_args);
// new_in2, new_out = op.infer(new_in)
if (new_call->op->is_type<OpNode>()) {
success = false;
std::tie(new_in2, new_out, success) = CallInfer(new_call, new_in, old_in, input_shapes);
if (!success) { return Expr(nullptr); }
} else {
return Expr(nullptr);
}
CHECK_EQ(new_out.size(), old_out.size())
<< "The number of output nodes should keep the same during alter_op_layout";
CHECK_EQ(new_in.size(), new_in2.size())
<< "The number of input nodes should keep the same during alter_op_layout";
// if (new_in != new_in2): insert transform (new_in -> new_in2)
Array<Expr> transformed_args;
size_t pt = 0;
for (auto arg : new_call->args) {
if (arg->is_type<TupleNode>()) { // unflatten tuple
Tuple tuple_arg = Downcast<Tuple>(arg);
std::vector<Expr> transformed_tuple_arg;
for (auto arg_item : tuple_arg->fields) {
transformed_tuple_arg.push_back(
memorizer.Transform(arg_item, new_in[pt], new_in2[pt]));
pt++;
}
transformed_args.push_back(TupleNode::make(transformed_tuple_arg));
} else {
transformed_args.push_back(
memorizer.Transform(arg, new_in[pt], new_in2[pt]));
pt++;
}
}
CHECK_EQ(pt, inputs.size());
// state[node] = (old_out, new_out)
// (handle tuple output)
if (ref_call->checked_type()->is_type<TupleTypeNode>()) {
Expr tuple_output = CallNode::make(new_call->op, transformed_args,
new_call->attrs);
Array<Expr> fields;
for (size_t i = 0; i < new_out.size(); ++i) {
auto rnode = make_node<LayoutAlternatedExprNode>();
rnode->value = TupleGetItemNode::make(tuple_output, i);
rnode->old_layout = old_out[i];
rnode->new_layout = new_out[i];
rnode->memorizer = memorizer;
fields.push_back(Expr(rnode));
}
return TupleNode::make(fields);
} else {
auto rnode = make_node<LayoutAlternatedExprNode>();
CHECK_EQ(new_out.size(), 1);
rnode->value = CallNode::make(new_call->op, transformed_args,
new_call->attrs);
rnode->old_layout = old_out[0];
rnode->new_layout = new_out[0];
rnode->memorizer = memorizer;
return Expr(rnode);
}
}
// Limiations:
// 1. the altered op should have the same number of arguments as the previous one
// 2. do not support nested tuple arguments
TVM_REGISTER_API("relay._ir_pass.AlterOpLayout")
.set_body([](TVMArgs args, TVMRetValue *ret) {
TransformMemorizer transformMemorizer(make_node<TransformMemorizerNode>());
auto fcontext = [&](const Call& call) -> NodeRef{
return transformMemorizer;
};
*ret = ForwardRewrite(args[0], AlterOpLayoutRewrite, fcontext);
});
} // namespace alter_op_layout
} // namespace relay
} // namespace tvm
<commit_msg>Removed std::unary_function because it is deprecated and removed in newer c++(https://en.cppreference.com/w/cpp/utility/functional/unary_function) (#2962)<commit_after>/*!
* Copyright (c) 2018 by Contributors
* \file alter_op_layout.cc
* \brief Alternate the layouts of operators or replace primitive operators with
other expressions. This pass can be used for computing convolution in
custom layouts or other general weight pre-transformation.
*/
#include <tvm/relay/pass.h>
#include <tvm/relay/op_attr_types.h>
#include <tvm/relay/attrs/transform.h>
#include <tvm/tvm.h>
#include <tuple>
#include <vector>
#include <functional>
#include <string>
#include <utility>
#include <unordered_map>
#include "alter_op_layout.h"
namespace tvm {
namespace relay {
namespace alter_op_layout {
// Make a transform CallNode
Expr TransformLayout(Expr raw, Layout src_layout, Layout dst_layout) {
if (src_layout.Equals(dst_layout)) { return raw; }
CHECK(src_layout.defined() && dst_layout.defined())
<< "Cannot insert layout transform because there are undefined layouts";
CHECK(BijectiveLayoutNode::make(src_layout, dst_layout).defined())
<< "Cannot insert layout transform because there are inconvertible layouts: "
<< src_layout << " v.s. " << dst_layout;
static auto &transform_op = Op::Get("layout_transform");
NodePtr<LayoutTransformAttrs> attrs = make_node<LayoutTransformAttrs>();
attrs->src_layout = src_layout.name();
attrs->dst_layout = dst_layout.name();
Call transform = CallNode::make(transform_op, {raw}, Attrs{attrs});
return std::move(transform);
}
// Memorize layout transform so we can reuse internal transformed nodes
class TransformMemorizerNode : public Node {
public:
// map from (Expr, src_layout, dst_layout) to transformed Expr
using TransformKey = std::tuple<const Node*, std::string, std::string>;
struct key_hash : public std::function<std::size_t(TransformKey)> {
std::size_t operator()(const TransformKey& k) const {
return dmlc::HashCombine<std::string>(dmlc::HashCombine<std::string>(
std::hash<const Node*>()(std::get<0>(k)), std::get<1>(k)), (std::get<2>(k)));
}
};
std::unordered_map<TransformKey, Expr, key_hash> memo;
static constexpr const char *_type_key = "relay.alter_op_layout.TransformMemorizerNode";
TVM_DECLARE_NODE_TYPE_INFO(TransformMemorizerNode, Node);
};
class TransformMemorizer : public NodeRef {
public:
TransformMemorizer() {}
explicit TransformMemorizer(NodePtr<Node> n) : NodeRef(n) {}
TransformMemorizerNode* operator->() {
return static_cast<TransformMemorizerNode*>(node_.get());
}
// Transform layout with memorizer
Expr Transform(Expr raw, const Layout& src_layout, const Layout& dst_layout) {
if (src_layout.Equals(dst_layout)) { return raw; }
std::tuple<const Node*, std::string, std::string> key =
std::make_tuple<>(raw.get(), src_layout.name(), dst_layout.name());
auto& memo = operator->()->memo;
auto iter = memo.find(key);
if (iter != memo.end()) {
return iter->second;
} else {
Expr transform = TransformLayout(raw, src_layout, dst_layout);
memo[key] = transform;
return transform;
}
}
using ContainerType = TransformMemorizerNode;
};
// TempExprNode during layout transform
// Instance of this expr will be Realized to normal expr ultimately
class LayoutAlternatedExprNode : public TempExprNode {
public:
Expr value;
Layout old_layout;
Layout new_layout;
TransformMemorizer memorizer;
Expr Realize() const final {
// NOTE: use a copy to discard the "const" qualifier
TransformMemorizer tmp_memorizer = memorizer;
// fallback to old layout
return tmp_memorizer.Transform(value, new_layout, old_layout);
}
void VisitAttrs(AttrVisitor *v) final {
v->Visit("value", &value);
v->Visit("old_layout", &old_layout);
v->Visit("new_layout", &new_layout);
}
static constexpr const char *_type_key = "relay.alter_op_layout.LayoutAlternatedExprNode";
TVM_DECLARE_NODE_TYPE_INFO(LayoutAlternatedExprNode, TempExprNode);
};
RELAY_DEFINE_NODE_REF(LayoutAlternatedExpr, LayoutAlternatedExprNode, TempExpr);
// Call registered FInferCorrectLayout of an op.
// Parameters are the same as the parameters for FInferCorrectLayout
// Returns inferred_input_layout, inferred_output_layout, success
std::tuple<Array<Layout>, Array<Layout>, bool> CallInfer(
const Call& call,
const Array<Layout>& new_in_layouts,
const Array<Layout>& old_in_layouts,
const Array<Array<IndexExpr> > &old_in_shapes) {
static auto finfer_layout = Op::GetAttr<FInferCorrectLayout>("FInferCorrectLayout");
Op op = Downcast<Op>(call->op);
if (finfer_layout.count(op)) {
Array<Array<Layout> > inferred_layouts;
inferred_layouts = finfer_layout[op](call->attrs, new_in_layouts,
old_in_layouts, old_in_shapes);
CHECK_EQ(inferred_layouts.size(), 2)
<< "FInferCorrectLayout should return an array with size of 2";
for (auto x : inferred_layouts) {
for (auto y : x) {
if (!y.defined()) { // inference fails
return std::make_tuple<>(Array<Layout>(nullptr), Array<Layout>(nullptr), false);
}
}
}
return std::make_tuple<>(inferred_layouts[0], inferred_layouts[1], true);
} else {
return std::make_tuple<>(Array<Layout>(nullptr), Array<Layout>(nullptr), false);
}
}
// Call registered FTVMAlterOpLayout of an op
// Returns the altered expression
Call CallAlter(const Call& ref_call,
const std::vector<Expr>& new_args) {
static auto falter_layout = Op::GetAttr<FTVMAlterOpLayout>("FTVMAlterOpLayout");
Op op = Downcast<Op>(ref_call->op);
Expr new_e;
bool modified = false;
if (falter_layout.count(op)) {
tvm::Array<tvm::Tensor> tinfos;
for (auto expr : ref_call->args) {
auto ttype = expr->type_as<TensorTypeNode>();
tinfos.push_back(tvm::placeholder(ttype->shape, ttype->dtype));
}
Expr altered_value = falter_layout[op](ref_call->attrs, new_args, tinfos);
if (altered_value.defined()) {
new_e = altered_value;
modified = true;
}
}
if (!modified) {
new_e = CallNode::make(ref_call->op, new_args,
ref_call->attrs);
}
const CallNode *new_call = new_e.as<CallNode>();
CHECK(new_call) << "Can only replace the original operator with another call node";
return GetRef<Call>(new_call);
}
Expr AlterOpLayoutRewrite(const Call &ref_call,
const Array<Expr> &new_args,
const NodeRef& ctx) {
std::vector<LayoutAlternatedExpr> inputs;
std::vector<Expr> normal_new_args;
Array<Array<IndexExpr> > input_shapes;
// NOTE: discard the "const" qualifier
TransformMemorizer memorizer = Downcast<TransformMemorizer>(ctx);
// fill incomplete state and flatten tuple
auto push_back_one_arg = [&inputs, memorizer](Expr arg) {
// We always expect LayoutAlternatedExpr.
// This is used to convert the normal Expr to LayoutAlternatedExpr.
if (const LayoutAlternatedExprNode *inp = arg.as<LayoutAlternatedExprNode>()) {
inputs.push_back(GetRef<LayoutAlternatedExpr>(inp));
return inp->value;
} else {
auto inode = make_node<LayoutAlternatedExprNode>();
inode->value = arg;
inode->memorizer = memorizer;
inputs.push_back(LayoutAlternatedExpr(inode));
return arg;
}
};
for (auto new_arg : new_args) {
// NOTE: do not support nested tuple
if (new_arg->is_type<TupleNode>()) {
Tuple tuple_new_arg = Downcast<Tuple>(new_arg);
std::vector<Expr> fields;
for (auto x : tuple_new_arg->fields) {
Expr tmp = push_back_one_arg(x);
fields.push_back(tmp);
}
normal_new_args.push_back(TupleNode::make(fields));
} else {
Expr tmp = push_back_one_arg(new_arg);
normal_new_args.push_back(tmp);
}
}
// old_in, new_in = state[inputs]
Array<Layout> old_in, old_out, new_in, new_out, new_in2;
for (auto inp : inputs) {
old_in.push_back(inp->old_layout);
new_in.push_back(inp->new_layout);
}
for (auto arg : ref_call->args) {
if (arg->is_type<TupleNode>()) { // flatten tuple
Tuple tuple_arg = Downcast<Tuple>(arg);
for (auto x : tuple_arg->fields) {
input_shapes.push_back(x->type_as<TensorTypeNode>()->shape);
}
} else {
input_shapes.push_back(arg->type_as<TensorTypeNode>()->shape);
}
}
// old_in, old_out = op.infer(old_in)
bool success = false;
std::tie(old_in, old_out, success) = CallInfer(ref_call,
Array<Layout>(nullptr),
old_in, input_shapes);
if (!success) { return Expr(nullptr); }
CHECK_EQ(old_in.size(), new_in.size());
// if new_in == 'undef': new_in = old_in
for (size_t i = 0; i < new_in.size(); ++i) {
if (!new_in[i].defined()) {
new_in.Set(i, old_in[i]);
}
}
// new_op = alter(op)
Call new_call = CallAlter(ref_call, normal_new_args);
// new_in2, new_out = op.infer(new_in)
if (new_call->op->is_type<OpNode>()) {
success = false;
std::tie(new_in2, new_out, success) = CallInfer(new_call, new_in, old_in, input_shapes);
if (!success) { return Expr(nullptr); }
} else {
return Expr(nullptr);
}
CHECK_EQ(new_out.size(), old_out.size())
<< "The number of output nodes should keep the same during alter_op_layout";
CHECK_EQ(new_in.size(), new_in2.size())
<< "The number of input nodes should keep the same during alter_op_layout";
// if (new_in != new_in2): insert transform (new_in -> new_in2)
Array<Expr> transformed_args;
size_t pt = 0;
for (auto arg : new_call->args) {
if (arg->is_type<TupleNode>()) { // unflatten tuple
Tuple tuple_arg = Downcast<Tuple>(arg);
std::vector<Expr> transformed_tuple_arg;
for (auto arg_item : tuple_arg->fields) {
transformed_tuple_arg.push_back(
memorizer.Transform(arg_item, new_in[pt], new_in2[pt]));
pt++;
}
transformed_args.push_back(TupleNode::make(transformed_tuple_arg));
} else {
transformed_args.push_back(
memorizer.Transform(arg, new_in[pt], new_in2[pt]));
pt++;
}
}
CHECK_EQ(pt, inputs.size());
// state[node] = (old_out, new_out)
// (handle tuple output)
if (ref_call->checked_type()->is_type<TupleTypeNode>()) {
Expr tuple_output = CallNode::make(new_call->op, transformed_args,
new_call->attrs);
Array<Expr> fields;
for (size_t i = 0; i < new_out.size(); ++i) {
auto rnode = make_node<LayoutAlternatedExprNode>();
rnode->value = TupleGetItemNode::make(tuple_output, i);
rnode->old_layout = old_out[i];
rnode->new_layout = new_out[i];
rnode->memorizer = memorizer;
fields.push_back(Expr(rnode));
}
return TupleNode::make(fields);
} else {
auto rnode = make_node<LayoutAlternatedExprNode>();
CHECK_EQ(new_out.size(), 1);
rnode->value = CallNode::make(new_call->op, transformed_args,
new_call->attrs);
rnode->old_layout = old_out[0];
rnode->new_layout = new_out[0];
rnode->memorizer = memorizer;
return Expr(rnode);
}
}
// Limiations:
// 1. the altered op should have the same number of arguments as the previous one
// 2. do not support nested tuple arguments
TVM_REGISTER_API("relay._ir_pass.AlterOpLayout")
.set_body([](TVMArgs args, TVMRetValue *ret) {
TransformMemorizer transformMemorizer(make_node<TransformMemorizerNode>());
auto fcontext = [&](const Call& call) -> NodeRef{
return transformMemorizer;
};
*ret = ForwardRewrite(args[0], AlterOpLayoutRewrite, fcontext);
});
} // namespace alter_op_layout
} // namespace relay
} // namespace tvm
<|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 <cassert>
#include "app/canvas.hh"
#include "bitmap/pattern.hh"
#include "geo/geo-func.hh"
#include "geo/int-rect.hh"
#include "text/formatting.hh"
#include "tools/standard-tool.hh"
#include "tools/tool-actions.hh"
#include "util/pos-info.hh"
#include "util/tool-util.hh"
namespace faint{
static bool should_pick_to_pattern(const PosInfo& info){
return info.modifiers.Primary();
}
static bool should_anchor_topleft(const PosInfo& info){
return info.modifiers.Secondary();
}
static Paint pattern_get_hovered_paint(const PosInside& info){
// Do not pick invisible object insides. Include the floating
// selection if hovered
return get_hovered_paint(info,
include_hidden_fill(false),
include_floating_selection(true));
}
class PickerTool : public StandardTool {
public:
PickerTool(ToolActions& actions)
: StandardTool(ToolId::PICKER, Settings()),
m_actions(actions)
{}
void Draw(FaintDC&, Overlays&, const PosInfo&) override{
}
bool DrawBeforeZoom(Layer) const override{
return false;
}
Command* GetCommand() override{
assert(false);
return nullptr;
}
Cursor GetCursor(const PosInfo& info) const override{
if (should_pick_to_pattern(info)){
return should_anchor_topleft(info) ?
Cursor::PICKER_PATTERN_TOPLEFT : Cursor::PICKER_PATTERN;
}
return Cursor::PICKER;
}
IntRect GetRefreshRect(const RefreshInfo&) const override{
return {};
}
ToolResult MouseDown(const PosInfo& info) override{
return inside_canvas(info).Visit(
[&](const PosInside& info){
const auto paintSetting = fg_or_bg(info);
const auto& bg = info->canvas.GetBitmap();
if (should_pick_to_pattern(info) && bg.IsSet()){
bool anchorTopLeft = should_anchor_topleft(info);
IntPoint anchor = anchorTopLeft ?
IntPoint(0,0) : // Image top left
floored(info->pos);
Pattern pattern(bg.Get(),
anchor, object_aligned_t(!anchorTopLeft));
m_actions.Set(paintSetting, Paint(pattern));
return ToolResult::NONE;
}
m_actions.Set(paintSetting, pattern_get_hovered_paint(info));
return ToolResult::NONE;
},
[](){
// Outside
return ToolResult::NONE;
});
}
ToolResult MouseUp(const PosInfo&) override{
return ToolResult::NONE;
}
ToolResult MouseMove(const PosInfo& info) override{
inside_canvas(info).Visit(
[](const PosInside& info){
// Inside canvas
if (should_pick_to_pattern(info)){
info->status.SetMainText("Click to use image as pattern");
info->status.SetText(should_anchor_topleft(info) ?
"Anchor: Top Left (0,0)" :
space_sep("Anchor:", bracketed(str_floor((info->pos)))));
}
else{
Paint paint(pattern_get_hovered_paint(info));
info->status.SetMainText("");
info->status.SetText(space_sep(str(paint),
bracketed(str_floor(info->pos))));
}
},
[&info](){
// Outside
info.status.SetMainText("");
info.status.SetText(bracketed(str_floor(info.pos)));
});
return ToolResult::NONE;
}
ToolResult Preempt(const PosInfo&) override{
return ToolResult::NONE;
}
ToolActions& m_actions;
};
Tool* picker_tool(ToolActions& actions){
return new PickerTool(actions);
}
} // namespace
<commit_msg>Simplified picker.<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 <cassert>
#include "app/canvas.hh"
#include "bitmap/pattern.hh"
#include "geo/geo-func.hh"
#include "geo/int-rect.hh"
#include "text/formatting.hh"
#include "tools/standard-tool.hh"
#include "tools/tool-actions.hh"
#include "util/pos-info.hh"
#include "util/tool-util.hh"
namespace faint{
static bool should_pick_to_pattern(const PosInfo& info){
return info.modifiers.Primary();
}
static bool should_anchor_topleft(const PosInfo& info){
return info.modifiers.Secondary();
}
static Paint pattern_get_hovered_paint(const PosInside& info){
// Pick either the hovered object fill, the color at the pixel in
// the background or floating raster selection.
// Do not pick invisible object insides.
return get_hovered_paint(info,
include_hidden_fill(false),
include_floating_selection(true));
}
static Paint pick_to_pattern(const PosInside& info, const Bitmap& bg){
// Pick the background bitmap as a pattern, anchored around either
// the click-point or the top-left corner
bool anchorTopLeft = should_anchor_topleft(info);
IntPoint anchor = anchorTopLeft ?
IntPoint(0,0) : // Image top left
floored(info->pos);
Pattern pattern(bg, anchor, object_aligned_t(!anchorTopLeft));
return Paint(pattern);
}
static ToolResult pick(const PosInside& info, ToolActions& actions){
const auto& bg = info->canvas.GetBitmap();
Paint paint = (should_pick_to_pattern(info) && bg.IsSet()) ?
pick_to_pattern(info, bg.Get()) :
pattern_get_hovered_paint(info);
actions.Set(fg_or_bg(info), paint);
return ToolResult::NONE;
}
class PickerTool : public StandardTool {
public:
PickerTool(ToolActions& actions)
: StandardTool(ToolId::PICKER, Settings()),
m_actions(actions)
{}
void Draw(FaintDC&, Overlays&, const PosInfo&) override{
}
bool DrawBeforeZoom(Layer) const override{
return false;
}
Command* GetCommand() override{
assert(false);
return nullptr;
}
Cursor GetCursor(const PosInfo& info) const override{
if (should_pick_to_pattern(info)){
return should_anchor_topleft(info) ?
Cursor::PICKER_PATTERN_TOPLEFT : Cursor::PICKER_PATTERN;
}
return Cursor::PICKER;
}
IntRect GetRefreshRect(const RefreshInfo&) const override{
return {};
}
ToolResult MouseDown(const PosInfo& info) override{
return inside_canvas(info).Visit(
[&](const PosInside& insidePos){
return pick(insidePos, m_actions);
},
otherwise(ToolResult::NONE));
}
ToolResult MouseUp(const PosInfo&) override{
return ToolResult::NONE;
}
ToolResult MouseMove(const PosInfo& info) override{
inside_canvas(info).Visit(
[](const PosInside& info){
// Inside canvas
if (should_pick_to_pattern(info)){
info->status.SetMainText("Click to use image as pattern");
info->status.SetText(should_anchor_topleft(info) ?
"Anchor: Top Left (0,0)" :
space_sep("Anchor:", bracketed(str_floor((info->pos)))));
}
else{
Paint paint(pattern_get_hovered_paint(info));
info->status.SetMainText("");
info->status.SetText(space_sep(str(paint),
bracketed(str_floor(info->pos))));
}
},
[&info](){
// Outside
info.status.SetMainText("");
info.status.SetText(bracketed(str_floor(info.pos)));
});
return ToolResult::NONE;
}
ToolResult Preempt(const PosInfo&) override{
return ToolResult::NONE;
}
ToolActions& m_actions;
};
Tool* picker_tool(ToolActions& actions){
return new PickerTool(actions);
}
} // namespace
<|endoftext|> |
<commit_before>#include <osg/GL>
#include <osgGLUT/glut>
#include <osgGLUT/Viewer>
#include <osg/Node>
#include <osg/Notify>
#include <osgUtil/Optimizer>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgTXP/TrPageArchive.h>
#include <osgTXP/TrPageViewer.h>
void write_usage(std::ostream& out,const std::string& name)
{
out << std::endl;
out <<"usage:"<< std::endl;
out <<" "<<name<<" [options] infile1 [infile2 ...]"<< std::endl;
out << std::endl;
out <<"options:"<< std::endl;
out <<" -l libraryName - load plugin of name libraryName"<< std::endl;
out <<" i.e. -l osgdb_pfb"<< std::endl;
out <<" Useful for loading reader/writers which can load"<< std::endl;
out <<" other file formats in addition to its extension."<< std::endl;
out <<" -e extensionName - load reader/wrter plugin for file extension"<< std::endl;
out <<" i.e. -e pfb"<< std::endl;
out <<" Useful short hand for specifying full library name as"<< std::endl;
out <<" done with -l above, as it automatically expands to"<< std::endl;
out <<" the full library name appropriate for each platform."<< std::endl;
out <<std::endl;
out <<" -stereo - switch on stereo rendering, using the default of,"<< std::endl;
out <<" ANAGLYPHIC or the value set in the OSG_STEREO_MODE "<< std::endl;
out <<" environmental variable. See doc/stereo.html for "<< std::endl;
out <<" further details on setting up accurate stereo "<< std::endl;
out <<" for your system. "<< std::endl;
out <<" -stereo ANAGLYPHIC - switch on anaglyphic(red/cyan) stereo rendering."<< std::endl;
out <<" -stereo QUAD_BUFFER - switch on quad buffered stereo rendering."<< std::endl;
out <<std::endl;
out <<" -stencil - use a visual with stencil buffer enabled, this "<< std::endl;
out <<" also allows the depth complexity statistics mode"<< std::endl;
out <<" to be used (press 'p' three times to cycle to it)."<< std::endl;
out <<" -f - start with a full screen, borderless window." << std::endl;
out << std::endl;
}
using namespace txp;
int main( int argc, char **argv )
{
// initialize the GLUT
glutInit( &argc, argv );
if (argc<2)
{
write_usage(std::cout,argv[0]);
return 0;
}
// create the commandline args.
std::vector<std::string> commandLine;
for(int i=1;i<argc;++i) commandLine.push_back(argv[i]);
// initialize the viewer.
PagingViewer *viewer = new PagingViewer();
viewer->setWindowTitle(argv[0]);
// configure the viewer from the commandline arguments, and eat any
// parameters that have been matched.
viewer->readCommandLine(commandLine);
// configure the plugin registry from the commandline arguments, and
// eat any parameters that have been matched.
osgDB::readCommandLine(commandLine);
// Initialize the TXP database
bool loadAll = false;
bool threadIt = false;
std::string fileName;
for(std::vector<std::string>::iterator itr=commandLine.begin();
itr!=commandLine.end();
++itr)
{
if ((*itr)[0]!='-')
{
fileName = (*itr);
} else {
// Look for switches we want
if (!strcasecmp((*itr).c_str(),"-loadall")) {
loadAll = true;
continue;
}
if (!strcasecmp((*itr).c_str(),"-thread")) {
threadIt = true;
continue;
}
}
}
if (fileName.empty()) {
fprintf(stderr,"No TerraPage file specified on command line.\n");
return 1;
}
// Open the TXP database
TrPageArchive *txpArchive = new TrPageArchive();
if (!txpArchive->OpenFile(fileName.c_str())) {
fprintf(stderr,"Couldn't load TerraPage archive %s.\n",fileName.c_str());
return 1;
}
// Note: Should be checking the return values
txpArchive->LoadMaterials();
// txpArchive->LoadModels();
// Might need a page manager if we're paging
OSGPageManager *pageManager = new OSGPageManager(txpArchive);
osg::Group *rootNode=NULL;
if (loadAll) {
// Load the whole scenegraph
rootNode = txpArchive->LoadAllTiles();
if (!rootNode) {
fprintf(stderr,"Couldn't load whole TerraPage archive %s.\n",fileName.c_str());
return 1;
}
// add a viewport to the viewer and attach the scene graph.
viewer->addViewport( rootNode );
} else {
viewer->Init(pageManager,(threadIt ? txp::OSGPageManager::ThreadFree : txp::OSGPageManager::ThreadNone));
rootNode = new osg::Group();
viewer->addViewport(rootNode);
}
// run optimization over the scene graph
// osgUtil::Optimizer optimzer;
// optimzer.optimize(rootnode);
// register trackball, flight and drive.
viewer->registerCameraManipulator(new osgGA::TrackballManipulator);
viewer->registerCameraManipulator(new osgGA::FlightManipulator);
viewer->registerCameraManipulator(new osgGA::DriveManipulator);
// Recenter the camera to the middle of the database
osg::Vec3 center;
txpArchive->GetCenter(center); center[2] += 200;
osgUtil::SceneView *sceneView = viewer->getViewportSceneView(0);
osg::Camera *camera = sceneView->getCamera();
osg::Vec3 eyePt = center;
eyePt[0] -= 1000;
osg::Vec3 upVec( 0, 0, 1 );
camera->setLookAt(eyePt,center,upVec);
// open the viewer window.
viewer->open();
// fire up the event loop.
viewer->run();
// Close things down
delete pageManager;
delete txpArchive;
delete viewer;
return 0;
}
<commit_msg>Added comment for future reference about the validity of using delete in the demo code... should really by using ref_ptr<> etc.<commit_after>#include <osg/GL>
#include <osgGLUT/glut>
#include <osgGLUT/Viewer>
#include <osg/Node>
#include <osg/Notify>
#include <osgUtil/Optimizer>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgTXP/TrPageArchive.h>
#include <osgTXP/TrPageViewer.h>
void write_usage(std::ostream& out,const std::string& name)
{
out << std::endl;
out <<"usage:"<< std::endl;
out <<" "<<name<<" [options] infile1 [infile2 ...]"<< std::endl;
out << std::endl;
out <<"options:"<< std::endl;
out <<" -l libraryName - load plugin of name libraryName"<< std::endl;
out <<" i.e. -l osgdb_pfb"<< std::endl;
out <<" Useful for loading reader/writers which can load"<< std::endl;
out <<" other file formats in addition to its extension."<< std::endl;
out <<" -e extensionName - load reader/wrter plugin for file extension"<< std::endl;
out <<" i.e. -e pfb"<< std::endl;
out <<" Useful short hand for specifying full library name as"<< std::endl;
out <<" done with -l above, as it automatically expands to"<< std::endl;
out <<" the full library name appropriate for each platform."<< std::endl;
out <<std::endl;
out <<" -stereo - switch on stereo rendering, using the default of,"<< std::endl;
out <<" ANAGLYPHIC or the value set in the OSG_STEREO_MODE "<< std::endl;
out <<" environmental variable. See doc/stereo.html for "<< std::endl;
out <<" further details on setting up accurate stereo "<< std::endl;
out <<" for your system. "<< std::endl;
out <<" -stereo ANAGLYPHIC - switch on anaglyphic(red/cyan) stereo rendering."<< std::endl;
out <<" -stereo QUAD_BUFFER - switch on quad buffered stereo rendering."<< std::endl;
out <<std::endl;
out <<" -stencil - use a visual with stencil buffer enabled, this "<< std::endl;
out <<" also allows the depth complexity statistics mode"<< std::endl;
out <<" to be used (press 'p' three times to cycle to it)."<< std::endl;
out <<" -f - start with a full screen, borderless window." << std::endl;
out << std::endl;
}
using namespace txp;
int main( int argc, char **argv )
{
// initialize the GLUT
glutInit( &argc, argv );
if (argc<2)
{
write_usage(std::cout,argv[0]);
return 0;
}
// create the commandline args.
std::vector<std::string> commandLine;
for(int i=1;i<argc;++i) commandLine.push_back(argv[i]);
// initialize the viewer.
PagingViewer *viewer = new PagingViewer();
viewer->setWindowTitle(argv[0]);
// configure the viewer from the commandline arguments, and eat any
// parameters that have been matched.
viewer->readCommandLine(commandLine);
// configure the plugin registry from the commandline arguments, and
// eat any parameters that have been matched.
osgDB::readCommandLine(commandLine);
// Initialize the TXP database
bool loadAll = false;
bool threadIt = false;
std::string fileName;
for(std::vector<std::string>::iterator itr=commandLine.begin();
itr!=commandLine.end();
++itr)
{
if ((*itr)[0]!='-')
{
fileName = (*itr);
} else {
// Look for switches we want
if (!strcasecmp((*itr).c_str(),"-loadall")) {
loadAll = true;
continue;
}
if (!strcasecmp((*itr).c_str(),"-thread")) {
threadIt = true;
continue;
}
}
}
if (fileName.empty()) {
fprintf(stderr,"No TerraPage file specified on command line.\n");
return 1;
}
// Open the TXP database
TrPageArchive *txpArchive = new TrPageArchive();
if (!txpArchive->OpenFile(fileName.c_str())) {
fprintf(stderr,"Couldn't load TerraPage archive %s.\n",fileName.c_str());
return 1;
}
// Note: Should be checking the return values
txpArchive->LoadMaterials();
// txpArchive->LoadModels();
// Might need a page manager if we're paging
OSGPageManager *pageManager = new OSGPageManager(txpArchive);
osg::Group *rootNode=NULL;
if (loadAll) {
// Load the whole scenegraph
rootNode = txpArchive->LoadAllTiles();
if (!rootNode) {
fprintf(stderr,"Couldn't load whole TerraPage archive %s.\n",fileName.c_str());
return 1;
}
// add a viewport to the viewer and attach the scene graph.
viewer->addViewport( rootNode );
} else {
viewer->Init(pageManager,(threadIt ? txp::OSGPageManager::ThreadFree : txp::OSGPageManager::ThreadNone));
rootNode = new osg::Group();
viewer->addViewport(rootNode);
}
// run optimization over the scene graph
// osgUtil::Optimizer optimzer;
// optimzer.optimize(rootnode);
// register trackball, flight and drive.
viewer->registerCameraManipulator(new osgGA::TrackballManipulator);
viewer->registerCameraManipulator(new osgGA::FlightManipulator);
viewer->registerCameraManipulator(new osgGA::DriveManipulator);
// Recenter the camera to the middle of the database
osg::Vec3 center;
txpArchive->GetCenter(center); center[2] += 200;
osgUtil::SceneView *sceneView = viewer->getViewportSceneView(0);
osg::Camera *camera = sceneView->getCamera();
osg::Vec3 eyePt = center;
eyePt[0] -= 1000;
osg::Vec3 upVec( 0, 0, 1 );
camera->setLookAt(eyePt,center,upVec);
// open the viewer window.
viewer->open();
// fire up the event loop.
viewer->run();
// Close things down
// (note from Robert Osfield, umm.... we should be using ref_ptr<> for handling memory here, this isn't robust..)
delete pageManager;
delete txpArchive;
delete viewer;
return 0;
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkView.h"
#include "SkBlurMaskFilter.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkTextBox.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "SkKey.h"
#ifdef SK_BUILD_FOR_WIN
extern SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT&);
#endif
static const char gText[] =
"When in the Course of human events it becomes necessary for one people "
"to dissolve the political bands which have connected them with another "
"and to assume among the powers of the earth, the separate and equal "
"station to which the Laws of Nature and of Nature's God entitle them, "
"a decent respect to the opinions of mankind requires that they should "
"declare the causes which impel them to the separation.";
class TextBoxView : public SampleView {
public:
TextBoxView() {
#ifdef SK_BUILD_FOR_WIN
LOGFONT lf;
sk_bzero(&lf, sizeof(lf));
lf.lfHeight = 9;
SkTypeface* tf0 = SkCreateTypefaceFromLOGFONT(lf);
lf.lfHeight = 12;
SkTypeface* tf1 = SkCreateTypefaceFromLOGFONT(lf);
// we assert that different sizes should not affect which face we get
SkASSERT(tf0 == tf1);
tf0->unref();
tf1->unref();
#endif
}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SkString str("TextBox");
SampleCode::TitleR(evt, str.c_str());
return true;
}
return this->INHERITED::onQuery(evt);
}
virtual void onDrawContent(SkCanvas* canvas) {
SkScalar margin = 20;
SkTextBox tbox;
tbox.setMode(SkTextBox::kLineBreak_Mode);
tbox.setBox(margin, margin,
this->width() - margin, this->height() - margin);
tbox.setSpacing(SkIntToScalar(3)/3, 0);
SkPaint paint;
paint.setAntiAlias(true);
paint.setLCDRenderText(true);
tbox.setText(gText, strlen(gText), paint);
for (int i = 9; i < 24; i += 2) {
paint.setTextSize(SkIntToScalar(i));
tbox.draw(canvas);
canvas->translate(0, tbox.getTextHeight() + paint.getFontSpacing());
}
}
private:
typedef SkView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new TextBoxView; }
static SkViewRegister reg(MyFactory);
<commit_msg>fix INHERITED to match class<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SampleCode.h"
#include "SkView.h"
#include "SkBlurMaskFilter.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkTypeface.h"
#include "SkTextBox.h"
#include "SkOSFile.h"
#include "SkStream.h"
#include "SkKey.h"
#ifdef SK_BUILD_FOR_WIN
extern SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT&);
#endif
static const char gText[] =
"When in the Course of human events it becomes necessary for one people "
"to dissolve the political bands which have connected them with another "
"and to assume among the powers of the earth, the separate and equal "
"station to which the Laws of Nature and of Nature's God entitle them, "
"a decent respect to the opinions of mankind requires that they should "
"declare the causes which impel them to the separation.";
class TextBoxView : public SampleView {
public:
TextBoxView() {
#ifdef SK_BUILD_FOR_WIN
LOGFONT lf;
sk_bzero(&lf, sizeof(lf));
lf.lfHeight = 9;
SkTypeface* tf0 = SkCreateTypefaceFromLOGFONT(lf);
lf.lfHeight = 12;
SkTypeface* tf1 = SkCreateTypefaceFromLOGFONT(lf);
// we assert that different sizes should not affect which face we get
SkASSERT(tf0 == tf1);
tf0->unref();
tf1->unref();
#endif
}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SkString str("TextBox");
SampleCode::TitleR(evt, str.c_str());
return true;
}
return this->INHERITED::onQuery(evt);
}
virtual void onDrawContent(SkCanvas* canvas) {
SkScalar margin = 20;
SkTextBox tbox;
tbox.setMode(SkTextBox::kLineBreak_Mode);
tbox.setBox(margin, margin,
this->width() - margin, this->height() - margin);
tbox.setSpacing(SkIntToScalar(3)/3, 0);
SkPaint paint;
paint.setAntiAlias(true);
paint.setLCDRenderText(true);
tbox.setText(gText, strlen(gText), paint);
for (int i = 9; i < 24; i += 2) {
paint.setTextSize(SkIntToScalar(i));
tbox.draw(canvas);
canvas->translate(0, tbox.getTextHeight() + paint.getFontSpacing());
}
}
private:
typedef SampleView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new TextBoxView; }
static SkViewRegister reg(MyFactory);
<|endoftext|> |
<commit_before>#ifndef __CLUSTERING_ADMINISTRATION_NAMESPACE_METADATA_HPP__
#define __CLUSTERING_ADMINISTRATION_NAMESPACE_METADATA_HPP__
#include <map>
#include "utils.hpp"
#include <boost/uuid/uuid.hpp>
#include <boost/bind.hpp>
#include "clustering/administration/datacenter_metadata.hpp"
#include "clustering/administration/json_adapters.hpp"
#include "clustering/administration/persistable_blueprint.hpp"
#include "clustering/immediate_consistency/branch/metadata.hpp"
#include "clustering/immediate_consistency/query/metadata.hpp"
#include "clustering/reactor/blueprint.hpp"
#include "clustering/reactor/directory_echo.hpp"
#include "clustering/reactor/metadata.hpp"
#include "http/json/json_adapter.hpp"
#include "rpc/semilattice/joins/deletable.hpp"
#include "rpc/semilattice/joins/macros.hpp"
#include "rpc/semilattice/joins/vclock.hpp"
#include "rpc/serialize_macros.hpp"
typedef boost::uuids::uuid namespace_id_t;
/* This is the metadata for a single namespace of a specific protocol. */
template<class protocol_t>
class namespace_semilattice_metadata_t {
public:
vclock_t<persistable_blueprint_t<protocol_t> > blueprint;
vclock_t<datacenter_id_t> primary_datacenter;
vclock_t<std::map<datacenter_id_t, int> > replica_affinities;
vclock_t<std::set<typename protocol_t::region_t> > shards;
vclock_t<std::string> name;
RDB_MAKE_ME_SERIALIZABLE_4(blueprint, primary_datacenter, replica_affinities, shards);
};
template<class protocol_t>
RDB_MAKE_SEMILATTICE_JOINABLE_4(namespace_semilattice_metadata_t<protocol_t>, blueprint, primary_datacenter, replica_affinities, shards);
template<class protocol_t>
RDB_MAKE_EQUALITY_COMPARABLE_4(namespace_semilattice_metadata_t<protocol_t>, blueprint, primary_datacenter, replica_affinities, shards);
//json adapter concept for namespace_semilattice_metadata_t
template <class ctx_t, class protocol_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(namespace_semilattice_metadata_t<protocol_t> *target, const ctx_t &) {
typename json_adapter_if_t<ctx_t>::json_adapter_map_t res;
res["blueprint"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<persistable_blueprint_t<protocol_t> >, ctx_t>(&target->blueprint));
res["primary_uuid"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<datacenter_id_t>, ctx_t>(&target->primary_datacenter));
res["replica_affinities"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<std::map<datacenter_id_t, int> >, ctx_t>(&target->replica_affinities));
res["name"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<std::string>, ctx_t>(&target->name));
res["shards"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<std::set<typename protocol_t::region_t> >, ctx_t>(&target->shards));
return res;
}
template <class ctx_t, class protocol_t>
cJSON *render_as_json(namespace_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
return render_as_directory(target, ctx);
}
template <class ctx_t, class protocol_t>
void apply_json_to(cJSON *change, namespace_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
apply_as_directory(change, target, ctx);
}
template <class ctx_t, class protocol_t>
void on_subfield_change(namespace_semilattice_metadata_t<protocol_t> *, const ctx_t &) { }
/* This is the metadata for all of the namespaces of a specific protocol. */
template <class protocol_t>
class namespaces_semilattice_metadata_t {
public:
typedef std::map<namespace_id_t, deletable_t<namespace_semilattice_metadata_t<protocol_t> > > namespace_map_t;
namespace_map_t namespaces;
branch_history_t<protocol_t> branch_history;
RDB_MAKE_ME_SERIALIZABLE_2(namespaces, branch_history);
};
template<class protocol_t>
RDB_MAKE_SEMILATTICE_JOINABLE_2(namespaces_semilattice_metadata_t<protocol_t>, namespaces, branch_history);
template<class protocol_t>
RDB_MAKE_EQUALITY_COMPARABLE_2(namespaces_semilattice_metadata_t<protocol_t>, namespaces, branch_history);
//json adapter concept for namespaces_semilattice_metadata_t
template <class ctx_t, class protocol_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
return get_json_subfields(&target->namespaces, ctx);
}
template <class ctx_t, class protocol_t>
cJSON *render_as_json(namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
return render_as_json(&target->namespaces, ctx);
}
template <class ctx_t, class protocol_t>
void apply_json_to(cJSON *change, namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
apply_as_directory(change, &target->namespaces, ctx);
}
template <class ctx_t, class protocol_t>
void on_subfield_change(namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
on_subfield_change(&target->namespaces, ctx);
}
template <class protocol_t>
class namespaces_directory_metadata_t {
public:
std::map<namespace_id_t, directory_echo_wrapper_t<reactor_business_card_t<protocol_t> > > reactor_bcards;
std::map<namespace_id_t, std::map<master_id_t, master_business_card_t<protocol_t> > > master_maps;
RDB_MAKE_ME_SERIALIZABLE_2(reactor_bcards, master_maps);
};
struct namespace_metadata_ctx_t {
boost::uuids::uuid us;
explicit namespace_metadata_ctx_t(boost::uuids::uuid _us)
: us(_us)
{ }
};
#endif /* __CLUSTERING_ARCHITECT_METADATA_HPP__ */
<commit_msg>fixing namespace name syncing across the cluster<commit_after>#ifndef __CLUSTERING_ADMINISTRATION_NAMESPACE_METADATA_HPP__
#define __CLUSTERING_ADMINISTRATION_NAMESPACE_METADATA_HPP__
#include <map>
#include "utils.hpp"
#include <boost/uuid/uuid.hpp>
#include <boost/bind.hpp>
#include "clustering/administration/datacenter_metadata.hpp"
#include "clustering/administration/json_adapters.hpp"
#include "clustering/administration/persistable_blueprint.hpp"
#include "clustering/immediate_consistency/branch/metadata.hpp"
#include "clustering/immediate_consistency/query/metadata.hpp"
#include "clustering/reactor/blueprint.hpp"
#include "clustering/reactor/directory_echo.hpp"
#include "clustering/reactor/metadata.hpp"
#include "http/json/json_adapter.hpp"
#include "rpc/semilattice/joins/deletable.hpp"
#include "rpc/semilattice/joins/macros.hpp"
#include "rpc/semilattice/joins/vclock.hpp"
#include "rpc/serialize_macros.hpp"
typedef boost::uuids::uuid namespace_id_t;
/* This is the metadata for a single namespace of a specific protocol. */
template<class protocol_t>
class namespace_semilattice_metadata_t {
public:
vclock_t<persistable_blueprint_t<protocol_t> > blueprint;
vclock_t<datacenter_id_t> primary_datacenter;
vclock_t<std::map<datacenter_id_t, int> > replica_affinities;
vclock_t<std::set<typename protocol_t::region_t> > shards;
vclock_t<std::string> name;
RDB_MAKE_ME_SERIALIZABLE_5(blueprint, primary_datacenter, replica_affinities, shards, name);
};
template<class protocol_t>
RDB_MAKE_SEMILATTICE_JOINABLE_5(namespace_semilattice_metadata_t<protocol_t>, blueprint, primary_datacenter, replica_affinities, shards, name);
template<class protocol_t>
RDB_MAKE_EQUALITY_COMPARABLE_5(namespace_semilattice_metadata_t<protocol_t>, blueprint, primary_datacenter, replica_affinities, shards, name);
//json adapter concept for namespace_semilattice_metadata_t
template <class ctx_t, class protocol_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(namespace_semilattice_metadata_t<protocol_t> *target, const ctx_t &) {
typename json_adapter_if_t<ctx_t>::json_adapter_map_t res;
res["blueprint"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<persistable_blueprint_t<protocol_t> >, ctx_t>(&target->blueprint));
res["primary_uuid"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<datacenter_id_t>, ctx_t>(&target->primary_datacenter));
res["replica_affinities"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<std::map<datacenter_id_t, int> >, ctx_t>(&target->replica_affinities));
res["name"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<std::string>, ctx_t>(&target->name));
res["shards"] = boost::shared_ptr<json_adapter_if_t<ctx_t> >(new json_adapter_t<vclock_t<std::set<typename protocol_t::region_t> >, ctx_t>(&target->shards));
return res;
}
template <class ctx_t, class protocol_t>
cJSON *render_as_json(namespace_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
return render_as_directory(target, ctx);
}
template <class ctx_t, class protocol_t>
void apply_json_to(cJSON *change, namespace_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
apply_as_directory(change, target, ctx);
}
template <class ctx_t, class protocol_t>
void on_subfield_change(namespace_semilattice_metadata_t<protocol_t> *, const ctx_t &) { }
/* This is the metadata for all of the namespaces of a specific protocol. */
template <class protocol_t>
class namespaces_semilattice_metadata_t {
public:
typedef std::map<namespace_id_t, deletable_t<namespace_semilattice_metadata_t<protocol_t> > > namespace_map_t;
namespace_map_t namespaces;
branch_history_t<protocol_t> branch_history;
RDB_MAKE_ME_SERIALIZABLE_2(namespaces, branch_history);
};
template<class protocol_t>
RDB_MAKE_SEMILATTICE_JOINABLE_2(namespaces_semilattice_metadata_t<protocol_t>, namespaces, branch_history);
template<class protocol_t>
RDB_MAKE_EQUALITY_COMPARABLE_2(namespaces_semilattice_metadata_t<protocol_t>, namespaces, branch_history);
//json adapter concept for namespaces_semilattice_metadata_t
template <class ctx_t, class protocol_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
return get_json_subfields(&target->namespaces, ctx);
}
template <class ctx_t, class protocol_t>
cJSON *render_as_json(namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
return render_as_json(&target->namespaces, ctx);
}
template <class ctx_t, class protocol_t>
void apply_json_to(cJSON *change, namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
apply_as_directory(change, &target->namespaces, ctx);
}
template <class ctx_t, class protocol_t>
void on_subfield_change(namespaces_semilattice_metadata_t<protocol_t> *target, const ctx_t &ctx) {
on_subfield_change(&target->namespaces, ctx);
}
template <class protocol_t>
class namespaces_directory_metadata_t {
public:
std::map<namespace_id_t, directory_echo_wrapper_t<reactor_business_card_t<protocol_t> > > reactor_bcards;
std::map<namespace_id_t, std::map<master_id_t, master_business_card_t<protocol_t> > > master_maps;
RDB_MAKE_ME_SERIALIZABLE_2(reactor_bcards, master_maps);
};
struct namespace_metadata_ctx_t {
boost::uuids::uuid us;
explicit namespace_metadata_ctx_t(boost::uuids::uuid _us)
: us(_us)
{ }
};
#endif /* __CLUSTERING_ARCHITECT_METADATA_HPP__ */
<|endoftext|> |
<commit_before>/*============================================================================*/
/*
Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib.
See the file GNU_GPL_v2.txt for full licensing terms.
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.
*/
/*============================================================================*/
class MidiDevicesImp : public MidiDevices, private Timer, private Thread
{
private:
struct CompareDevices
{
static int compareElements (Device const* const lhs, Device const* const rhs)
{
return lhs->getName ().compare (rhs->getName ());
}
static int compareElements (String const s, Device const* const rhs)
{
return s.compare (rhs->getName ());
}
};
//============================================================================
class InputImp : public Input
{
private:
InputImp& operator= (InputImp const&);
String const m_name;
int m_deviceIndex;
public:
InputImp (String const name, int deviceIndex)
: m_name (name)
, m_deviceIndex (deviceIndex)
{
}
String getName () const
{
return m_name;
}
int getDeviceIndex () const
{
return m_deviceIndex;
}
void setDeviceIndex (int newDeviceIndex)
{
m_deviceIndex = newDeviceIndex;
}
};
//============================================================================
class OutputImp : public Output
{
private:
OutputImp& operator= (OutputImp const&);
String const m_name;
int m_deviceIndex;
public:
OutputImp (String const name, int deviceIndex)
: m_name (name)
, m_deviceIndex (deviceIndex)
{
}
String getName () const
{
return m_name;
}
int getDeviceIndex () const
{
return m_deviceIndex;
}
void setDeviceIndex (int newDeviceIndex)
{
m_deviceIndex = newDeviceIndex;
}
};
private:
//============================================================================
struct State
{
OwnedArray <InputImp> inputs;
OwnedArray <OutputImp> outputs;
};
typedef ConcurrentState <State> StateType;
StateType m_state;
vf::Listeners <Listener> m_listeners;
public:
//============================================================================
MidiDevicesImp () : Thread ("MidiDevices")
{
// This object must be created from the JUCE Message Thread.
//
vfassert (MessageManager::getInstance()->isThisTheMessageThread());
//startTimer (1000);
startThread ();
}
~MidiDevicesImp ()
{
stopThread (-1);
}
void addListener (Listener* listener, CallQueue& thread)
{
m_listeners.add (listener, thread);
}
void removeListener (Listener* listener)
{
m_listeners.remove (listener);
}
private:
//----------------------------------------------------------------------------
void scanInputDevices ()
{
StateType::WriteAccess state (m_state);
// Make a copy of the currently connected devices.
Array <InputImp*> disconnected;
disconnected.ensureStorageAllocated (state->inputs.size ());
for (int i = 0; i < state->inputs.size (); ++i)
{
InputImp* const device = state->inputs [i];
if (device->getDeviceIndex () != -1)
disconnected.add (device);
}
// Enumerate connected devices.
StringArray const devices (juce::MidiInput::getDevices ());
for (int deviceIndex = 0; deviceIndex < devices.size (); ++deviceIndex)
{
CompareDevices comp;
String const deviceName (devices [deviceIndex]);
// Remove this device from list of disconnected devices.
{
int const index = disconnected.indexOfSorted (comp, deviceName);
if (index != -1)
disconnected.remove (index);
}
// Find this device in our list.
int const index = state->inputs.indexOfSorted (comp, deviceName);
if (index != -1)
{
// Device already exists
InputImp* const device = state->inputs [index];
// Notify listeners with connected status.
if (device->getDeviceIndex () == -1)
{
m_listeners.queue (&Listener::onMidiDevicesStatus, device, true);
Logger::outputDebugString (device->getName () + ": connected");
}
device->setDeviceIndex (deviceIndex);
}
else
{
InputImp* const device = new InputImp (deviceName, deviceIndex);
state->inputs.addSorted (comp, device);
}
}
// Notify listeners with disconnected status.
for (int i = 0; i < disconnected.size (); ++i)
{
InputImp* const device = disconnected [i];
device->setDeviceIndex (-1);
m_listeners.queue (&Listener::onMidiDevicesStatus, device, false);
Logger::outputDebugString (device->getName () + ": disconnected");
}
}
//----------------------------------------------------------------------------
void scanOutputDevices ()
{
StateType::WriteAccess state (m_state);
StringArray const devices (juce::MidiOutput::getDevices ());
}
//----------------------------------------------------------------------------
void timerCallback ()
{
scanInputDevices ();
scanOutputDevices ();
}
void run ()
{
do
{
wait (1000);
scanInputDevices ();
scanOutputDevices ();
}
while (!threadShouldExit ());
}
};
//==============================================================================
MidiDevices* MidiDevices::createInstance ()
{
return new MidiDevicesImp;
}
<commit_msg>Comment out MidiDevices function for changed JUCE api<commit_after>/*============================================================================*/
/*
Copyright (C) 2008 by Vinnie Falco, this file is part of VFLib.
See the file GNU_GPL_v2.txt for full licensing terms.
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.
*/
/*============================================================================*/
class MidiDevicesImp : public MidiDevices, private Timer, private Thread
{
private:
struct CompareDevices
{
static int compareElements (Device const* const lhs, Device const* const rhs)
{
return lhs->getName ().compare (rhs->getName ());
}
static int compareElements (String const s, Device const* const rhs)
{
return s.compare (rhs->getName ());
}
};
//============================================================================
class InputImp : public Input
{
private:
InputImp& operator= (InputImp const&);
String const m_name;
int m_deviceIndex;
public:
InputImp (String const name, int deviceIndex)
: m_name (name)
, m_deviceIndex (deviceIndex)
{
}
String getName () const
{
return m_name;
}
int getDeviceIndex () const
{
return m_deviceIndex;
}
void setDeviceIndex (int newDeviceIndex)
{
m_deviceIndex = newDeviceIndex;
}
};
//============================================================================
class OutputImp : public Output
{
private:
OutputImp& operator= (OutputImp const&);
String const m_name;
int m_deviceIndex;
public:
OutputImp (String const name, int deviceIndex)
: m_name (name)
, m_deviceIndex (deviceIndex)
{
}
String getName () const
{
return m_name;
}
int getDeviceIndex () const
{
return m_deviceIndex;
}
void setDeviceIndex (int newDeviceIndex)
{
m_deviceIndex = newDeviceIndex;
}
};
private:
//============================================================================
struct State
{
OwnedArray <InputImp> inputs;
OwnedArray <OutputImp> outputs;
};
typedef ConcurrentState <State> StateType;
StateType m_state;
vf::Listeners <Listener> m_listeners;
public:
//============================================================================
MidiDevicesImp () : Thread ("MidiDevices")
{
// This object must be created from the JUCE Message Thread.
//
vfassert (MessageManager::getInstance()->isThisTheMessageThread());
//startTimer (1000);
startThread ();
}
~MidiDevicesImp ()
{
stopThread (-1);
}
void addListener (Listener* listener, CallQueue& thread)
{
m_listeners.add (listener, thread);
}
void removeListener (Listener* listener)
{
m_listeners.remove (listener);
}
private:
//----------------------------------------------------------------------------
void scanInputDevices ()
{
#if 0
StateType::WriteAccess state (m_state);
// Make a copy of the currently connected devices.
Array <InputImp*> disconnected;
disconnected.ensureStorageAllocated (state->inputs.size ());
for (int i = 0; i < state->inputs.size (); ++i)
{
InputImp* const device = state->inputs [i];
if (device->getDeviceIndex () != -1)
disconnected.add (device);
}
// Enumerate connected devices.
StringArray const devices (juce::MidiInput::getDevices ());
for (int deviceIndex = 0; deviceIndex < devices.size (); ++deviceIndex)
{
CompareDevices comp;
String const deviceName (devices [deviceIndex]);
// Remove this device from list of disconnected devices.
{
int const index = disconnected.indexOfSorted (comp, deviceName);
if (index != -1)
disconnected.remove (index);
}
// Find this device in our list.
int const index = state->inputs.indexOfSorted (comp, deviceName);
if (index != -1)
{
// Device already exists
InputImp* const device = state->inputs [index];
// Notify listeners with connected status.
if (device->getDeviceIndex () == -1)
{
m_listeners.queue (&Listener::onMidiDevicesStatus, device, true);
Logger::outputDebugString (device->getName () + ": connected");
}
device->setDeviceIndex (deviceIndex);
}
else
{
InputImp* const device = new InputImp (deviceName, deviceIndex);
state->inputs.addSorted (comp, device);
}
}
// Notify listeners with disconnected status.
for (int i = 0; i < disconnected.size (); ++i)
{
InputImp* const device = disconnected [i];
device->setDeviceIndex (-1);
m_listeners.queue (&Listener::onMidiDevicesStatus, device, false);
Logger::outputDebugString (device->getName () + ": disconnected");
}
#else
jassertfalse;
#endif
}
//----------------------------------------------------------------------------
void scanOutputDevices ()
{
StateType::WriteAccess state (m_state);
StringArray const devices (juce::MidiOutput::getDevices ());
}
//----------------------------------------------------------------------------
void timerCallback ()
{
scanInputDevices ();
scanOutputDevices ();
}
void run ()
{
do
{
wait (1000);
scanInputDevices ();
scanOutputDevices ();
}
while (!threadShouldExit ());
}
};
//==============================================================================
MidiDevices* MidiDevices::createInstance ()
{
return new MidiDevicesImp;
}
<|endoftext|> |
<commit_before>/************************************************************************
filename: CEGUIRenderer.cpp
created: 20/2/2004
author: Paul D Turner
purpose: Some base class implementation for Renderer objects
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net)
Copyright (C)2004 Paul D Turner ([email protected])
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include "CEGUIRenderer.h"
#include "CEGUIEventSet.h"
#include "CEGUIEvent.h"
#include "CEGUIDefaultResourceProvider.h"
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Event name constants (static data definitions)
*************************************************************************/
const utf8 Renderer::EventDisplaySizeChanged[] = "DisplayModeChanged";
/*************************************************************************
Implementation constants
*************************************************************************/
const float Renderer::GuiZInitialValue = 1.0f;
const float Renderer::GuiZElementStep = 0.001f; // this is enough for 1000 Windows.
const float Renderer::GuiZLayerStep = 0.0001f; // provides space for 10 layers per Window.
/*************************************************************************
Constructor
*************************************************************************/
Renderer::Renderer(void)
{
// setup standard events available
addEvent(EventDisplaySizeChanged);
// default initialisation
resetZValue();
}
/*************************************************************************
Destructor
*************************************************************************/
Renderer::~Renderer(void)
{
if(d_resourceProvider)
{
delete d_resourceProvider;
d_resourceProvider = 0;
}
}
ResourceProvider* Renderer::createResourceProvider(void)
{
d_resourceProvider = new DefaultResourceProvider();
return d_resourceProvider;
}
} // End of CEGUI namespace section
<commit_msg>Initialise d_resourceProvider.<commit_after>/************************************************************************
filename: CEGUIRenderer.cpp
created: 20/2/2004
author: Paul D Turner
purpose: Some base class implementation for Renderer objects
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net)
Copyright (C)2004 Paul D Turner ([email protected])
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include "CEGUIRenderer.h"
#include "CEGUIEventSet.h"
#include "CEGUIEvent.h"
#include "CEGUIDefaultResourceProvider.h"
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Event name constants (static data definitions)
*************************************************************************/
const utf8 Renderer::EventDisplaySizeChanged[] = "DisplayModeChanged";
/*************************************************************************
Implementation constants
*************************************************************************/
const float Renderer::GuiZInitialValue = 1.0f;
const float Renderer::GuiZElementStep = 0.001f; // this is enough for 1000 Windows.
const float Renderer::GuiZLayerStep = 0.0001f; // provides space for 10 layers per Window.
/*************************************************************************
Constructor
*************************************************************************/
Renderer::Renderer(void)
: d_resourceProvider(0)
{
// setup standard events available
addEvent(EventDisplaySizeChanged);
// default initialisation
resetZValue();
}
/*************************************************************************
Destructor
*************************************************************************/
Renderer::~Renderer(void)
{
if(d_resourceProvider)
{
delete d_resourceProvider;
d_resourceProvider = 0;
}
}
ResourceProvider* Renderer::createResourceProvider(void)
{
d_resourceProvider = new DefaultResourceProvider();
return d_resourceProvider;
}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
static void help()
{
cout << "\nThis program demonstrates circle finding with the Hough transform.\n"
"Usage:\n"
"./houghcircles <image_name>, Default is pic1.png\n" << endl;
}
int main(int argc, char** argv)
{
const char* filename = argc >= 2 ? argv[1] : "board.jpg";
Mat img = imread(filename, 0);
if(img.empty())
{
help();
cout << "can not open " << filename << endl;
return -1;
}
Mat cimg;
medianBlur(img, img, 5);
cvtColor(img, cimg, COLOR_GRAY2BGR);
vector<Vec3f> circles;
HoughCircles(img, circles, CV_HOUGH_GRADIENT, 1, 10,
100, 30, 1, 30 // change the last two parameters
// (min_radius & max_radius) to detect larger circles
);
for( size_t i = 0; i < circles.size(); i++ )
{
Vec3i c = circles[i];
circle( cimg, Point(c[0], c[1]), c[2], Scalar(0,0,255), 3, CV_AA);
circle( cimg, Point(c[0], c[1]), 2, Scalar(0,255,0), 3, CV_AA);
}
imshow("detected circles", cimg);
waitKey();
return 0;
}
<commit_msg>filename correction from #3217<commit_after>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
using namespace cv;
using namespace std;
static void help()
{
cout << "\nThis program demonstrates circle finding with the Hough transform.\n"
"Usage:\n"
"./houghcircles <image_name>, Default is board.jpg\n" << endl;
}
int main(int argc, char** argv)
{
const char* filename = argc >= 2 ? argv[1] : "board.jpg";
Mat img = imread(filename, 0);
if(img.empty())
{
help();
cout << "can not open " << filename << endl;
return -1;
}
Mat cimg;
medianBlur(img, img, 5);
cvtColor(img, cimg, COLOR_GRAY2BGR);
vector<Vec3f> circles;
HoughCircles(img, circles, CV_HOUGH_GRADIENT, 1, 10,
100, 30, 1, 30 // change the last two parameters
// (min_radius & max_radius) to detect larger circles
);
for( size_t i = 0; i < circles.size(); i++ )
{
Vec3i c = circles[i];
circle( cimg, Point(c[0], c[1]), c[2], Scalar(0,0,255), 3, CV_AA);
circle( cimg, Point(c[0], c[1]), 2, Scalar(0,255,0), 3, CV_AA);
}
imshow("detected circles", cimg);
waitKey();
return 0;
}
<|endoftext|> |
<commit_before>#include "common/lazyworld.h"
#include <cstdio>
void LazyWorld::DoStep() {
// Collision check against player
}
void LazyWorld::CheckCollision(Entity *entity) {
PositionedBlock *block;
for (std::list<PositionedBlock*>::iterator it = VisibleBlocks.begin(); it != VisibleBlocks.end(); ++it) {
block = *it;
if (block->block->Type == 0) continue;
if (entity->Pos.X + entity->Hitbox.X >= block->pos.X && entity->Pos.X <= block->pos.X + 1
&& entity->Pos.Y + entity->Hitbox.Y >= block->pos.Y && entity->Pos.Y <= block->pos.Y + 1
&& entity->Pos.Z + entity->Hitbox.Z >= block->pos.Z && entity->Pos.Z <= block->pos.Z + 1)
entity->Collide(*block);
}
}
PositionedBlock *LazyWorld::CheckAim(Player *player) {
PositionedBlock *block;
Ray ray = Ray(player);
PositionedBlock *target = NULL;
float dist, best = 5.f;
for (std::list<PositionedBlock*>::iterator it = VisibleBlocks.begin(); it != VisibleBlocks.end(); ++it) {
block = *it; // Blocks[i];
dist = ray.CheckCollision(block);
if (0.f < dist && dist < best) {
best = dist;
target = block;
}
}
if (target != NULL)
target->marked = true;
return target;
}
void LazyWorld::DestroyTarget(Player *player) {
PositionedBlock *block = CheckAim(player);
if (!block) return;
VisibleBlocks.remove(block);
Vector3 chunkindex, pos;
chunkindex.X = floor(block->pos.X / ChunkSize);
chunkindex.Y = floor(block->pos.Y / ChunkSize);
chunkindex.Z = floor(block->pos.Z / ChunkSize);
pos = block->pos - (chunkindex * 16);
std::map<Vector3, Block*> chunk = LoadedChunks[chunkindex];
Block *blk;
if (pos.X > 0 && chunk[pos - Vector3(1, 0, 0)]->Type > 0) {
blk = chunk[pos - Vector3(1, 0, 0)];
if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos - Vector3(1, 0, 0), 1));
blk->faces |= 0x08;
}
if (pos.Y > 0 && chunk[pos - Vector3(0, 1, 0)]->Type > 0) {
blk = chunk[pos - Vector3(0, 1, 0)];
if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos - Vector3(0, 1, 0), 1));
blk->faces |= 0x10;
}
if (pos.Z > 0 && chunk[pos - Vector3(0, 0, 1)]->Type > 0) {
blk = chunk[pos - Vector3(0, 0, 1)];
if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos - Vector3(0, 0, 1), 1));
blk->faces |= 0x20;
}
if (pos.X < 15 && chunk[pos + Vector3(1, 0, 0)]->Type > 0) {
blk = chunk[pos + Vector3(1, 0, 0)];
if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos + Vector3(1, 0, 0), 1));
blk->faces |= 0x01;
}
if (pos.Y < 15 && chunk[pos + Vector3(0, 1, 0)]->Type > 0) {
blk = chunk[pos + Vector3(0, 1, 0)];
if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos + Vector3(0, 1, 0), 1));
blk->faces |= 0x02;
}
if (pos.Z < 15 && chunk[pos + Vector3(0, 0, 1)]->Type > 0) {
blk = chunk[pos + Vector3(0, 0, 1)];
if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos + Vector3(0, 0, 1), 1));
blk->faces |= 0x04;
}
}
bool contains(std::vector<Vector3> vector, Vector3 value) {
for (int i = 0; i < vector.size(); i++)
if (vector[i] == value) return true;
return false;
}
void LazyWorld::LoadChunk(sf::Packet Packet) {
int BlockCount;
Vector3 ChunkIndex; // TODO: remove from request list, add to loaded list
Packet >> ChunkIndex >> BlockCount;
std::map<Vector3, Block*> chunk;
sf::Uint8 type;
Block *block;
Vector3 Pos;
float SideLength;
printf("0 (%f, %f, %f)\n", ChunkIndex.X, ChunkIndex.Y, ChunkIndex.Z);
for (int i = 0; i < BlockCount; i++) {
Packet >> type >> Pos;
if (type == 3)
block = new GrassBlock();
else
block = new AirBlock();
chunk[Vector3(Pos)] = block;
}
for (std::map<Vector3, Block*>::iterator it = chunk.begin(); it != chunk.end(); ++it) {
if (it->second->Type == 0) continue;
Pos = it->first;
char sides = 0x3F;
if (Pos.X > 0 && chunk[Pos - Vector3(1, 0, 0)]->Type > 0)
sides &= (0xFE); // 0b00000001
if (Pos.Y > 0 && chunk[Pos - Vector3(0, 1, 0)]->Type > 0)
sides &= (0xFD); // 0b00000010
if (Pos.Z > 0 && chunk[Pos - Vector3(0, 0, 1)]->Type > 0)
sides &= (0xFB); // 0b00000100
if (Pos.X < 15 && chunk[Pos + Vector3(1, 0, 0)]->Type > 0)
sides &= (0xF7); // 0b00001000
if (Pos.Y < 15 && chunk[Pos + Vector3(0, 1, 0)]->Type > 0)
sides &= (0xEF); // 0b00010000
if (Pos.Z < 15 && chunk[Pos + Vector3(0, 0, 1)]->Type > 0)
sides &= (0xDF); // 0b00100000
it->second->faces = sides;
if (sides > 0)
VisibleBlocks.push_back(new PositionedBlock(it->second, (ChunkIndex * 16) + Pos, 1));
}
LoadedChunks[ChunkIndex] = chunk;
}
void LazyWorld::HandleRequests(Vector3 Pos) {
Vector3 CurrentChunk;
CurrentChunk.X = floor(Pos.X / ChunkSize);
CurrentChunk.Y = floor(Pos.Y / ChunkSize);
CurrentChunk.Z = floor(Pos.Z / ChunkSize);
RequestChunk(CurrentChunk);
RequestChunk(CurrentChunk + Vector3(-1, 0, 0));
RequestChunk(CurrentChunk + Vector3(-1, -1, 0));
RequestChunk(CurrentChunk + Vector3(0, -1, 0));
RequestChunk(CurrentChunk + Vector3(1, -1, 0));
RequestChunk(CurrentChunk + Vector3(1, 0, 0));
RequestChunk(CurrentChunk + Vector3(1, 1, 0));
RequestChunk(CurrentChunk + Vector3(0, 1, 0));
RequestChunk(CurrentChunk + Vector3(-1, 1, 0));
}
void LazyWorld::RequestChunk(Vector3 ChunkIndex) {
if (contains(RequestedChunks, ChunkIndex)) return;
// Send request to the server
sf::Packet Packet;
Packet << (sf::Uint8) 4 << ChunkIndex;
Socket.Send(Packet);
RequestedChunks.push_back(ChunkIndex);
}
<commit_msg>Hey look, more debug code<commit_after>#include "common/lazyworld.h"
#include <cstdio>
void LazyWorld::DoStep() {
// Collision check against player
}
void LazyWorld::CheckCollision(Entity *entity) {
PositionedBlock *block;
for (std::list<PositionedBlock*>::iterator it = VisibleBlocks.begin(); it != VisibleBlocks.end(); ++it) {
block = *it;
if (block->block->Type == 0) continue;
if (entity->Pos.X + entity->Hitbox.X >= block->pos.X && entity->Pos.X <= block->pos.X + 1
&& entity->Pos.Y + entity->Hitbox.Y >= block->pos.Y && entity->Pos.Y <= block->pos.Y + 1
&& entity->Pos.Z + entity->Hitbox.Z >= block->pos.Z && entity->Pos.Z <= block->pos.Z + 1)
entity->Collide(*block);
}
}
PositionedBlock *LazyWorld::CheckAim(Player *player) {
PositionedBlock *block;
Ray ray = Ray(player);
PositionedBlock *target = NULL;
float dist, best = 5.f;
for (std::list<PositionedBlock*>::iterator it = VisibleBlocks.begin(); it != VisibleBlocks.end(); ++it) {
block = *it; // Blocks[i];
dist = ray.CheckCollision(block);
if (0.f < dist && dist < best) {
best = dist;
target = block;
}
}
if (target != NULL)
target->marked = true;
return target;
}
void LazyWorld::DestroyTarget(Player *player) {
PositionedBlock *block = CheckAim(player);
if (!block) return;
VisibleBlocks.remove(block);
Vector3 chunkindex, pos;
chunkindex.X = floor(block->pos.X / ChunkSize);
chunkindex.Y = floor(block->pos.Y / ChunkSize);
chunkindex.Z = floor(block->pos.Z / ChunkSize);
pos = block->pos - (chunkindex * 16);
std::map<Vector3, Block*> chunk = LoadedChunks[chunkindex];
Block *blk;
if (pos.X > 0 && chunk[pos - Vector3(1, 0, 0)]->Type > 0) {
blk = chunk[pos - Vector3(1, 0, 0)];
if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos - Vector3(1, 0, 0), 1));
blk->faces |= 0x08;
}
if (pos.Y > 0 && chunk[pos - Vector3(0, 1, 0)]->Type > 0) {
blk = chunk[pos - Vector3(0, 1, 0)];
if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos - Vector3(0, 1, 0), 1));
blk->faces |= 0x10;
}
if (pos.Z > 0 && chunk[pos - Vector3(0, 0, 1)]->Type > 0) {
blk = chunk[pos - Vector3(0, 0, 1)];
if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos - Vector3(0, 0, 1), 1));
blk->faces |= 0x20;
}
if (pos.X < 15 && chunk[pos + Vector3(1, 0, 0)]->Type > 0) {
blk = chunk[pos + Vector3(1, 0, 0)];
if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos + Vector3(1, 0, 0), 1));
blk->faces |= 0x01;
}
if (pos.Y < 15 && chunk[pos + Vector3(0, 1, 0)]->Type > 0) {
blk = chunk[pos + Vector3(0, 1, 0)];
if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos + Vector3(0, 1, 0), 1));
blk->faces |= 0x02;
}
if (pos.Z < 15 && chunk[pos + Vector3(0, 0, 1)]->Type > 0) {
blk = chunk[pos + Vector3(0, 0, 1)];
if (blk->faces == 0) VisibleBlocks.push_back(new PositionedBlock(blk, block->pos + Vector3(0, 0, 1), 1));
blk->faces |= 0x04;
}
}
bool contains(std::vector<Vector3> vector, Vector3 value) {
for (int i = 0; i < vector.size(); i++)
if (vector[i] == value) return true;
return false;
}
void LazyWorld::LoadChunk(sf::Packet Packet) {
int BlockCount;
Vector3 ChunkIndex; // TODO: remove from request list, add to loaded list
Packet >> ChunkIndex >> BlockCount;
std::map<Vector3, Block*> chunk;
sf::Uint8 type;
Block *block;
Vector3 Pos;
float SideLength;
for (int i = 0; i < BlockCount; i++) {
Packet >> type >> Pos;
if (type == 3)
block = new GrassBlock();
else
block = new AirBlock();
chunk[Vector3(Pos)] = block;
}
for (std::map<Vector3, Block*>::iterator it = chunk.begin(); it != chunk.end(); ++it) {
if (it->second->Type == 0) continue;
Pos = it->first;
char sides = 0x3F;
if (Pos.X > 0 && chunk[Pos - Vector3(1, 0, 0)]->Type > 0)
sides &= (0xFE); // 0b00000001
if (Pos.Y > 0 && chunk[Pos - Vector3(0, 1, 0)]->Type > 0)
sides &= (0xFD); // 0b00000010
if (Pos.Z > 0 && chunk[Pos - Vector3(0, 0, 1)]->Type > 0)
sides &= (0xFB); // 0b00000100
if (Pos.X < 15 && chunk[Pos + Vector3(1, 0, 0)]->Type > 0)
sides &= (0xF7); // 0b00001000
if (Pos.Y < 15 && chunk[Pos + Vector3(0, 1, 0)]->Type > 0)
sides &= (0xEF); // 0b00010000
if (Pos.Z < 15 && chunk[Pos + Vector3(0, 0, 1)]->Type > 0)
sides &= (0xDF); // 0b00100000
it->second->faces = sides;
if (sides > 0)
VisibleBlocks.push_back(new PositionedBlock(it->second, (ChunkIndex * 16) + Pos, 1));
}
LoadedChunks[ChunkIndex] = chunk;
}
void LazyWorld::HandleRequests(Vector3 Pos) {
Vector3 CurrentChunk;
CurrentChunk.X = floor(Pos.X / ChunkSize);
CurrentChunk.Y = floor(Pos.Y / ChunkSize);
CurrentChunk.Z = floor(Pos.Z / ChunkSize);
RequestChunk(CurrentChunk);
RequestChunk(CurrentChunk + Vector3(-1, 0, 0));
RequestChunk(CurrentChunk + Vector3(-1, -1, 0));
RequestChunk(CurrentChunk + Vector3(0, -1, 0));
RequestChunk(CurrentChunk + Vector3(1, -1, 0));
RequestChunk(CurrentChunk + Vector3(1, 0, 0));
RequestChunk(CurrentChunk + Vector3(1, 1, 0));
RequestChunk(CurrentChunk + Vector3(0, 1, 0));
RequestChunk(CurrentChunk + Vector3(-1, 1, 0));
}
void LazyWorld::RequestChunk(Vector3 ChunkIndex) {
if (contains(RequestedChunks, ChunkIndex)) return;
// Send request to the server
sf::Packet Packet;
Packet << (sf::Uint8) 4 << ChunkIndex;
Socket.Send(Packet);
RequestedChunks.push_back(ChunkIndex);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <outputtype.h>
#include <pubkey.h>
#include <script/script.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <util/vector.h>
#include <assert.h>
#include <string>
static const std::string OUTPUT_TYPE_STRING_LEGACY = "legacy";
static const std::string OUTPUT_TYPE_STRING_P2SH_SEGWIT = "p2sh-segwit";
static const std::string OUTPUT_TYPE_STRING_BECH32 = "bech32";
const std::array<OutputType, 3> OUTPUT_TYPES = {OutputType::LEGACY, OutputType::P2SH_SEGWIT, OutputType::BECH32};
bool ParseOutputType(const std::string& type, OutputType& output_type)
{
if (type == OUTPUT_TYPE_STRING_LEGACY) {
output_type = OutputType::LEGACY;
return true;
} else if (type == OUTPUT_TYPE_STRING_P2SH_SEGWIT) {
output_type = OutputType::P2SH_SEGWIT;
return true;
} else if (type == OUTPUT_TYPE_STRING_BECH32) {
output_type = OutputType::BECH32;
return true;
}
return false;
}
const std::string& FormatOutputType(OutputType type)
{
switch (type) {
case OutputType::LEGACY: return OUTPUT_TYPE_STRING_LEGACY;
case OutputType::P2SH_SEGWIT: return OUTPUT_TYPE_STRING_P2SH_SEGWIT;
case OutputType::BECH32: return OUTPUT_TYPE_STRING_BECH32;
default: assert(false);
}
}
CTxDestination GetDestinationForKey(const CPubKey& key, OutputType type)
{
switch (type) {
case OutputType::LEGACY: return PKHash(key);
case OutputType::P2SH_SEGWIT:
case OutputType::BECH32: {
if (!key.IsCompressed()) return PKHash(key);
CTxDestination witdest = WitnessV0KeyHash(PKHash(key));
CScript witprog = GetScriptForDestination(witdest);
if (type == OutputType::P2SH_SEGWIT) {
return ScriptHash(witprog);
} else {
return witdest;
}
}
default: assert(false);
}
}
std::vector<CTxDestination> GetAllDestinationsForKey(const CPubKey& key)
{
PKHash keyid(key);
CTxDestination p2pkh{keyid};
if (key.IsCompressed()) {
CTxDestination segwit = WitnessV0KeyHash(keyid);
CTxDestination p2sh = ScriptHash(GetScriptForDestination(segwit));
return Vector(std::move(p2pkh), std::move(p2sh), std::move(segwit));
} else {
return Vector(std::move(p2pkh));
}
}
CTxDestination AddAndGetDestinationForScript(FillableSigningProvider& keystore, const CScript& script, OutputType type)
{
// Add script to keystore
keystore.AddCScript(script);
ScriptHash sh(script);
// Note that scripts over 520 bytes are not yet supported.
switch (type) {
case OutputType::LEGACY:
keystore.AddCScript(GetScriptForDestination(sh));
return sh;
case OutputType::P2SH_SEGWIT:
case OutputType::BECH32: {
CTxDestination witdest = WitnessV0ScriptHash(script);
CScript witprog = GetScriptForDestination(witdest);
// Check if the resulting program is solvable (i.e. doesn't use an uncompressed key)
if (!IsSolvable(keystore, witprog)) {
// Since the wsh is invalid, add and return the sh instead.
keystore.AddCScript(GetScriptForDestination(sh));
return sh;
}
// Add the redeemscript, so that P2WSH and P2SH-P2WSH outputs are recognized as ours.
keystore.AddCScript(witprog);
if (type == OutputType::BECH32) {
return witdest;
} else {
ScriptHash sh_w = ScriptHash(witprog);
keystore.AddCScript(GetScriptForDestination(sh_w));
return sh_w;
}
}
default: assert(false);
}
}
<commit_msg>Revert "Store p2sh scripts in AddAndGetDestinationForScript"<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <outputtype.h>
#include <pubkey.h>
#include <script/script.h>
#include <script/sign.h>
#include <script/signingprovider.h>
#include <script/standard.h>
#include <util/vector.h>
#include <assert.h>
#include <string>
static const std::string OUTPUT_TYPE_STRING_LEGACY = "legacy";
static const std::string OUTPUT_TYPE_STRING_P2SH_SEGWIT = "p2sh-segwit";
static const std::string OUTPUT_TYPE_STRING_BECH32 = "bech32";
const std::array<OutputType, 3> OUTPUT_TYPES = {OutputType::LEGACY, OutputType::P2SH_SEGWIT, OutputType::BECH32};
bool ParseOutputType(const std::string& type, OutputType& output_type)
{
if (type == OUTPUT_TYPE_STRING_LEGACY) {
output_type = OutputType::LEGACY;
return true;
} else if (type == OUTPUT_TYPE_STRING_P2SH_SEGWIT) {
output_type = OutputType::P2SH_SEGWIT;
return true;
} else if (type == OUTPUT_TYPE_STRING_BECH32) {
output_type = OutputType::BECH32;
return true;
}
return false;
}
const std::string& FormatOutputType(OutputType type)
{
switch (type) {
case OutputType::LEGACY: return OUTPUT_TYPE_STRING_LEGACY;
case OutputType::P2SH_SEGWIT: return OUTPUT_TYPE_STRING_P2SH_SEGWIT;
case OutputType::BECH32: return OUTPUT_TYPE_STRING_BECH32;
default: assert(false);
}
}
CTxDestination GetDestinationForKey(const CPubKey& key, OutputType type)
{
switch (type) {
case OutputType::LEGACY: return PKHash(key);
case OutputType::P2SH_SEGWIT:
case OutputType::BECH32: {
if (!key.IsCompressed()) return PKHash(key);
CTxDestination witdest = WitnessV0KeyHash(PKHash(key));
CScript witprog = GetScriptForDestination(witdest);
if (type == OutputType::P2SH_SEGWIT) {
return ScriptHash(witprog);
} else {
return witdest;
}
}
default: assert(false);
}
}
std::vector<CTxDestination> GetAllDestinationsForKey(const CPubKey& key)
{
PKHash keyid(key);
CTxDestination p2pkh{keyid};
if (key.IsCompressed()) {
CTxDestination segwit = WitnessV0KeyHash(keyid);
CTxDestination p2sh = ScriptHash(GetScriptForDestination(segwit));
return Vector(std::move(p2pkh), std::move(p2sh), std::move(segwit));
} else {
return Vector(std::move(p2pkh));
}
}
CTxDestination AddAndGetDestinationForScript(FillableSigningProvider& keystore, const CScript& script, OutputType type)
{
// Add script to keystore
keystore.AddCScript(script);
// Note that scripts over 520 bytes are not yet supported.
switch (type) {
case OutputType::LEGACY:
return ScriptHash(script);
case OutputType::P2SH_SEGWIT:
case OutputType::BECH32: {
CTxDestination witdest = WitnessV0ScriptHash(script);
CScript witprog = GetScriptForDestination(witdest);
// Check if the resulting program is solvable (i.e. doesn't use an uncompressed key)
if (!IsSolvable(keystore, witprog)) return ScriptHash(script);
// Add the redeemscript, so that P2WSH and P2SH-P2WSH outputs are recognized as ours.
keystore.AddCScript(witprog);
if (type == OutputType::BECH32) {
return witdest;
} else {
return ScriptHash(witprog);
}
}
default: assert(false);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// Tests for the UdpSocketManager interface.
// Note: This tests UdpSocketManager together with UdpSocketWrapper,
// due to the way the code is full of static-casts to the platform dependent
// subtypes.
// It also uses the static UdpSocketManager object.
// The most important property of these tests is that they do not leak memory.
#include "udp_socket_wrapper.h"
#include "udp_socket_manager_wrapper.h"
#include "gtest/gtest.h"
TEST(UdpSocketManager, CreateCallsInitAndDoesNotLeakMemory) {
WebRtc_Word32 id = 42;
WebRtc_UWord8 threads = 1;
webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
// Create is supposed to have called init on the object.
EXPECT_EQ(false, mgr->Init(id, threads))
<< "Init should return false since Create is supposed to call it.";
webrtc::UdpSocketManager::Return();
}
// Creates a socket and adds it to the socket manager, and then removes it
// before destroying the socket manager.
TEST(UdpSocketManager, AddAndRemoveSocketDoesNotLeakMemory) {
WebRtc_Word32 id = 42;
WebRtc_UWord8 threads = 1;
webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
webrtc::UdpSocketWrapper* socket
= webrtc::UdpSocketWrapper::CreateSocket(id,
mgr,
NULL, // CallbackObj
NULL, // IncomingSocketCallback
false, // ipV6Enable
false); // disableGQOS
// The constructor will do AddSocket on the manager.
EXPECT_EQ(true, mgr->RemoveSocket(socket));
webrtc::UdpSocketManager::Return();
}
// Creates a socket and add it to the socket manager, but does not remove it
// before destroying the socket manager.
// This should also destroy the socket.
TEST(UdpSocketManager, UnremovedSocketsGetCollectedAtManagerDeletion) {
WebRtc_Word32 id = 42;
WebRtc_UWord8 threads = 1;
webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
webrtc::UdpSocketWrapper* unused_socket
= webrtc::UdpSocketWrapper::CreateSocket(id,
mgr,
NULL, // CallbackObj
NULL, // IncomingSocketCallback
false, // ipV6Enable
false); // disableGQOS
// The constructor will do AddSocket on the manager.
unused_socket = NULL;
webrtc::UdpSocketManager::Return();
}
<commit_msg>Disabled UnremovedSocketsGetCollectedAtManagerDeletion in UdpSocketManager unittest.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// Tests for the UdpSocketManager interface.
// Note: This tests UdpSocketManager together with UdpSocketWrapper,
// due to the way the code is full of static-casts to the platform dependent
// subtypes.
// It also uses the static UdpSocketManager object.
// The most important property of these tests is that they do not leak memory.
#include "udp_socket_wrapper.h"
#include "udp_socket_manager_wrapper.h"
#include "gtest/gtest.h"
TEST(UdpSocketManager, CreateCallsInitAndDoesNotLeakMemory) {
WebRtc_Word32 id = 42;
WebRtc_UWord8 threads = 1;
webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
// Create is supposed to have called init on the object.
EXPECT_EQ(false, mgr->Init(id, threads))
<< "Init should return false since Create is supposed to call it.";
webrtc::UdpSocketManager::Return();
}
// Creates a socket and adds it to the socket manager, and then removes it
// before destroying the socket manager.
TEST(UdpSocketManager, AddAndRemoveSocketDoesNotLeakMemory) {
WebRtc_Word32 id = 42;
WebRtc_UWord8 threads = 1;
webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
webrtc::UdpSocketWrapper* socket
= webrtc::UdpSocketWrapper::CreateSocket(id,
mgr,
NULL, // CallbackObj
NULL, // IncomingSocketCallback
false, // ipV6Enable
false); // disableGQOS
// The constructor will do AddSocket on the manager.
EXPECT_EQ(true, mgr->RemoveSocket(socket));
webrtc::UdpSocketManager::Return();
}
// Creates a socket and add it to the socket manager, but does not remove it
// before destroying the socket manager.
// This should also destroy the socket.
TEST(UdpSocketManager, DISABLED_UnremovedSocketsGetCollectedAtManagerDeletion) {
WebRtc_Word32 id = 42;
WebRtc_UWord8 threads = 1;
webrtc::UdpSocketManager* mgr = webrtc::UdpSocketManager::Create(id, threads);
webrtc::UdpSocketWrapper* unused_socket
= webrtc::UdpSocketWrapper::CreateSocket(id,
mgr,
NULL, // CallbackObj
NULL, // IncomingSocketCallback
false, // ipV6Enable
false); // disableGQOS
// The constructor will do AddSocket on the manager.
unused_socket = NULL;
webrtc::UdpSocketManager::Return();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Pierre KRIEGER
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef INCLUDE_LUACONTEXTTHREAD_HPP
#define INCLUDE_LUACONTEXTTHREAD_HPP
#include "LuaContext.hpp"
/**
*
*/
class LuaContextThread {
public:
/**
* Creates a thread in the LuaContext
*/
explicit LuaContextThread(LuaContext* lua) :
mLua(lua),
mThread(lua->createThread())
{
}
/**
* Destroys the thread
*/
~LuaContextThread()
{
mLua->destroyThread(mThread);
}
/**
*
*/
void forkGlobals() const
{
mLua->forkGlobals(mThread);
}
/**
*
*/
template<typename TType, typename... TTypes>
auto readVariable(TTypes&&... elements) const
-> TType
{
return mLua->readVariable<TType>(mThread, std::forward<TTypes>(elements)...);
}
/**
*
*/
template<typename... TData>
void writeVariable(TData&&... data) const
{
mLua->writeVariable(mThread, std::forward<TData>(data)...);
}
/**
*
*/
template<typename TFunctionType, typename... TData>
void writeFunction(TData&&... data) const
{
mLua->writeFunction<TFunctionType>(mThread, std::forward<TData>(data)...);
}
/**
*
*/
template<typename... TData>
void writeFunction(TData&&... data) const
{
mLua->writeFunction(mThread, std::forward<TData>(data)...);
}
/**
*
*/
template<typename TType, typename TCode>
auto executeCode(TCode&& code) const
-> decltype(mLua->executeCode<TType>(std::forward<TCode>(code)))
{
return mLua->executeCode<TType>(mThread, std::forward<TCode>(code));
}
/**
*
*/
template<typename TCode>
void executeCode(TCode&& code) const
{
mLua->executeCode(mThread, std::forward<TCode>(code));
}
private:
LuaContext* const mLua;
LuaContext::ThreadID mThread; // TODO: const
};
#endif
<commit_msg>Compilation fix for LuaContextThread::executeCode<commit_after>/*
Copyright (c) 2013, Pierre KRIEGER
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef INCLUDE_LUACONTEXTTHREAD_HPP
#define INCLUDE_LUACONTEXTTHREAD_HPP
#include "LuaContext.hpp"
/**
*
*/
class LuaContextThread {
public:
/**
* Creates a thread in the LuaContext
*/
explicit LuaContextThread(LuaContext* lua) :
mLua(lua),
mThread(lua->createThread())
{
}
/**
* Destroys the thread
*/
~LuaContextThread()
{
mLua->destroyThread(mThread);
}
/**
*
*/
void forkGlobals() const
{
mLua->forkGlobals(mThread);
}
/**
*
*/
template<typename TType, typename... TTypes>
auto readVariable(TTypes&&... elements) const
-> TType
{
return mLua->readVariable<TType>(mThread, std::forward<TTypes>(elements)...);
}
/**
*
*/
template<typename... TData>
void writeVariable(TData&&... data) const
{
mLua->writeVariable(mThread, std::forward<TData>(data)...);
}
/**
*
*/
template<typename TFunctionType, typename... TData>
void writeFunction(TData&&... data) const
{
mLua->writeFunction<TFunctionType>(mThread, std::forward<TData>(data)...);
}
/**
*
*/
template<typename... TData>
void writeFunction(TData&&... data) const
{
mLua->writeFunction(mThread, std::forward<TData>(data)...);
}
/**
*
*/
template<typename TType, typename TCode>
auto executeCode(TCode&& code) const
-> TType
{
return mLua->executeCode<TType>(mThread, std::forward<TCode>(code));
}
/**
*
*/
template<typename TCode>
void executeCode(TCode&& code) const
{
mLua->executeCode(mThread, std::forward<TCode>(code));
}
private:
LuaContext* const mLua;
LuaContext::ThreadID mThread; // TODO: const
};
#endif
<|endoftext|> |
<commit_before>#include "swftStatusWindowWidget.h"
#include "ui_swftStatusWindowWidget.h"
#include <QHeaderView>
#include <QLineEdit>
#include <QStringList>
#include "vtkCommand.h"
#include "vtkEventQtSlotConnect.h"
#include <vtksys/SystemTools.hxx>
#include "vtkPVArrayInformation.h"
#include "vtkPVCompositeDataInformation.h"
#include "vtkPVDataInformation.h"
#include "vtkExecutive.h"
#include "vtkPVDataSetAttributesInformation.h"
#include "vtkSmartPointer.h"
#include "vtkSMDomain.h"
#include "vtkSMDomainIterator.h"
#include "vtkSMDoubleVectorProperty.h"
#include "vtkSMOutputPort.h"
#include "vtkSMPropertyIterator.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSelectionRepresentation.h"
#include "pqActiveObjects.h"
#include "pqNonEditableStyledItemDelegate.h"
#include "pqOutputPort.h"
#include "pqPipelineSource.h"
#include "pqSMAdaptor.h"
#include "pqServer.h"
#include "pqTimeKeeper.h"
#include <QVariant>
class swftStatusWindowWidget::pqUi
: public QObject, public Ui::swftStatusWindowWidget
{
public:
pqUi(QObject* p) : QObject(p) {}
};
swftStatusWindowWidget::swftStatusWindowWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::swftStatusWindowWidget)
{
ui->setupUi(this);
ui->modelNameLabel->setText("... Please Load a Model Run to Start ...");
this->VTKConnect = vtkEventQtSlotConnect::New();
this->updateInformation();
this->connect(&pqActiveObjects::instance(),
SIGNAL (portChanged(pqOutputPort*)),
this,
SLOT(setOutputPort(pqOutputPort*)));
}
swftStatusWindowWidget::~swftStatusWindowWidget()
{
this->VTKConnect->Disconnect();
this->VTKConnect->Delete();
delete ui;
}
pqOutputPort *swftStatusWindowWidget::getOutputPort()
{
return this->OutputPort;
}
void swftStatusWindowWidget::setOutputPort(pqOutputPort *source)
{
if(this->OutputPort == source)
{
return;
}
this->VTKConnect->Disconnect();
if (this->OutputPort)
{
// QObject::disconnect((this->OutputPort->getSource(),
// SIGNAL (dataUdated(pqPipelineSource*)),
// this, SLOT(updateInformation())));
// this->ui->currentFileInfo->setText("N/A");
// this->ui->currentFilePathInfo->setText("N/A");
}
this->OutputPort = source;
if(this->OutputPort)
{
QObject::connect(this->OutputPort->getSource(),
SIGNAL(dataUpdated(pqPipelineSource*)),
this, SLOT(updateInformation()));
}
this->updateInformation();
}
void swftStatusWindowWidget::fillDataInformation(vtkPVDataInformation *info)
{
// std::cout << __FUNCTION__ << " " << __LINE__ << " has been triggered" << std::endl;
}
void swftStatusWindowWidget::updateInformation()
{
// std::cout << "update Information triggered" << std::endl;
vtkPVDataInformation *dataInformation = NULL;
pqPipelineSource * source = NULL;
if(this->OutputPort)
{
source = this->OutputPort->getSource();
if(this->OutputPort->getOutputPortProxy())
{
dataInformation = this->OutputPort->getDataInformation();
}
}
if(!source || !dataInformation)
{
this->fillDataInformation(0);
return;
}
this->fillDataInformation(dataInformation);
//need to get the required information
//find the filename
vtkSmartPointer<vtkSMPropertyIterator> piter;
piter.TakeReference(source->getProxy()->NewPropertyIterator());
for(piter->Begin(); !piter->IsAtEnd(); piter->Next())
{
vtkSMProperty *prop = piter->GetProperty();
if(prop->IsA("vtkSMStringVectorProperty"))
{
vtkSmartPointer<vtkSMDomainIterator> diter;
diter.TakeReference(prop->NewDomainIterator());
for(diter->Begin(); !diter->IsAtEnd(); diter->Next())
{
if(diter->GetDomain()->IsA("vtkSMFileListDomain"))
{
vtkSMProperty* smprop = piter->GetProperty();
if(smprop->GetInformationProperty())
{
smprop = smprop->GetInformationProperty();
source->getProxy()->UpdatePropertyInformation(smprop);
}
QString filename = pqSMAdaptor::getElementProperty(smprop).toString();
QString path = vtksys::SystemTools::GetFilenamePath(filename.toAscii().data()).c_str();
// std::cout << "Path: " << path.toAscii().data() << std::endl;
// std::cout << "filename: " << filename.toAscii().data() << std::endl;
ui->currentFileInfo->setText(vtksys::SystemTools::GetFilenameName(filename.toAscii().data()).c_str());
ui->currentFilePathInfo->setText(path);
}
if(!diter->IsAtEnd())
{
break;
}
}
}
}
vtkPVDataSetAttributesInformation* fieldInfo;
fieldInfo = dataInformation->GetFieldDataInformation();
for(int q=0; q < fieldInfo->GetNumberOfArrays(); q++)
{
vtkPVArrayInformation* arrayInfo;
arrayInfo = fieldInfo->GetArrayInformation(q);
int numComponents = arrayInfo->GetNumberOfComponents();
QString name = arrayInfo->GetName();
QString value;
// std::cout << "Name: " << name.toAscii().data() << std::endl;
for(int j = 0; j < numComponents; j++)
{
//look for the correct values
}
}
}
<commit_msg>vtkSpaceCraftInfo filter: Working on parsing XML. Please note that the way this works will be changing. I am just getting a feel for the xml parser at the moment.<commit_after>#include "swftStatusWindowWidget.h"
#include "ui_swftStatusWindowWidget.h"
#include <QHeaderView>
#include <QLineEdit>
#include <QStringList>
#include "vtkCommand.h"
#include "vtkEventQtSlotConnect.h"
#include <vtksys/SystemTools.hxx>
#include "vtkPVArrayInformation.h"
#include "vtkPVCompositeDataInformation.h"
#include "vtkPVDataInformation.h"
#include "vtkExecutive.h"
#include "vtkPVDataSetAttributesInformation.h"
#include "vtkSmartPointer.h"
#include "vtkSMDomain.h"
#include "vtkSMDomainIterator.h"
#include "vtkSMDoubleVectorProperty.h"
#include "vtkSMOutputPort.h"
#include "vtkSMPropertyIterator.h"
#include "vtkSelection.h"
#include "vtkSelectionNode.h"
#include "vtkSelectionRepresentation.h"
#include "pqActiveObjects.h"
#include "pqNonEditableStyledItemDelegate.h"
#include "pqOutputPort.h"
#include "pqPipelineSource.h"
#include "pqSMAdaptor.h"
#include "pqServer.h"
#include "pqTimeKeeper.h"
#include <QVariant>
class swftStatusWindowWidget::pqUi
: public QObject, public Ui::swftStatusWindowWidget
{
public:
pqUi(QObject* p) : QObject(p) {}
};
swftStatusWindowWidget::swftStatusWindowWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::swftStatusWindowWidget)
{
ui->setupUi(this);
ui->modelNameLabel->setText("Enlil Model Information");
this->VTKConnect = vtkEventQtSlotConnect::New();
this->updateInformation();
this->connect(&pqActiveObjects::instance(),
SIGNAL (portChanged(pqOutputPort*)),
this,
SLOT(setOutputPort(pqOutputPort*)));
}
swftStatusWindowWidget::~swftStatusWindowWidget()
{
this->VTKConnect->Disconnect();
this->VTKConnect->Delete();
delete ui;
}
pqOutputPort *swftStatusWindowWidget::getOutputPort()
{
return this->OutputPort;
}
void swftStatusWindowWidget::setOutputPort(pqOutputPort *source)
{
if(this->OutputPort == source)
{
return;
}
this->VTKConnect->Disconnect();
if (this->OutputPort)
{
// QObject::disconnect((this->OutputPort->getSource(),
// SIGNAL (dataUdated(pqPipelineSource*)),
// this, SLOT(updateInformation())));
// this->ui->currentFileInfo->setText("N/A");
// this->ui->currentFilePathInfo->setText("N/A");
}
this->OutputPort = source;
if(this->OutputPort)
{
QObject::connect(this->OutputPort->getSource(),
SIGNAL(dataUpdated(pqPipelineSource*)),
this, SLOT(updateInformation()));
}
this->updateInformation();
}
void swftStatusWindowWidget::fillDataInformation(vtkPVDataInformation *info)
{
// std::cout << __FUNCTION__ << " " << __LINE__ << " has been triggered" << std::endl;
}
void swftStatusWindowWidget::updateInformation()
{
// std::cout << "update Information triggered" << std::endl;
vtkPVDataInformation *dataInformation = NULL;
pqPipelineSource * source = NULL;
if(this->OutputPort)
{
source = this->OutputPort->getSource();
if(this->OutputPort->getOutputPortProxy())
{
dataInformation = this->OutputPort->getDataInformation();
}
}
if(!source || !dataInformation)
{
this->fillDataInformation(0);
return;
}
this->fillDataInformation(dataInformation);
//need to get the required information
//find the filename
vtkSmartPointer<vtkSMPropertyIterator> piter;
piter.TakeReference(source->getProxy()->NewPropertyIterator());
for(piter->Begin(); !piter->IsAtEnd(); piter->Next())
{
vtkSMProperty *prop = piter->GetProperty();
if(prop->IsA("vtkSMStringVectorProperty"))
{
vtkSmartPointer<vtkSMDomainIterator> diter;
diter.TakeReference(prop->NewDomainIterator());
for(diter->Begin(); !diter->IsAtEnd(); diter->Next())
{
if(diter->GetDomain()->IsA("vtkSMFileListDomain"))
{
vtkSMProperty* smprop = piter->GetProperty();
if(smprop->GetInformationProperty())
{
smprop = smprop->GetInformationProperty();
source->getProxy()->UpdatePropertyInformation(smprop);
}
QString filename = pqSMAdaptor::getElementProperty(smprop).toString();
QString path = vtksys::SystemTools::GetFilenamePath(filename.toAscii().data()).c_str();
// std::cout << "Path: " << path.toAscii().data() << std::endl;
// std::cout << "filename: " << filename.toAscii().data() << std::endl;
ui->currentFileInfo->setText(vtksys::SystemTools::GetFilenameName(filename.toAscii().data()).c_str());
ui->currentFilePathInfo->setText(path);
}
if(!diter->IsAtEnd())
{
break;
}
}
}
}
vtkPVDataSetAttributesInformation* fieldInfo;
fieldInfo = dataInformation->GetFieldDataInformation();
for(int q=0; q < fieldInfo->GetNumberOfArrays(); q++)
{
vtkPVArrayInformation* arrayInfo;
arrayInfo = fieldInfo->GetArrayInformation(q);
int numComponents = arrayInfo->GetNumberOfComponents();
QString name = arrayInfo->GetName();
QString value;
// std::cout << "Name: " << name.toAscii().data() << std::endl;
for(int j = 0; j < numComponents; j++)
{
//look for the correct values
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/scoped_ptr.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/delete_tree_work_item.h"
#include "chrome/installer/util/helper.h"
#include "chrome/installer/util/logging_installer.h"
#include "chrome/installer/util/util_constants.h"
#include "chrome/installer/util/version.h"
#include "chrome/installer/util/work_item_list.h"
namespace {
std::wstring GetChromeInstallBasePath(bool system_install,
const wchar_t* subpath) {
FilePath install_path;
if (system_install) {
PathService::Get(base::DIR_PROGRAM_FILES, &install_path);
} else {
PathService::Get(base::DIR_LOCAL_APP_DATA, &install_path);
}
if (!install_path.empty()) {
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
install_path = install_path.Append(dist->GetInstallSubDir());
install_path = install_path.Append(subpath);
}
return install_path.ToWStringHack();
}
} // namespace
std::wstring installer::GetChromeInstallPath(bool system_install) {
return GetChromeInstallBasePath(system_install,
installer_util::kInstallBinaryDir);
}
std::wstring installer::GetChromeUserDataPath() {
return GetChromeInstallBasePath(false, installer_util::kInstallUserDataDir);
}
bool installer::LaunchChrome(bool system_install) {
std::wstring chrome_exe(L"\"");
chrome_exe.append(installer::GetChromeInstallPath(system_install));
file_util::AppendToPath(&chrome_exe, installer_util::kChromeExe);
chrome_exe.append(L"\"");
return base::LaunchApp(chrome_exe, false, false, NULL);
}
bool installer::LaunchChromeAndWaitForResult(bool system_install,
const std::wstring& options,
int32* exit_code) {
std::wstring chrome_exe(installer::GetChromeInstallPath(system_install));
if (chrome_exe.empty())
return false;
file_util::AppendToPath(&chrome_exe, installer_util::kChromeExe);
std::wstring command_line(L"\"" + chrome_exe + L"\"");
command_line.append(options);
STARTUPINFOW si = {sizeof(si)};
PROCESS_INFORMATION pi = {0};
if (!::CreateProcessW(chrome_exe.c_str(),
const_cast<wchar_t*>(command_line.c_str()),
NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL,
&si, &pi)) {
return false;
}
DWORD wr = ::WaitForSingleObject(pi.hProcess, INFINITE);
if (exit_code) {
::GetExitCodeProcess(pi.hProcess, reinterpret_cast<DWORD*>(exit_code));
}
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);
return true;
}
void installer::RemoveOldVersionDirs(const std::wstring& chrome_path,
const std::wstring& latest_version_str) {
std::wstring search_path(chrome_path);
file_util::AppendToPath(&search_path, L"*");
WIN32_FIND_DATA find_file_data;
HANDLE file_handle = FindFirstFile(search_path.c_str(), &find_file_data);
if (file_handle == INVALID_HANDLE_VALUE)
return;
BOOL ret = TRUE;
scoped_ptr<installer::Version> version;
scoped_ptr<installer::Version> latest_version(
installer::Version::GetVersionFromString(latest_version_str));
// We try to delete all directories whose versions are lower than
// latest_version.
while (ret) {
if (find_file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
LOG(INFO) << "directory found: " << find_file_data.cFileName;
version.reset(
installer::Version::GetVersionFromString(find_file_data.cFileName));
if (version.get() && latest_version->IsHigherThan(version.get())) {
std::wstring remove_dir(chrome_path);
file_util::AppendToPath(&remove_dir, find_file_data.cFileName);
std::wstring chrome_dll_path(remove_dir);
file_util::AppendToPath(&chrome_dll_path, installer_util::kChromeDll);
LOG(INFO) << "deleting directory " << remove_dir;
scoped_ptr<DeleteTreeWorkItem> item;
item.reset(WorkItem::CreateDeleteTreeWorkItem(remove_dir,
chrome_dll_path));
item->Do();
}
}
ret = FindNextFile(file_handle, &find_file_data);
}
FindClose(file_handle);
}
<commit_msg>Fixit: Coverity check return value.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h>
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/scoped_ptr.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/delete_tree_work_item.h"
#include "chrome/installer/util/helper.h"
#include "chrome/installer/util/logging_installer.h"
#include "chrome/installer/util/util_constants.h"
#include "chrome/installer/util/version.h"
#include "chrome/installer/util/work_item_list.h"
namespace {
std::wstring GetChromeInstallBasePath(bool system_install,
const wchar_t* subpath) {
FilePath install_path;
if (system_install) {
PathService::Get(base::DIR_PROGRAM_FILES, &install_path);
} else {
PathService::Get(base::DIR_LOCAL_APP_DATA, &install_path);
}
if (!install_path.empty()) {
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
install_path = install_path.Append(dist->GetInstallSubDir());
install_path = install_path.Append(subpath);
}
return install_path.ToWStringHack();
}
} // namespace
std::wstring installer::GetChromeInstallPath(bool system_install) {
return GetChromeInstallBasePath(system_install,
installer_util::kInstallBinaryDir);
}
std::wstring installer::GetChromeUserDataPath() {
return GetChromeInstallBasePath(false, installer_util::kInstallUserDataDir);
}
bool installer::LaunchChrome(bool system_install) {
std::wstring chrome_exe(L"\"");
chrome_exe.append(installer::GetChromeInstallPath(system_install));
file_util::AppendToPath(&chrome_exe, installer_util::kChromeExe);
chrome_exe.append(L"\"");
return base::LaunchApp(chrome_exe, false, false, NULL);
}
bool installer::LaunchChromeAndWaitForResult(bool system_install,
const std::wstring& options,
int32* exit_code) {
std::wstring chrome_exe(installer::GetChromeInstallPath(system_install));
if (chrome_exe.empty())
return false;
file_util::AppendToPath(&chrome_exe, installer_util::kChromeExe);
std::wstring command_line(L"\"" + chrome_exe + L"\"");
command_line.append(options);
STARTUPINFOW si = {sizeof(si)};
PROCESS_INFORMATION pi = {0};
if (!::CreateProcessW(chrome_exe.c_str(),
const_cast<wchar_t*>(command_line.c_str()),
NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL,
&si, &pi)) {
return false;
}
DWORD wr = ::WaitForSingleObject(pi.hProcess, INFINITE);
DWORD ret;
if (::GetExitCodeProcess(pi.hProcess, &ret) == 0)
return false;
if (exit_code)
*exit_code = ret;
::CloseHandle(pi.hProcess);
::CloseHandle(pi.hThread);
return true;
}
void installer::RemoveOldVersionDirs(const std::wstring& chrome_path,
const std::wstring& latest_version_str) {
std::wstring search_path(chrome_path);
file_util::AppendToPath(&search_path, L"*");
WIN32_FIND_DATA find_file_data;
HANDLE file_handle = FindFirstFile(search_path.c_str(), &find_file_data);
if (file_handle == INVALID_HANDLE_VALUE)
return;
BOOL ret = TRUE;
scoped_ptr<installer::Version> version;
scoped_ptr<installer::Version> latest_version(
installer::Version::GetVersionFromString(latest_version_str));
// We try to delete all directories whose versions are lower than
// latest_version.
while (ret) {
if (find_file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
LOG(INFO) << "directory found: " << find_file_data.cFileName;
version.reset(
installer::Version::GetVersionFromString(find_file_data.cFileName));
if (version.get() && latest_version->IsHigherThan(version.get())) {
std::wstring remove_dir(chrome_path);
file_util::AppendToPath(&remove_dir, find_file_data.cFileName);
std::wstring chrome_dll_path(remove_dir);
file_util::AppendToPath(&chrome_dll_path, installer_util::kChromeDll);
LOG(INFO) << "deleting directory " << remove_dir;
scoped_ptr<DeleteTreeWorkItem> item;
item.reset(WorkItem::CreateDeleteTreeWorkItem(remove_dir,
chrome_dll_path));
item->Do();
}
}
ret = FindNextFile(file_handle, &find_file_data);
}
FindClose(file_handle);
}
<|endoftext|> |
<commit_before><commit_msg>WaE: -Wunused-variable<commit_after><|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <actionlib/server/simple_action_server.h>
#include <moveit_msgs/MoveGroupAction.h>
#include <tf/transform_listener.h>
#include <planning_interface/planning_interface.h>
#include <planning_request_adapter/planning_request_adapter.h>
#include <planning_scene_monitor/planning_scene_monitor.h>
#include <trajectory_execution_ros/trajectory_execution_monitor_ros.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <boost/tokenizer.hpp>
#include <trajectory_processing/iterative_smoother.h>
static const std::string ROBOT_DESCRIPTION = "robot_description"; // name of the robot description (a param name, so it can be changed externally)
static const std::string DISPLAY_PATH_PUB_TOPIC = "display_trajectory";
class MoveGroupAction
{
public:
enum MoveGroupState
{
IDLE,
PLANNING,
MONITOR
};
MoveGroupAction(planning_scene_monitor::PlanningSceneMonitor &psm) :
nh_("~"), psm_(psm), state_(IDLE)
{
// load the group name
if (nh_.getParam("group", group_name_))
ROS_INFO("Starting move_group for group '%s'", group_name_.c_str());
else
ROS_FATAL("Group name not specified. Cannot start move_group");
bool manage_controllers= false;
nh_.param("manage_controllers", manage_controllers, true);
trajectory_execution_.reset(new trajectory_execution_ros::TrajectoryExecutionMonitorRos(psm_.getPlanningScene()->getKinematicModel(),
manage_controllers));
// load the planning plugin
try
{
planner_plugin_loader_.reset(new pluginlib::ClassLoader<planning_interface::Planner>("planning_interface", "planning_interface::Planner"));
}
catch(pluginlib::PluginlibException& ex)
{
ROS_FATAL_STREAM("Exception while creating planning plugin loader " << ex.what());
}
nh_.getParam("planning_plugin", planning_plugin_name_);
const std::vector<std::string> &classes = planner_plugin_loader_->getDeclaredClasses();
if (planning_plugin_name_.empty() && classes.size() == 1)
{
planning_plugin_name_ = classes[0];
ROS_INFO("No 'planning_plugin' parameter specified, but only '%s' planning plugin is available. Using that one.", planning_plugin_name_.c_str());
}
if (planning_plugin_name_.empty() && classes.size() > 1)
{
planning_plugin_name_ = classes[0];
ROS_INFO("Multiple planning plugins available. You shuold specify the 'planning_plugin' parameter. Using '%s' for now.", planning_plugin_name_.c_str());
}
try
{
planner_instance_.reset(planner_plugin_loader_->createUnmanagedInstance(planning_plugin_name_));
planner_instance_->init(psm_.getPlanningScene()->getKinematicModel());
ROS_INFO_STREAM("Using planning interface '" << planner_instance_->getDescription() << "'");
}
catch(pluginlib::PluginlibException& ex)
{
std::stringstream ss;
for (std::size_t i = 0 ; i < classes.size() ; ++i)
ss << classes[i] << " ";
ROS_FATAL_STREAM("Exception while loading planner '" << planning_plugin_name_ << "': " << ex.what() << std::endl
<< "Available plugins: " << ss.str());
}
// load the planner request adapters
std::string adapters;
if (nh_.getParam("request_adapters", adapters))
{
try
{
adapter_plugin_loader_.reset(new pluginlib::ClassLoader<planning_request_adapter::PlanningRequestAdapter>("planning_request_adapter", "planning_request_adapter::PlanningRequestAdapter"));
}
catch(pluginlib::PluginlibException& ex)
{
ROS_ERROR_STREAM("Exception while creating planning plugin loader " << ex.what());
}
boost::char_separator<char> sep(" ");
boost::tokenizer<boost::char_separator<char> > tok(adapters, sep);
std::vector<planning_request_adapter::PlanningRequestAdapterConstPtr> ads;
for(boost::tokenizer<boost::char_separator<char> >::iterator beg = tok.begin() ; beg != tok.end(); ++beg)
{
planning_request_adapter::PlanningRequestAdapterConstPtr ad;
try
{
ad.reset(adapter_plugin_loader_->createUnmanagedInstance(*beg));
}
catch (pluginlib::PluginlibException& ex)
{
ROS_ERROR_STREAM("Exception while planning adapter plugin '" << *beg << "': " << ex.what());
}
if (ad)
ads.push_back(ad);
}
if (!ads.empty())
{
adapter_chain_.reset(new planning_request_adapter::PlanningRequestAdapterChain());
for (std::size_t i = 0 ; i < ads.size() ; ++i)
{
ROS_INFO_STREAM("Using planning request adapter '" << ads[i]->getDescription() << "'");
adapter_chain_->addAdapter(ads[i]);
}
}
}
display_path_publisher_ = root_nh_.advertise<moveit_msgs::DisplayTrajectory>("move_" + group_name_ + "/" + DISPLAY_PATH_PUB_TOPIC, 1, true);
// start the action server
action_server_.reset(new actionlib::SimpleActionServer<moveit_msgs::MoveGroupAction>(root_nh_, "move_" + group_name_, false));
action_server_->registerGoalCallback(boost::bind(&MoveGroupAction::goalCallback, this));
action_server_->registerPreemptCallback(boost::bind(&MoveGroupAction::preemptCallback, this));
action_server_->start();
}
void goalCallback(void)
{
if (service_goal_thread_)
{
terminate_service_thread_ = true;
service_goal_thread_->join();
service_goal_thread_.reset();
}
goal_ = action_server_->acceptNewGoal();
if (!goal_)
{
ROS_ERROR("Something unexpected happened. No goal found in callback for goal...");
return;
}
if (!goal_->request.group_name.empty() && goal_->request.group_name != group_name_)
{
moveit_msgs::MoveGroupResult res;
res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GROUP_NAME;
action_server_->setAborted(res, "Cannot accept requests for group '" +
goal_->request.group_name + "' when the move_group action is loaded for group '" +
group_name_ + "'");
}
else
service_goal_thread_.reset(new boost::thread(boost::bind(&MoveGroupAction::serviceGoalRequest, this)));
}
void preemptCallback(void)
{
action_server_->setPreempted();
terminate_service_thread_ = true;
}
void serviceGoalRequest(void)
{
setState(PLANNING);
bool solved = false;
moveit_msgs::GetMotionPlan::Request req;
req.motion_plan_request = goal_->request;
if (req.motion_plan_request.group_name.empty())
req.motion_plan_request.group_name = group_name_;
moveit_msgs::GetMotionPlan::Response res;
const planning_scene::PlanningScenePtr &the_scene =
planning_scene::PlanningScene::isEmpty(goal_->planning_scene_diff) ? psm_.getPlanningScene() : planning_scene::PlanningScene::diff(psm_.getPlanningScene(), goal_->planning_scene_diff);
try
{
if (adapter_chain_)
solved = adapter_chain_->adaptAndPlan(planner_instance_, the_scene, req, res);
else
solved = planner_instance_->solve(the_scene, req, res);
}
catch(std::runtime_error &ex)
{
ROS_ERROR("Exception caught: '%s'", ex.what());
}
catch(...)
{
ROS_ERROR("Unknown exception thrown by planner");
}
if (solved)
{
trajectory_msgs::JointTrajectory trajectory_out;
smoother_.smooth(res.trajectory.joint_trajectory, trajectory_out, psm_.getGroupJointLimitsMap().at(group_name_));
res.trajectory.joint_trajectory = trajectory_out;
setState(MONITOR);
execution_complete_ = false;
// display the trajectory
moveit_msgs::DisplayTrajectory disp;
disp.model_id = psm_.getPlanningScene()->getKinematicModel()->getName();
disp.trajectory_start = res.trajectory_start;
disp.trajectory = res.trajectory;
display_path_publisher_.publish(disp);
trajectory_execution::TrajectoryExecutionRequest ter;
ter.group_name_ = group_name_;
ter.trajectory_ = res.trajectory.joint_trajectory; // \TODO This should take in a RobotTrajectory
if (trajectory_execution_->executeTrajectory(ter, boost::bind(&MoveGroupAction::doneWithTrajectoryExecution, this, _1)))
{
ros::WallDuration d(0.01);
while (nh_.ok() && !execution_complete_ && !terminate_service_thread_)
{
/// \TODO Check if the remainder of the path is still valid; If not, replan.
/// We need a callback in the trajectory monitor for this
d.sleep();
}
moveit_msgs::MoveGroupResult res;
res.error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
action_server_->setSucceeded(res, "Solution was found and executed.");
}
else
{
moveit_msgs::MoveGroupResult res;
// res.error_code.val = moveit_msgs::MoveItErrorCodes::CONTROL_FAILED;
action_server_->setAborted(res, "Solution was found but the controller failed to execute it.");
}
}
else
{
moveit_msgs::MoveGroupResult res;
res.error_code.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED;
action_server_->setAborted(res, "No motion plan found. No execution attempted.");
}
setState(IDLE);
}
bool doneWithTrajectoryExecution(trajectory_execution::TrajectoryExecutionDataVector data)
{
execution_complete_ = true;
return true;
}
void setState(MoveGroupState state)
{
state_ = state;
switch (state_)
{
case IDLE:
feedback_.state = "IDLE";
feedback_.time_to_completion = ros::Duration(0.0);
break;
case PLANNING:
feedback_.state = "PLANNING";
feedback_.time_to_completion = ros::Duration(0.0);
break;
case MONITOR:
feedback_.state = "MONITOR";
feedback_.time_to_completion = ros::Duration(0.0);
break;
}
action_server_->publishFeedback(feedback_);
}
void status(void)
{
ROS_INFO("MoveGroup action for group '%s' running using planning plugin '%s'", group_name_.c_str(), planning_plugin_name_.c_str());
}
private:
ros::NodeHandle root_nh_;
ros::NodeHandle nh_;
planning_scene_monitor::PlanningSceneMonitor &psm_;
std::string planning_plugin_name_;
boost::scoped_ptr<pluginlib::ClassLoader<planning_interface::Planner> > planner_plugin_loader_;
planning_interface::PlannerPtr planner_instance_;
std::string group_name_;
boost::scoped_ptr<pluginlib::ClassLoader<planning_request_adapter::PlanningRequestAdapter> > adapter_plugin_loader_;
boost::scoped_ptr<planning_request_adapter::PlanningRequestAdapterChain> adapter_chain_;
boost::shared_ptr<actionlib::SimpleActionServer<moveit_msgs::MoveGroupAction> > action_server_;
moveit_msgs::MoveGroupGoalConstPtr goal_;
moveit_msgs::MoveGroupFeedback feedback_;
boost::scoped_ptr<boost::thread> service_goal_thread_;
boost::shared_ptr<trajectory_execution_ros::TrajectoryExecutionMonitorRos> trajectory_execution_;
bool terminate_service_thread_;
bool execution_complete_;
MoveGroupState state_;
trajectory_processing::IterativeParabolicSmoother smoother_;
ros::Publisher display_path_publisher_;
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "move_group", ros::init_options::AnonymousName);
ros::AsyncSpinner spinner(1);
spinner.start();
tf::TransformListener tf;
planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION, &tf);
if (psm.getPlanningScene()->isConfigured())
{
psm.startWorldGeometryMonitor();
psm.startSceneMonitor();
psm.startStateMonitor();
MoveGroupAction mga(psm);
mga.status();
ros::waitForShutdown();
}
else
ROS_ERROR("Planning scene not configured");
return 0;
}
<commit_msg>Unsetting terminate_server_thread_ so the move group action doesn't terminate immediately<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <actionlib/server/simple_action_server.h>
#include <moveit_msgs/MoveGroupAction.h>
#include <tf/transform_listener.h>
#include <planning_interface/planning_interface.h>
#include <planning_request_adapter/planning_request_adapter.h>
#include <planning_scene_monitor/planning_scene_monitor.h>
#include <trajectory_execution_ros/trajectory_execution_monitor_ros.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <boost/tokenizer.hpp>
#include <trajectory_processing/iterative_smoother.h>
static const std::string ROBOT_DESCRIPTION = "robot_description"; // name of the robot description (a param name, so it can be changed externally)
static const std::string DISPLAY_PATH_PUB_TOPIC = "display_trajectory";
class MoveGroupAction
{
public:
enum MoveGroupState
{
IDLE,
PLANNING,
MONITOR
};
MoveGroupAction(planning_scene_monitor::PlanningSceneMonitor &psm) :
nh_("~"), psm_(psm), state_(IDLE)
{
// load the group name
if (nh_.getParam("group", group_name_))
ROS_INFO("Starting move_group for group '%s'", group_name_.c_str());
else
ROS_FATAL("Group name not specified. Cannot start move_group");
bool manage_controllers= false;
nh_.param("manage_controllers", manage_controllers, true);
trajectory_execution_.reset(new trajectory_execution_ros::TrajectoryExecutionMonitorRos(psm_.getPlanningScene()->getKinematicModel(),
manage_controllers));
// load the planning plugin
try
{
planner_plugin_loader_.reset(new pluginlib::ClassLoader<planning_interface::Planner>("planning_interface", "planning_interface::Planner"));
}
catch(pluginlib::PluginlibException& ex)
{
ROS_FATAL_STREAM("Exception while creating planning plugin loader " << ex.what());
}
nh_.getParam("planning_plugin", planning_plugin_name_);
const std::vector<std::string> &classes = planner_plugin_loader_->getDeclaredClasses();
if (planning_plugin_name_.empty() && classes.size() == 1)
{
planning_plugin_name_ = classes[0];
ROS_INFO("No 'planning_plugin' parameter specified, but only '%s' planning plugin is available. Using that one.", planning_plugin_name_.c_str());
}
if (planning_plugin_name_.empty() && classes.size() > 1)
{
planning_plugin_name_ = classes[0];
ROS_INFO("Multiple planning plugins available. You shuold specify the 'planning_plugin' parameter. Using '%s' for now.", planning_plugin_name_.c_str());
}
try
{
planner_instance_.reset(planner_plugin_loader_->createUnmanagedInstance(planning_plugin_name_));
planner_instance_->init(psm_.getPlanningScene()->getKinematicModel());
ROS_INFO_STREAM("Using planning interface '" << planner_instance_->getDescription() << "'");
}
catch(pluginlib::PluginlibException& ex)
{
std::stringstream ss;
for (std::size_t i = 0 ; i < classes.size() ; ++i)
ss << classes[i] << " ";
ROS_FATAL_STREAM("Exception while loading planner '" << planning_plugin_name_ << "': " << ex.what() << std::endl
<< "Available plugins: " << ss.str());
}
// load the planner request adapters
std::string adapters;
if (nh_.getParam("request_adapters", adapters))
{
try
{
adapter_plugin_loader_.reset(new pluginlib::ClassLoader<planning_request_adapter::PlanningRequestAdapter>("planning_request_adapter", "planning_request_adapter::PlanningRequestAdapter"));
}
catch(pluginlib::PluginlibException& ex)
{
ROS_ERROR_STREAM("Exception while creating planning plugin loader " << ex.what());
}
boost::char_separator<char> sep(" ");
boost::tokenizer<boost::char_separator<char> > tok(adapters, sep);
std::vector<planning_request_adapter::PlanningRequestAdapterConstPtr> ads;
for(boost::tokenizer<boost::char_separator<char> >::iterator beg = tok.begin() ; beg != tok.end(); ++beg)
{
planning_request_adapter::PlanningRequestAdapterConstPtr ad;
try
{
ad.reset(adapter_plugin_loader_->createUnmanagedInstance(*beg));
}
catch (pluginlib::PluginlibException& ex)
{
ROS_ERROR_STREAM("Exception while planning adapter plugin '" << *beg << "': " << ex.what());
}
if (ad)
ads.push_back(ad);
}
if (!ads.empty())
{
adapter_chain_.reset(new planning_request_adapter::PlanningRequestAdapterChain());
for (std::size_t i = 0 ; i < ads.size() ; ++i)
{
ROS_INFO_STREAM("Using planning request adapter '" << ads[i]->getDescription() << "'");
adapter_chain_->addAdapter(ads[i]);
}
}
}
display_path_publisher_ = root_nh_.advertise<moveit_msgs::DisplayTrajectory>("move_" + group_name_ + "/" + DISPLAY_PATH_PUB_TOPIC, 1, true);
// start the action server
action_server_.reset(new actionlib::SimpleActionServer<moveit_msgs::MoveGroupAction>(root_nh_, "move_" + group_name_, false));
action_server_->registerGoalCallback(boost::bind(&MoveGroupAction::goalCallback, this));
action_server_->registerPreemptCallback(boost::bind(&MoveGroupAction::preemptCallback, this));
action_server_->start();
}
void goalCallback(void)
{
if (service_goal_thread_)
{
terminate_service_thread_ = true;
service_goal_thread_->join();
service_goal_thread_.reset();
}
goal_ = action_server_->acceptNewGoal();
if (!goal_)
{
ROS_ERROR("Something unexpected happened. No goal found in callback for goal...");
return;
}
if (!goal_->request.group_name.empty() && goal_->request.group_name != group_name_)
{
moveit_msgs::MoveGroupResult res;
res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GROUP_NAME;
action_server_->setAborted(res, "Cannot accept requests for group '" +
goal_->request.group_name + "' when the move_group action is loaded for group '" +
group_name_ + "'");
}
else {
terminate_service_thread_ = false;
service_goal_thread_.reset(new boost::thread(boost::bind(&MoveGroupAction::serviceGoalRequest, this)));
}
}
void preemptCallback(void)
{
action_server_->setPreempted();
terminate_service_thread_ = true;
}
void serviceGoalRequest(void)
{
setState(PLANNING);
bool solved = false;
moveit_msgs::GetMotionPlan::Request req;
req.motion_plan_request = goal_->request;
if (req.motion_plan_request.group_name.empty())
req.motion_plan_request.group_name = group_name_;
moveit_msgs::GetMotionPlan::Response res;
const planning_scene::PlanningScenePtr &the_scene =
planning_scene::PlanningScene::isEmpty(goal_->planning_scene_diff) ? psm_.getPlanningScene() : planning_scene::PlanningScene::diff(psm_.getPlanningScene(), goal_->planning_scene_diff);
try
{
if (adapter_chain_)
solved = adapter_chain_->adaptAndPlan(planner_instance_, the_scene, req, res);
else
solved = planner_instance_->solve(the_scene, req, res);
}
catch(std::runtime_error &ex)
{
ROS_ERROR("Exception caught: '%s'", ex.what());
}
catch(...)
{
ROS_ERROR("Unknown exception thrown by planner");
}
if (solved)
{
trajectory_msgs::JointTrajectory trajectory_out;
smoother_.smooth(res.trajectory.joint_trajectory, trajectory_out, psm_.getGroupJointLimitsMap().at(group_name_));
res.trajectory.joint_trajectory = trajectory_out;
setState(MONITOR);
execution_complete_ = false;
// display the trajectory
moveit_msgs::DisplayTrajectory disp;
disp.model_id = psm_.getPlanningScene()->getKinematicModel()->getName();
disp.trajectory_start = res.trajectory_start;
disp.trajectory = res.trajectory;
display_path_publisher_.publish(disp);
trajectory_execution::TrajectoryExecutionRequest ter;
ter.group_name_ = group_name_;
ter.trajectory_ = res.trajectory.joint_trajectory; // \TODO This should take in a RobotTrajectory
if (trajectory_execution_->executeTrajectory(ter, boost::bind(&MoveGroupAction::doneWithTrajectoryExecution, this, _1)))
{
ros::WallDuration d(0.01);
while (nh_.ok() && !execution_complete_ && !terminate_service_thread_)
{
/// \TODO Check if the remainder of the path is still valid; If not, replan.
/// We need a callback in the trajectory monitor for this
d.sleep();
}
moveit_msgs::MoveGroupResult res;
res.error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
action_server_->setSucceeded(res, "Solution was found and executed.");
}
else
{
moveit_msgs::MoveGroupResult res;
// res.error_code.val = moveit_msgs::MoveItErrorCodes::CONTROL_FAILED;
action_server_->setAborted(res, "Solution was found but the controller failed to execute it.");
}
}
else
{
moveit_msgs::MoveGroupResult res;
res.error_code.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED;
action_server_->setAborted(res, "No motion plan found. No execution attempted.");
}
setState(IDLE);
}
bool doneWithTrajectoryExecution(trajectory_execution::TrajectoryExecutionDataVector data)
{
execution_complete_ = true;
return true;
}
void setState(MoveGroupState state)
{
state_ = state;
switch (state_)
{
case IDLE:
feedback_.state = "IDLE";
feedback_.time_to_completion = ros::Duration(0.0);
break;
case PLANNING:
feedback_.state = "PLANNING";
feedback_.time_to_completion = ros::Duration(0.0);
break;
case MONITOR:
feedback_.state = "MONITOR";
feedback_.time_to_completion = ros::Duration(0.0);
break;
}
action_server_->publishFeedback(feedback_);
}
void status(void)
{
ROS_INFO("MoveGroup action for group '%s' running using planning plugin '%s'", group_name_.c_str(), planning_plugin_name_.c_str());
}
private:
ros::NodeHandle root_nh_;
ros::NodeHandle nh_;
planning_scene_monitor::PlanningSceneMonitor &psm_;
std::string planning_plugin_name_;
boost::scoped_ptr<pluginlib::ClassLoader<planning_interface::Planner> > planner_plugin_loader_;
planning_interface::PlannerPtr planner_instance_;
std::string group_name_;
boost::scoped_ptr<pluginlib::ClassLoader<planning_request_adapter::PlanningRequestAdapter> > adapter_plugin_loader_;
boost::scoped_ptr<planning_request_adapter::PlanningRequestAdapterChain> adapter_chain_;
boost::shared_ptr<actionlib::SimpleActionServer<moveit_msgs::MoveGroupAction> > action_server_;
moveit_msgs::MoveGroupGoalConstPtr goal_;
moveit_msgs::MoveGroupFeedback feedback_;
boost::scoped_ptr<boost::thread> service_goal_thread_;
boost::shared_ptr<trajectory_execution_ros::TrajectoryExecutionMonitorRos> trajectory_execution_;
bool terminate_service_thread_;
bool execution_complete_;
MoveGroupState state_;
trajectory_processing::IterativeParabolicSmoother smoother_;
ros::Publisher display_path_publisher_;
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "move_group", ros::init_options::AnonymousName);
ros::AsyncSpinner spinner(1);
spinner.start();
tf::TransformListener tf;
planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION, &tf);
if (psm.getPlanningScene()->isConfigured())
{
psm.startWorldGeometryMonitor();
psm.startSceneMonitor();
psm.startStateMonitor();
MoveGroupAction mga(psm);
mga.status();
ros::waitForShutdown();
}
else
ROS_ERROR("Planning scene not configured");
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: graphsh.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:44:59 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef GRAPHSH_HXX
#define GRAPHSH_HXX
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#include "shellids.hxx"
#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif
class ScViewData;
#include "drawsh.hxx"
class ScGraphicShell: public ScDrawShell
{
public:
TYPEINFO();
SFX_DECL_INTERFACE(SCID_GRAPHIC_SHELL);
ScGraphicShell(ScViewData* pData);
virtual ~ScGraphicShell();
};
#endif
<commit_msg>Execute/GetAttrState for graphic object functions<commit_after>/*************************************************************************
*
* $RCSfile: graphsh.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: nn $ $Date: 2000-10-20 18:24:10 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef GRAPHSH_HXX
#define GRAPHSH_HXX
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#include "shellids.hxx"
#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif
#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif
class ScViewData;
#include "drawsh.hxx"
class ScGraphicShell: public ScDrawShell
{
public:
TYPEINFO();
SFX_DECL_INTERFACE(SCID_GRAPHIC_SHELL);
ScGraphicShell(ScViewData* pData);
virtual ~ScGraphicShell();
void Execute(SfxRequest& rReq);
void GetAttrState(SfxItemSet &rSet);
};
#endif
<|endoftext|> |
<commit_before>/*ckwg +29
* Copyright 2016 by Kitware, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither name of Kitware, Inc. nor the names of any 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 AUTHORS 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 <super3d/depth/super_config.h>
#include <super3d/depth/tv_refine_search.h>
#include <super3d/depth/cost_volume.h>
#include <super3d/depth/file_io.h>
#include <super3d/depth/depth_map.h>
#include <super3d/depth/multiscale.h>
#include <super3d/depth/tv_refine_plane.h>
#include <super3d/depth/world_rectilinear.h>
#include <super3d/depth/world_frustum.h>
#include <super3d/depth/exposure.h>
// VXL includes
#include <vil/vil_convert.h>
#include <vil/vil_save.h>
#include <vil/vil_crop.h>
#include <vil/vil_load.h>
#include <vil/vil_copy.h>
#include <vil/vil_decimate.h>
#include <vul/vul_timer.h>
#include <super3d/imesh/imesh_mesh.h>
#include <super3d/imesh/imesh_fileio.h>
#include <vpgl/vpgl_perspective_camera.h>
#include <vtkXMLImageDataWriter.h>
#include <vtkImageData.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkDoubleArray.h>
#include <vtkPoints.h>
#include <vtkUnsignedCharArray.h>
#include <sstream>
int main(int argc, char* argv[])
{
try
{
std::unique_ptr<super3d::config> cfg(new super3d::config);
cfg->read_config(argv[1]);
std::string frame_file = cfg->get_value<std::string>("frame_list");
std::string dir("");
if (cfg->is_set("directory"))
dir = cfg->get_value<std::string>("directory");
std::string camera_dir = cfg->get_value<std::string>("camera_dir");
std::cout << "Using frame file: " << frame_file << " to find images and " << camera_dir << " to find cameras.\n";
std::ifstream infile(frame_file.c_str());
std::vector<std::string> filenames;
std::string x;
while (infile >> x) filenames.push_back(x);
int numsupport = cfg->get_value<int>("support_frames");
int stride = cfg->get_value<int>("stride");
std::cout << "Read " << filenames.size() << " filenames.\n";
int halfsupport = numsupport / 2;
for (int i = halfsupport; i < static_cast<int>(filenames.size()) - halfsupport; i += stride)
{
std::cout << "Computing depth map on frame: " << i << "\n";
std::vector<std::string> support_frames(filenames.begin() + (i - halfsupport), filenames.begin() + (i + halfsupport));
std::cout << support_frames.size() << std::endl;
std::vector<vil_image_view<double> > frames;
std::vector<vpgl_perspective_camera<double> > cameras;
super3d::load_frames(support_frames, frames, cfg->get_value<bool>("use_color"), cfg->get_value<bool>("use_rgb12"));
for (unsigned int f = 0; f < support_frames.size(); f++)
{
std::string camname = support_frames[f];
unsigned int found = camname.find_last_of("/\\");
camname = camname.substr(found + 1, camname.size() - 4 - found - 1);
camname = cfg->get_value<std::string>("camera_dir") + "/" + camname + ".krtd";
cameras.push_back(super3d::load_cam(camname));
}
unsigned int ref_frame = halfsupport;
vpgl_perspective_camera<double> ref_cam = cameras[ref_frame];
super3d::world_space *ws = NULL;
int ni = frames[ref_frame].ni(), nj = frames[ref_frame].nj();
double depth_min, depth_max;
std::cout << "Computing depth range from " << cfg->get_value<std::string>("landmarks_path") << "\n";
std::vector<vnl_double_3> landmarks;
super3d::read_landmark_file(cfg->get_value<std::string>("landmarks_path"), landmarks);
std::vector<vnl_double_3> visible_landmarks =
super3d::filter_visible_landmarks(cameras[ref_frame], 0, ni, 0, nj, landmarks);
super3d::compute_depth_range(visible_landmarks, cameras[ref_frame], depth_min, depth_max);
std::cout << "Max estimated depth: " << depth_max << "\n";
std::cout << "Min estimated depth: " << depth_min << "\n";
ws = new super3d::world_frustum(cameras[ref_frame], depth_min, depth_max, ni, nj);
std::cout << "Refining depth" << std::endl;
unsigned int S = cfg->get_value<unsigned int>("num_slices");
double theta0 = cfg->get_value<double>("theta_start");
double theta_end = cfg->get_value<double>("theta_end");
//double beta = cfg->get_value<double>("beta");
double lambda = cfg->get_value<double>("lambda");
double gw_alpha = cfg->get_value<double>("gw_alpha");
double epsilon = cfg->get_value<double>("epsilon");
vil_image_view<double> g;
vil_image_view<double> cost_volume;
double iw = cfg->get_value<double>("intensity_cost_weight");
double gw = cfg->get_value<double>("gradient_cost_weight");
double cw = cfg->get_value<double>("census_cost_weight");
super3d::compute_world_cost_volume(frames, cameras, ws, ref_frame, S, cost_volume, iw, gw, cw);
//compute_cost_volume_warp(frames, cameras, ref_frame, S, depth_min, depth_max, cost_volume);
ws->compute_g(frames[ref_frame], g, gw_alpha, 1.0);
std::cout << "Refining Depth. ..\n";
vil_image_view<double> depth(cost_volume.ni(), cost_volume.nj(), 1);
vul_timer timer;
unsigned int iterations = 2000;
if (cfg->is_set("iterations"))
iterations = cfg->get_value<unsigned int>("iterations");
super3d::refine_depth(cost_volume, g, depth, iterations, theta0, theta_end, lambda, epsilon);
double sec = 1e-3 * timer.real();
std::cout << "super3d took " << sec << " seconds.\n";
std::string outdir = cfg->get_value<std::string>("outdir");
std::ostringstream depth_name;
depth_name << outdir << "/" << i;
vil_image_view<vxl_byte> dmap;
vil_convert_stretch_range_limited(depth, dmap, 0.0, 1.0);
// depth map are drawn inverted (white == closest) for viewing
vil_math_scale_and_offset_values(dmap, -1.0, 255);
std::string depthmap_file = depth_name.str() + ".png";
vil_save(dmap, depthmap_file.c_str());
super3d::save_depth_to_vtp((depth_name.str() + ".vtp").c_str(), depth, frames[ref_frame], ref_cam, ws);
// map depth from normalized range back into true depth
double depth_scale = depth_max - depth_min;
vil_math_scale_and_offset_values(depth, depth_scale, depth_min);
double minv, maxv;
vil_math_value_range(depth, minv, maxv);
std::cout << "Depth range: " << minv << " - " << maxv << "\n";
vtkNew<vtkDoubleArray> uniquenessRatios;
uniquenessRatios->SetName("Uniqueness Ratios");
uniquenessRatios->SetNumberOfValues(ni*nj);
vtkNew<vtkDoubleArray> bestCost;
bestCost->SetName("Best Cost Values");
bestCost->SetNumberOfValues(ni*nj);
vtkNew<vtkUnsignedCharArray> color;
color->SetName("Color");
color->SetNumberOfComponents(3);
color->SetNumberOfTuples(ni*nj);
vtkNew<vtkDoubleArray> depths;
depths->SetName("Depths");
depths->SetNumberOfComponents(1);
depths->SetNumberOfTuples(ni*nj);
vil_image_view<vxl_byte> ref_img_color = vil_load(support_frames[ref_frame].c_str());
vtkIdType pt_id = 0;
for (int y = nj - 1; y >= 0; y--)
{
for (int x = 0; x < ni; x++)
{
uniquenessRatios->SetValue(pt_id, 0);
bestCost->SetValue(pt_id, 0);
depths->SetValue(pt_id, depth(x, y));
color->SetTuple3(pt_id, (int)ref_img_color(x, y, 0), (int)ref_img_color(x, y, 1), (int)ref_img_color(x, y, 2));
pt_id++;
}
}
vtkNew<vtkImageData> imageData;
imageData->SetSpacing(1, 1, 1);
imageData->SetOrigin(0, 0, 0);
imageData->SetDimensions(ni, nj, 1);
imageData->GetPointData()->AddArray(depths.Get());
imageData->GetPointData()->AddArray(color.Get());
imageData->GetPointData()->AddArray(uniquenessRatios.Get());
imageData->GetPointData()->AddArray(bestCost.Get());
vtkNew<vtkXMLImageDataWriter> writerI;
std::string depthmapImageFileName = depth_name.str() + ".vti";
writerI->SetFileName(depthmapImageFileName.c_str());
writerI->AddInputDataObject(imageData.Get());
writerI->SetDataModeToBinary();
writerI->Write();
std::cout << "Saved : " << depthmapImageFileName << std::endl;
if (ws) delete ws;
}
}
catch (const super3d::config::cfg_exception &e)
{
std::cout << "Error in config: " << e.what() << "\n";
}
return 0;
}
<commit_msg>added angled frustum support to video_depth tool<commit_after>/*ckwg +29
* Copyright 2016 by Kitware, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither name of Kitware, Inc. nor the names of any 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 AUTHORS 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 <super3d/depth/super_config.h>
#include <super3d/depth/tv_refine_search.h>
#include <super3d/depth/cost_volume.h>
#include <super3d/depth/file_io.h>
#include <super3d/depth/depth_map.h>
#include <super3d/depth/multiscale.h>
#include <super3d/depth/tv_refine_plane.h>
#include <super3d/depth/world_rectilinear.h>
#include <super3d/depth/world_frustum.h>
#include <super3d/depth/world_angled_frustum.h>
#include <super3d/depth/exposure.h>
// VXL includes
#include <vil/vil_convert.h>
#include <vil/vil_save.h>
#include <vil/vil_crop.h>
#include <vil/vil_load.h>
#include <vil/vil_copy.h>
#include <vil/vil_decimate.h>
#include <vul/vul_timer.h>
#include <super3d/imesh/imesh_mesh.h>
#include <super3d/imesh/imesh_fileio.h>
#include <vpgl/vpgl_perspective_camera.h>
#include <vtkXMLImageDataWriter.h>
#include <vtkImageData.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkDoubleArray.h>
#include <vtkPoints.h>
#include <vtkUnsignedCharArray.h>
#include <sstream>
int main(int argc, char* argv[])
{
try
{
std::unique_ptr<super3d::config> cfg(new super3d::config);
cfg->read_config(argv[1]);
std::string frame_file = cfg->get_value<std::string>("frame_list");
std::string dir("");
if (cfg->is_set("directory"))
dir = cfg->get_value<std::string>("directory");
std::string camera_dir = cfg->get_value<std::string>("camera_dir");
std::cout << "Using frame file: " << frame_file << " to find images and " << camera_dir << " to find cameras.\n";
std::ifstream infile(frame_file.c_str());
std::vector<std::string> filenames;
std::string x;
while (infile >> x) filenames.push_back(x);
int numsupport = cfg->get_value<int>("support_frames");
int stride = cfg->get_value<int>("stride");
std::cout << "Read " << filenames.size() << " filenames.\n";
bool use_world_planes = false;
vnl_double_3 normal;
if (cfg->is_set("world_plane_normal"))
{
// use world coordinate slices in this direction instead of depth
std::istringstream ss(cfg->get_value<std::string>("world_plane_normal"));
ss >> normal;
normal.normalize();
use_world_planes = true;
}
int halfsupport = numsupport / 2;
for (int i = halfsupport; i < static_cast<int>(filenames.size()) - halfsupport; i += stride)
{
std::cout << "Computing depth map on frame: " << i << "\n";
std::vector<std::string> support_frames(filenames.begin() + (i - halfsupport), filenames.begin() + (i + halfsupport));
std::cout << support_frames.size() << std::endl;
std::vector<vil_image_view<double> > frames;
std::vector<vpgl_perspective_camera<double> > cameras;
super3d::load_frames(support_frames, frames, cfg->get_value<bool>("use_color"), cfg->get_value<bool>("use_rgb12"));
for (unsigned int f = 0; f < support_frames.size(); f++)
{
std::string camname = support_frames[f];
unsigned int found = camname.find_last_of("/\\");
camname = camname.substr(found + 1, camname.size() - 4 - found - 1);
camname = cfg->get_value<std::string>("camera_dir") + "/" + camname + ".krtd";
cameras.push_back(super3d::load_cam(camname));
}
unsigned int ref_frame = halfsupport;
vpgl_perspective_camera<double> ref_cam = cameras[ref_frame];
super3d::world_space *ws = NULL;
int ni = frames[ref_frame].ni(), nj = frames[ref_frame].nj();
double depth_min, depth_max;
std::cout << "Computing depth range from " << cfg->get_value<std::string>("landmarks_path") << "\n";
std::vector<vnl_double_3> landmarks;
super3d::read_landmark_file(cfg->get_value<std::string>("landmarks_path"), landmarks);
std::vector<vnl_double_3> visible_landmarks =
super3d::filter_visible_landmarks(cameras[ref_frame], 0, ni, 0, nj, landmarks);
if (use_world_planes)
{
super3d::compute_offset_range(visible_landmarks, normal, depth_min, depth_max, 0, 0.5);
std::cout << "Max estimated offset: " << depth_max << "\n";
std::cout << "Min estimated offset: " << depth_min << "\n";
ws = new super3d::world_angled_frustum(cameras[ref_frame], normal, depth_min, depth_max, ni, nj);
}
else
{
super3d::compute_depth_range(visible_landmarks, cameras[ref_frame], depth_min, depth_max);
std::cout << "Max estimated depth: " << depth_max << "\n";
std::cout << "Min estimated depth: " << depth_min << "\n";
ws = new super3d::world_frustum(cameras[ref_frame], depth_min, depth_max, ni, nj);
}
std::cout << "Refining depth" << std::endl;
unsigned int S = cfg->get_value<unsigned int>("num_slices");
double theta0 = cfg->get_value<double>("theta_start");
double theta_end = cfg->get_value<double>("theta_end");
//double beta = cfg->get_value<double>("beta");
double lambda = cfg->get_value<double>("lambda");
double gw_alpha = cfg->get_value<double>("gw_alpha");
double epsilon = cfg->get_value<double>("epsilon");
vil_image_view<double> g;
vil_image_view<double> cost_volume;
double iw = cfg->get_value<double>("intensity_cost_weight");
double gw = cfg->get_value<double>("gradient_cost_weight");
double cw = cfg->get_value<double>("census_cost_weight");
super3d::compute_world_cost_volume(frames, cameras, ws, ref_frame, S, cost_volume, iw, gw, cw);
//compute_cost_volume_warp(frames, cameras, ref_frame, S, depth_min, depth_max, cost_volume);
ws->compute_g(frames[ref_frame], g, gw_alpha, 1.0);
std::cout << "Refining Depth. ..\n";
vil_image_view<double> depth(cost_volume.ni(), cost_volume.nj(), 1);
vul_timer timer;
unsigned int iterations = 2000;
if (cfg->is_set("iterations"))
iterations = cfg->get_value<unsigned int>("iterations");
super3d::refine_depth(cost_volume, g, depth, iterations, theta0, theta_end, lambda, epsilon);
double sec = 1e-3 * timer.real();
std::cout << "super3d took " << sec << " seconds.\n";
std::string outdir = cfg->get_value<std::string>("outdir");
std::ostringstream depth_name;
depth_name << outdir << "/" << i;
super3d::save_depth_to_vtp((depth_name.str() + ".vtp").c_str(), depth, frames[ref_frame], ref_cam, ws);
// map depth from normalized range back into true depth
double depth_scale = depth_max - depth_min;
vil_math_scale_and_offset_values(depth, depth_scale, depth_min);
vil_image_view<double> height_map;
if (use_world_planes)
{
height_map = depth;
depth = vil_image_view<double>();
super3d::height_map_to_depth_map(cameras[ref_frame], height_map, depth);
}
else
{
super3d::depth_map_to_height_map(cameras[ref_frame], depth, height_map);
}
// save byte depth map
vil_image_view<vxl_byte> bmap;
vil_convert_stretch_range(depth, bmap);
// depth map are drawn inverted (white == closest) for viewing
vil_math_scale_and_offset_values(bmap, -1.0, 255);
std::string depthmap_file = depth_name.str() + "_depth.png";
vil_save(bmap, depthmap_file.c_str());
// save byte height map
vil_convert_stretch_range(height_map, bmap);
std::string heightmap_file = depth_name.str() + "_height.png";
vil_save(bmap, heightmap_file.c_str());
double minv, maxv;
vil_math_value_range(depth, minv, maxv);
std::cout << "Depth range: " << minv << " - " << maxv << "\n";
vil_math_value_range(height_map, minv, maxv);
std::cout << "Height range: " << minv << " - " << maxv << "\n";
vtkNew<vtkDoubleArray> uniquenessRatios;
uniquenessRatios->SetName("Uniqueness Ratios");
uniquenessRatios->SetNumberOfValues(ni*nj);
vtkNew<vtkDoubleArray> bestCost;
bestCost->SetName("Best Cost Values");
bestCost->SetNumberOfValues(ni*nj);
vtkNew<vtkUnsignedCharArray> color;
color->SetName("Color");
color->SetNumberOfComponents(3);
color->SetNumberOfTuples(ni*nj);
vtkNew<vtkDoubleArray> depths;
depths->SetName("Depths");
depths->SetNumberOfComponents(1);
depths->SetNumberOfTuples(ni*nj);
vil_image_view<vxl_byte> ref_img_color = vil_load(support_frames[ref_frame].c_str());
vtkIdType pt_id = 0;
for (int y = nj - 1; y >= 0; y--)
{
for (int x = 0; x < ni; x++)
{
uniquenessRatios->SetValue(pt_id, 0);
bestCost->SetValue(pt_id, 0);
depths->SetValue(pt_id, depth(x, y));
color->SetTuple3(pt_id, (int)ref_img_color(x, y, 0), (int)ref_img_color(x, y, 1), (int)ref_img_color(x, y, 2));
pt_id++;
}
}
vtkNew<vtkImageData> imageData;
imageData->SetSpacing(1, 1, 1);
imageData->SetOrigin(0, 0, 0);
imageData->SetDimensions(ni, nj, 1);
imageData->GetPointData()->AddArray(depths.Get());
imageData->GetPointData()->AddArray(color.Get());
imageData->GetPointData()->AddArray(uniquenessRatios.Get());
imageData->GetPointData()->AddArray(bestCost.Get());
vtkNew<vtkXMLImageDataWriter> writerI;
std::string depthmapImageFileName = depth_name.str() + ".vti";
writerI->SetFileName(depthmapImageFileName.c_str());
writerI->AddInputDataObject(imageData.Get());
writerI->SetDataModeToBinary();
writerI->Write();
std::cout << "Saved : " << depthmapImageFileName << std::endl;
if (ws) delete ws;
}
}
catch (const super3d::config::cfg_exception &e)
{
std::cout << "Error in config: " << e.what() << "\n";
}
return 0;
}
<|endoftext|> |
<commit_before>/* Deathray - An Avisynth plug-in filter for spatial/temporal non-local means de-noising.
*
* version 1.01
*
* Copyright 2013, Jawed Ashraf - [email protected]
*/
#include "device.h"
#include "buffer.h"
#include "buffer_map.h"
#include "CLKernel.h"
#include "MultiFrame.h"
extern int g_device_count;
extern device *g_devices;
extern cl_context g_context;
extern int g_gaussian;
MultiFrame::MultiFrame() {
device_id_ = 0;
temporal_radius_ = 0;
frames_.clear();
dest_plane_ = 0;
width_ = 0;
height_ = 0;
src_pitch_ = 0;
dst_pitch_ = 0;
}
result MultiFrame::Init(
const int &device_id,
const int &temporal_radius,
const int &width,
const int &height,
const int &src_pitch,
const int &dst_pitch,
const float &h,
const int &sample_expand,
const int &linear,
const int &correction) {
if (device_id >= g_device_count) return FILTER_ERROR;
result status = FILTER_OK;
device_id_ = device_id;
temporal_radius_ = temporal_radius;
width_ = width;
height_ = height;
src_pitch_ = src_pitch;
dst_pitch_ = dst_pitch;
h_ = h;
cq_ = g_devices[device_id_].cq();
if (width_ == 0 || height_ == 0 || src_pitch_ == 0 || dst_pitch_ == 0 || h == 0 ) return FILTER_INVALID_PARAMETER;
status = InitBuffers();
if (status != FILTER_OK) return status;
status = InitKernels(sample_expand, linear, correction);
if (status != FILTER_OK) return status;
status = InitFrames();
return status;
}
result MultiFrame::InitBuffers() {
result status = FILTER_OK;
// Buffer is sized upwards to the next highest multiple of 32
// horizontally and vertically because tile size is 32x32
intermediate_width_ = ByPowerOf2(width_, 5) >> 2;
intermediate_height_ = ByPowerOf2(height_, 5);
const size_t bytes = intermediate_width_ * intermediate_height_ * sizeof(float) << 2;
status = g_devices[device_id_].buffers_.AllocBuffer(cq_, bytes, &averages_);
if (status != FILTER_OK) return status;
status = g_devices[device_id_].buffers_.AllocBuffer(cq_, bytes, &weights_);
if (status != FILTER_OK) return status;
status = g_devices[device_id_].buffers_.AllocPlane(cq_, width_, height_, &dest_plane_);
return status;
}
result MultiFrame::InitKernels(
const int &sample_expand,
const int &linear,
const int &correction) {
NLM_kernel_ = CLKernel(device_id_, "NLMMultiFrameFourPixel");
NLM_kernel_.SetNumberedArg(3, sizeof(int), &width_);
NLM_kernel_.SetNumberedArg(4, sizeof(int), &height_);
NLM_kernel_.SetNumberedArg(5, sizeof(float), &h_);
NLM_kernel_.SetNumberedArg(6, sizeof(int), &sample_expand);
NLM_kernel_.SetNumberedArg(7, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(g_gaussian));
NLM_kernel_.SetNumberedArg(8, sizeof(int), &intermediate_width_);
NLM_kernel_.SetNumberedArg(9, sizeof(int), &linear);
NLM_kernel_.SetNumberedArg(10, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(averages_));
NLM_kernel_.SetNumberedArg(11, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(weights_));
const size_t set_local_work_size[2] = {8, 32};
const size_t set_scalar_global_size[2] = {width_, height_};
const size_t set_scalar_item_size[2] = {4, 1};
if (NLM_kernel_.arguments_valid()) {
NLM_kernel_.set_work_dim(2);
NLM_kernel_.set_local_work_size(set_local_work_size);
NLM_kernel_.set_scalar_global_size(set_scalar_global_size);
NLM_kernel_.set_scalar_item_size(set_scalar_item_size);
} else {
return FILTER_KERNEL_ARGUMENT_ERROR;
}
finalise_kernel_ = CLKernel(device_id_, "NLMFinalise");
finalise_kernel_.SetNumberedArg(1, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(averages_));
finalise_kernel_.SetNumberedArg(2, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(weights_));
finalise_kernel_.SetNumberedArg(3, sizeof(int), &intermediate_width_);
finalise_kernel_.SetNumberedArg(4, sizeof(int), &linear);
finalise_kernel_.SetNumberedArg(5, sizeof(int), &correction);
finalise_kernel_.SetNumberedArg(6, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(dest_plane_));
if (finalise_kernel_.arguments_valid()) {
finalise_kernel_.set_work_dim(2);
finalise_kernel_.set_local_work_size(set_local_work_size);
finalise_kernel_.set_scalar_global_size(set_scalar_global_size);
finalise_kernel_.set_scalar_item_size(set_scalar_item_size);
} else {
return FILTER_KERNEL_ARGUMENT_ERROR;
}
return FILTER_OK;
}
result MultiFrame::InitFrames() {
const int frame_count = 2 * temporal_radius_ + 1;
frames_.reserve(frame_count);
for (int i = 0; i < frame_count; ++i) {
Frame new_frame;
frames_.push_back(new_frame);
frames_[i].Init(device_id_, &cq_, NLM_kernel_, width_, height_, src_pitch_);
}
if (frames_.size() != frame_count)
return FILTER_MULTI_FRAME_INITIALISATION_FAILED;
return FILTER_OK;
}
result MultiFrame::ZeroIntermediates() {
result status = FILTER_OK;
CLKernel Intermediates = CLKernel(device_id_, "Zero");
Intermediates.SetArg(sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(averages_));
if (Intermediates.arguments_valid()) {
const size_t set_local_work_size[1] = {256};
const size_t set_scalar_global_size[1] = {intermediate_width_ * intermediate_height_ << 2};
const size_t set_scalar_item_size[1] = {4};
Intermediates.set_work_dim(1);
Intermediates.set_local_work_size(set_local_work_size);
Intermediates.set_scalar_global_size(set_scalar_global_size);
Intermediates.set_scalar_item_size(set_scalar_item_size);
status = Intermediates.Execute(cq_, NULL);
if (status != FILTER_OK) return status;
} else {
return FILTER_KERNEL_ARGUMENT_ERROR;
}
Intermediates.SetNumberedArg(0, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(weights_));
if (Intermediates.arguments_valid()) {
status = Intermediates.Execute(cq_, NULL);
if (status != FILTER_OK) return status;
} else {
return FILTER_KERNEL_ARGUMENT_ERROR;
}
clFinish(cq_);
return status;
}
void MultiFrame::SupplyFrameNumbers(
const int &target_frame_number,
MultiFrameRequest *required) {
target_frame_number_ = target_frame_number;
for (int i = -temporal_radius_, frame_id = 0; i <= temporal_radius_; ++i, ++frame_id) {
int frame_number = target_frame_number_ - ((target_frame_number_ - i + temporal_radius_) % frames_.size()) + temporal_radius_;
if (frames_[frame_id].IsCopyRequired(frame_number))
required->Request(frame_number);
}
}
result MultiFrame::CopyTo(MultiFrameRequest *retrieved) {
result status = FILTER_OK;
status = ZeroIntermediates();
if (status != FILTER_OK) return status;
for (int i = -temporal_radius_, frame_id = 0; i <= temporal_radius_; ++i, ++frame_id) {
int frame_number = target_frame_number_ - ((target_frame_number_ - i + temporal_radius_) % frames_.size()) + temporal_radius_;
status = frames_[frame_id].CopyTo(frame_number, retrieved->Retrieve(frame_number));
if (status != FILTER_OK) return status;
}
clFinish(cq_);
return status;
}
result MultiFrame::ExecuteFrame(
const int &frame_id,
const bool &sample_equals_target,
cl_event ©ing_target,
cl_event *filter_events) {
cl_event executed;
result status = frames_[frame_id].Execute(sample_equals_target, ©ing_target, &executed);
filter_events[frame_id] = executed;
return status;
}
result MultiFrame::Execute() {
result status = FILTER_OK;
// Query the Frame object handling the target frame to get the plane for the other Frames to use
int target_frame_id = (target_frame_number_ + temporal_radius_) % frames_.size();
int target_frame_plane;
cl_event copying_target;
frames_[target_frame_id].Plane(&target_frame_plane, ©ing_target);
NLM_kernel_.SetNumberedArg(0, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(target_frame_plane));
cl_event *filter_events = new cl_event[frames_.size()];
for (int i = 0; i < 2 * temporal_radius_ + 1; ++i) {
bool sample_equals_target = i == target_frame_id;
/* if (sample_equals_target) { // process the target frame last
} else {*/
status = ExecuteFrame(i, sample_equals_target, copying_target, filter_events);
if (status != FILTER_OK) return status;
//}
}
finalise_kernel_.SetNumberedArg(0, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(target_frame_plane));
status = finalise_kernel_.ExecuteWaitList(cq_, frames_.size(), filter_events, &executed_);
if (status != FILTER_OK) return status;
clFinish(cq_);
return status;
}
result MultiFrame::CopyFrom(
unsigned char *dest,
cl_event *returned) {
return g_devices[device_id_].buffers_.CopyFromPlaneAsynch(dest_plane_,
width_,
height_,
dst_pitch_,
&executed_,
returned,
dest);
}
// Frame
MultiFrame::Frame::Frame() {
frame_number_ = 0;
plane_ = 0;
width_ = 0;
height_ = 0;
pitch_ = 0;
}
result MultiFrame::Frame::Init(
const int &device_id,
cl_command_queue *cq,
const CLKernel &NLM_kernel,
const int &width,
const int &height,
const int &pitch) {
// Setting this frame's NLM_kernel_ to the client's kernel object means all frames share the
// same instance, and therefore each Frame object only needs to do minimal argument
// setup.
device_id_ = device_id;
cq_ = *cq;
NLM_kernel_ = NLM_kernel;
width_ = width;
height_ = height;
pitch_ = pitch;
frame_used_ = 0;
return g_devices[device_id_].buffers_.AllocPlane(cq_, width_, height_, &plane_);
}
bool MultiFrame::Frame::IsCopyRequired(int &frame_number) {
// BUG: erroneous frames will appear early in clip
// FIX: frame_used_ < 3 is a kludge.
if (frame_used_ < 3 || (frame_number != frame_number_))
return true;
else
return false;
}
result MultiFrame::Frame::CopyTo(int &frame_number, const unsigned char* const source) {
result status = FILTER_OK;
if (IsCopyRequired(frame_number)) {
frame_number_ = frame_number;
status = g_devices[device_id_].buffers_.CopyToPlaneAsynch(plane_, *source, width_, height_, pitch_, &copied_);
} else {
copied_ = NULL;
}
++frame_used_;
return status;
}
void MultiFrame::Frame::Plane(int *plane, cl_event *target_copied) {
*plane = plane_;
*target_copied = copied_;
}
result MultiFrame::Frame::Execute(
const bool &is_sample_equal_to_target,
cl_event *antecedent,
cl_event *executed) {
result status = FILTER_OK;
int sample_equals_target = is_sample_equal_to_target ? k_sample_equals_target : k_sample_is_not_target;
NLM_kernel_.SetNumberedArg(1, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(plane_));
NLM_kernel_.SetNumberedArg(2, sizeof(int), &sample_equals_target);
if (copied_ == NULL && *antecedent == NULL) { // target and sample frame are both on device from prior iteration
status = NLM_kernel_.Execute(cq_, executed);
} else if (*antecedent == NULL) { // target is on device, awaiting sample
status = NLM_kernel_.ExecuteAsynch(cq_, &copied_, executed);
} else if (copied_ == NULL) { // sample is on device, awaiting target
status = NLM_kernel_.ExecuteAsynch(cq_, antecedent, executed);
} else { // awaiting sample and target planes
wait_list_[0] = copied_;
wait_list_[1] = *antecedent;
status = NLM_kernel_.ExecuteWaitList(cq_, 2, wait_list_, executed);
}
return status;
}
<commit_msg>Process target frame last<commit_after>/* Deathray - An Avisynth plug-in filter for spatial/temporal non-local means de-noising.
*
* version 1.01
*
* Copyright 2013, Jawed Ashraf - [email protected]
*/
#include "device.h"
#include "buffer.h"
#include "buffer_map.h"
#include "CLKernel.h"
#include "MultiFrame.h"
extern int g_device_count;
extern device *g_devices;
extern cl_context g_context;
extern int g_gaussian;
MultiFrame::MultiFrame() {
device_id_ = 0;
temporal_radius_ = 0;
frames_.clear();
dest_plane_ = 0;
width_ = 0;
height_ = 0;
src_pitch_ = 0;
dst_pitch_ = 0;
}
result MultiFrame::Init(
const int &device_id,
const int &temporal_radius,
const int &width,
const int &height,
const int &src_pitch,
const int &dst_pitch,
const float &h,
const int &sample_expand,
const int &linear,
const int &correction) {
if (device_id >= g_device_count) return FILTER_ERROR;
result status = FILTER_OK;
device_id_ = device_id;
temporal_radius_ = temporal_radius;
width_ = width;
height_ = height;
src_pitch_ = src_pitch;
dst_pitch_ = dst_pitch;
h_ = h;
cq_ = g_devices[device_id_].cq();
if (width_ == 0 || height_ == 0 || src_pitch_ == 0 || dst_pitch_ == 0 || h == 0 ) return FILTER_INVALID_PARAMETER;
status = InitBuffers();
if (status != FILTER_OK) return status;
status = InitKernels(sample_expand, linear, correction);
if (status != FILTER_OK) return status;
status = InitFrames();
return status;
}
result MultiFrame::InitBuffers() {
result status = FILTER_OK;
// Buffer is sized upwards to the next highest multiple of 32
// horizontally and vertically because tile size is 32x32
intermediate_width_ = ByPowerOf2(width_, 5) >> 2;
intermediate_height_ = ByPowerOf2(height_, 5);
const size_t bytes = intermediate_width_ * intermediate_height_ * sizeof(float) << 2;
status = g_devices[device_id_].buffers_.AllocBuffer(cq_, bytes, &averages_);
if (status != FILTER_OK) return status;
status = g_devices[device_id_].buffers_.AllocBuffer(cq_, bytes, &weights_);
if (status != FILTER_OK) return status;
status = g_devices[device_id_].buffers_.AllocPlane(cq_, width_, height_, &dest_plane_);
return status;
}
result MultiFrame::InitKernels(
const int &sample_expand,
const int &linear,
const int &correction) {
NLM_kernel_ = CLKernel(device_id_, "NLMMultiFrameFourPixel");
NLM_kernel_.SetNumberedArg(3, sizeof(int), &width_);
NLM_kernel_.SetNumberedArg(4, sizeof(int), &height_);
NLM_kernel_.SetNumberedArg(5, sizeof(float), &h_);
NLM_kernel_.SetNumberedArg(6, sizeof(int), &sample_expand);
NLM_kernel_.SetNumberedArg(7, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(g_gaussian));
NLM_kernel_.SetNumberedArg(8, sizeof(int), &intermediate_width_);
NLM_kernel_.SetNumberedArg(9, sizeof(int), &linear);
NLM_kernel_.SetNumberedArg(10, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(averages_));
NLM_kernel_.SetNumberedArg(11, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(weights_));
const size_t set_local_work_size[2] = {8, 32};
const size_t set_scalar_global_size[2] = {width_, height_};
const size_t set_scalar_item_size[2] = {4, 1};
if (NLM_kernel_.arguments_valid()) {
NLM_kernel_.set_work_dim(2);
NLM_kernel_.set_local_work_size(set_local_work_size);
NLM_kernel_.set_scalar_global_size(set_scalar_global_size);
NLM_kernel_.set_scalar_item_size(set_scalar_item_size);
} else {
return FILTER_KERNEL_ARGUMENT_ERROR;
}
finalise_kernel_ = CLKernel(device_id_, "NLMFinalise");
finalise_kernel_.SetNumberedArg(1, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(averages_));
finalise_kernel_.SetNumberedArg(2, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(weights_));
finalise_kernel_.SetNumberedArg(3, sizeof(int), &intermediate_width_);
finalise_kernel_.SetNumberedArg(4, sizeof(int), &linear);
finalise_kernel_.SetNumberedArg(5, sizeof(int), &correction);
finalise_kernel_.SetNumberedArg(6, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(dest_plane_));
if (finalise_kernel_.arguments_valid()) {
finalise_kernel_.set_work_dim(2);
finalise_kernel_.set_local_work_size(set_local_work_size);
finalise_kernel_.set_scalar_global_size(set_scalar_global_size);
finalise_kernel_.set_scalar_item_size(set_scalar_item_size);
} else {
return FILTER_KERNEL_ARGUMENT_ERROR;
}
return FILTER_OK;
}
result MultiFrame::InitFrames() {
const int frame_count = 2 * temporal_radius_ + 1;
frames_.reserve(frame_count);
for (int i = 0; i < frame_count; ++i) {
Frame new_frame;
frames_.push_back(new_frame);
frames_[i].Init(device_id_, &cq_, NLM_kernel_, width_, height_, src_pitch_);
}
if (frames_.size() != frame_count)
return FILTER_MULTI_FRAME_INITIALISATION_FAILED;
return FILTER_OK;
}
result MultiFrame::ZeroIntermediates() {
result status = FILTER_OK;
CLKernel Intermediates = CLKernel(device_id_, "Zero");
Intermediates.SetArg(sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(averages_));
if (Intermediates.arguments_valid()) {
const size_t set_local_work_size[1] = {256};
const size_t set_scalar_global_size[1] = {intermediate_width_ * intermediate_height_ << 2};
const size_t set_scalar_item_size[1] = {4};
Intermediates.set_work_dim(1);
Intermediates.set_local_work_size(set_local_work_size);
Intermediates.set_scalar_global_size(set_scalar_global_size);
Intermediates.set_scalar_item_size(set_scalar_item_size);
status = Intermediates.Execute(cq_, NULL);
if (status != FILTER_OK) return status;
} else {
return FILTER_KERNEL_ARGUMENT_ERROR;
}
Intermediates.SetNumberedArg(0, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(weights_));
if (Intermediates.arguments_valid()) {
status = Intermediates.Execute(cq_, NULL);
if (status != FILTER_OK) return status;
} else {
return FILTER_KERNEL_ARGUMENT_ERROR;
}
clFinish(cq_);
return status;
}
void MultiFrame::SupplyFrameNumbers(
const int &target_frame_number,
MultiFrameRequest *required) {
target_frame_number_ = target_frame_number;
for (int i = -temporal_radius_, frame_id = 0; i <= temporal_radius_; ++i, ++frame_id) {
int frame_number = target_frame_number_ - ((target_frame_number_ - i + temporal_radius_) % frames_.size()) + temporal_radius_;
if (frames_[frame_id].IsCopyRequired(frame_number))
required->Request(frame_number);
}
}
result MultiFrame::CopyTo(MultiFrameRequest *retrieved) {
result status = FILTER_OK;
status = ZeroIntermediates();
if (status != FILTER_OK) return status;
for (int i = -temporal_radius_, frame_id = 0; i <= temporal_radius_; ++i, ++frame_id) {
int frame_number = target_frame_number_ - ((target_frame_number_ - i + temporal_radius_) % frames_.size()) + temporal_radius_;
status = frames_[frame_id].CopyTo(frame_number, retrieved->Retrieve(frame_number));
if (status != FILTER_OK) return status;
}
clFinish(cq_);
return status;
}
result MultiFrame::ExecuteFrame(
const int &frame_id,
const bool &sample_equals_target,
cl_event ©ing_target,
cl_event *filter_events) {
cl_event executed;
result status = frames_[frame_id].Execute(sample_equals_target, ©ing_target, &executed);
filter_events[frame_id] = executed;
return status;
}
result MultiFrame::Execute() {
result status = FILTER_OK;
// Query the Frame object handling the target frame to get the plane for the other Frames to use
int target_frame_id = (target_frame_number_ + temporal_radius_) % frames_.size();
int target_frame_plane;
cl_event copying_target;
frames_[target_frame_id].Plane(&target_frame_plane, ©ing_target);
NLM_kernel_.SetNumberedArg(0, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(target_frame_plane));
cl_event *filter_events = new cl_event[frames_.size()];
for (int i = 0; i < 2 * temporal_radius_ + 1; ++i) {
bool sample_equals_target = i == target_frame_id;
if (!sample_equals_target) { // exclude the target frame so that it is processed last
status = ExecuteFrame(i, sample_equals_target, copying_target, filter_events);
if (status != FILTER_OK) return status;
}
}
status = ExecuteFrame(target_frame_id, true, copying_target, filter_events);
if (status != FILTER_OK) return status;
finalise_kernel_.SetNumberedArg(0, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(target_frame_plane));
status = finalise_kernel_.ExecuteWaitList(cq_, frames_.size(), filter_events, &executed_);
if (status != FILTER_OK) return status;
clFinish(cq_);
return status;
}
result MultiFrame::CopyFrom(
unsigned char *dest,
cl_event *returned) {
return g_devices[device_id_].buffers_.CopyFromPlaneAsynch(dest_plane_,
width_,
height_,
dst_pitch_,
&executed_,
returned,
dest);
}
// Frame
MultiFrame::Frame::Frame() {
frame_number_ = 0;
plane_ = 0;
width_ = 0;
height_ = 0;
pitch_ = 0;
}
result MultiFrame::Frame::Init(
const int &device_id,
cl_command_queue *cq,
const CLKernel &NLM_kernel,
const int &width,
const int &height,
const int &pitch) {
// Setting this frame's NLM_kernel_ to the client's kernel object means all frames share the
// same instance, and therefore each Frame object only needs to do minimal argument
// setup.
device_id_ = device_id;
cq_ = *cq;
NLM_kernel_ = NLM_kernel;
width_ = width;
height_ = height;
pitch_ = pitch;
frame_used_ = 0;
return g_devices[device_id_].buffers_.AllocPlane(cq_, width_, height_, &plane_);
}
bool MultiFrame::Frame::IsCopyRequired(int &frame_number) {
// BUG: erroneous frames will appear early in clip
// FIX: frame_used_ < 3 is a kludge.
if (frame_used_ < 3 || (frame_number != frame_number_))
return true;
else
return false;
}
result MultiFrame::Frame::CopyTo(int &frame_number, const unsigned char* const source) {
result status = FILTER_OK;
if (IsCopyRequired(frame_number)) {
frame_number_ = frame_number;
status = g_devices[device_id_].buffers_.CopyToPlaneAsynch(plane_, *source, width_, height_, pitch_, &copied_);
} else {
copied_ = NULL;
}
++frame_used_;
return status;
}
void MultiFrame::Frame::Plane(int *plane, cl_event *target_copied) {
*plane = plane_;
*target_copied = copied_;
}
result MultiFrame::Frame::Execute(
const bool &is_sample_equal_to_target,
cl_event *antecedent,
cl_event *executed) {
result status = FILTER_OK;
int sample_equals_target = is_sample_equal_to_target ? k_sample_equals_target : k_sample_is_not_target;
NLM_kernel_.SetNumberedArg(1, sizeof(cl_mem), g_devices[device_id_].buffers_.ptr(plane_));
NLM_kernel_.SetNumberedArg(2, sizeof(int), &sample_equals_target);
if (copied_ == NULL && *antecedent == NULL) { // target and sample frame are both on device from prior iteration
status = NLM_kernel_.Execute(cq_, executed);
} else if (*antecedent == NULL) { // target is on device, awaiting sample
status = NLM_kernel_.ExecuteAsynch(cq_, &copied_, executed);
} else if (copied_ == NULL) { // sample is on device, awaiting target
status = NLM_kernel_.ExecuteAsynch(cq_, antecedent, executed);
} else { // awaiting sample and target planes
wait_list_[0] = copied_;
wait_list_[1] = *antecedent;
status = NLM_kernel_.ExecuteWaitList(cq_, 2, wait_list_, executed);
}
return status;
}
<|endoftext|> |
<commit_before>#ifndef ARABICA_PARSERCONFIG_H
#define ARABICA_PARSERCONFIG_H
#ifdef ARABICA_USE_LIBXML2
#include <SAX/wrappers/saxlibxml2.hpp>
#undef DEF_SAX_P
#define DEF_SAX_P libxml2_wrapper
#ifdef _MSC_VER
#pragma message("Including libxml2")
#pragma comment(lib, "libxml2.lib")
#endif
#endif
#ifdef ARABICA_USE_MSXML
#ifndef _MSC_VER
#error "Can only use MSXML on Windows"
#endif
#pragma message("Including MSXML")
#include <SAX/wrappers/saxmsxml2.hpp>
#undef DEF_SAX_P
#define DEF_SAX_P msxml2_wrapper
#endif
#ifdef ARABICA_USE_XERCES
#include <SAX/wrappers/saxxerces.hpp>
#undef DEF_SAX_P
#define DEF_SAX_P xerces_wrapper
#ifdef _MSC_VER
#pragma message("Including Xerces")
#ifdef _DEBUG
#pragma comment(lib, "xerces-c_2D.lib")
#else
#pragma comment(lib, "xerces-c_2.lib")
#endif
#endif
#endif
#ifdef ARABICA_USE_GARDEN
#ifdef _MSC_VER
#pragma message("Including Garden")
#endif
#include <SAX/parsers/saxgarden.hpp>
#undef DEF_SAX_P
#define DEF_SAX_P Garden
#endif
#ifdef ARABICA_USE_EXPAT
#include <SAX/wrappers/saxexpat.hpp>
#undef DEF_SAX_P
#define DEF_SAX_P expat_wrapper
#ifdef _MSC_VER
#pragma message("Including Expat")
#ifndef XML_STATIC
#pragma comment(lib, "libexpat.lib")
#else
#pragma comment(lib, "libexpatMT.lib")
#endif
#endif
#endif
#ifdef _MSC_VER
#pragma comment(lib, "wsock32.lib")
#endif
#ifndef NO_DEFAULT_PARSER
#ifdef DEF_SAX_P
namespace Arabica
{
namespace SAX
{
template<class string_type, class T0 = Arabica::nil_t, class T1 = Arabica::nil_t>
class XMLReader : public DEF_SAX_P<string_type, T0, T1> { };
} // namespace SAX
} // namespace Arabica
#else
#error "No default parser defined."
#endif
#endif
#undef DEF_P
#endif
<commit_msg>On Windows look for Xerces v3, rather than 2.<commit_after>#ifndef ARABICA_PARSERCONFIG_H
#define ARABICA_PARSERCONFIG_H
#ifdef ARABICA_USE_LIBXML2
#include <SAX/wrappers/saxlibxml2.hpp>
#undef DEF_SAX_P
#define DEF_SAX_P libxml2_wrapper
#ifdef _MSC_VER
#pragma message("Including libxml2")
#pragma comment(lib, "libxml2.lib")
#endif
#endif
#ifdef ARABICA_USE_MSXML
#ifndef _MSC_VER
#error "Can only use MSXML on Windows"
#endif
#pragma message("Including MSXML")
#include <SAX/wrappers/saxmsxml2.hpp>
#undef DEF_SAX_P
#define DEF_SAX_P msxml2_wrapper
#endif
#ifdef ARABICA_USE_XERCES
#include <SAX/wrappers/saxxerces.hpp>
#undef DEF_SAX_P
#define DEF_SAX_P xerces_wrapper
#ifdef _MSC_VER
#pragma message("Including Xerces v3")
#ifdef _DEBUG
#pragma comment(lib, "xerces-c_3D.lib")
#else
#pragma comment(lib, "xerces-c_3.lib")
#endif
#endif
#endif
#ifdef ARABICA_USE_GARDEN
#ifdef _MSC_VER
#pragma message("Including Garden")
#endif
#include <SAX/parsers/saxgarden.hpp>
#undef DEF_SAX_P
#define DEF_SAX_P Garden
#endif
#ifdef ARABICA_USE_EXPAT
#include <SAX/wrappers/saxexpat.hpp>
#undef DEF_SAX_P
#define DEF_SAX_P expat_wrapper
#ifdef _MSC_VER
#pragma message("Including Expat")
#ifndef XML_STATIC
#pragma comment(lib, "libexpat.lib")
#else
#pragma comment(lib, "libexpatMT.lib")
#endif
#endif
#endif
#ifdef _MSC_VER
#pragma comment(lib, "wsock32.lib")
#endif
#ifndef NO_DEFAULT_PARSER
#ifdef DEF_SAX_P
namespace Arabica
{
namespace SAX
{
template<class string_type, class T0 = Arabica::nil_t, class T1 = Arabica::nil_t>
class XMLReader : public DEF_SAX_P<string_type, T0, T1> { };
} // namespace SAX
} // namespace Arabica
#else
#error "No default parser defined."
#endif
#endif
#undef DEF_P
#endif
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <gtest/gtest.h>
#include <moveit/mesh_filter/mesh_filter.h>
#include <moveit/mesh_filter/stereo_camera_model.h>
#include <geometric_shapes/shapes.h>
#include <geometric_shapes/shape_operations.h>
#include <eigen3/Eigen/Eigen>
#include <vector>
using namespace mesh_filter;
using namespace Eigen;
using namespace std;
using namespace boost;
namespace mesh_filter_test
{
template<typename Type> inline const Type getRandomNumber (const Type& min, const Type& max)
{
return Type(min + (max-min) * double(rand ()) / double(RAND_MAX));
}
template<typename Type>
class FilterTraits
{
public:
static const GLushort GL_TYPE = GL_ZERO;
};
template<>
class FilterTraits<unsigned short>
{
public:
static const GLushort GL_TYPE = GL_UNSIGNED_SHORT;
static const double ToMetricScale = 0.001;
};
template<>
class FilterTraits<float>
{
public:
static const GLushort GL_TYPE = GL_FLOAT;
static const double ToMetricScale = 1.0f;
};
template<typename Type>
class MeshFilterTest : public testing::TestWithParam <double>
{
BOOST_STATIC_ASSERT_MSG (FilterTraits<Type>::GL_TYPE != GL_ZERO, "Only \"float\" and \"unsigned short int\" are allowed.");
public:
MeshFilterTest (unsigned width = 500, unsigned height = 500, double near = 0.5, double far = 5.0, double shadow = 0.1, double epsilon = 1e-7);
void test ();
void setMeshDistance (double distance) { distance_ = distance; }
private:
shapes::Mesh createMesh (double z) const;
bool transform_callback (MeshHandle handle, Affine3d& transform) const;
void getGroundTruth (unsigned int* labels, float* depth) const;
const unsigned int width_;
const unsigned int height_;
const double near_;
const double far_;
const double shadow_;
const double epsilon_;
StereoCameraModel::Parameters sensor_parameters_;
MeshFilter<StereoCameraModel> filter_;
MeshHandle handle_;
vector<Type> sensor_data_;
double distance_;
};
template<typename Type>
MeshFilterTest<Type>::MeshFilterTest (unsigned width, unsigned height, double near, double far, double shadow, double epsilon)
: width_ (width)
, height_ (height)
, near_ (near)
, far_ (far)
, shadow_ (shadow)
, epsilon_ (epsilon)
, sensor_parameters_ (width, height, near_, far_, width >> 1, height >> 1, width >> 1, height >> 1, 0.1, 0.1)
, filter_ (boost::bind(&MeshFilterTest<Type>::transform_callback, this, _1, _2), sensor_parameters_)
, sensor_data_ (width_ * height_)
, distance_ (0.0)
{
filter_.setShadowThreshold (shadow_);
// no padding
filter_.setPaddingOffset (0.0);
filter_.setPaddingScale (0.0);
// create a large plane that covers the whole visible area -> no boundaries
shapes::Mesh mesh = createMesh (0);
handle_ = filter_.addMesh (mesh);
// make it random but reproducable
srand (0);
Type t_near = near_ / FilterTraits<Type>::ToMetricScale;
Type t_far = far_ / FilterTraits<Type>::ToMetricScale;
for (typename vector<Type>::iterator sIt = sensor_data_.begin (); sIt != sensor_data_.end (); ++sIt)
{
do {
*sIt = getRandomNumber<Type> (0.0, 10.0 / FilterTraits<Type>::ToMetricScale);
} while (*sIt == t_near || *sIt == t_far);
}
}
template<typename Type>
shapes::Mesh MeshFilterTest<Type>::createMesh (double z) const
{
shapes::Mesh mesh (4, 4);
mesh.vertices [0] = -5;
mesh.vertices [1] = -5;
mesh.vertices [2] = z;
mesh.vertices [3] = -5;
mesh.vertices [4] = 5;
mesh.vertices [5] = z;
mesh.vertices [6] = 5;
mesh.vertices [7] = 5;
mesh.vertices [8] = z;
mesh.vertices [9] = 5;
mesh.vertices [10] = -5;
mesh.vertices [11] = z;
mesh.triangles [0] = 0;
mesh.triangles [1] = 3;
mesh.triangles [2] = 2;
mesh.triangles [3] = 0;
mesh.triangles [4] = 2;
mesh.triangles [5] = 1;
mesh.triangles [6] = 0;
mesh.triangles [7] = 2;
mesh.triangles [8] = 3;
mesh.triangles [9] = 0;
mesh.triangles [10] = 1;
mesh.triangles [11] = 2;
mesh.vertex_normals [0] = 0;
mesh.vertex_normals [1] = 0;
mesh.vertex_normals [2] = 1;
mesh.vertex_normals [3] = 0;
mesh.vertex_normals [4] = 0;
mesh.vertex_normals [5] = 1;
mesh.vertex_normals [6] = 0;
mesh.vertex_normals [7] = 0;
mesh.vertex_normals [8] = 1;
mesh.vertex_normals [9] = 0;
mesh.vertex_normals [10] = 0;
mesh.vertex_normals [11] = 1;
return mesh;
}
template<typename Type>
bool MeshFilterTest<Type>::transform_callback (MeshHandle handle, Affine3d& transform) const
{
transform = Affine3d::Identity();
if (handle == handle_)
transform.translation () = Vector3d (0, 0, distance_);
return true;
}
template<typename Type>
void MeshFilterTest<Type>::test ()
{
shapes::Mesh mesh = createMesh (0);
mesh_filter::MeshHandle handle = filter_.addMesh (mesh);
filter_.filter (&sensor_data_[0], FilterTraits<Type>::GL_TYPE, false);
vector<float> gt_depth (width_ * height_);
vector<unsigned int> gt_labels (width_ * height_);
getGroundTruth (>_labels [0], >_depth [0]);
vector<float> filtered_depth (width_ * height_);
vector<unsigned int> filtered_labels (width_ * height_);
filter_.getFilteredDepth (& filtered_depth[0]);
filter_.getFilteredLabels (& filtered_labels[0]);
for (unsigned idx = 0; idx < width_ * height_; ++idx)
{
// Only test if we are not very close to boundaries of object meshes and shadow-boundaries.
float sensor_depth = sensor_data_ [idx] * FilterTraits<Type>::ToMetricScale;
if (fabs(sensor_depth - distance_ - shadow_) > epsilon_ && fabs(sensor_depth - distance_) > epsilon_)
{
// if (filtered_labels [idx] != gt_labels [idx])
// {
// cout << idx << " :: " << filtered_labels [idx] << " vs. " << gt_labels [idx] << " :: " << sensor_data_ [idx] << " = " << filtered_depth [idx] << " vs. " << gt_depth [idx] << endl;
// exit (1);
// }
EXPECT_FLOAT_EQ (filtered_depth [idx], gt_depth [idx]);
EXPECT_EQ (filtered_labels [idx], gt_labels [idx]);
}
}
filter_.removeMesh (handle);
}
template<typename Type>
void MeshFilterTest<Type>::getGroundTruth (unsigned int *labels, float* depth) const
{
const double scale = FilterTraits<Type>::ToMetricScale;
if (distance_ <= near_ || distance_ >= far_)
{
// no filtering is done -> no shadow values or label values
for (unsigned yIdx = 0, idx = 0; yIdx < height_; ++yIdx)
{
for (unsigned xIdx = 0; xIdx < width_; ++xIdx, ++idx)
{
depth[idx] = double(sensor_data_ [idx]) * scale;
if (depth[idx] < near_)
labels [idx] = MeshFilterBase::NearClip;
else if (depth[idx] >= far_)
labels [idx] = MeshFilterBase::FarClip;
else
labels [idx] = MeshFilterBase::Background;
if (depth [idx] <= near_ || depth [idx] >= far_)
depth [idx] = 0;
}
}
}
else
{
for (unsigned yIdx = 0, idx = 0; yIdx < height_; ++yIdx)
{
for (unsigned xIdx = 0; xIdx < width_; ++xIdx, ++idx)
{
depth[idx] = double(sensor_data_ [idx]) * scale;
if (depth [idx] < near_)
{
labels [idx] = MeshFilterBase::NearClip;
depth [idx] = 0;
}
else
{
double diff = depth [idx] - distance_;
if (diff < 0 && depth[idx] < far_)
labels [idx] = MeshFilterBase::Background;
else if (diff > shadow_)
labels [idx] = MeshFilterBase::Shadow;
else if (depth[idx] >= far_)
labels [idx] = MeshFilterBase::FarClip;
else
{
labels [idx] = MeshFilterBase::FirstLabel;
depth [idx] = 0;
}
if (depth[idx] >= far_)
depth[idx] = 0;
}
}
}
}
}
} // namespace mesh_filter_test
typedef mesh_filter_test::MeshFilterTest<float> MeshFilterTestFloat;
TEST_P (MeshFilterTestFloat, float)
{
this->setMeshDistance (this->GetParam ());
this->test ();
}
INSTANTIATE_TEST_CASE_P(float_test, MeshFilterTestFloat, ::testing::Range<double>(0.0f, 6.0f, 0.5f));
typedef mesh_filter_test::MeshFilterTest<unsigned short> MeshFilterTestUnsignedShort;
TEST_P (MeshFilterTestUnsignedShort, unsigned_short)
{
this->setMeshDistance (this->GetParam ());
this->test ();
}
INSTANTIATE_TEST_CASE_P(ushort_test, MeshFilterTestUnsignedShort, ::testing::Range<double>(0.0f, 6.0f, 0.5f));
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
int arg;
return RUN_ALL_TESTS();
}
<commit_msg>GL_TYPE() is a function in newer versions of OpenGL, this fixes tests on Ubuntu 14.04<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <gtest/gtest.h>
#include <moveit/mesh_filter/mesh_filter.h>
#include <moveit/mesh_filter/stereo_camera_model.h>
#include <geometric_shapes/shapes.h>
#include <geometric_shapes/shape_operations.h>
#include <eigen3/Eigen/Eigen>
#include <vector>
using namespace mesh_filter;
using namespace Eigen;
using namespace std;
using namespace boost;
namespace mesh_filter_test
{
template<typename Type> inline const Type getRandomNumber (const Type& min, const Type& max)
{
return Type(min + (max-min) * double(rand ()) / double(RAND_MAX));
}
template<typename Type>
class FilterTraits
{
public:
static const GLushort FILTER_GL_TYPE = GL_ZERO;
};
template<>
class FilterTraits<unsigned short>
{
public:
static const GLushort FILTER_GL_TYPE = GL_UNSIGNED_SHORT;
static const double ToMetricScale = 0.001;
};
template<>
class FilterTraits<float>
{
public:
static const GLushort FILTER_GL_TYPE = GL_FLOAT;
static const double ToMetricScale = 1.0f;
};
template<typename Type>
class MeshFilterTest : public testing::TestWithParam <double>
{
BOOST_STATIC_ASSERT_MSG (FilterTraits<Type>::FILTER_GL_TYPE != GL_ZERO, "Only \"float\" and \"unsigned short int\" are allowed.");
public:
MeshFilterTest (unsigned width = 500, unsigned height = 500, double near = 0.5, double far = 5.0, double shadow = 0.1, double epsilon = 1e-7);
void test ();
void setMeshDistance (double distance) { distance_ = distance; }
private:
shapes::Mesh createMesh (double z) const;
bool transform_callback (MeshHandle handle, Affine3d& transform) const;
void getGroundTruth (unsigned int* labels, float* depth) const;
const unsigned int width_;
const unsigned int height_;
const double near_;
const double far_;
const double shadow_;
const double epsilon_;
StereoCameraModel::Parameters sensor_parameters_;
MeshFilter<StereoCameraModel> filter_;
MeshHandle handle_;
vector<Type> sensor_data_;
double distance_;
};
template<typename Type>
MeshFilterTest<Type>::MeshFilterTest (unsigned width, unsigned height, double near, double far, double shadow, double epsilon)
: width_ (width)
, height_ (height)
, near_ (near)
, far_ (far)
, shadow_ (shadow)
, epsilon_ (epsilon)
, sensor_parameters_ (width, height, near_, far_, width >> 1, height >> 1, width >> 1, height >> 1, 0.1, 0.1)
, filter_ (boost::bind(&MeshFilterTest<Type>::transform_callback, this, _1, _2), sensor_parameters_)
, sensor_data_ (width_ * height_)
, distance_ (0.0)
{
filter_.setShadowThreshold (shadow_);
// no padding
filter_.setPaddingOffset (0.0);
filter_.setPaddingScale (0.0);
// create a large plane that covers the whole visible area -> no boundaries
shapes::Mesh mesh = createMesh (0);
handle_ = filter_.addMesh (mesh);
// make it random but reproducable
srand (0);
Type t_near = near_ / FilterTraits<Type>::ToMetricScale;
Type t_far = far_ / FilterTraits<Type>::ToMetricScale;
for (typename vector<Type>::iterator sIt = sensor_data_.begin (); sIt != sensor_data_.end (); ++sIt)
{
do {
*sIt = getRandomNumber<Type> (0.0, 10.0 / FilterTraits<Type>::ToMetricScale);
} while (*sIt == t_near || *sIt == t_far);
}
}
template<typename Type>
shapes::Mesh MeshFilterTest<Type>::createMesh (double z) const
{
shapes::Mesh mesh (4, 4);
mesh.vertices [0] = -5;
mesh.vertices [1] = -5;
mesh.vertices [2] = z;
mesh.vertices [3] = -5;
mesh.vertices [4] = 5;
mesh.vertices [5] = z;
mesh.vertices [6] = 5;
mesh.vertices [7] = 5;
mesh.vertices [8] = z;
mesh.vertices [9] = 5;
mesh.vertices [10] = -5;
mesh.vertices [11] = z;
mesh.triangles [0] = 0;
mesh.triangles [1] = 3;
mesh.triangles [2] = 2;
mesh.triangles [3] = 0;
mesh.triangles [4] = 2;
mesh.triangles [5] = 1;
mesh.triangles [6] = 0;
mesh.triangles [7] = 2;
mesh.triangles [8] = 3;
mesh.triangles [9] = 0;
mesh.triangles [10] = 1;
mesh.triangles [11] = 2;
mesh.vertex_normals [0] = 0;
mesh.vertex_normals [1] = 0;
mesh.vertex_normals [2] = 1;
mesh.vertex_normals [3] = 0;
mesh.vertex_normals [4] = 0;
mesh.vertex_normals [5] = 1;
mesh.vertex_normals [6] = 0;
mesh.vertex_normals [7] = 0;
mesh.vertex_normals [8] = 1;
mesh.vertex_normals [9] = 0;
mesh.vertex_normals [10] = 0;
mesh.vertex_normals [11] = 1;
return mesh;
}
template<typename Type>
bool MeshFilterTest<Type>::transform_callback (MeshHandle handle, Affine3d& transform) const
{
transform = Affine3d::Identity();
if (handle == handle_)
transform.translation () = Vector3d (0, 0, distance_);
return true;
}
template<typename Type>
void MeshFilterTest<Type>::test ()
{
shapes::Mesh mesh = createMesh (0);
mesh_filter::MeshHandle handle = filter_.addMesh (mesh);
filter_.filter (&sensor_data_[0], FilterTraits<Type>::FILTER_GL_TYPE, false);
vector<float> gt_depth (width_ * height_);
vector<unsigned int> gt_labels (width_ * height_);
getGroundTruth (>_labels [0], >_depth [0]);
vector<float> filtered_depth (width_ * height_);
vector<unsigned int> filtered_labels (width_ * height_);
filter_.getFilteredDepth (& filtered_depth[0]);
filter_.getFilteredLabels (& filtered_labels[0]);
for (unsigned idx = 0; idx < width_ * height_; ++idx)
{
// Only test if we are not very close to boundaries of object meshes and shadow-boundaries.
float sensor_depth = sensor_data_ [idx] * FilterTraits<Type>::ToMetricScale;
if (fabs(sensor_depth - distance_ - shadow_) > epsilon_ && fabs(sensor_depth - distance_) > epsilon_)
{
// if (filtered_labels [idx] != gt_labels [idx])
// {
// cout << idx << " :: " << filtered_labels [idx] << " vs. " << gt_labels [idx] << " :: " << sensor_data_ [idx] << " = " << filtered_depth [idx] << " vs. " << gt_depth [idx] << endl;
// exit (1);
// }
EXPECT_FLOAT_EQ (filtered_depth [idx], gt_depth [idx]);
EXPECT_EQ (filtered_labels [idx], gt_labels [idx]);
}
}
filter_.removeMesh (handle);
}
template<typename Type>
void MeshFilterTest<Type>::getGroundTruth (unsigned int *labels, float* depth) const
{
const double scale = FilterTraits<Type>::ToMetricScale;
if (distance_ <= near_ || distance_ >= far_)
{
// no filtering is done -> no shadow values or label values
for (unsigned yIdx = 0, idx = 0; yIdx < height_; ++yIdx)
{
for (unsigned xIdx = 0; xIdx < width_; ++xIdx, ++idx)
{
depth[idx] = double(sensor_data_ [idx]) * scale;
if (depth[idx] < near_)
labels [idx] = MeshFilterBase::NearClip;
else if (depth[idx] >= far_)
labels [idx] = MeshFilterBase::FarClip;
else
labels [idx] = MeshFilterBase::Background;
if (depth [idx] <= near_ || depth [idx] >= far_)
depth [idx] = 0;
}
}
}
else
{
for (unsigned yIdx = 0, idx = 0; yIdx < height_; ++yIdx)
{
for (unsigned xIdx = 0; xIdx < width_; ++xIdx, ++idx)
{
depth[idx] = double(sensor_data_ [idx]) * scale;
if (depth [idx] < near_)
{
labels [idx] = MeshFilterBase::NearClip;
depth [idx] = 0;
}
else
{
double diff = depth [idx] - distance_;
if (diff < 0 && depth[idx] < far_)
labels [idx] = MeshFilterBase::Background;
else if (diff > shadow_)
labels [idx] = MeshFilterBase::Shadow;
else if (depth[idx] >= far_)
labels [idx] = MeshFilterBase::FarClip;
else
{
labels [idx] = MeshFilterBase::FirstLabel;
depth [idx] = 0;
}
if (depth[idx] >= far_)
depth[idx] = 0;
}
}
}
}
}
} // namespace mesh_filter_test
typedef mesh_filter_test::MeshFilterTest<float> MeshFilterTestFloat;
TEST_P (MeshFilterTestFloat, float)
{
this->setMeshDistance (this->GetParam ());
this->test ();
}
INSTANTIATE_TEST_CASE_P(float_test, MeshFilterTestFloat, ::testing::Range<double>(0.0f, 6.0f, 0.5f));
typedef mesh_filter_test::MeshFilterTest<unsigned short> MeshFilterTestUnsignedShort;
TEST_P (MeshFilterTestUnsignedShort, unsigned_short)
{
this->setMeshDistance (this->GetParam ());
this->test ();
}
INSTANTIATE_TEST_CASE_P(ushort_test, MeshFilterTestUnsignedShort, ::testing::Range<double>(0.0f, 6.0f, 0.5f));
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
int arg;
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/**
* @file
* FunctionBlockTest.cpp
*
* @date: Dec 18, 2013
* @author: sblume
*/
#include "FunctionBlockTest.h"
#include "brics_3d/core/Logger.h"
#include "brics_3d/worldModel/sceneGraph/DotGraphGenerator.h"
namespace unitTests {
// Registers the fixture into the 'registry'
CPPUNIT_TEST_SUITE_REGISTRATION( FunctionBlockTest );
void FunctionBlockTest::setUp() {
wm = new brics_3d::WorldModel();
// functionBlockFile = "cppdemo";
functionBlockFile = "testblock";
blockRepositoryPath = "/opt/src/sandbox/brics_3d_function_blocks/lib/";
brics_3d::Logger::setMinLoglevel(brics_3d::Logger::LOGDEBUG);
}
void FunctionBlockTest::tearDown() {
delete wm;
brics_3d::Logger::setMinLoglevel(brics_3d::Logger::WARNING);
}
void FunctionBlockTest::testFunctionBlockLoader() {
CPPUNIT_ASSERT(!wm->loadFunctionBlock("wrongFileName"));
CPPUNIT_ASSERT(wm->loadFunctionBlock(functionBlockFile, blockRepositoryPath));
}
void FunctionBlockTest::testFunctionBlockExecution() {
CPPUNIT_ASSERT(wm->loadFunctionBlock(functionBlockFile, blockRepositoryPath));
vector<brics_3d::rsg::Id> input;
input.push_back(wm->getRootNodeId()); // input hook
input.push_back(wm->getRootNodeId()); // output hook
vector<brics_3d::rsg::Id> output;
CPPUNIT_ASSERT(!wm->executeFunctionBlock("wrongFileName", input, output));
CPPUNIT_ASSERT(wm->executeFunctionBlock(functionBlockFile, input, output));
CPPUNIT_ASSERT(wm->executeFunctionBlock(functionBlockFile, input, output));
CPPUNIT_ASSERT(wm->executeFunctionBlock(functionBlockFile, input, output));
}
void FunctionBlockTest::testExternalFunctionBlockExecution() {
// string blockName = "cppdemo";
// string blockPath = "/home/sblume/sandbox/microblx/microblx/std_blocks/cppdemo/";
string blockName = "roifilter";//"testblock";
string blockPath = blockRepositoryPath;
CPPUNIT_ASSERT(wm->loadFunctionBlock(blockName, blockPath));
brics_3d::rsg::Id pc1Id = 1025;
brics_3d::PointCloud3D::PointCloud3DPtr pointCloud1(new brics_3d::PointCloud3D());
pointCloud1->addPoint(brics_3d::Point3D(1,2,3));
brics_3d::rsg::PointCloud<brics_3d::PointCloud3D>::PointCloudPtr pc1Container(new brics_3d::rsg::PointCloud<brics_3d::PointCloud3D>());
pc1Container->data = pointCloud1;
std::vector<brics_3d::rsg::Attribute> tmpAttributes;
tmpAttributes.clear();
tmpAttributes.push_back(brics_3d::rsg::Attribute("name","point_cloud1"));
wm->scene.addGeometricNode(wm->getRootNodeId(), pc1Id, tmpAttributes, pc1Container, brics_3d::rsg::TimeStamp(0.0)/*, true*/);
/* Just print what the world model has to offer. */
brics_3d::rsg::DotGraphGenerator* wmPrinter = new brics_3d::rsg::DotGraphGenerator();
wmPrinter->reset();
brics_3d::rsg::VisualizationConfiguration config;
config.abbreviateIds = false;
wmPrinter->setConfig(config);
wm->scene.executeGraphTraverser(wmPrinter, wm->getRootNodeId());
LOG(DEBUG) << "testExternalFunctionBlockExecution: Current state of the world model: " << std::endl << wmPrinter->getDotGraph();
vector<brics_3d::rsg::Id> input;
brics_3d::rsg::Id inputHook = pc1Id;//1042; //wm->getRootNodeId();
brics_3d::rsg::Id outputHook = wm->getRootNodeId();
input.push_back(outputHook); // output input hook
input.push_back(inputHook); // input hook
vector<brics_3d::rsg::Id> output;
CPPUNIT_ASSERT(wm->executeFunctionBlock(blockName, input, output));
wmPrinter->reset();
wm->scene.executeGraphTraverser(wmPrinter, wm->getRootNodeId());
LOG(DEBUG) << "testExternalFunctionBlockExecution: Current state of the world model: " << std::endl << wmPrinter->getDotGraph();
/* modify mw */
brics_3d::rsg::Id groupId = 0;
std::vector<brics_3d::rsg::Attribute> attributes;
attributes.push_back(brics_3d::rsg::Attribute("name","test_group1"));
wm->scene.addGroup(wm->getRootNodeId(), groupId, attributes);
wmPrinter->reset();
wm->scene.executeGraphTraverser(wmPrinter, wm->getRootNodeId());
LOG(DEBUG) << "testExternalFunctionBlockExecution: Current state of the world model: " << std::endl << wmPrinter->getDotGraph();
output.clear();
CPPUNIT_ASSERT_EQUAL(0u, static_cast<unsigned int>(output.size()));
CPPUNIT_ASSERT(wm->executeFunctionBlock(blockName, input, output));
CPPUNIT_ASSERT_EQUAL(2u, static_cast<unsigned int>(output.size()));
CPPUNIT_ASSERT(output[0] == outputHook);
LOG(DEBUG) << "testExternalFunctionBlockExecution: result ID: " << output[1];
wmPrinter->reset();
wm->scene.executeGraphTraverser(wmPrinter, wm->getRootNodeId());
LOG(DEBUG) << "testExternalFunctionBlockExecution: Current state of the world model: " << std::endl << wmPrinter->getDotGraph();
// CPPUNIT_ASSERT(wm->loadFunctionBlock(blockName, blockPath)); //not yet working
CPPUNIT_ASSERT(wm->executeFunctionBlock(blockName, input, output));
wmPrinter->reset();
wm->scene.executeGraphTraverser(wmPrinter, wm->getRootNodeId());
LOG(DEBUG) << "testExternalFunctionBlockExecution: Current state of the world model: " << std::endl << wmPrinter->getDotGraph();
}
} // namespace unitTests
/* EOF */
<commit_msg>Unit test for function blocks takes FBX_MODULES environment variable into account.<commit_after>/**
* @file
* FunctionBlockTest.cpp
*
* @date: Dec 18, 2013
* @author: sblume
*/
#include "FunctionBlockTest.h"
#include "brics_3d/core/Logger.h"
#include "brics_3d/worldModel/sceneGraph/DotGraphGenerator.h"
namespace unitTests {
// Registers the fixture into the 'registry'
CPPUNIT_TEST_SUITE_REGISTRATION( FunctionBlockTest );
void FunctionBlockTest::setUp() {
wm = new brics_3d::WorldModel();
// functionBlockFile = "cppdemo";
/*
* NOTE: This one is located in the brics_3d_function_blocks repository.
* If it is not installed the tests will fail.
*/
functionBlockFile = "testblock";
if(getenv("FBX_MODULES") != 0) {
string functionBlocksModulesPath(getenv("FBX_MODULES"));
blockRepositoryPath = functionBlocksModulesPath + "/lib/";
} else {
blockRepositoryPath = "/opt/src/sandbox/brics_3d_function_blocks/lib/";
}
brics_3d::Logger::setMinLoglevel(brics_3d::Logger::LOGDEBUG);
}
void FunctionBlockTest::tearDown() {
delete wm;
brics_3d::Logger::setMinLoglevel(brics_3d::Logger::WARNING);
}
void FunctionBlockTest::testFunctionBlockLoader() {
CPPUNIT_ASSERT(!wm->loadFunctionBlock("wrongFileName"));
CPPUNIT_ASSERT(wm->loadFunctionBlock(functionBlockFile, blockRepositoryPath));
}
void FunctionBlockTest::testFunctionBlockExecution() {
CPPUNIT_ASSERT(wm->loadFunctionBlock(functionBlockFile, blockRepositoryPath));
vector<brics_3d::rsg::Id> input;
input.push_back(wm->getRootNodeId()); // input hook
input.push_back(wm->getRootNodeId()); // output hook
vector<brics_3d::rsg::Id> output;
CPPUNIT_ASSERT(!wm->executeFunctionBlock("wrongFileName", input, output));
CPPUNIT_ASSERT(wm->executeFunctionBlock(functionBlockFile, input, output));
CPPUNIT_ASSERT(wm->executeFunctionBlock(functionBlockFile, input, output));
CPPUNIT_ASSERT(wm->executeFunctionBlock(functionBlockFile, input, output));
}
void FunctionBlockTest::testExternalFunctionBlockExecution() {
string blockName = "roifilter";//"testblock";
string blockPath = blockRepositoryPath;
CPPUNIT_ASSERT(wm->loadFunctionBlock(blockName, blockPath));
brics_3d::rsg::Id pc1Id = 1025;
brics_3d::PointCloud3D::PointCloud3DPtr pointCloud1(new brics_3d::PointCloud3D());
pointCloud1->addPoint(brics_3d::Point3D(1,2,3));
brics_3d::rsg::PointCloud<brics_3d::PointCloud3D>::PointCloudPtr pc1Container(new brics_3d::rsg::PointCloud<brics_3d::PointCloud3D>());
pc1Container->data = pointCloud1;
std::vector<brics_3d::rsg::Attribute> tmpAttributes;
tmpAttributes.clear();
tmpAttributes.push_back(brics_3d::rsg::Attribute("name","point_cloud1"));
wm->scene.addGeometricNode(wm->getRootNodeId(), pc1Id, tmpAttributes, pc1Container, brics_3d::rsg::TimeStamp(0.0)/*, true*/);
/* Just print what the world model has to offer. */
brics_3d::rsg::DotGraphGenerator* wmPrinter = new brics_3d::rsg::DotGraphGenerator();
wmPrinter->reset();
brics_3d::rsg::VisualizationConfiguration config;
config.abbreviateIds = false;
wmPrinter->setConfig(config);
wm->scene.executeGraphTraverser(wmPrinter, wm->getRootNodeId());
LOG(DEBUG) << "testExternalFunctionBlockExecution: Current state of the world model: " << std::endl << wmPrinter->getDotGraph();
vector<brics_3d::rsg::Id> input;
brics_3d::rsg::Id inputHook = pc1Id;//1042; //wm->getRootNodeId();
brics_3d::rsg::Id outputHook = wm->getRootNodeId();
input.push_back(outputHook); // output input hook
input.push_back(inputHook); // input hook
vector<brics_3d::rsg::Id> output;
CPPUNIT_ASSERT(wm->executeFunctionBlock(blockName, input, output));
wmPrinter->reset();
wm->scene.executeGraphTraverser(wmPrinter, wm->getRootNodeId());
LOG(DEBUG) << "testExternalFunctionBlockExecution: Current state of the world model: " << std::endl << wmPrinter->getDotGraph();
/* modify mw */
brics_3d::rsg::Id groupId = 0;
std::vector<brics_3d::rsg::Attribute> attributes;
attributes.push_back(brics_3d::rsg::Attribute("name","test_group1"));
wm->scene.addGroup(wm->getRootNodeId(), groupId, attributes);
wmPrinter->reset();
wm->scene.executeGraphTraverser(wmPrinter, wm->getRootNodeId());
LOG(DEBUG) << "testExternalFunctionBlockExecution: Current state of the world model: " << std::endl << wmPrinter->getDotGraph();
output.clear();
CPPUNIT_ASSERT_EQUAL(0u, static_cast<unsigned int>(output.size()));
CPPUNIT_ASSERT(wm->executeFunctionBlock(blockName, input, output));
CPPUNIT_ASSERT_EQUAL(2u, static_cast<unsigned int>(output.size()));
CPPUNIT_ASSERT(output[0] == outputHook);
LOG(DEBUG) << "testExternalFunctionBlockExecution: result ID: " << output[1];
wmPrinter->reset();
wm->scene.executeGraphTraverser(wmPrinter, wm->getRootNodeId());
LOG(DEBUG) << "testExternalFunctionBlockExecution: Current state of the world model: " << std::endl << wmPrinter->getDotGraph();
// CPPUNIT_ASSERT(wm->loadFunctionBlock(blockName, blockPath)); //not yet working
CPPUNIT_ASSERT(wm->executeFunctionBlock(blockName, input, output));
wmPrinter->reset();
wm->scene.executeGraphTraverser(wmPrinter, wm->getRootNodeId());
LOG(DEBUG) << "testExternalFunctionBlockExecution: Current state of the world model: " << std::endl << wmPrinter->getDotGraph();
}
} // namespace unitTests
/* EOF */
<|endoftext|> |
<commit_before>#ifndef TOUCH_HPP
#define TOUCH_HPP
#include <VBE/math.hpp>
#include <vector>
class InputImpl;
///
/// \brief The Touch class provides support to read multi-touch gestures
///
class Touch {
public:
///
/// \brief The Finger class represents one of the user's fingers
///
class Finger {
public:
///
/// \brief Returns the ID of this fingers
///
int getId() const;
///
/// \brief Returns whether this finger just made contact with the display
///
bool justPressed() const;
///
/// \brief Returns the current position of the finger in normalized (0..1) coordinates
///
vec2f position() const;
///
/// \brief Returns the current movement relative to the last frame
///
vec2f movement() const;
private:
int id;
vec2f pos;
vec2f oldPos;
bool isNew;
friend class Touch;
friend class InputImpl;
};
///
/// \class Finger Window.hpp <VBE/system/Touch.hpp>
/// \ingroup System
///
/// Each user finger is kept track of since the moment of contact untill release, and it will
/// maintain the same ID throughout the whole gesture.
///
/// \see Touch
///
///
/// \brief Returns a vector reference that contains all the currently tracked fingers
///
static const std::vector<Finger>& getFingers();
};
/// \class Touch Touch.hpp <VBE/system/Touch.hpp>
/// \ingroup System
///
/// The total number of fingers is only limited by the actual device.
///
#endif
<commit_msg>Update Touch.hpp<commit_after>#ifndef TOUCH_HPP
#define TOUCH_HPP
#include <VBE/math.hpp>
#include <vector>
class InputImpl;
///
/// \brief The Touch class provides support to read touch and multi-touch screens
///
class Touch {
public:
///
/// \brief The Finger class represents one of the user's fingers
///
class Finger {
public:
///
/// \brief Returns the ID of this finger
///
int getId() const;
///
/// \brief Returns whether this finger just made contact with the display in this frame
///
bool justPressed() const;
///
/// \brief Returns the current position of the finger in normalized (0..1) coordinates
///
vec2f position() const;
///
/// \brief Returns the movement relative to the last frame
///
vec2f movement() const;
private:
int id;
vec2f pos;
vec2f oldPos;
bool isNew;
friend class Touch;
friend class InputImpl;
};
///
/// \class Finger Window.hpp <VBE/system/Touch.hpp>
/// \ingroup System
///
/// Each user finger is tracked from the moment of contact until release, and it will
/// maintain the same ID throughout the whole gesture.
///
/// \see Touch
///
///
/// \brief Returns all the tracked fingers
///
static const std::vector<Finger>& getFingers();
};
/// \class Touch Touch.hpp <VBE/system/Touch.hpp>
/// \ingroup System
///
/// The total number of fingers is only limited by the actual device.
///
#endif
<|endoftext|> |
<commit_before>#include <core/stdafx.h>
#include <core/mapi/cache/namedPropCache.h>
#include <core/mapi/cache/namedProps.h>
#include <core/interpret/guid.h>
#include <core/mapi/mapiMemory.h>
#include <core/mapi/mapiFunctions.h>
#include <core/utility/registry.h>
#include <core/utility/strings.h>
#include <core/utility/output.h>
#include <core/addin/mfcmapi.h>
#include <core/addin/addin.h>
#include <core/utility/error.h>
namespace cache
{
namespace directMapi
{
// Returns a vector of NamedPropCacheEntry for the input tags
// Sourced directly from MAPI
_Check_return_ std::vector<std::shared_ptr<namedPropCacheEntry>>
GetNamesFromIDs(_In_ LPMAPIPROP lpMAPIProp, _In_ LPSPropTagArray* lppPropTags, ULONG ulFlags)
{
if (!lpMAPIProp) return {};
LPMAPINAMEID* lppPropNames = nullptr;
auto ulPropNames = ULONG{};
WC_H_GETPROPS_S(lpMAPIProp->GetNamesFromIDs(lppPropTags, nullptr, ulFlags, &ulPropNames, &lppPropNames));
auto ids = std::vector<std::shared_ptr<namedPropCacheEntry>>{};
if (ulPropNames && lppPropNames)
{
for (ULONG i = 0; i < ulPropNames; i++)
{
auto ulPropID = ULONG{};
if (lppPropTags && *lppPropTags) ulPropID = PROP_ID(mapi::getTag(*lppPropTags, i));
ids.emplace_back(namedPropCacheEntry::make(lppPropNames[i], ulPropID));
}
}
MAPIFreeBuffer(lppPropNames);
return ids;
}
// Returns a vector of NamedPropCacheEntry for the input tags
// Sourced directly from MAPI
_Check_return_ std::vector<std::shared_ptr<namedPropCacheEntry>>
GetNamesFromIDs(_In_ LPMAPIPROP lpMAPIProp, _In_ const std::vector<ULONG> tags, ULONG ulFlags)
{
if (!lpMAPIProp) return {};
auto ids = std::vector<std::shared_ptr<namedPropCacheEntry>>{};
auto ulPropTags = mapi::allocate<LPSPropTagArray>(CbNewSPropTagArray(tags.size()));
if (ulPropTags)
{
ulPropTags->cValues = tags.size();
ULONG i = 0;
for (const auto& tag : tags)
{
mapi::setTag(ulPropTags, i++) = tag;
}
ids = GetNamesFromIDs(lpMAPIProp, &ulPropTags, ulFlags);
}
MAPIFreeBuffer(ulPropTags);
return ids;
}
// Returns a vector of tags for the input names
// Sourced directly from MAPI
_Check_return_ LPSPropTagArray
GetIDsFromNames(_In_ LPMAPIPROP lpMAPIProp, std::vector<MAPINAMEID> nameIDs, ULONG ulFlags)
{
if (!lpMAPIProp) return {};
LPSPropTagArray lpTags = nullptr;
if (nameIDs.empty())
{
WC_H_GETPROPS_S(lpMAPIProp->GetIDsFromNames(0, nullptr, ulFlags, &lpTags));
}
else
{
std::vector<const MAPINAMEID*> lpNameIDs = {};
for (const auto& nameID : nameIDs)
{
lpNameIDs.emplace_back(&nameID);
}
auto names = const_cast<MAPINAMEID**>(lpNameIDs.data());
WC_H_GETPROPS_S(lpMAPIProp->GetIDsFromNames(lpNameIDs.size(), names, ulFlags, &lpTags));
}
return lpTags;
}
} // namespace directMapi
std::list<std::shared_ptr<namedPropCacheEntry>>& namedPropCache::getCache() noexcept
{
// We keep a list of named prop cache entries
static std::list<std::shared_ptr<namedPropCacheEntry>> cache;
return cache;
}
_Check_return_ std::shared_ptr<namedPropCacheEntry>
namedPropCache::find(const std::function<bool(const std::shared_ptr<namedPropCacheEntry>&)>& compare)
{
const auto& cache = getCache();
const auto entry =
find_if(cache.begin(), cache.end(), [compare](const auto& _entry) { return compare(_entry); });
return entry != cache.end() ? *entry : namedPropCacheEntry::empty();
}
_Check_return_ std::shared_ptr<namedPropCacheEntry> namedPropCache::find(
const std::shared_ptr<cache::namedPropCacheEntry>& entry,
bool bMatchSig,
bool bMatchID,
bool bMatchName)
{
return find([&](const auto& _entry) { return _entry->match(entry, bMatchSig, bMatchID, bMatchName); });
}
_Check_return_ std::shared_ptr<namedPropCacheEntry>
namedPropCache::find(_In_ const std::vector<BYTE>& _sig, _In_ const MAPINAMEID& _mapiNameId)
{
return find([&](const auto& _entry) { return _entry->match(_sig, _mapiNameId); });
}
_Check_return_ std::shared_ptr<namedPropCacheEntry>
namedPropCache::find(_In_ const std::vector<BYTE>& _sig, ULONG _ulPropID)
{
return find([&](const auto& _entry) { return _entry->match(_sig, _ulPropID); });
}
_Check_return_ std::shared_ptr<namedPropCacheEntry>
namedPropCache::find(ULONG _ulPropID, _In_ const MAPINAMEID& _mapiNameId)
{
return find([&](const auto& _entry) { return _entry->match(_ulPropID, _mapiNameId); });
}
// Add a mapping to the cache if it doesn't already exist
// If given a signature, we include it in our search.
// If not, we search without it
void namedPropCache::add(std::vector<std::shared_ptr<namedPropCacheEntry>>& entries, const std::vector<BYTE>& sig)
{
auto& cache = getCache();
for (auto& entry : entries)
{
auto match = std::shared_ptr<namedPropCacheEntry>{};
if (sig.empty())
{
match = find(entry, false, true, true);
}
else
{
entry->setSig(sig);
match = find(entry, true, true, true);
}
if (!match || !match->valid())
{
if (fIsSet(output::dbgLevel::NamedPropCacheMisses))
{
const auto mni = entry->getMapiNameId();
const auto names = NameIDToPropNames(mni);
if (names.empty())
{
output::DebugPrint(
output::dbgLevel::NamedPropCacheMisses,
L"add: Caching unknown property 0x%08X %ws\n",
mni->Kind.lID,
guid::GUIDToStringAndName(mni->lpguid).c_str());
}
else
{
output::DebugPrint(
output::dbgLevel::NamedPropCacheMisses,
L"add: Caching property 0x%08X %ws = %ws\n",
mni->Kind.lID,
guid::GUIDToStringAndName(mni->lpguid).c_str(),
names[0].c_str());
}
}
cache.emplace_back(entry);
}
}
}
// If signature is empty then do not use a signature
_Check_return_ std::vector<std::shared_ptr<namedPropCacheEntry>> namedPropCache::GetNamesFromIDs(
_In_ LPMAPIPROP lpMAPIProp,
const std::vector<BYTE>& sig,
_In_ LPSPropTagArray* lppPropTags)
{
if (!lpMAPIProp || !lppPropTags || !*lppPropTags) return {};
// We're going to walk the cache, looking for the values we need. As soon as we have all the values we need, we're done
// If we reach the end of the cache and don't have everything, we set up to make a GetNamesFromIDs call.
auto results = std::vector<std::shared_ptr<namedPropCacheEntry>>{};
const SPropTagArray* lpPropTags = *lppPropTags;
auto misses = std::vector<ULONG>{};
// First pass, find any misses we might have
for (ULONG ulTarget = 0; ulTarget < lpPropTags->cValues; ulTarget++)
{
const auto ulPropTag = mapi::getTag(lpPropTags, ulTarget);
const auto ulPropId = PROP_ID(ulPropTag);
// ...check the cache
const auto lpEntry = find([&](const auto& entry) noexcept { return entry->match(sig, ulPropId); });
if (!lpEntry)
{
misses.emplace_back(ulPropTag);
}
}
// Go to MAPI with whatever's left. We set up for a single call to GetNamesFromIDs.
if (!misses.empty())
{
auto missed = directMapi::GetNamesFromIDs(lpMAPIProp, misses, NULL);
// Cache the results
add(missed, sig);
}
// Second pass, do our lookup with a populated cache
for (ULONG ulTarget = 0; ulTarget < lpPropTags->cValues; ulTarget++)
{
const auto ulPropId = PROP_ID(mapi::getTag(lpPropTags, ulTarget));
// ...check the cache
const auto lpEntry = find([&](const auto& entry) noexcept { return entry->match(sig, ulPropId); });
if (lpEntry)
{
results.emplace_back(lpEntry);
}
else
{
results.emplace_back(namedPropCacheEntry::make(nullptr, ulPropId, sig));
}
}
return results;
}
// If signature is empty then do not use a signature
_Check_return_ LPSPropTagArray namedPropCache::GetIDsFromNames(
_In_ LPMAPIPROP lpMAPIProp,
_In_ const std::vector<BYTE>& sig,
_In_ std::vector<MAPINAMEID> nameIDs,
ULONG ulFlags)
{
if (!lpMAPIProp || !nameIDs.size()) return {};
// We're going to walk the cache, looking for the values we need. As soon as we have all the values we need, we're done
// If we reach the end of the cache and don't have everything, we set up to make a GetIDsFromNames call.
auto misses = std::vector<MAPINAMEID>{};
// First pass, find the tags we don't have cached
for (const auto& nameID : nameIDs)
{
const auto lpEntry = find([&](const auto& entry) noexcept { return entry->match(sig, nameID); });
if (!lpEntry)
{
misses.emplace_back(nameID);
}
}
// Go to MAPI with whatever's left.
if (!misses.empty())
{
auto missed = directMapi::GetIDsFromNames(lpMAPIProp, misses, ulFlags);
if (missed && missed->cValues == misses.size())
{
// Cache the results
auto toCache = std::vector<std::shared_ptr<namedPropCacheEntry>>{};
for (ULONG i = 0; i < misses.size(); i++)
{
toCache.emplace_back(namedPropCacheEntry::make(&misses[i], mapi::getTag(missed, i), sig));
}
add(toCache, sig);
}
MAPIFreeBuffer(missed);
}
// Second pass, do our lookup with a populated cache
auto results = mapi::allocate<LPSPropTagArray>(CbNewSPropTagArray(nameIDs.size()));
results->cValues = nameIDs.size();
ULONG i = 0;
for (const auto nameID : nameIDs)
{
const auto lpEntry = find([&](const auto& entry) noexcept { return entry->match(sig, nameID); });
mapi::setTag(results, i++) = lpEntry ? lpEntry->getPropID() : 0;
}
return results;
}
} // namespace cache<commit_msg>add some validation checks<commit_after>#include <core/stdafx.h>
#include <core/mapi/cache/namedPropCache.h>
#include <core/mapi/cache/namedProps.h>
#include <core/interpret/guid.h>
#include <core/mapi/mapiMemory.h>
#include <core/mapi/mapiFunctions.h>
#include <core/utility/registry.h>
#include <core/utility/strings.h>
#include <core/utility/output.h>
#include <core/addin/mfcmapi.h>
#include <core/addin/addin.h>
#include <core/utility/error.h>
namespace cache
{
namespace directMapi
{
// Returns a vector of NamedPropCacheEntry for the input tags
// Sourced directly from MAPI
_Check_return_ std::vector<std::shared_ptr<namedPropCacheEntry>>
GetNamesFromIDs(_In_ LPMAPIPROP lpMAPIProp, _In_ LPSPropTagArray* lppPropTags, ULONG ulFlags)
{
if (!lpMAPIProp) return {};
LPMAPINAMEID* lppPropNames = nullptr;
auto ulPropNames = ULONG{};
WC_H_GETPROPS_S(lpMAPIProp->GetNamesFromIDs(lppPropTags, nullptr, ulFlags, &ulPropNames, &lppPropNames));
auto ids = std::vector<std::shared_ptr<namedPropCacheEntry>>{};
if (ulPropNames && lppPropNames)
{
for (ULONG i = 0; i < ulPropNames; i++)
{
auto ulPropID = ULONG{};
if (lppPropTags && *lppPropTags) ulPropID = PROP_ID(mapi::getTag(*lppPropTags, i));
ids.emplace_back(namedPropCacheEntry::make(lppPropNames[i], ulPropID));
}
}
MAPIFreeBuffer(lppPropNames);
return ids;
}
// Returns a vector of NamedPropCacheEntry for the input tags
// Sourced directly from MAPI
_Check_return_ std::vector<std::shared_ptr<namedPropCacheEntry>>
GetNamesFromIDs(_In_ LPMAPIPROP lpMAPIProp, _In_ const std::vector<ULONG> tags, ULONG ulFlags)
{
if (!lpMAPIProp) return {};
auto ids = std::vector<std::shared_ptr<namedPropCacheEntry>>{};
auto ulPropTags = mapi::allocate<LPSPropTagArray>(CbNewSPropTagArray(tags.size()));
if (ulPropTags)
{
ulPropTags->cValues = tags.size();
ULONG i = 0;
for (const auto& tag : tags)
{
mapi::setTag(ulPropTags, i++) = tag;
}
ids = GetNamesFromIDs(lpMAPIProp, &ulPropTags, ulFlags);
}
MAPIFreeBuffer(ulPropTags);
return ids;
}
// Returns a vector of tags for the input names
// Sourced directly from MAPI
_Check_return_ LPSPropTagArray
GetIDsFromNames(_In_ LPMAPIPROP lpMAPIProp, std::vector<MAPINAMEID> nameIDs, ULONG ulFlags)
{
if (!lpMAPIProp) return {};
LPSPropTagArray lpTags = nullptr;
if (nameIDs.empty())
{
WC_H_GETPROPS_S(lpMAPIProp->GetIDsFromNames(0, nullptr, ulFlags, &lpTags));
}
else
{
std::vector<const MAPINAMEID*> lpNameIDs = {};
for (const auto& nameID : nameIDs)
{
lpNameIDs.emplace_back(&nameID);
}
auto names = const_cast<MAPINAMEID**>(lpNameIDs.data());
WC_H_GETPROPS_S(lpMAPIProp->GetIDsFromNames(lpNameIDs.size(), names, ulFlags, &lpTags));
}
return lpTags;
}
} // namespace directMapi
std::list<std::shared_ptr<namedPropCacheEntry>>& namedPropCache::getCache() noexcept
{
// We keep a list of named prop cache entries
static std::list<std::shared_ptr<namedPropCacheEntry>> cache;
return cache;
}
_Check_return_ std::shared_ptr<namedPropCacheEntry>
namedPropCache::find(const std::function<bool(const std::shared_ptr<namedPropCacheEntry>&)>& compare)
{
const auto& cache = getCache();
const auto entry =
find_if(cache.begin(), cache.end(), [compare](const auto& _entry) { return compare(_entry); });
return entry != cache.end() ? *entry : namedPropCacheEntry::empty();
}
_Check_return_ std::shared_ptr<namedPropCacheEntry> namedPropCache::find(
const std::shared_ptr<cache::namedPropCacheEntry>& entry,
bool bMatchSig,
bool bMatchID,
bool bMatchName)
{
return find([&](const auto& _entry) { return _entry->match(entry, bMatchSig, bMatchID, bMatchName); });
}
_Check_return_ std::shared_ptr<namedPropCacheEntry>
namedPropCache::find(_In_ const std::vector<BYTE>& _sig, _In_ const MAPINAMEID& _mapiNameId)
{
return find([&](const auto& _entry) { return _entry->match(_sig, _mapiNameId); });
}
_Check_return_ std::shared_ptr<namedPropCacheEntry>
namedPropCache::find(_In_ const std::vector<BYTE>& _sig, ULONG _ulPropID)
{
return find([&](const auto& _entry) { return _entry->match(_sig, _ulPropID); });
}
_Check_return_ std::shared_ptr<namedPropCacheEntry>
namedPropCache::find(ULONG _ulPropID, _In_ const MAPINAMEID& _mapiNameId)
{
return find([&](const auto& _entry) { return _entry->match(_ulPropID, _mapiNameId); });
}
// Add a mapping to the cache if it doesn't already exist
// If given a signature, we include it in our search.
// If not, we search without it
void namedPropCache::add(std::vector<std::shared_ptr<namedPropCacheEntry>>& entries, const std::vector<BYTE>& sig)
{
auto& cache = getCache();
for (auto& entry : entries)
{
auto match = std::shared_ptr<namedPropCacheEntry>{};
if (sig.empty())
{
match = find(entry, false, true, true);
}
else
{
entry->setSig(sig);
match = find(entry, true, true, true);
}
if (!match || !match->valid())
{
if (fIsSet(output::dbgLevel::NamedPropCacheMisses))
{
const auto mni = entry->getMapiNameId();
const auto names = NameIDToPropNames(mni);
if (names.empty())
{
output::DebugPrint(
output::dbgLevel::NamedPropCacheMisses,
L"add: Caching unknown property 0x%08X %ws\n",
mni->Kind.lID,
guid::GUIDToStringAndName(mni->lpguid).c_str());
}
else
{
output::DebugPrint(
output::dbgLevel::NamedPropCacheMisses,
L"add: Caching property 0x%08X %ws = %ws\n",
mni->Kind.lID,
guid::GUIDToStringAndName(mni->lpguid).c_str(),
names[0].c_str());
}
}
cache.emplace_back(entry);
}
}
}
// If signature is empty then do not use a signature
_Check_return_ std::vector<std::shared_ptr<namedPropCacheEntry>> namedPropCache::GetNamesFromIDs(
_In_ LPMAPIPROP lpMAPIProp,
const std::vector<BYTE>& sig,
_In_ LPSPropTagArray* lppPropTags)
{
if (!lpMAPIProp || !lppPropTags || !*lppPropTags) return {};
// We're going to walk the cache, looking for the values we need. As soon as we have all the values we need, we're done
// If we reach the end of the cache and don't have everything, we set up to make a GetNamesFromIDs call.
auto results = std::vector<std::shared_ptr<namedPropCacheEntry>>{};
const SPropTagArray* lpPropTags = *lppPropTags;
auto misses = std::vector<ULONG>{};
// First pass, find any misses we might have
for (ULONG ulTarget = 0; ulTarget < lpPropTags->cValues; ulTarget++)
{
const auto ulPropTag = mapi::getTag(lpPropTags, ulTarget);
const auto ulPropId = PROP_ID(ulPropTag);
// ...check the cache
const auto lpEntry = find([&](const auto& entry) noexcept { return entry->match(sig, ulPropId); });
if (!lpEntry || !lpEntry->valid())
{
misses.emplace_back(ulPropTag);
}
}
// Go to MAPI with whatever's left. We set up for a single call to GetNamesFromIDs.
if (!misses.empty())
{
auto missed = directMapi::GetNamesFromIDs(lpMAPIProp, misses, NULL);
// Cache the results
add(missed, sig);
}
// Second pass, do our lookup with a populated cache
for (ULONG ulTarget = 0; ulTarget < lpPropTags->cValues; ulTarget++)
{
const auto ulPropId = PROP_ID(mapi::getTag(lpPropTags, ulTarget));
// ...check the cache
const auto lpEntry = find([&](const auto& entry) noexcept { return entry->match(sig, ulPropId); });
if (lpEntry)
{
results.emplace_back(lpEntry);
}
else
{
results.emplace_back(namedPropCacheEntry::make(nullptr, ulPropId, sig));
}
}
return results;
}
// If signature is empty then do not use a signature
_Check_return_ LPSPropTagArray namedPropCache::GetIDsFromNames(
_In_ LPMAPIPROP lpMAPIProp,
_In_ const std::vector<BYTE>& sig,
_In_ std::vector<MAPINAMEID> nameIDs,
ULONG ulFlags)
{
if (!lpMAPIProp || !nameIDs.size()) return {};
// We're going to walk the cache, looking for the values we need. As soon as we have all the values we need, we're done
// If we reach the end of the cache and don't have everything, we set up to make a GetIDsFromNames call.
auto misses = std::vector<MAPINAMEID>{};
// First pass, find the tags we don't have cached
for (const auto& nameID : nameIDs)
{
const auto lpEntry = find([&](const auto& entry) noexcept { return entry->match(sig, nameID); });
if (!lpEntry || !lpEntry->valid())
{
misses.emplace_back(nameID);
}
}
// Go to MAPI with whatever's left.
if (!misses.empty())
{
auto missed = directMapi::GetIDsFromNames(lpMAPIProp, misses, ulFlags);
if (missed && missed->cValues == misses.size())
{
// Cache the results
auto toCache = std::vector<std::shared_ptr<namedPropCacheEntry>>{};
for (ULONG i = 0; i < misses.size(); i++)
{
toCache.emplace_back(namedPropCacheEntry::make(&misses[i], mapi::getTag(missed, i), sig));
}
add(toCache, sig);
}
MAPIFreeBuffer(missed);
}
// Second pass, do our lookup with a populated cache
auto results = mapi::allocate<LPSPropTagArray>(CbNewSPropTagArray(nameIDs.size()));
results->cValues = nameIDs.size();
ULONG i = 0;
for (const auto nameID : nameIDs)
{
const auto lpEntry = find([&](const auto& entry) noexcept { return entry->match(sig, nameID); });
mapi::setTag(results, i++) = lpEntry ? lpEntry->getPropID() : 0;
}
return results;
}
} // namespace cache<|endoftext|> |
<commit_before>/*!
* \file dependency_list.hpp
* \brief file dependency_list.hpp
*
* Copyright 2016 by Intel.
*
* Contact: [email protected]
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <[email protected]>
*
*/
#pragma once
#include <string>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include <fastuidraw/util/reference_counted.hpp>
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/util/string_array.hpp>
#include <fastuidraw/glsl/painter_item_shader_glsl.hpp>
namespace fastuidraw { namespace glsl { namespace detail {
template<typename T>
class DependencyListPrivateT
{
public:
void
add_element(c_string name, const reference_counted_ptr<const T> &shader,
const varying_list *varyings);
varying_list
compute_varyings(const varying_list &combine_with) const;
string_array
compute_name_list(void) const;
std::vector<reference_counted_ptr<const T> >
compute_shader_list(void) const;
private:
class PerShader
{
public:
reference_counted_ptr<const T> m_shader;
varying_list m_varyings;
};
class EqClass:public reference_counted<EqClass>::non_concurrent
{
public:
EqClass(void):
m_type(varying_list::interpolator_number_types),
m_added(false)
{}
std::string
extract_double_colon_value(void);
std::set<std::string> m_names;
enum varying_list::interpolator_type_t m_type;
bool m_added;
};
class VaryingTracker
{
public:
void
add_to_tracker(c_string prefix, const varying_list &src);
void
add_varyings_from_tracker(varying_list *dst);
private:
typedef reference_counted_ptr<EqClass> EqClassRef;
static
std::string
make_name(c_string prefix, c_string name);
void
add_varying(const std::string &name,
enum varying_list::interpolator_type_t q);
void
add_alias(const std::string &name, const std::string &src_name);
std::map<std::string, EqClassRef> m_data;
};
static
void
add_varyings(c_string prefix, const varying_list &src, varying_list *dst);
std::map<std::string, PerShader> m_shaders;
};
//////////////////////////////////////////////
// DependencyListPrivateT<T>::EqClass methods
template<typename T>
std::string
DependencyListPrivateT<T>::EqClass::
extract_double_colon_value(void)
{
std::string return_value;
std::set<std::string>::iterator iter;
for (iter = m_names.begin(); iter != m_names.end(); ++iter)
{
if (iter->find("::") != std::string::npos)
{
return_value = *iter;
m_names.erase(iter);
return return_value;
}
}
iter = m_names.begin();
return_value = *iter;
m_names.erase(iter);
return return_value;
}
/////////////////////////////////////////////////////
// DependencyListPrivateT<T>::VaryingTracker methods
template<typename T>
std::string
DependencyListPrivateT<T>::VaryingTracker::
make_name(c_string prefix, c_string name)
{
FASTUIDRAWassert(name);
if (!prefix)
{
return name;
}
std::ostringstream tmp;
tmp << prefix << "::" << name;
return tmp.str();
}
template<typename T>
void
DependencyListPrivateT<T>::VaryingTracker::
add_varying(const std::string &name,
enum varying_list::interpolator_type_t q)
{
EqClassRef &ref(m_data[name]);
if (!ref)
{
ref = FASTUIDRAWnew EqClass();
}
ref->m_names.insert(name);
FASTUIDRAWmessaged_assert(ref->m_type == varying_list::interpolator_number_types
|| ref->m_type == q,
"Shader aliases merge across different varying types");
ref->m_type = q;
}
template<typename T>
void
DependencyListPrivateT<T>::VaryingTracker::
add_alias(const std::string &name, const std::string &src_name)
{
EqClassRef &ref1(m_data[name]);
EqClassRef &ref2(m_data[src_name]);
if (!ref1)
{
ref1 = FASTUIDRAWnew EqClass();
}
if (!ref2)
{
ref2 = FASTUIDRAWnew EqClass();
}
ref1->m_names.insert(name);
ref2->m_names.insert(src_name);
if (&ref1 != &ref2)
{
for (const std::string &nm : ref2->m_names)
{
ref1->m_names.insert(nm);
}
FASTUIDRAWmessaged_assert(ref1->m_type == varying_list::interpolator_number_types
|| ref1->m_type == ref2->m_type,
"Shader aliases merge across different varying types");
if (ref1->m_type == varying_list::interpolator_number_types)
{
ref1->m_type = ref2->m_type;
}
ref2 = ref1;
}
}
template<typename T>
void
DependencyListPrivateT<T>::VaryingTracker::
add_to_tracker(c_string prefix, const varying_list &src)
{
for (unsigned int i = 0; i < varying_list::interpolator_number_types; ++i)
{
enum varying_list::interpolator_type_t q;
q = static_cast<enum varying_list::interpolator_type_t>(i);
for (c_string v : src.varyings(q))
{
add_varying(make_name(prefix, v), q);
}
}
c_array<const c_string> names(src.alias_varying_names());
c_array<const c_string> src_names(src.alias_varying_source_names());
FASTUIDRAWassert(names.size() == src_names.size());
for (unsigned int i = 0; i < names.size(); ++i)
{
add_alias(make_name(prefix, names[i]).c_str(),
make_name(prefix, src_names[i]).c_str());
}
}
template<typename T>
void
DependencyListPrivateT<T>::VaryingTracker::
add_varyings_from_tracker(varying_list *dst)
{
for (const auto &e : m_data)
{
EqClassRef ref(e.second);
FASTUIDRAWassert(ref);
if (!ref->m_added)
{
FASTUIDRAWassert(!ref->m_names.empty());
ref->m_added = true;
FASTUIDRAWmessaged_assert(ref->m_type != varying_list::interpolator_number_types,
"Shader alias chain lacks alias to actual varying");
/* find an entry that does not have :: in it */
std::string vname(ref->extract_double_colon_value());
dst->add_varying(vname.c_str(), ref->m_type);
for (const std::string &nm : ref->m_names)
{
dst->add_varying_alias(nm.c_str(), vname.c_str());
}
}
}
}
/////////////////////////////////////////////
// DependencyListPrivateT<T> methods
template<typename T>
void
DependencyListPrivateT<T>::
add_element(c_string pname,
const reference_counted_ptr<const T> &shader,
const varying_list *varyings)
{
FASTUIDRAWassert(pname && shader);
std::string name(pname);
FASTUIDRAWassert(m_shaders.find(name) == m_shaders.end());
PerShader &sh(m_shaders[name]);
sh.m_shader = shader;
if (varyings)
{
sh.m_varyings = *varyings;
}
}
template<typename T>
string_array
DependencyListPrivateT<T>::
compute_name_list(void) const
{
string_array return_value;
for (const auto &v : m_shaders)
{
return_value.push_back(v.first.c_str());
}
return return_value;
}
template<typename T>
std::vector<reference_counted_ptr<const T> >
DependencyListPrivateT<T>::
compute_shader_list(void) const
{
std::vector<reference_counted_ptr<const T> > return_value;
for (const auto &v : m_shaders)
{
return_value.push_back(v.second.m_shader);
}
return return_value;
}
template<typename T>
varying_list
DependencyListPrivateT<T>::
compute_varyings(const varying_list &combine_with) const
{
VaryingTracker tracker;
varying_list return_value;
for (const auto &v : m_shaders)
{
tracker.add_to_tracker(v.first.c_str(), v.second.m_varyings);
}
tracker.add_to_tracker(nullptr, combine_with);
tracker.add_varyings_from_tracker(&return_value);
return return_value;
}
}}}
<commit_msg>fastuidraw/glsl/dependency_list: bug fix for merging aliases together<commit_after>/*!
* \file dependency_list.hpp
* \brief file dependency_list.hpp
*
* Copyright 2016 by Intel.
*
* Contact: [email protected]
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <[email protected]>
*
*/
#pragma once
#include <string>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include <fastuidraw/util/reference_counted.hpp>
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/util/string_array.hpp>
#include <fastuidraw/glsl/painter_item_shader_glsl.hpp>
namespace fastuidraw { namespace glsl { namespace detail {
template<typename T>
class DependencyListPrivateT
{
public:
void
add_element(c_string name, const reference_counted_ptr<const T> &shader,
const varying_list *varyings);
varying_list
compute_varyings(const varying_list &combine_with) const;
string_array
compute_name_list(void) const;
std::vector<reference_counted_ptr<const T> >
compute_shader_list(void) const;
private:
class PerShader
{
public:
reference_counted_ptr<const T> m_shader;
varying_list m_varyings;
};
class EqClass:public reference_counted<EqClass>::non_concurrent
{
public:
EqClass(void):
m_type(varying_list::interpolator_number_types),
m_added(false)
{}
std::string
extract_double_colon_value(void);
std::set<std::string> m_names;
enum varying_list::interpolator_type_t m_type;
bool m_added;
};
class VaryingTracker
{
public:
void
add_to_tracker(c_string prefix, const varying_list &src);
void
add_varyings_from_tracker(varying_list *dst);
private:
typedef reference_counted_ptr<EqClass> EqClassRef;
static
std::string
make_name(c_string prefix, c_string name);
void
add_varying(const std::string &name,
enum varying_list::interpolator_type_t q);
void
add_alias(const std::string &name, const std::string &src_name);
std::map<std::string, EqClassRef> m_data;
};
static
void
add_varyings(c_string prefix, const varying_list &src, varying_list *dst);
std::map<std::string, PerShader> m_shaders;
};
//////////////////////////////////////////////
// DependencyListPrivateT<T>::EqClass methods
template<typename T>
std::string
DependencyListPrivateT<T>::EqClass::
extract_double_colon_value(void)
{
std::string return_value;
std::set<std::string>::iterator iter;
for (iter = m_names.begin(); iter != m_names.end(); ++iter)
{
if (iter->find("::") != std::string::npos)
{
return_value = *iter;
m_names.erase(iter);
return return_value;
}
}
iter = m_names.begin();
return_value = *iter;
m_names.erase(iter);
return return_value;
}
/////////////////////////////////////////////////////
// DependencyListPrivateT<T>::VaryingTracker methods
template<typename T>
std::string
DependencyListPrivateT<T>::VaryingTracker::
make_name(c_string prefix, c_string name)
{
FASTUIDRAWassert(name);
if (!prefix)
{
return name;
}
std::ostringstream tmp;
tmp << prefix << "::" << name;
return tmp.str();
}
template<typename T>
void
DependencyListPrivateT<T>::VaryingTracker::
add_varying(const std::string &name,
enum varying_list::interpolator_type_t q)
{
EqClassRef &ref(m_data[name]);
if (!ref)
{
ref = FASTUIDRAWnew EqClass();
}
ref->m_names.insert(name);
FASTUIDRAWmessaged_assert(ref->m_type == varying_list::interpolator_number_types
|| ref->m_type == q,
"Shader aliases merge across different varying types");
ref->m_type = q;
}
template<typename T>
void
DependencyListPrivateT<T>::VaryingTracker::
add_alias(const std::string &name, const std::string &src_name)
{
EqClassRef &pref1(m_data[name]);
EqClassRef &pref2(m_data[src_name]);
if (!pref1)
{
pref1 = FASTUIDRAWnew EqClass();
}
if (!pref2)
{
pref2 = FASTUIDRAWnew EqClass();
}
EqClassRef r1(pref1);
EqClassRef r2(pref2);
r1->m_names.insert(name);
r2->m_names.insert(src_name);
if (r1 != r2)
{
for (const std::string &nm : r2->m_names)
{
r1->m_names.insert(nm);
EqClassRef &ref(m_data[nm]);
if (ref != r1)
{
ref = r1;
}
}
FASTUIDRAWmessaged_assert(r1->m_type == varying_list::interpolator_number_types
|| r1->m_type == r2->m_type,
"Shader aliases merge across different varying types");
if (r1->m_type == varying_list::interpolator_number_types)
{
r1->m_type = r2->m_type;
}
}
}
template<typename T>
void
DependencyListPrivateT<T>::VaryingTracker::
add_to_tracker(c_string prefix, const varying_list &src)
{
for (unsigned int i = 0; i < varying_list::interpolator_number_types; ++i)
{
enum varying_list::interpolator_type_t q;
q = static_cast<enum varying_list::interpolator_type_t>(i);
for (c_string v : src.varyings(q))
{
add_varying(make_name(prefix, v), q);
}
}
c_array<const c_string> names(src.alias_varying_names());
c_array<const c_string> src_names(src.alias_varying_source_names());
FASTUIDRAWassert(names.size() == src_names.size());
for (unsigned int i = 0; i < names.size(); ++i)
{
add_alias(make_name(prefix, names[i]).c_str(),
make_name(prefix, src_names[i]).c_str());
}
}
template<typename T>
void
DependencyListPrivateT<T>::VaryingTracker::
add_varyings_from_tracker(varying_list *dst)
{
for (const auto &e : m_data)
{
EqClassRef ref(e.second);
FASTUIDRAWassert(ref);
if (!ref->m_added)
{
FASTUIDRAWassert(!ref->m_names.empty());
ref->m_added = true;
FASTUIDRAWmessaged_assert(ref->m_type != varying_list::interpolator_number_types,
"Shader alias chain lacks alias to actual varying");
/* find an entry that does not have :: in it */
std::string vname(ref->extract_double_colon_value());
dst->add_varying(vname.c_str(), ref->m_type);
for (const std::string &nm : ref->m_names)
{
dst->add_varying_alias(nm.c_str(), vname.c_str());
}
}
}
}
/////////////////////////////////////////////
// DependencyListPrivateT<T> methods
template<typename T>
void
DependencyListPrivateT<T>::
add_element(c_string pname,
const reference_counted_ptr<const T> &shader,
const varying_list *varyings)
{
FASTUIDRAWassert(pname && shader);
std::string name(pname);
FASTUIDRAWassert(m_shaders.find(name) == m_shaders.end());
PerShader &sh(m_shaders[name]);
sh.m_shader = shader;
if (varyings)
{
sh.m_varyings = *varyings;
}
}
template<typename T>
string_array
DependencyListPrivateT<T>::
compute_name_list(void) const
{
string_array return_value;
for (const auto &v : m_shaders)
{
return_value.push_back(v.first.c_str());
}
return return_value;
}
template<typename T>
std::vector<reference_counted_ptr<const T> >
DependencyListPrivateT<T>::
compute_shader_list(void) const
{
std::vector<reference_counted_ptr<const T> > return_value;
for (const auto &v : m_shaders)
{
return_value.push_back(v.second.m_shader);
}
return return_value;
}
template<typename T>
varying_list
DependencyListPrivateT<T>::
compute_varyings(const varying_list &combine_with) const
{
VaryingTracker tracker;
varying_list return_value;
for (const auto &v : m_shaders)
{
tracker.add_to_tracker(v.first.c_str(), v.second.m_varyings);
}
tracker.add_to_tracker(nullptr, combine_with);
tracker.add_varyings_from_tracker(&return_value);
return return_value;
}
}}}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/chrome_launcher.h"
#include <windows.h>
#include <shellapi.h>
#include <shlwapi.h>
#include "policy/policy_constants.h"
// Herein lies stuff selectively stolen from Chrome. We don't pull it in
// directly because all of it results in many things we don't want being
// included as well.
namespace {
// These are the switches we will allow (along with their values) in the
// safe-for-Low-Integrity version of the Chrome command line.
// Including the chrome switch files pulls in a bunch of dependencies sadly, so
// we redefine things here:
const wchar_t* kAllowedSwitches[] = {
L"automation-channel",
L"chrome-frame",
L"chrome-version",
L"disable-background-mode",
L"disable-popup-blocking",
L"disable-print-preview",
L"disable-renderer-accessibility",
L"enable-experimental-extension-apis",
L"force-renderer-accessibility",
L"full-memory-crash-report",
L"lang",
L"no-default-browser-check",
L"no-first-run",
L"noerrdialogs",
L"user-data-dir",
};
const wchar_t kWhitespaceChars[] = {
0x0009, /* <control-0009> to <control-000D> */
0x000A,
0x000B,
0x000C,
0x000D,
0x0020, /* Space */
0x0085, /* <control-0085> */
0x00A0, /* No-Break Space */
0x1680, /* Ogham Space Mark */
0x180E, /* Mongolian Vowel Separator */
0x2000, /* En Quad to Hair Space */
0x2001,
0x2002,
0x2003,
0x2004,
0x2005,
0x2006,
0x2007,
0x2008,
0x2009,
0x200A,
0x200C, /* Zero Width Non-Joiner */
0x2028, /* Line Separator */
0x2029, /* Paragraph Separator */
0x202F, /* Narrow No-Break Space */
0x205F, /* Medium Mathematical Space */
0x3000, /* Ideographic Space */
0
};
const wchar_t kLauncherExeBaseName[] = L"chrome_launcher.exe";
const wchar_t kBrowserProcessExecutableName[] = L"chrome.exe";
} // end namespace
namespace chrome_launcher {
std::wstring TrimWhiteSpace(const wchar_t* input_str) {
std::wstring output;
if (input_str != NULL) {
std::wstring str(input_str);
const std::wstring::size_type first_good_char =
str.find_first_not_of(kWhitespaceChars);
const std::wstring::size_type last_good_char =
str.find_last_not_of(kWhitespaceChars);
if (first_good_char != std::wstring::npos &&
last_good_char != std::wstring::npos &&
last_good_char >= first_good_char) {
// + 1 because find_last_not_of returns the index, and we want the count
output = str.substr(first_good_char,
last_good_char - first_good_char + 1);
}
}
return output;
}
bool IsValidArgument(const std::wstring& arg) {
if (arg.length() < 2) {
return false;
}
for (int i = 0; i < arraysize(kAllowedSwitches); ++i) {
size_t arg_length = lstrlenW(kAllowedSwitches[i]);
if (arg.find(kAllowedSwitches[i], 2) == 2) {
// The argument starts off right, now it must either end here, or be
// followed by an equals sign.
if (arg.length() == (arg_length + 2) ||
(arg.length() > (arg_length + 2) && arg[arg_length+2] == L'=')) {
return true;
}
}
}
return false;
}
bool IsValidCommandLine(const wchar_t* command_line) {
if (command_line == NULL) {
return false;
}
int num_args = 0;
wchar_t** args = NULL;
args = CommandLineToArgvW(command_line, &num_args);
bool success = true;
// Note that we skip args[0] since that is just our executable name and
// doesn't get passed through to Chrome.
for (int i = 1; i < num_args; ++i) {
std::wstring trimmed_arg = TrimWhiteSpace(args[i]);
if (!IsValidArgument(trimmed_arg.c_str())) {
success = false;
break;
}
}
return success;
}
// Looks up optionally configured launch parameters for Chrome that may have
// been set via group policy.
void AppendAdditionalLaunchParameters(std::wstring* command_line) {
static const HKEY kRootKeys[] = {
HKEY_LOCAL_MACHINE,
HKEY_CURRENT_USER
};
std::wstring launch_params_value_name(
&policy::key::kAdditionalLaunchParameters[0],
&policy::key::kAdditionalLaunchParameters[
lstrlenA(policy::key::kAdditionalLaunchParameters)]);
// Used for basic checks since CreateProcess doesn't support command lines
// longer than 0x8000 characters. If we surpass that length, we do not add the
// additional parameters. Because we need to add a space before the
// extra parameters, we use 0x7fff and not 0x8000.
const size_t kMaxChars = 0x7FFF - command_line->size();
HKEY key;
LONG result;
bool found = false;
for (int i = 0; !found && i < arraysize(kRootKeys); ++i) {
result = ::RegOpenKeyExW(kRootKeys[i], policy::kRegistryChromePolicyKey, 0,
KEY_QUERY_VALUE, &key);
if (result == ERROR_SUCCESS) {
DWORD size = 0;
DWORD type = 0;
result = RegQueryValueExW(key, launch_params_value_name.c_str(),
0, &type, NULL, &size);
if (result == ERROR_SUCCESS && type == REG_SZ && size > 0 &&
(size / sizeof(wchar_t)) < kMaxChars) {
// This size includes any terminating null character or characters
// unless the data was stored without them, so for safety we allocate
// one extra char and zero out the buffer.
wchar_t* value = new wchar_t[(size / sizeof(wchar_t)) + 1];
memset(value, 0, size + sizeof(wchar_t));
result = RegQueryValueExW(key, launch_params_value_name.c_str(), 0,
&type, reinterpret_cast<BYTE*>(&value[0]),
&size);
if (result == ERROR_SUCCESS) {
*command_line += L' ';
*command_line += value;
found = true;
}
delete [] value;
}
::RegCloseKey(key);
}
}
}
bool SanitizeAndLaunchChrome(const wchar_t* command_line) {
bool success = false;
if (IsValidCommandLine(command_line)) {
std::wstring chrome_path;
if (GetChromeExecutablePath(&chrome_path)) {
const wchar_t* args = PathGetArgs(command_line);
// Build the command line string with the quoted path to chrome.exe.
std::wstring command_line;
command_line.reserve(chrome_path.size() + 2);
command_line.append(1, L'\"').append(chrome_path).append(1, L'\"');
if (args != NULL) {
command_line += L' ';
command_line += args;
}
// Append parameters that might be set by group policy.
AppendAdditionalLaunchParameters(&command_line);
STARTUPINFO startup_info = {0};
startup_info.cb = sizeof(startup_info);
startup_info.dwFlags = STARTF_USESHOWWINDOW;
startup_info.wShowWindow = SW_SHOW;
PROCESS_INFORMATION process_info = {0};
if (CreateProcess(&chrome_path[0], &command_line[0],
NULL, NULL, FALSE, 0, NULL, NULL,
&startup_info, &process_info)) {
// Close handles.
CloseHandle(process_info.hThread);
CloseHandle(process_info.hProcess);
success = true;
} else {
_ASSERT(FALSE);
}
}
}
return success;
}
bool GetChromeExecutablePath(std::wstring* chrome_path) {
_ASSERT(chrome_path);
wchar_t cur_path[MAX_PATH * 4] = {0};
// Assume that we are always built into an exe.
GetModuleFileName(NULL, cur_path, arraysize(cur_path) / 2);
PathRemoveFileSpec(cur_path);
bool success = false;
if (PathAppend(cur_path, kBrowserProcessExecutableName)) {
if (!PathFileExists(cur_path)) {
// The installation model for Chrome places the DLLs in a versioned
// sub-folder one down from the Chrome executable. If we fail to find
// chrome.exe in the current path, try looking one up and launching that
// instead. In practice, that means we back up two and append the
// executable name again.
PathRemoveFileSpec(cur_path);
PathRemoveFileSpec(cur_path);
PathAppend(cur_path, kBrowserProcessExecutableName);
}
if (PathFileExists(cur_path)) {
*chrome_path = cur_path;
success = true;
}
}
return success;
}
} // namespace chrome_launcher
<commit_msg>Remove useless string copy.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/chrome_launcher.h"
#include <windows.h>
#include <shellapi.h>
#include <shlwapi.h>
#include "policy/policy_constants.h"
// Herein lies stuff selectively stolen from Chrome. We don't pull it in
// directly because all of it results in many things we don't want being
// included as well.
namespace {
// These are the switches we will allow (along with their values) in the
// safe-for-Low-Integrity version of the Chrome command line.
// Including the chrome switch files pulls in a bunch of dependencies sadly, so
// we redefine things here:
const wchar_t* kAllowedSwitches[] = {
L"automation-channel",
L"chrome-frame",
L"chrome-version",
L"disable-background-mode",
L"disable-popup-blocking",
L"disable-print-preview",
L"disable-renderer-accessibility",
L"enable-experimental-extension-apis",
L"force-renderer-accessibility",
L"full-memory-crash-report",
L"lang",
L"no-default-browser-check",
L"no-first-run",
L"noerrdialogs",
L"user-data-dir",
};
const wchar_t kWhitespaceChars[] = {
0x0009, /* <control-0009> to <control-000D> */
0x000A,
0x000B,
0x000C,
0x000D,
0x0020, /* Space */
0x0085, /* <control-0085> */
0x00A0, /* No-Break Space */
0x1680, /* Ogham Space Mark */
0x180E, /* Mongolian Vowel Separator */
0x2000, /* En Quad to Hair Space */
0x2001,
0x2002,
0x2003,
0x2004,
0x2005,
0x2006,
0x2007,
0x2008,
0x2009,
0x200A,
0x200C, /* Zero Width Non-Joiner */
0x2028, /* Line Separator */
0x2029, /* Paragraph Separator */
0x202F, /* Narrow No-Break Space */
0x205F, /* Medium Mathematical Space */
0x3000, /* Ideographic Space */
0
};
const wchar_t kLauncherExeBaseName[] = L"chrome_launcher.exe";
const wchar_t kBrowserProcessExecutableName[] = L"chrome.exe";
} // end namespace
namespace chrome_launcher {
std::wstring TrimWhiteSpace(const wchar_t* input_str) {
std::wstring output;
if (input_str != NULL) {
std::wstring str(input_str);
const std::wstring::size_type first_good_char =
str.find_first_not_of(kWhitespaceChars);
const std::wstring::size_type last_good_char =
str.find_last_not_of(kWhitespaceChars);
if (first_good_char != std::wstring::npos &&
last_good_char != std::wstring::npos &&
last_good_char >= first_good_char) {
// + 1 because find_last_not_of returns the index, and we want the count
output = str.substr(first_good_char,
last_good_char - first_good_char + 1);
}
}
return output;
}
bool IsValidArgument(const std::wstring& arg) {
if (arg.length() < 2) {
return false;
}
for (int i = 0; i < arraysize(kAllowedSwitches); ++i) {
size_t arg_length = lstrlenW(kAllowedSwitches[i]);
if (arg.find(kAllowedSwitches[i], 2) == 2) {
// The argument starts off right, now it must either end here, or be
// followed by an equals sign.
if (arg.length() == (arg_length + 2) ||
(arg.length() > (arg_length + 2) && arg[arg_length+2] == L'=')) {
return true;
}
}
}
return false;
}
bool IsValidCommandLine(const wchar_t* command_line) {
if (command_line == NULL) {
return false;
}
int num_args = 0;
wchar_t** args = NULL;
args = CommandLineToArgvW(command_line, &num_args);
bool success = true;
// Note that we skip args[0] since that is just our executable name and
// doesn't get passed through to Chrome.
for (int i = 1; i < num_args; ++i) {
std::wstring trimmed_arg = TrimWhiteSpace(args[i]);
if (!IsValidArgument(trimmed_arg)) {
success = false;
break;
}
}
return success;
}
// Looks up optionally configured launch parameters for Chrome that may have
// been set via group policy.
void AppendAdditionalLaunchParameters(std::wstring* command_line) {
static const HKEY kRootKeys[] = {
HKEY_LOCAL_MACHINE,
HKEY_CURRENT_USER
};
std::wstring launch_params_value_name(
&policy::key::kAdditionalLaunchParameters[0],
&policy::key::kAdditionalLaunchParameters[
lstrlenA(policy::key::kAdditionalLaunchParameters)]);
// Used for basic checks since CreateProcess doesn't support command lines
// longer than 0x8000 characters. If we surpass that length, we do not add the
// additional parameters. Because we need to add a space before the
// extra parameters, we use 0x7fff and not 0x8000.
const size_t kMaxChars = 0x7FFF - command_line->size();
HKEY key;
LONG result;
bool found = false;
for (int i = 0; !found && i < arraysize(kRootKeys); ++i) {
result = ::RegOpenKeyExW(kRootKeys[i], policy::kRegistryChromePolicyKey, 0,
KEY_QUERY_VALUE, &key);
if (result == ERROR_SUCCESS) {
DWORD size = 0;
DWORD type = 0;
result = RegQueryValueExW(key, launch_params_value_name.c_str(),
0, &type, NULL, &size);
if (result == ERROR_SUCCESS && type == REG_SZ && size > 0 &&
(size / sizeof(wchar_t)) < kMaxChars) {
// This size includes any terminating null character or characters
// unless the data was stored without them, so for safety we allocate
// one extra char and zero out the buffer.
wchar_t* value = new wchar_t[(size / sizeof(wchar_t)) + 1];
memset(value, 0, size + sizeof(wchar_t));
result = RegQueryValueExW(key, launch_params_value_name.c_str(), 0,
&type, reinterpret_cast<BYTE*>(&value[0]),
&size);
if (result == ERROR_SUCCESS) {
*command_line += L' ';
*command_line += value;
found = true;
}
delete [] value;
}
::RegCloseKey(key);
}
}
}
bool SanitizeAndLaunchChrome(const wchar_t* command_line) {
bool success = false;
if (IsValidCommandLine(command_line)) {
std::wstring chrome_path;
if (GetChromeExecutablePath(&chrome_path)) {
const wchar_t* args = PathGetArgs(command_line);
// Build the command line string with the quoted path to chrome.exe.
std::wstring command_line;
command_line.reserve(chrome_path.size() + 2);
command_line.append(1, L'\"').append(chrome_path).append(1, L'\"');
if (args != NULL) {
command_line += L' ';
command_line += args;
}
// Append parameters that might be set by group policy.
AppendAdditionalLaunchParameters(&command_line);
STARTUPINFO startup_info = {0};
startup_info.cb = sizeof(startup_info);
startup_info.dwFlags = STARTF_USESHOWWINDOW;
startup_info.wShowWindow = SW_SHOW;
PROCESS_INFORMATION process_info = {0};
if (CreateProcess(&chrome_path[0], &command_line[0],
NULL, NULL, FALSE, 0, NULL, NULL,
&startup_info, &process_info)) {
// Close handles.
CloseHandle(process_info.hThread);
CloseHandle(process_info.hProcess);
success = true;
} else {
_ASSERT(FALSE);
}
}
}
return success;
}
bool GetChromeExecutablePath(std::wstring* chrome_path) {
_ASSERT(chrome_path);
wchar_t cur_path[MAX_PATH * 4] = {0};
// Assume that we are always built into an exe.
GetModuleFileName(NULL, cur_path, arraysize(cur_path) / 2);
PathRemoveFileSpec(cur_path);
bool success = false;
if (PathAppend(cur_path, kBrowserProcessExecutableName)) {
if (!PathFileExists(cur_path)) {
// The installation model for Chrome places the DLLs in a versioned
// sub-folder one down from the Chrome executable. If we fail to find
// chrome.exe in the current path, try looking one up and launching that
// instead. In practice, that means we back up two and append the
// executable name again.
PathRemoveFileSpec(cur_path);
PathRemoveFileSpec(cur_path);
PathAppend(cur_path, kBrowserProcessExecutableName);
}
if (PathFileExists(cur_path)) {
*chrome_path = cur_path;
success = true;
}
}
return success;
}
} // namespace chrome_launcher
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Copyright (c) 2017 Josef Adamsson, Denise Härnström
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/crystalvisualization/processors/structuremesh.h>
#include <inviwo/core/datastructures/geometry/basicmesh.h>
#include <inviwo/core/interaction/events/pickingevent.h>
#include <inviwo/core/interaction/events/mouseevent.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/datastructures/buffer/buffer.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo StructureMesh::processorInfo_{
"envision.StructureMesh", // Class identifier
"Structure Mesh", // Display name
"Crystal", // Category
CodeState::Experimental, // Code state
Tags::None, // Tags
};
const ProcessorInfo StructureMesh::getProcessorInfo() const {
return processorInfo_;
}
StructureMesh::StructureMesh()
: Processor()
, structure_("coordinates")
, mesh_("mesh")
, scalingFactor_("scalingFactor", "Scaling factor", 1.f)
, basis_("basis", "Basis", glm::mat3x3())
, fullMesh_("fullMesh", "Full mesh", false)
, animation_("animation", "Animation", false)
, timestep_("timestep", "Time step", false)
, enablePicking_("enablePicking", "Enable Picking", false)
, spherePicking_(this, 0, [&](PickingEvent* p) { handlePicking(p); })
, inds_("inds", "Picked atoms") {
addPort(structure_);
addPort(mesh_);
addProperty(scalingFactor_);
addProperty(basis_);
addProperty(fullMesh_);
addProperty(animation_);
addProperty(timestep_);
addProperty(enablePicking_);
addProperty(inds_);
structure_.onChange([&](){
const auto data = structure_.getVectorData();
for(int i = colors_.size(); i < data.size(); ++i) {
colors_.push_back(std::make_unique<FloatVec4Property>("color" + toString(i), "Color " + toString(i),
vec4(1.0f, 1.0f, 1.0f, 1.0f), vec4(0.0f), vec4(1.0f), vec4(0.01f),
InvalidationLevel::InvalidOutput, PropertySemantics::Color));
addProperty(colors_.back().get(), false);
radii_.push_back(std::make_unique<FloatProperty>("radius"+ toString(i), "Atom Radius"+ toString(i), 1.0f));
addProperty(radii_.back().get(), false);
num_.push_back(std::make_unique<IntProperty>("atoms" + toString(i), "Atoms" + toString(i), 0));
addProperty(num_.back().get(), false);
}
int numSpheres = 0;
for (const auto &strucs : structure_)
numSpheres += strucs->size();
spherePicking_.resize(numSpheres);
});
}
void StructureMesh::process() {
if (fullMesh_.get()) {
auto mesh = std::make_shared<BasicMesh>();
mesh_.setData(mesh);
size_t ind = 0;
for (const auto &strucs : structure_) {
for (long long j = 0; j < static_cast<long long>(strucs->size()); ++j) {
auto center = scalingFactor_.get() * basis_.get() * strucs->at(j) - 0.5f * (basis_.get()[0] + basis_.get()[1] + basis_.get()[2]);
BasicMesh::sphere(center, radii_[ind]->get(), colors_[ind]->get(), mesh);
}
++ind;
}
} else {
if (structure_.isChanged() || animation_.isModified() || std::any_of(num_.begin(), num_.end(),
[](const std::unique_ptr<IntProperty>& property) {
return property->isModified();
}) || enablePicking_.isModified()) {
int numSpheres = 0;
size_t pInd = 0;
for (const auto &strucs : structure_) {
if (animation_.get()) {
numSpheres += num_[pInd]->get();
++pInd;
}
else {
numSpheres += strucs->size();
}
}
vertexRAM_ = std::make_shared<BufferRAMPrecision<vec3>>(numSpheres);
colorRAM_ = std::make_shared<BufferRAMPrecision<vec4>>(numSpheres);
radiiRAM_ = std::make_shared<BufferRAMPrecision<float>>(numSpheres);
auto mesh = std::make_shared<Mesh>(DrawType::Points, ConnectivityType::None);
mesh->addBuffer(Mesh::BufferInfo(BufferType::PositionAttrib),
std::make_shared<Buffer<vec3>>(vertexRAM_));
mesh->addBuffer(Mesh::BufferInfo(BufferType::ColorAttrib),
std::make_shared<Buffer<vec4>>(colorRAM_));
mesh->addBuffer(Mesh::BufferInfo(BufferType::NumberOfBufferTypes, 5),
std::make_shared<Buffer<float>>(radiiRAM_));
mesh_.setData(mesh);
if (enablePicking_.get()) {
auto pickingRAM = std::make_shared<BufferRAMPrecision<uint32_t>>(numSpheres);
auto& data = pickingRAM->getDataContainer();
// fill in picking IDs
std::iota(data.begin(), data.end(), static_cast<uint32_t>(spherePicking_.getPickingId(0)));
mesh->addBuffer(Mesh::BufferInfo(BufferType::NumberOfBufferTypes, 4),
std::make_shared<Buffer<uint32_t>>(pickingRAM));
}
}
auto& vertices = vertexRAM_->getDataContainer();
auto& colors = colorRAM_->getDataContainer();
auto& radii = radiiRAM_->getDataContainer();
size_t portInd = 0;
size_t sphereInd = 0;
for (const auto &strucs : structure_) {
long long j_start, j_stop;
j_start = 0;
j_stop = static_cast<long long>(strucs->size());
if (animation_.get()) {
j_start = num_[portInd]->get() * timestep_.get();
j_stop = num_[portInd]->get() * (timestep_.get() + 1);
}
for (long long j = j_start; j < j_stop ; ++j) {
auto center = scalingFactor_.get() * basis_.get() * strucs->at(j); //- 0.5f * (basis_.get()[0] + basis_.get()[1] + basis_.get()[2]);
vertices[sphereInd] = center;
colors[sphereInd] = colors_[portInd]->get();
radii[sphereInd] = radii_[portInd]->get();
++sphereInd;
}
++portInd;
}
if (enablePicking_.get()) {
//Set alpha-layer of picked atoms
if (!inds_.get().empty()) {
for (const auto &ind : inds_.get()) {
if (ind < sphereInd) {
colors[ind].w = 0.5;
}
}
}
}
colorRAM_->getOwner()->invalidateAllOther(colorRAM_.get());
vertexRAM_->getOwner()->invalidateAllOther(vertexRAM_.get());
radiiRAM_->getOwner()->invalidateAllOther(radiiRAM_.get());
invalidate(InvalidationLevel::InvalidOutput);
}
}
void StructureMesh::handlePicking(PickingEvent* p) {
if (enablePicking_.get()) {
if (p->getState() == PickingState::Updated &&
p->getEvent()->hash() == MouseEvent::chash()) {
auto me = p->getEventAs<MouseEvent>();
if ((me->buttonState() & MouseButton::Left) && me->state() != MouseState::Move) {
auto& color = colorRAM_->getDataContainer();
std::vector<int> temp = inds_.get();
auto picked = p->getPickedId();
if( std::none_of(temp.begin(), temp.end(), [&](unsigned int i){return i == picked;}) ) {
temp.push_back(picked);
color[picked].w = 0.5;
} else {
temp.erase(std::remove(temp.begin(), temp.end(), picked), temp.end());
color[picked].w = 1;
}
inds_.set(temp);
colorRAM_->getOwner()->invalidateAllOther(colorRAM_.get());
invalidate(InvalidationLevel::InvalidOutput);
p->markAsUsed();
}
}
}
}
} // namespace
<commit_msg>Update of the BSD2 license.<commit_after>/*********************************************************************************
*
* Copyright (c) 2017 Josef Adamsson, Denise Härnström, Anders Rehult
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2017 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/crystalvisualization/processors/structuremesh.h>
#include <inviwo/core/datastructures/geometry/basicmesh.h>
#include <inviwo/core/interaction/events/pickingevent.h>
#include <inviwo/core/interaction/events/mouseevent.h>
#include <inviwo/core/datastructures/buffer/bufferramprecision.h>
#include <inviwo/core/datastructures/buffer/buffer.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo StructureMesh::processorInfo_{
"envision.StructureMesh", // Class identifier
"Structure Mesh", // Display name
"Crystal", // Category
CodeState::Experimental, // Code state
Tags::None, // Tags
};
const ProcessorInfo StructureMesh::getProcessorInfo() const {
return processorInfo_;
}
StructureMesh::StructureMesh()
: Processor()
, structure_("coordinates")
, mesh_("mesh")
, scalingFactor_("scalingFactor", "Scaling factor", 1.f)
, basis_("basis", "Basis", glm::mat3x3())
, fullMesh_("fullMesh", "Full mesh", false)
, animation_("animation", "Animation", false)
, timestep_("timestep", "Time step", false)
, enablePicking_("enablePicking", "Enable Picking", false)
, spherePicking_(this, 0, [&](PickingEvent* p) { handlePicking(p); })
, inds_("inds", "Picked atoms") {
addPort(structure_);
addPort(mesh_);
addProperty(scalingFactor_);
addProperty(basis_);
addProperty(fullMesh_);
addProperty(animation_);
addProperty(timestep_);
addProperty(enablePicking_);
addProperty(inds_);
structure_.onChange([&](){
const auto data = structure_.getVectorData();
for(int i = colors_.size(); i < data.size(); ++i) {
colors_.push_back(std::make_unique<FloatVec4Property>("color" + toString(i), "Color " + toString(i),
vec4(1.0f, 1.0f, 1.0f, 1.0f), vec4(0.0f), vec4(1.0f), vec4(0.01f),
InvalidationLevel::InvalidOutput, PropertySemantics::Color));
addProperty(colors_.back().get(), false);
radii_.push_back(std::make_unique<FloatProperty>("radius"+ toString(i), "Atom Radius"+ toString(i), 1.0f));
addProperty(radii_.back().get(), false);
num_.push_back(std::make_unique<IntProperty>("atoms" + toString(i), "Atoms" + toString(i), 0));
addProperty(num_.back().get(), false);
}
int numSpheres = 0;
for (const auto &strucs : structure_)
numSpheres += strucs->size();
spherePicking_.resize(numSpheres);
});
}
void StructureMesh::process() {
if (fullMesh_.get()) {
auto mesh = std::make_shared<BasicMesh>();
mesh_.setData(mesh);
size_t ind = 0;
for (const auto &strucs : structure_) {
for (long long j = 0; j < static_cast<long long>(strucs->size()); ++j) {
auto center = scalingFactor_.get() * basis_.get() * strucs->at(j) - 0.5f * (basis_.get()[0] + basis_.get()[1] + basis_.get()[2]);
BasicMesh::sphere(center, radii_[ind]->get(), colors_[ind]->get(), mesh);
}
++ind;
}
} else {
if (structure_.isChanged() || animation_.isModified() || std::any_of(num_.begin(), num_.end(),
[](const std::unique_ptr<IntProperty>& property) {
return property->isModified();
}) || enablePicking_.isModified()) {
int numSpheres = 0;
size_t pInd = 0;
for (const auto &strucs : structure_) {
if (animation_.get()) {
numSpheres += num_[pInd]->get();
++pInd;
}
else {
numSpheres += strucs->size();
}
}
vertexRAM_ = std::make_shared<BufferRAMPrecision<vec3>>(numSpheres);
colorRAM_ = std::make_shared<BufferRAMPrecision<vec4>>(numSpheres);
radiiRAM_ = std::make_shared<BufferRAMPrecision<float>>(numSpheres);
auto mesh = std::make_shared<Mesh>(DrawType::Points, ConnectivityType::None);
mesh->addBuffer(Mesh::BufferInfo(BufferType::PositionAttrib),
std::make_shared<Buffer<vec3>>(vertexRAM_));
mesh->addBuffer(Mesh::BufferInfo(BufferType::ColorAttrib),
std::make_shared<Buffer<vec4>>(colorRAM_));
mesh->addBuffer(Mesh::BufferInfo(BufferType::NumberOfBufferTypes, 5),
std::make_shared<Buffer<float>>(radiiRAM_));
mesh_.setData(mesh);
if (enablePicking_.get()) {
auto pickingRAM = std::make_shared<BufferRAMPrecision<uint32_t>>(numSpheres);
auto& data = pickingRAM->getDataContainer();
// fill in picking IDs
std::iota(data.begin(), data.end(), static_cast<uint32_t>(spherePicking_.getPickingId(0)));
mesh->addBuffer(Mesh::BufferInfo(BufferType::NumberOfBufferTypes, 4),
std::make_shared<Buffer<uint32_t>>(pickingRAM));
}
}
auto& vertices = vertexRAM_->getDataContainer();
auto& colors = colorRAM_->getDataContainer();
auto& radii = radiiRAM_->getDataContainer();
size_t portInd = 0;
size_t sphereInd = 0;
for (const auto &strucs : structure_) {
long long j_start, j_stop;
j_start = 0;
j_stop = static_cast<long long>(strucs->size());
if (animation_.get()) {
j_start = num_[portInd]->get() * timestep_.get();
j_stop = num_[portInd]->get() * (timestep_.get() + 1);
}
for (long long j = j_start; j < j_stop ; ++j) {
auto center = scalingFactor_.get() * basis_.get() * strucs->at(j); //- 0.5f * (basis_.get()[0] + basis_.get()[1] + basis_.get()[2]);
vertices[sphereInd] = center;
colors[sphereInd] = colors_[portInd]->get();
radii[sphereInd] = radii_[portInd]->get();
++sphereInd;
}
++portInd;
}
if (enablePicking_.get()) {
//Set alpha-layer of picked atoms
if (!inds_.get().empty()) {
for (const auto &ind : inds_.get()) {
if (ind < sphereInd) {
colors[ind].w = 0.5;
}
}
}
}
colorRAM_->getOwner()->invalidateAllOther(colorRAM_.get());
vertexRAM_->getOwner()->invalidateAllOther(vertexRAM_.get());
radiiRAM_->getOwner()->invalidateAllOther(radiiRAM_.get());
invalidate(InvalidationLevel::InvalidOutput);
}
}
void StructureMesh::handlePicking(PickingEvent* p) {
if (enablePicking_.get()) {
if (p->getState() == PickingState::Updated &&
p->getEvent()->hash() == MouseEvent::chash()) {
auto me = p->getEventAs<MouseEvent>();
if ((me->buttonState() & MouseButton::Left) && me->state() != MouseState::Move) {
auto& color = colorRAM_->getDataContainer();
std::vector<int> temp = inds_.get();
auto picked = p->getPickedId();
if( std::none_of(temp.begin(), temp.end(), [&](unsigned int i){return i == picked;}) ) {
temp.push_back(picked);
color[picked].w = 0.5;
} else {
temp.erase(std::remove(temp.begin(), temp.end(), picked), temp.end());
color[picked].w = 1;
}
inds_.set(temp);
colorRAM_->getOwner()->invalidateAllOther(colorRAM_.get());
invalidate(InvalidationLevel::InvalidOutput);
p->markAsUsed();
}
}
}
}
} // namespace
<|endoftext|> |
<commit_before>/*************************************************************************/
/* grid_container.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "grid_container.h"
#include "core/templates/rb_set.h"
void GridContainer::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_SORT_CHILDREN: {
RBMap<int, int> col_minw; // Max of min_width of all controls in each col (indexed by col).
RBMap<int, int> row_minh; // Max of min_height of all controls in each row (indexed by row).
RBSet<int> col_expanded; // Columns which have the SIZE_EXPAND flag set.
RBSet<int> row_expanded; // Rows which have the SIZE_EXPAND flag set.
int hsep = get_theme_constant(SNAME("h_separation"));
int vsep = get_theme_constant(SNAME("v_separation"));
int max_col = MIN(get_child_count(), columns);
int max_row = ceil((float)get_child_count() / (float)columns);
// Compute the per-column/per-row data.
int valid_controls_index = 0;
for (int i = 0; i < get_child_count(); i++) {
Control *c = Object::cast_to<Control>(get_child(i));
if (!c || !c->is_visible_in_tree()) {
continue;
}
if (c->is_set_as_top_level()) {
continue;
}
int row = valid_controls_index / columns;
int col = valid_controls_index % columns;
valid_controls_index++;
Size2i ms = c->get_combined_minimum_size();
if (col_minw.has(col)) {
col_minw[col] = MAX(col_minw[col], ms.width);
} else {
col_minw[col] = ms.width;
}
if (row_minh.has(row)) {
row_minh[row] = MAX(row_minh[row], ms.height);
} else {
row_minh[row] = ms.height;
}
if (c->get_h_size_flags() & SIZE_EXPAND) {
col_expanded.insert(col);
}
if (c->get_v_size_flags() & SIZE_EXPAND) {
row_expanded.insert(row);
}
}
// Consider all empty columns expanded.
for (int i = valid_controls_index; i < columns; i++) {
col_expanded.insert(i);
}
// Evaluate the remaining space for expanded columns/rows.
Size2 remaining_space = get_size();
for (const KeyValue<int, int> &E : col_minw) {
if (!col_expanded.has(E.key)) {
remaining_space.width -= E.value;
}
}
for (const KeyValue<int, int> &E : row_minh) {
if (!row_expanded.has(E.key)) {
remaining_space.height -= E.value;
}
}
remaining_space.height -= vsep * MAX(max_row - 1, 0);
remaining_space.width -= hsep * MAX(max_col - 1, 0);
bool can_fit = false;
while (!can_fit && col_expanded.size() > 0) {
// Check if all minwidth constraints are OK if we use the remaining space.
can_fit = true;
int max_index = col_expanded.front()->get();
for (const int &E : col_expanded) {
if (col_minw[E] > col_minw[max_index]) {
max_index = E;
}
if (can_fit && (remaining_space.width / col_expanded.size()) < col_minw[E]) {
can_fit = false;
}
}
// If not, the column with maximum minwidth is not expanded.
if (!can_fit) {
col_expanded.erase(max_index);
remaining_space.width -= col_minw[max_index];
}
}
can_fit = false;
while (!can_fit && row_expanded.size() > 0) {
// Check if all minheight constraints are OK if we use the remaining space.
can_fit = true;
int max_index = row_expanded.front()->get();
for (const int &E : row_expanded) {
if (row_minh[E] > row_minh[max_index]) {
max_index = E;
}
if (can_fit && (remaining_space.height / row_expanded.size()) < row_minh[E]) {
can_fit = false;
}
}
// If not, the row with maximum minheight is not expanded.
if (!can_fit) {
row_expanded.erase(max_index);
remaining_space.height -= row_minh[max_index];
}
}
// Finally, fit the nodes.
int col_remaining_pixel = 0;
int col_expand = 0;
if (col_expanded.size() > 0) {
col_expand = remaining_space.width / col_expanded.size();
col_remaining_pixel = remaining_space.width - col_expanded.size() * col_expand;
}
int row_remaining_pixel = 0;
int row_expand = 0;
if (row_expanded.size() > 0) {
row_expand = remaining_space.height / row_expanded.size();
row_remaining_pixel = remaining_space.height - row_expanded.size() * row_expand;
}
bool rtl = is_layout_rtl();
int col_ofs = 0;
int row_ofs = 0;
// Calculate the index of rows and columns that receive the remaining pixel.
int col_remaining_pixel_index = 0;
for (int i = 0; i < max_col; i++) {
if (col_remaining_pixel == 0) {
break;
}
if (col_expanded.has(i)) {
col_remaining_pixel_index = i + 1;
col_remaining_pixel--;
}
}
int row_remaining_pixel_index = 0;
for (int i = 0; i < max_row; i++) {
if (row_remaining_pixel == 0) {
break;
}
if (row_expanded.has(i)) {
row_remaining_pixel_index = i + 1;
row_remaining_pixel--;
}
}
valid_controls_index = 0;
for (int i = 0; i < get_child_count(); i++) {
Control *c = Object::cast_to<Control>(get_child(i));
if (!c || !c->is_visible_in_tree()) {
continue;
}
int row = valid_controls_index / columns;
int col = valid_controls_index % columns;
valid_controls_index++;
if (col == 0) {
if (rtl) {
col_ofs = get_size().width;
} else {
col_ofs = 0;
}
if (row > 0) {
row_ofs += (row_expanded.has(row - 1) ? row_expand : row_minh[row - 1]) + vsep;
if (row_expanded.has(row - 1) && row - 1 < row_remaining_pixel_index) {
// Apply the remaining pixel of the previous row.
row_ofs++;
}
}
}
Size2 s(col_expanded.has(col) ? col_expand : col_minw[col], row_expanded.has(row) ? row_expand : row_minh[row]);
// Add the remaining pixel to the expanding columns and rows, starting from left and top.
if (col_expanded.has(col) && col < col_remaining_pixel_index) {
s.x++;
}
if (row_expanded.has(row) && row < row_remaining_pixel_index) {
s.y++;
}
if (rtl) {
Point2 p(col_ofs - s.width, row_ofs);
fit_child_in_rect(c, Rect2(p, s));
col_ofs -= s.width + hsep;
} else {
Point2 p(col_ofs, row_ofs);
fit_child_in_rect(c, Rect2(p, s));
col_ofs += s.width + hsep;
}
}
} break;
case NOTIFICATION_THEME_CHANGED: {
update_minimum_size();
} break;
case NOTIFICATION_TRANSLATION_CHANGED:
case NOTIFICATION_LAYOUT_DIRECTION_CHANGED: {
queue_sort();
} break;
}
}
void GridContainer::set_columns(int p_columns) {
ERR_FAIL_COND(p_columns < 1);
columns = p_columns;
queue_sort();
update_minimum_size();
}
int GridContainer::get_columns() const {
return columns;
}
void GridContainer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_columns", "columns"), &GridContainer::set_columns);
ClassDB::bind_method(D_METHOD("get_columns"), &GridContainer::get_columns);
ADD_PROPERTY(PropertyInfo(Variant::INT, "columns", PROPERTY_HINT_RANGE, "1,1024,1"), "set_columns", "get_columns");
}
Size2 GridContainer::get_minimum_size() const {
RBMap<int, int> col_minw;
RBMap<int, int> row_minh;
int hsep = get_theme_constant(SNAME("h_separation"));
int vsep = get_theme_constant(SNAME("v_separation"));
int max_row = 0;
int max_col = 0;
int valid_controls_index = 0;
for (int i = 0; i < get_child_count(); i++) {
Control *c = Object::cast_to<Control>(get_child(i));
if (!c || !c->is_visible()) {
continue;
}
int row = valid_controls_index / columns;
int col = valid_controls_index % columns;
valid_controls_index++;
Size2i ms = c->get_combined_minimum_size();
if (col_minw.has(col)) {
col_minw[col] = MAX(col_minw[col], ms.width);
} else {
col_minw[col] = ms.width;
}
if (row_minh.has(row)) {
row_minh[row] = MAX(row_minh[row], ms.height);
} else {
row_minh[row] = ms.height;
}
max_col = MAX(col, max_col);
max_row = MAX(row, max_row);
}
Size2 ms;
for (const KeyValue<int, int> &E : col_minw) {
ms.width += E.value;
}
for (const KeyValue<int, int> &E : row_minh) {
ms.height += E.value;
}
ms.height += vsep * max_row;
ms.width += hsep * max_col;
return ms;
}
GridContainer::GridContainer() {}
<commit_msg>Fixed bug in grid_container with hidden children<commit_after>/*************************************************************************/
/* grid_container.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "grid_container.h"
#include "core/templates/rb_set.h"
void GridContainer::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_SORT_CHILDREN: {
RBMap<int, int> col_minw; // Max of min_width of all controls in each col (indexed by col).
RBMap<int, int> row_minh; // Max of min_height of all controls in each row (indexed by row).
RBSet<int> col_expanded; // Columns which have the SIZE_EXPAND flag set.
RBSet<int> row_expanded; // Rows which have the SIZE_EXPAND flag set.
int hsep = get_theme_constant(SNAME("h_separation"));
int vsep = get_theme_constant(SNAME("v_separation"));
// Compute the per-column/per-row data.
int valid_controls_index = 0;
for (int i = 0; i < get_child_count(); i++) {
Control *c = Object::cast_to<Control>(get_child(i));
if (!c || !c->is_visible_in_tree()) {
continue;
}
if (c->is_set_as_top_level()) {
continue;
}
int row = valid_controls_index / columns;
int col = valid_controls_index % columns;
valid_controls_index++;
Size2i ms = c->get_combined_minimum_size();
if (col_minw.has(col)) {
col_minw[col] = MAX(col_minw[col], ms.width);
} else {
col_minw[col] = ms.width;
}
if (row_minh.has(row)) {
row_minh[row] = MAX(row_minh[row], ms.height);
} else {
row_minh[row] = ms.height;
}
if (c->get_h_size_flags() & SIZE_EXPAND) {
col_expanded.insert(col);
}
if (c->get_v_size_flags() & SIZE_EXPAND) {
row_expanded.insert(row);
}
}
int max_col = MIN(valid_controls_index, columns);
int max_row = ceil((float)valid_controls_index / (float)columns);
// Consider all empty columns expanded.
for (int i = valid_controls_index; i < columns; i++) {
col_expanded.insert(i);
}
// Evaluate the remaining space for expanded columns/rows.
Size2 remaining_space = get_size();
for (const KeyValue<int, int> &E : col_minw) {
if (!col_expanded.has(E.key)) {
remaining_space.width -= E.value;
}
}
for (const KeyValue<int, int> &E : row_minh) {
if (!row_expanded.has(E.key)) {
remaining_space.height -= E.value;
}
}
remaining_space.height -= vsep * MAX(max_row - 1, 0);
remaining_space.width -= hsep * MAX(max_col - 1, 0);
bool can_fit = false;
while (!can_fit && col_expanded.size() > 0) {
// Check if all minwidth constraints are OK if we use the remaining space.
can_fit = true;
int max_index = col_expanded.front()->get();
for (const int &E : col_expanded) {
if (col_minw[E] > col_minw[max_index]) {
max_index = E;
}
if (can_fit && (remaining_space.width / col_expanded.size()) < col_minw[E]) {
can_fit = false;
}
}
// If not, the column with maximum minwidth is not expanded.
if (!can_fit) {
col_expanded.erase(max_index);
remaining_space.width -= col_minw[max_index];
}
}
can_fit = false;
while (!can_fit && row_expanded.size() > 0) {
// Check if all minheight constraints are OK if we use the remaining space.
can_fit = true;
int max_index = row_expanded.front()->get();
for (const int &E : row_expanded) {
if (row_minh[E] > row_minh[max_index]) {
max_index = E;
}
if (can_fit && (remaining_space.height / row_expanded.size()) < row_minh[E]) {
can_fit = false;
}
}
// If not, the row with maximum minheight is not expanded.
if (!can_fit) {
row_expanded.erase(max_index);
remaining_space.height -= row_minh[max_index];
}
}
// Finally, fit the nodes.
int col_remaining_pixel = 0;
int col_expand = 0;
if (col_expanded.size() > 0) {
col_expand = remaining_space.width / col_expanded.size();
col_remaining_pixel = remaining_space.width - col_expanded.size() * col_expand;
}
int row_remaining_pixel = 0;
int row_expand = 0;
if (row_expanded.size() > 0) {
row_expand = remaining_space.height / row_expanded.size();
row_remaining_pixel = remaining_space.height - row_expanded.size() * row_expand;
}
bool rtl = is_layout_rtl();
int col_ofs = 0;
int row_ofs = 0;
// Calculate the index of rows and columns that receive the remaining pixel.
int col_remaining_pixel_index = 0;
for (int i = 0; i < max_col; i++) {
if (col_remaining_pixel == 0) {
break;
}
if (col_expanded.has(i)) {
col_remaining_pixel_index = i + 1;
col_remaining_pixel--;
}
}
int row_remaining_pixel_index = 0;
for (int i = 0; i < max_row; i++) {
if (row_remaining_pixel == 0) {
break;
}
if (row_expanded.has(i)) {
row_remaining_pixel_index = i + 1;
row_remaining_pixel--;
}
}
valid_controls_index = 0;
for (int i = 0; i < get_child_count(); i++) {
Control *c = Object::cast_to<Control>(get_child(i));
if (!c || !c->is_visible_in_tree()) {
continue;
}
int row = valid_controls_index / columns;
int col = valid_controls_index % columns;
valid_controls_index++;
if (col == 0) {
if (rtl) {
col_ofs = get_size().width;
} else {
col_ofs = 0;
}
if (row > 0) {
row_ofs += (row_expanded.has(row - 1) ? row_expand : row_minh[row - 1]) + vsep;
if (row_expanded.has(row - 1) && row - 1 < row_remaining_pixel_index) {
// Apply the remaining pixel of the previous row.
row_ofs++;
}
}
}
Size2 s(col_expanded.has(col) ? col_expand : col_minw[col], row_expanded.has(row) ? row_expand : row_minh[row]);
// Add the remaining pixel to the expanding columns and rows, starting from left and top.
if (col_expanded.has(col) && col < col_remaining_pixel_index) {
s.x++;
}
if (row_expanded.has(row) && row < row_remaining_pixel_index) {
s.y++;
}
if (rtl) {
Point2 p(col_ofs - s.width, row_ofs);
fit_child_in_rect(c, Rect2(p, s));
col_ofs -= s.width + hsep;
} else {
Point2 p(col_ofs, row_ofs);
fit_child_in_rect(c, Rect2(p, s));
col_ofs += s.width + hsep;
}
}
} break;
case NOTIFICATION_THEME_CHANGED: {
update_minimum_size();
} break;
case NOTIFICATION_TRANSLATION_CHANGED:
case NOTIFICATION_LAYOUT_DIRECTION_CHANGED: {
queue_sort();
} break;
}
}
void GridContainer::set_columns(int p_columns) {
ERR_FAIL_COND(p_columns < 1);
columns = p_columns;
queue_sort();
update_minimum_size();
}
int GridContainer::get_columns() const {
return columns;
}
void GridContainer::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_columns", "columns"), &GridContainer::set_columns);
ClassDB::bind_method(D_METHOD("get_columns"), &GridContainer::get_columns);
ADD_PROPERTY(PropertyInfo(Variant::INT, "columns", PROPERTY_HINT_RANGE, "1,1024,1"), "set_columns", "get_columns");
}
Size2 GridContainer::get_minimum_size() const {
RBMap<int, int> col_minw;
RBMap<int, int> row_minh;
int hsep = get_theme_constant(SNAME("h_separation"));
int vsep = get_theme_constant(SNAME("v_separation"));
int max_row = 0;
int max_col = 0;
int valid_controls_index = 0;
for (int i = 0; i < get_child_count(); i++) {
Control *c = Object::cast_to<Control>(get_child(i));
if (!c || !c->is_visible()) {
continue;
}
int row = valid_controls_index / columns;
int col = valid_controls_index % columns;
valid_controls_index++;
Size2i ms = c->get_combined_minimum_size();
if (col_minw.has(col)) {
col_minw[col] = MAX(col_minw[col], ms.width);
} else {
col_minw[col] = ms.width;
}
if (row_minh.has(row)) {
row_minh[row] = MAX(row_minh[row], ms.height);
} else {
row_minh[row] = ms.height;
}
max_col = MAX(col, max_col);
max_row = MAX(row, max_row);
}
Size2 ms;
for (const KeyValue<int, int> &E : col_minw) {
ms.width += E.value;
}
for (const KeyValue<int, int> &E : row_minh) {
ms.height += E.value;
}
ms.height += vsep * max_row;
ms.width += hsep * max_col;
return ms;
}
GridContainer::GridContainer() {}
<|endoftext|> |
<commit_before>/*
KPeople
Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]>
Copyright (C) 2013 Martin Klapetek <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "persondata.h"
#include "persons-model.h"
#include "person-item.h"
#include "persons-presence-model.h"
#include <Nepomuk2/Resource>
#include <Nepomuk2/Query/Query>
#include <Nepomuk2/ResourceManager>
#include <Nepomuk2/ResourceWatcher>
#include <Nepomuk2/Vocabulary/PIMO>
#include <Nepomuk2/Vocabulary/NCO>
#include <Nepomuk2/Vocabulary/NIE>
#include <Nepomuk2/Variant>
#include <Soprano/Model>
#include <Soprano/QueryResultIterator>
#include <KDebug>
using namespace Nepomuk2::Vocabulary;
class PersonDataPrivate {
public:
QString uri;
QString id;
Nepomuk2::Resource res;
};
K_GLOBAL_STATIC(PersonsPresenceModel, s_presenceModel)
PersonData::PersonData(QObject *parent)
: QObject(parent),
d_ptr(new PersonDataPrivate)
{
}
PersonData::PersonData(const QString &uri, QObject *parent)
: QObject(parent),
d_ptr(new PersonDataPrivate)
{
setUri(uri);
}
void PersonData::setContactId(const QString &id)
{
Q_D(PersonData);
if (d->id == id) {
return;
}
d->id = id;
QString query = QString::fromUtf8(
"select DISTINCT ?uri "
"WHERE { "
"?uri a nco:PersonContact. "
"?uri nco:hasContactMedium ?a . "
"?a ?b \"%1\"^^xsd:string . "
"}").arg(id);
Soprano::Model *model = Nepomuk2::ResourceManager::instance()->mainModel();
Soprano::QueryResultIterator it = model->executeQuery(query, Soprano::Query::QueryLanguageSparqlNoInference);
QString uri;
while (it.next()) {
uri = it[0].uri().toString();
}
if (d->uri != uri) {
d->uri = uri;
d->res = Nepomuk2::Resource(uri);
d->res.setWatchEnabled(true);
}
}
QString PersonData::contactId() const
{
Q_D(const PersonData);
return d->id;
}
QString PersonData::uri() const
{
Q_D(const PersonData);
return d->uri;
}
void PersonData::setUri(const QString &uri)
{
Q_D(PersonData);
d->uri = uri;
d->res = Nepomuk2::Resource(uri);
d->res.setWatchEnabled(true);
Nepomuk2::ResourceWatcher *watcher = new Nepomuk2::ResourceWatcher(this);
watcher->addResource(d->res);
connect(watcher, SIGNAL(propertyChanged(Nepomuk2::Resource,Nepomuk2::Types::Property,QVariantList,QVariantList)),
this, SIGNAL(dataChanged()));
connect(s_presenceModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(presenceModelChange(QModelIndex,QModelIndex)));
emit uriChanged();
emit dataChanged();
}
QString PersonData::status() const
{
Q_D(const PersonData);
QStringList presenceList;
if (d->res.type() == PIMO::Person()) {
Q_FOREACH (const Nepomuk2::Resource &resource, d->res.property(PIMO::groundingOccurrence()).toResourceList()) {
if (resource.hasProperty(NCO::hasIMAccount())) {
QString imID = resource.property(NCO::hasIMAccount()).toResource().property(NCO::imID()).toString();
presenceList << s_presenceModel->dataForContactId(imID, PersonsModel::StatusStringRole).toString();
}
}
return findMostOnlinePresence(presenceList);
} else {
QString imID = d->res.property(NCO::hasIMAccount()).toResource().property(NCO::imID()).toString();
return s_presenceModel->dataForContactId(imID, PersonsModel::StatusStringRole).toString();
}
}
QUrl PersonData::avatar() const
{
Q_D(const PersonData);
Nepomuk2::Resource r;
if (d->res.type() == PIMO::Person()) {
Q_FOREACH (const Nepomuk2::Resource &resource, d->res.property(PIMO::groundingOccurrence()).toResourceList()) {
if (resource.hasProperty(NCO::photo())) {
r = resource;
break;
}
}
} else {
r = d->res;
}
return r.property(NCO::photo()).toResource().property(NIE::url()).toUrl();
}
QString PersonData::name() const
{
Q_D(const PersonData);
QString label;
Nepomuk2::Resource r;
if (d->res.type() == PIMO::Person()) {
//simply pick the first GO for now
r = d->res.property(PIMO::groundingOccurrence()).toResource();
} else {
r = d->res;
}
label = r.property(NCO::fullname()).toString();
if (!label.isEmpty()) {
return label;
}
label = r.property(NCO::hasIMAccount()).toResource().property(NCO::imNickname()).toString();
if (!label.isEmpty()) {
return label;
}
return d->res.property(NCO::hasContactMedium()).toResource().genericLabel();
}
QStringList PersonData::emails() const
{
Q_D(const PersonData);
QStringList emails;
if (d->res.type() == PIMO::Person()) {
Q_FOREACH (const Nepomuk2::Resource &resource, d->res.property(PIMO::groundingOccurrence()).toResourceList()) {
if (resource.hasProperty(NCO::hasEmailAddress())) {
Q_FOREACH (const Nepomuk2::Resource &email, resource.property(NCO::hasEmailAddress()).toResourceList()) {
emails << email.property(NCO::emailAddress()).toString();
}
}
}
} else {
if (d->res.hasProperty(NCO::hasEmailAddress())) {
Q_FOREACH (const Nepomuk2::Resource &email, d->res.property(NCO::hasEmailAddress()).toResourceList()) {
emails << email.property(NCO::emailAddress()).toString();
}
}
}
return emails;
}
QStringList PersonData::phones() const
{
Q_D(const PersonData);
QStringList phones;
if (d->res.type() == PIMO::Person()) {
Q_FOREACH (const Nepomuk2::Resource &resource, d->res.property(PIMO::groundingOccurrence()).toResourceList()) {
if (resource.hasProperty(NCO::hasPhoneNumber())) {
Q_FOREACH (const Nepomuk2::Resource &phone, resource.property(NCO::hasPhoneNumber()).toResourceList()) {
phones << phone.property(NCO::phoneNumber()).toString();
}
}
}
} else {
if (d->res.hasProperty(NCO::hasPhoneNumber())) {
Q_FOREACH (const Nepomuk2::Resource &phone, d->res.property(NCO::hasPhoneNumber()).toResourceList()) {
phones << phone.property(NCO::phoneNumber()).toString();
}
}
}
return phones;
}
QStringList PersonData::imAccounts() const
{
Q_D(const PersonData);
QStringList ims;
if (d->res.type() == PIMO::Person()) {
Q_FOREACH (const Nepomuk2::Resource &resource, d->res.property(PIMO::groundingOccurrence()).toResourceList()) {
if (resource.hasProperty(NCO::hasIMAccount())) {
Q_FOREACH (const Nepomuk2::Resource &im, resource.property(NCO::hasIMAccount()).toResourceList()) {
ims << im.property(NCO::imAccountType()).toString();
ims << im.property(NCO::imNickname()).toString();
ims << im.property(NCO::imID()).toString();
}
}
}
} else {
if (d->res.hasProperty(NCO::hasIMAccount())) {
Q_FOREACH (const Nepomuk2::Resource &im, d->res.property(NCO::hasIMAccount()).toResourceList()) {
ims << im.property(NCO::imAccountType()).toString();
ims << im.property(NCO::imNickname()).toString();
ims << im.property(NCO::imID()).toString();
}
}
}
return ims;
}
KDateTime PersonData::birthday() const
{
Q_D(const PersonData);
if (d->res.type() == PIMO::Person()) {
//we'll go through all the dates we have and from every date we
//get msecs from epoch and then we'll check whichever is greater
//If the date has only month and a year, it will be counted
//to 1st day of that month. If the real date is actually 15th day,
//it means the more complete date will have more msecs from the epoch
KDateTime bd;
Q_FOREACH (const Nepomuk2::Resource &resource, d->res.property(PIMO::groundingOccurrence()).toResourceList()) {
if (resource.hasProperty(NCO::birthDate())) {
KDateTime bdTemp(d->res.property(NCO::birthDate()).toDateTime());
if (bdTemp.isValid() && bdTemp.dateTime().toMSecsSinceEpoch() > bd.dateTime().toMSecsSinceEpoch()) {
bd = bdTemp;
}
}
}
return bd;
} else {
return KDateTime(d->res.property(NCO::birthDate()).toDateTime());
}
}
QStringList PersonData::groups() const
{
Q_D(const PersonData);
QStringList groups;
if (d->res.type() == PIMO::Person()) {
Q_FOREACH (const Nepomuk2::Resource &resource, d->res.property(PIMO::groundingOccurrence()).toResourceList()) {
Nepomuk2::Variant groupProperties = resource.property(NCO::belongsToGroup());
if (!groupProperties.isValid()) {
continue;
}
Q_FOREACH (const Nepomuk2::Resource &groupResource, groupProperties.toResourceList()) {
groups << groupResource.property(NCO::contactGroupName()).toString();
}
}
} else {
Nepomuk2::Variant groupProperties = d->res.property(NCO::belongsToGroup());
Q_FOREACH (const Nepomuk2::Resource &groupResource, groupProperties.toResourceList()) {
groups << groupResource.property(NCO::contactGroupName()).toString();
}
}
return groups;
}
// QStringList PersonData::bareContacts() const
// {
// return personIndex().data(PersonsModel::ContactIdRole).toStringList();
// }
//
// QModelIndex PersonData::personIndex() const
// {
// Q_D(const PersonData);
// Q_ASSERT(d->model->rowCount()>0);
// QModelIndex idx = d->model->index(0,0);
// Q_ASSERT(idx.isValid());
// return idx;
// }
//
bool PersonData::isPerson() const
{
Q_D(const PersonData);
return d->res.type() == PIMO::Person();
}
QString PersonData::findMostOnlinePresence(const QStringList &presences) const
{
if (presences.contains("available")) {
return "available";
}
if (presences.contains("away")) {
return "away";
}
if (presences.contains("busy") || presences.contains("dnd")) {
return "busy";
}
if (presences.contains("xa")) {
return "xa";
}
return "offline";
}
void PersonData::presenceModelChange(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
Q_D(PersonData);
if (topLeft != bottomRight) {
return;
}
if (topLeft.data(PersonsModel::UriRole).toString() == d->uri) {
emit dataChanged();
}
}
<commit_msg>Simplify PersonData code<commit_after>/*
KPeople
Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]>
Copyright (C) 2013 Martin Klapetek <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "persondata.h"
#include "persons-model.h"
#include "person-item.h"
#include "persons-presence-model.h"
#include <Nepomuk2/Resource>
#include <Nepomuk2/Query/Query>
#include <Nepomuk2/ResourceManager>
#include <Nepomuk2/ResourceWatcher>
#include <Nepomuk2/Vocabulary/PIMO>
#include <Nepomuk2/Vocabulary/NCO>
#include <Nepomuk2/Vocabulary/NIE>
#include <Nepomuk2/Variant>
#include <Soprano/Model>
#include <Soprano/QueryResultIterator>
#include <KDebug>
using namespace Nepomuk2::Vocabulary;
class PersonDataPrivate {
public:
QString uri;
QString id;
QPointer<Nepomuk2::ResourceWatcher> watcher;
Nepomuk2::Resource personResource;
QList<Nepomuk2::Resource> contactResources;
};
K_GLOBAL_STATIC(PersonsPresenceModel, s_presenceModel)
PersonData::PersonData(QObject *parent)
: QObject(parent),
d_ptr(new PersonDataPrivate)
{
}
PersonData::PersonData(const QString &uri, QObject *parent)
: QObject(parent),
d_ptr(new PersonDataPrivate)
{
setUri(uri);
}
void PersonData::setContactId(const QString &id)
{
Q_D(PersonData);
if (d->id == id) {
return;
}
d->id = id;
QString query = QString::fromUtf8(
"select DISTINCT ?uri "
"WHERE { "
"?uri a nco:PersonContact. "
"?uri nco:hasContactMedium ?a . "
"?a ?b \"%1\"^^xsd:string . "
"}").arg(id);
Soprano::Model *model = Nepomuk2::ResourceManager::instance()->mainModel();
Soprano::QueryResultIterator it = model->executeQuery(query, Soprano::Query::QueryLanguageSparqlNoInference);
QString uri;
while (it.next()) {
uri = it[0].uri().toString();
}
if (d->uri != uri) {
setUri(uri);
}
}
QString PersonData::contactId() const
{
Q_D(const PersonData);
return d->id;
}
QString PersonData::uri() const
{
Q_D(const PersonData);
return d->uri;
}
void PersonData::setUri(const QString &uri)
{
Q_D(PersonData);
d->uri = uri;
d->contactResources.clear();
d->personResource = Nepomuk2::Resource();
Nepomuk2::Resource r(uri);
if (!d->watcher.isNull()) {
delete d->watcher;
}
d->watcher = new Nepomuk2::ResourceWatcher(this);
if (r.type() == PIMO::Person()) {
d->personResource = r;
d->contactResources = r.property(PIMO::groundingOccurrence()).toResourceList();
Q_FOREACH (Nepomuk2::Resource res, d->contactResources) { //cannot use const here as we're modifying the resource
d->watcher->addResource(res);
res.setWatchEnabled(true);
}
} else {
d->contactResources = QList<Nepomuk2::Resource>() << r;
}
r.setWatchEnabled(true);
d->watcher->addResource(r);
connect(d->watcher.data(), SIGNAL(propertyChanged(Nepomuk2::Resource,Nepomuk2::Types::Property,QVariantList,QVariantList)),
this, SIGNAL(dataChanged()));
connect(s_presenceModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(presenceModelChange(QModelIndex,QModelIndex)));
emit uriChanged();
emit dataChanged();
}
QString PersonData::status() const
{
Q_D(const PersonData);
QStringList presenceList;
Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) {
if (resource.hasProperty(NCO::hasIMAccount())) {
QString imID = resource.property(NCO::hasIMAccount()).toResource().property(NCO::imID()).toString();
presenceList << s_presenceModel->dataForContactId(imID, PersonsModel::StatusStringRole).toString();
}
}
return findMostOnlinePresence(presenceList);
}
QUrl PersonData::avatar() const
{
Q_D(const PersonData);
Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) {
if (resource.hasProperty(NCO::photo())) {
return resource.property(NCO::photo()).toResource().property(NIE::url()).toUrl();
}
}
return QUrl();
}
QString PersonData::name() const
{
Q_D(const PersonData);
QString label;
//simply pick the first for now
Nepomuk2::Resource r = d->contactResources.first();
label = r.property(NCO::fullname()).toString();
if (!label.isEmpty()) {
return label;
}
label = r.property(NCO::hasIMAccount()).toResource().property(NCO::imNickname()).toString();
if (!label.isEmpty()) {
return label;
}
return r.property(NCO::hasContactMedium()).toResource().genericLabel();
}
QStringList PersonData::emails() const
{
Q_D(const PersonData);
QStringList emails;
Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) {
if (resource.hasProperty(NCO::hasEmailAddress())) {
Q_FOREACH (const Nepomuk2::Resource &email, resource.property(NCO::hasEmailAddress()).toResourceList()) {
emails << email.property(NCO::emailAddress()).toString();
}
}
}
return emails;
}
QStringList PersonData::phones() const
{
Q_D(const PersonData);
QStringList phones;
Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) {
if (resource.hasProperty(NCO::hasPhoneNumber())) {
Q_FOREACH (const Nepomuk2::Resource &phone, resource.property(NCO::hasPhoneNumber()).toResourceList()) {
phones << phone.property(NCO::phoneNumber()).toString();
}
}
}
return phones;
}
QStringList PersonData::imAccounts() const
{
Q_D(const PersonData);
QStringList ims;
Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) {
if (resource.hasProperty(NCO::hasIMAccount())) {
Q_FOREACH (const Nepomuk2::Resource &im, resource.property(NCO::hasIMAccount()).toResourceList()) {
ims << im.property(NCO::imAccountType()).toString();
ims << im.property(NCO::imNickname()).toString();
ims << im.property(NCO::imID()).toString();
}
}
}
return ims;
}
KDateTime PersonData::birthday() const
{
Q_D(const PersonData);
//we'll go through all the dates we have and from every date we
//get msecs from epoch and then we'll check whichever is greater
//If the date has only month and a year, it will be counted
//to 1st day of that month. If the real date is actually 15th day,
//it means the more complete date will have more msecs from the epoch
KDateTime bd;
Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) {
if (resource.hasProperty(NCO::birthDate())) {
KDateTime bdTemp(resource.property(NCO::birthDate()).toDateTime());
if (bdTemp.isValid() && bdTemp.dateTime().toMSecsSinceEpoch() > bd.dateTime().toMSecsSinceEpoch()) {
bd = bdTemp;
}
}
}
return bd;
}
QStringList PersonData::groups() const
{
Q_D(const PersonData);
QStringList groups;
Q_FOREACH (const Nepomuk2::Resource &resource, d->contactResources) {
Nepomuk2::Variant groupProperties = resource.property(NCO::belongsToGroup());
if (!groupProperties.isValid()) {
continue;
}
Q_FOREACH (const Nepomuk2::Resource &groupResource, groupProperties.toResourceList()) {
groups << groupResource.property(NCO::contactGroupName()).toString();
}
}
return groups;
}
// QStringList PersonData::bareContacts() const
// {
// return personIndex().data(PersonsModel::ContactIdRole).toStringList();
// }
//
// QModelIndex PersonData::personIndex() const
// {
// Q_D(const PersonData);
// Q_ASSERT(d->model->rowCount()>0);
// QModelIndex idx = d->model->index(0,0);
// Q_ASSERT(idx.isValid());
// return idx;
// }
//
bool PersonData::isPerson() const
{
Q_D(const PersonData);
return d->personResource.isValid();
}
QString PersonData::findMostOnlinePresence(const QStringList &presences) const
{
if (presences.contains("available")) {
return "available";
}
if (presences.contains("away")) {
return "away";
}
if (presences.contains("busy") || presences.contains("dnd")) {
return "busy";
}
if (presences.contains("xa")) {
return "xa";
}
return "offline";
}
void PersonData::presenceModelChange(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
Q_D(PersonData);
if (topLeft != bottomRight) {
return;
}
if (topLeft.data(PersonsModel::UriRole).toString() == d->uri) {
emit dataChanged();
}
}
<|endoftext|> |
<commit_before>#include "ElectrocardioIC.h"
#include <math.h>
template<>
InputParameters validParams<ElectrocardioIC>()
{
InputParameters params = validParams<InitialCondition>();
return params;
}
ElectrocardioIC::ElectrocardioIC(const std::string & name,
InputParameters parameters) :
InitialCondition(name, parameters)
{
}
ElectrocardioIC::~ElectrocardioIC()
{
}
Real
ElectrocardioIC::value(const Point & p)
{
/// The value -90.272 is the resting potential of the bernus model for all except one case...
/// \todo TODO: make this more general: different ion models have different resting potentials
return -90.272;
}
<commit_msg>modified resting potential for bernus model; apparently the ewe implementation does not exactly reproduce the -90.272mV; have to check parameters<commit_after>#include "ElectrocardioIC.h"
#include <math.h>
template<>
InputParameters validParams<ElectrocardioIC>()
{
InputParameters params = validParams<InitialCondition>();
return params;
}
ElectrocardioIC::ElectrocardioIC(const std::string & name,
InputParameters parameters) :
InitialCondition(name, parameters)
{
}
ElectrocardioIC::~ElectrocardioIC()
{
}
Real
ElectrocardioIC::value(const Point & p)
{
/// The value -90.272 is the resting potential of the bernus model for all except one case...
/// \todo TODO: make this more general: different ion models have different resting potentials
// return -90.272;
return -92.189; // for some reason, my Bernus model has a slightly different resting potential.. probably a slighly wrong parameter?
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <typeclass/functor.h>
#include <typeclass/functor_list.h>
#include <typeclass/functor_vector.h>
#include <typeclass/functor_optional.h>
#include <typeclass/eq_primitive.h>
#include <typeclass/eq_list.h>
#include <typeclass/eq.h>
#include <typeclass/monoid.h>
#include <typeclass/monoid_primitive.h>
#include <typeclass/monoid_list.h>
#include <typeclass/monad.h>
#include <typeclass/monad_list.h>
#include <typeclass/monad_free.h>
#include <boost/variant.hpp>
#define ASSERT(...) if(!(__VA_ARGS__)) throw "Assertion that " #__VA_ARGS__ " failed"
#define ASSERT_NOT(...) if(__VA_ARGS__) throw "Assertion that not " #__VA_ARGS__ " failed"
using namespace funcpp::typeclass;
void testEqPrimitive() {
using namespace funcpp::typeclass::eq;
ASSERT(equal(1,1));
ASSERT_NOT(equal(2,1));
ASSERT(equal(1.0,1.0));
ASSERT_NOT(equal(1.1,1.0));
}
void testEqList() {
using namespace funcpp::typeclass::eq;
ASSERT(equal(std::list<int>{1,2,3},std::list<int>{1,2,3}));
ASSERT_NOT(equal(std::list<int>{1,2,3},std::list<int>{1,0,3}));
ASSERT_NOT(equal(std::list<int>{0,2,3},std::list<int>{1,0,3}));
}
void testFunctorList() {
std::list<int> in {1,2,3};
std::list<double> out = functor::fmap([](int x) { return 2.0*x; }, in);
}
void testMonoidPrimitive() {
using namespace monoid;
ASSERT(42+100 == mappend(42,100));
ASSERT(42+100 == mappend<int,std::plus<int>>(42,100));
ASSERT(42*100 == mappend<int,std::multiplies<int>>(42,100));
}
void testMonoidList() {
using namespace monoid;
std::list<int> a{1,2,3,4}, b{1,2}, c{3,4};
ASSERT(a == b + c);
}
void testMonadList() {
using namespace monad;
std::list<int> a{42}, b{1,2}, c{3,4};
ASSERT(a == mreturn<std::list>(42));
ASSERT(std::list<int>{84} == (instance<std::list>::mreturn(42) >>= [](int x){ return instance<std::list>::mreturn(2*x); }));
ASSERT(a >> std::list<int>{72} == std::list<int>{72});
}
using unit = std::tuple<>;
template <typename Next>
struct Prog {
struct Read {
std::function<Next(int)> next;
};
template <typename F>
static Prog<std::result_of_t<F(int)>> read(F next) {
return { Read{next} };
}
struct Write {
int x;
std::function<Next(unit)> next;
};
template <typename F>
static Prog<std::result_of_t<F(unit)>> write(int x, F next) {
return { Write{x, next} };
}
boost::variant<Read, Write> v;
};
template <typename Fun, typename Next>
Prog<std::result_of_t<Fun(Next)>>
fmap(Fun&& fun, const Prog<Next>& prog) {
using Res = std::result_of_t<Fun(Next)>;
struct Visitor {
Fun& fun;
// fmap f (Read n) = Read (f . n)
Prog<Res> operator()(const typename Prog<Next>::Read& read) const {
return Prog<Res>::read(compose(fun, read.next));
}
// fmap f (Write x n) = Write x (f . n)
Prog<Res> operator()(const typename Prog<Next>::Write& write) const {
return Prog<Res>::write(write.x, compose(fun, write.next));
}
};
return boost::apply_visitor(Visitor{fun}, prog.v);
}
void testMonadFree() {
using namespace monad;
using namespace funcpp::free;
}
int main() {
try {
testEqPrimitive();
testEqList();
testMonoidPrimitive();
testMonoidList();
testMonadList();
testMonadFree();
std::cout << "***************************************\n";
std::cout << "** ALL TESTS OK **\n";
std::cout << "***************************************\n";
}
catch(const char* ex) {
std::cout << "***************************************\n";
std::cout << "** TESTS FAILED: **\n";
std::cout << "***************************************\n";
std::cout << ex << std::endl;
}
}<commit_msg>Quick sketch of referentially transparent file-i/o<commit_after>
#include <iostream>
#include <fstream>
#include <vector>
#include <type_traits>
#include <map>
#include <experimental/optional>
namespace std {
using namespace std::experimental;
template< class, class = std::void_t<> >
struct is_callable : std::false_type { };
template< class T >
struct is_callable<T, std::void_t<decltype(std::declval<T>()())>> : std::true_type { };
}
template <typename T> struct with_type { using type = T; };
struct unit_t : std::tuple<> {};
constexpr unit_t unit {};
template <typename T>
class IO : public with_type<T> {
std::function<T()> m_action;
public:
template <typename Fn>
IO(Fn&& action)
: m_action{ std::forward<Fn>(action) }
{}
template <typename U>
IO(IO<U> & action)
: m_action{ action.m_action }
{}
template <typename U>
IO(IO<U> const & action)
: m_action{ action.m_action }
{}
template <typename U>
IO(IO<U>&& action)
: m_action{ std::move(action.m_action) }
{}
IO(IO&&) = default;
IO(IO const&) = default;
IO& operator= (IO&&) = default;
IO& operator= (IO const&) = default;
template <typename Fn>
auto then(Fn&& cont) const {
using res_t = decltype(cont(m_action()));
return res_t{ [cont=std::forward<Fn>(cont),action=m_action]() mutable {
return cont(action()).run();
}};
}
T run() { return m_action(); }
};
template <typename U>
auto yield(U&& val) -> IO<std::decay_t<U>> {
return IO<std::decay_t<U>> { [val=std::forward<U>(val)]() -> std::decay_t<U> {
return val;
}};
}
class SharedResource {
protected:
struct Details {
virtual ~Details() {}
};
private:
std::shared_ptr<Details> m_impl;
public:
SharedResource(std::shared_ptr<Details> impl)
: m_impl{ std::move(impl) }
{}
};
template <typename T>
class ReadStore {
protected:
struct Details {
virtual IO<std::optional<T>> read_impl() const = 0;
virtual ~Details() {}
};
private:
std::shared_ptr<Details> m_impl;
public:
ReadStore(std::shared_ptr<Details> impl) : m_impl{ std::move(impl) } {}
IO<std::optional<T>>
read() { return m_impl->read_impl(); }
};
template <typename T>
class WriteStore {
protected:
struct Details {
virtual IO<std::optional<unit_t>> write_impl(T value) const = 0;
virtual ~Details() {}
};
private:
std::shared_ptr<Details> m_impl;
public:
WriteStore(std::shared_ptr<Details> impl) : m_impl{ std::move(impl) } {}
IO<std::optional<unit_t>>
write(T value) { return m_impl->write_impl(std::move(value)); }
};
template <typename T>
class Store
: public ReadStore<T>
, public WriteStore<T>
{
protected:
struct Details : ReadStore<T>::Details, WriteStore<T>::Details {};
public:
Store(std::shared_ptr<Details> impl)
: ReadStore<T>(impl)
, WriteStore<T>(impl)
{}
};
class SDCardMounted : SharedResource {
struct Details : SharedResource::Details {
std::string m_dev;
virtual ~Details() override {
std::cout << "Executing SD-card unmount action for device " << m_dev << std::endl;
}
Details(std::string dev)
: m_dev{ std::move(dev) }
{
std::cout << "Executing SD-card mount action for device " << m_dev << std::endl;
}
};
public:
SDCardMounted(std::string dev)
: SharedResource(std::make_shared<Details>(std::move(dev))) {}
};
class FileStore final
: public Store<std::vector<uint8_t>>
{
struct Details : Store<std::vector<uint8_t>>::Details {
std::string m_filename;
virtual IO<std::optional<unit_t>> write_impl(std::vector<uint8_t> value) const override {
return IO<std::optional<unit_t>>([fname=m_filename, value=std::move(value)]() mutable -> std::optional<unit_t> {
try {
std::ofstream(fname, std::ios::binary).write(reinterpret_cast<char const*>(value.data()),value.size());
return std::make_optional(unit);
} catch(...) {
return std::nullopt;
}
});
}
virtual IO<std::optional<std::vector<uint8_t>>> read_impl() const override {
return IO<std::optional<std::vector<uint8_t>>>([fname=m_filename]() mutable -> std::optional<std::vector<uint8_t>> {
try {
std::ifstream file(fname, std::ios::binary | std::ios::ate);
auto const size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<uint8_t> buffer(size);
if(!file.read(reinterpret_cast<char*>(buffer.data()), size))
return std::nullopt;
return std::make_optional(std::move(buffer));
}
catch(...) {
return std::nullopt;
}
});
}
Details(std::string filename)
: m_filename{std::move(filename)} {}
};
public:
FileStore(std::string filename)
: Store<std::vector<uint8_t>>(std::make_shared<Details>(std::move(filename)))
{}
};
class MountedFileStore final
: public Store<std::vector<uint8_t>>
{
struct Details : Store<std::vector<uint8_t>>::Details {
IO<std::optional<SDCardMounted>> m_mountedState;
FileStore m_file;
virtual IO<std::optional<unit_t>> write_impl(std::vector<uint8_t> value) const override {
return m_mountedState.then([file=m_file, val=std::move(value)](std::optional<SDCardMounted> mounted) mutable {
if(!mounted) return yield<std::optional<unit_t>>(std::nullopt); // TODO: monad transformers
return file.write(std::move(val));
});
}
virtual IO<std::optional<std::vector<uint8_t>>> read_impl() const override {
return m_mountedState.then([file=m_file](std::optional<SDCardMounted> mounted) mutable {
if(!mounted) return yield<std::optional<std::vector<uint8_t>>>(std::nullopt); // TODO: monad transformers
return file.read();
});
}
Details(IO<std::optional<SDCardMounted>> mountedState, FileStore file)
: m_mountedState{ std::move(mountedState) }
, m_file{std::move(file)} {}
};
public:
MountedFileStore(IO<std::optional<SDCardMounted>> mountedState, std::string filename)
: Store<std::vector<uint8_t>>(std::make_shared<Details>(std::move(mountedState), FileStore(filename)))
{
}
};
class Console {
public:
IO<std::ostream&> cout() const {
return { []() -> std::ostream& { return { std::cout }; }};
}
};
class SDCardMounter {
using device_id_t = std::size_t;
std::map<device_id_t, std::string> m_devMap;
public:
SDCardMounter()
: m_devMap{ {0, "/dev/mmcblk1p1"}, {1, "/dev/sda1"} }
{}
IO<std::optional<SDCardMounted>> mounted(device_id_t devId) const {
return { [device=m_devMap.at(devId)]() -> std::optional<SDCardMounted> {
return std::make_optional(SDCardMounted{device});
}};
}
};
template <typename T>
class StreamWriteStore final
: public WriteStore<T>
{
struct Details
: WriteStore<T>::Details
{
IO<std::ostream&> m_stream;
virtual IO<std::optional<unit_t>> write_impl(T value) const override {
return m_stream.then([value=std::move(value)](std::ostream & stream) mutable -> IO<std::optional<unit_t>> {
try {
stream << std::move(value);
return yield<std::optional<unit_t>>(std::make_optional(unit));
} catch(...) {
return yield<std::optional<unit_t>>(std::nullopt);
}
});
}
Details(IO<std::ostream&> stream)
: m_stream{std::move(stream)} {}
};
public:
StreamWriteStore(IO<std::ostream&> stream)
: WriteStore<T>(std::make_shared<Details>(std::move(stream)))
{}
};
int main() {
auto const mountedCard = SDCardMounter().mounted(/*devId*/0);
Store<std::vector<uint8_t>> store = MountedFileStore{mountedCard, "file1"};
WriteStore<std::vector<uint8_t>> writeStore = store; // slicing has no effect :-)
ReadStore<std::vector<uint8_t>> readStore = store;
{
std::vector<uint8_t> data{1,2,3,4,5};
auto action = writeStore.write(data).then([](auto res) -> IO<unit_t> {
if(res)
std::cout << "successfully wrote file" << std::endl;
return yield(unit);
});
action.run();
}
{
std::vector<uint8_t> dataIn;
auto readAction = readStore.read();
if(auto readResult = readAction.run()) {
std::cout << "successfully read file" << std::endl;
for(auto const& i : *readResult)
std::cout << (int)i << std::endl;
}
else {
std::cout << "failure reading file" << std::endl;
}
}
{
auto c = Console{}.cout();
StreamWriteStore<double> doubles(c);
StreamWriteStore<std::string> strings(c);
std::vector<IO<std::optional<unit_t>>> actions {
strings.write("Hello "),
strings.write("World\n"),
doubles.write(3.14159)
};
for(auto& action : actions)
action.run();
}
}<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/string16.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/mock_network_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/login/mock_screen_observer.h"
#include "chrome/browser/chromeos/login/network_screen.h"
#include "chrome/browser/chromeos/login/view_screen.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/login/wizard_in_process_browser_test.h"
#include "chrome/browser/chromeos/login/wizard_screen.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chromeos/dbus/mock_dbus_thread_manager.h"
#include "chromeos/dbus/mock_session_manager_client.h"
#include "grit/generated_resources.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/controls/button/text_button.h"
namespace chromeos {
using ::testing::A;
using ::testing::AnyNumber;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::_;
using views::Button;
class DummyButtonListener : public views::ButtonListener {
public:
virtual void ButtonPressed(views::Button* sender,
const views::Event& event) {}
};
class NetworkScreenTest : public WizardInProcessBrowserTest {
public:
NetworkScreenTest(): WizardInProcessBrowserTest("network"),
mock_network_library_(NULL) {
}
protected:
virtual void SetUpInProcessBrowserTestFixture() {
MockDBusThreadManager* mock_dbus_thread_manager =
new MockDBusThreadManager;
DBusThreadManager::InitializeForTesting(mock_dbus_thread_manager);
cros_mock_->InitStatusAreaMocks();
mock_network_library_ = cros_mock_->mock_network_library();
MockSessionManagerClient* mock_session_manager_client =
mock_dbus_thread_manager->mock_session_manager_client();
cellular_.reset(new NetworkDevice("cellular"));
EXPECT_CALL(*mock_session_manager_client, EmitLoginPromptReady())
.Times(1);
EXPECT_CALL(*mock_session_manager_client, RetrieveDevicePolicy(_))
.Times(AnyNumber());
// Minimal set of expectations needed on NetworkScreen initialization.
// Status bar expectations are defined with RetiresOnSaturation() so
// these mocks will be active once status bar is initialized.
EXPECT_CALL(*mock_network_library_, AddUserActionObserver(_))
.Times(AnyNumber());
EXPECT_CALL(*mock_network_library_, wifi_connected())
.Times(1)
.WillRepeatedly(Return(false));
EXPECT_CALL(*mock_network_library_, FindWifiDevice())
.Times(AnyNumber());
EXPECT_CALL(*mock_network_library_, FindEthernetDevice())
.Times(AnyNumber());
cros_mock_->SetStatusAreaMocksExpectations();
// Override these return values, but do not set specific expectation:
EXPECT_CALL(*mock_network_library_, wifi_available())
.Times(AnyNumber())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_network_library_, wifi_enabled())
.Times(AnyNumber())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_network_library_, wifi_busy())
.Times(AnyNumber())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connecting())
.Times(AnyNumber())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_scanning())
.Times(AnyNumber())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_available())
.Times(AnyNumber())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_network_library_, cellular_enabled())
.Times(AnyNumber())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_network_library_, cellular_busy())
.Times(AnyNumber())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_connecting())
.Times(AnyNumber())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_network_library_, FindCellularDevice())
.Times(AnyNumber())
.WillRepeatedly((Return(cellular_.get())));
}
virtual void SetUpOnMainThread() {
WizardInProcessBrowserTest::SetUpOnMainThread();
mock_screen_observer_.reset(new MockScreenObserver());
ASSERT_TRUE(WizardController::default_controller() != NULL);
network_screen_ =
WizardController::default_controller()->GetNetworkScreen();
ASSERT_TRUE(network_screen_ != NULL);
ASSERT_EQ(WizardController::default_controller()->current_screen(),
network_screen_);
network_screen_->screen_observer_ = mock_screen_observer_.get();
ASSERT_TRUE(network_screen_->actor() != NULL);
}
virtual void TearDownInProcessBrowserTestFixture() {
CrosInProcessBrowserTest::TearDownInProcessBrowserTestFixture();
DBusThreadManager::Shutdown();
}
void EmulateContinueButtonExit(NetworkScreen* network_screen) {
EXPECT_CALL(*mock_screen_observer_,
OnExit(ScreenObserver::NETWORK_CONNECTED))
.Times(1);
EXPECT_CALL(*mock_network_library_, Connected())
.WillOnce(Return(true));
network_screen->OnContinuePressed();
ui_test_utils::RunAllPendingInMessageLoop();
}
scoped_ptr<MockScreenObserver> mock_screen_observer_;
MockNetworkLibrary* mock_network_library_;
scoped_ptr<NetworkDevice> cellular_;
NetworkScreen* network_screen_;
private:
DISALLOW_COPY_AND_ASSIGN(NetworkScreenTest);
};
IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Ethernet) {
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, ethernet_connecting())
.WillOnce((Return(true)));
// EXPECT_FALSE(actor_->IsContinueEnabled());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce(Return(true));
EXPECT_CALL(*mock_network_library_, Connected())
.Times(3)
.WillRepeatedly(Return(true));
// TODO(nkostylev): Add integration with WebUI actor http://crosbug.com/22570
// EXPECT_FALSE(actor_->IsContinueEnabled());
// EXPECT_FALSE(actor_->IsConnecting());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
// EXPECT_TRUE(actor_->IsContinueEnabled());
EmulateContinueButtonExit(network_screen_);
}
IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Wifi) {
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, ethernet_connecting())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connecting())
.WillOnce((Return(true)));
scoped_ptr<WifiNetwork> wifi(new WifiNetwork("wifi"));
WifiNetworkVector wifi_networks;
wifi_networks.push_back(wifi.get());
EXPECT_CALL(*mock_network_library_, wifi_network())
.WillRepeatedly(Return(wifi.get()));
EXPECT_CALL(*mock_network_library_, wifi_networks())
.WillRepeatedly(ReturnRef(wifi_networks));
// EXPECT_FALSE(actor_->IsContinueEnabled());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce(Return(true));
EXPECT_CALL(*mock_network_library_, Connected())
.Times(3)
.WillRepeatedly(Return(true));
// TODO(nkostylev): Add integration with WebUI actor http://crosbug.com/22570
// EXPECT_FALSE(actor_->IsContinueEnabled());
// EXPECT_FALSE(actor_->IsConnecting());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
// EXPECT_TRUE(actor_->IsContinueEnabled());
EmulateContinueButtonExit(network_screen_);
}
IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Cellular) {
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, ethernet_connecting())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connecting())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_connecting())
.WillOnce((Return(true)));
scoped_ptr<CellularNetwork> cellular(new CellularNetwork("cellular"));
EXPECT_CALL(*mock_network_library_, cellular_network())
.WillOnce(Return(cellular.get()));
// EXPECT_FALSE(actor_->IsContinueEnabled());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce(Return(true));
EXPECT_CALL(*mock_network_library_, Connected())
.Times(3)
.WillRepeatedly(Return(true));
// TODO(nkostylev): Add integration with WebUI actor http://crosbug.com/22570
// EXPECT_FALSE(actor_->IsContinueEnabled());
// EXPECT_FALSE(actor_->IsConnecting());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
// EXPECT_TRUE(actor_->IsContinueEnabled());
EmulateContinueButtonExit(network_screen_);
}
// See crbug.com/89392
#if defined(OS_LINUX)
#define MAYBE_Timeout DISABLED_Timeout
#else
#define MAYBE_Timeout Timeout
#endif
IN_PROC_BROWSER_TEST_F(NetworkScreenTest, MAYBE_Timeout) {
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, ethernet_connecting())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connecting())
.WillOnce((Return(true)));
scoped_ptr<WifiNetwork> wifi(new WifiNetwork("wifi"));
EXPECT_CALL(*mock_network_library_, wifi_network())
.WillOnce(Return(wifi.get()));
// EXPECT_FALSE(actor_->IsContinueEnabled());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
EXPECT_CALL(*mock_network_library_, Connected())
.Times(2)
.WillRepeatedly(Return(false));
// TODO(nkostylev): Add integration with WebUI actor http://crosbug.com/22570
// EXPECT_FALSE(actor_->IsContinueEnabled());
// EXPECT_FALSE(actor_->IsConnecting());
network_screen_->OnConnectionTimeout();
// Close infobubble with error message - it makes the test stable.
// EXPECT_FALSE(actor_->IsContinueEnabled());
// EXPECT_FALSE(actor_->IsConnecting());
// actor_->ClearErrors();
}
} // namespace chromeos
<commit_msg>Fix test expectations to include wimax<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/string16.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/mock_network_library.h"
#include "chrome/browser/chromeos/cros/network_library.h"
#include "chrome/browser/chromeos/login/mock_screen_observer.h"
#include "chrome/browser/chromeos/login/network_screen.h"
#include "chrome/browser/chromeos/login/view_screen.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/login/wizard_in_process_browser_test.h"
#include "chrome/browser/chromeos/login/wizard_screen.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chromeos/dbus/mock_dbus_thread_manager.h"
#include "chromeos/dbus/mock_session_manager_client.h"
#include "grit/generated_resources.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/controls/button/text_button.h"
namespace chromeos {
using ::testing::A;
using ::testing::AnyNumber;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::_;
using views::Button;
class DummyButtonListener : public views::ButtonListener {
public:
virtual void ButtonPressed(views::Button* sender,
const views::Event& event) {}
};
class NetworkScreenTest : public WizardInProcessBrowserTest {
public:
NetworkScreenTest(): WizardInProcessBrowserTest("network"),
mock_network_library_(NULL) {
}
protected:
virtual void SetUpInProcessBrowserTestFixture() {
MockDBusThreadManager* mock_dbus_thread_manager =
new MockDBusThreadManager;
DBusThreadManager::InitializeForTesting(mock_dbus_thread_manager);
cros_mock_->InitStatusAreaMocks();
mock_network_library_ = cros_mock_->mock_network_library();
MockSessionManagerClient* mock_session_manager_client =
mock_dbus_thread_manager->mock_session_manager_client();
cellular_.reset(new NetworkDevice("cellular"));
EXPECT_CALL(*mock_session_manager_client, EmitLoginPromptReady())
.Times(1);
EXPECT_CALL(*mock_session_manager_client, RetrieveDevicePolicy(_))
.Times(AnyNumber());
// Minimal set of expectations needed on NetworkScreen initialization.
// Status bar expectations are defined with RetiresOnSaturation() so
// these mocks will be active once status bar is initialized.
EXPECT_CALL(*mock_network_library_, AddUserActionObserver(_))
.Times(AnyNumber());
EXPECT_CALL(*mock_network_library_, wifi_connected())
.Times(1)
.WillRepeatedly(Return(false));
EXPECT_CALL(*mock_network_library_, FindWifiDevice())
.Times(AnyNumber());
EXPECT_CALL(*mock_network_library_, FindEthernetDevice())
.Times(AnyNumber());
cros_mock_->SetStatusAreaMocksExpectations();
// Override these return values, but do not set specific expectation:
EXPECT_CALL(*mock_network_library_, wifi_available())
.Times(AnyNumber())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_network_library_, wifi_enabled())
.Times(AnyNumber())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_network_library_, wifi_busy())
.Times(AnyNumber())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connecting())
.Times(AnyNumber())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_scanning())
.Times(AnyNumber())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_available())
.Times(AnyNumber())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_network_library_, cellular_enabled())
.Times(AnyNumber())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_network_library_, cellular_busy())
.Times(AnyNumber())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_connecting())
.Times(AnyNumber())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_network_library_, wimax_available())
.Times(AnyNumber())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_network_library_, wimax_enabled())
.Times(AnyNumber())
.WillRepeatedly((Return(true)));
EXPECT_CALL(*mock_network_library_, wimax_connected())
.Times(AnyNumber())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_network_library_, wimax_connecting())
.Times(AnyNumber())
.WillRepeatedly((Return(false)));
EXPECT_CALL(*mock_network_library_, FindCellularDevice())
.Times(AnyNumber())
.WillRepeatedly((Return(cellular_.get())));
}
virtual void SetUpOnMainThread() {
WizardInProcessBrowserTest::SetUpOnMainThread();
mock_screen_observer_.reset(new MockScreenObserver());
ASSERT_TRUE(WizardController::default_controller() != NULL);
network_screen_ =
WizardController::default_controller()->GetNetworkScreen();
ASSERT_TRUE(network_screen_ != NULL);
ASSERT_EQ(WizardController::default_controller()->current_screen(),
network_screen_);
network_screen_->screen_observer_ = mock_screen_observer_.get();
ASSERT_TRUE(network_screen_->actor() != NULL);
}
virtual void TearDownInProcessBrowserTestFixture() {
CrosInProcessBrowserTest::TearDownInProcessBrowserTestFixture();
DBusThreadManager::Shutdown();
}
void EmulateContinueButtonExit(NetworkScreen* network_screen) {
EXPECT_CALL(*mock_screen_observer_,
OnExit(ScreenObserver::NETWORK_CONNECTED))
.Times(1);
EXPECT_CALL(*mock_network_library_, Connected())
.WillOnce(Return(true));
network_screen->OnContinuePressed();
ui_test_utils::RunAllPendingInMessageLoop();
}
scoped_ptr<MockScreenObserver> mock_screen_observer_;
MockNetworkLibrary* mock_network_library_;
scoped_ptr<NetworkDevice> cellular_;
NetworkScreen* network_screen_;
private:
DISALLOW_COPY_AND_ASSIGN(NetworkScreenTest);
};
IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Ethernet) {
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, ethernet_connecting())
.WillOnce((Return(true)));
// EXPECT_FALSE(actor_->IsContinueEnabled());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce(Return(true));
EXPECT_CALL(*mock_network_library_, Connected())
.Times(3)
.WillRepeatedly(Return(true));
// TODO(nkostylev): Add integration with WebUI actor http://crosbug.com/22570
// EXPECT_FALSE(actor_->IsContinueEnabled());
// EXPECT_FALSE(actor_->IsConnecting());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
// EXPECT_TRUE(actor_->IsContinueEnabled());
EmulateContinueButtonExit(network_screen_);
}
IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Wifi) {
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, ethernet_connecting())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connecting())
.WillOnce((Return(true)));
scoped_ptr<WifiNetwork> wifi(new WifiNetwork("wifi"));
WifiNetworkVector wifi_networks;
wifi_networks.push_back(wifi.get());
EXPECT_CALL(*mock_network_library_, wifi_network())
.WillRepeatedly(Return(wifi.get()));
EXPECT_CALL(*mock_network_library_, wifi_networks())
.WillRepeatedly(ReturnRef(wifi_networks));
// EXPECT_FALSE(actor_->IsContinueEnabled());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce(Return(true));
EXPECT_CALL(*mock_network_library_, Connected())
.Times(3)
.WillRepeatedly(Return(true));
// TODO(nkostylev): Add integration with WebUI actor http://crosbug.com/22570
// EXPECT_FALSE(actor_->IsContinueEnabled());
// EXPECT_FALSE(actor_->IsConnecting());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
// EXPECT_TRUE(actor_->IsContinueEnabled());
EmulateContinueButtonExit(network_screen_);
}
IN_PROC_BROWSER_TEST_F(NetworkScreenTest, Cellular) {
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, ethernet_connecting())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connecting())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_connecting())
.WillOnce((Return(true)));
scoped_ptr<CellularNetwork> cellular(new CellularNetwork("cellular"));
EXPECT_CALL(*mock_network_library_, cellular_network())
.WillOnce(Return(cellular.get()));
// EXPECT_FALSE(actor_->IsContinueEnabled());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce(Return(true));
EXPECT_CALL(*mock_network_library_, Connected())
.Times(3)
.WillRepeatedly(Return(true));
// TODO(nkostylev): Add integration with WebUI actor http://crosbug.com/22570
// EXPECT_FALSE(actor_->IsContinueEnabled());
// EXPECT_FALSE(actor_->IsConnecting());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
// EXPECT_TRUE(actor_->IsContinueEnabled());
EmulateContinueButtonExit(network_screen_);
}
// See crbug.com/89392
#if defined(OS_LINUX)
#define MAYBE_Timeout DISABLED_Timeout
#else
#define MAYBE_Timeout Timeout
#endif
IN_PROC_BROWSER_TEST_F(NetworkScreenTest, MAYBE_Timeout) {
EXPECT_CALL(*mock_network_library_, ethernet_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, cellular_connected())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, ethernet_connecting())
.WillOnce((Return(false)));
EXPECT_CALL(*mock_network_library_, wifi_connecting())
.WillOnce((Return(true)));
scoped_ptr<WifiNetwork> wifi(new WifiNetwork("wifi"));
EXPECT_CALL(*mock_network_library_, wifi_network())
.WillOnce(Return(wifi.get()));
// EXPECT_FALSE(actor_->IsContinueEnabled());
network_screen_->OnNetworkManagerChanged(mock_network_library_);
EXPECT_CALL(*mock_network_library_, Connected())
.Times(2)
.WillRepeatedly(Return(false));
// TODO(nkostylev): Add integration with WebUI actor http://crosbug.com/22570
// EXPECT_FALSE(actor_->IsContinueEnabled());
// EXPECT_FALSE(actor_->IsConnecting());
network_screen_->OnConnectionTimeout();
// Close infobubble with error message - it makes the test stable.
// EXPECT_FALSE(actor_->IsContinueEnabled());
// EXPECT_FALSE(actor_->IsConnecting());
// actor_->ClearErrors();
}
} // namespace chromeos
<|endoftext|> |
<commit_before>#include <QDataStream>
#include "Connections/Bootstrapper.hpp"
#include "Connections/Connection.hpp"
#include "Transports/AddressFactory.hpp"
#include "Transports/EdgeListenerFactory.hpp"
#include "BaseOverlay.hpp"
using Dissent::Transports::AddressFactory;
using Dissent::Transports::EdgeListenerFactory;
namespace Dissent {
namespace Overlay {
BaseOverlay::BaseOverlay(const Id &local_id,
const QList<Address> &local_endpoints,
const QList<Address> &remote_endpoints) :
_local_endpoints(local_endpoints),
_remote_endpoints(remote_endpoints),
_local_id(local_id),
_rpc(new RpcHandler()),
_cm(new ConnectionManager(_local_id, _rpc))
{
}
BaseOverlay::~BaseOverlay()
{
}
void BaseOverlay::OnStart()
{
qDebug() << "Starting node" << _local_id.ToString();
QObject::connect(_cm.data(), SIGNAL(Disconnected()),
this, SLOT(HandleDisconnected()));
foreach(const Address &addr, _local_endpoints) {
EdgeListener *el = EdgeListenerFactory::GetInstance().CreateEdgeListener(addr);
QSharedPointer<EdgeListener> pel(el);
_cm->AddEdgeListener(pel);
pel->Start();
}
QSharedPointer<ConnectionAcquirer> cab(
new Dissent::Connections::Bootstrapper(_cm, _remote_endpoints));
_con_acquirers.append(cab);
foreach(const QSharedPointer<ConnectionAcquirer> &ca, _con_acquirers) {
ca->Start();
}
}
void BaseOverlay::AddConnectionAcquirer(
const QSharedPointer<ConnectionAcquirer> &ca)
{
_con_acquirers.append(ca);
if(Started() && !Stopped()) {
ca->Start();
}
}
void BaseOverlay::OnStop()
{
emit Disconnecting();
foreach(const QSharedPointer<ConnectionAcquirer> &ca, _con_acquirers) {
ca->Stop();
}
_cm->Stop();
}
void BaseOverlay::HandleDisconnected()
{
emit Disconnected();
}
}
}
<commit_msg>[Overlay] ConnectionManager needs to be started in order to monitor edge timeouts<commit_after>#include <QDataStream>
#include "Connections/Bootstrapper.hpp"
#include "Connections/Connection.hpp"
#include "Transports/AddressFactory.hpp"
#include "Transports/EdgeListenerFactory.hpp"
#include "BaseOverlay.hpp"
using Dissent::Transports::AddressFactory;
using Dissent::Transports::EdgeListenerFactory;
namespace Dissent {
namespace Overlay {
BaseOverlay::BaseOverlay(const Id &local_id,
const QList<Address> &local_endpoints,
const QList<Address> &remote_endpoints) :
_local_endpoints(local_endpoints),
_remote_endpoints(remote_endpoints),
_local_id(local_id),
_rpc(new RpcHandler()),
_cm(new ConnectionManager(_local_id, _rpc))
{
}
BaseOverlay::~BaseOverlay()
{
}
void BaseOverlay::OnStart()
{
qDebug() << "Starting node" << _local_id.ToString();
QObject::connect(_cm.data(), SIGNAL(Disconnected()),
this, SLOT(HandleDisconnected()));
foreach(const Address &addr, _local_endpoints) {
EdgeListener *el = EdgeListenerFactory::GetInstance().CreateEdgeListener(addr);
QSharedPointer<EdgeListener> pel(el);
_cm->AddEdgeListener(pel);
pel->Start();
}
QSharedPointer<ConnectionAcquirer> cab(
new Dissent::Connections::Bootstrapper(_cm, _remote_endpoints));
_con_acquirers.append(cab);
_cm->Start();
foreach(const QSharedPointer<ConnectionAcquirer> &ca, _con_acquirers) {
ca->Start();
}
}
void BaseOverlay::AddConnectionAcquirer(
const QSharedPointer<ConnectionAcquirer> &ca)
{
_con_acquirers.append(ca);
if(Started() && !Stopped()) {
ca->Start();
}
}
void BaseOverlay::OnStop()
{
emit Disconnecting();
foreach(const QSharedPointer<ConnectionAcquirer> &ca, _con_acquirers) {
ca->Stop();
}
_cm->Stop();
}
void BaseOverlay::HandleDisconnected()
{
emit Disconnected();
}
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <Navigation.h>
// Nodes
#include <nodes/Gps.h>
Gps gps;
Navigation::Navigation(){
}
void Navigation::cycle(int hz )//, nSync pointer)
{
switch(hz)
{
case 400:
{
//printf("Navigation: 400\n");
break;
}
case 200:
{
//printf("Navigation: 200\n");
break;
}
case 100:
{
//printf("Navigation: 100\n");
break;
}
case 50:
{
//printf("Navigation: 50\n");
break;
}
case 10:
{
//printf("Navigation: 10\n");
break;
}
case 5:
{
//printf("Navigation: 5\n");
int res = 0;
res = gps.update();
printf("***************** TOA: %lld.%.9ld\n", (long long)gps.data.TOA.tv_sec, gps.data.TOA.tv_nsec);
printf("UTC time: %f\n",gps.data.utc_time);
printf("gps fix quality: %d\n",gps.data.fix_quality);
printf("gps latitude: %f\n",gps.data.latitude);
printf("gps longitude: %f\n",gps.data.longitude);
printf("gps altitude: %f\n",gps.data.altitude);
printf("gps Hdop: %f\n",gps.data.hdop);
printf("gps # sats: %d\n",gps.data.num_sats);
printf("gps nav mode: %s\n",gps.data.nav_mode);
printf("gps cog magnetic: %f\n",gps.data.cog_m);
printf("gps sog kps: %f\n",gps.data.sog_kph);
printf("gps sog mps: %f\n",gps.data.sog_mps);
break;
if(res != 0)
{
printf("gps update failed");
}
}
}
}
<commit_msg>Changed include identifyers <> ""<commit_after>#include <stdio.h>
#include "Navigation.h"
// Nodes
#include "Gps.h"
Gps gps;
Navigation::Navigation(){
}
void Navigation::cycle(int hz )//, nSync pointer)
{
switch(hz)
{
case 400:
{
//printf("Navigation: 400\n");
break;
}
case 200:
{
//printf("Navigation: 200\n");
break;
}
case 100:
{
//printf("Navigation: 100\n");
break;
}
case 50:
{
//printf("Navigation: 50\n");
break;
}
case 10:
{
//printf("Navigation: 10\n");
break;
}
case 5:
{
//printf("Navigation: 5\n");
int res = 0;
res = gps.update();
printf("***************** TOA: %lld.%.9ld\n", (long long)gps.data.TOA.tv_sec, gps.data.TOA.tv_nsec);
printf("UTC time: %f\n",gps.data.utc_time);
printf("gps fix quality: %d\n",gps.data.fix_quality);
printf("gps latitude: %f\n",gps.data.latitude);
printf("gps longitude: %f\n",gps.data.longitude);
printf("gps altitude: %f\n",gps.data.altitude);
printf("gps Hdop: %f\n",gps.data.hdop);
printf("gps # sats: %d\n",gps.data.num_sats);
printf("gps nav mode: %s\n",gps.data.nav_mode);
printf("gps cog magnetic: %f\n",gps.data.cog_m);
printf("gps sog kps: %f\n",gps.data.sog_kph);
printf("gps sog mps: %f\n",gps.data.sog_mps);
break;
if(res != 0)
{
printf("gps update failed");
}
}
}
}
<|endoftext|> |
<commit_before>#include "King.h"
#include "Rook.h"
#include "Board.h"
namespace Chess {
King::King(const Position& position, bool white) : Piece(position, white) {
_hasMoved = false;
}
void King::move(const Position& newPosition) {
position = newPosition;
_hasMoved = true;
}
bool King::hasMoved() const {
return _hasMoved;
}
bool King::isChecked(const Board& board) const {
// Check other pieces.
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = board.getPiece(Position(x, y));
if (piece != nullptr && isWhite() != piece->isWhite() && piece->notation() != 'k' && piece->notation() != 'K') {
std::vector<Position> moves = piece->moves(board);
for (Position move : moves) {
if (move == position)
return true;
}
}
}
}
// Check opponent's king.
for (int x = position.x - 1; x <= position.x + 1; x++) {
for (int y = position.y - 1; y <= position.y + 1; y++) {
if (Position(x, y).valid()) {
Piece* piece = board.getPiece(Position(x, y));
if (piece != nullptr && piece->isWhite() != isWhite() && (piece->notation() == 'k' || piece->notation() == 'K'))
return true;
}
}
}
return false;
}
char King::notation() const {
return isWhite() ? 'K' : 'k';
}
std::vector<Position> King::moves(const Board& board) const {
std::vector<Position> validPosition;
Position tempPosition;
for (int i = 0; i < 3; i++) {
tempPosition.x = this->position.x - 1 + i;
for (int j = 0; j < 3; j++) {
tempPosition.y = this->position.y - 1 + j;
if (tempPosition.valid() &&
( ( board.getPiece(tempPosition) == nullptr ) || (board.getPiece(tempPosition)->isWhite() != this->isWhite()) ) )
validPosition.push_back(tempPosition);
}
}
// Check for valid castling
if (!_hasMoved && !isChecked(board)) {
Rook* leftRook = dynamic_cast<Rook *>(board.getPiece(Position(0, position.y)));
Rook* rightRook = dynamic_cast<Rook *>(board.getPiece(Position(7, position.y)));
bool leftCastling = true;
bool rightCastling = true;
King castlingKing = King(position,isWhite());
for (int l = -1; l < 2; l += 2) {
if (board.getPiece(Position(position.x + 1 * l, position.y)) == nullptr
&& board.getPiece(Position(position.x + 2 * l, position.y)) == nullptr) {
for (int k = 1; k < 3; k++) {
Position tempPosition = position;
tempPosition.x += k*l;
castlingKing.position = tempPosition;
if (l == -1) {
if (board.getPiece(Position(position.x + 3 * l, position.y)) != nullptr || leftRook->hasMoved() || castlingKing.isChecked(board)) {
leftCastling = false;
}
} else if (l == 1) {
if (rightRook == nullptr || rightRook->hasMoved() || castlingKing.isChecked(board)) {
rightCastling = false;
}
}
}
} else {
if (l == 1) {
rightCastling = false;
} else if (l == -1) {
leftCastling = false;
}
}
}
if (leftCastling)
validPosition.push_back(Position(position.x - 2, position.y));
if (rightCastling)
validPosition.push_back(Position(position.x + 2, position.y));
}
return validPosition;
}
}<commit_msg>Fix castling crash<commit_after>#include "King.h"
#include "Rook.h"
#include "Board.h"
namespace Chess {
King::King(const Position& position, bool white) : Piece(position, white) {
_hasMoved = false;
}
void King::move(const Position& newPosition) {
position = newPosition;
_hasMoved = true;
}
bool King::hasMoved() const {
return _hasMoved;
}
bool King::isChecked(const Board& board) const {
// Check other pieces.
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = board.getPiece(Position(x, y));
if (piece != nullptr && isWhite() != piece->isWhite() && piece->notation() != 'k' && piece->notation() != 'K') {
std::vector<Position> moves = piece->moves(board);
for (Position move : moves) {
if (move == position)
return true;
}
}
}
}
// Check opponent's king.
for (int x = position.x - 1; x <= position.x + 1; x++) {
for (int y = position.y - 1; y <= position.y + 1; y++) {
if (Position(x, y).valid()) {
Piece* piece = board.getPiece(Position(x, y));
if (piece != nullptr && piece->isWhite() != isWhite() && (piece->notation() == 'k' || piece->notation() == 'K'))
return true;
}
}
}
return false;
}
char King::notation() const {
return isWhite() ? 'K' : 'k';
}
std::vector<Position> King::moves(const Board& board) const {
std::vector<Position> validPosition;
Position tempPosition;
for (int i = 0; i < 3; i++) {
tempPosition.x = this->position.x - 1 + i;
for (int j = 0; j < 3; j++) {
tempPosition.y = this->position.y - 1 + j;
if (tempPosition.valid() &&
( ( board.getPiece(tempPosition) == nullptr ) || (board.getPiece(tempPosition)->isWhite() != this->isWhite()) ) )
validPosition.push_back(tempPosition);
}
}
// Check for valid castling
if (!_hasMoved && !isChecked(board)) {
Rook* leftRook = dynamic_cast<Rook *>(board.getPiece(Position(0, position.y)));
Rook* rightRook = dynamic_cast<Rook *>(board.getPiece(Position(7, position.y)));
bool leftCastling = true;
bool rightCastling = true;
King castlingKing = King(position,isWhite());
for (int l = -1; l < 2; l += 2) {
if (board.getPiece(Position(position.x + 1 * l, position.y)) == nullptr
&& board.getPiece(Position(position.x + 2 * l, position.y)) == nullptr) {
for (int k = 1; k < 3; k++) {
Position tempPosition = position;
tempPosition.x += k*l;
castlingKing.position = tempPosition;
if (l == -1) {
if (board.getPiece(Position(position.x + 3 * l, position.y)) != nullptr || leftRook == nullptr || leftRook->hasMoved() || castlingKing.isChecked(board)) {
leftCastling = false;
}
} else if (l == 1) {
if (rightRook == nullptr || rightRook->hasMoved() || castlingKing.isChecked(board)) {
rightCastling = false;
}
}
}
} else {
if (l == 1) {
rightCastling = false;
} else if (l == -1) {
leftCastling = false;
}
}
}
if (leftCastling)
validPosition.push_back(Position(position.x - 2, position.y));
if (rightCastling)
validPosition.push_back(Position(position.x + 2, position.y));
}
return validPosition;
}
}<|endoftext|> |
<commit_before><?hh //strict
/**
* This file is part of package.
*
* (c) Noritaka Horio <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace package;
use \ReflectionClass;
use \ReflectionException;
final class PackageSpecification
{
private PackageNamespace $namespace;
private DirectoryPath $packageDirectory;
public function __construct(
Package $package
)
{
$this->namespace = (string) $package['namespace'];
$this->packageDirectory = realpath($package['packageDirectory']);
}
<<__Memoize>>
public function getNamespace() : PackageNamespace
{
$atoms = explode('\\', $this->namespace);
$atoms = (new Vector($atoms))->filter((string $atom) ==> {
return trim($atom) !== '';
});
return implode('\\', $atoms);
}
public function getPackageDirectory() : DirectoryPath
{
return $this->packageDirectory;
}
public function resolve<T>(PackageFile $file) : T
{
$relativeClass = $this->relativeClassFrom($file);
$fullName = $this->namespace . $relativeClass;
try {
$reflection = new ReflectionClass($fullName);
} catch (ReflectionException $exception) {
throw new NotPackageFileException();
}
return $reflection->newInstance();
}
private function relativeClassFrom(PackageFile $file) : string
{
$replaceTargets = [
$this->packageDirectory . '/',
'/',
'.hh'
];
$replaceValues = [
'',
'\\',
''
];
$relativeClass = str_replace($replaceTargets, $replaceValues, $file);
return $relativeClass;
}
}
<commit_msg>add resolveWith<commit_after><?hh //strict
/**
* This file is part of package.
*
* (c) Noritaka Horio <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace package;
use \ReflectionClass;
use \ReflectionException;
final class PackageSpecification
{
private PackageNamespace $namespace;
private DirectoryPath $packageDirectory;
public function __construct(
Package $package
)
{
$this->namespace = (string) $package['namespace'];
$this->packageDirectory = realpath($package['packageDirectory']);
}
<<__Memoize>>
public function getNamespace() : PackageNamespace
{
$atoms = explode('\\', $this->namespace);
$atoms = (new Vector($atoms))->filter((string $atom) ==> {
return trim($atom) !== '';
});
return implode('\\', $atoms);
}
public function getPackageDirectory() : DirectoryPath
{
return $this->packageDirectory;
}
public function resolve<T>(PackageFile $file) : T
{
$reflection = $this->reflectionFrom($file);
return $reflection->newInstance();
}
public function resolveWith<T>(PackageFile $file, array<mixed> $parameters) : T
{
$reflection = $this->reflectionFrom($file);
return $reflection->newInstanceArgs($parameters);
}
private function reflectionFrom<T>(PackageFile $file) : ReflectionClass
{
$relativeClass = $this->relativeClassFrom($file);
$fullClassName = $this->namespace . $relativeClass;
try {
$reflection = new ReflectionClass($fullClassName);
} catch (ReflectionException $exception) {
throw new NotPackageFileException();
}
return $reflection;
}
private function relativeClassFrom(PackageFile $file) : string
{
$replaceTargets = [
$this->packageDirectory . '/',
'/',
'.hh'
];
$replaceValues = [
'',
'\\',
''
];
$relativeClass = str_replace($replaceTargets, $replaceValues, $file);
return $relativeClass;
}
}
<|endoftext|> |
<commit_before>/**
* @file main.cpp
* @brief Simple packet sniffer/monitor using ESP8266 in
* promiscuous mode.
*
* @author Simon Lövgren
* @license MIT
*
* Based on "PacketMonitor" by Stefan Kremser:
* https://github.com/spacehuhn/PacketMonitor
*/
/**
* ------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
/**
* ------------------------------------------------------------------
* Defines
* ------------------------------------------------------------------
*/
// De-mystify enable/disable functions
#define DISABLE 0
#define ENABLE 1
// Max channel number (US = 11, EU = 13, Japan = 14)
#define MAX_CHANNEL 13
// Deauth alarm level (packet rate per second)
#define DEAUTH_ALARM_LEVEL 5
// How long to sleep in main loop
#define LOOP_DELAY_MS 1000
/**
* ------------------------------------------------------------------
* Typedefs
* ------------------------------------------------------------------
*/
/**
* ------------------------------------------------------------------
* Prototypes
* ------------------------------------------------------------------
*/
static void packetSniffer( uint8_t* buffer, uint16_t length );
/**
* ------------------------------------------------------------------
* Private data
* ------------------------------------------------------------------
*/
// Packet counters
static unsigned long packets = 0;
static unsigned long deauths = 0;
static unsigned long totalPackets = 0; // Should probably be long long, but can't be bothered to fix the serial print of it...
static unsigned long totalDeauths = 0; // Should probably be long long, but can't be bothered to fix the serial print of it...
static unsigned long maxPackets = 0;
static unsigned long maxDeauths = 0;
static unsigned long minPackets = -1;
static unsigned long minDeauths = -1;
/**
* ------------------------------------------------------------------
* Interface implementation
* ------------------------------------------------------------------
*/
/**
* ******************************************************************
* Function
* ******************************************************************
*/
void setup( void )
{
// Enable serial communication over UART @ 115200 baud
Serial.begin( 115200 );
// Set up ESP8266 in promiscuous mode
wifi_set_opmode( STATION_MODE );
wifi_promiscuous_enable( DISABLE );
WiFi.disconnect();
wifi_set_promiscuous_rx_cb( packetSniffer );
wifi_promiscuous_enable( ENABLE );
// Report setup completed
Serial.println( "Setup completed." );
}
/**
* ******************************************************************
* Function
* ******************************************************************
*/
void loop( void )
{
delay( LOOP_DELAY_MS );
unsigned long currentPackets = packets;
unsigned long currentDeauths = deauths;
// Add to total
totalPackets += currentPackets;
totalDeauths += currentDeauths;
// Grab max/min
if ( currentPackets > maxPackets )
{
maxPackets = currentPackets;
}
if ( currentPackets < minPackets )
{
minPackets = currentPackets;
}
if ( currentDeauths > maxDeauths )
{
maxDeauths = currentDeauths;
}
if ( currentDeauths < minDeauths )
{
minDeauths = currentDeauths;
}
// Spacing
Serial.print( "\n" );
// Print statistics
Serial.print( " SEEN MAX MIN TOTAL\n" );
Serial.print( " --------------------------------------\n" );
Serial.printf( "PACKETS %-4lu %-4lu %-4lu %lu\n", currentPackets, maxPackets, minPackets, totalPackets );
Serial.printf( "DEAUTHS %-4lu %-4lu %-4lu %lu\n", currentDeauths, maxDeauths, minDeauths, totalDeauths );
// Deauth alarm
if ( deauths > DEAUTH_ALARM_LEVEL )
{
Serial.println("\n[ DEAUTH ALARM ]");
}
// For additional spacing
Serial.print( "\n" );
// Reset counters
packets = 0;
deauths = 0;
}
/**
* ------------------------------------------------------------------
* Private functions
* ------------------------------------------------------------------
*/
/**
* ******************************************************************
* Function
* ******************************************************************
*/
static void packetSniffer( uint8_t* buffer, uint16_t length )
{
// Gets called for each packet
++packets;
if ( buffer[ 12 ] == 0xA0 || buffer[ 12 ] == 0xC0 )
{
++deauths;
}
}<commit_msg>Set explicit wifi channel in ESP8266/packetsniffer.<commit_after>/**
* @file main.cpp
* @brief Simple packet sniffer/monitor using ESP8266 in
* promiscuous mode.
*
* @author Simon Lövgren
* @license MIT
*
* Based on "PacketMonitor" by Stefan Kremser:
* https://github.com/spacehuhn/PacketMonitor
*/
/**
* ------------------------------------------------------------------
* Includes
* ------------------------------------------------------------------
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
/**
* ------------------------------------------------------------------
* Defines
* ------------------------------------------------------------------
*/
// De-mystify enable/disable functions
#define DISABLE 0
#define ENABLE 1
// Max channel number (US = 11, EU = 13, Japan = 14)
#define MAX_CHANNEL 13
// Channel to set
#define CHANNEL 1
// Deauth alarm level (packet rate per second)
#define DEAUTH_ALARM_LEVEL 5
// How long to sleep in main loop
#define LOOP_DELAY_MS 1000
/**
* ------------------------------------------------------------------
* Typedefs
* ------------------------------------------------------------------
*/
/**
* ------------------------------------------------------------------
* Prototypes
* ------------------------------------------------------------------
*/
static void packetSniffer( uint8_t* buffer, uint16_t length );
/**
* ------------------------------------------------------------------
* Private data
* ------------------------------------------------------------------
*/
// Packet counters
static unsigned long packets = 0;
static unsigned long deauths = 0;
static unsigned long totalPackets = 0; // Should probably be long long, but can't be bothered to fix the serial print of it...
static unsigned long totalDeauths = 0; // Should probably be long long, but can't be bothered to fix the serial print of it...
static unsigned long maxPackets = 0;
static unsigned long maxDeauths = 0;
static unsigned long minPackets = -1;
static unsigned long minDeauths = -1;
/**
* ------------------------------------------------------------------
* Interface implementation
* ------------------------------------------------------------------
*/
/**
* ******************************************************************
* Function
* ******************************************************************
*/
void setup( void )
{
// Enable serial communication over UART @ 115200 baud
Serial.begin( 115200 );
// Set up ESP8266 in promiscuous mode
wifi_set_opmode( STATION_MODE );
wifi_promiscuous_enable( DISABLE );
WiFi.disconnect();
wifi_set_promiscuous_rx_cb( packetSniffer );
wifi_promiscuous_enable( ENABLE );
// Currently only sniffing pre-defined channel.
// Should rotate through all channels in loop continuously and
// use yield() instead of sleep.
wifi_set_channel( CHANNEL );
// Report setup completed
Serial.println( "Setup completed." );
}
/**
* ******************************************************************
* Function
* ******************************************************************
*/
void loop( void )
{
delay( LOOP_DELAY_MS );
unsigned long currentPackets = packets;
unsigned long currentDeauths = deauths;
// Add to total
totalPackets += currentPackets;
totalDeauths += currentDeauths;
// Grab max/min
if ( currentPackets > maxPackets )
{
maxPackets = currentPackets;
}
if ( currentPackets < minPackets )
{
minPackets = currentPackets;
}
if ( currentDeauths > maxDeauths )
{
maxDeauths = currentDeauths;
}
if ( currentDeauths < minDeauths )
{
minDeauths = currentDeauths;
}
// Spacing
Serial.print( "\n" );
// Print statistics
Serial.print( " SEEN MAX MIN TOTAL\n" );
Serial.print( " --------------------------------------\n" );
Serial.printf( "PACKETS %-4lu %-4lu %-4lu %lu\n", currentPackets, maxPackets, minPackets, totalPackets );
Serial.printf( "DEAUTHS %-4lu %-4lu %-4lu %lu\n", currentDeauths, maxDeauths, minDeauths, totalDeauths );
// Deauth alarm
if ( deauths > DEAUTH_ALARM_LEVEL )
{
Serial.println("\n[ DEAUTH ALARM ]");
}
// For additional spacing
Serial.print( "\n" );
// Reset counters
packets = 0;
deauths = 0;
}
/**
* ------------------------------------------------------------------
* Private functions
* ------------------------------------------------------------------
*/
/**
* ******************************************************************
* Function
* ******************************************************************
*/
static void packetSniffer( uint8_t* buffer, uint16_t length )
{
// Gets called for each packet
++packets;
if ( buffer[ 12 ] == 0xA0 || buffer[ 12 ] == 0xC0 )
{
++deauths;
}
}<|endoftext|> |
<commit_before>// Copyright 2010-2021, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifdef OS_WIN
#include <windows.h>
#endif // OS_WIN
#include <QGuiApplication>
#include <QtGui>
#include "base/logging.h"
#include "base/process_mutex.h"
#include "base/system_util.h"
#include "gui/base/util.h"
#include "gui/set_default_dialog/set_default_dialog.h"
#ifdef OS_WIN
#include "base/win_util.h"
#endif // OS_WIN
int RunSetDefaultDialog(int argc, char *argv[]) {
Q_INIT_RESOURCE(qrc_set_default_dialog);
mozc::SystemUtil::DisableIME();
std::string name = "set_default_dialog.";
name += mozc::SystemUtil::GetDesktopNameAsString();
mozc::ProcessMutex mutex(name.c_str());
if (!mutex.Lock()) {
LOG(INFO) << "set_default_dialog is already running";
return -1;
}
#ifdef OS_WIN
// For ImeUtil::SetDefault.
mozc::ScopedCOMInitializer com_initializer;
#endif // OS_WIN
auto app = mozc::gui::GuiUtil::InitQt(argc, argv);
mozc::gui::GuiUtil::InstallTranslator("set_default_dialog");
mozc::gui::SetDefaultDialog dialog;
return dialog.exec();
}
<commit_msg>Fix 1 ClangTidyBuild finding:<commit_after>// Copyright 2010-2021, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifdef OS_WIN
#include <windows.h>
#endif // OS_WIN
#include <QGuiApplication>
#include <QtGui>
#include <string>
#include "base/logging.h"
#include "base/process_mutex.h"
#include "base/system_util.h"
#include "gui/base/util.h"
#include "gui/set_default_dialog/set_default_dialog.h"
#ifdef OS_WIN
#include "base/win_util.h"
#endif // OS_WIN
int RunSetDefaultDialog(int argc, char *argv[]) {
Q_INIT_RESOURCE(qrc_set_default_dialog);
mozc::SystemUtil::DisableIME();
std::string name = "set_default_dialog.";
name += mozc::SystemUtil::GetDesktopNameAsString();
mozc::ProcessMutex mutex(name.c_str());
if (!mutex.Lock()) {
LOG(INFO) << "set_default_dialog is already running";
return -1;
}
#ifdef OS_WIN
// For ImeUtil::SetDefault.
mozc::ScopedCOMInitializer com_initializer;
#endif // OS_WIN
auto app = mozc::gui::GuiUtil::InitQt(argc, argv);
mozc::gui::GuiUtil::InstallTranslator("set_default_dialog");
mozc::gui::SetDefaultDialog dialog;
return dialog.exec();
}
<|endoftext|> |
<commit_before>#include "Reader/IniConfigReader.hpp"
namespace Utils
{
IniConfigReader::IniConfigReader(std::string filePath):
Reader(filePath)
{
}
bool IniConfigReader::Read()
{
//TODO: écrire le parser de fichier ini
return true;
}
Config IniConfigReader::GetConfig() const
{
return m_config;
}
}<commit_msg>petite modif<commit_after>#include "Reader/IniConfigReader.hpp"
namespace Utils
{
IniConfigReader::IniConfigReader(std::string filePath):
Reader(filePath)
{
}
bool IniConfigReader::Read()
{
std::string vCurrentSection = "undefined";
while(m_file.good())
{
//On lit une ligne avec un fonction getLine(pointer sur fonction de détection de commentaire, ou caractère(s) de commentaire)
std::cout << "lecture" << std::endl;
}
if(!m_file.good){
//TODO : faire une fonction dans Reader pour répertorier les erreurs survenus
std::cout << "pas ok" << std::endl;
}
return true;
}
Config IniConfigReader::GetConfig() const
{
return m_config;
}
}<|endoftext|> |
<commit_before>#include "ComPortScanner.h"
#include "simpleserial.h"
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/foreach.hpp>
ComPortScanner::ComPortScanner()
{
}
std::string ComPortScanner::CheckPort(boost::asio::io_service &io_service, const std::string &portNum)
{
try {
std::string id = "";
SimpleSerial port = SimpleSerial(io_service, portNum, 115200);
for (int i = 0; i < 10; i++){
port.writeString("?\n");
id = port.readLineAsync(1000);
std::cout << "Check result: " << portNum<< " -> " << id << std::endl;
if (id == "discharged") continue;
if (id.empty()) continue;
if (id == "<id:0>") throw std::runtime_error(("ID not set in port " + portNum).c_str());
if (id.substr(0, 4) != "<id:") throw std::runtime_error(("Invalid ID " + id + " received from port " + portNum).c_str());
id = id.substr(4, 1);
std::cout << "Found port " << portNum << ", id: " << id << std::endl;
return id;
}
if (id.empty()) throw std::runtime_error(("No ID received from port " + portNum).c_str());
}
catch (std::runtime_error const&e){
std::cout << "Port not accessible: " << portNum << ", error: " << e.what() << std::endl;
}
return "";
}
bool ComPortScanner::Verify(boost::asio::io_service &io_service, const std::string &conf_file)
{
bool ok = true;
boost::property_tree::ptree ports;
try {
read_ini(conf_file, ports);
}
catch (...) {
std::cout << "Error reading old port configuration: " << std::endl;
return false;
}
//BOOST_FOREACH(const boost::property_tree::ptree::value_type &v, ports) {
for (int i = ID_WHEEL_LEFT; i < ID_OBJECT_COUNT; i++) {
// v.first is the name of the child.
// v.second is the child tree.
std::stringstream portNum;
//portNum << prefix <<
std::string _id = std::to_string(i); // v.first;
try {
portNum << ports.get<std::string>(std::to_string(i));//(v.second).data();
}
catch (...)
{
std::cout << "ID: " << _id << " not found in conf file" << std::endl;
ok = false;
continue;
}
std::string id = CheckPort(io_service, portNum.str());
if (id.empty()) {
ok = false;
}
}
return ok;
}
bool ComPortScanner::Scan(boost::asio::io_service &io_service)
{
// std::map<short, std::string> portMap;
boost::property_tree::ptree ports;
bool ok = true;
for (int i = 0; i < 20; i++) {
std::stringstream portNum;
portNum << prefix << i;
std::string id = CheckPort(io_service, portNum.str());
if (!id.empty()) {
ports.put(id, portNum.str());
}
}
if (true){
write_ini("conf/ports_new.ini", ports);
}
if (Verify(io_service, "conf/ports_new.ini")) {
#ifdef WIN32
_unlink("conf/ports.ini");
#else
unlink("conf/ports.ini");
#endif
rename("conf/ports_new.ini", "conf/ports.ini");
return true;
}
return false;
}
ComPortScanner::~ComPortScanner()
{
}
<commit_msg>sanity<commit_after>#include "ComPortScanner.h"
#include "simpleserial.h"
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/foreach.hpp>
ComPortScanner::ComPortScanner()
{
}
std::string ComPortScanner::CheckPort(boost::asio::io_service &io_service, const std::string &portNum)
{
try {
std::string id = "";
SimpleSerial port = SimpleSerial(io_service, portNum, 115200);
for (int i = 0; i < 10; i++){
port.writeString("?\n");
id = port.readLineAsync(1000);
std::cout << "Check result: " << portNum<< " -> " << id << std::endl;
if (id == "discharged") continue;
if (id == "~x~~x~?") continue;
if (id.empty()) continue;
if (id == "<id:0>") throw std::runtime_error(("ID not set in port " + portNum).c_str());
if (id.substr(0, 4) != "<id:") throw std::runtime_error(("Invalid ID " + id + " received from port " + portNum).c_str());
id = id.substr(4, 1);
std::cout << "Found port " << portNum << ", id: " << id << std::endl;
return id;
}
if (id.empty()) throw std::runtime_error(("No ID received from port " + portNum).c_str());
}
catch (std::runtime_error const&e){
std::cout << "Port not accessible: " << portNum << ", error: " << e.what() << std::endl;
}
return "";
}
bool ComPortScanner::Verify(boost::asio::io_service &io_service, const std::string &conf_file)
{
bool ok = true;
boost::property_tree::ptree ports;
try {
read_ini(conf_file, ports);
}
catch (...) {
std::cout << "Error reading old port configuration: " << std::endl;
return false;
}
//BOOST_FOREACH(const boost::property_tree::ptree::value_type &v, ports) {
for (int i = ID_WHEEL_LEFT; i < ID_OBJECT_COUNT; i++) {
// v.first is the name of the child.
// v.second is the child tree.
std::stringstream portNum;
//portNum << prefix <<
std::string _id = std::to_string(i); // v.first;
try {
portNum << ports.get<std::string>(std::to_string(i));//(v.second).data();
}
catch (...)
{
std::cout << "ID: " << _id << " not found in conf file" << std::endl;
ok = false;
continue;
}
std::string id = CheckPort(io_service, portNum.str());
if (id.empty()) {
ok = false;
}
}
return ok;
}
bool ComPortScanner::Scan(boost::asio::io_service &io_service)
{
// std::map<short, std::string> portMap;
boost::property_tree::ptree ports;
bool ok = true;
for (int i = 0; i < 20; i++) {
std::stringstream portNum;
portNum << prefix << i;
std::string id = CheckPort(io_service, portNum.str());
if (!id.empty()) {
ports.put(id, portNum.str());
}
}
if (true){
write_ini("conf/ports_new.ini", ports);
}
if (Verify(io_service, "conf/ports_new.ini")) {
#ifdef WIN32
_unlink("conf/ports.ini");
#else
unlink("conf/ports.ini");
#endif
rename("conf/ports_new.ini", "conf/ports.ini");
return true;
}
return false;
}
ComPortScanner::~ComPortScanner()
{
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCell.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 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 "vtkCell.h"
#include "vtkMarchingSquaresCases.h"
#include "vtkPoints.h"
vtkCxxRevisionMacro(vtkCell, "1.56");
// Construct cell.
vtkCell::vtkCell()
{
this->Points = vtkPoints::New();
this->PointIds = vtkIdList::New();
// Consistent Register/Deletes (ShallowCopy uses Register.)
this->Points->Register(this);
this->Points->Delete();
this->PointIds->Register(this);
this->PointIds->Delete();
}
vtkCell::~vtkCell()
{
this->Points->UnRegister(this);
this->PointIds->UnRegister(this);
}
//
// Instantiate cell from outside
//
void vtkCell::Initialize(int npts, vtkIdType *pts, vtkPoints *p)
{
this->PointIds->Reset();
this->Points->Reset();
for (int i=0; i<npts; i++)
{
this->PointIds->InsertId(i,pts[i]);
this->Points->InsertPoint(i,p->GetPoint(pts[i]));
}
}
void vtkCell::ShallowCopy(vtkCell *c)
{
this->Points->ShallowCopy(c->Points);
if ( this->PointIds )
{
this->PointIds->UnRegister(this);
this->PointIds = c->PointIds;
this->PointIds->Register(this);
}
}
void vtkCell::DeepCopy(vtkCell *c)
{
this->Points->DeepCopy(c->Points);
this->PointIds->DeepCopy(c->PointIds);
}
#define VTK_RIGHT 0
#define VTK_LEFT 1
#define VTK_MIDDLE 2
// Bounding box intersection modified from Graphics Gems Vol I. The method
// returns a non-zero value if the bounding box is hit. Origin[3] starts
// the ray, dir[3] is the vector components of the ray in the x-y-z
// directions, coord[3] is the location of hit, and t is the parametric
// coordinate along line. (Notes: the intersection ray dir[3] is NOT
// normalized. Valid intersections will only occur between 0<=t<=1.)
char vtkCell::HitBBox (float bounds[6], float origin[3], float dir[3],
float coord[3], float& t)
{
char inside=1;
char quadrant[3];
int i, whichPlane=0;
float maxT[3], candidatePlane[3];
// First find closest planes
//
for (i=0; i<3; i++)
{
if ( origin[i] < bounds[2*i] )
{
quadrant[i] = VTK_LEFT;
candidatePlane[i] = bounds[2*i];
inside = 0;
}
else if ( origin[i] > bounds[2*i+1] )
{
quadrant[i] = VTK_RIGHT;
candidatePlane[i] = bounds[2*i+1];
inside = 0;
}
else
{
quadrant[i] = VTK_MIDDLE;
}
}
// Check whether origin of ray is inside bbox
//
if (inside)
{
coord[0] = origin[0];
coord[1] = origin[1];
coord[2] = origin[2];
t = 0;
return 1;
}
// Calculate parametric distances to plane
//
for (i=0; i<3; i++)
{
if ( quadrant[i] != VTK_MIDDLE && dir[i] != 0.0 )
{
maxT[i] = (candidatePlane[i]-origin[i]) / dir[i];
}
else
{
maxT[i] = -1.0;
}
}
// Find the largest parametric value of intersection
//
for (i=0; i<3; i++)
{
if ( maxT[whichPlane] < maxT[i] )
{
whichPlane = i;
}
}
// Check for valid intersection along line
//
if ( maxT[whichPlane] > 1.0 || maxT[whichPlane] < 0.0 )
{
return 0;
}
else
{
t = maxT[whichPlane];
}
// Intersection point along line is okay. Check bbox.
//
for (i=0; i<3; i++)
{
if (whichPlane != i)
{
coord[i] = origin[i] + maxT[whichPlane]*dir[i];
if ( coord[i] < bounds[2*i] || coord[i] > bounds[2*i+1] )
{
return 0;
}
}
else
{
coord[i] = candidatePlane[i];
}
}
return 1;
}
// Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Return pointer
// to array of six float values.
float *vtkCell::GetBounds ()
{
float *x;
int i, numPts=this->Points->GetNumberOfPoints();
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_LARGE_FLOAT;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;
for (i=0; i<numPts; i++)
{
x = this->Points->GetPoint(i);
this->Bounds[0] = (x[0] < this->Bounds[0] ? x[0] : this->Bounds[0]);
this->Bounds[1] = (x[0] > this->Bounds[1] ? x[0] : this->Bounds[1]);
this->Bounds[2] = (x[1] < this->Bounds[2] ? x[1] : this->Bounds[2]);
this->Bounds[3] = (x[1] > this->Bounds[3] ? x[1] : this->Bounds[3]);
this->Bounds[4] = (x[2] < this->Bounds[4] ? x[2] : this->Bounds[4]);
this->Bounds[5] = (x[2] > this->Bounds[5] ? x[2] : this->Bounds[5]);
}
return this->Bounds;
}
// Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Copy result into
// user provided array.
void vtkCell::GetBounds(float bounds[6])
{
this->GetBounds();
for (int i=0; i < 6; i++)
{
bounds[i] = this->Bounds[i];
}
}
// Compute Length squared of cell (i.e., bounding box diagonal squared).
float vtkCell::GetLength2 ()
{
double diff, l=0.0;
int i;
this->GetBounds();
for (i=0; i<3; i++)
{
diff = this->Bounds[2*i+1] - this->Bounds[2*i];
l += diff * diff;
}
if(l > VTK_LARGE_FLOAT)
{
return VTK_LARGE_FLOAT;
}
return static_cast<float>(l);
}
// Return center of the cell in parametric coordinates.
// Note that the parametric center is not always located
// at (0.5,0.5,0.5). The return value is the subId that
// the center is in (if a composite cell). If you want the
// center in x-y-z space, invoke the EvaluateLocation() method.
int vtkCell::GetParametricCenter(float pcoords[3])
{
pcoords[0] = pcoords[1] = pcoords[2] = 0.5;
return 0;
}
// This method works fine for all "rectangular" cells, not triangular
// and tetrahedral topologies.
float vtkCell::GetParametricDistance(float pcoords[3])
{
int i;
float pDist, pDistMax=0.0f;
for (i=0; i<3; i++)
{
if ( pcoords[i] < 0.0 )
{
pDist = -pcoords[i];
}
else if ( pcoords[i] > 1.0 )
{
pDist = pcoords[i] - 1.0f;
}
else //inside the cell in the parametric direction
{
pDist = 0.0;
}
if ( pDist > pDistMax )
{
pDistMax = pDist;
}
}
return pDistMax;
}
void vtkCell::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
int numIds=this->PointIds->GetNumberOfIds();
os << indent << "Number Of Points: " << numIds << "\n";
if ( numIds > 0 )
{
float *bounds=this->GetBounds();
os << indent << "Bounds: \n";
os << indent << " Xmin,Xmax: (" << bounds[0] << ", " << bounds[1] << ")\n";
os << indent << " Ymin,Ymax: (" << bounds[2] << ", " << bounds[3] << ")\n";
os << indent << " Zmin,Zmax: (" << bounds[4] << ", " << bounds[5] << ")\n";
os << indent << " Point ids are: ";
for (int i=0; i < numIds; i++)
{
os << this->PointIds->GetId(i);
if ( i && !(i % 12) )
{
os << "\n\t";
}
else
{
if ( i != (numIds-1) )
{
os << ", ";
}
}
}
os << indent << "\n";
}
}
// Note: the following code is placed here to deal with cross-library
// symbol export and import on Microsoft compilers.
static vtkMarchingSquaresLineCases VTK_MARCHING_SQUARES_LINECASES[] = {
{{-1, -1, -1, -1, -1}},
{{0, 3, -1, -1, -1}},
{{1, 0, -1, -1, -1}},
{{1, 3, -1, -1, -1}},
{{2, 1, -1, -1, -1}},
{{0, 3, 2, 1, -1}},
{{2, 0, -1, -1, -1}},
{{2, 3, -1, -1, -1}},
{{3, 2, -1, -1, -1}},
{{0, 2, -1, -1, -1}},
{{1, 0, 3, 2, -1}},
{{1, 2, -1, -1, -1}},
{{3, 1, -1, -1, -1}},
{{0, 1, -1, -1, -1}},
{{3, 0, -1, -1, -1}},
{{-1, -1, -1, -1, -1}}
};
vtkMarchingSquaresLineCases* vtkMarchingSquaresLineCases::GetCases()
{
return VTK_MARCHING_SQUARES_LINECASES;
}
//----------------------------------------------------------------------------
#ifndef VTK_REMOVE_LEGACY_CODE
vtkCell* vtkCell::MakeObject()
{
VTK_LEGACY_METHOD(MakeObject, "4.2");
vtkCell* c = this->NewInstance();
c->DeepCopy(this);
return c;
}
#endif
<commit_msg>ERR:Forgot to undefine some #defs<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCell.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 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 "vtkCell.h"
#include "vtkMarchingSquaresCases.h"
#include "vtkPoints.h"
vtkCxxRevisionMacro(vtkCell, "1.57");
// Construct cell.
vtkCell::vtkCell()
{
this->Points = vtkPoints::New();
this->PointIds = vtkIdList::New();
// Consistent Register/Deletes (ShallowCopy uses Register.)
this->Points->Register(this);
this->Points->Delete();
this->PointIds->Register(this);
this->PointIds->Delete();
}
vtkCell::~vtkCell()
{
this->Points->UnRegister(this);
this->PointIds->UnRegister(this);
}
//
// Instantiate cell from outside
//
void vtkCell::Initialize(int npts, vtkIdType *pts, vtkPoints *p)
{
this->PointIds->Reset();
this->Points->Reset();
for (int i=0; i<npts; i++)
{
this->PointIds->InsertId(i,pts[i]);
this->Points->InsertPoint(i,p->GetPoint(pts[i]));
}
}
void vtkCell::ShallowCopy(vtkCell *c)
{
this->Points->ShallowCopy(c->Points);
if ( this->PointIds )
{
this->PointIds->UnRegister(this);
this->PointIds = c->PointIds;
this->PointIds->Register(this);
}
}
void vtkCell::DeepCopy(vtkCell *c)
{
this->Points->DeepCopy(c->Points);
this->PointIds->DeepCopy(c->PointIds);
}
#define VTK_RIGHT 0
#define VTK_LEFT 1
#define VTK_MIDDLE 2
// Bounding box intersection modified from Graphics Gems Vol I. The method
// returns a non-zero value if the bounding box is hit. Origin[3] starts
// the ray, dir[3] is the vector components of the ray in the x-y-z
// directions, coord[3] is the location of hit, and t is the parametric
// coordinate along line. (Notes: the intersection ray dir[3] is NOT
// normalized. Valid intersections will only occur between 0<=t<=1.)
char vtkCell::HitBBox (float bounds[6], float origin[3], float dir[3],
float coord[3], float& t)
{
char inside=1;
char quadrant[3];
int i, whichPlane=0;
float maxT[3], candidatePlane[3];
// First find closest planes
//
for (i=0; i<3; i++)
{
if ( origin[i] < bounds[2*i] )
{
quadrant[i] = VTK_LEFT;
candidatePlane[i] = bounds[2*i];
inside = 0;
}
else if ( origin[i] > bounds[2*i+1] )
{
quadrant[i] = VTK_RIGHT;
candidatePlane[i] = bounds[2*i+1];
inside = 0;
}
else
{
quadrant[i] = VTK_MIDDLE;
}
}
// Check whether origin of ray is inside bbox
//
if (inside)
{
coord[0] = origin[0];
coord[1] = origin[1];
coord[2] = origin[2];
t = 0;
return 1;
}
// Calculate parametric distances to plane
//
for (i=0; i<3; i++)
{
if ( quadrant[i] != VTK_MIDDLE && dir[i] != 0.0 )
{
maxT[i] = (candidatePlane[i]-origin[i]) / dir[i];
}
else
{
maxT[i] = -1.0;
}
}
// Find the largest parametric value of intersection
//
for (i=0; i<3; i++)
{
if ( maxT[whichPlane] < maxT[i] )
{
whichPlane = i;
}
}
// Check for valid intersection along line
//
if ( maxT[whichPlane] > 1.0 || maxT[whichPlane] < 0.0 )
{
return 0;
}
else
{
t = maxT[whichPlane];
}
// Intersection point along line is okay. Check bbox.
//
for (i=0; i<3; i++)
{
if (whichPlane != i)
{
coord[i] = origin[i] + maxT[whichPlane]*dir[i];
if ( coord[i] < bounds[2*i] || coord[i] > bounds[2*i+1] )
{
return 0;
}
}
else
{
coord[i] = candidatePlane[i];
}
}
return 1;
}
#undef VTK_RIGHT
#undef VTK_LEFT
#undef VTK_MIDDLE
// Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Return pointer
// to array of six float values.
float *vtkCell::GetBounds ()
{
float *x;
int i, numPts=this->Points->GetNumberOfPoints();
this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_LARGE_FLOAT;
this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;
for (i=0; i<numPts; i++)
{
x = this->Points->GetPoint(i);
this->Bounds[0] = (x[0] < this->Bounds[0] ? x[0] : this->Bounds[0]);
this->Bounds[1] = (x[0] > this->Bounds[1] ? x[0] : this->Bounds[1]);
this->Bounds[2] = (x[1] < this->Bounds[2] ? x[1] : this->Bounds[2]);
this->Bounds[3] = (x[1] > this->Bounds[3] ? x[1] : this->Bounds[3]);
this->Bounds[4] = (x[2] < this->Bounds[4] ? x[2] : this->Bounds[4]);
this->Bounds[5] = (x[2] > this->Bounds[5] ? x[2] : this->Bounds[5]);
}
return this->Bounds;
}
// Compute cell bounding box (xmin,xmax,ymin,ymax,zmin,zmax). Copy result into
// user provided array.
void vtkCell::GetBounds(float bounds[6])
{
this->GetBounds();
for (int i=0; i < 6; i++)
{
bounds[i] = this->Bounds[i];
}
}
// Compute Length squared of cell (i.e., bounding box diagonal squared).
float vtkCell::GetLength2 ()
{
double diff, l=0.0;
int i;
this->GetBounds();
for (i=0; i<3; i++)
{
diff = this->Bounds[2*i+1] - this->Bounds[2*i];
l += diff * diff;
}
if(l > VTK_LARGE_FLOAT)
{
return VTK_LARGE_FLOAT;
}
return static_cast<float>(l);
}
// Return center of the cell in parametric coordinates.
// Note that the parametric center is not always located
// at (0.5,0.5,0.5). The return value is the subId that
// the center is in (if a composite cell). If you want the
// center in x-y-z space, invoke the EvaluateLocation() method.
int vtkCell::GetParametricCenter(float pcoords[3])
{
pcoords[0] = pcoords[1] = pcoords[2] = 0.5;
return 0;
}
// This method works fine for all "rectangular" cells, not triangular
// and tetrahedral topologies.
float vtkCell::GetParametricDistance(float pcoords[3])
{
int i;
float pDist, pDistMax=0.0f;
for (i=0; i<3; i++)
{
if ( pcoords[i] < 0.0 )
{
pDist = -pcoords[i];
}
else if ( pcoords[i] > 1.0 )
{
pDist = pcoords[i] - 1.0f;
}
else //inside the cell in the parametric direction
{
pDist = 0.0;
}
if ( pDist > pDistMax )
{
pDistMax = pDist;
}
}
return pDistMax;
}
void vtkCell::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
int numIds=this->PointIds->GetNumberOfIds();
os << indent << "Number Of Points: " << numIds << "\n";
if ( numIds > 0 )
{
float *bounds=this->GetBounds();
os << indent << "Bounds: \n";
os << indent << " Xmin,Xmax: (" << bounds[0] << ", " << bounds[1] << ")\n";
os << indent << " Ymin,Ymax: (" << bounds[2] << ", " << bounds[3] << ")\n";
os << indent << " Zmin,Zmax: (" << bounds[4] << ", " << bounds[5] << ")\n";
os << indent << " Point ids are: ";
for (int i=0; i < numIds; i++)
{
os << this->PointIds->GetId(i);
if ( i && !(i % 12) )
{
os << "\n\t";
}
else
{
if ( i != (numIds-1) )
{
os << ", ";
}
}
}
os << indent << "\n";
}
}
// Note: the following code is placed here to deal with cross-library
// symbol export and import on Microsoft compilers.
static vtkMarchingSquaresLineCases VTK_MARCHING_SQUARES_LINECASES[] = {
{{-1, -1, -1, -1, -1}},
{{0, 3, -1, -1, -1}},
{{1, 0, -1, -1, -1}},
{{1, 3, -1, -1, -1}},
{{2, 1, -1, -1, -1}},
{{0, 3, 2, 1, -1}},
{{2, 0, -1, -1, -1}},
{{2, 3, -1, -1, -1}},
{{3, 2, -1, -1, -1}},
{{0, 2, -1, -1, -1}},
{{1, 0, 3, 2, -1}},
{{1, 2, -1, -1, -1}},
{{3, 1, -1, -1, -1}},
{{0, 1, -1, -1, -1}},
{{3, 0, -1, -1, -1}},
{{-1, -1, -1, -1, -1}}
};
vtkMarchingSquaresLineCases* vtkMarchingSquaresLineCases::GetCases()
{
return VTK_MARCHING_SQUARES_LINECASES;
}
//----------------------------------------------------------------------------
#ifndef VTK_REMOVE_LEGACY_CODE
vtkCell* vtkCell::MakeObject()
{
VTK_LEGACY_METHOD(MakeObject, "4.2");
vtkCell* c = this->NewInstance();
c->DeepCopy(this);
return c;
}
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.