text stringlengths 54 60.6k |
|---|
<commit_before>#include "MPU9150.h"
#include "AConfig.h"
#if(HAS_MPU9150)
#include "Device.h"
#include "Settings.h"
#include <Wire.h>
//#include "I2Cdev.h"
#include "MPU9150Lib.h"
//#include "CalLib.h"
//#include "dmpKey.h"
//#include "dmpmap.h"
//#include "inv_mpu.h"
//#include "inv_mpu_dmp_motion_driver.h"
#include <EEPROM.h>
MPU9150Lib MPU; // the MPU object
// MPU_UPDATE_RATE defines the rate (in Hz) at which the MPU updates the sensor data and DMP output
#define MPU_UPDATE_RATE (10)
void MPU9150::device_setup(){
//Todo: Read calibration values from EPROM
Wire.begin();
MPU.selectDevice(1);
MPU.init(MPU_UPDATE_RATE); // start the MPU
Settings::capability_bitarray |= (1 << COMPASS_CAPABLE);
Settings::capability_bitarray |= (1 << ORIENTATION_CAPABLE);
}
void MPU9150::device_loop(Command command){
if (command.cmp("ccal")){
// Compass_Calibrate();
//Todo: Write calibrated values to EPROM
}
else if (command.cmp("i2cscan")){
// scan();
}
MPU.read();
navdata::HDGD = MPU.m_fusedEulerPose[VEC3_Z] * RAD_TO_DEGREE + 180; //need to confirm
navdata::PITC = MPU.m_fusedEulerPose[VEC3_X] * RAD_TO_DEGREE;
navdata::ROLL = MPU.m_fusedEulerPose[VEC3_Y] * RAD_TO_DEGREE;
navdata::YAW = MPU.m_fusedEulerPose[VEC3_Z] * RAD_TO_DEGREE;
}
#endif
<commit_msg>Fixed #194; Added calibration code for mag/acc<commit_after>#include "MPU9150.h"
#include "AConfig.h"
#if(HAS_MPU9150)
#include "Device.h"
#include "Settings.h"
#include <Wire.h>
//#include "I2Cdev.h"
#include "MPU9150Lib.h"
#include "CalLib.h"
//#include "dmpKey.h"
//#include "dmpmap.h"
//#include "inv_mpu.h"
//#include "inv_mpu_dmp_motion_driver.h"
#include <EEPROM.h>
#include "Timer.h"
MPU9150Lib MPU; // the MPU object
int MPUDeviceId = 1;
boolean DidInit = false;
boolean InCallibrationMode = false;
Timer MPU9150ReInit;
CALLIB_DATA calData;
Timer calibration_timer;
int counter = 0;
// MPU_UPDATE_RATE defines the rate (in Hz) at which the MPU updates the sensor data and DMP output
// MPU_UPDATE_RATE defines the rate (in Hz) at which the MPU updates the sensor data and DMP output
#define MPU_UPDATE_RATE (20)
// MAG_UPDATE_RATE defines the rate (in Hz) at which the MPU updates the magnetometer data
// MAG_UPDATE_RATE should be less than or equal to the MPU_UPDATE_RATE
#define MAG_UPDATE_RATE (10)
// MPU_MAG_MIX defines the influence that the magnetometer has on the yaw output.
// The magnetometer itself is quite noisy so some mixing with the gyro yaw can help
// significantly. Some example values are defined below:
#define MPU_MAG_MIX_GYRO_ONLY 0 // just use gyro yaw
#define MPU_MAG_MIX_MAG_ONLY 1 // just use magnetometer and no gyro yaw
#define MPU_MAG_MIX_GYRO_AND_MAG 10 // a good mix value
#define MPU_MAG_MIX_GYRO_AND_SOME_MAG 50 // mainly gyros with a bit of mag correction
// MPU_LPF_RATE is the low pas filter rate and can be between 5 and 188Hz
#define MPU_LPF_RATE 5
void MPU9150::device_setup(){
//Todo: Read calibration values from EPROM
Wire.begin();
MPU.selectDevice(MPUDeviceId);
// MPU.init(MPU_UPDATE_RATE, MPU_MAG_MIX_GYRO_AND_MAG, MAG_UPDATE_RATE, MPU_LPF_RATE);
if (!MPU.init(MPU_UPDATE_RATE, MPU_MAG_MIX_GYRO_AND_MAG, MAG_UPDATE_RATE, MPU_LPF_RATE)){
Serial.println(F("log:Trying other MPU9150 address to init;"));
Serial.print(F("log:IMU Address was :"));
Serial.print(1);
MPUDeviceId = !MPUDeviceId;
Serial.print(F(" but is now:"));
Serial.print(MPUDeviceId);
Serial.println(";");
MPU.selectDevice(MPUDeviceId);
if (MPU.init(MPU_UPDATE_RATE, MPU_MAG_MIX_GYRO_AND_MAG, MAG_UPDATE_RATE, MPU_LPF_RATE)){
DidInit = true;
Serial.println(F("log:Init worked the second time;"));
} else {
Serial.println(F("log:Failed to init on both addresses;"));
}
} else {
DidInit = true;
Serial.println(F("log:init on primary addresses;"));
} // start the MPU
Settings::capability_bitarray |= (1 << COMPASS_CAPABLE);
Settings::capability_bitarray |= (1 << ORIENTATION_CAPABLE);
MPU9150ReInit.reset();
}
void MPU9150::device_loop(Command command){
if (!DidInit){
if( MPU9150ReInit.elapsed(30000)){
MPU9150::device_setup();
}
return;
}
if (command.cmp("ccal")){
// Compass_Calibrate();
// The IMU needs both Magnatrometer and Acceleromter to be calibrated. This attempts to do them both at the same time
calLibRead(MPUDeviceId, &calData); // pick up existing accel data if there
calData.accelValid = false;
calData.accelMinX = 0x7fff; // init accel cal data
calData.accelMaxX = 0x8000;
calData.accelMinY = 0x7fff;
calData.accelMaxY = 0x8000;
calData.accelMinZ = 0x7fff;
calData.accelMaxZ = 0x8000;
calData.magValid = false;
calData.magMinX = 0x7fff; // init mag cal data
calData.magMaxX = 0x8000;
calData.magMinY = 0x7fff;
calData.magMaxY = 0x8000;
calData.magMinZ = 0x7fff;
calData.magMaxZ = 0x8000;
MPU.useAccelCal(false);
//MPU.init(MPU_UPDATE_RATE, 5, 1, MPU_LPF_RATE);
counter = 359;
InCallibrationMode = true;
calibration_timer.reset();
Serial.println(F("!!!:While the compass counts down from 360 to 0, rotate the ROV slowly in all three axis;"));
}
if (InCallibrationMode){
bool changed = false;
if(counter>0){
if (MPU.read()) { // get the latest data
changed = false;
if (MPU.m_rawAccel[VEC3_X] < calData.accelMinX) {
calData.accelMinX = MPU.m_rawAccel[VEC3_X];
changed = true;
}
if (MPU.m_rawAccel[VEC3_X] > calData.accelMaxX) {
calData.accelMaxX = MPU.m_rawAccel[VEC3_X];
changed = true;
}
if (MPU.m_rawAccel[VEC3_Y] < calData.accelMinY) {
calData.accelMinY = MPU.m_rawAccel[VEC3_Y];
changed = true;
}
if (MPU.m_rawAccel[VEC3_Y] > calData.accelMaxY) {
calData.accelMaxY = MPU.m_rawAccel[VEC3_Y];
changed = true;
}
if (MPU.m_rawAccel[VEC3_Z] < calData.accelMinZ) {
calData.accelMinZ = MPU.m_rawAccel[VEC3_Z];
changed = true;
}
if (MPU.m_rawAccel[VEC3_Z] > calData.accelMaxZ) {
calData.accelMaxZ = MPU.m_rawAccel[VEC3_Z];
changed = true;
}
if (MPU.m_rawMag[VEC3_X] < calData.magMinX) {
calData.magMinX = MPU.m_rawMag[VEC3_X];
changed = true;
}
if (MPU.m_rawMag[VEC3_X] > calData.magMaxX) {
calData.magMaxX = MPU.m_rawMag[VEC3_X];
changed = true;
}
if (MPU.m_rawMag[VEC3_Y] < calData.magMinY) {
calData.magMinY = MPU.m_rawMag[VEC3_Y];
changed = true;
}
if (MPU.m_rawMag[VEC3_Y] > calData.magMaxY) {
calData.magMaxY = MPU.m_rawMag[VEC3_Y];
changed = true;
}
if (MPU.m_rawMag[VEC3_Z] < calData.magMinZ) {
calData.magMinZ = MPU.m_rawMag[VEC3_Z];
changed = true;
}
if (MPU.m_rawMag[VEC3_Z] > calData.magMaxZ) {
calData.magMaxZ = MPU.m_rawMag[VEC3_Z];
changed = true;
}
if (changed) {
Serial.print(F("dia:accel.MinX=")); Serial.print(calData.accelMinX); Serial.println(";");
Serial.print(F("dia:accel.maxX=")); Serial.print(calData.accelMaxX); Serial.println(";");
Serial.print(F("dia:accel.minY=")); Serial.print(calData.accelMinY); Serial.println(";");
Serial.print(F("dia:accel.maxY=")); Serial.print(calData.accelMaxY); Serial.println(";");
Serial.print(F("dia:accel.minZ=")); Serial.print(calData.accelMinZ); Serial.println(";");
Serial.print(F("dia:accel.maxZ=")); Serial.print(calData.accelMaxZ); Serial.println(";");
Serial.print(F("dia:mag.minX=")); Serial.print(calData.magMinX); Serial.println(";");
Serial.print(F("dia:mag.maxX=")); Serial.print(calData.magMaxX); Serial.println(";");
Serial.print(F("dia:mag.minY=")); Serial.print(calData.magMinY); Serial.println(";");
Serial.print(F("dia:mag.maxY=")); Serial.print(calData.magMaxY); Serial.println(";");
Serial.print(F("dia:mag.minZ=")); Serial.print(calData.magMinZ); Serial.println(";");
Serial.print(F("dia:mag.maxZ=")); Serial.print(calData.magMaxZ); Serial.println(";");
}
}
if (calibration_timer.elapsed (1000)) {
counter--;
navdata::HDGD = counter;
Serial.print(F("hdgd:"));
Serial.print(navdata::HDGD);
Serial.print(';');
}
}
if (counter <= 0){
calData.accelValid = true;
calData.magValid = true;
calLibWrite(MPUDeviceId, &calData);
Serial.println(F("log:Accel cal data saved for device;"));
InCallibrationMode = false;
}
return; //prevents the normal read and reporting of IMU data
}
else if (command.cmp("i2cscan")){
// scan();
}
// MPU.selectDevice(MPUDeviceId);
MPU.read();
// {
// Serial.println(F("log:SwappingIMUAddress;"));
// MPUDeviceId = !MPUDeviceId;
// MPU.selectDevice(MPUDeviceId);
// if(!MPU.read()){
// Serial.println(F("log:Failed to read IMU on both addresses. Sleeping for 1 minute"));
// DidInit = false;
// }
// }
navdata::HDGD = MPU.m_fusedEulerPose[VEC3_Z] * RAD_TO_DEGREE;
//To convert to-180/180 to 0/360
if (navdata::HDGD < 0) navdata::HDGD+=360;
navdata::PITC = MPU.m_fusedEulerPose[VEC3_X] * RAD_TO_DEGREE;
navdata::ROLL = MPU.m_fusedEulerPose[VEC3_Y] * RAD_TO_DEGREE;
navdata::YAW = MPU.m_fusedEulerPose[VEC3_Z] * RAD_TO_DEGREE;
}
#endif
<|endoftext|> |
<commit_before><commit_msg>Increased fill rate of the support 1st layer from 50% to 70%.<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <math.h>
#include <sys/times.h>
#include "../include/PSATsolver.hpp"
#include "../include/CVC4solver.hpp"
#include "../include/Parser.hpp"
using namespace std;
using namespace arma;
int PSATsolver::solve(int**& m,
vector<double>& prob,
double* time,
char* inputPath,
bool v)
{
Parser problem(inputPath);
prob = problem.getProbs();
return solve(m,
prob,
time,
problem.getClauses(),
v);
}
int PSATsolver::solve(int**& m,
vector<double>& prob,
double* time,
vector<vector<int>> clauses,
bool v)
{
struct tms tmsstart, tmsend;
clock_t start, end;
static long clktck = 0;
if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
cout << "sysconf error" << endl;
if ((start = times(&tmsstart)) == -1)
cout << "times error" << endl;
double delta = CVC4Solver::getDelta();
vector<double> cleaned;
vector<int> extra;
cleaned.push_back(1);
for(int i = 0; i < prob.size(); i++)
if(prob[i] == -1)
extra.push_back(i);
else
cleaned.push_back(prob[i]);
int n = cleaned.size();
mat B = supTriangle(n, cleaned);
mat c = makeCostVector(n, B, extra, clauses);
mat p = vectorToMat(cleaned);
mat pi = B.i()*p;
mat z = c.t()*pi;
if(v)
{
cout << "c:\n" << c << "\n";
cout << "B:\n" << B << "\n";
cout << "p:\n" << p << "\n";
cout << "pi:\n" << pi << "\n";
cout << "c*pi:" << z(0,0) << "\n";
}
int count = 0;
double min = 1;
vector<mat> partialSolutions;
while(z(0,0) > delta)
{
vector<double> coeffs = matToVector(c.t()*B.i());
int solIndex;
mat sol;
if(v)
cout << z << "\n";
solIndex = findSolutions(partialSolutions, coeffs);
if(solIndex > -1)
sol = partialSolutions[solIndex];
else
{
vector<int> newSolution = CVC4Solver::solve(coeffs,
extra,
clauses,
n-1);
if(newSolution[0] == 0)
{
if(v)
{
cout << "Unsat" << "\n";
cout << count << " iterations\n";
}
if ((end = times(&tmsend)) == -1)
cout << "times error" << endl;
prob.clear();
prob.push_back(0);
*time = ((tmsend.tms_utime - tmsstart.tms_utime) /
(double) clktck);
return n;
}
sol = vectorToMat(newSolution);
partialSolutions.push_back(sol);
}
mat teste = (c.t()*B.i())*sol;
if (teste(0,0) < min)
min = teste(0,0);
if(v)
cout << "min: " << min << "\n";
pivoting(B, pi, c, sol, p, v);
z = c.t()*pi;
count++;
}
mat onlyones = ones<mat>(n,1);
if(v)
{
cout << "c:\n" << c << "\n";
cout << "p:\n" << p << "\n";
cout << "c*pi:\n" << z(0,0) << "\n";
cout << "tem que ser 1: " << onlyones.t()*pi << "\n";
cout << "tem que ser p:\n" << B*pi << "\n";
cout << count << " iterações\n";
cout << "B:\n" << B << "\n";
cout << "pi:\n" << pi << "\n";
}
int** matrix = makeMatrix(n);
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
matrix[i][j] = B(i,j);
prob.clear();
prob.push_back(1);
for(int i = 0; i < pi.size(); i++)
prob.push_back(pi(i,0));
m = matrix;
if ((end = times(&tmsend)) == -1)
cout << "times error" << endl;
*time = ((tmsend.tms_utime - tmsstart.tms_utime) /
(double) clktck);
return n;
}
mat PSATsolver::supTriangle(int n, vector<double>& probs)
{
vector<double*> probsWithIndex;
for(int i = 0; i < probs.size(); i++)
{
double* temp = (double*) malloc((sizeof (double))*2);
temp[0] = probs[i];
temp[1] = (double) i;
probsWithIndex.push_back(temp);
}
sort(probsWithIndex.begin(), probsWithIndex.end(), lessProbs);
mat matrix = ones<mat>(n,n);
for(int i = 0; i < probs.size(); i++)
for(int j = 0; j < probs.size() - i - 1; j++)
{
int row = rint(probsWithIndex[i][1]);
matrix(row, j) = 0;
}
return matrix;
}
mat PSATsolver::makeCostVector(int n,
mat B,
vector<int>& free,
vector<vector<int>>& clauses)
{
mat c = ones<mat>(n,1);
for(int i = 0; i < B.n_cols; i++)
{
vector<int> col = matToVector(B.col(i));
}
cout << B;
exit(-1);
return c;
}
vector<double> PSATsolver::matToVector(mat A)
{
double iDelta = 1/CVC4Solver::getDelta();
vector<double> v;
for(int i = 0; i < A.n_cols; i++)
{
int temp;
if(A(0,i) >= 0)
temp = A(0,i)*iDelta;
else
temp = ceil(A(0,i)*iDelta);
v.push_back(temp/iDelta);
}
return v;
}
mat PSATsolver::vectorToMat(vector<int>& v)
{
mat A(v.size(), 1);
for(int i = 0; i < A.n_rows; i++)
{
A(i,0) = v[i];
}
return A;
}
mat PSATsolver::vectorToMat(vector<double>& v)
{
mat A(v.size(), 1);
for(int i = 0; i < A.n_rows; i++)
{
A(i,0) = v[i];
}
return A;
}
int** PSATsolver::makeMatrix(int n)
{
int** matrix = (int**) malloc((sizeof (int*)) * n);
for(int i = 0; i < n; i ++)
matrix[i] = (int*) malloc((sizeof (int)) * n);
return matrix;
}
void PSATsolver::pivoting(mat& B,
mat& pi,
mat& c,
mat Aj,
mat p,
bool v)
{
double delta = CVC4Solver::getDelta();
double min = 2;
int minIndex = -1;
mat Xj = B.i()*Aj;
for(int i = 0; i < Xj.n_rows; i++)
{
if(Xj(i,0) > delta && pi(i,0)/Xj(i,0) < min - delta)
{
min = pi(i,0)/Xj(i,0);
minIndex = i;
if (min < delta)
break;
}
}
B.insert_cols(minIndex, Aj);
B.shed_col(minIndex+1);
c(minIndex,0) = 0;
if(v)
cout << "B:\n" << B << "\n";
if(arma::rank(B) < B.n_cols)
{
cout << "Caso degenerado" << "\n";
exit(-1);
}
pi = B.i()*p;
}
int PSATsolver::findSolutions(vector<mat>& matrix, mat coeffs)
{
double delta = CVC4Solver::getDelta();
for(int i = 0; i < matrix.size(); i++)
{
mat check = coeffs.t()*matrix[i];
if(check(0,0) > delta*matrix[i].n_rows)
return i;
}
return -1;
}
bool PSATsolver::lessProbs(double *a, double* b)
{
return a[0] < b[0];
}
<commit_msg>Working on ordering A<commit_after>#include <iostream>
#include <math.h>
#include <sys/times.h>
#include "../include/PSATsolver.hpp"
#include "../include/CVC4solver.hpp"
#include "../include/Parser.hpp"
using namespace std;
using namespace arma;
int PSATsolver::solve(int**& m,
vector<double>& prob,
double* time,
char* inputPath,
bool v)
{
Parser problem(inputPath);
prob = problem.getProbs();
return solve(m,
prob,
time,
problem.getClauses(),
v);
}
int PSATsolver::solve(int**& m,
vector<double>& prob,
double* time,
vector<vector<int>> clauses,
bool v)
{
struct tms tmsstart, tmsend;
clock_t start, end;
static long clktck = 0;
if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
cout << "sysconf error" << endl;
if ((start = times(&tmsstart)) == -1)
cout << "times error" << endl;
double delta = CVC4Solver::getDelta();
vector<double> cleaned;
vector<int> extra;
cleaned.push_back(1);
for(int i = 0; i < prob.size(); i++)
if(prob[i] == -1)
extra.push_back(i);
else
cleaned.push_back(prob[i]);
int n = cleaned.size();
mat B = supTriangle(n, cleaned);
mat c = makeCostVector(n, B, extra, clauses);
mat p = vectorToMat(cleaned);
mat pi = B.i()*p;
mat z = c.t()*pi;
if(v)
{
cout << "c:\n" << c << "\n";
cout << "B:\n" << B << "\n";
cout << "p:\n" << p << "\n";
cout << "pi:\n" << pi << "\n";
cout << "c*pi:" << z(0,0) << "\n";
}
int count = 0;
double min = 1;
vector<mat> partialSolutions;
while(z(0,0) > delta)
{
vector<double> coeffs = matToVector(c.t()*B.i());
int solIndex;
mat sol;
if(v)
cout << z << "\n";
solIndex = findSolutions(partialSolutions, coeffs);
if(solIndex > -1)
sol = partialSolutions[solIndex];
else
{
vector<int> newSolution = CVC4Solver::solve(coeffs,
extra,
clauses,
n-1);
if(newSolution[0] == 0)
{
if(v)
{
cout << "Unsat" << "\n";
cout << count << " iterations\n";
}
if ((end = times(&tmsend)) == -1)
cout << "times error" << endl;
prob.clear();
prob.push_back(0);
*time = ((tmsend.tms_utime - tmsstart.tms_utime) /
(double) clktck);
return n;
}
sol = vectorToMat(newSolution);
partialSolutions.push_back(sol);
}
mat teste = (c.t()*B.i())*sol;
if (teste(0,0) < min)
min = teste(0,0);
if(v)
cout << "min: " << min << "\n";
pivoting(B, pi, c, sol, p, v);
z = c.t()*pi;
count++;
}
mat onlyones = ones<mat>(n,1);
if(v)
{
cout << "c:\n" << c << "\n";
cout << "p:\n" << p << "\n";
cout << "c*pi:\n" << z(0,0) << "\n";
cout << "tem que ser 1: " << onlyones.t()*pi << "\n";
cout << "tem que ser p:\n" << B*pi << "\n";
cout << count << " iterações\n";
cout << "B:\n" << B << "\n";
cout << "pi:\n" << pi << "\n";
}
int** matrix = makeMatrix(n);
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
matrix[i][j] = B(i,j);
prob.clear();
prob.push_back(1);
for(int i = 0; i < pi.size(); i++)
prob.push_back(pi(i,0));
m = matrix;
if ((end = times(&tmsend)) == -1)
cout << "times error" << endl;
*time = ((tmsend.tms_utime - tmsstart.tms_utime) /
(double) clktck);
return n;
}
mat PSATsolver::supTriangle(int n, vector<double>& probs)
{
vector<double*> probsWithIndex;
for(int i = 0; i < probs.size(); i++)
{
double* temp = (double*) malloc((sizeof (double))*2);
temp[0] = probs[i];
temp[1] = (double) i;
probsWithIndex.push_back(temp);
}
sort(probsWithIndex.begin(), probsWithIndex.end(), lessProbs);
mat matrix = ones<mat>(n,n);
for(int i = 0; i < probs.size(); i++)
for(int j = 0; j < probs.size() - i - 1; j++)
{
int row = rint(probsWithIndex[i][1]);
matrix(row, j) = 0;
}
return matrix;
}
mat PSATsolver::makeCostVector(int n,
mat B,
vector<int>& free,
vector<vector<int>>& clauses)
{
mat c = ones<mat>(n,1);
for(int i = 0; i < B.n_cols; i++)
{
vector<int> col = matToVector(B.col(i));
bool sat = CVC4solver::isSat(col, free, clauses, n);
if(sat)
c(i,0) = 0.0;
}
cout << c;
exit(-1);
return c;
}
vector<double> PSATsolver::matToVector(mat A)
{
double iDelta = 1/CVC4Solver::getDelta();
vector<double> v;
for(int i = 0; i < A.n_cols; i++)
{
int temp;
if(A(0,i) >= 0)
temp = A(0,i)*iDelta;
else
temp = ceil(A(0,i)*iDelta);
v.push_back(temp/iDelta);
}
return v;
}
vector<int> PSATsolver::matToVector(mat A)
{
double iDelta = 1/CVC4Solver::getDelta();
vector<int> v;
for(int i = 0; i < A.n_cols; i++)
v.push_back(rint(A(i,0)));
return v;
}
mat PSATsolver::vectorToMat(vector<int>& v)
{
mat A(v.size(), 1);
for(int i = 0; i < A.n_rows; i++)
{
A(i,0) = v[i];
}
return A;
}
mat PSATsolver::vectorToMat(vector<double>& v)
{
mat A(v.size(), 1);
for(int i = 0; i < A.n_rows; i++)
{
A(i,0) = v[i];
}
return A;
}
int** PSATsolver::makeMatrix(int n)
{
int** matrix = (int**) malloc((sizeof (int*)) * n);
for(int i = 0; i < n; i ++)
matrix[i] = (int*) malloc((sizeof (int)) * n);
return matrix;
}
void PSATsolver::pivoting(mat& B,
mat& pi,
mat& c,
mat Aj,
mat p,
bool v)
{
double delta = CVC4Solver::getDelta();
double min = 2;
int minIndex = -1;
mat Xj = B.i()*Aj;
for(int i = 0; i < Xj.n_rows; i++)
{
if(Xj(i,0) > delta && pi(i,0)/Xj(i,0) < min - delta)
{
min = pi(i,0)/Xj(i,0);
minIndex = i;
if (min < delta)
break;
}
}
B.insert_cols(minIndex, Aj);
B.shed_col(minIndex+1);
c(minIndex,0) = 0;
if(v)
cout << "B:\n" << B << "\n";
if(arma::rank(B) < B.n_cols)
{
cout << "Caso degenerado" << "\n";
exit(-1);
}
pi = B.i()*p;
}
int PSATsolver::findSolutions(vector<mat>& matrix, mat coeffs)
{
double delta = CVC4Solver::getDelta();
for(int i = 0; i < matrix.size(); i++)
{
mat check = coeffs.t()*matrix[i];
if(check(0,0) > delta*matrix[i].n_rows)
return i;
}
return -1;
}
bool PSATsolver::lessProbs(double *a, double* b)
{
return a[0] < b[0];
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2013-2014 PX4 Development Team. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file navigator_rtl.cpp
* Helper class to access RTL
* @author Julian Oes <julian@oes.ch>
* @author Anton Babushkin <anton.babushkin@me.com>
*/
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <fcntl.h>
#include <mavlink/mavlink_log.h>
#include <systemlib/err.h>
#include <geo/geo.h>
#include <uORB/uORB.h>
#include <navigator/navigation.h>
#include <uORB/topics/home_position.h>
#include "navigator.h"
#include "rtl.h"
#define DELAY_SIGMA 0.01f
RTL::RTL(Navigator *navigator, const char *name) :
MissionBlock(navigator, name),
_rtl_state(RTL_STATE_NONE),
_rtl_start_lock(false),
_param_return_alt(this, "RTL_RETURN_ALT", false),
_param_descend_alt(this, "RTL_DESCEND_ALT", false),
_param_land_delay(this, "RTL_LAND_DELAY", false)
{
/* load initial params */
updateParams();
/* initial reset */
on_inactive();
}
RTL::~RTL()
{
}
void
RTL::on_inactive()
{
/* reset RTL state only if setpoint moved */
if (!_navigator->get_can_loiter_at_sp()) {
_rtl_state = RTL_STATE_NONE;
}
}
void
RTL::on_activation()
{
/* decide where to enter the RTL procedure when we switch into it */
if (_rtl_state == RTL_STATE_NONE) {
/* for safety reasons don't go into RTL if landed */
if (_navigator->get_vstatus()->condition_landed) {
_rtl_state = RTL_STATE_LANDED;
mavlink_log_critical(_navigator->get_mavlink_fd(), "no RTL when landed");
/* if lower than return altitude, climb up first */
} else if (_navigator->get_global_position()->alt < _navigator->get_home_position()->alt
+ _param_return_alt.get()) {
_rtl_state = RTL_STATE_CLIMB;
_rtl_start_lock = false;
/* otherwise go straight to return */
} else {
/* set altitude setpoint to current altitude */
_rtl_state = RTL_STATE_RETURN;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_global_position()->alt;
_rtl_start_lock = false;
}
}
set_rtl_item();
}
void
RTL::on_active()
{
if (_rtl_state != RTL_STATE_LANDED && is_mission_item_reached()) {
advance_rtl();
set_rtl_item();
}
}
void
RTL::set_rtl_item()
{
struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();
/* make sure we have the latest params */
updateParams();
if (!_rtl_start_lock) {
set_previous_pos_setpoint();
}
_navigator->set_can_loiter_at_sp(false);
switch (_rtl_state) {
case RTL_STATE_CLIMB: {
float climb_alt = _navigator->get_home_position()->alt + _param_return_alt.get();
_mission_item.lat = _navigator->get_global_position()->lat;
_mission_item.lon = _navigator->get_global_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = climb_alt;
_mission_item.yaw = NAN;
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_WAYPOINT;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = true;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: climb to %d m (%d m above home)",
(int)(climb_alt),
(int)(climb_alt - _navigator->get_home_position()->alt));
break;
}
case RTL_STATE_RETURN: {
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
// don't change altitude
if (pos_sp_triplet->previous.valid) {
/* if previous setpoint is valid then use it to calculate heading to home */
_mission_item.yaw = get_bearing_to_next_waypoint(
pos_sp_triplet->previous.lat, pos_sp_triplet->previous.lon,
_mission_item.lat, _mission_item.lon);
} else {
/* else use current position */
_mission_item.yaw = get_bearing_to_next_waypoint(
_navigator->get_global_position()->lat, _navigator->get_global_position()->lon,
_mission_item.lat, _mission_item.lon);
}
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_WAYPOINT;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = true;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: return at %d m (%d m above home)",
(int)(_mission_item.altitude),
(int)(_mission_item.altitude - _navigator->get_home_position()->alt));
_rtl_start_lock = true;
break;
}
case RTL_STATE_DESCEND: {
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get();
_mission_item.yaw = _navigator->get_home_position()->yaw;
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_LOITER_TIME_LIMIT;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = false;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: descend to %d m (%d m above home)",
(int)(_mission_item.altitude),
(int)(_mission_item.altitude - _navigator->get_home_position()->alt));
break;
}
case RTL_STATE_LOITER: {
bool autoland = _param_land_delay.get() > -DELAY_SIGMA;
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get();
_mission_item.yaw = NAN;
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = autoland ? NAV_CMD_LOITER_TIME_LIMIT : NAV_CMD_LOITER_UNLIMITED;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get();
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = autoland;
_mission_item.origin = ORIGIN_ONBOARD;
_navigator->set_can_loiter_at_sp(true);
if (autoland) {
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: loiter %.1fs", (double)_mission_item.time_inside);
} else {
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: completed, loiter");
}
break;
}
case RTL_STATE_LAND: {
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_home_position()->alt;
_mission_item.yaw = NAN;
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_LAND;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = true;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: land at home");
break;
}
case RTL_STATE_LANDED: {
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_home_position()->alt;
_mission_item.yaw = NAN;
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_IDLE;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = true;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: completed, landed");
break;
}
default:
break;
}
reset_mission_item_reached();
/* convert mission item to current position setpoint and make it valid */
mission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);
pos_sp_triplet->next.valid = false;
_navigator->set_position_setpoint_triplet_updated();
}
void
RTL::advance_rtl()
{
switch (_rtl_state) {
case RTL_STATE_CLIMB:
_rtl_state = RTL_STATE_RETURN;
break;
case RTL_STATE_RETURN:
_rtl_state = RTL_STATE_DESCEND;
break;
case RTL_STATE_DESCEND:
/* only go to land if autoland is enabled */
if (_param_land_delay.get() < -DELAY_SIGMA || _param_land_delay.get() > DELAY_SIGMA) {
_rtl_state = RTL_STATE_LOITER;
} else {
_rtl_state = RTL_STATE_LAND;
}
break;
case RTL_STATE_LOITER:
_rtl_state = RTL_STATE_LAND;
break;
case RTL_STATE_LAND:
_rtl_state = RTL_STATE_LANDED;
break;
default:
break;
}
}
<commit_msg>Add missing yaw entries<commit_after>/****************************************************************************
*
* Copyright (c) 2013-2014 PX4 Development Team. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file navigator_rtl.cpp
* Helper class to access RTL
* @author Julian Oes <julian@oes.ch>
* @author Anton Babushkin <anton.babushkin@me.com>
*/
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <fcntl.h>
#include <mavlink/mavlink_log.h>
#include <systemlib/err.h>
#include <geo/geo.h>
#include <uORB/uORB.h>
#include <navigator/navigation.h>
#include <uORB/topics/home_position.h>
#include "navigator.h"
#include "rtl.h"
#define DELAY_SIGMA 0.01f
RTL::RTL(Navigator *navigator, const char *name) :
MissionBlock(navigator, name),
_rtl_state(RTL_STATE_NONE),
_rtl_start_lock(false),
_param_return_alt(this, "RTL_RETURN_ALT", false),
_param_descend_alt(this, "RTL_DESCEND_ALT", false),
_param_land_delay(this, "RTL_LAND_DELAY", false)
{
/* load initial params */
updateParams();
/* initial reset */
on_inactive();
}
RTL::~RTL()
{
}
void
RTL::on_inactive()
{
/* reset RTL state only if setpoint moved */
if (!_navigator->get_can_loiter_at_sp()) {
_rtl_state = RTL_STATE_NONE;
}
}
void
RTL::on_activation()
{
/* decide where to enter the RTL procedure when we switch into it */
if (_rtl_state == RTL_STATE_NONE) {
/* for safety reasons don't go into RTL if landed */
if (_navigator->get_vstatus()->condition_landed) {
_rtl_state = RTL_STATE_LANDED;
mavlink_log_critical(_navigator->get_mavlink_fd(), "no RTL when landed");
/* if lower than return altitude, climb up first */
} else if (_navigator->get_global_position()->alt < _navigator->get_home_position()->alt
+ _param_return_alt.get()) {
_rtl_state = RTL_STATE_CLIMB;
_rtl_start_lock = false;
/* otherwise go straight to return */
} else {
/* set altitude setpoint to current altitude */
_rtl_state = RTL_STATE_RETURN;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_global_position()->alt;
_rtl_start_lock = false;
}
}
set_rtl_item();
}
void
RTL::on_active()
{
if (_rtl_state != RTL_STATE_LANDED && is_mission_item_reached()) {
advance_rtl();
set_rtl_item();
}
}
void
RTL::set_rtl_item()
{
struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();
/* make sure we have the latest params */
updateParams();
if (!_rtl_start_lock) {
set_previous_pos_setpoint();
}
_navigator->set_can_loiter_at_sp(false);
switch (_rtl_state) {
case RTL_STATE_CLIMB: {
float climb_alt = _navigator->get_home_position()->alt + _param_return_alt.get();
_mission_item.lat = _navigator->get_global_position()->lat;
_mission_item.lon = _navigator->get_global_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = climb_alt;
_mission_item.yaw = NAN;
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_WAYPOINT;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = true;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: climb to %d m (%d m above home)",
(int)(climb_alt),
(int)(climb_alt - _navigator->get_home_position()->alt));
break;
}
case RTL_STATE_RETURN: {
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
// don't change altitude
if (pos_sp_triplet->previous.valid) {
/* if previous setpoint is valid then use it to calculate heading to home */
_mission_item.yaw = get_bearing_to_next_waypoint(
pos_sp_triplet->previous.lat, pos_sp_triplet->previous.lon,
_mission_item.lat, _mission_item.lon);
} else {
/* else use current position */
_mission_item.yaw = get_bearing_to_next_waypoint(
_navigator->get_global_position()->lat, _navigator->get_global_position()->lon,
_mission_item.lat, _mission_item.lon);
}
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_WAYPOINT;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = true;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: return at %d m (%d m above home)",
(int)(_mission_item.altitude),
(int)(_mission_item.altitude - _navigator->get_home_position()->alt));
_rtl_start_lock = true;
break;
}
case RTL_STATE_DESCEND: {
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get();
_mission_item.yaw = _navigator->get_home_position()->yaw;
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_LOITER_TIME_LIMIT;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = false;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: descend to %d m (%d m above home)",
(int)(_mission_item.altitude),
(int)(_mission_item.altitude - _navigator->get_home_position()->alt));
break;
}
case RTL_STATE_LOITER: {
bool autoland = _param_land_delay.get() > -DELAY_SIGMA;
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_home_position()->alt + _param_descend_alt.get();
_mission_item.yaw = _navigator->get_home_position()->yaw;
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = autoland ? NAV_CMD_LOITER_TIME_LIMIT : NAV_CMD_LOITER_UNLIMITED;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = _param_land_delay.get() < 0.0f ? 0.0f : _param_land_delay.get();
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = autoland;
_mission_item.origin = ORIGIN_ONBOARD;
_navigator->set_can_loiter_at_sp(true);
if (autoland) {
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: loiter %.1fs", (double)_mission_item.time_inside);
} else {
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: completed, loiter");
}
break;
}
case RTL_STATE_LAND: {
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_home_position()->alt;
_mission_item.yaw = _navigator->get_home_position()->yaw;
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_LAND;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = true;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: land at home");
break;
}
case RTL_STATE_LANDED: {
_mission_item.lat = _navigator->get_home_position()->lat;
_mission_item.lon = _navigator->get_home_position()->lon;
_mission_item.altitude_is_relative = false;
_mission_item.altitude = _navigator->get_home_position()->alt;
// Do not change / control yaw in landed
_mission_item.yaw = NAN;
_mission_item.loiter_radius = _navigator->get_loiter_radius();
_mission_item.loiter_direction = 1;
_mission_item.nav_cmd = NAV_CMD_IDLE;
_mission_item.acceptance_radius = _navigator->get_acceptance_radius();
_mission_item.time_inside = 0.0f;
_mission_item.pitch_min = 0.0f;
_mission_item.autocontinue = true;
_mission_item.origin = ORIGIN_ONBOARD;
mavlink_log_critical(_navigator->get_mavlink_fd(), "RTL: completed, landed");
break;
}
default:
break;
}
reset_mission_item_reached();
/* convert mission item to current position setpoint and make it valid */
mission_item_to_position_setpoint(&_mission_item, &pos_sp_triplet->current);
pos_sp_triplet->next.valid = false;
_navigator->set_position_setpoint_triplet_updated();
}
void
RTL::advance_rtl()
{
switch (_rtl_state) {
case RTL_STATE_CLIMB:
_rtl_state = RTL_STATE_RETURN;
break;
case RTL_STATE_RETURN:
_rtl_state = RTL_STATE_DESCEND;
break;
case RTL_STATE_DESCEND:
/* only go to land if autoland is enabled */
if (_param_land_delay.get() < -DELAY_SIGMA || _param_land_delay.get() > DELAY_SIGMA) {
_rtl_state = RTL_STATE_LOITER;
} else {
_rtl_state = RTL_STATE_LAND;
}
break;
case RTL_STATE_LOITER:
_rtl_state = RTL_STATE_LAND;
break;
case RTL_STATE_LAND:
_rtl_state = RTL_STATE_LANDED;
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __RAPICORN_PIXMAP_HH__
#define __RAPICORN_PIXMAP_HH__
#include <rcore/utilities.hh>
namespace Rapicorn {
/// A Pixmap (i.e. PixmapT<Pixbuf>) conveniently wraps a Pixbuf and provides various pixel operations.
template<class Pixbuf>
class PixmapT {
std::shared_ptr<Pixbuf> m_pixbuf;
public:
explicit PixmapT (); ///< Construct Pixmap with 0x0 pixesl.
explicit PixmapT (uint w, uint h); ///< Construct Pixmap at given width and height.
explicit PixmapT (const Pixbuf &source); ///< Copy-construct Pixmap from a Pixbuf structure.
explicit PixmapT (const String &res_png); ///< Construct Pixmap from a PNG resource blob.
PixmapT& operator= (const Pixbuf &source); ///< Re-initialize the Pixmap from a Pixbuf structure.
int width () const { return m_pixbuf->width(); } ///< Get the width of the Pixmap.
int height () const { return m_pixbuf->height(); } ///< Get the height of the Pixmap.
void resize (uint w, uint h); ///< Reset width and height and resize pixel sequence.
bool try_resize (uint w, uint h); ///< Resize unless width and height are too big.
const uint32* row (uint y) const { return m_pixbuf->row (y); } ///< Access row read-only.
uint32* row (uint y) { return m_pixbuf->row (y); } ///< Access row as endian dependant ARGB integers.
uint32& pixel (uint x, uint y) { return m_pixbuf->row (y)[x]; } ///< Retrieve an ARGB pixel value reference.
uint32 pixel (uint x, uint y) const { return m_pixbuf->row (y)[x]; } ///< Retrieve an ARGB pixel value.
bool load_png (const String &filename, bool tryrepair = false); ///< Load from PNG file, assigns errno on failure.
bool load_png (size_t nbytes, const char *bytes, bool tryrepair = false); ///< Load PNG data, sets errno.
bool save_png (const String &filename); ///< Save to PNG, assigns errno on failure.
bool load_pixstream (const uint8 *pixstream); ///< Decode and load from pixel stream, assigns errno on failure.
void set_attribute (const String &name, const String &value); ///< Set string attribute, e.g. "comment".
String get_attribute (const String &name) const; ///< Get string attribute, e.g. "comment".
void copy (const Pixbuf &source, uint sx, uint sy,
int swidth, int sheight, uint tx, uint ty); ///< Copy a Pixbuf area into this pximap.
bool compare (const Pixbuf &source, uint sx, uint sy, int swidth, int sheight,
uint tx, uint ty, double *averrp = NULL, double *maxerrp = NULL, double *nerrp = NULL,
double *npixp = NULL) const; ///< Compare area and calculate difference metrics.
operator const Pixbuf& () const { return *m_pixbuf; } ///< Allow automatic conversion of a Pixmap into a Pixbuf.
};
// RAPICORN_PIXBUF_TYPE is defined in <rcore/clientapi.hh> and <rcore/serverapi.hh>
typedef PixmapT<RAPICORN_PIXBUF_TYPE> Pixmap; ///< Pixmap is a convenience alias for PixmapT<Pixbuf>.
} // Rapicorn
#endif /* __RAPICORN_PIXMAP_HH__ */
<commit_msg>RCORE: Pixmap docu additions<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __RAPICORN_PIXMAP_HH__
#define __RAPICORN_PIXMAP_HH__
#include <rcore/utilities.hh>
namespace Rapicorn {
/** Pixmap (PixmapT) is a Pixbuf wrapper template which provides various pixel operations.
* A Pixmap really is defined as PixmapT<Pixbuf>, a template class around Pixbuf which
* provides automatic memory management, pixel operations and IO functions.
* This class stores ARGB pixels of size @a width * @a height. The pixels are stored as unsigned
* 32-bit values in native endian format with premultiplied alpha (compatible with libcairo).
* The @a comment attribute is preserved during saving and loading by some file formats, such as PNG.
*/
template<class Pixbuf>
class PixmapT {
std::shared_ptr<Pixbuf> m_pixbuf;
public:
explicit PixmapT (); ///< Construct Pixmap with 0x0 pixesl.
explicit PixmapT (uint w, uint h); ///< Construct Pixmap at given width and height.
explicit PixmapT (const Pixbuf &source); ///< Copy-construct Pixmap from a Pixbuf structure.
explicit PixmapT (const String &res_png); ///< Construct Pixmap from a PNG resource blob.
PixmapT& operator= (const Pixbuf &source); ///< Re-initialize the Pixmap from a Pixbuf structure.
int width () const { return m_pixbuf->width(); } ///< Get the width of the Pixmap.
int height () const { return m_pixbuf->height(); } ///< Get the height of the Pixmap.
void resize (uint w, uint h); ///< Reset width and height and resize pixel sequence.
bool try_resize (uint w, uint h); ///< Resize unless width and height are too big.
const uint32* row (uint y) const { return m_pixbuf->row (y); } ///< Access row read-only.
uint32* row (uint y) { return m_pixbuf->row (y); } ///< Access row as endian dependant ARGB integers.
uint32& pixel (uint x, uint y) { return m_pixbuf->row (y)[x]; } ///< Retrieve an ARGB pixel value reference.
uint32 pixel (uint x, uint y) const { return m_pixbuf->row (y)[x]; } ///< Retrieve an ARGB pixel value.
bool load_png (const String &filename, bool tryrepair = false); ///< Load from PNG file, assigns errno on failure.
bool load_png (size_t nbytes, const char *bytes, bool tryrepair = false); ///< Load PNG data, sets errno.
bool save_png (const String &filename); ///< Save to PNG, assigns errno on failure.
bool load_pixstream (const uint8 *pixstream); ///< Decode and load from pixel stream, assigns errno on failure.
void set_attribute (const String &name, const String &value); ///< Set string attribute, e.g. "comment".
String get_attribute (const String &name) const; ///< Get string attribute, e.g. "comment".
void copy (const Pixbuf &source, uint sx, uint sy,
int swidth, int sheight, uint tx, uint ty); ///< Copy a Pixbuf area into this pximap.
bool compare (const Pixbuf &source, uint sx, uint sy, int swidth, int sheight,
uint tx, uint ty, double *averrp = NULL, double *maxerrp = NULL, double *nerrp = NULL,
double *npixp = NULL) const; ///< Compare area and calculate difference metrics.
operator const Pixbuf& () const { return *m_pixbuf; } ///< Allow automatic conversion of a Pixmap into a Pixbuf.
};
// RAPICORN_PIXBUF_TYPE is defined in <rcore/clientapi.hh> and <rcore/serverapi.hh>
typedef PixmapT<RAPICORN_PIXBUF_TYPE> Pixmap; ///< Pixmap is a convenience alias for PixmapT<Pixbuf>.
} // Rapicorn
#endif /* __RAPICORN_PIXMAP_HH__ */
<|endoftext|> |
<commit_before>/*
BelaCsound.cpp:
Copyright (C) 2017 V Lazzarini
This file is part of Csound.
The Csound 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.
Csound 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 Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
#include <Bela.h>
#include <Midi.h>
#include <csound/csound.hpp>
#include <csound/plugin.h>
#include <vector>
#include <sstream>
#define ANCHNS 8
static int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiInDevice(CSOUND *csound, void *userData);
static int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,
int nbytes);
static int OpenMidiOutDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiOutDevice(CSOUND *csound, void *userData);
static int WriteMidiData(CSOUND *csound, void *userData, const unsigned char *mbuf,
int nbytes);
/** DigiIn opcode
ksig digiInBela ipin
asig digiInBela ipin
*/
struct DigiIn : csnd::Plugin<1, 1> {
int pin;
int fcount;
int frms;
init init_done;
BelaContext *context;
int init() {
pin = (int) inargs[0];
if(pin < 0 ) pin = 0;
if(pin > 15) pin = 15;
context = (BelaContext *) csound->host_data();
fcount = 0;
init_done = 0;
frms = context->digitalFrames;
return OK;
}
int kperf() {
if(!init_done) {
pinMode(context,0,pin,0);
init_done = 1;
}
outargs[0] = (MYFLT) digitalRead(context,fcount,pin);
fcount += nsmps;
fcount %= frms;
return OK;
}
int aperf() {
csnd::AudioSig out(this, outargs(0));
int cnt = fcount;
if(!init_done) {
pinMode(context,0,pin,0);
init_done = 1;
}
for (auto &s : out) {
s = (MYFLT) digitalRead(context,cnt,pin);
if(cnt == frms - 1) cnt = 0;
else cnt++;
}
fcount = cnt;
return OK;
}
};
/** DigiOut opcode
digiOutBela ksig,ipin
digiOutBela asig,ipin
*/
struct DigiOut : csnd::Plugin<0, 2> {
int pin;
int fcount;
int frms;
int init_done;
BelaContext *context;
int init() {
pin = (int) inargs[1];
if(pin < 0 ) pin = 0;
if(pin > 15) pin = 15;
context = (BelaContext *) csound->host_data();
init_done = 0;
fcount = 0;
frms = context->digitalFrames;
return OK;
}
int kperf() {
if(!init_done) {
pinMode(context,0,pin,1);
init_done = 1;
}
digitalWrite(context,fcount,pin,(inargs[0] > 0.0 ? 1 : 0));
fcount += nsmps;
fcount %= frms;
return OK;
}
int aperf() {
csnd::AudioSig in(this, inargs(0));
int cnt = fcount;
if(!init_done) {
pinMode(context,0,pin,1);
init_done = 1;
}
for (auto s : in) {
digitalWriteOnce(context,cnt,pin, (s > 0.0 ? 1 : 0));
if(cnt == frms - 1) cnt = 0;
else cnt++;
}
fcount = cnt;
return OK;
}
};
struct CsChan {
std::vector<MYFLT> data;
std::stringstream name;
};
struct CsData {
Csound *csound;
int blocksize;
int res;
int count;
CsChan channel[ANCHNS];
CsChan ochannel[ANCHNS];
};
static CsData gCsData;
static Midi gMidi;
bool setup(BelaContext *context, void *Data)
{
Csound *csound;
const char *csdfile = "my.csd"; /* CSD name */
const char *midiDev = "-Mhw:1,0,0"; /* MIDI IN device */
const char *midiOutDev = "-Qhw:1,0,0"; /* MIDI OUT device */
const char *args[] = { "csound", csdfile, "-iadc", "-odac", "-+rtaudio=null",
"--realtime", "--daemon", midiDev, midiOutDev };
int numArgs = (int) (sizeof(args)/sizeof(char *));
if(context->audioInChannels != context->audioOutChannels) {
printf("Error: number of audio inputs != number of audio outputs.\n");
return false;
}
if(context->analogInChannels != context->analogOutChannels) {
printf("Error: number of analog inputs != number of analog outputs.\n");
return false;
}
/* set up Csound */
csound = new Csound();
gCsData.csound = csound;
csound->SetHostData((void *) context);
csound->SetHostImplementedAudioIO(1,0);
csound->SetHostImplementedMIDIIO(1);
csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);
csound->SetExternalMidiReadCallback(ReadMidiData);
csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);
csound->SetExternalMidiOutOpenCallback(OpenMidiOutDevice);
csound->SetExternalMidiWriteCallback(WriteMidiData);
csound->SetExternalMidiOutCloseCallback(CloseMidiOutDevice);
/* set up digi opcodes */
if(csnd::plugin<DigiIn>((csnd::Csound *) csound->GetCsound(), "digiInBela" , "k",
"i", csnd::thread::ik) != 0)
printf("Warning: could not add digiInBela k-rate opcode\n");
if(csnd::plugin<DigiIn>((csnd::Csound *) csound->GetCsound(), "digiInBela" , "a",
"i", csnd::thread::ia) != 0)
printf("Warning: could not add digiInBela a-rate opcode\n");
if(csnd::plugin<DigiOut>((csnd::Csound *) csound->GetCsound(), "digiOutBela" , "",
"ki", csnd::thread::ik) != 0)
printf("Warning: could not add digiOutBela k-rate opcode\n");
if(csnd::plugin<DigiOut>((csnd::Csound *) csound->GetCsound(), "digiOutBela" , "",
"ai", csnd::thread::ia) != 0)
printf("Warning: could not add digiOutBela a-rate opcode\n");
if((gCsData.res = csound->Compile(numArgs, args)) != 0) {
printf("Error: Csound could not compile CSD file.\n");
return false;
}
gCsData.blocksize = csound->GetKsmps()*csound->GetNchnls();
gCsData.count = 0;
/* set up the channels */
for(int i=0; i < ANCHNS; i++) {
gCsData.channel[i].data.resize(csound->GetKsmps());
gCsData.channel[i].name << "analogIn" << i+1;
gCsData.ochannel[i].data.resize(csound->GetKsmps());
gCsData.ochannel[i].name << "analogOut" << i+1;
}
return true;
}
void render(BelaContext *context, void *Data)
{
if(gCsData.res == 0) {
int n,i,k,count, frmcount,blocksize,res;
Csound *csound = gCsData.csound;
MYFLT scal = csound->Get0dBFS();
MYFLT* audioIn = csound->GetSpin();
MYFLT* audioOut = csound->GetSpout();
int nchnls = csound->GetNchnls();
int chns = nchnls < context->audioOutChannels ?
nchnls : context->audioOutChannels;
int an_chns = context->analogInChannels > ANCHNS ?
ANCHNS : context->analogInChannels;
CsChan *channel = &(gCsData.channel[0]);
CsChan *ochannel = &(gCsData.ochannel[0]);
float frm = 0.f, incr = ((float) context->analogFrames)/context->audioFrames;
count = gCsData.count;
blocksize = gCsData.blocksize;
/* processing loop */
for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){
if(count == blocksize) {
/* set the channels */
for(i = 0; i < an_chns; i++) {
csound->SetChannel(channel[i].name.str().c_str(),
&(channel[i].data[0]));
csound->GetAudioChannel(ochannel[i].name.str().c_str(),
&(ochannel[i].data[0]));
}
/* run csound */
if((res = csound->PerformKsmps()) == 0) count = 0;
else break;
}
/* read/write audio data */
for(i = 0; i < chns; i++){
audioIn[count+i] = audioRead(context,n,i);
audioWrite(context,n,i,audioOut[count+i]/scal);
}
/* read analogue data
analogue frame pos frm gets incremented according to the
ratio analogFrames/audioFrames.
*/
frmcount = count/nchnls;
for(i = 0; i < an_chns; i++) {
k = (int) frm;
channel[i].data[frmcount] = analogRead(context,k,i);
analogWriteOnce(context,k,i,ochannel[i].data[frmcount]);
}
}
gCsData.res = res;
gCsData.count = count;
}
}
void cleanup(BelaContext *context, void *Data)
{
delete gCsData.csound;
}
/** MIDI Input functions
*/
int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {
if(gMidi.readFrom(dev) == 1) {
gMidi.enableParser(false);
*userData = (void *) &gMidi;
return 0;
}
csoundMessage(csound, "Could not open Midi in device %s", dev);
return -1;
}
int CloseMidiInDevice(CSOUND *csound, void *userData) {
return 0;
}
int ReadMidiData(CSOUND *csound, void *userData,
unsigned char *mbuf, int nbytes) {
int n = 0, byte;
if(userData) {
Midi *midi = (Midi *) userData;
while((byte = midi->getInput()) >= 0) {
*mbuf++ = (unsigned char) byte;
if(++n == nbytes) break;
}
return n;
}
return 0;
}
int OpenMidiOutDevice(CSOUND *csound, void **userData, const char *dev) {
if(gMidi.writeTo(dev) == 1) {
gMidi.enableParser(false);
*userData = (void *) &gMidi;
return 0;
}
csoundMessage(csound, "Could not open Midi out device %s", dev);
return -1;
}
int CloseMidiOutDevice(CSOUND *csound, void *userData) {
return 0;
}
int WriteMidiData(CSOUND *csound, void *userData,
const unsigned char *mbuf, int nbytes) {
if(userData) {
Midi *midi = (Midi *) userData;
if(midi->writeOutput((midi_byte_t *)mbuf, nbytes) > 0) return nbytes;
return 0;
}
return 0;
}
<commit_msg>init_done typo<commit_after>/*
BelaCsound.cpp:
Copyright (C) 2017 V Lazzarini
This file is part of Csound.
The Csound 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.
Csound 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 Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
#include <Bela.h>
#include <Midi.h>
#include <csound/csound.hpp>
#include <csound/plugin.h>
#include <vector>
#include <sstream>
#define ANCHNS 8
static int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiInDevice(CSOUND *csound, void *userData);
static int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,
int nbytes);
static int OpenMidiOutDevice(CSOUND *csound, void **userData, const char *dev);
static int CloseMidiOutDevice(CSOUND *csound, void *userData);
static int WriteMidiData(CSOUND *csound, void *userData, const unsigned char *mbuf,
int nbytes);
/** DigiIn opcode
ksig digiInBela ipin
asig digiInBela ipin
*/
struct DigiIn : csnd::Plugin<1, 1> {
int pin;
int fcount;
int frms;
int init_done;
BelaContext *context;
int init() {
pin = (int) inargs[0];
if(pin < 0 ) pin = 0;
if(pin > 15) pin = 15;
context = (BelaContext *) csound->host_data();
fcount = 0;
init_done = 0;
frms = context->digitalFrames;
return OK;
}
int kperf() {
if(!init_done) {
pinMode(context,0,pin,0);
init_done = 1;
}
outargs[0] = (MYFLT) digitalRead(context,fcount,pin);
fcount += nsmps;
fcount %= frms;
return OK;
}
int aperf() {
csnd::AudioSig out(this, outargs(0));
int cnt = fcount;
if(!init_done) {
pinMode(context,0,pin,0);
init_done = 1;
}
for (auto &s : out) {
s = (MYFLT) digitalRead(context,cnt,pin);
if(cnt == frms - 1) cnt = 0;
else cnt++;
}
fcount = cnt;
return OK;
}
};
/** DigiOut opcode
digiOutBela ksig,ipin
digiOutBela asig,ipin
*/
struct DigiOut : csnd::Plugin<0, 2> {
int pin;
int fcount;
int frms;
int init_done;
BelaContext *context;
int init() {
pin = (int) inargs[1];
if(pin < 0 ) pin = 0;
if(pin > 15) pin = 15;
context = (BelaContext *) csound->host_data();
init_done = 0;
fcount = 0;
frms = context->digitalFrames;
return OK;
}
int kperf() {
if(!init_done) {
pinMode(context,0,pin,1);
init_done = 1;
}
digitalWrite(context,fcount,pin,(inargs[0] > 0.0 ? 1 : 0));
fcount += nsmps;
fcount %= frms;
return OK;
}
int aperf() {
csnd::AudioSig in(this, inargs(0));
int cnt = fcount;
if(!init_done) {
pinMode(context,0,pin,1);
init_done = 1;
}
for (auto s : in) {
digitalWriteOnce(context,cnt,pin, (s > 0.0 ? 1 : 0));
if(cnt == frms - 1) cnt = 0;
else cnt++;
}
fcount = cnt;
return OK;
}
};
struct CsChan {
std::vector<MYFLT> data;
std::stringstream name;
};
struct CsData {
Csound *csound;
int blocksize;
int res;
int count;
CsChan channel[ANCHNS];
CsChan ochannel[ANCHNS];
};
static CsData gCsData;
static Midi gMidi;
bool setup(BelaContext *context, void *Data)
{
Csound *csound;
const char *csdfile = "my.csd"; /* CSD name */
const char *midiDev = "-Mhw:1,0,0"; /* MIDI IN device */
const char *midiOutDev = "-Qhw:1,0,0"; /* MIDI OUT device */
const char *args[] = { "csound", csdfile, "-iadc", "-odac", "-+rtaudio=null",
"--realtime", "--daemon", midiDev, midiOutDev };
int numArgs = (int) (sizeof(args)/sizeof(char *));
if(context->audioInChannels != context->audioOutChannels) {
printf("Error: number of audio inputs != number of audio outputs.\n");
return false;
}
if(context->analogInChannels != context->analogOutChannels) {
printf("Error: number of analog inputs != number of analog outputs.\n");
return false;
}
/* set up Csound */
csound = new Csound();
gCsData.csound = csound;
csound->SetHostData((void *) context);
csound->SetHostImplementedAudioIO(1,0);
csound->SetHostImplementedMIDIIO(1);
csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);
csound->SetExternalMidiReadCallback(ReadMidiData);
csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);
csound->SetExternalMidiOutOpenCallback(OpenMidiOutDevice);
csound->SetExternalMidiWriteCallback(WriteMidiData);
csound->SetExternalMidiOutCloseCallback(CloseMidiOutDevice);
/* set up digi opcodes */
if(csnd::plugin<DigiIn>((csnd::Csound *) csound->GetCsound(), "digiInBela" , "k",
"i", csnd::thread::ik) != 0)
printf("Warning: could not add digiInBela k-rate opcode\n");
if(csnd::plugin<DigiIn>((csnd::Csound *) csound->GetCsound(), "digiInBela" , "a",
"i", csnd::thread::ia) != 0)
printf("Warning: could not add digiInBela a-rate opcode\n");
if(csnd::plugin<DigiOut>((csnd::Csound *) csound->GetCsound(), "digiOutBela" , "",
"ki", csnd::thread::ik) != 0)
printf("Warning: could not add digiOutBela k-rate opcode\n");
if(csnd::plugin<DigiOut>((csnd::Csound *) csound->GetCsound(), "digiOutBela" , "",
"ai", csnd::thread::ia) != 0)
printf("Warning: could not add digiOutBela a-rate opcode\n");
if((gCsData.res = csound->Compile(numArgs, args)) != 0) {
printf("Error: Csound could not compile CSD file.\n");
return false;
}
gCsData.blocksize = csound->GetKsmps()*csound->GetNchnls();
gCsData.count = 0;
/* set up the channels */
for(int i=0; i < ANCHNS; i++) {
gCsData.channel[i].data.resize(csound->GetKsmps());
gCsData.channel[i].name << "analogIn" << i+1;
gCsData.ochannel[i].data.resize(csound->GetKsmps());
gCsData.ochannel[i].name << "analogOut" << i+1;
}
return true;
}
void render(BelaContext *context, void *Data)
{
if(gCsData.res == 0) {
int n,i,k,count, frmcount,blocksize,res;
Csound *csound = gCsData.csound;
MYFLT scal = csound->Get0dBFS();
MYFLT* audioIn = csound->GetSpin();
MYFLT* audioOut = csound->GetSpout();
int nchnls = csound->GetNchnls();
int chns = nchnls < context->audioOutChannels ?
nchnls : context->audioOutChannels;
int an_chns = context->analogInChannels > ANCHNS ?
ANCHNS : context->analogInChannels;
CsChan *channel = &(gCsData.channel[0]);
CsChan *ochannel = &(gCsData.ochannel[0]);
float frm = 0.f, incr = ((float) context->analogFrames)/context->audioFrames;
count = gCsData.count;
blocksize = gCsData.blocksize;
/* processing loop */
for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){
if(count == blocksize) {
/* set the channels */
for(i = 0; i < an_chns; i++) {
csound->SetChannel(channel[i].name.str().c_str(),
&(channel[i].data[0]));
csound->GetAudioChannel(ochannel[i].name.str().c_str(),
&(ochannel[i].data[0]));
}
/* run csound */
if((res = csound->PerformKsmps()) == 0) count = 0;
else break;
}
/* read/write audio data */
for(i = 0; i < chns; i++){
audioIn[count+i] = audioRead(context,n,i);
audioWrite(context,n,i,audioOut[count+i]/scal);
}
/* read analogue data
analogue frame pos frm gets incremented according to the
ratio analogFrames/audioFrames.
*/
frmcount = count/nchnls;
for(i = 0; i < an_chns; i++) {
k = (int) frm;
channel[i].data[frmcount] = analogRead(context,k,i);
analogWriteOnce(context,k,i,ochannel[i].data[frmcount]);
}
}
gCsData.res = res;
gCsData.count = count;
}
}
void cleanup(BelaContext *context, void *Data)
{
delete gCsData.csound;
}
/** MIDI Input functions
*/
int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {
if(gMidi.readFrom(dev) == 1) {
gMidi.enableParser(false);
*userData = (void *) &gMidi;
return 0;
}
csoundMessage(csound, "Could not open Midi in device %s", dev);
return -1;
}
int CloseMidiInDevice(CSOUND *csound, void *userData) {
return 0;
}
int ReadMidiData(CSOUND *csound, void *userData,
unsigned char *mbuf, int nbytes) {
int n = 0, byte;
if(userData) {
Midi *midi = (Midi *) userData;
while((byte = midi->getInput()) >= 0) {
*mbuf++ = (unsigned char) byte;
if(++n == nbytes) break;
}
return n;
}
return 0;
}
int OpenMidiOutDevice(CSOUND *csound, void **userData, const char *dev) {
if(gMidi.writeTo(dev) == 1) {
gMidi.enableParser(false);
*userData = (void *) &gMidi;
return 0;
}
csoundMessage(csound, "Could not open Midi out device %s", dev);
return -1;
}
int CloseMidiOutDevice(CSOUND *csound, void *userData) {
return 0;
}
int WriteMidiData(CSOUND *csound, void *userData,
const unsigned char *mbuf, int nbytes) {
if(userData) {
Midi *midi = (Midi *) userData;
if(midi->writeOutput((midi_byte_t *)mbuf, nbytes) > 0) return nbytes;
return 0;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "GameScene.h"
#include "utils\global.h"
#include <chrono>
USING_NS_CC;
using namespace std::chrono;
Scene* GameScene::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::createWithPhysics();
scene->getPhysicsWorld()->setAutoStep(false);
scene->getPhysicsWorld()->setGravity(Vec2::ZERO);
// 'layer' is an autorelease object
auto layer = GameScene::create();
layer->mWorld = scene->getPhysicsWorld();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool GameScene::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
this->addListener();
this->visibleSize = Director::getInstance()->getVisibleSize();
this->origin = Director::getInstance()->getVisibleOrigin();
auto background = Sprite::create("background.jpg");
background->setPosition(visibleSize / 2);
this->addChild(background, -1);
// received as the game starts
GSocket->on("initData", [=](GameSocket* client, Document& dom) {
this->selfId = dom["data"]["selfId"].GetString();
auto& arr = dom["data"]["players"];
for (SizeType i = 0; i < arr.Size(); i++) {
const std::string& id = arr[i].GetString();
if (id == selfId) {
this->selfPlayer = createPlayer();
this->selfPlayer->setPosition(visibleSize / 2);
this->addChild(selfPlayer, 1);
}
else {
auto player = createPlayer(id);
player->setPosition(visibleSize / 2);
this->addChild(player, 1);
this->otherPlayers.insert(std::make_pair(id, player));
}
}
started = true;
});
// received periodically, like every x frames
GSocket->on("sync", [=](GameSocket* client, Document& dom) {
auto& arr = dom["data"];
for (SizeType i = 0; i < arr.Size(); i++) {
auto& data = arr[i]["data"];
// check ping
// milliseconds ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
// CCLOG("ping: %lld", ms.count() - data["timestamp"].GetInt64());
const std::string& id = arr[i]["id"].GetString();
auto it = this->otherPlayers.find(id);
if (it == this->otherPlayers.end()) continue; // data of selfPlayer, just ignore it
auto player = it->second;
syncSprite(player, data);
}
});
// manually update the physics world
schedule(schedule_selector(GameScene::update), 1.0f / FRAME_RATE, kRepeatForever, 0.1f);
return true;
}
void GameScene::update(float dt) {
if (!started) return;
static int frameCounter = 0;
this->getScene()->getPhysicsWorld()->step(1.0f / FRAME_RATE);
frameCounter++;
if (frameCounter == SYNC_LIMIT) {
frameCounter = 0;
// CCLOG("sync");
// TODO: sync with server
GSocket->sendEvent("sync", createSyncData(this->selfPlayer));
}
}
void GameScene::onKeyPressed(EventKeyboard::KeyCode code, Event* event) {
switch (code) {
case cocos2d::EventKeyboard::KeyCode::KEY_W:
setSpeedY(selfPlayer, 150.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_S:
setSpeedY(selfPlayer, -150.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_A:
setSpeedX(selfPlayer, -150.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_D:
setSpeedX(selfPlayer, 150.0f);
break;
}
}
void GameScene::onKeyReleased(EventKeyboard::KeyCode code, Event* event) {
switch (code) {
case cocos2d::EventKeyboard::KeyCode::KEY_W:
setSpeedY(selfPlayer, 0);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_S:
setSpeedY(selfPlayer, 0);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_A:
setSpeedX(selfPlayer, 0);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_D:
setSpeedX(selfPlayer, 0);
break;
}
}
void GameScene::onMouseMove(EventMouse* event) {
auto pos = Vec2(event->getCursorX(), event->getCursorY());
selfPlayer->setRotation(-CC_RADIANS_TO_DEGREES((pos - selfPlayer->getPosition()).getAngle()) + 90.0f);
}
void GameScene::addListener() {
auto keyboardListener = EventListenerKeyboard::create();
keyboardListener->onKeyPressed = CC_CALLBACK_2(GameScene::onKeyPressed, this);
keyboardListener->onKeyReleased = CC_CALLBACK_2(GameScene::onKeyReleased, this);
auto mouseListener = EventListenerMouse::create();
mouseListener->onMouseMove = CC_CALLBACK_1(GameScene::onMouseMove, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
// auto contactListener = EventListenerPhysicsContact::create();
// contactListener->onContactBegin = CC_CALLBACK_1(GameScene::onConcactBegin, this);
// _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this);
}
void addSpeed(Node* node, Vec2 speed) {
auto body = node->getPhysicsBody();
if (body) {
body->setVelocity(body->getVelocity() + speed);
}
}
void setSpeedX(Node* node, float spx) {
auto body = node->getPhysicsBody();
if (body) {
body->setVelocity(Vec2(spx, body->getVelocity().y));
}
}
void setSpeedY(Node* node, float spy) {
auto body = node->getPhysicsBody();
if (body) {
body->setVelocity(Vec2(body->getVelocity().x, spy));
}
}
void resetPhysics(Node* node, PhysicsBody* body) {
node->removeComponent(node->getPhysicsBody());
node->setPhysicsBody(body);
}
Sprite* createPlayer(const std::string& id) {
auto player = Sprite::create("player.png");
player->setScale(0.5f);
auto playerBody = PhysicsBody::createBox(player->getContentSize(), PhysicsMaterial(10.0f, 0.0f, 0.0f));
player->setPhysicsBody(playerBody);
return player;
}
Document createSyncData(Node* player) {
Document dom;
auto body = player->getPhysicsBody();
dom.SetObject();
// position & speed & angle
rapidjson::Value speedX, speedY, posX, posY;
auto speed = body->getVelocity();
auto pos = body->getPosition();
dom.AddMember("speedX", speed.x, dom.GetAllocator());
dom.AddMember("speedY", speed.y, dom.GetAllocator());
dom.AddMember("posX", pos.x, dom.GetAllocator());
dom.AddMember("posY", pos.y, dom.GetAllocator());
dom.AddMember("angle", player->getRotation(), dom.GetAllocator());
milliseconds ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
dom.AddMember("timestamp", ms.count(), dom.GetAllocator()); // used to check ping
return dom;
}
void syncSprite(Node* sprite, GenericValue<rapidjson::UTF8<>>& data) {
auto body = sprite->getPhysicsBody();
body->setVelocity(Vec2(data["speedX"].GetDouble(), data["speedY"].GetDouble()));
sprite->setPosition(data["posX"].GetDouble(), data["posY"].GetDouble());
sprite->setRotation(data["angle"].GetDouble());
}<commit_msg>camera mode. fixed #8.<commit_after>#include "GameScene.h"
#include "utils\global.h"
#include <chrono>
USING_NS_CC;
using namespace std::chrono;
Scene* GameScene::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::createWithPhysics();
scene->getPhysicsWorld()->setAutoStep(false);
scene->getPhysicsWorld()->setGravity(Vec2::ZERO);
// 'layer' is an autorelease object
auto layer = GameScene::create();
layer->mWorld = scene->getPhysicsWorld();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool GameScene::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
this->addListener();
this->visibleSize = Director::getInstance()->getVisibleSize();
this->origin = Director::getInstance()->getVisibleOrigin();
auto background = Sprite::create("background.jpg");
background->setPosition(visibleSize / 2);
this->addChild(background, -1);
// received as the game starts
GSocket->on("initData", [=](GameSocket* client, Document& dom) {
this->selfId = dom["data"]["selfId"].GetString();
auto& arr = dom["data"]["players"];
for (SizeType i = 0; i < arr.Size(); i++) {
const std::string& id = arr[i].GetString();
if (id == selfId) {
this->selfPlayer = createPlayer();
this->selfPlayer->setPosition(visibleSize / 2);
this->addChild(selfPlayer, 1);
// make the camera follow the player
this->runAction(Follow::create(selfPlayer));
}
else {
auto player = createPlayer(id);
player->setPosition(visibleSize / 2);
this->addChild(player, 1);
this->otherPlayers.insert(std::make_pair(id, player));
}
}
started = true;
});
// received periodically, like every x frames
GSocket->on("sync", [=](GameSocket* client, Document& dom) {
auto& arr = dom["data"];
for (SizeType i = 0; i < arr.Size(); i++) {
auto& data = arr[i]["data"];
// check ping
// milliseconds ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
// CCLOG("ping: %lld", ms.count() - data["timestamp"].GetInt64());
const std::string& id = arr[i]["id"].GetString();
auto it = this->otherPlayers.find(id);
if (it == this->otherPlayers.end()) continue; // data of selfPlayer, just ignore it
auto player = it->second;
syncSprite(player, data);
}
});
// manually update the physics world
schedule(schedule_selector(GameScene::update), 1.0f / FRAME_RATE, kRepeatForever, 0.1f);
return true;
}
void GameScene::update(float dt) {
if (!started) return;
static int frameCounter = 0;
CCLOG("%lf %lf", selfPlayer->getPhysicsBody()->getPosition().x, selfPlayer->getPhysicsBody()->getPosition().y);
this->getScene()->getPhysicsWorld()->step(1.0f / FRAME_RATE);
frameCounter++;
if (frameCounter == SYNC_LIMIT) {
frameCounter = 0;
// CCLOG("sync");
// TODO: sync with server
GSocket->sendEvent("sync", createSyncData(this->selfPlayer));
}
}
void GameScene::onKeyPressed(EventKeyboard::KeyCode code, Event* event) {
switch (code) {
case cocos2d::EventKeyboard::KeyCode::KEY_W:
setSpeedY(selfPlayer, 150.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_S:
setSpeedY(selfPlayer, -150.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_A:
setSpeedX(selfPlayer, -150.0f);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_D:
setSpeedX(selfPlayer, 150.0f);
break;
}
}
void GameScene::onKeyReleased(EventKeyboard::KeyCode code, Event* event) {
switch (code) {
case cocos2d::EventKeyboard::KeyCode::KEY_W:
setSpeedY(selfPlayer, 0);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_S:
setSpeedY(selfPlayer, 0);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_A:
setSpeedX(selfPlayer, 0);
break;
case cocos2d::EventKeyboard::KeyCode::KEY_D:
setSpeedX(selfPlayer, 0);
break;
}
}
void GameScene::onMouseMove(EventMouse* event) {
auto pos = Vec2(event->getCursorX(), event->getCursorY());
// position of physicsBody as relative to the camera
selfPlayer->setRotation(-CC_RADIANS_TO_DEGREES((pos - selfPlayer->getPhysicsBody()->getPosition()).getAngle()) + 90.0f);
}
void GameScene::addListener() {
auto keyboardListener = EventListenerKeyboard::create();
keyboardListener->onKeyPressed = CC_CALLBACK_2(GameScene::onKeyPressed, this);
keyboardListener->onKeyReleased = CC_CALLBACK_2(GameScene::onKeyReleased, this);
auto mouseListener = EventListenerMouse::create();
mouseListener->onMouseMove = CC_CALLBACK_1(GameScene::onMouseMove, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this);
// auto contactListener = EventListenerPhysicsContact::create();
// contactListener->onContactBegin = CC_CALLBACK_1(GameScene::onConcactBegin, this);
// _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this);
}
void addSpeed(Node* node, Vec2 speed) {
auto body = node->getPhysicsBody();
if (body) {
body->setVelocity(body->getVelocity() + speed);
}
}
void setSpeedX(Node* node, float spx) {
auto body = node->getPhysicsBody();
if (body) {
body->setVelocity(Vec2(spx, body->getVelocity().y));
}
}
void setSpeedY(Node* node, float spy) {
auto body = node->getPhysicsBody();
if (body) {
body->setVelocity(Vec2(body->getVelocity().x, spy));
}
}
void resetPhysics(Node* node, PhysicsBody* body) {
node->removeComponent(node->getPhysicsBody());
node->setPhysicsBody(body);
}
Sprite* createPlayer(const std::string& id) {
auto player = Sprite::create("player.png");
player->setScale(0.5f);
auto playerBody = PhysicsBody::createBox(player->getContentSize(), PhysicsMaterial(10.0f, 0.0f, 0.0f));
player->setPhysicsBody(playerBody);
return player;
}
Document createSyncData(Node* player) {
Document dom;
auto body = player->getPhysicsBody();
dom.SetObject();
// position & speed & angle
rapidjson::Value speedX, speedY, posX, posY;
auto speed = body->getVelocity();
// note: must use position of 'player' instead of 'body', to have a correct position
// while working with the Follow Action
auto pos = player->getPosition();
dom.AddMember("speedX", speed.x, dom.GetAllocator());
dom.AddMember("speedY", speed.y, dom.GetAllocator());
dom.AddMember("posX", pos.x, dom.GetAllocator());
dom.AddMember("posY", pos.y, dom.GetAllocator());
dom.AddMember("angle", player->getRotation(), dom.GetAllocator());
milliseconds ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
dom.AddMember("timestamp", ms.count(), dom.GetAllocator()); // used to check ping
return dom;
}
void syncSprite(Node* sprite, GenericValue<rapidjson::UTF8<>>& data) {
auto body = sprite->getPhysicsBody();
body->setVelocity(Vec2(data["speedX"].GetDouble(), data["speedY"].GetDouble()));
sprite->setPosition(data["posX"].GetDouble(), data["posY"].GetDouble());
sprite->setRotation(data["angle"].GetDouble());
}
<|endoftext|> |
<commit_before>#include <math.h>
#include "PathFinder.h"
void PathFinder::PrintStateInfo(void * /*state*/)
{
// For debug purposes, for example write state to stdout.
}
Vec2 PathFinder::NodeToPoint(void *node)
{
int index = (int) node;
int y = index / MAP_WIDTH;
int x = index - y * MAP_WIDTH;
return Vec2(x, y);
}
void *PathFinder::PointToNode(const Vec2 &point)
{
return (void *) (point.y * MAP_WIDTH + point.x);
}
void PathFinder::AdjacentCost(void *state, std::vector<micropather::StateCost> *adjacent)
{
const int dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
const float cost[8] = {1.0f, 1.41f, 1.0f, 1.41f, 1.0f, 1.41f, 1.0f, 1.41f};
Vec2 p = NodeToPoint(state);
for (int i = 0; i < 8; ++i)
{
//TODO: Use Vec2.
int nx = p.x + dx[i];
int ny = p.y + dy[i];
if (passable(nx, ny))
{
micropather::StateCost nodeCost = {PointToNode(Vec2(nx, ny)), cost[i]};
adjacent->push_back(nodeCost);
}
}
}
bool PathFinder::passable(int nx, int ny)
{
if ((nx >= 0) && (nx < MAP_WIDTH) && (ny >= 0) && (ny < MAP_HEIGHT))
{
MapCell cell = cells[nx][ny];
if (cell == 0)
return true;
}
return false;
}
float PathFinder::LeastCostEstimate(void *stateStart, void *stateEnd)
{
Vec2 start = NodeToPoint(stateStart);
Vec2 end = NodeToPoint(stateEnd);
//TODO: Use Vec2.
int dx = start.x - end.x;
int dy = start.y - end.y;
return (float) sqrt((double) (dx * dx) + (double) (dy * dy));
}
int PathFinder::find(const Vec2 &from, const Vec2 &to, std::vector<Vec2> &path)
{
path.clear();
//TODO: Dont recreate MicroPather.
micropather::MicroPather pather(this);
std::vector<void *> p;
float totalCost;
int result = pather.Solve(PointToNode(from), PointToNode(to), &p, &totalCost);
if (!result)
{
for (std::vector<void *>::iterator it = p.begin();
it != p.end();
++it)
{
path.push_back(NodeToPoint(*it) * 8);
}
}
return result;
}
//bool PathFinder::isPointEmpty(int x, int y) const
//{
// //TODO: precision problem.
// int col = x / 8;
// int row = y / 8;
//
// if ((col < 0) && (col >= MAP_WIDTH))
// return false;
//
// if ((row < 0) && (row >= MAP_HEIGHT))
// return false;
//
// if (cells[col][row])
// return false;
//
// return true;
//}
<commit_msg>Try to resolve cast from ‘void*’ to ‘int’ and vice versa in PathFinder.cpp.<commit_after>#include <math.h>
#include "PathFinder.h"
void PathFinder::PrintStateInfo(void * /*state*/)
{
// For debug purposes, for example write state to stdout.
}
Vec2 PathFinder::NodeToPoint(void *node)
{
intptr_t index = reinterpret_cast<intptr_t>(node);
int y = index / MAP_WIDTH;
int x = index - y * MAP_WIDTH;
return Vec2(x, y);
}
void *PathFinder::PointToNode(const Vec2 &point)
{
return reinterpret_cast<void*>(static_cast<intptr_t>(point.y * MAP_WIDTH + point.x));
}
void PathFinder::AdjacentCost(void *state, std::vector<micropather::StateCost> *adjacent)
{
const int dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};
const float cost[8] = {1.0f, 1.41f, 1.0f, 1.41f, 1.0f, 1.41f, 1.0f, 1.41f};
Vec2 p = NodeToPoint(state);
for (int i = 0; i < 8; ++i)
{
//TODO: Use Vec2.
int nx = p.x + dx[i];
int ny = p.y + dy[i];
if (passable(nx, ny))
{
micropather::StateCost nodeCost = {PointToNode(Vec2(nx, ny)), cost[i]};
adjacent->push_back(nodeCost);
}
}
}
bool PathFinder::passable(int nx, int ny)
{
if ((nx >= 0) && (nx < MAP_WIDTH) && (ny >= 0) && (ny < MAP_HEIGHT))
{
MapCell cell = cells[nx][ny];
if (cell == 0)
return true;
}
return false;
}
float PathFinder::LeastCostEstimate(void *stateStart, void *stateEnd)
{
Vec2 start = NodeToPoint(stateStart);
Vec2 end = NodeToPoint(stateEnd);
//TODO: Use Vec2.
int dx = start.x - end.x;
int dy = start.y - end.y;
return (float) sqrt((double) (dx * dx) + (double) (dy * dy));
}
int PathFinder::find(const Vec2 &from, const Vec2 &to, std::vector<Vec2> &path)
{
path.clear();
//TODO: Dont recreate MicroPather.
micropather::MicroPather pather(this);
std::vector<void *> p;
float totalCost;
int result = pather.Solve(PointToNode(from), PointToNode(to), &p, &totalCost);
if (!result)
{
for (std::vector<void *>::iterator it = p.begin();
it != p.end();
++it)
{
path.push_back(NodeToPoint(*it) * 8);
}
}
return result;
}
//bool PathFinder::isPointEmpty(int x, int y) const
//{
// //TODO: precision problem.
// int col = x / 8;
// int row = y / 8;
//
// if ((col < 0) && (col >= MAP_WIDTH))
// return false;
//
// if ((row < 0) && (row >= MAP_HEIGHT))
// return false;
//
// if (cells[col][row])
// return false;
//
// return true;
//}
<|endoftext|> |
<commit_before>#include <cassert>
#include "PointField.h"
using namespace cigma;
// ---------------------------------------------------------------------------
PointField::PointField()
{
points = new Points();
values = new Points();
}
PointField::~PointField()
{
delete points;
delete values;
}
// ---------------------------------------------------------------------------
void PointField::set_points(double *pts, int npts, int nsd)
{
points->set_data(pts, npts, nsd);
}
void PointField::set_values(double *vals, int nvals, int rank)
{
values->set_data(vals, nvals, rank);
}
// ---------------------------------------------------------------------------
bool PointField::eval(double *point, double *value)
{
/* XXX: quick sanity check
static int checked = 0;
if (!checked)
{
assert(points->n_points() != 0);
assert(values->n_points() != 0);
assert(points->n_points() == values->n_points());
assert(points->n_dim() == values->n_dim());
checked = 1;
} // */
// Find index of closest point
int n;
bool found = points->find_ann_index(point, &n);
if (found && (0 <= n) && (n < points->n_points()))
{
// Retrieve corresponding value
value = (*values)[n];
return true;
}
return false;
}
// ---------------------------------------------------------------------------
<commit_msg>Fixes for PointField::eval()<commit_after>#include <iostream>
#include <cassert>
#include "PointField.h"
using namespace std;
using namespace cigma;
// ---------------------------------------------------------------------------
PointField::PointField()
{
points = new Points();
values = new Points();
}
PointField::~PointField()
{
delete points;
delete values;
}
// ---------------------------------------------------------------------------
void PointField::set_points(double *pts, int npts, int nsd)
{
points->set_data(pts, npts, nsd);
}
void PointField::set_values(double *vals, int nvals, int rank)
{
values->set_data(vals, nvals, rank);
}
// ---------------------------------------------------------------------------
bool PointField::eval(double *point, double *value)
{
const bool debug = false;
// XXX: sanity check
//static int checked = 0;
//if (!checked)
//{
// assert(points->n_points() != 0);
// assert(values->n_points() != 0);
// assert(points->n_points() == values->n_points());
// assert(points->n_dim() == values->n_dim());
// checked = 1;
//}
// Find index of closest point
int n;
bool found = points->find_ann_index(point, &n);
if (!found) { return false; }
if ((0 <= n) && (n < points->n_points()))
{
int i;
// Show ANN point
if (debug)
{
double *p = (*points)[n];
cerr << "ANNPT( ";
for (i = 0; i < points->n_dim(); i++)
{
cerr << p[i] << " ";
}
cerr << ")" << endl;
}
// Retrieve corresponding value
double *v = (*values)[n];
for (i = 0; i < values->n_dim(); i++)
{
value[i] = v[i];
}
return true;
}
return false;
}
// ---------------------------------------------------------------------------
<|endoftext|> |
<commit_before>//
// ASTTypeExpr.cpp
// Emojicode
//
// Created by Theo Weidmann on 04/08/2017.
// Copyright © 2017 Theo Weidmann. All rights reserved.
//
#include "ASTTypeExpr.hpp"
#include "../Analysis/SemanticAnalyser.hpp"
#include "../Generation/FnCodeGenerator.hpp"
namespace EmojicodeCompiler {
Type ASTInferType::analyse(SemanticAnalyser *analyser, const TypeExpectation &expectation) {
if (expectation.type() == TypeType::StorageExpectation || expectation.type() == TypeType::NoReturn) {
throw CompilerError(position(), "Cannot infer ⚫️.");
}
Type type = expectation.copyType();
type.setOptional(false);
type_ = type;
availability_ = expectation.type() == TypeType::Class ? TypeAvailability::StaticAndAvailabale
: TypeAvailability::StaticAndAvailabale;
return type;
}
Type ASTTypeFromExpr::analyse(SemanticAnalyser *analyser, const TypeExpectation &expectation) {
auto type = expr_->analyse(analyser, expectation);
if (!type.meta()) {
throw CompilerError(position(), "Expected meta type.");
}
if (type.optional()) {
throw CompilerError(position(), "🍬 can’t be used as meta type.");
}
type.setMeta(false);
return type;
}
void ASTTypeFromExpr::generateExpr(FnCodeGenerator *fncg) const {
expr_->generate(fncg);
}
Type ASTStaticType::analyse(SemanticAnalyser *analyser, const TypeExpectation &expectation) {
return type_;
}
void ASTStaticType::generateExpr(FnCodeGenerator *fncg) const {
if (type_.type() == TypeType::Class) {
fncg->wr().writeInstruction(INS_GET_CLASS_FROM_INDEX);
fncg->wr().writeInstruction(type_.eclass()->index);
}
else {
assert(availability() == TypeAvailability::StaticAndUnavailable);
}
}
Type ASTThisType::analyse(SemanticAnalyser *analyser, const TypeExpectation &expectation) {
return analyser->typeContext().calleeType();
}
void ASTThisType::generateExpr(FnCodeGenerator *fncg) const {
fncg->wr().writeInstruction(INS_THIS);
}
} // namespace EmojicodeCompiler
<commit_msg>😶 Fix minor bug<commit_after>//
// ASTTypeExpr.cpp
// Emojicode
//
// Created by Theo Weidmann on 04/08/2017.
// Copyright © 2017 Theo Weidmann. All rights reserved.
//
#include "ASTTypeExpr.hpp"
#include "../Analysis/SemanticAnalyser.hpp"
#include "../Generation/FnCodeGenerator.hpp"
namespace EmojicodeCompiler {
Type ASTInferType::analyse(SemanticAnalyser *analyser, const TypeExpectation &expectation) {
if (expectation.type() == TypeType::StorageExpectation || expectation.type() == TypeType::NoReturn) {
throw CompilerError(position(), "Cannot infer ⚫️.");
}
Type type = expectation.copyType();
type.setOptional(false);
type_ = type;
availability_ = expectation.type() == TypeType::Class ? TypeAvailability::DynamicAndAvailable
: TypeAvailability::StaticAndAvailabale;
return type;
}
Type ASTTypeFromExpr::analyse(SemanticAnalyser *analyser, const TypeExpectation &expectation) {
auto type = expr_->analyse(analyser, expectation);
if (!type.meta()) {
throw CompilerError(position(), "Expected meta type.");
}
if (type.optional()) {
throw CompilerError(position(), "🍬 can’t be used as meta type.");
}
type.setMeta(false);
return type;
}
void ASTTypeFromExpr::generateExpr(FnCodeGenerator *fncg) const {
expr_->generate(fncg);
}
Type ASTStaticType::analyse(SemanticAnalyser *analyser, const TypeExpectation &expectation) {
return type_;
}
void ASTStaticType::generateExpr(FnCodeGenerator *fncg) const {
if (type_.type() == TypeType::Class) {
fncg->wr().writeInstruction(INS_GET_CLASS_FROM_INDEX);
fncg->wr().writeInstruction(type_.eclass()->index);
}
else {
assert(availability() == TypeAvailability::StaticAndUnavailable);
}
}
Type ASTThisType::analyse(SemanticAnalyser *analyser, const TypeExpectation &expectation) {
return analyser->typeContext().calleeType();
}
void ASTThisType::generateExpr(FnCodeGenerator *fncg) const {
fncg->wr().writeInstruction(INS_THIS);
}
} // namespace EmojicodeCompiler
<|endoftext|> |
<commit_before>#include <stdarg.h>
#include <ctype.h>
#include "../log.h"
#include "../console.h"
#include "../common.h"
#include <QTextCodec>
#define BLNKW (2) /* 横方向の余白 */
#define BLNKH (2) /* 縦方向の余白 */
VSurface *JFont::ZFont = NULL; // 全角フォントデータサーフェスへのポインタ
VSurface *JFont::HFont = NULL; // 半角フォントデータサーフェスへのポインタ
int JFont::zWidth = 0; // 全角文字の幅
int JFont::zHeight = 0; // 高さ
int JFont::hWidth = 0; // 半角文字の幅
int JFont::hHeight = 0; // 高さ
////////////////////////////////////////////////////////////////
// コンストラクタ
////////////////////////////////////////////////////////////////
JFont::JFont( void ){}
////////////////////////////////////////////////////////////////
// デストラクタ
////////////////////////////////////////////////////////////////
JFont::~JFont( void ){}
////////////////////////////////////////////////////////////////
// フォントファイルを開く
////////////////////////////////////////////////////////////////
bool JFont::OpenFont( char *zfilename, char *hfilename )
{
// 既に読込まれていたら破棄する
CloseFont();
// とりあえずサイズ指定
hWidth = FSIZE;
hHeight = hWidth * 2;
// フォントファイル読み込み
HFont = LoadImg( hfilename );
ZFont = LoadImg( zfilename );
// フォントファイルが無ければダミー作成
if( !HFont ){
HFont = new VSurface;
HFont->InitSurface( hWidth*96*2, hHeight* 2, 8 );
}
if( !ZFont ){
ZFont = new VSurface;
ZFont->InitSurface( zWidth*96*2, zHeight*96, 8 );
}
// 半角と全角でサイズが異なった場合は小さいほうに合わせる(当然表示がズレる)
hWidth = std::min( HFont->Width(), ZFont->Width() ) / 96 / 2;
hHeight = std::min( HFont->Height() / 2, ZFont->Height() / 96 );
zWidth = hWidth * 2;
zHeight = hHeight;
return true;
}
////////////////////////////////////////////////////////////////
// フォントを破棄する
////////////////////////////////////////////////////////////////
void JFont::CloseFont( void )
{
if( HFont ){
delete HFont;
HFont = NULL;
}
if( ZFont ){
delete ZFont;
ZFont = NULL;
}
}
////////////////////////////////////////////////////////////////
// 半角文字描画
////////////////////////////////////////////////////////////////
void JFont::PutCharh( VSurface *dst, int dx, int dy, BYTE txt, BYTE fg, BYTE bg )
{
PRINTD( GRP_LOG, "[JFont][PutCharh]\n" );
int index = txt;
// クリッピング
VRect sr,dr;
sr.x = ( index % 128 ) * hWidth;
sr.y = ( index / 128 ) * hHeight;
dr.x = dx;
dr.y = dy;
sr.w = dr.w = hWidth;
sr.h = dr.h = hHeight;
// 転送
for( int y=0; y<sr.h; y++ )
for( int x=0; x<sr.w; x++ )
dst->PSet( dr.x + x, dr.y + y, (DWORD)( HFont && HFont->PGet( sr.x + x, sr.y + y ) ? fg : bg ) );
}
////////////////////////////////////////////////////////////////
// 全角文字描画
////////////////////////////////////////////////////////////////
void JFont::PutCharz( VSurface *dst, int dx, int dy, WORD txt, BYTE fg, BYTE bg )
{
PRINTD( GRP_LOG, "[JFont][PutCharz]\n" );
BYTE high = (txt>>8) & 0xff;
BYTE low = txt & 0xff;
Convert2Jis( &high, &low );
int index = ( high - 0x20 ) * 96 + low - 0x20;
// クリッピング
VRect sr,dr;
sr.x = ( index % 96 ) * zWidth;
sr.y = ( index / 96 ) * zHeight;
dr.x = dx;
dr.y = dy;
sr.w = dr.w = zWidth;
sr.h = dr.h = zHeight;
// 転送
for( int y=0; y<sr.h; y++ )
for( int x=0; x<sr.w; x++ )
dst->PSet( dr.x + x, dr.y + y, (DWORD)( ZFont && ZFont->PGet( sr.x + x, sr.y + y ) ? fg : bg ) );
}
////////////////////////////////////////////////////////////////
// コンストラクタ
////////////////////////////////////////////////////////////////
ZCons::ZCons( void )
{
Xmax = Ymax = x = y = 0;
fgc = FC_WHITE;
bgc = FC_BLACK;
*Caption = '\0';
}
////////////////////////////////////////////////////////////////
// デストラクタ
////////////////////////////////////////////////////////////////
ZCons::~ZCons( void ){}
////////////////////////////////////////////////////////////////
// コンソール作成(文字数でサイズ指定)
////////////////////////////////////////////////////////////////
bool ZCons::Init( int winx, int winy, const char *caption, int fcol, int bcol )
{
int winxr = winx * hWidth + BLNKW * 2;
int winyr = winy * hHeight + BLNKH * 2;
return InitRes( winxr, winyr, caption, fcol, bcol );
}
////////////////////////////////////////////////////////////////
// コンソール作成(解像度でサイズ指定)
////////////////////////////////////////////////////////////////
bool ZCons::InitRes( int winx, int winy, const char *caption, int fcol, int bcol )
{
// サーフェス作成
if( !VSurface::InitSurface( winx, winy, 8 ) ) return false;
// サーフェス全体を背景色で塗りつぶす
VSurface::Fill( bcol );
// 縦横最大文字数設定
Xmax = ( winx - BLNKW * 2 ) / hWidth;
Ymax = ( winy - BLNKH * 2 ) / hHeight;
// 描画範囲設定
con.x = BLNKW;
con.y = BLNKH;
con.w = Xmax * hWidth;
con.h = Ymax * hHeight;
if( caption ){ // キャプションあり(フレームあり)の場合
// キャプション保存
strncpy( Caption, caption, std::min( Xmax-2, (int)sizeof(Caption)-1 ) );
// フレーム描画
DrawFrame();
// 縦横最大文字数設定
Xmax -= 2;
Ymax -= 2;
// 描画範囲設定
con.x += hWidth;
con.y += hHeight;
con.w = Xmax * hWidth;
con.h = Ymax * hHeight;
}
x = y = 0;
return true;
}
////////////////////////////////////////////////////////////////
// カーソル位置設定
////////////////////////////////////////////////////////////////
void ZCons::Locate( int xx, int yy )
{
// 右端,下端チェック
// 負だったら右端,下端から
if( ( xx >= 0 )&&( xx < Xmax ) ) x = xx;
else if( ( xx < 0 )&&( (Xmax-xx)>=0 ) ) x = Xmax + xx;
if( ( yy >= 0 )&&( yy < Ymax ) ) y = yy;
else if( ( yy < 0 )&&( (Ymax-yy)>=0 ) ) y = Ymax + yy;
}
////////////////////////////////////////////////////////////////
// カーソル位置設定(間接座標)
////////////////////////////////////////////////////////////////
void ZCons::LocateR( int xx, int yy )
{
x += xx;
if( x < 0 ) x = 0;
if( x >= Xmax ) x = Xmax;
y += yy;
if( y < 0 ) y = 0;
if( y >= Ymax ) y = Ymax;
}
////////////////////////////////////////////////////////////////
// 描画色設定
////////////////////////////////////////////////////////////////
void ZCons::SetColor( BYTE fg, BYTE bg )
{
fgc = fg;
bgc = bg;
}
void ZCons::SetColor( BYTE fg )
{
fgc = fg;
}
////////////////////////////////////////////////////////////////
// 画面消去
////////////////////////////////////////////////////////////////
void ZCons::Cls( void )
{
// 描画範囲を背景色で塗りつぶす
if( VSurface::pixels ) VSurface::Fill( bgc, &con );
// カーソルをホームに戻す
x = y = 0;
}
////////////////////////////////////////////////////////////////
// 半角1文字描画
////////////////////////////////////////////////////////////////
void ZCons::PutCharH( BYTE c )
{
JFont::PutCharh( this, x * hWidth + con.x, y * hHeight + con.y, c, fgc, bgc );
// 次のカーソルを設定
x++;
}
////////////////////////////////////////////////////////////////
// 全角1文字描画
////////////////////////////////////////////////////////////////
void ZCons::PutCharZ( WORD c )
{
JFont::PutCharz( this, x * hWidth + con.x, y * hHeight + con.y, c, fgc, bgc );
// 次のカーソルを設定
x += 2;
}
////////////////////////////////////////////////////////////////
// 書式付文字列描画(制御文字非対応)
////////////////////////////////////////////////////////////////
void ZCons::Print( const char *text, ... )
{
BYTE buf[1024];
int num = 0;
va_list ap;
// 可変長引数展開(文字列に変換)
va_start( ap, text );
QString str = QString().vsprintf(text, ap);
const QByteArray array = QTextCodec::codecForName("Shift-JIS")->fromUnicode(str);
for( int i=0; i<array.size(); i++ ){
if( isprint( array[i] ) )
PutCharH( array[i] );
else{
const unsigned char c1 = array[i];
const unsigned char c2 = array[i+1];
PutCharZ( c1<<8 | c2 );
i++;
}
}
}
////////////////////////////////////////////////////////////////
// 書式付文字列描画(制御文字対応)
////////////////////////////////////////////////////////////////
void ZCons::Printf( const char *text, ... )
{
BYTE buf[1024];
int num = 0;
va_list ap;
// 可変長引数展開(文字列に変換)
va_start( ap, text );
QString str = QString().vsprintf(text, ap);
const QByteArray array = QTextCodec::codecForName("Shift-JIS")->fromUnicode(str);
for( int i=0; i<array.size(); i++ ){
switch( array[i] ){
case '\n': // 改行
x = 0;
y++;
break;
default: // 普通の文字
if( isprint( array[i] ) )
PutCharH( array[i] );
else{
const unsigned char c1 = array[i];
const unsigned char c2 = array[i+1];
PutCharZ( c1<<8 | c2 );
i++;
}
// 次のカーソルを設定
if( x >= Xmax ){
x = 0;
y++;
}
}
// スクロール?
if( y >= Ymax){
y = Ymax - 1;
ScrollUp();
}
}
}
////////////////////////////////////////////////////////////////
// 書式付文字列描画(右詰め)
////////////////////////////////////////////////////////////////
void ZCons::Printfr( const char *text, ... )
{
char buf[1024];
int num = 0;
va_list ap;
// 可変長引数展開(文字列に変換)
va_start( ap, text );
QString str = QString().vsprintf(text, ap);
const QByteArray array = QTextCodec::codecForName("Shift-JIS")->fromUnicode(str);
if( array.size() > Xmax ) num = Xmax;
Locate( -array.size(), y );
for( int i=0; i<array.size(); i++ ){
if( isprint( array[i] ) )
PutCharH( array[i] );
else{
const unsigned char c1 = array[i];
const unsigned char c2 = array[i+1];
PutCharZ( c1<<8 | c2 );
i++;
}
}
}
////////////////////////////////////////////////////////////////
// 横最大文字数取得
////////////////////////////////////////////////////////////////
int ZCons::GetXline( void )
{
return Xmax;
}
////////////////////////////////////////////////////////////////
// 縦最大文字数取得
////////////////////////////////////////////////////////////////
int ZCons::GetYline( void )
{
return Ymax;
}
////////////////////////////////////////////////////////////////
// 枠描画
////////////////////////////////////////////////////////////////
void ZCons::DrawFrame( void )
{
VRect frm;
frm.x = con.x;
frm.y = con.y + 4;
frm.w = con.w;
frm.h = con.h - 8;
VSurface::Fill( fgc, &frm );
frm.x += 1;
frm.y += 1;
frm.w -= 2;
frm.h -= 2;
VSurface::Fill( bgc, &frm );
// キャプション
if( strlen( Caption ) > 0 ){
Locate( 1, 0 );
Print( " %s ", Caption );
}
}
////////////////////////////////////////////////////////////////
// スクロールアップ
////////////////////////////////////////////////////////////////
void ZCons::ScrollUp( void )
{
VRect SPos,DPos;
// 転送元
SPos.x = con.x;
SPos.y = con.y + hHeight;
SPos.w = con.w;
SPos.h = con.h - hHeight;
// 転送先
DPos.x = con.x;
DPos.y = con.y;
// スクロール
VSurface::Blit( &SPos, this, &DPos );
// 描画範囲を背景色で塗りつぶす
DPos.x = con.x;
DPos.y = con.y + con.h - hHeight;
DPos.w = con.w;
DPos.h = hHeight;
VSurface::Fill( bgc, &DPos );
}
<commit_msg>デバッグモードが文字化けしていたのを修正<commit_after>#include <stdarg.h>
#include <ctype.h>
#include "../log.h"
#include "../console.h"
#include "../common.h"
#include <QTextCodec>
#define BLNKW (2) /* 横方向の余白 */
#define BLNKH (2) /* 縦方向の余白 */
VSurface *JFont::ZFont = NULL; // 全角フォントデータサーフェスへのポインタ
VSurface *JFont::HFont = NULL; // 半角フォントデータサーフェスへのポインタ
int JFont::zWidth = 0; // 全角文字の幅
int JFont::zHeight = 0; // 高さ
int JFont::hWidth = 0; // 半角文字の幅
int JFont::hHeight = 0; // 高さ
////////////////////////////////////////////////////////////////
// コンストラクタ
////////////////////////////////////////////////////////////////
JFont::JFont( void ){}
////////////////////////////////////////////////////////////////
// デストラクタ
////////////////////////////////////////////////////////////////
JFont::~JFont( void ){}
////////////////////////////////////////////////////////////////
// フォントファイルを開く
////////////////////////////////////////////////////////////////
bool JFont::OpenFont( char *zfilename, char *hfilename )
{
// 既に読込まれていたら破棄する
CloseFont();
// とりあえずサイズ指定
hWidth = FSIZE;
hHeight = hWidth * 2;
// フォントファイル読み込み
HFont = LoadImg( hfilename );
ZFont = LoadImg( zfilename );
// フォントファイルが無ければダミー作成
if( !HFont ){
HFont = new VSurface;
HFont->InitSurface( hWidth*96*2, hHeight* 2, 8 );
}
if( !ZFont ){
ZFont = new VSurface;
ZFont->InitSurface( zWidth*96*2, zHeight*96, 8 );
}
// 半角と全角でサイズが異なった場合は小さいほうに合わせる(当然表示がズレる)
hWidth = std::min( HFont->Width(), ZFont->Width() ) / 96 / 2;
hHeight = std::min( HFont->Height() / 2, ZFont->Height() / 96 );
zWidth = hWidth * 2;
zHeight = hHeight;
return true;
}
////////////////////////////////////////////////////////////////
// フォントを破棄する
////////////////////////////////////////////////////////////////
void JFont::CloseFont( void )
{
if( HFont ){
delete HFont;
HFont = NULL;
}
if( ZFont ){
delete ZFont;
ZFont = NULL;
}
}
////////////////////////////////////////////////////////////////
// 半角文字描画
////////////////////////////////////////////////////////////////
void JFont::PutCharh( VSurface *dst, int dx, int dy, BYTE txt, BYTE fg, BYTE bg )
{
PRINTD( GRP_LOG, "[JFont][PutCharh]\n" );
int index = txt;
// クリッピング
VRect sr,dr;
sr.x = ( index % 128 ) * hWidth;
sr.y = ( index / 128 ) * hHeight;
dr.x = dx;
dr.y = dy;
sr.w = dr.w = hWidth;
sr.h = dr.h = hHeight;
// 転送
for( int y=0; y<sr.h; y++ )
for( int x=0; x<sr.w; x++ )
dst->PSet( dr.x + x, dr.y + y, (DWORD)( HFont && HFont->PGet( sr.x + x, sr.y + y ) ? fg : bg ) );
}
////////////////////////////////////////////////////////////////
// 全角文字描画
////////////////////////////////////////////////////////////////
void JFont::PutCharz( VSurface *dst, int dx, int dy, WORD txt, BYTE fg, BYTE bg )
{
PRINTD( GRP_LOG, "[JFont][PutCharz]\n" );
BYTE high = (txt>>8) & 0xff;
BYTE low = txt & 0xff;
Convert2Jis( &high, &low );
int index = ( high - 0x20 ) * 96 + low - 0x20;
// クリッピング
VRect sr,dr;
sr.x = ( index % 96 ) * zWidth;
sr.y = ( index / 96 ) * zHeight;
dr.x = dx;
dr.y = dy;
sr.w = dr.w = zWidth;
sr.h = dr.h = zHeight;
// 転送
for( int y=0; y<sr.h; y++ )
for( int x=0; x<sr.w; x++ )
dst->PSet( dr.x + x, dr.y + y, (DWORD)( ZFont && ZFont->PGet( sr.x + x, sr.y + y ) ? fg : bg ) );
}
////////////////////////////////////////////////////////////////
// コンストラクタ
////////////////////////////////////////////////////////////////
ZCons::ZCons( void )
{
Xmax = Ymax = x = y = 0;
fgc = FC_WHITE;
bgc = FC_BLACK;
*Caption = '\0';
}
////////////////////////////////////////////////////////////////
// デストラクタ
////////////////////////////////////////////////////////////////
ZCons::~ZCons( void ){}
////////////////////////////////////////////////////////////////
// コンソール作成(文字数でサイズ指定)
////////////////////////////////////////////////////////////////
bool ZCons::Init( int winx, int winy, const char *caption, int fcol, int bcol )
{
int winxr = winx * hWidth + BLNKW * 2;
int winyr = winy * hHeight + BLNKH * 2;
return InitRes( winxr, winyr, caption, fcol, bcol );
}
////////////////////////////////////////////////////////////////
// コンソール作成(解像度でサイズ指定)
////////////////////////////////////////////////////////////////
bool ZCons::InitRes( int winx, int winy, const char *caption, int fcol, int bcol )
{
// サーフェス作成
if( !VSurface::InitSurface( winx, winy, 8 ) ) return false;
// サーフェス全体を背景色で塗りつぶす
VSurface::Fill( bcol );
// 縦横最大文字数設定
Xmax = ( winx - BLNKW * 2 ) / hWidth;
Ymax = ( winy - BLNKH * 2 ) / hHeight;
// 描画範囲設定
con.x = BLNKW;
con.y = BLNKH;
con.w = Xmax * hWidth;
con.h = Ymax * hHeight;
if( caption ){ // キャプションあり(フレームあり)の場合
// キャプション保存
strncpy( Caption, caption, std::min( Xmax-2, (int)sizeof(Caption)-1 ) );
// フレーム描画
DrawFrame();
// 縦横最大文字数設定
Xmax -= 2;
Ymax -= 2;
// 描画範囲設定
con.x += hWidth;
con.y += hHeight;
con.w = Xmax * hWidth;
con.h = Ymax * hHeight;
}
x = y = 0;
return true;
}
////////////////////////////////////////////////////////////////
// カーソル位置設定
////////////////////////////////////////////////////////////////
void ZCons::Locate( int xx, int yy )
{
// 右端,下端チェック
// 負だったら右端,下端から
if( ( xx >= 0 )&&( xx < Xmax ) ) x = xx;
else if( ( xx < 0 )&&( (Xmax-xx)>=0 ) ) x = Xmax + xx;
if( ( yy >= 0 )&&( yy < Ymax ) ) y = yy;
else if( ( yy < 0 )&&( (Ymax-yy)>=0 ) ) y = Ymax + yy;
}
////////////////////////////////////////////////////////////////
// カーソル位置設定(間接座標)
////////////////////////////////////////////////////////////////
void ZCons::LocateR( int xx, int yy )
{
x += xx;
if( x < 0 ) x = 0;
if( x >= Xmax ) x = Xmax;
y += yy;
if( y < 0 ) y = 0;
if( y >= Ymax ) y = Ymax;
}
////////////////////////////////////////////////////////////////
// 描画色設定
////////////////////////////////////////////////////////////////
void ZCons::SetColor( BYTE fg, BYTE bg )
{
fgc = fg;
bgc = bg;
}
void ZCons::SetColor( BYTE fg )
{
fgc = fg;
}
////////////////////////////////////////////////////////////////
// 画面消去
////////////////////////////////////////////////////////////////
void ZCons::Cls( void )
{
// 描画範囲を背景色で塗りつぶす
if( VSurface::pixels ) VSurface::Fill( bgc, &con );
// カーソルをホームに戻す
x = y = 0;
}
////////////////////////////////////////////////////////////////
// 半角1文字描画
////////////////////////////////////////////////////////////////
void ZCons::PutCharH( BYTE c )
{
JFont::PutCharh( this, x * hWidth + con.x, y * hHeight + con.y, c, fgc, bgc );
// 次のカーソルを設定
x++;
}
////////////////////////////////////////////////////////////////
// 全角1文字描画
////////////////////////////////////////////////////////////////
void ZCons::PutCharZ( WORD c )
{
JFont::PutCharz( this, x * hWidth + con.x, y * hHeight + con.y, c, fgc, bgc );
// 次のカーソルを設定
x += 2;
}
////////////////////////////////////////////////////////////////
// 書式付文字列描画(制御文字非対応)
////////////////////////////////////////////////////////////////
void ZCons::Print( const char *text, ... )
{
char buf[1024];
int num = 0;
va_list ap;
// 可変長引数展開(文字列に変換)
va_start( ap, text );
vsprintf(buf, text, ap);
QString str = buf;
const QByteArray array = QTextCodec::codecForName("Shift-JIS")->fromUnicode(str);
for( int i=0; i<array.size(); i++ ){
if( isprint( array[i] ) )
PutCharH( array[i] );
else{
const unsigned char c1 = array[i];
const unsigned char c2 = array[i+1];
PutCharZ( c1<<8 | c2 );
i++;
}
}
}
////////////////////////////////////////////////////////////////
// 書式付文字列描画(制御文字対応)
////////////////////////////////////////////////////////////////
void ZCons::Printf( const char *text, ... )
{
char buf[1024];
int num = 0;
va_list ap;
// 可変長引数展開(文字列に変換)
va_start( ap, text );
vsprintf(buf, text, ap);
QString str = buf;
const QByteArray array = QTextCodec::codecForName("Shift-JIS")->fromUnicode(str);
for( int i=0; i<array.size(); i++ ){
switch( array[i] ){
case '\n': // 改行
x = 0;
y++;
break;
default: // 普通の文字
if( isprint( array[i] ) )
PutCharH( array[i] );
else{
const unsigned char c1 = array[i];
const unsigned char c2 = array[i+1];
PutCharZ( c1<<8 | c2 );
i++;
}
// 次のカーソルを設定
if( x >= Xmax ){
x = 0;
y++;
}
}
// スクロール?
if( y >= Ymax){
y = Ymax - 1;
ScrollUp();
}
}
}
////////////////////////////////////////////////////////////////
// 書式付文字列描画(右詰め)
////////////////////////////////////////////////////////////////
void ZCons::Printfr( const char *text, ... )
{
char buf[1024];
int num = 0;
va_list ap;
// 可変長引数展開(文字列に変換)
va_start( ap, text );
vsprintf(buf, text, ap);
QString str = buf;
const QByteArray array = QTextCodec::codecForName("Shift-JIS")->fromUnicode(str);
if( array.size() > Xmax ) num = Xmax;
Locate( -array.size(), y );
for( int i=0; i<array.size(); i++ ){
if( isprint( array[i] ) )
PutCharH( array[i] );
else{
const unsigned char c1 = array[i];
const unsigned char c2 = array[i+1];
PutCharZ( c1<<8 | c2 );
i++;
}
}
}
////////////////////////////////////////////////////////////////
// 横最大文字数取得
////////////////////////////////////////////////////////////////
int ZCons::GetXline( void )
{
return Xmax;
}
////////////////////////////////////////////////////////////////
// 縦最大文字数取得
////////////////////////////////////////////////////////////////
int ZCons::GetYline( void )
{
return Ymax;
}
////////////////////////////////////////////////////////////////
// 枠描画
////////////////////////////////////////////////////////////////
void ZCons::DrawFrame( void )
{
VRect frm;
frm.x = con.x;
frm.y = con.y + 4;
frm.w = con.w;
frm.h = con.h - 8;
VSurface::Fill( fgc, &frm );
frm.x += 1;
frm.y += 1;
frm.w -= 2;
frm.h -= 2;
VSurface::Fill( bgc, &frm );
// キャプション
if( strlen( Caption ) > 0 ){
Locate( 1, 0 );
Print( " %s ", Caption );
}
}
////////////////////////////////////////////////////////////////
// スクロールアップ
////////////////////////////////////////////////////////////////
void ZCons::ScrollUp( void )
{
VRect SPos,DPos;
// 転送元
SPos.x = con.x;
SPos.y = con.y + hHeight;
SPos.w = con.w;
SPos.h = con.h - hHeight;
// 転送先
DPos.x = con.x;
DPos.y = con.y;
// スクロール
VSurface::Blit( &SPos, this, &DPos );
// 描画範囲を背景色で塗りつぶす
DPos.x = con.x;
DPos.y = con.y + con.h - hHeight;
DPos.w = con.w;
DPos.h = hHeight;
VSurface::Fill( bgc, &DPos );
}
<|endoftext|> |
<commit_before>#include "Task/TaskManager.h"
#include "Platform/Os.h"
namespace Flourish
{
TaskManager::TaskManager()
: _nextId(1)
, _workerThreads(new std::thread[5])
, _taskQueue()
, _taskQueueMutex()
, _workAddedToTaskQueue()
, _openTaskQueue()
, _openTaskQueueMutex()
{
CreateAndStartWorkerThreads();
}
TaskManager::~TaskManager()
{
delete[] _workerThreads;
}
TaskId TaskManager::BeginAdd(WorkItem workItem, TaskId dependsOn /* = 0*/)
{
std::lock_guard<std::mutex>openTaskLock(_openTaskQueueMutex);
Task task = {};
task._id = _nextId++;
task._workItem = workItem;
task._dependency = dependsOn;
// Setting open work items to 2 prevents race conditions
// when adding children
// Because even if the taskFunction for this task is complete
// it will still have an openWorkItems of 1 until
// FinishAdd is called
task._openWorkItems = 2;
_openTaskQueue.push_back(task);
std::lock_guard<std::mutex>taskQueue(_taskQueueMutex);
_taskQueue.push_back(task);
return task._id;
}
void TaskManager::FinishAdd(TaskId id)
{
DecrementOpenWorkItems(id);
_workAddedToTaskQueue.notify_one();
}
void TaskManager::AddChild(TaskId parentId, TaskId childId)
{
std::lock_guard<std::mutex>lock(_openTaskQueueMutex);
for (auto openTaskIter = _openTaskQueue.begin(); openTaskIter != _openTaskQueue.end(); ++openTaskIter)
{
if (openTaskIter->_id == childId)
{
openTaskIter->_parentId = parentId;
if (openTaskIter->_openWorkItems <= 0)
{
// Child task is already complete
// Don't bother telling the parent it has a new work item
return;
}
}
}
for (auto openTaskIter = _openTaskQueue.begin(); openTaskIter != _openTaskQueue.end(); ++openTaskIter)
{
if (openTaskIter->_id == parentId)
{
openTaskIter->_openWorkItems++;
return;
}
}
}
void TaskManager::Wait(TaskId id)
{
while (TaskPending(id))
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void TaskManager::CreateAndStartWorkerThreads()
{
for (int32_t threadIdx = 0; threadIdx < 5; threadIdx++)
{
_workerThreads[threadIdx] = std::thread(&TaskManager::WorkerThreadFunc, this);
}
}
void TaskManager::WorkerThreadFunc()
{
for (;;)
{
std::unique_lock<std::mutex> lock(_taskQueueMutex);
_workAddedToTaskQueue.wait(lock);
auto taskIter = GetHighestPriorityTask();
if (taskIter == _taskQueue.end())
{
// If we get here, we either had a spurious wake-up (https://en.wikipedia.org/wiki/Spurious_wakeup)
// or all the queued tasks still have a dependency, in which case we'll hang out until FinishAdd is called
// either way, we just unlock and loop back to waiting on the condition_variable
lock.unlock();
continue;
}
auto task = *taskIter;
_taskQueue.erase(taskIter);
lock.unlock();
task._workItem();
DecrementOpenWorkItems(task._id);
}
}
bool TaskManager::TaskQueueHasItems() const
{
return _taskQueue.size() > 0;
}
std::vector<Task>::iterator TaskManager::GetHighestPriorityTask()
{
auto highestPriorityTask = _taskQueue.end();
auto highestPriority = INT32_MIN;
for (auto taskQueueIter = _taskQueue.begin(); taskQueueIter != _taskQueue.end(); ++taskQueueIter)
{
if (taskQueueIter->_dependency != 0)
{
continue; // This task has a non-complete dependency, we can't start it
}
if (taskQueueIter->_priority > highestPriority)
{
highestPriority = taskQueueIter->_priority;
highestPriorityTask = taskQueueIter;
}
}
return highestPriorityTask;
}
void TaskManager::DecrementOpenWorkItems(TaskId id)
{
std::lock_guard<std::mutex>lock(_openTaskQueueMutex);
NonThreadSafeDecrementOpenWorkItemsRecursive(id);
}
void TaskManager::NonThreadSafeDecrementOpenWorkItemsRecursive(TaskId id)
{
for (auto openTaskIter = _openTaskQueue.begin(); openTaskIter != _openTaskQueue.end(); ++openTaskIter)
{
if (openTaskIter->_id == id)
{
openTaskIter->_openWorkItems--;
if (openTaskIter->_openWorkItems <= 0)
{
if (openTaskIter->_parentId != 0)
{
NonThreadSafeDecrementOpenWorkItemsRecursive(openTaskIter->_parentId);
}
for (auto dependantTaskIter = _openTaskQueue.begin(); dependantTaskIter != _openTaskQueue.end(); ++dependantTaskIter)
{
if (dependantTaskIter->_dependency == id)
{
dependantTaskIter->_dependency = 0;
}
}
_openTaskQueue.erase(openTaskIter);
return;
}
}
}
}
bool TaskManager::TaskPending(TaskId id)
{
std::unique_lock<std::mutex> lock(_openTaskQueueMutex);
for (auto& task : _openTaskQueue)
{
if (task._id == id)
{
return true;
}
}
return false;
}
}
<commit_msg>Somewhat dodgy fix for face condition if the FinishAdd was called before any threads started. This is all going to be re-written anyway<commit_after>#include "Task/TaskManager.h"
#include "Platform/Os.h"
namespace Flourish
{
TaskManager::TaskManager()
: _nextId(1)
, _workerThreads(new std::thread[5])
, _taskQueue()
, _taskQueueMutex()
, _workAddedToTaskQueue()
, _openTaskQueue()
, _openTaskQueueMutex()
{
CreateAndStartWorkerThreads();
}
TaskManager::~TaskManager()
{
delete[] _workerThreads;
}
TaskId TaskManager::BeginAdd(WorkItem workItem, TaskId dependsOn /* = 0*/)
{
std::lock_guard<std::mutex>openTaskLock(_openTaskQueueMutex);
Task task = {};
task._id = _nextId++;
task._workItem = workItem;
task._dependency = dependsOn;
// Setting open work items to 2 prevents race conditions
// when adding children
// Because even if the taskFunction for this task is complete
// it will still have an openWorkItems of 1 until
// FinishAdd is called
task._openWorkItems = 2;
_openTaskQueue.push_back(task);
std::lock_guard<std::mutex>taskQueue(_taskQueueMutex);
_taskQueue.push_back(task);
return task._id;
}
void TaskManager::FinishAdd(TaskId id)
{
DecrementOpenWorkItems(id);
_workAddedToTaskQueue.notify_one();
}
void TaskManager::AddChild(TaskId parentId, TaskId childId)
{
std::lock_guard<std::mutex>lock(_openTaskQueueMutex);
for (auto openTaskIter = _openTaskQueue.begin(); openTaskIter != _openTaskQueue.end(); ++openTaskIter)
{
if (openTaskIter->_id == childId)
{
openTaskIter->_parentId = parentId;
if (openTaskIter->_openWorkItems <= 0)
{
// Child task is already complete
// Don't bother telling the parent it has a new work item
return;
}
}
}
for (auto openTaskIter = _openTaskQueue.begin(); openTaskIter != _openTaskQueue.end(); ++openTaskIter)
{
if (openTaskIter->_id == parentId)
{
openTaskIter->_openWorkItems++;
return;
}
}
}
void TaskManager::Wait(TaskId id)
{
while (TaskPending(id))
{
std::this_thread::yield();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void TaskManager::CreateAndStartWorkerThreads()
{
for (int32_t threadIdx = 0; threadIdx < 5; threadIdx++)
{
_workerThreads[threadIdx] = std::thread(&TaskManager::WorkerThreadFunc, this);
}
std::this_thread::yield();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
void TaskManager::WorkerThreadFunc()
{
for (;;)
{
std::unique_lock<std::mutex> lock(_taskQueueMutex);
_workAddedToTaskQueue.wait(lock);
auto taskIter = GetHighestPriorityTask();
if (taskIter == _taskQueue.end())
{
// If we get here, we either had a spurious wake-up (https://en.wikipedia.org/wiki/Spurious_wakeup)
// or all the queued tasks still have a dependency, in which case we'll hang out until FinishAdd is called
// either way, we just unlock and loop back to waiting on the condition_variable
lock.unlock();
continue;
}
auto task = *taskIter;
_taskQueue.erase(taskIter);
lock.unlock();
task._workItem();
DecrementOpenWorkItems(task._id);
}
}
bool TaskManager::TaskQueueHasItems() const
{
return _taskQueue.size() > 0;
}
std::vector<Task>::iterator TaskManager::GetHighestPriorityTask()
{
auto highestPriorityTask = _taskQueue.end();
auto highestPriority = INT32_MIN;
for (auto taskQueueIter = _taskQueue.begin(); taskQueueIter != _taskQueue.end(); ++taskQueueIter)
{
if (taskQueueIter->_dependency != 0)
{
continue; // This task has a non-complete dependency, we can't start it
}
if (taskQueueIter->_priority > highestPriority)
{
highestPriority = taskQueueIter->_priority;
highestPriorityTask = taskQueueIter;
}
}
return highestPriorityTask;
}
void TaskManager::DecrementOpenWorkItems(TaskId id)
{
std::lock_guard<std::mutex>lock(_openTaskQueueMutex);
NonThreadSafeDecrementOpenWorkItemsRecursive(id);
}
void TaskManager::NonThreadSafeDecrementOpenWorkItemsRecursive(TaskId id)
{
for (auto openTaskIter = _openTaskQueue.begin(); openTaskIter != _openTaskQueue.end(); ++openTaskIter)
{
if (openTaskIter->_id == id)
{
openTaskIter->_openWorkItems--;
if (openTaskIter->_openWorkItems <= 0)
{
if (openTaskIter->_parentId != 0)
{
NonThreadSafeDecrementOpenWorkItemsRecursive(openTaskIter->_parentId);
}
for (auto dependantTaskIter = _openTaskQueue.begin(); dependantTaskIter != _openTaskQueue.end(); ++dependantTaskIter)
{
if (dependantTaskIter->_dependency == id)
{
dependantTaskIter->_dependency = 0;
}
}
_openTaskQueue.erase(openTaskIter);
return;
}
}
}
}
bool TaskManager::TaskPending(TaskId id)
{
std::unique_lock<std::mutex> lock(_openTaskQueueMutex);
for (auto& task : _openTaskQueue)
{
if (task._id == id)
{
return true;
}
}
return false;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "../Base/Renderer.hpp"
#include <vulkan/vulkan.h>
#include <vector>
#include "../Base/Window.hpp"
/// Vulkan implementation of the renderer.
class VulkanRenderer : public Renderer {
public:
/// Create new Vulkan renderer.
/**
* @param window The window to render in.
*/
VulkanRenderer(Window& window);
/// Destructor.
~VulkanRenderer() final;
/// Render image to screen.
void render();
private:
struct SwapChainSupport {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
void createInstance();
void setupDebugCallback();
void createDevice();
void createSurface(GLFWwindow* window);
VkFormat createSwapChain(unsigned int width, unsigned int height);
SwapChainSupport querySwapChainSupport();
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, unsigned int width, unsigned int height);
void createImageViews(VkFormat format);
void createRenderPass(VkFormat format);
void createFramebuffers();
void createCommandPools();
void createCommandBuffers();
void createDescriptorPool();
void createSemaphores();
void createFence();
VkInstance instance;
#ifndef NDEBUG
VkDebugReportCallbackEXT callback;
#endif
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device;
int graphicsFamily;
int computeFamily;
VkQueue graphicsQueue;
VkQueue computeQueue;
VkQueue presentQueue;
VkSurfaceKHR surface;
VkSwapchainKHR swapChain;
VkExtent2D swapChainExtent;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkRenderPass renderPass;
std::vector<VkFramebuffer> swapChainFramebuffers;
VkCommandPool graphicsCommandPool;
VkCommandPool computeCommandPool;
VkCommandBuffer graphicsCommandBuffer;
VkCommandBuffer computeCommandBuffer;
VkDescriptorPool descriptorPool;
VkSemaphore imageAvailableSemaphore;
VkSemaphore renderFinishedSemaphore;
VkFence fence;
};
<commit_msg>Finalized render() in vulkanrenderer.<commit_after>#pragma once
#include "../Base/Renderer.hpp"
#include <vulkan/vulkan.h>
#include <vector>
#include "../Base/Window.hpp"
/// Vulkan implementation of the renderer.
class VulkanRenderer : public Renderer {
public:
/// Create new Vulkan renderer.
/**
* @param window The window to render in.
*/
VulkanRenderer(Window& window);
/// Destructor.
~VulkanRenderer() final;
/// Render image to screen.
void render() final;
private:
struct SwapChainSupport {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
void createInstance();
void setupDebugCallback();
void createDevice();
void createSurface(GLFWwindow* window);
VkFormat createSwapChain(unsigned int width, unsigned int height);
SwapChainSupport querySwapChainSupport();
VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats);
VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes);
VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, unsigned int width, unsigned int height);
void createImageViews(VkFormat format);
void createRenderPass(VkFormat format);
void createFramebuffers();
void createCommandPools();
void createCommandBuffers();
void createDescriptorPool();
void createSemaphores();
void createFence();
VkInstance instance;
#ifndef NDEBUG
VkDebugReportCallbackEXT callback;
#endif
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device;
int graphicsFamily;
int computeFamily;
VkQueue graphicsQueue;
VkQueue computeQueue;
VkQueue presentQueue;
VkSurfaceKHR surface;
VkSwapchainKHR swapChain;
VkExtent2D swapChainExtent;
std::vector<VkImage> swapChainImages;
std::vector<VkImageView> swapChainImageViews;
VkRenderPass renderPass;
std::vector<VkFramebuffer> swapChainFramebuffers;
VkCommandPool graphicsCommandPool;
VkCommandPool computeCommandPool;
VkCommandBuffer graphicsCommandBuffer;
VkCommandBuffer computeCommandBuffer;
VkDescriptorPool descriptorPool;
VkSemaphore imageAvailableSemaphore;
VkSemaphore renderFinishedSemaphore;
VkFence fence;
};
<|endoftext|> |
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastracture and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef JUBATUS_CORE_ANOMALY_ANOMALY_BASE_HPP_
#define JUBATUS_CORE_ANOMALY_ANOMALY_BASE_HPP_
#include <string>
#include <vector>
#include "jubatus/util/data/unordered_map.h"
#include "jubatus/util/lang/shared_ptr.h"
#include "../common/type.hpp"
#include "../framework/mixable.hpp"
#include "../storage/sparse_matrix_storage.hpp"
#include "anomaly_type.hpp"
namespace jubatus {
namespace core {
namespace anomaly {
class anomaly_base {
public:
anomaly_base();
virtual ~anomaly_base();
// Calculates and returns anomaly score of given query.
virtual float calc_anomaly_score(const common::sfv_t& query) const = 0;
// Returns anomaly score of the row corresponding to given id.
virtual float calc_anomaly_score(const std::string& id) const = 0;
// Clears all rows.
virtual void clear() = 0;
// Removes the row corresponding to given id.
//
// The removal event must be shared among other MIX participants. Thus,
// typical implementation does not eliminate the row immediately but marks it
// as "removed" instead. Some implementations including light_lof do not
// support this function.
virtual void clear_row(const std::string& id) = 0;
// Partially updates the row corresponding to given id.
//
// Some implementations including light_lof do not support this function.
virtual void update_row(const std::string& id, const sfv_diff_t& diff) = 0;
// Updates the row corresponding to given id.
//
// Some implementations including lof do not support this function.
virtual void set_row(const std::string& id, const common::sfv_t& sfv) = 0;
virtual void get_all_row_ids(std::vector<std::string>& ids) const = 0;
virtual std::string type() const = 0;
virtual void register_mixables_to_holder(
framework::mixable_holder& holder) const = 0;
uint64_t find_max_int_id() const;
protected:
// static const uint32_t NEIGHBOR_NUM;
};
} // namespace anomaly
} // namespace core
} // namespace jubatus
#endif // JUBATUS_CORE_ANOMALY_ANOMALY_BASE_HPP_
<commit_msg>delete unneeded comment<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2012 Preferred Infrastracture and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef JUBATUS_CORE_ANOMALY_ANOMALY_BASE_HPP_
#define JUBATUS_CORE_ANOMALY_ANOMALY_BASE_HPP_
#include <string>
#include <vector>
#include "jubatus/util/data/unordered_map.h"
#include "jubatus/util/lang/shared_ptr.h"
#include "../common/type.hpp"
#include "../framework/mixable.hpp"
#include "../storage/sparse_matrix_storage.hpp"
#include "anomaly_type.hpp"
namespace jubatus {
namespace core {
namespace anomaly {
class anomaly_base {
public:
anomaly_base();
virtual ~anomaly_base();
// Calculates and returns anomaly score of given query.
virtual float calc_anomaly_score(const common::sfv_t& query) const = 0;
// Returns anomaly score of the row corresponding to given id.
virtual float calc_anomaly_score(const std::string& id) const = 0;
// Clears all rows.
virtual void clear() = 0;
// Removes the row corresponding to given id.
//
// The removal event must be shared among other MIX participants. Thus,
// typical implementation does not eliminate the row immediately but marks it
// as "removed" instead. Some implementations including light_lof do not
// support this function.
virtual void clear_row(const std::string& id) = 0;
// Partially updates the row corresponding to given id.
//
// Some implementations including light_lof do not support this function.
virtual void update_row(const std::string& id, const sfv_diff_t& diff) = 0;
// Updates the row corresponding to given id.
//
// Some implementations including lof do not support this function.
virtual void set_row(const std::string& id, const common::sfv_t& sfv) = 0;
virtual void get_all_row_ids(std::vector<std::string>& ids) const = 0;
virtual std::string type() const = 0;
virtual void register_mixables_to_holder(
framework::mixable_holder& holder) const = 0;
uint64_t find_max_int_id() const;
};
} // namespace anomaly
} // namespace core
} // namespace jubatus
#endif // JUBATUS_CORE_ANOMALY_ANOMALY_BASE_HPP_
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/////////////////////////////////////////////////////////////
//
// base class for AOD containers
//
/////////////////////////////////////////////////////////////
#include <TParticle.h>
#include "AliAOD.h"
#include "AliAODParticle.h"
#include "AliTrackPoints.h"
ClassImp(AliAOD)
AliAOD::AliAOD():
fParticles(10),
fIsRandomized(kFALSE),
fPrimaryVertexX(0.0),
fPrimaryVertexY(0.0),
fPrimaryVertexZ(0.0)
{
//ctor
SetOwner(kTRUE);
}
/**************************************************************************/
void AliAOD::AddParticle(TParticle* part, Int_t idx)
{
//Adds TParticle to event
if (part == 0x0)
{
Error("AddParticle(TParticle*,Int_t)","pointer to particle is NULL");
return;
}
AddParticle( new AliAODParticle(*part,idx) );
}
/**************************************************************************/
void AliAOD::AddParticle(Int_t pdg, Int_t idx,
Double_t px, Double_t py, Double_t pz, Double_t etot,
Double_t vx, Double_t vy, Double_t vz, Double_t time)
{
//adds particle to event
AddParticle(new AliAODParticle(pdg,idx,px,py,pz,etot,vx,vy,vz,time));
}
/**************************************************************************/
void AliAOD::SwapParticles(Int_t i, Int_t j)
{
//swaps particles positions; used by AliHBTEvent::Blend
if ( (i<0) || (i>=GetNumberOfParticles()) ) return;
if ( (j<0) || (j>=GetNumberOfParticles()) ) return;
AliVAODParticle* tmp = (AliVAODParticle*)fParticles.At(i);
fParticles.AddAt(fParticles.At(j),i);
fParticles.AddAt(tmp,j);
}
/**************************************************************************/
void AliAOD::Reset()
{
//deletes all particles from the event
for(Int_t i =0; i<GetNumberOfParticles(); i++)
{
for (Int_t j = i+1; j<GetNumberOfParticles(); j++)
if ( fParticles.At(j) == fParticles.At(i) ) fParticles.RemoveAt(j);
delete fParticles.RemoveAt(i);
}
// fRandomized = kFALSE;
}
/**************************************************************************/
void AliAOD::GetPrimaryVertex(Double_t&x, Double_t&y, Double_t&z)
{
//returns positions of the primary vertex
x = fPrimaryVertexX;
y = fPrimaryVertexY;
z = fPrimaryVertexZ;
}
/**************************************************************************/
void AliAOD::SetPrimaryVertex(Double_t x, Double_t y, Double_t z)
{
//Sets positions of the primary vertex
fPrimaryVertexX = x;
fPrimaryVertexY = y;
fPrimaryVertexZ = z;
}
/**************************************************************************/
Int_t AliAOD::GetNumberOfCharged(Double_t etamin, Double_t etamax) const
{
//reurns number of charged particles within given pseudorapidity range
Int_t n;
Int_t npart = fParticles.GetEntries();
for (Int_t i = 0; i < npart; i++)
{
AliVAODParticle* p = (AliVAODParticle*)fParticles.At(i);
Double_t eta = p->Eta();
if ( (eta < etamin) || (eta > etamax) ) continue;
if (p->Charge() != 0.0) n++;
}
return 0;
}
/**************************************************************************/
void AliAOD::Move(Double_t x, Double_t y, Double_t z)
{
//moves all spacial coordinates about this vector
// vertex
// track points
// and whatever will be added to AOD and AOD particles that is a space coordinate
fPrimaryVertexX += x;
fPrimaryVertexY += y;
fPrimaryVertexZ += z;
Int_t npart = fParticles.GetEntries();
for (Int_t i = 0; i < npart; i++)
{
AliVAODParticle* p = (AliVAODParticle*)fParticles.At(i);
AliTrackPoints* tp = p->GetTPCTrackPoints();
if (tp) tp->Move(x,y,z);
tp = p->GetITSTrackPoints();
if (tp) tp->Move(x,y,z);
}
}
<commit_msg>Bug correction<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/////////////////////////////////////////////////////////////
//
// base class for AOD containers
//
/////////////////////////////////////////////////////////////
#include <TParticle.h>
#include "AliAOD.h"
#include "AliAODParticle.h"
#include "AliTrackPoints.h"
ClassImp(AliAOD)
AliAOD::AliAOD():
fParticles(10),
fIsRandomized(kFALSE),
fPrimaryVertexX(0.0),
fPrimaryVertexY(0.0),
fPrimaryVertexZ(0.0)
{
//ctor
SetOwner(kTRUE);
}
/**************************************************************************/
void AliAOD::AddParticle(TParticle* part, Int_t idx)
{
//Adds TParticle to event
if (part == 0x0)
{
Error("AddParticle(TParticle*,Int_t)","pointer to particle is NULL");
return;
}
AddParticle( new AliAODParticle(*part,idx) );
}
/**************************************************************************/
void AliAOD::AddParticle(Int_t pdg, Int_t idx,
Double_t px, Double_t py, Double_t pz, Double_t etot,
Double_t vx, Double_t vy, Double_t vz, Double_t time)
{
//adds particle to event
AddParticle(new AliAODParticle(pdg,idx,px,py,pz,etot,vx,vy,vz,time));
}
/**************************************************************************/
void AliAOD::SwapParticles(Int_t i, Int_t j)
{
//swaps particles positions; used by AliHBTEvent::Blend
if ( (i<0) || (i>=GetNumberOfParticles()) ) return;
if ( (j<0) || (j>=GetNumberOfParticles()) ) return;
AliVAODParticle* tmp = (AliVAODParticle*)fParticles.At(i);
fParticles.AddAt(fParticles.At(j),i);
fParticles.AddAt(tmp,j);
}
/**************************************************************************/
void AliAOD::Reset()
{
//deletes all particles from the event
for(Int_t i =0; i<GetNumberOfParticles(); i++)
{
for (Int_t j = i+1; j<GetNumberOfParticles(); j++)
if ( fParticles.At(j) == fParticles.At(i) ) fParticles.RemoveAt(j);
delete fParticles.RemoveAt(i);
}
// fRandomized = kFALSE;
}
/**************************************************************************/
void AliAOD::GetPrimaryVertex(Double_t&x, Double_t&y, Double_t&z)
{
//returns positions of the primary vertex
x = fPrimaryVertexX;
y = fPrimaryVertexY;
z = fPrimaryVertexZ;
}
/**************************************************************************/
void AliAOD::SetPrimaryVertex(Double_t x, Double_t y, Double_t z)
{
//Sets positions of the primary vertex
fPrimaryVertexX = x;
fPrimaryVertexY = y;
fPrimaryVertexZ = z;
}
/**************************************************************************/
Int_t AliAOD::GetNumberOfCharged(Double_t etamin, Double_t etamax) const
{
//reurns number of charged particles within given pseudorapidity range
Int_t n = 0;
Int_t npart = fParticles.GetEntries();
for (Int_t i = 0; i < npart; i++)
{
AliVAODParticle* p = (AliVAODParticle*)fParticles.At(i);
Double_t eta = p->Eta();
if ( (eta < etamin) || (eta > etamax) ) continue;
if (p->Charge() != 0.0) n++;
}
return n;
}
/**************************************************************************/
void AliAOD::Move(Double_t x, Double_t y, Double_t z)
{
//moves all spacial coordinates about this vector
// vertex
// track points
// and whatever will be added to AOD and AOD particles that is a space coordinate
fPrimaryVertexX += x;
fPrimaryVertexY += y;
fPrimaryVertexZ += z;
Int_t npart = fParticles.GetEntries();
for (Int_t i = 0; i < npart; i++)
{
AliVAODParticle* p = (AliVAODParticle*)fParticles.At(i);
AliTrackPoints* tp = p->GetTPCTrackPoints();
if (tp) tp->Move(x,y,z);
tp = p->GetITSTrackPoints();
if (tp) tp->Move(x,y,z);
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <string>
namespace principia {
namespace base {
#define STRINGIFY(X) #X
#define STRINGIFY_EXPANSION(X) STRINGIFY(X)
// See http://goo.gl/2EVxN4 for a partial overview of compiler detection and
// version macros. We cannot use |COMPILER_MSVC| because it conflicts with
// a macro in the benchmark library, so the macros have obnoxiously long names.
// TODO(phl): See whether that |COMPILER_MSVC| macro can be removed from port.h.
#if defined(_MSC_VER) && defined(__clang__)
#define PRINCIPIA_COMPILER_CLANG_CL 1
char const* const kCompilerName = "Clang-cl";
char const* const kCompilerVersion = __VERSION__;
#elif defined(__clang__)
#define PRINCIPIA_COMPILER_CLANG 1
char const* const kCompilerName = "Clang";
char const* const kCompilerVersion = __VERSION__;
#elif defined(_MSC_VER)
#define PRINCIPIA_COMPILER_MSVC 1
char const* const kCompilerName = "Microsoft Visual C++";
char const* const kCompilerVersion = STRINGIFY_EXPANSION(_MSC_FULL_VER);
#elif defined(__ICC) || defined(__INTEL_COMPILER)
#define PRINCIPIA_COMPILER_ICC 1
char const* const kCompilerName = "Intel C++ Compiler";
char const* const kCompilerVersion = __VERSION__;
#elif defined(__GNUC__)
#define PRINCIPIA_COMPILER_GCC 1
char const* const kCompilerName = "G++";
char const* const kCompilerVersion = __VERSION__;
#else
#error "What is this, Borland C++?"
#endif
#if defined(__APPLE__)
#define OS_MACOSX 1
char const* const kOperatingSystem = "OS X";
#elif defined(__linux__)
#define OS_LINUX 1
char const* const kOperatingSystem = "Linux";
#elif defined(__FreeBSD__)
#define OS_FREEBSD 1
char const* const kOperatingSystem = "FreeBSD";
#elif defined(_WIN32)
#define OS_WIN 1
char const* const kOperatingSystem = "Windows";
#else
#error "Try OS/360."
#endif
#if defined(__i386) || defined(_M_IX86)
#define ARCH_CPU_X86_FAMILY 1
#define ARCH_CPU_X86 1
#define ARCH_CPU_32_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
char const* const kArchitecture = "x86";
#elif defined(_M_X64) || defined(__x86_64__)
#define ARCH_CPU_X86_FAMILY 1
#define ARCH_CPU_X86_64 1
#define ARCH_CPU_64_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
char const* const kArchitecture = "x86-64";
#else
#error "Have you tried a Cray-1?"
#endif
#if defined(CDECL)
# error "CDECL already defined"
#else
// Architecture macros from http://goo.gl/ZypnO8.
// We use cdecl on x86, the calling convention is unambiguous on x86-64.
# if ARCH_CPU_X86
# if PRINCIPIA_COMPILER_CLANG || \
PRINCIPIA_COMPILER_MSVC || \
PRINCIPIA_COMPILER_CLANG_CL
# define CDECL __cdecl
# elif PRINCIPIA_COMPILER_ICC || PRINCIPIA_COMPILER_GCC
# define CDECL __attribute__((cdecl))
# else
# error "Get a real compiler!"
# endif
# elif ARCH_CPU_X86_64
# define CDECL
# else
# error "Have you tried a Cray-1?"
# endif
#endif
// DLL-exported functions for interfacing with Platform Invocation Services.
#if defined(DLLEXPORT)
# error "DLLEXPORT already defined"
#else
# if OS_WIN
# define DLLEXPORT __declspec(dllexport)
# else
# define DLLEXPORT __attribute__((visibility("default")))
# endif
#endif
// A function for use on control paths that don't return a value, typically
// because they end with a |LOG(FATAL)|.
#if PRINCIPIA_COMPILER_CLANG || PRINCIPIA_COMPILER_CLANG_CL
[[noreturn]]
#elif PRINCIPIA_COMPILER_MSVC
__declspec(noreturn)
#elif PRINCIPIA_COMPILER_ICC
__attribute__((noreturn))
#else
#error "What compiler is this?"
#endif
inline void noreturn() { exit(0); }
// Used to force inlining.
#if PRINCIPIA_COMPILER_CLANG || \
PRINCIPIA_COMPILER_CLANG_CL || \
PRINCIPIA_COMPILER_GCC
# define FORCE_INLINE [[gnu::always_inline]] // NOLINT(whitespace/braces)
#elif PRINCIPIA_COMPILER_MSVC
# define FORCE_INLINE __forceinline
#elif PRINCIPIA_COMPILER_ICC
# define FORCE_INLINE __attribute__((always_inline))
#else
# error "What compiler is this?"
#endif
// Thread-safety analysis.
#if PRINCIPIA_COMPILER_CLANG || PRINCIPIA_COMPILER_CLANG_CL
# define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x))
# define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
#else
# define GUARDED_BY(x)
#endif
// A workaround for a MSVC bug wherein a |typename| is required by the standard
// and by clang but forbidden by MSVC.
#if PRINCIPIA_COMPILER_MSVC
# define TYPENAME
#else
# define TYPENAME typename
#endif
// Same as above, with |template|.
#if PRINCIPIA_COMPILER_MSVC
# define TEMPLATE
#else
# define TEMPLATE template
#endif
#define VLOG_AND_RETURN(verboselevel, expression) \
do { \
auto const& value__ = (expression); \
VLOG(verboselevel) << __FUNCTION__ << " returns " << value__; \
return value__; \
} while (false)
#define NAMED(expression) #expression << ": " << (expression)
} // namespace base
} // namespace principia
<commit_msg>Use std::exit and <cstdlib><commit_after>#pragma once
#include <string>
#include <cstdlib>
namespace principia {
namespace base {
#define STRINGIFY(X) #X
#define STRINGIFY_EXPANSION(X) STRINGIFY(X)
// See http://goo.gl/2EVxN4 for a partial overview of compiler detection and
// version macros. We cannot use |COMPILER_MSVC| because it conflicts with
// a macro in the benchmark library, so the macros have obnoxiously long names.
// TODO(phl): See whether that |COMPILER_MSVC| macro can be removed from port.h.
#if defined(_MSC_VER) && defined(__clang__)
#define PRINCIPIA_COMPILER_CLANG_CL 1
char const* const kCompilerName = "Clang-cl";
char const* const kCompilerVersion = __VERSION__;
#elif defined(__clang__)
#define PRINCIPIA_COMPILER_CLANG 1
char const* const kCompilerName = "Clang";
char const* const kCompilerVersion = __VERSION__;
#elif defined(_MSC_VER)
#define PRINCIPIA_COMPILER_MSVC 1
char const* const kCompilerName = "Microsoft Visual C++";
char const* const kCompilerVersion = STRINGIFY_EXPANSION(_MSC_FULL_VER);
#elif defined(__ICC) || defined(__INTEL_COMPILER)
#define PRINCIPIA_COMPILER_ICC 1
char const* const kCompilerName = "Intel C++ Compiler";
char const* const kCompilerVersion = __VERSION__;
#elif defined(__GNUC__)
#define PRINCIPIA_COMPILER_GCC 1
char const* const kCompilerName = "G++";
char const* const kCompilerVersion = __VERSION__;
#else
#error "What is this, Borland C++?"
#endif
#if defined(__APPLE__)
#define OS_MACOSX 1
char const* const kOperatingSystem = "OS X";
#elif defined(__linux__)
#define OS_LINUX 1
char const* const kOperatingSystem = "Linux";
#elif defined(__FreeBSD__)
#define OS_FREEBSD 1
char const* const kOperatingSystem = "FreeBSD";
#elif defined(_WIN32)
#define OS_WIN 1
char const* const kOperatingSystem = "Windows";
#else
#error "Try OS/360."
#endif
#if defined(__i386) || defined(_M_IX86)
#define ARCH_CPU_X86_FAMILY 1
#define ARCH_CPU_X86 1
#define ARCH_CPU_32_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
char const* const kArchitecture = "x86";
#elif defined(_M_X64) || defined(__x86_64__)
#define ARCH_CPU_X86_FAMILY 1
#define ARCH_CPU_X86_64 1
#define ARCH_CPU_64_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
char const* const kArchitecture = "x86-64";
#else
#error "Have you tried a Cray-1?"
#endif
#if defined(CDECL)
# error "CDECL already defined"
#else
// Architecture macros from http://goo.gl/ZypnO8.
// We use cdecl on x86, the calling convention is unambiguous on x86-64.
# if ARCH_CPU_X86
# if PRINCIPIA_COMPILER_CLANG || \
PRINCIPIA_COMPILER_MSVC || \
PRINCIPIA_COMPILER_CLANG_CL
# define CDECL __cdecl
# elif PRINCIPIA_COMPILER_ICC || PRINCIPIA_COMPILER_GCC
# define CDECL __attribute__((cdecl))
# else
# error "Get a real compiler!"
# endif
# elif ARCH_CPU_X86_64
# define CDECL
# else
# error "Have you tried a Cray-1?"
# endif
#endif
// DLL-exported functions for interfacing with Platform Invocation Services.
#if defined(DLLEXPORT)
# error "DLLEXPORT already defined"
#else
# if OS_WIN
# define DLLEXPORT __declspec(dllexport)
# else
# define DLLEXPORT __attribute__((visibility("default")))
# endif
#endif
// A function for use on control paths that don't return a value, typically
// because they end with a |LOG(FATAL)|.
#if PRINCIPIA_COMPILER_CLANG || PRINCIPIA_COMPILER_CLANG_CL
[[noreturn]]
#elif PRINCIPIA_COMPILER_MSVC
__declspec(noreturn)
#elif PRINCIPIA_COMPILER_ICC
__attribute__((noreturn))
#else
#error "What compiler is this?"
#endif
inline void noreturn() { std::exit(0); }
// Used to force inlining.
#if PRINCIPIA_COMPILER_CLANG || \
PRINCIPIA_COMPILER_CLANG_CL || \
PRINCIPIA_COMPILER_GCC
# define FORCE_INLINE [[gnu::always_inline]] // NOLINT(whitespace/braces)
#elif PRINCIPIA_COMPILER_MSVC
# define FORCE_INLINE __forceinline
#elif PRINCIPIA_COMPILER_ICC
# define FORCE_INLINE __attribute__((always_inline))
#else
# error "What compiler is this?"
#endif
// Thread-safety analysis.
#if PRINCIPIA_COMPILER_CLANG || PRINCIPIA_COMPILER_CLANG_CL
# define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x))
# define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
#else
# define GUARDED_BY(x)
#endif
// A workaround for a MSVC bug wherein a |typename| is required by the standard
// and by clang but forbidden by MSVC.
#if PRINCIPIA_COMPILER_MSVC
# define TYPENAME
#else
# define TYPENAME typename
#endif
// Same as above, with |template|.
#if PRINCIPIA_COMPILER_MSVC
# define TEMPLATE
#else
# define TEMPLATE template
#endif
#define VLOG_AND_RETURN(verboselevel, expression) \
do { \
auto const& value__ = (expression); \
VLOG(verboselevel) << __FUNCTION__ << " returns " << value__; \
return value__; \
} while (false)
#define NAMED(expression) #expression << ": " << (expression)
} // namespace base
} // namespace principia
<|endoftext|> |
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include"boost/spirit/home/support/common_terminals.hpp"
#include"boost/spirit/home/qi.hpp"
#include"ork/ork.hpp"
/*
Placeholders for parser components
*/
namespace ork {
namespace orq {
BOOST_SPIRIT_TERMINAL(id);
}//namespace ork
}//namespace ork
/*
Enablers for parser components
*/
namespace boost {
namespace spirit {
//Make custom_parser::iter_pos usable as a terminal only, and only for parser expressions (qi::domain).
template <>
struct use_terminal<qi::domain, ork::orq::tag::id> : mpl::true_ {};
}//namespace spirit
}//namespace boost
namespace ork {
namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace ascii = spirit::ascii;
namespace proto = boost::proto;
#if UNICODE
typedef spirit::char_encoding::standard_wide charset;
#else
typedef spirit::char_encoding::standard charset;
#endif
namespace orq {//ork-qi :)
struct id_parser : qi::primitive_parser<id_parser> {
public://Parser component stuff
template<typename context, typename iter>
struct attribute {//Define the attribute type exposed by this parser component
typedef string type;
};
//This function is called during the actual parsing process
template<typename iter, typename context, typename skipper, typename attribute>
bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip
iter it(first);
if(!std::isalpha(*it) && *it != ORK('_')) {
return false;
}
while(it != last && (std::isalnum(*it) || *it == ORK('_'))) {
++it;
}
if(it != last) {
return false;
}
attribute result(first, it);
if(result.empty()) {
return false;
}
first = it;
spirit::traits::assign_to(result, attr);
return true;
}
//This function is called during error handling to create a human readable string for the error context.
template<typename context>
boost::spirit::info what(context&) const {
return boost::spirit::info("id");
}
};
struct identifier : qi::grammar<string::const_iterator, string(), ascii::space_type> {
public:
typedef string::const_iterator iter;
public:
identifier() : identifier::base_type(start) {
first %=
qi::alpha | qi::char_(ORK('_'))
;
rest %=
qi::alnum | qi::char_(ORK('_'))
;
start %=
qi::lexeme[first >> *rest]
;
}
public:
qi::rule<iter, letr()> first;
qi::rule<iter, letr()> rest;
qi::rule<iter, string(), ascii::space_type> start;
};
}//namespace orq
}//namespace ork
/*
Instantiators for parser components
*/
namespace boost {
namespace spirit {
namespace qi {
//This is the factory function object invoked in order to create an instance of our parser.
template<typename modifiers>
struct make_primitive<ork::orq::tag::id, modifiers> {
typedef typename ork::orq::id_parser result_type;
result_type operator()(unused_type, unused_type) const {
return result_type();
}
};
}//namespace qi
}//namespace spirit
}//namespace boost<commit_msg>Fixed 2 bugs testing iterators<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include"boost/spirit/home/support/common_terminals.hpp"
#include"boost/spirit/home/qi.hpp"
#include"ork/ork.hpp"
/*
Placeholders for parser components
*/
namespace ork {
namespace orq {
BOOST_SPIRIT_TERMINAL(id);
}//namespace ork
}//namespace ork
/*
Enablers for parser components
*/
namespace boost {
namespace spirit {
//Make custom_parser::iter_pos usable as a terminal only, and only for parser expressions (qi::domain).
template <>
struct use_terminal<qi::domain, ork::orq::tag::id> : mpl::true_ {};
}//namespace spirit
}//namespace boost
namespace ork {
namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace ascii = spirit::ascii;
namespace proto = boost::proto;
#if UNICODE
typedef spirit::char_encoding::standard_wide charset;
#else
typedef spirit::char_encoding::standard charset;
#endif
namespace orq {//ork-qi :)
struct id_parser : qi::primitive_parser<id_parser> {
public://Parser component stuff
template<typename context, typename iter>
struct attribute {//Define the attribute type exposed by this parser component
typedef string type;
};
//This function is called during the actual parsing process
template<typename iter, typename context, typename skipper, typename attribute>
bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip
if(first == last) {
return false;
}
iter it(first);
if(!std::isalpha(*it) && *it != ORK('_')) {
return false;
}
while(it != last && (std::isalnum(*it) || *it == ORK('_'))) {
++it;
}
attribute result(first, it);
if(result.empty()) {
return false;
}
first = it;
spirit::traits::assign_to(result, attr);
return true;
}
//This function is called during error handling to create a human readable string for the error context.
template<typename context>
boost::spirit::info what(context&) const {
return boost::spirit::info("id");
}
};
struct identifier : qi::grammar<string::const_iterator, string(), ascii::space_type> {
public:
typedef string::const_iterator iter;
public:
identifier() : identifier::base_type(start) {
first %=
qi::alpha | qi::char_(ORK('_'))
;
rest %=
qi::alnum | qi::char_(ORK('_'))
;
start %=
qi::lexeme[first >> *rest]
;
}
public:
qi::rule<iter, letr()> first;
qi::rule<iter, letr()> rest;
qi::rule<iter, string(), ascii::space_type> start;
};
}//namespace orq
}//namespace ork
/*
Instantiators for parser components
*/
namespace boost {
namespace spirit {
namespace qi {
//This is the factory function object invoked in order to create an instance of our parser.
template<typename modifiers>
struct make_primitive<ork::orq::tag::id, modifiers> {
typedef typename ork::orq::id_parser result_type;
result_type operator()(unused_type, unused_type) const {
return result_type();
}
};
}//namespace qi
}//namespace spirit
}//namespace boost<|endoftext|> |
<commit_before><commit_msg>win: _set_ouput_format is no longer available or required on VS2015<commit_after><|endoftext|> |
<commit_before>// ShapeTools.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "ShapeTools.h"
#include "Vertex.h"
const wxBitmap &CFaceList::GetIcon()
{
static wxBitmap* icon = NULL;
if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/faces.png")));
return *icon;
}
const wxBitmap &CEdgeList::GetIcon()
{
static wxBitmap* icon = NULL;
if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/edges.png")));
return *icon;
}
const wxBitmap &CVertexList::GetIcon()
{
static wxBitmap* icon = NULL;
if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/vertices.png")));
return *icon;
}
void CreateFacesAndEdges(TopoDS_Shape shape, CFaceList* faces, CEdgeList* edges, CVertexList* vertices)
{
// create index maps
TopTools_IndexedMapOfShape faceMap;
TopTools_IndexedMapOfShape edgeMap;
TopTools_IndexedMapOfShape vertexMap;
for (TopExp_Explorer explorer(shape, TopAbs_FACE); explorer.More(); explorer.Next())
{
faceMap.Add(explorer.Current());
}
for (TopExp_Explorer explorer(shape, TopAbs_EDGE); explorer.More(); explorer.Next())
{
edgeMap.Add(explorer.Current());
}
for (TopExp_Explorer explorer(shape, TopAbs_VERTEX); explorer.More(); explorer.Next())
{
vertexMap.Add(explorer.Current());
}
std::vector<CFace*> face_array;
face_array.resize(faceMap.Extent() + 1);
std::vector<CEdge*> edge_array;
edge_array.resize(edgeMap.Extent() + 1);
std::vector<CVertex*> vertex_array;
vertex_array.resize(vertexMap.Extent() + 1);
// create the edge objects
for(int i = 1;i<=edgeMap.Extent();i++)
{
const TopoDS_Shape &s = edgeMap(i);
CEdge* new_object = new CEdge(TopoDS::Edge(s));
edge_array[i] = new_object;
}
// create the vertex objects
for(int i = 1;i<=vertexMap.Extent();i++)
{
const TopoDS_Shape &s = vertexMap(i);
CVertex* new_object = new CVertex(TopoDS::Vertex(s));
vertex_array[i] = new_object;
}
// add the edges in their face loop order
std::set<CEdge*> edges_added;
std::set<CVertex*> vertices_added;
// create the face objects
for(int i = 1;i<=faceMap.Extent();i++)
{
const TopoDS_Shape &s = faceMap(i);
CFace* new_face_object = new CFace(TopoDS::Face(s));
faces->Add(new_face_object, NULL);
face_array[i] = new_face_object;
TopAbs_Orientation face_orientation = s.Orientation();
// create the loop objects
TopTools_IndexedMapOfShape loopMap;
for (TopExp_Explorer explorer(s, TopAbs_WIRE); explorer.More(); explorer.Next())
{
loopMap.Add(explorer.Current());
}
TopoDS_Wire outerWire=BRepTools::OuterWire(new_face_object->Face());
int outer_index = loopMap.FindIndex(outerWire);
for(int i = 1;i<=loopMap.Extent();i++)
{
const TopoDS_Shape &s = loopMap(i);
CLoop* new_loop_object = new CLoop(TopoDS::Wire(s));
new_face_object->m_loops.push_back(new_loop_object);
if(outer_index == i)new_loop_object->m_is_outer = true;
new_loop_object->m_pface = new_face_object;
TopAbs_Orientation orientation = s.Orientation();
// find the loop's edges
for(BRepTools_WireExplorer explorer(TopoDS::Wire(s)); explorer.More(); explorer.Next())
{
CEdge* e = edge_array[edgeMap.FindIndex(explorer.Current())];
new_loop_object->m_edges.push_back(e);
// add the edge
if(edges_added.find(e) == edges_added.end())
{
edges->Add(e, NULL);
edges_added.insert(e);
}
// add the vertex
CVertex* v = vertex_array[vertexMap.FindIndex(explorer.CurrentVertex())];
if(vertices_added.find(v) == vertices_added.end())
{
vertices->Add(v, NULL);
vertices_added.insert(v);
}
}
}
}
// find the vertices' edges
for(unsigned int i = 1; i<vertex_array.size(); i++)
{
CVertex* v = vertex_array[i];
TopTools_IndexedMapOfShape vertexEdgeMap;
for (TopExp_Explorer expEdge(v->Vertex(), TopAbs_EDGE); expEdge.More(); expEdge.Next())
{
vertexEdgeMap.Add(expEdge.Current());
}
for(int i = 1; i<=vertexEdgeMap.Extent(); i++)
{
const TopoDS_Shape &s = vertexEdgeMap(i);
CEdge* e = edge_array[edgeMap.FindIndex(s)];
v->m_edges.push_back(e);
}
}
// find the faces' edges
for(unsigned int i = 1; i<face_array.size(); i++)
{
CFace* face = face_array[i];
TopTools_IndexedMapOfShape faceEdgeMap;
for (TopExp_Explorer expEdge(face->Face(), TopAbs_EDGE); expEdge.More(); expEdge.Next())
{
faceEdgeMap.Add(expEdge.Current());
}
for(int i = 1; i<=faceEdgeMap.Extent(); i++)
{
const TopoDS_Shape &s = faceEdgeMap(i);
CEdge* e = edge_array[edgeMap.FindIndex(s)];
face->m_edges.push_back(e);
e->m_faces.push_back(face);
bool sense = (s.IsEqual(e->Edge()) == Standard_True);
e->m_face_senses.push_back(sense);
}
}
}
<commit_msg>I removed 2 unreferenced variables, after seeing warnings in Linux build.<commit_after>// ShapeTools.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "ShapeTools.h"
#include "Vertex.h"
const wxBitmap &CFaceList::GetIcon()
{
static wxBitmap* icon = NULL;
if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/faces.png")));
return *icon;
}
const wxBitmap &CEdgeList::GetIcon()
{
static wxBitmap* icon = NULL;
if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/edges.png")));
return *icon;
}
const wxBitmap &CVertexList::GetIcon()
{
static wxBitmap* icon = NULL;
if(icon == NULL)icon = new wxBitmap(wxImage(wxGetApp().GetResFolder() + _T("/icons/vertices.png")));
return *icon;
}
void CreateFacesAndEdges(TopoDS_Shape shape, CFaceList* faces, CEdgeList* edges, CVertexList* vertices)
{
// create index maps
TopTools_IndexedMapOfShape faceMap;
TopTools_IndexedMapOfShape edgeMap;
TopTools_IndexedMapOfShape vertexMap;
for (TopExp_Explorer explorer(shape, TopAbs_FACE); explorer.More(); explorer.Next())
{
faceMap.Add(explorer.Current());
}
for (TopExp_Explorer explorer(shape, TopAbs_EDGE); explorer.More(); explorer.Next())
{
edgeMap.Add(explorer.Current());
}
for (TopExp_Explorer explorer(shape, TopAbs_VERTEX); explorer.More(); explorer.Next())
{
vertexMap.Add(explorer.Current());
}
std::vector<CFace*> face_array;
face_array.resize(faceMap.Extent() + 1);
std::vector<CEdge*> edge_array;
edge_array.resize(edgeMap.Extent() + 1);
std::vector<CVertex*> vertex_array;
vertex_array.resize(vertexMap.Extent() + 1);
// create the edge objects
for(int i = 1;i<=edgeMap.Extent();i++)
{
const TopoDS_Shape &s = edgeMap(i);
CEdge* new_object = new CEdge(TopoDS::Edge(s));
edge_array[i] = new_object;
}
// create the vertex objects
for(int i = 1;i<=vertexMap.Extent();i++)
{
const TopoDS_Shape &s = vertexMap(i);
CVertex* new_object = new CVertex(TopoDS::Vertex(s));
vertex_array[i] = new_object;
}
// add the edges in their face loop order
std::set<CEdge*> edges_added;
std::set<CVertex*> vertices_added;
// create the face objects
for(int i = 1;i<=faceMap.Extent();i++)
{
const TopoDS_Shape &s = faceMap(i);
CFace* new_face_object = new CFace(TopoDS::Face(s));
faces->Add(new_face_object, NULL);
face_array[i] = new_face_object;
// create the loop objects
TopTools_IndexedMapOfShape loopMap;
for (TopExp_Explorer explorer(s, TopAbs_WIRE); explorer.More(); explorer.Next())
{
loopMap.Add(explorer.Current());
}
TopoDS_Wire outerWire=BRepTools::OuterWire(new_face_object->Face());
int outer_index = loopMap.FindIndex(outerWire);
for(int i = 1;i<=loopMap.Extent();i++)
{
const TopoDS_Shape &s = loopMap(i);
CLoop* new_loop_object = new CLoop(TopoDS::Wire(s));
new_face_object->m_loops.push_back(new_loop_object);
if(outer_index == i)new_loop_object->m_is_outer = true;
new_loop_object->m_pface = new_face_object;
// find the loop's edges
for(BRepTools_WireExplorer explorer(TopoDS::Wire(s)); explorer.More(); explorer.Next())
{
CEdge* e = edge_array[edgeMap.FindIndex(explorer.Current())];
new_loop_object->m_edges.push_back(e);
// add the edge
if(edges_added.find(e) == edges_added.end())
{
edges->Add(e, NULL);
edges_added.insert(e);
}
// add the vertex
CVertex* v = vertex_array[vertexMap.FindIndex(explorer.CurrentVertex())];
if(vertices_added.find(v) == vertices_added.end())
{
vertices->Add(v, NULL);
vertices_added.insert(v);
}
}
}
}
// find the vertices' edges
for(unsigned int i = 1; i<vertex_array.size(); i++)
{
CVertex* v = vertex_array[i];
TopTools_IndexedMapOfShape vertexEdgeMap;
for (TopExp_Explorer expEdge(v->Vertex(), TopAbs_EDGE); expEdge.More(); expEdge.Next())
{
vertexEdgeMap.Add(expEdge.Current());
}
for(int i = 1; i<=vertexEdgeMap.Extent(); i++)
{
const TopoDS_Shape &s = vertexEdgeMap(i);
CEdge* e = edge_array[edgeMap.FindIndex(s)];
v->m_edges.push_back(e);
}
}
// find the faces' edges
for(unsigned int i = 1; i<face_array.size(); i++)
{
CFace* face = face_array[i];
TopTools_IndexedMapOfShape faceEdgeMap;
for (TopExp_Explorer expEdge(face->Face(), TopAbs_EDGE); expEdge.More(); expEdge.Next())
{
faceEdgeMap.Add(expEdge.Current());
}
for(int i = 1; i<=faceEdgeMap.Extent(); i++)
{
const TopoDS_Shape &s = faceEdgeMap(i);
CEdge* e = edge_array[edgeMap.FindIndex(s)];
face->m_edges.push_back(e);
e->m_faces.push_back(face);
bool sense = (s.IsEqual(e->Edge()) == Standard_True);
e->m_face_senses.push_back(sense);
}
}
}
<|endoftext|> |
<commit_before>// $Id: numeric_vector.C,v 1.17 2005-10-14 15:20:31 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// 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
// C++ includes
#include <cmath> // for std::abs
// Local Includes
#include "numeric_vector.h"
#include "laspack_vector.h"
#include "petsc_vector.h"
//------------------------------------------------------------------
// NumericVector methods
// Full specialization for Real datatypes
template <typename T>
AutoPtr<NumericVector<T> >
NumericVector<T>::build(const SolverPackage solver_package)
{
// Build the appropriate vector
switch (solver_package)
{
#ifdef HAVE_LASPACK
case LASPACK_SOLVERS:
{
AutoPtr<NumericVector<T> > ap(new LaspackVector<T>);
return ap;
}
#endif
#ifdef HAVE_PETSC
case PETSC_SOLVERS:
{
AutoPtr<NumericVector<T> > ap(new PetscVector<T>);
return ap;
}
#endif
default:
std::cerr << "ERROR: Unrecognized solver package: "
<< solver_package
<< std::endl;
error();
}
AutoPtr<NumericVector<T> > ap(NULL);
return ap;
}
// Full specialization for float datatypes (DistributedVector wants this)
template <>
int NumericVector<float>::compare (const NumericVector<float> &other_vector,
const Real threshold) const
{
assert (this->initialized());
assert (other_vector.initialized());
assert (this->first_local_index() == other_vector.first_local_index());
assert (this->last_local_index() == other_vector.last_local_index());
int rvalue = -1;
unsigned int i = first_local_index();
do
{
if ( std::abs( (*this)(i) - other_vector(i) ) > threshold )
rvalue = i;
else
i++;
}
while (rvalue==-1 && i<last_local_index());
return rvalue;
}
// Full specialization for double datatypes
template <>
int NumericVector<double>::compare (const NumericVector<double> &other_vector,
const Real threshold) const
{
assert (this->initialized());
assert (other_vector.initialized());
assert (this->first_local_index() == other_vector.first_local_index());
assert (this->last_local_index() == other_vector.last_local_index());
int rvalue = -1;
unsigned int i = first_local_index();
do
{
if ( std::abs( (*this)(i) - other_vector(i) ) > threshold )
rvalue = i;
else
i++;
}
while (rvalue==-1 && i<last_local_index());
return rvalue;
}
// Full specialization for Complex datatypes
template <>
int NumericVector<Complex>::compare (const NumericVector<Complex> &other_vector,
const Real threshold) const
{
assert (this->initialized());
assert (other_vector.initialized());
assert (this->first_local_index() == other_vector.first_local_index());
assert (this->last_local_index() == other_vector.last_local_index());
int rvalue = -1;
unsigned int i = first_local_index();
do
{
if (( std::abs( (*this)(i).real() - other_vector(i).real() ) > threshold ) ||
( std::abs( (*this)(i).imag() - other_vector(i).imag() ) > threshold ))
rvalue = i;
else
i++;
}
while (rvalue==-1 && i<this->last_local_index());
return rvalue;
}
//------------------------------------------------------------------
// Explicit instantiations
template class NumericVector<Number>;
<commit_msg>Added long double specialization for compare()<commit_after>// $Id: numeric_vector.C,v 1.18 2005-11-30 00:28:32 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// 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
// C++ includes
#include <cmath> // for std::abs
// Local Includes
#include "numeric_vector.h"
#include "laspack_vector.h"
#include "petsc_vector.h"
//------------------------------------------------------------------
// NumericVector methods
// Full specialization for Real datatypes
template <typename T>
AutoPtr<NumericVector<T> >
NumericVector<T>::build(const SolverPackage solver_package)
{
// Build the appropriate vector
switch (solver_package)
{
#ifdef HAVE_LASPACK
case LASPACK_SOLVERS:
{
AutoPtr<NumericVector<T> > ap(new LaspackVector<T>);
return ap;
}
#endif
#ifdef HAVE_PETSC
case PETSC_SOLVERS:
{
AutoPtr<NumericVector<T> > ap(new PetscVector<T>);
return ap;
}
#endif
default:
std::cerr << "ERROR: Unrecognized solver package: "
<< solver_package
<< std::endl;
error();
}
AutoPtr<NumericVector<T> > ap(NULL);
return ap;
}
// Full specialization for float datatypes (DistributedVector wants this)
template <>
int NumericVector<float>::compare (const NumericVector<float> &other_vector,
const Real threshold) const
{
assert (this->initialized());
assert (other_vector.initialized());
assert (this->first_local_index() == other_vector.first_local_index());
assert (this->last_local_index() == other_vector.last_local_index());
int rvalue = -1;
unsigned int i = first_local_index();
do
{
if ( std::abs( (*this)(i) - other_vector(i) ) > threshold )
rvalue = i;
else
i++;
}
while (rvalue==-1 && i<last_local_index());
return rvalue;
}
// Full specialization for double datatypes
template <>
int NumericVector<double>::compare (const NumericVector<double> &other_vector,
const Real threshold) const
{
assert (this->initialized());
assert (other_vector.initialized());
assert (this->first_local_index() == other_vector.first_local_index());
assert (this->last_local_index() == other_vector.last_local_index());
int rvalue = -1;
unsigned int i = first_local_index();
do
{
if ( std::abs( (*this)(i) - other_vector(i) ) > threshold )
rvalue = i;
else
i++;
}
while (rvalue==-1 && i<last_local_index());
return rvalue;
}
#ifdef TRIPLE_PRECISION
// Full specialization for long double datatypes
template <>
int NumericVector<long double>::compare (const NumericVector<long double> &other_vector,
const Real threshold) const
{
assert (this->initialized());
assert (other_vector.initialized());
assert (this->first_local_index() == other_vector.first_local_index());
assert (this->last_local_index() == other_vector.last_local_index());
int rvalue = -1;
unsigned int i = first_local_index();
do
{
if ( std::abs( (*this)(i) - other_vector(i) ) > threshold )
rvalue = i;
else
i++;
}
while (rvalue==-1 && i<last_local_index());
return rvalue;
}
#endif
// Full specialization for Complex datatypes
template <>
int NumericVector<Complex>::compare (const NumericVector<Complex> &other_vector,
const Real threshold) const
{
assert (this->initialized());
assert (other_vector.initialized());
assert (this->first_local_index() == other_vector.first_local_index());
assert (this->last_local_index() == other_vector.last_local_index());
int rvalue = -1;
unsigned int i = first_local_index();
do
{
if (( std::abs( (*this)(i).real() - other_vector(i).real() ) > threshold ) ||
( std::abs( (*this)(i).imag() - other_vector(i).imag() ) > threshold ))
rvalue = i;
else
i++;
}
while (rvalue==-1 && i<this->last_local_index());
return rvalue;
}
//------------------------------------------------------------------
// Explicit instantiations
template class NumericVector<Number>;
<|endoftext|> |
<commit_before>#include "widget.h"
#include "ui_widget.h"
#include <math.h>
#include <string.h>
#include <QPainter>
#include <QConicalGradient>
#include <QMessageBox>
#include <QDebug>
#include <QApplication>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
// initialize pointers
input = NULL;
wheels = NULL;
// set up the UI
ui->setupUi(this);
populateSelects();
// hide the advanced interface
toggleAdvanced(false);
// connect the audio input
connectInput();
// autoselect by default
toggleAutoselect(true);
// initialize wheel definitions
selectScale(0);
// start the update timer
updateTimer = new QTimer(this);
connect(updateTimer, SIGNAL(timeout()), this, SLOT(updateWheels()));
updateTimer->start(50);
}
void Widget::populateSelects()
{
int i, p;
QString s;
for (i = 0; i < freqs.scales.length(); i++) {
ui->selectScale->addItem(freqs.scales.at(i).name, i);
}
for (i = 0; i < freqs.temperaments.length(); i++) {
ui->selectTemperament->addItem(freqs.temperaments.at(i).name, i);
if (i == freqs.temperamentIndex) ui->selectTemperament->setCurrentIndex(i);
}
for (i = 0; i < freqs.pitchNames.length(); i++) {
s = freqs.pitchNames.at(i);
p = freqs.pitches[s];
ui->refPitch->addItem(s, p);
if (p == 69 /* (A4) */) {
ui->refPitch->setCurrentIndex(i);
}
}
ui->refFreq->setValue(freqs.refFreq);
}
void Widget::selectScale(int index)
{
initWheels(freqs.scales[index]);
}
void Widget::updateScale()
{
selectScale(ui->selectScale->currentIndex());
}
void Widget::selectTemperament(int index)
{
if (index != freqs.temperamentIndex) {
freqs.temperamentIndex = index;
freqs.updateFrequencies();
}
}
void Widget::selectRefPitch(int index)
{
int pitch = ui->refPitch->itemData(index).toInt();
if (pitch != freqs.refPitch) {
freqs.refPitch = pitch;
freqs.updateFrequencies();
updateScale();
}
}
void Widget::changeRefFreq(double freq) {
if (freq != freqs.refFreq) {
freqs.refFreq = freq;
freqs.updateFrequencies();
updateScale();
}
}
void Widget::initWheels(Scale scale)
{
// remove any existing wheel definitions
destroyWheels();
// make new ones
float period;
int sampleCount, d;
float sampleRate = (input != NULL) ? (float)input->getSampleRate() : 44100.0;
QString pitch;
wheelCount = scale.pitches.length();
wheels = new Wheel[wheelCount];
Wheel *wheel = wheels;
for (int i = 0; i < wheelCount; i++) {
pitch = scale.pitches.at(i);
wheel->frequency = freqs.frequencies[freqs.pitches[pitch]];
wheel->label = pitch;
if (wheel->frequency >= 20.0) {
period = sampleRate / wheel->frequency;
sampleCount = (int)period - 1;
}
else {
period = 2.0;
sampleCount = 2;
}
wheel->sampleCount = sampleCount;
wheel->sampleBuffer = new jack_default_audio_sample_t[sampleCount];
wheel->sample = wheel->sampleBuffer;
wheel->endSample = wheel->sample + sampleCount;
wheel->addCounts = new int[sampleCount];
wheel->addCount = wheel->addCounts;
wheel->step = (float)sampleCount / period;
wheel->error = 0.0;
wheel->unders = 0;
wheel->overs = 0;
wheel->diffIndex = 0;
for (d = 0; d < WHEEL_DIFF_COUNT; d++) {
wheel->diffs[d] = 0;
}
wheel++;
}
}
void Widget::updateWheels()
{
if (input == NULL) return;
// clear existing wheel data
int w;
Wheel *wheel = wheels;
for (w = 0; w < wheelCount; w++) {
memset(wheel->sampleBuffer, 0,
wheel->sampleCount * sizeof(*(wheel->sampleBuffer)));
memset(wheel->addCounts, 0,
wheel->sampleCount * sizeof(*(wheel->addCounts)));
wheel++;
}
// get audio input
jack_default_audio_sample_t *samples = NULL;
jack_nframes_t sampleCount = input->read(&samples);
jack_default_audio_sample_t *sample = samples;
// add input samples to wheels
jack_nframes_t s;
int intStep;
for (s = 0; s < sampleCount; s++) {
wheel = wheels;
for (w = 0; w < wheelCount; w++) {
*(wheel->sample) += *sample;
*(wheel->addCount) += 1;
// advance the wheel sample pointer
wheel->error += wheel->step;
if (wheel->error >= 1.0) {
intStep = (int)wheel->error;
wheel->sample += intStep;
wheel->addCount += intStep;
wheel->error -= (float)intStep;
}
if (wheel->sample >= wheel->endSample) {
intStep = wheel->sample - wheel->endSample;
wheel->sample = wheel->sampleBuffer + intStep;
wheel->addCount = wheel->addCounts + intStep;
}
wheel++;
}
sample++;
}
// release sample buffer
delete[] samples;
// do post-processing of samples in the wheel
wheel = wheels;
int *addCount;
jack_default_audio_sample_t maxAmplitude;
jack_default_audio_sample_t amplify;
jack_default_audio_sample_t amplitude;
for (w = 0; w < wheelCount; w++) {
maxAmplitude = 0.0;
// average added samples and get the maximum amplitude
addCount = wheel->addCounts;
sample = wheel->sampleBuffer;
for (s = 0; s < wheel->sampleCount; s++) {
*sample /= (float)*addCount;
// track the maximum amplitude
amplitude = fabs(*sample);
if (amplitude > maxAmplitude) maxAmplitude = amplitude;
// advance to the next sample
addCount++;
sample++;
}
// normalize all samples to compensate for low levels
// (unless we're basically getting silence)
if (maxAmplitude > 0.0001) {
amplify = 1.0 / maxAmplitude;
sample = wheel->sampleBuffer;
for (s = 0; s < wheel->sampleCount; s++) {
*sample *= amplify;
sample++;
}
}
wheel->maxAmplitude = maxAmplitude;
// update stats
updateWheelStats(wheel);
wheel++;
}
selectWheels();
// repaint the wheels
repaint();
}
void Widget::updateWheelStats(Wheel *wheel)
{
jack_nframes_t s;
int unders, overs, diff, diffSum, d;
// reset counters
wheel->zeroCrossings = unders = overs = 0;
// loop over samples
jack_default_audio_sample_t *sample = wheel->sampleBuffer;
jack_default_audio_sample_t last = wheel->sampleBuffer[wheel->sampleCount - 1];
for (s = 0; s < wheel->sampleCount; s++) {
// count samples above and below zero
if (*sample < 0.0) {
if (last >= 0.0) wheel->zeroCrossings++;
unders++;
}
else {
if (last < 0.0) wheel->zeroCrossings++;
overs++;
}
last = *sample;
sample++;
}
diff = abs(wheel->unders - unders) + abs(wheel->overs - overs);
wheel->unders = unders;
wheel->overs = overs;
wheel->diffs[wheel->diffIndex] = diff;
wheel->diffIndex = (wheel->diffIndex + 1) % WHEEL_DIFF_COUNT;
diffSum = 0;
for (d = 0; d < WHEEL_DIFF_COUNT; d++) {
diffSum += wheel->diffs[d];
}
wheel->instability =
(float)diffSum / (float)(WHEEL_DIFF_COUNT * wheel->sampleCount);
}
void Widget::selectWheels()
{
int i;
float maxAmplitude = 0.0;
for (i = 0; i < wheelCount; i++) {
wheels[i].selected = true;
if (wheels[i].maxAmplitude > maxAmplitude) {
maxAmplitude = wheels[i].maxAmplitude;
}
}
if (autoselect) {
float cutoff = maxAmplitude * 0.95;
int minZC = 1000000;
for (i = 0; i < wheelCount; i++) {
if (wheels[i].maxAmplitude < cutoff) {
wheels[i].selected = false;
}
else if (wheels[i].zeroCrossings < minZC) {
minZC = wheels[i].zeroCrossings;
}
}
for (i = 0; i < wheelCount; i++) {
if (wheels[i].zeroCrossings > minZC) {
wheels[i].selected = false;
}
}
}
}
void Widget::destroyWheels()
{
if (wheels != NULL) {
for (int i = 0; i < wheelCount; i++) {
delete[] wheels[i].sampleBuffer;
delete[] wheels[i].addCounts;
}
delete[] wheels;
wheels = NULL;
}
wheelCount = 0;
}
void Widget::toggleConnected(bool connected)
{
if (connected) connectInput();
else disconnectInput();
}
void Widget::connectInput()
{
// if input is already connected, we're done
if (input != NULL) return;
try {
input = new JackInput(0.2);
ui->toggleConnected->setChecked(true);
}
catch (JackInputException& e) {
ui->toggleConnected->setChecked(false);
QMessageBox *msg = new QMessageBox(QMessageBox::Critical,
"JACK Input Error", e.what());
msg->exec();
}
}
void Widget::disconnectInput()
{
if (input != NULL) {
delete input;
input = NULL;
ui->toggleConnected->setChecked(false);
}
}
void Widget::toggleAutoselect(bool value)
{
autoselect = value;
ui->toggleAutoselect->setChecked(value);
}
void Widget::toggleAdvanced(bool showAdvanced)
{
if (! showAdvanced) {
ui->advancedFrame->setMaximumWidth(0);
ui->toggleAdvanced->setText("»");
ui->toggleAdvanced->setChecked(false);
}
else {
ui->advancedFrame->setMaximumWidth(QWIDGETSIZE_MAX);
ui->toggleAdvanced->setText("«");
ui->toggleAdvanced->setChecked(true);
}
}
void Widget::paintEvent(QPaintEvent *)
{
// check boundary conditions
if ((! (width() > 0)) || (! (height() > 0))) return;
if ((! (wheelCount > 0)) || (wheels == NULL)) return;
// set layout params
QRect bounds = ui->wheelArea->geometry();
int w = bounds.width();
int h = bounds.height();
// lay out the wheels in a grid of squares
int columns = 1;
int rows;
while ((rows = h / (w / columns)) * columns < wheelCount) {
columns++;
}
w /= columns;
h /= rows;
// draw the wheels
float alpha;
int margin = 6;
QRect r(bounds.x(), bounds.y(), w, h);
r.adjust(margin, margin, - margin, - margin);
Wheel *wheel = wheels;
for (int i = 0; i < wheelCount; i++) {
if (wheel->instability <= 0.05) alpha = 1.0;
else {
alpha = 1.0 - (wheel->instability - 0.05) / 0.10;
if (alpha < 0.05) alpha = 0.05;
}
if (autoselect) alpha *= wheel->selected ? 1.0 : 0.05;
drawWheel(r, wheel, alpha);
// advance to the next position
r.moveLeft(r.left() + w);
if (r.right() > width()) {
r.moveLeft(bounds.x());
r.moveTop(r.top() + h);
}
wheel++;
}
}
void Widget::drawWheel(QRect r, Wheel *wheel, float alpha)
{
QPainter painter(this);
painter.save();
painter.setRenderHint(QPainter::Antialiasing);
painter.translate(r.center().x(), r.center().y());
// precompute dimensions and steps
float outerRadius = (float)qMin(r.width(), r.height()) / 2.0;
float innerRadius = outerRadius / 2.0;
float phaseStep = 1.0 / (float)wheel->sampleCount;
// set up a gradient to make the wheel contents
painter.setPen(Qt::NoPen);
jack_default_audio_sample_t *sample = wheel->sampleBuffer;
float value;
float phase = 0.0;
QColor color;
QConicalGradient gradient(QPointF(0, 0), 90);
for (jack_nframes_t s = 0; s < wheel->sampleCount; s++) {
value = qMin(1.0, fabs(*sample)) * alpha;
if (*sample > 0.0) {
color = QColor::fromHsvF(0.0, 0.0, 1.0, value);
}
else {
color = QColor::fromHsvF(0.0, 0.0, 0.0, value);
}
gradient.setColorAt(phase, color);
sample++;
phase += phaseStep;
}
// draw the wheel contents
QPainterPath path;
path.addEllipse(QPointF(0.0, 0.0), outerRadius, outerRadius);
QPainterPath hole;
hole.addEllipse(QPointF(0.0, 0.0), innerRadius, innerRadius);
path = path.subtracted(hole);
painter.setPen(QPen(QApplication::palette().windowText(), 1));
painter.setBrush(QBrush(gradient));
painter.drawPath(path);
// restore context
painter.restore();
// draw the label in the center
if (wheel->label != NULL) {
QFont font = painter.font();
font.setPixelSize((int)floor(innerRadius * 0.75));
painter.setFont(font);
painter.drawText(r, Qt::AlignHCenter | Qt::AlignVCenter, wheel->label);
}
}
Widget::~Widget()
{
delete ui;
delete updateTimer;
destroyWheels();
}
<commit_msg>Fix build error by using floats in qMin comparison<commit_after>#include "widget.h"
#include "ui_widget.h"
#include <math.h>
#include <string.h>
#include <QPainter>
#include <QConicalGradient>
#include <QMessageBox>
#include <QDebug>
#include <QApplication>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
// initialize pointers
input = NULL;
wheels = NULL;
// set up the UI
ui->setupUi(this);
populateSelects();
// hide the advanced interface
toggleAdvanced(false);
// connect the audio input
connectInput();
// autoselect by default
toggleAutoselect(true);
// initialize wheel definitions
selectScale(0);
// start the update timer
updateTimer = new QTimer(this);
connect(updateTimer, SIGNAL(timeout()), this, SLOT(updateWheels()));
updateTimer->start(50);
}
void Widget::populateSelects()
{
int i, p;
QString s;
for (i = 0; i < freqs.scales.length(); i++) {
ui->selectScale->addItem(freqs.scales.at(i).name, i);
}
for (i = 0; i < freqs.temperaments.length(); i++) {
ui->selectTemperament->addItem(freqs.temperaments.at(i).name, i);
if (i == freqs.temperamentIndex) ui->selectTemperament->setCurrentIndex(i);
}
for (i = 0; i < freqs.pitchNames.length(); i++) {
s = freqs.pitchNames.at(i);
p = freqs.pitches[s];
ui->refPitch->addItem(s, p);
if (p == 69 /* (A4) */) {
ui->refPitch->setCurrentIndex(i);
}
}
ui->refFreq->setValue(freqs.refFreq);
}
void Widget::selectScale(int index)
{
initWheels(freqs.scales[index]);
}
void Widget::updateScale()
{
selectScale(ui->selectScale->currentIndex());
}
void Widget::selectTemperament(int index)
{
if (index != freqs.temperamentIndex) {
freqs.temperamentIndex = index;
freqs.updateFrequencies();
}
}
void Widget::selectRefPitch(int index)
{
int pitch = ui->refPitch->itemData(index).toInt();
if (pitch != freqs.refPitch) {
freqs.refPitch = pitch;
freqs.updateFrequencies();
updateScale();
}
}
void Widget::changeRefFreq(double freq) {
if (freq != freqs.refFreq) {
freqs.refFreq = freq;
freqs.updateFrequencies();
updateScale();
}
}
void Widget::initWheels(Scale scale)
{
// remove any existing wheel definitions
destroyWheels();
// make new ones
float period;
int sampleCount, d;
float sampleRate = (input != NULL) ? (float)input->getSampleRate() : 44100.0;
QString pitch;
wheelCount = scale.pitches.length();
wheels = new Wheel[wheelCount];
Wheel *wheel = wheels;
for (int i = 0; i < wheelCount; i++) {
pitch = scale.pitches.at(i);
wheel->frequency = freqs.frequencies[freqs.pitches[pitch]];
wheel->label = pitch;
if (wheel->frequency >= 20.0) {
period = sampleRate / wheel->frequency;
sampleCount = (int)period - 1;
}
else {
period = 2.0;
sampleCount = 2;
}
wheel->sampleCount = sampleCount;
wheel->sampleBuffer = new jack_default_audio_sample_t[sampleCount];
wheel->sample = wheel->sampleBuffer;
wheel->endSample = wheel->sample + sampleCount;
wheel->addCounts = new int[sampleCount];
wheel->addCount = wheel->addCounts;
wheel->step = (float)sampleCount / period;
wheel->error = 0.0;
wheel->unders = 0;
wheel->overs = 0;
wheel->diffIndex = 0;
for (d = 0; d < WHEEL_DIFF_COUNT; d++) {
wheel->diffs[d] = 0;
}
wheel++;
}
}
void Widget::updateWheels()
{
if (input == NULL) return;
// clear existing wheel data
int w;
Wheel *wheel = wheels;
for (w = 0; w < wheelCount; w++) {
memset(wheel->sampleBuffer, 0,
wheel->sampleCount * sizeof(*(wheel->sampleBuffer)));
memset(wheel->addCounts, 0,
wheel->sampleCount * sizeof(*(wheel->addCounts)));
wheel++;
}
// get audio input
jack_default_audio_sample_t *samples = NULL;
jack_nframes_t sampleCount = input->read(&samples);
jack_default_audio_sample_t *sample = samples;
// add input samples to wheels
jack_nframes_t s;
int intStep;
for (s = 0; s < sampleCount; s++) {
wheel = wheels;
for (w = 0; w < wheelCount; w++) {
*(wheel->sample) += *sample;
*(wheel->addCount) += 1;
// advance the wheel sample pointer
wheel->error += wheel->step;
if (wheel->error >= 1.0) {
intStep = (int)wheel->error;
wheel->sample += intStep;
wheel->addCount += intStep;
wheel->error -= (float)intStep;
}
if (wheel->sample >= wheel->endSample) {
intStep = wheel->sample - wheel->endSample;
wheel->sample = wheel->sampleBuffer + intStep;
wheel->addCount = wheel->addCounts + intStep;
}
wheel++;
}
sample++;
}
// release sample buffer
delete[] samples;
// do post-processing of samples in the wheel
wheel = wheels;
int *addCount;
jack_default_audio_sample_t maxAmplitude;
jack_default_audio_sample_t amplify;
jack_default_audio_sample_t amplitude;
for (w = 0; w < wheelCount; w++) {
maxAmplitude = 0.0;
// average added samples and get the maximum amplitude
addCount = wheel->addCounts;
sample = wheel->sampleBuffer;
for (s = 0; s < wheel->sampleCount; s++) {
*sample /= (float)*addCount;
// track the maximum amplitude
amplitude = fabs(*sample);
if (amplitude > maxAmplitude) maxAmplitude = amplitude;
// advance to the next sample
addCount++;
sample++;
}
// normalize all samples to compensate for low levels
// (unless we're basically getting silence)
if (maxAmplitude > 0.0001) {
amplify = 1.0 / maxAmplitude;
sample = wheel->sampleBuffer;
for (s = 0; s < wheel->sampleCount; s++) {
*sample *= amplify;
sample++;
}
}
wheel->maxAmplitude = maxAmplitude;
// update stats
updateWheelStats(wheel);
wheel++;
}
selectWheels();
// repaint the wheels
repaint();
}
void Widget::updateWheelStats(Wheel *wheel)
{
jack_nframes_t s;
int unders, overs, diff, diffSum, d;
// reset counters
wheel->zeroCrossings = unders = overs = 0;
// loop over samples
jack_default_audio_sample_t *sample = wheel->sampleBuffer;
jack_default_audio_sample_t last = wheel->sampleBuffer[wheel->sampleCount - 1];
for (s = 0; s < wheel->sampleCount; s++) {
// count samples above and below zero
if (*sample < 0.0) {
if (last >= 0.0) wheel->zeroCrossings++;
unders++;
}
else {
if (last < 0.0) wheel->zeroCrossings++;
overs++;
}
last = *sample;
sample++;
}
diff = abs(wheel->unders - unders) + abs(wheel->overs - overs);
wheel->unders = unders;
wheel->overs = overs;
wheel->diffs[wheel->diffIndex] = diff;
wheel->diffIndex = (wheel->diffIndex + 1) % WHEEL_DIFF_COUNT;
diffSum = 0;
for (d = 0; d < WHEEL_DIFF_COUNT; d++) {
diffSum += wheel->diffs[d];
}
wheel->instability =
(float)diffSum / (float)(WHEEL_DIFF_COUNT * wheel->sampleCount);
}
void Widget::selectWheels()
{
int i;
float maxAmplitude = 0.0;
for (i = 0; i < wheelCount; i++) {
wheels[i].selected = true;
if (wheels[i].maxAmplitude > maxAmplitude) {
maxAmplitude = wheels[i].maxAmplitude;
}
}
if (autoselect) {
float cutoff = maxAmplitude * 0.95;
int minZC = 1000000;
for (i = 0; i < wheelCount; i++) {
if (wheels[i].maxAmplitude < cutoff) {
wheels[i].selected = false;
}
else if (wheels[i].zeroCrossings < minZC) {
minZC = wheels[i].zeroCrossings;
}
}
for (i = 0; i < wheelCount; i++) {
if (wheels[i].zeroCrossings > minZC) {
wheels[i].selected = false;
}
}
}
}
void Widget::destroyWheels()
{
if (wheels != NULL) {
for (int i = 0; i < wheelCount; i++) {
delete[] wheels[i].sampleBuffer;
delete[] wheels[i].addCounts;
}
delete[] wheels;
wheels = NULL;
}
wheelCount = 0;
}
void Widget::toggleConnected(bool connected)
{
if (connected) connectInput();
else disconnectInput();
}
void Widget::connectInput()
{
// if input is already connected, we're done
if (input != NULL) return;
try {
input = new JackInput(0.2);
ui->toggleConnected->setChecked(true);
}
catch (JackInputException& e) {
ui->toggleConnected->setChecked(false);
QMessageBox *msg = new QMessageBox(QMessageBox::Critical,
"JACK Input Error", e.what());
msg->exec();
}
}
void Widget::disconnectInput()
{
if (input != NULL) {
delete input;
input = NULL;
ui->toggleConnected->setChecked(false);
}
}
void Widget::toggleAutoselect(bool value)
{
autoselect = value;
ui->toggleAutoselect->setChecked(value);
}
void Widget::toggleAdvanced(bool showAdvanced)
{
if (! showAdvanced) {
ui->advancedFrame->setMaximumWidth(0);
ui->toggleAdvanced->setText("»");
ui->toggleAdvanced->setChecked(false);
}
else {
ui->advancedFrame->setMaximumWidth(QWIDGETSIZE_MAX);
ui->toggleAdvanced->setText("«");
ui->toggleAdvanced->setChecked(true);
}
}
void Widget::paintEvent(QPaintEvent *)
{
// check boundary conditions
if ((! (width() > 0)) || (! (height() > 0))) return;
if ((! (wheelCount > 0)) || (wheels == NULL)) return;
// set layout params
QRect bounds = ui->wheelArea->geometry();
int w = bounds.width();
int h = bounds.height();
// lay out the wheels in a grid of squares
int columns = 1;
int rows;
while ((rows = h / (w / columns)) * columns < wheelCount) {
columns++;
}
w /= columns;
h /= rows;
// draw the wheels
float alpha;
int margin = 6;
QRect r(bounds.x(), bounds.y(), w, h);
r.adjust(margin, margin, - margin, - margin);
Wheel *wheel = wheels;
for (int i = 0; i < wheelCount; i++) {
if (wheel->instability <= 0.05) alpha = 1.0;
else {
alpha = 1.0 - (wheel->instability - 0.05) / 0.10;
if (alpha < 0.05) alpha = 0.05;
}
if (autoselect) alpha *= wheel->selected ? 1.0 : 0.05;
drawWheel(r, wheel, alpha);
// advance to the next position
r.moveLeft(r.left() + w);
if (r.right() > width()) {
r.moveLeft(bounds.x());
r.moveTop(r.top() + h);
}
wheel++;
}
}
void Widget::drawWheel(QRect r, Wheel *wheel, float alpha)
{
QPainter painter(this);
painter.save();
painter.setRenderHint(QPainter::Antialiasing);
painter.translate(r.center().x(), r.center().y());
// precompute dimensions and steps
float outerRadius = (float)qMin(r.width(), r.height()) / 2.0;
float innerRadius = outerRadius / 2.0;
float phaseStep = 1.0 / (float)wheel->sampleCount;
// set up a gradient to make the wheel contents
painter.setPen(Qt::NoPen);
jack_default_audio_sample_t *sample = wheel->sampleBuffer;
float value;
float phase = 0.0;
QColor color;
QConicalGradient gradient(QPointF(0, 0), 90);
for (jack_nframes_t s = 0; s < wheel->sampleCount; s++) {
value = qMin(1.0f, fabsf(*sample)) * alpha;
if (*sample > 0.0) {
color = QColor::fromHsvF(0.0, 0.0, 1.0, value);
}
else {
color = QColor::fromHsvF(0.0, 0.0, 0.0, value);
}
gradient.setColorAt(phase, color);
sample++;
phase += phaseStep;
}
// draw the wheel contents
QPainterPath path;
path.addEllipse(QPointF(0.0, 0.0), outerRadius, outerRadius);
QPainterPath hole;
hole.addEllipse(QPointF(0.0, 0.0), innerRadius, innerRadius);
path = path.subtracted(hole);
painter.setPen(QPen(QApplication::palette().windowText(), 1));
painter.setBrush(QBrush(gradient));
painter.drawPath(path);
// restore context
painter.restore();
// draw the label in the center
if (wheel->label != NULL) {
QFont font = painter.font();
font.setPixelSize((int)floor(innerRadius * 0.75));
painter.setFont(font);
painter.drawText(r, Qt::AlignHCenter | Qt::AlignVCenter, wheel->label);
}
}
Widget::~Widget()
{
delete ui;
delete updateTimer;
destroyWheels();
}
<|endoftext|> |
<commit_before>#ifndef __STRUCTDESC_HPP__
#define __STRUCTDESC_HPP__
#include <string>
#include <memory>
#include "FileSink.hpp"
#include "StructDescTypes.hpp"
#define offsetof(type, member) __builtin_offsetof (type, member)
#define REGISTER_RAW_VALUE(desc, _class_, field, name) \
(desc)->registerRawValue<decltype(_class_::field)>( \
name, offsetof(_class_, field))
#define REGISTER_STRING(desc, _class_, field, name) \
(desc)->registerRawValue<const char *>( \
name, offsetof(_class_, field))
class StructDesc {
private:
enum EntryType : uint8_t {
ENTRY_TYPE_RAWVALUE = 0,
};
struct EntryDesc {
std::string mName;
std::shared_ptr<StructDesc> mChildDesc;
ssize_t (*mDescWriter) (EntryDesc *desc, ISink *sink);
ssize_t (*mValueWriter) (EntryDesc *desc, ISink *sink, void *base);
EntryDesc()
{
mChildDesc = nullptr;
mDescWriter = nullptr;
mValueWriter = nullptr;
}
union {
struct {
uint64_t offset;
} raw;
} mParams;
};
// TODO : try to restore this for gcc versions >= 4.7
// template <typename T>
// using EnumType = typename std::underlying_type<T>::type;
private:
std::list<EntryDesc *> mEntryDescList;
private:
template <typename T>
static ssize_t descWriterRaw(EntryDesc *desc, ISink *sink)
{
ValueTrait<std::string>::write(sink, desc->mName);
uint8_t type = EntryType::ENTRY_TYPE_RAWVALUE;
ValueTrait<uint8_t>::write(sink, type);
uint8_t rawType = ValueTrait<T>::type;
ValueTrait<uint8_t>::write(sink, rawType);
return 0;
}
template <typename T>
static ssize_t valueWriterRaw(EntryDesc *desc, ISink *sink, void *base)
{
std::ptrdiff_t p = (std::ptrdiff_t ) base + desc->mParams.raw.offset;
return ValueTrait<T>::write(sink, *((T *) p));
}
public:
~StructDesc()
{
for (auto &e : mEntryDescList) {
e->mChildDesc.reset();
delete e;
}
}
template <typename T>
int registerRawValue(const char *name, uint64_t offset)
{
EntryDesc *desc = new EntryDesc();
static_assert(ValueTrait<T>::type != RAW_VALUE_TYPE_INVALID,
"Unsupported type");
desc->mName = name;
desc->mDescWriter = descWriterRaw<T>;
desc->mValueWriter = valueWriterRaw<T>;
desc->mParams.raw.offset = offset;
mEntryDescList.push_back(desc);
return 0;
}
int writeDesc(ISink *sink)
{
uint32_t entryCount = (uint32_t) mEntryDescList.size();
ValueTrait<uint32_t>::write(sink, entryCount);
for (auto &desc: mEntryDescList)
desc->mDescWriter(desc, sink);
return 0;
}
int writeValueInternal(ISink *sink, void *p)
{
for (auto &desc: mEntryDescList)
desc->mValueWriter(desc, sink, p);
return 0;
}
template <typename T>
int writeValue(ISink *sink, T *p)
{
return writeValueInternal(sink, (void *) p);
}
};
template <>
ssize_t StructDesc::valueWriterRaw<const char *>(EntryDesc *desc, ISink *sink, void *base)
{
std::ptrdiff_t p = (std::ptrdiff_t ) base + desc->mParams.raw.offset;
return ValueTrait<const char *>::write(sink, (const char *) p);
}
#endif // !__STRUCTDESC_HPP__
<commit_msg>[DEV] Remove useless StructDesc::EntryDesc::mChildDesc<commit_after>#ifndef __STRUCTDESC_HPP__
#define __STRUCTDESC_HPP__
#include <string>
#include <memory>
#include "FileSink.hpp"
#include "StructDescTypes.hpp"
#define offsetof(type, member) __builtin_offsetof (type, member)
#define REGISTER_RAW_VALUE(desc, _class_, field, name) \
(desc)->registerRawValue<decltype(_class_::field)>( \
name, offsetof(_class_, field))
#define REGISTER_STRING(desc, _class_, field, name) \
(desc)->registerRawValue<const char *>( \
name, offsetof(_class_, field))
class StructDesc {
private:
enum EntryType : uint8_t {
ENTRY_TYPE_RAWVALUE = 0,
};
struct EntryDesc {
std::string mName;
ssize_t (*mDescWriter) (EntryDesc *desc, ISink *sink);
ssize_t (*mValueWriter) (EntryDesc *desc, ISink *sink, void *base);
EntryDesc()
{
mDescWriter = nullptr;
mValueWriter = nullptr;
}
union {
struct {
uint64_t offset;
} raw;
} mParams;
};
// TODO : try to restore this for gcc versions >= 4.7
// template <typename T>
// using EnumType = typename std::underlying_type<T>::type;
private:
std::list<EntryDesc *> mEntryDescList;
private:
template <typename T>
static ssize_t descWriterRaw(EntryDesc *desc, ISink *sink)
{
ValueTrait<std::string>::write(sink, desc->mName);
uint8_t type = EntryType::ENTRY_TYPE_RAWVALUE;
ValueTrait<uint8_t>::write(sink, type);
uint8_t rawType = ValueTrait<T>::type;
ValueTrait<uint8_t>::write(sink, rawType);
return 0;
}
template <typename T>
static ssize_t valueWriterRaw(EntryDesc *desc, ISink *sink, void *base)
{
std::ptrdiff_t p = (std::ptrdiff_t ) base + desc->mParams.raw.offset;
return ValueTrait<T>::write(sink, *((T *) p));
}
public:
~StructDesc()
{
for (auto &e : mEntryDescList)
delete e;
}
template <typename T>
int registerRawValue(const char *name, uint64_t offset)
{
EntryDesc *desc = new EntryDesc();
static_assert(ValueTrait<T>::type != RAW_VALUE_TYPE_INVALID,
"Unsupported type");
desc->mName = name;
desc->mDescWriter = descWriterRaw<T>;
desc->mValueWriter = valueWriterRaw<T>;
desc->mParams.raw.offset = offset;
mEntryDescList.push_back(desc);
return 0;
}
int writeDesc(ISink *sink)
{
uint32_t entryCount = (uint32_t) mEntryDescList.size();
ValueTrait<uint32_t>::write(sink, entryCount);
for (auto &desc: mEntryDescList)
desc->mDescWriter(desc, sink);
return 0;
}
int writeValueInternal(ISink *sink, void *p)
{
for (auto &desc: mEntryDescList)
desc->mValueWriter(desc, sink, p);
return 0;
}
template <typename T>
int writeValue(ISink *sink, T *p)
{
return writeValueInternal(sink, (void *) p);
}
};
template <>
ssize_t StructDesc::valueWriterRaw<const char *>(EntryDesc *desc, ISink *sink, void *base)
{
std::ptrdiff_t p = (std::ptrdiff_t ) base + desc->mParams.raw.offset;
return ValueTrait<const char *>::write(sink, (const char *) p);
}
#endif // !__STRUCTDESC_HPP__
<|endoftext|> |
<commit_before>#include <string.h>
#include "JWModules.hpp"
struct ThingThingBall {
NVGcolor color;
};
struct ThingThing : Module {
enum ParamIds {
BALL_RAD_PARAM,
ZOOM_MULT_PARAM,
NUM_PARAMS
};
enum InputIds {
BALL_RAD_INPUT,
ZOOM_MULT_INPUT,
ANG_INPUT,
NUM_INPUTS = ANG_INPUT + 5
};
enum OutputIds {
NUM_OUTPUTS
};
enum LightIds {
NUM_LIGHTS
};
ThingThingBall *balls = new ThingThingBall[5];
float atten[5] = {1, 1, 1, 1, 1};
// float atten[5] = {0.0, 0.25, 0.5, 0.75, 1};
ThingThing() {
config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);
configParam(BALL_RAD_PARAM, 0.0, 30.0, 10.0);
configParam(ZOOM_MULT_PARAM, 1.0, 200.0, 20.0);
balls[0].color = nvgRGB(255, 255, 255);//white
balls[1].color = nvgRGB(255, 151, 9);//orange
balls[2].color = nvgRGB(255, 243, 9);//yellow
balls[3].color = nvgRGB(144, 26, 252);//purple
balls[4].color = nvgRGB(25, 150, 252);//blue
}
~ThingThing() {
delete [] balls;
}
void process(const ProcessArgs &args) override {};
void onReset() override {}
json_t *dataToJson() override {
json_t *rootJ = json_object();
return rootJ;
}
void dataFromJson(json_t *rootJ) override {}
};
struct ThingThingDisplay : Widget {
ThingThing *module;
ThingThingDisplay(){}
void draw(const DrawArgs &args) override {
//background
nvgFillColor(args.vg, nvgRGB(20, 30, 33));
nvgBeginPath(args.vg);
nvgRect(args.vg, 0, 0, box.size.x, box.size.y);
nvgFill(args.vg);
if(module == NULL) return;
float ballRadius = module->params[ThingThing::BALL_RAD_PARAM].getValue();
if(module->inputs[ThingThing::BALL_RAD_INPUT].isConnected()){
ballRadius += rescalefjw(module->inputs[ThingThing::BALL_RAD_INPUT].getVoltage(), -5.0, 5.0, 0.0, 30.0);
}
float zoom = module->params[ThingThing::ZOOM_MULT_PARAM].getValue();
if(module->inputs[ThingThing::ZOOM_MULT_INPUT].isConnected()){
ballRadius += rescalefjw(module->inputs[ThingThing::ZOOM_MULT_INPUT].getVoltage(), -5.0, 5.0, 1.0, 50.0);
}
float x[5];
float y[5];
float angle[5];
for(int i=0; i<5; i++){
angle[i] = i==0 ? 0 : (module->inputs[ThingThing::ANG_INPUT+i].getVoltage() + angle[i-1]) * module->atten[i];
x[i] = i==0 ? 0 : sinf(rescalefjw(angle[i], -5, 5, -2*M_PI + M_PI/2.0f, 2*M_PI + M_PI/2.0f)) * zoom;
y[i] = i==0 ? 0 : cosf(rescalefjw(angle[i], -5, 5, -2*M_PI + M_PI/2.0f, 2*M_PI + M_PI/2.0f)) * zoom;
}
/////////////////////// LINES ///////////////////////
nvgSave(args.vg);
nvgTranslate(args.vg, box.size.x * 0.5, box.size.y * 0.5);
for(int i=0; i<5; i++){
nvgTranslate(args.vg, x[i], y[i]);
nvgStrokeColor(args.vg, nvgRGB(255, 255, 255));
if(i>0){
nvgStrokeWidth(args.vg, 1);
nvgBeginPath(args.vg);
nvgMoveTo(args.vg, 0, 0);
nvgLineTo(args.vg, -x[i], -y[i]);
nvgStroke(args.vg);
}
}
nvgRestore(args.vg);
/////////////////////// BALLS ///////////////////////
nvgSave(args.vg);
nvgTranslate(args.vg, box.size.x * 0.5, box.size.y * 0.5);
for(int i=0; i<5; i++){
nvgTranslate(args.vg, x[i], y[i]);
nvgStrokeColor(args.vg, module->balls[i].color);
nvgFillColor(args.vg, module->balls[i].color);
nvgStrokeWidth(args.vg, 2);
nvgBeginPath(args.vg);
nvgCircle(args.vg, 0, 0, ballRadius);
nvgFill(args.vg);
nvgStroke(args.vg);
}
nvgRestore(args.vg);
}
};
struct ThingThingWidget : ModuleWidget {
ThingThingWidget(ThingThing *module);
};
ThingThingWidget::ThingThingWidget(ThingThing *module) {
setModule(module);
box.size = Vec(RACK_GRID_WIDTH*20, RACK_GRID_HEIGHT);
SVGPanel *panel = new SVGPanel();
panel->box.size = box.size;
panel->setBackground(APP->window->loadSvg(asset::plugin(pluginInstance, "res/ThingThing.svg")));
addChild(panel);
ThingThingDisplay *display = new ThingThingDisplay();
display->module = module;
display->box.pos = Vec(0, 0);
display->box.size = Vec(box.size.x, RACK_GRID_HEIGHT);
addChild(display);
addChild(createWidget<Screw_J>(Vec(265, 365)));
addChild(createWidget<Screw_W>(Vec(280, 365)));
for(int i=0; i<4; i++){
addInput(createInput<TinyPJ301MPort>(Vec(5+(20*i), 360), module, ThingThing::ANG_INPUT+i+1));
}
addInput(createInput<TinyPJ301MPort>(Vec(140, 360), module, ThingThing::BALL_RAD_INPUT));
addParam(createParam<JwTinyKnob>(Vec(155, 360), module, ThingThing::BALL_RAD_PARAM));
addInput(createInput<TinyPJ301MPort>(Vec(190, 360), module, ThingThing::ZOOM_MULT_INPUT));
addParam(createParam<JwTinyKnob>(Vec(205, 360), module, ThingThing::ZOOM_MULT_PARAM));
}
Model *modelThingThing = createModel<ThingThing, ThingThingWidget>("ThingThing");
<commit_msg>fixed thing thing input bug<commit_after>#include <string.h>
#include "JWModules.hpp"
struct ThingThingBall {
NVGcolor color;
};
struct ThingThing : Module {
enum ParamIds {
BALL_RAD_PARAM,
ZOOM_MULT_PARAM,
NUM_PARAMS
};
enum InputIds {
BALL_RAD_INPUT,
ZOOM_MULT_INPUT,
ANG_INPUT,
NUM_INPUTS = ANG_INPUT + 5
};
enum OutputIds {
NUM_OUTPUTS
};
enum LightIds {
NUM_LIGHTS
};
ThingThingBall *balls = new ThingThingBall[5];
float atten[5] = {1, 1, 1, 1, 1};
// float atten[5] = {0.0, 0.25, 0.5, 0.75, 1};
ThingThing() {
config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);
configParam(BALL_RAD_PARAM, 0.0, 30.0, 10.0);
configParam(ZOOM_MULT_PARAM, 1.0, 200.0, 20.0);
balls[0].color = nvgRGB(255, 255, 255);//white
balls[1].color = nvgRGB(255, 151, 9);//orange
balls[2].color = nvgRGB(255, 243, 9);//yellow
balls[3].color = nvgRGB(144, 26, 252);//purple
balls[4].color = nvgRGB(25, 150, 252);//blue
}
~ThingThing() {
delete [] balls;
}
void process(const ProcessArgs &args) override {};
void onReset() override {}
json_t *dataToJson() override {
json_t *rootJ = json_object();
return rootJ;
}
void dataFromJson(json_t *rootJ) override {}
};
struct ThingThingDisplay : Widget {
ThingThing *module;
ThingThingDisplay(){}
void draw(const DrawArgs &args) override {
//background
nvgFillColor(args.vg, nvgRGB(20, 30, 33));
nvgBeginPath(args.vg);
nvgRect(args.vg, 0, 0, box.size.x, box.size.y);
nvgFill(args.vg);
if(module == NULL) return;
float ballRadius = module->params[ThingThing::BALL_RAD_PARAM].getValue();
if(module->inputs[ThingThing::BALL_RAD_INPUT].isConnected()){
ballRadius += rescalefjw(module->inputs[ThingThing::BALL_RAD_INPUT].getVoltage(), -5.0, 5.0, 0.0, 30.0);
}
float zoom = module->params[ThingThing::ZOOM_MULT_PARAM].getValue();
if(module->inputs[ThingThing::ZOOM_MULT_INPUT].isConnected()){
zoom += rescalefjw(module->inputs[ThingThing::ZOOM_MULT_INPUT].getVoltage(), -5.0, 5.0, 1.0, 50.0);
}
float x[5];
float y[5];
float angle[5];
for(int i=0; i<5; i++){
angle[i] = i==0 ? 0 : (module->inputs[ThingThing::ANG_INPUT+i].getVoltage() + angle[i-1]) * module->atten[i];
x[i] = i==0 ? 0 : sinf(rescalefjw(angle[i], -5, 5, -2*M_PI + M_PI/2.0f, 2*M_PI + M_PI/2.0f)) * zoom;
y[i] = i==0 ? 0 : cosf(rescalefjw(angle[i], -5, 5, -2*M_PI + M_PI/2.0f, 2*M_PI + M_PI/2.0f)) * zoom;
}
/////////////////////// LINES ///////////////////////
nvgSave(args.vg);
nvgTranslate(args.vg, box.size.x * 0.5, box.size.y * 0.5);
for(int i=0; i<5; i++){
nvgTranslate(args.vg, x[i], y[i]);
nvgStrokeColor(args.vg, nvgRGB(255, 255, 255));
if(i>0){
nvgStrokeWidth(args.vg, 1);
nvgBeginPath(args.vg);
nvgMoveTo(args.vg, 0, 0);
nvgLineTo(args.vg, -x[i], -y[i]);
nvgStroke(args.vg);
}
}
nvgRestore(args.vg);
/////////////////////// BALLS ///////////////////////
nvgSave(args.vg);
nvgTranslate(args.vg, box.size.x * 0.5, box.size.y * 0.5);
for(int i=0; i<5; i++){
nvgTranslate(args.vg, x[i], y[i]);
nvgStrokeColor(args.vg, module->balls[i].color);
nvgFillColor(args.vg, module->balls[i].color);
nvgStrokeWidth(args.vg, 2);
nvgBeginPath(args.vg);
nvgCircle(args.vg, 0, 0, ballRadius);
nvgFill(args.vg);
nvgStroke(args.vg);
}
nvgRestore(args.vg);
}
};
struct ThingThingWidget : ModuleWidget {
ThingThingWidget(ThingThing *module);
};
ThingThingWidget::ThingThingWidget(ThingThing *module) {
setModule(module);
box.size = Vec(RACK_GRID_WIDTH*20, RACK_GRID_HEIGHT);
SVGPanel *panel = new SVGPanel();
panel->box.size = box.size;
panel->setBackground(APP->window->loadSvg(asset::plugin(pluginInstance, "res/ThingThing.svg")));
addChild(panel);
ThingThingDisplay *display = new ThingThingDisplay();
display->module = module;
display->box.pos = Vec(0, 0);
display->box.size = Vec(box.size.x, RACK_GRID_HEIGHT);
addChild(display);
addChild(createWidget<Screw_J>(Vec(265, 365)));
addChild(createWidget<Screw_W>(Vec(280, 365)));
for(int i=0; i<4; i++){
addInput(createInput<TinyPJ301MPort>(Vec(5+(20*i), 360), module, ThingThing::ANG_INPUT+i+1));
}
addInput(createInput<TinyPJ301MPort>(Vec(140, 360), module, ThingThing::BALL_RAD_INPUT));
addParam(createParam<JwTinyKnob>(Vec(155, 360), module, ThingThing::BALL_RAD_PARAM));
addInput(createInput<TinyPJ301MPort>(Vec(190, 360), module, ThingThing::ZOOM_MULT_INPUT));
addParam(createParam<JwTinyKnob>(Vec(205, 360), module, ThingThing::ZOOM_MULT_PARAM));
}
Model *modelThingThing = createModel<ThingThing, ThingThingWidget>("ThingThing");
<|endoftext|> |
<commit_before>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <vector>
#include <iostream>
#include <exception>
#include <algorithm>
#include <iomanip>
#include <ctime>
#include <configuration.hpp>
#include <ArgumentList.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <Triad.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>
const inputDataType factor = 42;
void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * A, cl::Buffer * A_d, std::vector< inputDataType > * B, cl::Buffer * B_d, cl::Buffer * C_d);
int main(int argc, char * argv[]) {
bool reInit = true;
unsigned int nrIterations = 0;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
unsigned int vectorSize = 0;
unsigned int maxThreads = 0;
unsigned int maxItems = 0;
unsigned int inputSize = 0;
isa::OpenCL::KernelConf conf;
try {
isa::utils::ArgumentList args(argc, argv);
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
vectorSize = args.getSwitchArgument< unsigned int >("-vector");
maxThreads = args.getSwitchArgument< unsigned int >("-max_threads");
maxItems = args.getSwitchArgument< unsigned int >("-max_items");
inputSize = args.getSwitchArgument< unsigned int >("-input_size");
} catch ( isa::utils::EmptyCommandLine & err ) {
std::cerr << argv[0] << " -opencl_platform ... -opencl_device ... -iterations ... -vector ... -max_threads ... -max_items ... -input_size ... " << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
cl::Context clContext;
std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
std::vector< std::vector< cl::CommandQueue > > * clQueues = 0;
// Allocate host memory
std::vector< inputDataType > A(inputSize), B(inputSize), C(inputSize), C_control(inputSize);
cl::Buffer A_d, B_d, C_d;
srand(time(0));
for ( unsigned int item = 0; item < A.size(); item++ ) {
A[item] = rand() % factor;
B[item] = rand() % factor;
}
std::fill(C.begin(), C.end(), factor);
std::fill(C_control.begin(), C_control.end(), factor);
TuneBench::triad(A, B, C_control, factor);
std::cout << std::fixed << std::endl;
std::cout << "# inputSize nrThreadsD0 nrItemsD0 GB/s time stdDeviation COV" << std::endl << std::endl;
for ( unsigned int threads = vectorSize; threads <= maxThreads; threads += vectorSize ) {
conf.setNrThreadsD0(threads);
for ( unsigned int items = 1; items <= maxItems; items++ ) {
conf.setNrItemsD0(items);
if ( inputSize % (conf.getNrThreadsD0() * conf.getNrItemsD0()) != 0 ) {
continue;
}
// Generate kernel
double gbytes = isa::utils::giga(static_cast< uint64_t >(inputSize) * sizeof(inputDataType) * 3);
cl::Event clEvent;
cl::Kernel * kernel;
isa::utils::Timer timer;
std::string * code = TuneBench::getTriadOpenCL(conf, inputDataName, factor);
if ( reInit ) {
delete clQueues;
clQueues = new std::vector< std::vector< cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
try {
initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &A, &A_d, &B, &B_d, &C_d);
} catch ( cl::Error & err ) {
return -1;
}
reInit = false;
}
try {
kernel = isa::OpenCL::compile("triad", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError & err ) {
std::cerr << err.what() << std::endl;
delete code;
break;
}
delete code;
cl::NDRange global(inputSize / conf.getNrItemsD0());
cl::NDRange local(conf.getNrThreadsD0());
kernel->setArg(0, A_d);
kernel->setArg(1, B_d);
kernel->setArg(2, C_d);
try {
// Warm-up run
clQueues->at(clDeviceID)[0].finish();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);
clEvent.wait();
// Tuning runs
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
timer.start();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);
clEvent.wait();
timer.stop();
}
clQueues->at(clDeviceID)[0].enqueueReadBuffer(C_d, CL_TRUE, 0, C.size() * sizeof(inputDataType), reinterpret_cast< void * >(C.data()), 0, &clEvent);
clEvent.wait();
} catch ( cl::Error & err ) {
std::cerr << "OpenCL kernel execution error (";
std::cerr << conf.print();
std::cerr << "), (";
std::cerr << isa::utils::toString(inputSize / conf.getNrItemsD0()) << "): ";
std::cerr << isa::utils::toString(err.err()) << std::endl;
delete kernel;
if ( err.err() == -4 || err.err() == -61 ) {
return -1;
}
reInit = true;
break;
}
delete kernel;
bool error = false;
for ( unsigned int item = 0; item < C.size(); item++ ) {
if ( !isa::utils::same(C[item], C_control[item]) ) {
std::cerr << "Output error (" << conf.print() << ")." << std::endl;
error = true;
break;
}
}
if ( error ) {
continue;
}
std::cout << inputSize << " " << outputSize << " ";
std::cout << conf.print() << " ";
std::cout << std::setprecision(3);
std::cout << gbytes / timer.getAverageTime() << " ";
std::cout << std::setprecision(6);
std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl;
}
}
std::cout << std::endl;
return 0;
}
void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * A, cl::Buffer * A_d, std::vector< inputDataType > * B, cl::Buffer * B_d, cl::Buffer * C_d) {
try {
*A_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, A->size() * sizeof(inputDataType), 0, 0);
*B_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, B->size() * sizeof(inputDataType), 0, 0);
*C_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, A->size() * sizeof(inputDataType), 0, 0);
clQueue->enqueueWriteBuffer(*A_d, CL_FALSE, 0, A->size() * sizeof(inputDataType), reinterpret_cast< void * >(A->data()));
clQueue->enqueueWriteBuffer(*B_d, CL_FALSE, 0, B->size() * sizeof(inputDataType), reinterpret_cast< void * >(B->data()));
clQueue->finish();
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error (memory initialization): " << isa::utils::toString(err.err()) << "." << std::endl;
throw;
}
}
<commit_msg>Typo.<commit_after>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <vector>
#include <iostream>
#include <exception>
#include <algorithm>
#include <iomanip>
#include <ctime>
#include <configuration.hpp>
#include <ArgumentList.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <Triad.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>
const inputDataType factor = 42;
void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * A, cl::Buffer * A_d, std::vector< inputDataType > * B, cl::Buffer * B_d, cl::Buffer * C_d);
int main(int argc, char * argv[]) {
bool reInit = true;
unsigned int nrIterations = 0;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
unsigned int vectorSize = 0;
unsigned int maxThreads = 0;
unsigned int maxItems = 0;
unsigned int inputSize = 0;
isa::OpenCL::KernelConf conf;
try {
isa::utils::ArgumentList args(argc, argv);
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
vectorSize = args.getSwitchArgument< unsigned int >("-vector");
maxThreads = args.getSwitchArgument< unsigned int >("-max_threads");
maxItems = args.getSwitchArgument< unsigned int >("-max_items");
inputSize = args.getSwitchArgument< unsigned int >("-input_size");
} catch ( isa::utils::EmptyCommandLine & err ) {
std::cerr << argv[0] << " -opencl_platform ... -opencl_device ... -iterations ... -vector ... -max_threads ... -max_items ... -input_size ... " << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
cl::Context clContext;
std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
std::vector< std::vector< cl::CommandQueue > > * clQueues = 0;
// Allocate host memory
std::vector< inputDataType > A(inputSize), B(inputSize), C(inputSize), C_control(inputSize);
cl::Buffer A_d, B_d, C_d;
srand(time(0));
for ( unsigned int item = 0; item < A.size(); item++ ) {
A[item] = rand() % factor;
B[item] = rand() % factor;
}
std::fill(C.begin(), C.end(), factor);
std::fill(C_control.begin(), C_control.end(), factor);
TuneBench::triad(A, B, C_control, factor);
std::cout << std::fixed << std::endl;
std::cout << "# inputSize nrThreadsD0 nrItemsD0 GB/s time stdDeviation COV" << std::endl << std::endl;
for ( unsigned int threads = vectorSize; threads <= maxThreads; threads += vectorSize ) {
conf.setNrThreadsD0(threads);
for ( unsigned int items = 1; items <= maxItems; items++ ) {
conf.setNrItemsD0(items);
if ( inputSize % (conf.getNrThreadsD0() * conf.getNrItemsD0()) != 0 ) {
continue;
}
// Generate kernel
double gbytes = isa::utils::giga(static_cast< uint64_t >(inputSize) * sizeof(inputDataType) * 3);
cl::Event clEvent;
cl::Kernel * kernel;
isa::utils::Timer timer;
std::string * code = TuneBench::getTriadOpenCL(conf, inputDataName, factor);
if ( reInit ) {
delete clQueues;
clQueues = new std::vector< std::vector< cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
try {
initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &A, &A_d, &B, &B_d, &C_d);
} catch ( cl::Error & err ) {
return -1;
}
reInit = false;
}
try {
kernel = isa::OpenCL::compile("triad", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError & err ) {
std::cerr << err.what() << std::endl;
delete code;
break;
}
delete code;
cl::NDRange global(inputSize / conf.getNrItemsD0());
cl::NDRange local(conf.getNrThreadsD0());
kernel->setArg(0, A_d);
kernel->setArg(1, B_d);
kernel->setArg(2, C_d);
try {
// Warm-up run
clQueues->at(clDeviceID)[0].finish();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);
clEvent.wait();
// Tuning runs
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
timer.start();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);
clEvent.wait();
timer.stop();
}
clQueues->at(clDeviceID)[0].enqueueReadBuffer(C_d, CL_TRUE, 0, C.size() * sizeof(inputDataType), reinterpret_cast< void * >(C.data()), 0, &clEvent);
clEvent.wait();
} catch ( cl::Error & err ) {
std::cerr << "OpenCL kernel execution error (";
std::cerr << conf.print();
std::cerr << "), (";
std::cerr << isa::utils::toString(inputSize / conf.getNrItemsD0()) << "): ";
std::cerr << isa::utils::toString(err.err()) << std::endl;
delete kernel;
if ( err.err() == -4 || err.err() == -61 ) {
return -1;
}
reInit = true;
break;
}
delete kernel;
bool error = false;
for ( unsigned int item = 0; item < C.size(); item++ ) {
if ( !isa::utils::same(C[item], C_control[item]) ) {
std::cerr << "Output error (" << conf.print() << ")." << std::endl;
error = true;
break;
}
}
if ( error ) {
continue;
}
std::cout << inputSize << " ";
std::cout << conf.print() << " ";
std::cout << std::setprecision(3);
std::cout << gbytes / timer.getAverageTime() << " ";
std::cout << std::setprecision(6);
std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl;
}
}
std::cout << std::endl;
return 0;
}
void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * A, cl::Buffer * A_d, std::vector< inputDataType > * B, cl::Buffer * B_d, cl::Buffer * C_d) {
try {
*A_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, A->size() * sizeof(inputDataType), 0, 0);
*B_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, B->size() * sizeof(inputDataType), 0, 0);
*C_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, A->size() * sizeof(inputDataType), 0, 0);
clQueue->enqueueWriteBuffer(*A_d, CL_FALSE, 0, A->size() * sizeof(inputDataType), reinterpret_cast< void * >(A->data()));
clQueue->enqueueWriteBuffer(*B_d, CL_FALSE, 0, B->size() * sizeof(inputDataType), reinterpret_cast< void * >(B->data()));
clQueue->finish();
} catch ( cl::Error & err ) {
std::cerr << "OpenCL error (memory initialization): " << isa::utils::toString(err.err()) << "." << std::endl;
throw;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: appdata.hxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: kz $ $Date: 2008-03-06 19:57:12 $
*
* 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 _SFX_APPDATA_HXX
#define _SFX_APPDATA_HXX
#include <tools/link.hxx>
#include <tools/list.hxx>
#include <svtools/lstner.hxx>
#include <vcl/timer.hxx>
#include <tools/string.hxx>
#include "rtl/ref.hxx"
#include <com/sun/star/frame/XModel.hpp>
#include "bitset.hxx"
class SfxApplication;
class SvStrings;
class SfxProgress;
class SfxChildWinFactArr_Impl;
class SfxDdeDocTopics_Impl;
class DdeService;
class SfxEventConfiguration;
class SfxMacroConfig;
class SfxItemPool;
class SfxInitLinkList;
class SfxFilterMatcher;
class SvUShorts;
class ISfxTemplateCommon;
class SfxFilterMatcher;
class SfxCancelManager;
class SfxStatusDispatcher;
class SfxDdeTriggerTopic_Impl;
class SfxMiscCfg;
class SfxDocumentTemplates;
class SfxFrameArr_Impl;
class SvtSaveOptions;
class SvtUndoOptions;
class SvtHelpOptions;
class SfxObjectFactory;
class SfxObjectShell;
class ResMgr;
class Window;
class SfxTbxCtrlFactArr_Impl;
class SfxStbCtrlFactArr_Impl;
class SfxMenuCtrlFactArr_Impl;
class SfxViewFrameArr_Impl;
class SfxViewShellArr_Impl;
class SfxObjectShellArr_Impl;
class ResMgr;
class SimpleResMgr;
class SfxViewFrame;
class SfxSlotPool;
class SfxResourceManager;
class SfxDispatcher;
class SfxInterface;
class BasicManager;
class SfxBasicManagerHolder;
class SfxBasicManagerCreationListener;
namespace sfx2 { namespace appl { class ImeStatusWindow; } }
//=========================================================================
// SfxAppData_Impl
//=========================================================================
class SfxAppData_Impl
{
public:
IndexBitSet aIndexBitSet; // for counting noname documents
String aLastDir; // for IO dialog
// DDE stuff
DdeService* pDdeService;
SfxDdeDocTopics_Impl* pDocTopics;
SfxDdeTriggerTopic_Impl* pTriggerTopic;
DdeService* pDdeService2;
// single instance classes
SfxChildWinFactArr_Impl* pFactArr;
SfxFrameArr_Impl* pTopFrames;
// special members
SfxInitLinkList* pInitLinkList;
// application members
SfxFilterMatcher* pMatcher;
SfxCancelManager* pCancelMgr;
ResMgr* pLabelResMgr;
SfxStatusDispatcher* pAppDispatch;
SfxDocumentTemplates* pTemplates;
// global pointers
SfxItemPool* pPool;
SfxEventConfiguration* pEventConfig;
SvUShorts* pDisabledSlotList;
SvStrings* pSecureURLs;
SfxMiscCfg* pMiscConfig;
SvtSaveOptions* pSaveOptions;
SvtUndoOptions* pUndoOptions;
SvtHelpOptions* pHelpOptions;
// "current" functionality
SfxProgress* pProgress;
ISfxTemplateCommon* pTemplateCommon;
USHORT nDocModalMode; // counts documents in modal mode
USHORT nAutoTabPageId;
USHORT nBasicCallLevel;
USHORT nRescheduleLocks;
USHORT nInReschedule;
USHORT nAsynchronCalls;
rtl::Reference< sfx2::appl::ImeStatusWindow > m_xImeStatusWindow;
SfxTbxCtrlFactArr_Impl* pTbxCtrlFac;
SfxStbCtrlFactArr_Impl* pStbCtrlFac;
SfxMenuCtrlFactArr_Impl* pMenuCtrlFac;
SfxViewFrameArr_Impl* pViewFrames;
SfxViewShellArr_Impl* pViewShells;
SfxObjectShellArr_Impl* pObjShells;
ResMgr* pSfxResManager;
ResMgr* pOfaResMgr;
SimpleResMgr* pSimpleResManager;
SfxBasicManagerHolder* pBasicManager;
SfxBasicManagerCreationListener*
pBasMgrListener;
SfxViewFrame* pViewFrame;
SfxSlotPool* pSlotPool;
SfxResourceManager* pResMgr;
SfxDispatcher* pAppDispat; // Dispatcher falls kein Doc
SfxInterface** pInterfaces;
USHORT nDocNo; // Laufende Doc-Nummer (AutoName)
USHORT nInterfaces;
BOOL bDispatcherLocked:1; // nichts ausf"uhren
BOOL bDowning:1; // TRUE ab Exit und danach
BOOL bInQuit : 1;
BOOL bInvalidateOnUnlock : 1;
BOOL bODFVersionWarningLater : 1;
SfxAppData_Impl( SfxApplication* );
~SfxAppData_Impl();
void UpdateApplicationSettings( BOOL bDontHide );
SfxDocumentTemplates* GetDocumentTemplates();
void DeInitDDE();
/** called when the Application's BasicManager has been created. This can happen
explicitly in SfxApplication::GetBasicManager, or implicitly if a document's
BasicManager is created before the application's BasicManager exists.
*/
void OnApplicationBasicManagerCreated( BasicManager& _rManager );
};
#endif // #ifndef _SFX_APPDATA_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.18.28); FILE MERGED 2008/03/31 13:38:34 rt 1.18.28.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: appdata.hxx,v $
* $Revision: 1.19 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SFX_APPDATA_HXX
#define _SFX_APPDATA_HXX
#include <tools/link.hxx>
#include <tools/list.hxx>
#include <svtools/lstner.hxx>
#include <vcl/timer.hxx>
#include <tools/string.hxx>
#include "rtl/ref.hxx"
#include <com/sun/star/frame/XModel.hpp>
#include "bitset.hxx"
class SfxApplication;
class SvStrings;
class SfxProgress;
class SfxChildWinFactArr_Impl;
class SfxDdeDocTopics_Impl;
class DdeService;
class SfxEventConfiguration;
class SfxMacroConfig;
class SfxItemPool;
class SfxInitLinkList;
class SfxFilterMatcher;
class SvUShorts;
class ISfxTemplateCommon;
class SfxFilterMatcher;
class SfxCancelManager;
class SfxStatusDispatcher;
class SfxDdeTriggerTopic_Impl;
class SfxMiscCfg;
class SfxDocumentTemplates;
class SfxFrameArr_Impl;
class SvtSaveOptions;
class SvtUndoOptions;
class SvtHelpOptions;
class SfxObjectFactory;
class SfxObjectShell;
class ResMgr;
class Window;
class SfxTbxCtrlFactArr_Impl;
class SfxStbCtrlFactArr_Impl;
class SfxMenuCtrlFactArr_Impl;
class SfxViewFrameArr_Impl;
class SfxViewShellArr_Impl;
class SfxObjectShellArr_Impl;
class ResMgr;
class SimpleResMgr;
class SfxViewFrame;
class SfxSlotPool;
class SfxResourceManager;
class SfxDispatcher;
class SfxInterface;
class BasicManager;
class SfxBasicManagerHolder;
class SfxBasicManagerCreationListener;
namespace sfx2 { namespace appl { class ImeStatusWindow; } }
//=========================================================================
// SfxAppData_Impl
//=========================================================================
class SfxAppData_Impl
{
public:
IndexBitSet aIndexBitSet; // for counting noname documents
String aLastDir; // for IO dialog
// DDE stuff
DdeService* pDdeService;
SfxDdeDocTopics_Impl* pDocTopics;
SfxDdeTriggerTopic_Impl* pTriggerTopic;
DdeService* pDdeService2;
// single instance classes
SfxChildWinFactArr_Impl* pFactArr;
SfxFrameArr_Impl* pTopFrames;
// special members
SfxInitLinkList* pInitLinkList;
// application members
SfxFilterMatcher* pMatcher;
SfxCancelManager* pCancelMgr;
ResMgr* pLabelResMgr;
SfxStatusDispatcher* pAppDispatch;
SfxDocumentTemplates* pTemplates;
// global pointers
SfxItemPool* pPool;
SfxEventConfiguration* pEventConfig;
SvUShorts* pDisabledSlotList;
SvStrings* pSecureURLs;
SfxMiscCfg* pMiscConfig;
SvtSaveOptions* pSaveOptions;
SvtUndoOptions* pUndoOptions;
SvtHelpOptions* pHelpOptions;
// "current" functionality
SfxProgress* pProgress;
ISfxTemplateCommon* pTemplateCommon;
USHORT nDocModalMode; // counts documents in modal mode
USHORT nAutoTabPageId;
USHORT nBasicCallLevel;
USHORT nRescheduleLocks;
USHORT nInReschedule;
USHORT nAsynchronCalls;
rtl::Reference< sfx2::appl::ImeStatusWindow > m_xImeStatusWindow;
SfxTbxCtrlFactArr_Impl* pTbxCtrlFac;
SfxStbCtrlFactArr_Impl* pStbCtrlFac;
SfxMenuCtrlFactArr_Impl* pMenuCtrlFac;
SfxViewFrameArr_Impl* pViewFrames;
SfxViewShellArr_Impl* pViewShells;
SfxObjectShellArr_Impl* pObjShells;
ResMgr* pSfxResManager;
ResMgr* pOfaResMgr;
SimpleResMgr* pSimpleResManager;
SfxBasicManagerHolder* pBasicManager;
SfxBasicManagerCreationListener*
pBasMgrListener;
SfxViewFrame* pViewFrame;
SfxSlotPool* pSlotPool;
SfxResourceManager* pResMgr;
SfxDispatcher* pAppDispat; // Dispatcher falls kein Doc
SfxInterface** pInterfaces;
USHORT nDocNo; // Laufende Doc-Nummer (AutoName)
USHORT nInterfaces;
BOOL bDispatcherLocked:1; // nichts ausf"uhren
BOOL bDowning:1; // TRUE ab Exit und danach
BOOL bInQuit : 1;
BOOL bInvalidateOnUnlock : 1;
BOOL bODFVersionWarningLater : 1;
SfxAppData_Impl( SfxApplication* );
~SfxAppData_Impl();
void UpdateApplicationSettings( BOOL bDontHide );
SfxDocumentTemplates* GetDocumentTemplates();
void DeInitDDE();
/** called when the Application's BasicManager has been created. This can happen
explicitly in SfxApplication::GetBasicManager, or implicitly if a document's
BasicManager is created before the application's BasicManager exists.
*/
void OnApplicationBasicManagerCreated( BasicManager& _rManager );
};
#endif // #ifndef _SFX_APPDATA_HXX
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2014 The QXmpp developers
*
* Author:
* Jeremy Lainé
*
* Source:
* https://github.com/qxmpp-project/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include "QXmppStun.h"
#include "util.h"
class tst_QXmppIceConnection : public QObject
{
Q_OBJECT
private slots:
void testConnect();
};
void tst_QXmppIceConnection::testConnect()
{
const int component = 1024;
QXmppLogger logger;
logger.setLoggingType(QXmppLogger::StdoutLogging);
QXmppIceConnection clientL;
connect(&clientL, SIGNAL(logMessage(QXmppLogger::MessageType,QString)),
&logger, SLOT(log(QXmppLogger::MessageType,QString)));
clientL.setIceControlling(true);
clientL.addComponent(component);
clientL.bind(QXmppIceComponent::discoverAddresses());
QXmppIceConnection clientR;
connect(&clientR, SIGNAL(logMessage(QXmppLogger::MessageType,QString)),
&logger, SLOT(log(QXmppLogger::MessageType,QString)));
clientR.setIceControlling(false);
clientR.addComponent(component);
clientR.bind(QXmppIceComponent::discoverAddresses());
// exchange credentials
clientL.setRemoteUser(clientR.localUser());
clientL.setRemotePassword(clientR.localPassword());
clientR.setRemoteUser(clientL.localUser());
clientR.setRemotePassword(clientL.localPassword());
// exchange candidates
foreach (const QXmppJingleCandidate &candidate, clientR.localCandidates())
clientL.addRemoteCandidate(candidate);
foreach (const QXmppJingleCandidate &candidate, clientL.localCandidates())
clientR.addRemoteCandidate(candidate);
// start ICE
QEventLoop loop;
connect(&clientL, SIGNAL(connected()), &loop, SLOT(quit()));
connect(&clientR, SIGNAL(connected()), &loop, SLOT(quit()));
clientL.connectToHost();
clientR.connectToHost();
// check both clients are connected
loop.exec();
loop.exec();
QVERIFY(clientL.isConnected());
QVERIFY(clientR.isConnected());
}
QTEST_MAIN(tst_QXmppIceConnection)
#include "tst_qxmppiceconnection.moc"
<commit_msg>ICE: test server-reflexive candidate gathering<commit_after>/*
* Copyright (C) 2008-2014 The QXmpp developers
*
* Author:
* Jeremy Lainé
*
* Source:
* https://github.com/qxmpp-project/qxmpp
*
* This file is a part of QXmpp library.
*
* 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.
*
*/
#include <QHostInfo>
#include "QXmppStun.h"
#include "util.h"
class tst_QXmppIceConnection : public QObject
{
Q_OBJECT
private slots:
void testBind();
void testBindStun();
void testConnect();
};
void tst_QXmppIceConnection::testBind()
{
const int componentId = 1024;
QXmppLogger logger;
logger.setLoggingType(QXmppLogger::StdoutLogging);
QXmppIceConnection client;
connect(&client, SIGNAL(logMessage(QXmppLogger::MessageType,QString)),
&logger, SLOT(log(QXmppLogger::MessageType,QString)));
client.setIceControlling(true);
client.addComponent(componentId);
QXmppIceComponent *component = client.component(componentId);
QVERIFY(component);
client.bind(QXmppIceComponent::discoverAddresses());
QCOMPARE(client.localCandidates().size(), component->localCandidates().size());
QVERIFY(!client.localCandidates().isEmpty());
foreach (const QXmppJingleCandidate &c, client.localCandidates()) {
QCOMPARE(c.component(), componentId);
QCOMPARE(c.type(), QXmppJingleCandidate::HostType);
}
}
void tst_QXmppIceConnection::testBindStun()
{
const int componentId = 1024;
QXmppLogger logger;
logger.setLoggingType(QXmppLogger::StdoutLogging);
QHostInfo stunInfo = QHostInfo::fromName("stun.l.google.com");
QVERIFY(!stunInfo.addresses().isEmpty());
QXmppIceConnection client;
connect(&client, SIGNAL(logMessage(QXmppLogger::MessageType,QString)),
&logger, SLOT(log(QXmppLogger::MessageType,QString)));
client.setIceControlling(true);
client.setStunServer(stunInfo.addresses().first(), 19302);
client.addComponent(componentId);
QXmppIceComponent *component = client.component(componentId);
QVERIFY(component);
QEventLoop loop;
connect(&client, SIGNAL(localCandidatesChanged()),
&loop, SLOT(quit()));
client.bind(QXmppIceComponent::discoverAddresses());
loop.exec();
bool foundReflexive = false;
QCOMPARE(client.localCandidates().size(), component->localCandidates().size());
QVERIFY(!client.localCandidates().isEmpty());
foreach (const QXmppJingleCandidate &c, client.localCandidates()) {
QCOMPARE(c.component(), componentId);
if (c.type() == QXmppJingleCandidate::ServerReflexiveType)
foundReflexive = true;
else
QCOMPARE(c.type(), QXmppJingleCandidate::HostType);
}
QVERIFY(foundReflexive);
}
void tst_QXmppIceConnection::testConnect()
{
const int component = 1024;
QXmppLogger logger;
logger.setLoggingType(QXmppLogger::StdoutLogging);
QXmppIceConnection clientL;
connect(&clientL, SIGNAL(logMessage(QXmppLogger::MessageType,QString)),
&logger, SLOT(log(QXmppLogger::MessageType,QString)));
clientL.setIceControlling(true);
clientL.addComponent(component);
clientL.bind(QXmppIceComponent::discoverAddresses());
QXmppIceConnection clientR;
connect(&clientR, SIGNAL(logMessage(QXmppLogger::MessageType,QString)),
&logger, SLOT(log(QXmppLogger::MessageType,QString)));
clientR.setIceControlling(false);
clientR.addComponent(component);
clientR.bind(QXmppIceComponent::discoverAddresses());
// exchange credentials
clientL.setRemoteUser(clientR.localUser());
clientL.setRemotePassword(clientR.localPassword());
clientR.setRemoteUser(clientL.localUser());
clientR.setRemotePassword(clientL.localPassword());
// exchange candidates
foreach (const QXmppJingleCandidate &candidate, clientR.localCandidates())
clientL.addRemoteCandidate(candidate);
foreach (const QXmppJingleCandidate &candidate, clientL.localCandidates())
clientR.addRemoteCandidate(candidate);
// start ICE
QEventLoop loop;
connect(&clientL, SIGNAL(connected()), &loop, SLOT(quit()));
connect(&clientR, SIGNAL(connected()), &loop, SLOT(quit()));
clientL.connectToHost();
clientR.connectToHost();
// check both clients are connected
loop.exec();
loop.exec();
QVERIFY(clientL.isConnected());
QVERIFY(clientR.isConnected());
}
QTEST_MAIN(tst_QXmppIceConnection)
#include "tst_qxmppiceconnection.moc"
<|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/browser/chromeos/setting_level_bubble.h"
#include <algorithm>
#include <gdk/gdk.h>
#include "chrome/browser/chromeos/login/background_view.h"
#include "chrome/browser/chromeos/login/login_utils.h"
#include "chrome/browser/chromeos/login/webui_login_display.h"
#include "chrome/browser/chromeos/setting_level_bubble_view.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/bubble/bubble.h"
#include "ui/gfx/screen.h"
#include "views/widget/root_view.h"
using base::TimeDelta;
using base::TimeTicks;
using std::max;
using std::min;
namespace {
// How long should the bubble be shown onscreen whenever the setting changes?
const int kBubbleShowTimeoutMs = 1000;
// How long should the level initially take to move up or down when it changes?
// (The rate adapts to handle keyboard autorepeat.)
const int64 kInitialAnimationDurationMs = 200;
// Horizontal position of the center of the bubble on the screen: 0 is left
// edge, 0.5 is center, 1 is right edge.
const double kBubbleXRatio = 0.5;
// Vertical gap from the bottom of the screen in pixels.
const int kBubbleBottomGap = 30;
// Duration between animation frames.
// Chosen to match ui::SlideAnimation's kDefaultFramerateHz.
const int kAnimationIntervalMs = 1000 / 50;
double LimitPercent(double percent) {
return min(max(percent, 0.0), 100.0);
}
} // namespace
namespace chromeos {
// Temporary helper routine. Tries to first return the widget from the
// most-recently-focused normal browser window, then from a login
// background, and finally NULL if both of those fail.
// TODO(glotov): remove this in favor of enabling Bubble class act
// without |parent| specified. crosbug.com/4025
static views::Widget* GetToplevelWidget() {
GtkWindow* window = NULL;
// We just use the default profile here -- this gets overridden as needed
// in Chrome OS depending on whether the user is logged in or not.
Browser* browser =
BrowserList::FindTabbedBrowser(
ProfileManager::GetDefaultProfile(),
true); // match_incognito
if (browser) {
window = GTK_WINDOW(browser->window()->GetNativeHandle());
} else {
// Otherwise, see if there's a background window that we can use.
BackgroundView* background = LoginUtils::Get()->GetBackgroundView();
if (background)
window = GTK_WINDOW(background->GetNativeWindow());
}
if (window)
return views::Widget::GetWidgetForNativeWindow(window);
else
return WebUILoginDisplay::GetLoginWindow();
}
SettingLevelBubble::SettingLevelBubble(SkBitmap* increase_icon,
SkBitmap* decrease_icon,
SkBitmap* disabled_icon)
: current_percent_(-1.0),
target_percent_(-1.0),
increase_icon_(increase_icon),
decrease_icon_(decrease_icon),
disabled_icon_(disabled_icon),
bubble_(NULL),
view_(NULL),
is_animating_(false) {
}
SettingLevelBubble::~SettingLevelBubble() {}
void SettingLevelBubble::ShowBubble(double percent, bool enabled) {
const double old_target_percent = target_percent_;
UpdateTargetPercent(percent);
SkBitmap* icon = increase_icon_;
if (!enabled || target_percent_ == 0)
icon = disabled_icon_;
else if (old_target_percent >= 0 && target_percent_ < old_target_percent)
icon = decrease_icon_;
if (!bubble_) {
views::Widget* parent_widget = GetToplevelWidget();
if (parent_widget == NULL) {
LOG(WARNING) << "Unable to locate parent widget to display a bubble";
return;
}
DCHECK(view_ == NULL);
view_ = new SettingLevelBubbleView;
view_->Init(icon, current_percent_, enabled);
// Calculate the position in screen coordinates that the bubble should
// "point" at (since we use BubbleBorder::FLOAT, this position actually
// specifies the center of the bubble).
const gfx::Rect monitor_area =
gfx::Screen::GetMonitorAreaNearestWindow(
GTK_WIDGET(parent_widget->GetNativeWindow()));
const gfx::Size view_size = view_->GetPreferredSize();
const gfx::Rect position_relative_to(
monitor_area.x() + kBubbleXRatio * monitor_area.width(),
monitor_area.bottom() - view_size.height() / 2 - kBubbleBottomGap,
0, 0);
bubble_ = Bubble::ShowFocusless(parent_widget,
position_relative_to,
BubbleBorder::FLOAT,
view_, // contents
this, // delegate
true); // show while screen is locked
// TODO(derat): We probably shouldn't be using Bubble. It'd be nice to call
// bubble_->set_fade_away_on_close(true) here, but then, if ShowBubble()
// gets called while the bubble is fading away, we end up just adjusting the
// value on the disappearing bubble; ideally we'd have a way to cancel the
// fade and show the bubble at full opacity for another
// kBubbleShowTimeoutMs.
} else {
DCHECK(view_);
hide_timer_.Stop();
view_->SetIcon(icon);
view_->SetEnabled(enabled);
}
hide_timer_.Start(base::TimeDelta::FromMilliseconds(kBubbleShowTimeoutMs),
this, &SettingLevelBubble::OnHideTimeout);
}
void SettingLevelBubble::HideBubble() {
if (bubble_)
bubble_->Close();
}
void SettingLevelBubble::UpdateWithoutShowingBubble(double percent,
bool enabled) {
UpdateTargetPercent(percent);
if (view_)
view_->SetEnabled(enabled);
}
void SettingLevelBubble::OnHideTimeout() {
HideBubble();
}
void SettingLevelBubble::OnAnimationTimeout() {
const TimeTicks now = TimeTicks::Now();
const int64 remaining_ms = (target_time_ - now).InMilliseconds();
if (remaining_ms <= 0) {
current_percent_ = target_percent_;
StopAnimation();
} else {
// Figure out what fraction of the total time until we want to reach the
// target has elapsed since the last update.
const double remaining_percent = target_percent_ - current_percent_;
const int64 elapsed_ms =
(now - last_animation_update_time_).InMilliseconds();
current_percent_ +=
remaining_percent *
(static_cast<double>(elapsed_ms) / (elapsed_ms + remaining_ms));
}
last_animation_update_time_ = now;
if (view_)
view_->SetLevel(current_percent_);
}
void SettingLevelBubble::BubbleClosing(Bubble* bubble, bool) {
DCHECK(bubble == bubble_);
hide_timer_.Stop();
StopAnimation();
bubble_ = NULL;
view_ = NULL;
current_percent_ = -1.0;
target_percent_ = -1.0;
target_time_ = TimeTicks();
last_animation_update_time_ = TimeTicks();
last_target_update_time_ = TimeTicks();
}
bool SettingLevelBubble::CloseOnEscape() {
return true;
}
bool SettingLevelBubble::FadeInOnShow() {
return false;
}
void SettingLevelBubble::UpdateTargetPercent(double percent) {
target_percent_ = LimitPercent(percent);
const TimeTicks now = TimeTicks::Now();
if (current_percent_ < 0.0) {
// If we're setting the level for the first time, no need to animate.
current_percent_ = target_percent_;
if (view_)
view_->SetLevel(current_percent_);
} else {
// Use the time since the last request as a hint for the duration of the
// animation. This makes us automatically adapt to the repeat rate if a key
// is being held down to change a setting (which prevents us from lagging
// behind when the key is finally released).
int64 duration_ms = kInitialAnimationDurationMs;
if (!last_target_update_time_.is_null())
duration_ms = min(kInitialAnimationDurationMs,
(now - last_target_update_time_).InMilliseconds());
target_time_ = now + TimeDelta::FromMilliseconds(duration_ms);
if (!is_animating_) {
animation_timer_.Start(TimeDelta::FromMilliseconds(kAnimationIntervalMs),
this,
&SettingLevelBubble::OnAnimationTimeout);
is_animating_ = true;
last_animation_update_time_ = now;
}
}
last_target_update_time_ = now;
}
void SettingLevelBubble::StopAnimation() {
animation_timer_.Stop();
is_animating_ = false;
}
} // namespace chromeos
<commit_msg>chromeos: Animate volume/brightness when re-showing bubbles.<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/browser/chromeos/setting_level_bubble.h"
#include <algorithm>
#include <gdk/gdk.h>
#include "chrome/browser/chromeos/login/background_view.h"
#include "chrome/browser/chromeos/login/login_utils.h"
#include "chrome/browser/chromeos/login/webui_login_display.h"
#include "chrome/browser/chromeos/setting_level_bubble_view.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/bubble/bubble.h"
#include "ui/gfx/screen.h"
#include "views/widget/root_view.h"
using base::TimeDelta;
using base::TimeTicks;
using std::max;
using std::min;
namespace {
// How long should the bubble be shown onscreen whenever the setting changes?
const int kBubbleShowTimeoutMs = 1000;
// How long should the level initially take to move up or down when it changes?
// (The rate adapts to handle keyboard autorepeat.)
const int64 kInitialAnimationDurationMs = 200;
// Horizontal position of the center of the bubble on the screen: 0 is left
// edge, 0.5 is center, 1 is right edge.
const double kBubbleXRatio = 0.5;
// Vertical gap from the bottom of the screen in pixels.
const int kBubbleBottomGap = 30;
// Duration between animation frames.
// Chosen to match ui::SlideAnimation's kDefaultFramerateHz.
const int kAnimationIntervalMs = 1000 / 50;
double LimitPercent(double percent) {
return min(max(percent, 0.0), 100.0);
}
} // namespace
namespace chromeos {
// Temporary helper routine. Tries to first return the widget from the
// most-recently-focused normal browser window, then from a login
// background, and finally NULL if both of those fail.
// TODO(glotov): remove this in favor of enabling Bubble class act
// without |parent| specified. crosbug.com/4025
static views::Widget* GetToplevelWidget() {
GtkWindow* window = NULL;
// We just use the default profile here -- this gets overridden as needed
// in Chrome OS depending on whether the user is logged in or not.
Browser* browser =
BrowserList::FindTabbedBrowser(
ProfileManager::GetDefaultProfile(),
true); // match_incognito
if (browser) {
window = GTK_WINDOW(browser->window()->GetNativeHandle());
} else {
// Otherwise, see if there's a background window that we can use.
BackgroundView* background = LoginUtils::Get()->GetBackgroundView();
if (background)
window = GTK_WINDOW(background->GetNativeWindow());
}
if (window)
return views::Widget::GetWidgetForNativeWindow(window);
else
return WebUILoginDisplay::GetLoginWindow();
}
SettingLevelBubble::SettingLevelBubble(SkBitmap* increase_icon,
SkBitmap* decrease_icon,
SkBitmap* disabled_icon)
: current_percent_(-1.0),
target_percent_(-1.0),
increase_icon_(increase_icon),
decrease_icon_(decrease_icon),
disabled_icon_(disabled_icon),
bubble_(NULL),
view_(NULL),
is_animating_(false) {
}
SettingLevelBubble::~SettingLevelBubble() {}
void SettingLevelBubble::ShowBubble(double percent, bool enabled) {
const double old_target_percent = target_percent_;
UpdateTargetPercent(percent);
SkBitmap* icon = increase_icon_;
if (!enabled || target_percent_ == 0)
icon = disabled_icon_;
else if (old_target_percent >= 0 && target_percent_ < old_target_percent)
icon = decrease_icon_;
if (!bubble_) {
views::Widget* parent_widget = GetToplevelWidget();
if (parent_widget == NULL) {
LOG(WARNING) << "Unable to locate parent widget to display a bubble";
return;
}
DCHECK(view_ == NULL);
view_ = new SettingLevelBubbleView;
view_->Init(icon, current_percent_, enabled);
// Calculate the position in screen coordinates that the bubble should
// "point" at (since we use BubbleBorder::FLOAT, this position actually
// specifies the center of the bubble).
const gfx::Rect monitor_area =
gfx::Screen::GetMonitorAreaNearestWindow(
GTK_WIDGET(parent_widget->GetNativeWindow()));
const gfx::Size view_size = view_->GetPreferredSize();
const gfx::Rect position_relative_to(
monitor_area.x() + kBubbleXRatio * monitor_area.width(),
monitor_area.bottom() - view_size.height() / 2 - kBubbleBottomGap,
0, 0);
bubble_ = Bubble::ShowFocusless(parent_widget,
position_relative_to,
BubbleBorder::FLOAT,
view_, // contents
this, // delegate
true); // show while screen is locked
// TODO(derat): We probably shouldn't be using Bubble. It'd be nice to call
// bubble_->set_fade_away_on_close(true) here, but then, if ShowBubble()
// gets called while the bubble is fading away, we end up just adjusting the
// value on the disappearing bubble; ideally we'd have a way to cancel the
// fade and show the bubble at full opacity for another
// kBubbleShowTimeoutMs.
} else {
DCHECK(view_);
hide_timer_.Stop();
view_->SetIcon(icon);
view_->SetEnabled(enabled);
}
hide_timer_.Start(base::TimeDelta::FromMilliseconds(kBubbleShowTimeoutMs),
this, &SettingLevelBubble::OnHideTimeout);
}
void SettingLevelBubble::HideBubble() {
if (bubble_)
bubble_->Close();
}
void SettingLevelBubble::UpdateWithoutShowingBubble(double percent,
bool enabled) {
UpdateTargetPercent(percent);
if (view_)
view_->SetEnabled(enabled);
}
void SettingLevelBubble::OnHideTimeout() {
HideBubble();
}
void SettingLevelBubble::OnAnimationTimeout() {
const TimeTicks now = TimeTicks::Now();
const int64 remaining_ms = (target_time_ - now).InMilliseconds();
if (remaining_ms <= 0) {
current_percent_ = target_percent_;
StopAnimation();
} else {
// Figure out what fraction of the total time until we want to reach the
// target has elapsed since the last update.
const double remaining_percent = target_percent_ - current_percent_;
const int64 elapsed_ms =
(now - last_animation_update_time_).InMilliseconds();
current_percent_ +=
remaining_percent *
(static_cast<double>(elapsed_ms) / (elapsed_ms + remaining_ms));
}
last_animation_update_time_ = now;
if (view_)
view_->SetLevel(current_percent_);
}
void SettingLevelBubble::BubbleClosing(Bubble* bubble, bool) {
DCHECK(bubble == bubble_);
hide_timer_.Stop();
StopAnimation();
bubble_ = NULL;
view_ = NULL;
current_percent_ = target_percent_;
target_time_ = TimeTicks();
last_animation_update_time_ = TimeTicks();
last_target_update_time_ = TimeTicks();
}
bool SettingLevelBubble::CloseOnEscape() {
return true;
}
bool SettingLevelBubble::FadeInOnShow() {
return false;
}
void SettingLevelBubble::UpdateTargetPercent(double percent) {
target_percent_ = LimitPercent(percent);
const TimeTicks now = TimeTicks::Now();
if (current_percent_ < 0.0) {
// If we're setting the level for the first time, no need to animate.
current_percent_ = target_percent_;
if (view_)
view_->SetLevel(current_percent_);
} else {
// Use the time since the last request as a hint for the duration of the
// animation. This makes us automatically adapt to the repeat rate if a key
// is being held down to change a setting (which prevents us from lagging
// behind when the key is finally released).
int64 duration_ms = kInitialAnimationDurationMs;
if (!last_target_update_time_.is_null())
duration_ms = min(kInitialAnimationDurationMs,
(now - last_target_update_time_).InMilliseconds());
target_time_ = now + TimeDelta::FromMilliseconds(duration_ms);
if (!is_animating_) {
animation_timer_.Start(TimeDelta::FromMilliseconds(kAnimationIntervalMs),
this,
&SettingLevelBubble::OnAnimationTimeout);
is_animating_ = true;
last_animation_update_time_ = now;
}
}
last_target_update_time_ = now;
}
void SettingLevelBubble::StopAnimation() {
animation_timer_.Stop();
is_animating_ = false;
}
} // namespace chromeos
<|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/browser/chromeos/setting_level_bubble.h"
#include <gdk/gdk.h>
#include "base/timer.h"
#include "chrome/browser/chromeos/login/background_view.h"
#include "chrome/browser/chromeos/login/login_utils.h"
#include "chrome/browser/chromeos/setting_level_bubble_view.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/bubble/bubble.h"
#include "views/widget/root_view.h"
namespace {
const int kBubbleShowTimeoutSec = 2;
const int kAnimationDurationMs = 200;
// Horizontal relative position: 0 - leftmost, 0.5 - center, 1 - rightmost.
const double kBubbleXRatio = 0.5;
// Vertical gap from the bottom of the screen in pixels.
const int kBubbleBottomGap = 30;
int LimitPercent(int percent) {
if (percent < 0)
percent = 0;
else if (percent > 100)
percent = 100;
return percent;
}
} // namespace
namespace chromeos {
// Temporary helper routine. Tries to first return the widget from the
// most-recently-focused normal browser window, then from a login
// background, and finally NULL if both of those fail.
// TODO(glotov): remove this in favor of enabling Bubble class act
// without |parent| specified. crosbug.com/4025
static views::Widget* GetToplevelWidget() {
GtkWindow* window = NULL;
// We just use the default profile here -- this gets overridden as needed
// in Chrome OS depending on whether the user is logged in or not.
Browser* browser =
BrowserList::FindTabbedBrowser(
ProfileManager::GetDefaultProfile(),
true); // match_incognito
if (browser) {
window = GTK_WINDOW(browser->window()->GetNativeHandle());
} else {
// Otherwise, see if there's a background window that we can use.
BackgroundView* background = LoginUtils::Get()->GetBackgroundView();
if (background)
window = GTK_WINDOW(background->GetNativeWindow());
}
if (!window)
return NULL;
return views::Widget::GetWidgetForNativeWindow(window);
}
SettingLevelBubble::SettingLevelBubble(SkBitmap* increase_icon,
SkBitmap* decrease_icon,
SkBitmap* zero_icon)
: previous_percent_(-1),
current_percent_(-1),
increase_icon_(increase_icon),
decrease_icon_(decrease_icon),
zero_icon_(zero_icon),
bubble_(NULL),
view_(NULL),
animation_(this) {
animation_.SetSlideDuration(kAnimationDurationMs);
animation_.SetTweenType(ui::Tween::LINEAR);
}
SettingLevelBubble::~SettingLevelBubble() {}
void SettingLevelBubble::ShowBubble(int percent) {
percent = LimitPercent(percent);
if (previous_percent_ == -1)
previous_percent_ = percent;
current_percent_ = percent;
SkBitmap* icon = increase_icon_;
if (current_percent_ == 0)
icon = zero_icon_;
else if (current_percent_ < previous_percent_)
icon = decrease_icon_;
if (!bubble_) {
views::Widget* widget = GetToplevelWidget();
if (widget == NULL)
return;
DCHECK(view_ == NULL);
view_ = new SettingLevelBubbleView;
view_->Init(icon, previous_percent_);
// Calculate position of the bubble.
gfx::Rect bounds = widget->GetClientAreaScreenBounds();
const gfx::Size view_size = view_->GetPreferredSize();
// Note that (x, y) is the point of the center of the bubble.
const int x = view_size.width() / 2 +
kBubbleXRatio * (bounds.width() - view_size.width());
const int y = bounds.height() - view_size.height() / 2 - kBubbleBottomGap;
// ShowFocusless doesn't set ESC accelerator.
bubble_ = Bubble::ShowFocusless(widget, // parent
gfx::Rect(x, y, 0, 20),
BubbleBorder::FLOAT,
view_, // contents
this, // delegate
true); // show while screen is locked
} else {
DCHECK(view_);
timeout_timer_.Stop();
view_->SetIcon(icon);
}
if (animation_.is_animating())
animation_.End();
animation_.Reset();
animation_.Show();
timeout_timer_.Start(base::TimeDelta::FromSeconds(kBubbleShowTimeoutSec),
this, &SettingLevelBubble::OnTimeout);
}
void SettingLevelBubble::HideBubble() {
if (bubble_)
bubble_->Close();
}
void SettingLevelBubble::UpdateWithoutShowingBubble(int percent) {
percent = LimitPercent(percent);
previous_percent_ =
animation_.is_animating() ?
animation_.GetCurrentValue() :
current_percent_;
if (previous_percent_ < 0)
previous_percent_ = percent;
current_percent_ = percent;
if (animation_.is_animating())
animation_.End();
animation_.Reset();
animation_.Show();
}
void SettingLevelBubble::OnTimeout() {
HideBubble();
}
void SettingLevelBubble::BubbleClosing(Bubble* bubble, bool) {
DCHECK(bubble == bubble_);
timeout_timer_.Stop();
animation_.Stop();
bubble_ = NULL;
view_ = NULL;
}
bool SettingLevelBubble::CloseOnEscape() {
return true;
}
bool SettingLevelBubble::FadeInOnShow() {
return false;
}
void SettingLevelBubble::AnimationEnded(const ui::Animation* animation) {
previous_percent_ = current_percent_;
}
void SettingLevelBubble::AnimationProgressed(const ui::Animation* animation) {
if (view_) {
view_->Update(
ui::Tween::ValueBetween(animation->GetCurrentValue(),
previous_percent_,
current_percent_));
}
}
} // namespace chromeos
<commit_msg>wm: Center setting level bubbles onscreen.<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/browser/chromeos/setting_level_bubble.h"
#include <gdk/gdk.h>
#include "base/timer.h"
#include "chrome/browser/chromeos/login/background_view.h"
#include "chrome/browser/chromeos/login/login_utils.h"
#include "chrome/browser/chromeos/setting_level_bubble_view.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/bubble/bubble.h"
#include "views/screen.h"
#include "views/widget/root_view.h"
namespace {
const int kBubbleShowTimeoutSec = 2;
const int kAnimationDurationMs = 200;
// Horizontal position of the center of the bubble on the screen: 0 is left
// edge, 0.5 is center, 1 is right edge.
const double kBubbleXRatio = 0.5;
// Vertical gap from the bottom of the screen in pixels.
const int kBubbleBottomGap = 30;
int LimitPercent(int percent) {
if (percent < 0)
percent = 0;
else if (percent > 100)
percent = 100;
return percent;
}
} // namespace
namespace chromeos {
// Temporary helper routine. Tries to first return the widget from the
// most-recently-focused normal browser window, then from a login
// background, and finally NULL if both of those fail.
// TODO(glotov): remove this in favor of enabling Bubble class act
// without |parent| specified. crosbug.com/4025
static views::Widget* GetToplevelWidget() {
GtkWindow* window = NULL;
// We just use the default profile here -- this gets overridden as needed
// in Chrome OS depending on whether the user is logged in or not.
Browser* browser =
BrowserList::FindTabbedBrowser(
ProfileManager::GetDefaultProfile(),
true); // match_incognito
if (browser) {
window = GTK_WINDOW(browser->window()->GetNativeHandle());
} else {
// Otherwise, see if there's a background window that we can use.
BackgroundView* background = LoginUtils::Get()->GetBackgroundView();
if (background)
window = GTK_WINDOW(background->GetNativeWindow());
}
if (!window)
return NULL;
return views::Widget::GetWidgetForNativeWindow(window);
}
SettingLevelBubble::SettingLevelBubble(SkBitmap* increase_icon,
SkBitmap* decrease_icon,
SkBitmap* zero_icon)
: previous_percent_(-1),
current_percent_(-1),
increase_icon_(increase_icon),
decrease_icon_(decrease_icon),
zero_icon_(zero_icon),
bubble_(NULL),
view_(NULL),
animation_(this) {
animation_.SetSlideDuration(kAnimationDurationMs);
animation_.SetTweenType(ui::Tween::LINEAR);
}
SettingLevelBubble::~SettingLevelBubble() {}
void SettingLevelBubble::ShowBubble(int percent) {
percent = LimitPercent(percent);
if (previous_percent_ == -1)
previous_percent_ = percent;
current_percent_ = percent;
SkBitmap* icon = increase_icon_;
if (current_percent_ == 0)
icon = zero_icon_;
else if (current_percent_ < previous_percent_)
icon = decrease_icon_;
if (!bubble_) {
views::Widget* parent_widget = GetToplevelWidget();
if (parent_widget == NULL)
return;
DCHECK(view_ == NULL);
view_ = new SettingLevelBubbleView;
view_->Init(icon, previous_percent_);
// Calculate the position in screen coordinates that the bubble should
// "point" at (since we use BubbleBorder::FLOAT, this position actually
// specifies the center of the bubble).
const gfx::Rect monitor_area =
views::Screen::GetMonitorAreaNearestWindow(
GTK_WIDGET(parent_widget->GetNativeWindow()));
const gfx::Size view_size = view_->GetPreferredSize();
const gfx::Rect position_relative_to(
monitor_area.x() + kBubbleXRatio * monitor_area.width(),
monitor_area.bottom() - view_size.height() / 2 - kBubbleBottomGap,
0, 0);
// ShowFocusless doesn't set ESC accelerator.
bubble_ = Bubble::ShowFocusless(parent_widget,
position_relative_to,
BubbleBorder::FLOAT,
view_, // contents
this, // delegate
true); // show while screen is locked
} else {
DCHECK(view_);
timeout_timer_.Stop();
view_->SetIcon(icon);
}
if (animation_.is_animating())
animation_.End();
animation_.Reset();
animation_.Show();
timeout_timer_.Start(base::TimeDelta::FromSeconds(kBubbleShowTimeoutSec),
this, &SettingLevelBubble::OnTimeout);
}
void SettingLevelBubble::HideBubble() {
if (bubble_)
bubble_->Close();
}
void SettingLevelBubble::UpdateWithoutShowingBubble(int percent) {
percent = LimitPercent(percent);
previous_percent_ =
animation_.is_animating() ?
animation_.GetCurrentValue() :
current_percent_;
if (previous_percent_ < 0)
previous_percent_ = percent;
current_percent_ = percent;
if (animation_.is_animating())
animation_.End();
animation_.Reset();
animation_.Show();
}
void SettingLevelBubble::OnTimeout() {
HideBubble();
}
void SettingLevelBubble::BubbleClosing(Bubble* bubble, bool) {
DCHECK(bubble == bubble_);
timeout_timer_.Stop();
animation_.Stop();
bubble_ = NULL;
view_ = NULL;
}
bool SettingLevelBubble::CloseOnEscape() {
return true;
}
bool SettingLevelBubble::FadeInOnShow() {
return false;
}
void SettingLevelBubble::AnimationEnded(const ui::Animation* animation) {
previous_percent_ = current_percent_;
}
void SettingLevelBubble::AnimationProgressed(const ui::Animation* animation) {
if (view_) {
view_->Update(
ui::Tween::ValueBetween(animation->GetCurrentValue(),
previous_percent_,
current_percent_));
}
}
} // namespace chromeos
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgSim/LightPointNode>
#include <osgSim/LightPointSystem>
#include "LightPointDrawable.h"
#include "LightPointSpriteDrawable.h"
#include <osg/Timer>
#include <osg/BoundingBox>
#include <osg/BlendFunc>
#include <osg/Material>
#include <osg/PointSprite>
#include <osgUtil/CullVisitor>
#include <typeinfo>
namespace osgSim
{
osg::StateSet* getSingletonLightPointSystemSet()
{
static osg::ref_ptr<osg::StateSet> s_stateset = 0;
if (!s_stateset)
{
s_stateset = new osg::StateSet;
// force light point nodes to be drawn after everything else by picking a renderin bin number after
// the transparent bin.
s_stateset->setRenderBinDetails(20,"DepthSortedBin");
}
return s_stateset.get();
}
LightPointNode::LightPointNode():
_minPixelSize(0.0f),
_maxPixelSize(30.0f),
_maxVisibleDistance2(FLT_MAX),
_lightSystem(0),
_pointSprites(false)
{
setStateSet(getSingletonLightPointSystemSet());
}
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
LightPointNode::LightPointNode(const LightPointNode& lpn,const osg::CopyOp& copyop):
osg::Node(lpn,copyop),
_lightPointList(lpn._lightPointList),
_minPixelSize(lpn._minPixelSize),
_maxPixelSize(lpn._maxPixelSize),
_maxVisibleDistance2(lpn._maxVisibleDistance2),
_lightSystem(lpn._lightSystem),
_pointSprites(lpn._pointSprites)
{
}
unsigned int LightPointNode::addLightPoint(const LightPoint& lp)
{
unsigned int num = _lightPointList.size();
_lightPointList.push_back(lp);
dirtyBound();
return num;
}
void LightPointNode::removeLightPoint(unsigned int pos)
{
if (pos<_lightPointList.size())
{
_lightPointList.erase(_lightPointList.begin()+pos);
dirtyBound();
}
dirtyBound();
}
osg::BoundingSphere LightPointNode::computeBound() const
{
osg::BoundingSphere bsphere;
bsphere.init();
_bbox.init();
if (_lightPointList.empty())
{
return bsphere;
}
LightPointList::const_iterator itr;
for(itr=_lightPointList.begin();
itr!=_lightPointList.end();
++itr)
{
_bbox.expandBy(itr->_position);
}
bsphere.set(_bbox.center(),0.0f);
for(itr=_lightPointList.begin();
itr!=_lightPointList.end();
++itr)
{
osg::Vec3 dv(itr->_position-bsphere.center());
float radius = dv.length()+itr->_radius;
if (bsphere.radius()<radius) bsphere.radius()=radius;
}
bsphere.radius()+=1.0f;
return bsphere;
}
void LightPointNode::traverse(osg::NodeVisitor& nv)
{
if (_lightPointList.empty())
{
// no light points so no op.
return;
}
//#define USE_TIMER
#ifdef USE_TIMER
osg::Timer timer;
osg::Timer_t t1=0,t2=0,t3=0,t4=0,t5=0,t6=0,t7=0,t8=0;
#endif
#ifdef USE_TIMER
t1 = timer.tick();
#endif
osgUtil::CullVisitor* cv = NULL;
if (typeid(nv)==typeid(osgUtil::CullVisitor))
{
cv = static_cast<osgUtil::CullVisitor*>(&nv);
}
#ifdef USE_TIMER
t2 = timer.tick();
#endif
// should we disabled small feature culling here?
if (cv /*&& !cv->isCulled(_bbox)*/)
{
osg::Matrix matrix = *(cv->getModelViewMatrix());
osg::RefMatrix& projection = *(cv->getProjectionMatrix());
osgUtil::StateGraph* rg = cv->getCurrentStateGraph();
if (rg->leaves_empty())
{
// this is first leaf to be added to StateGraph
// and therefore should not already know to current render bin,
// so need to add it.
cv->getCurrentRenderBin()->addStateGraph(rg);
}
#ifdef USE_TIMER
t3 = timer.tick();
#endif
LightPointDrawable* drawable = NULL;
osg::Referenced* object = rg->getUserData();
if (object)
{
if (typeid(*object)==typeid(LightPointDrawable))
{
// resuse the user data attached to the render graph.
drawable = static_cast<LightPointDrawable*>(object);
}
else if (typeid(*object)==typeid(LightPointSpriteDrawable))
{
drawable = static_cast<LightPointSpriteDrawable*>(object);
}
else
{
// will need to replace UserData.
osg::notify(osg::WARN) << "Warning: Replacing osgUtil::StateGraph::_userData to support osgSim::LightPointNode, may have undefined results."<<std::endl;
}
}
if (!drawable)
{
drawable = _pointSprites ? new LightPointSpriteDrawable : new LightPointDrawable;
rg->setUserData(drawable);
if (cv->getFrameStamp())
{
drawable->setSimulationTime(cv->getFrameStamp()->getSimulationTime());
}
}
// search for a drawable in the RenderLead list equal to the attached the one attached to StateGraph user data
// as this will be our special light point drawable.
osgUtil::StateGraph::LeafList::iterator litr;
for(litr = rg->_leaves.begin();
litr != rg->_leaves.end() && (*litr)->_drawable!=drawable;
++litr)
{}
if (litr == rg->_leaves.end())
{
// havn't found the drawable added in the RenderLeaf list, there this my be the
// first time through LightPointNode in this frame, so need to add drawable into the StateGraph RenderLeaf list
// and update its time signatures.
drawable->reset();
rg->addLeaf(new osgUtil::RenderLeaf(drawable,&projection,NULL,FLT_MAX));
// need to update the drawable's frame count.
if (cv->getFrameStamp())
{
drawable->updateSimulationTime(cv->getFrameStamp()->getSimulationTime());
}
}
#ifdef USE_TIMER
t4 = timer.tick();
#endif
#ifdef USE_TIMER
t7 = timer.tick();
#endif
if (cv->getComputeNearFarMode() != osgUtil::CullVisitor::DO_NOT_COMPUTE_NEAR_FAR)
cv->updateCalculatedNearFar(matrix,_bbox);
const float minimumIntensity = 1.0f/256.0f;
const osg::Vec3 eyePoint = cv->getEyeLocal();
double time=drawable->getSimulationTime();
double timeInterval=drawable->getSimulationTimeInterval();
const osg::Polytope clipvol(cv->getCurrentCullingSet().getFrustum());
const bool computeClipping = false;//(clipvol.getCurrentMask()!=0);
//LightPointDrawable::ColorPosition cp;
for(LightPointList::iterator itr=_lightPointList.begin();
itr!=_lightPointList.end();
++itr)
{
const LightPoint& lp = *itr;
if (!lp._on) continue;
const osg::Vec3& position = lp._position;
// skip light point if it is not contianed in the view frustum.
if (computeClipping && !clipvol.contains(position)) continue;
// delta vector between eyepoint and light point.
osg::Vec3 dv(eyePoint-position);
float intensity = (_lightSystem.valid()) ? _lightSystem->getIntensity() : lp._intensity;
// slip light point if it is intensity is 0.0 or negative.
if (intensity<=minimumIntensity) continue;
// (SIB) Clip on distance, if close to limit, add transparancy
float distanceFactor = 1.0f;
if (_maxVisibleDistance2!=FLT_MAX)
{
if (dv.length2()>_maxVisibleDistance2) continue;
else if (_maxVisibleDistance2 > 0)
distanceFactor = 1.0f - osg::square(dv.length2() / _maxVisibleDistance2);
}
osg::Vec4 color = lp._color;
// check the sector.
if (lp._sector.valid())
{
intensity *= (*lp._sector)(dv);
// slip light point if it is intensity is 0.0 or negative.
if (intensity<=minimumIntensity) continue;
}
// temporary accounting of intensity.
//color *= intensity;
// check the blink sequence.
bool doBlink = lp._blinkSequence.valid();
if (doBlink && _lightSystem.valid())
doBlink = (_lightSystem->getAnimationState() == LightPointSystem::ANIMATION_ON);
if (doBlink)
{
osg::Vec4 bs = lp._blinkSequence->color(time,timeInterval);
color[0] *= bs[0];
color[1] *= bs[1];
color[2] *= bs[2];
color[3] *= bs[3];
}
// if alpha value is less than the min intentsive then skip
if (color[3]<=minimumIntensity) continue;
float pixelSize = cv->pixelSize(position,lp._radius);
// cout << "pixelsize = "<<pixelSize<<endl;
// adjust pixel size to account for intensity.
if (intensity!=1.0) pixelSize *= sqrt(intensity);
// adjust alfa to account for max range (Fade on distance)
color[3] *= distanceFactor;
// round up to the minimum pixel size if required.
float orgPixelSize = pixelSize;
if (pixelSize<_minPixelSize) pixelSize = _minPixelSize;
osg::Vec3 xpos(position*matrix);
if (lp._blendingMode==LightPoint::BLENDED)
{
if (pixelSize<1.0f)
{
// need to use alpha blending...
color[3] *= pixelSize;
// color[3] *= osg::square(pixelSize);
if (color[3]<=minimumIntensity) continue;
drawable->addBlendedLightPoint(0, xpos,color);
}
else if (pixelSize<_maxPixelSize)
{
unsigned int lowerBoundPixelSize = (unsigned int)pixelSize;
float remainder = osg::square(pixelSize-(float)lowerBoundPixelSize);
// (SIB) Add transparency if pixel is clamped to minpixelsize
if (orgPixelSize<_minPixelSize)
color[3] *= (2.0/3.0) + (1.0/3.0) * sqrt(orgPixelSize / pixelSize);
drawable->addBlendedLightPoint(lowerBoundPixelSize-1, xpos,color);
color[3] *= remainder;
drawable->addBlendedLightPoint(lowerBoundPixelSize, xpos,color);
}
else // use a billboard geometry.
{
drawable->addBlendedLightPoint((unsigned int)(_maxPixelSize-1.0), xpos,color);
}
}
else // ADDITIVE blending.
{
if (pixelSize<1.0f)
{
// need to use alpha blending...
color[3] *= pixelSize;
// color[3] *= osg::square(pixelSize);
if (color[3]<=minimumIntensity) continue;
drawable->addAdditiveLightPoint(0, xpos,color);
}
else if (pixelSize<_maxPixelSize)
{
unsigned int lowerBoundPixelSize = (unsigned int)pixelSize;
float remainder = osg::square(pixelSize-(float)lowerBoundPixelSize);
// (SIB) Add transparency if pixel is clamped to minpixelsize
if (orgPixelSize<_minPixelSize)
color[3] *= (2.0/3.0) + (1.0/3.0) * sqrt(orgPixelSize / pixelSize);
float alpha = color[3];
color[3] = alpha*(1.0f-remainder);
drawable->addAdditiveLightPoint(lowerBoundPixelSize-1, xpos,color);
color[3] = alpha*remainder;
drawable->addAdditiveLightPoint(lowerBoundPixelSize, xpos,color);
}
else // use a billboard geometry.
{
drawable->addAdditiveLightPoint((unsigned int)(_maxPixelSize-1.0), xpos,color);
}
}
}
#ifdef USE_TIMER
t8 = timer.tick();
#endif
}
#ifdef USE_TIMER
cout << "compute"<<endl;
cout << " t2-t1="<<t2-t1<<endl;
cout << " t4-t3="<<t4-t3<<endl;
cout << " t6-t5="<<t6-t5<<endl;
cout << " t8-t7="<<t8-t7<<endl;
cout << "_lightPointList.size()="<<_lightPointList.size()<<endl;
cout << " t8-t7/size = "<<(float)(t8-t7)/(float)_lightPointList.size()<<endl;
#endif
}
} // end of namespace
<commit_msg>Changed typeid(CullVisitor) check to dynamic_cast<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgSim/LightPointNode>
#include <osgSim/LightPointSystem>
#include "LightPointDrawable.h"
#include "LightPointSpriteDrawable.h"
#include <osg/Timer>
#include <osg/BoundingBox>
#include <osg/BlendFunc>
#include <osg/Material>
#include <osg/PointSprite>
#include <osgUtil/CullVisitor>
#include <typeinfo>
namespace osgSim
{
osg::StateSet* getSingletonLightPointSystemSet()
{
static osg::ref_ptr<osg::StateSet> s_stateset = 0;
if (!s_stateset)
{
s_stateset = new osg::StateSet;
// force light point nodes to be drawn after everything else by picking a renderin bin number after
// the transparent bin.
s_stateset->setRenderBinDetails(20,"DepthSortedBin");
}
return s_stateset.get();
}
LightPointNode::LightPointNode():
_minPixelSize(0.0f),
_maxPixelSize(30.0f),
_maxVisibleDistance2(FLT_MAX),
_lightSystem(0),
_pointSprites(false)
{
setStateSet(getSingletonLightPointSystemSet());
}
/** Copy constructor using CopyOp to manage deep vs shallow copy.*/
LightPointNode::LightPointNode(const LightPointNode& lpn,const osg::CopyOp& copyop):
osg::Node(lpn,copyop),
_lightPointList(lpn._lightPointList),
_minPixelSize(lpn._minPixelSize),
_maxPixelSize(lpn._maxPixelSize),
_maxVisibleDistance2(lpn._maxVisibleDistance2),
_lightSystem(lpn._lightSystem),
_pointSprites(lpn._pointSprites)
{
}
unsigned int LightPointNode::addLightPoint(const LightPoint& lp)
{
unsigned int num = _lightPointList.size();
_lightPointList.push_back(lp);
dirtyBound();
return num;
}
void LightPointNode::removeLightPoint(unsigned int pos)
{
if (pos<_lightPointList.size())
{
_lightPointList.erase(_lightPointList.begin()+pos);
dirtyBound();
}
dirtyBound();
}
osg::BoundingSphere LightPointNode::computeBound() const
{
osg::BoundingSphere bsphere;
bsphere.init();
_bbox.init();
if (_lightPointList.empty())
{
return bsphere;
}
LightPointList::const_iterator itr;
for(itr=_lightPointList.begin();
itr!=_lightPointList.end();
++itr)
{
_bbox.expandBy(itr->_position);
}
bsphere.set(_bbox.center(),0.0f);
for(itr=_lightPointList.begin();
itr!=_lightPointList.end();
++itr)
{
osg::Vec3 dv(itr->_position-bsphere.center());
float radius = dv.length()+itr->_radius;
if (bsphere.radius()<radius) bsphere.radius()=radius;
}
bsphere.radius()+=1.0f;
return bsphere;
}
void LightPointNode::traverse(osg::NodeVisitor& nv)
{
if (_lightPointList.empty())
{
// no light points so no op.
return;
}
//#define USE_TIMER
#ifdef USE_TIMER
osg::Timer timer;
osg::Timer_t t1=0,t2=0,t3=0,t4=0,t5=0,t6=0,t7=0,t8=0;
#endif
#ifdef USE_TIMER
t1 = timer.tick();
#endif
osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(&nv);
#ifdef USE_TIMER
t2 = timer.tick();
#endif
// should we disabled small feature culling here?
if (cv /*&& !cv->isCulled(_bbox)*/)
{
osg::Matrix matrix = *(cv->getModelViewMatrix());
osg::RefMatrix& projection = *(cv->getProjectionMatrix());
osgUtil::StateGraph* rg = cv->getCurrentStateGraph();
if (rg->leaves_empty())
{
// this is first leaf to be added to StateGraph
// and therefore should not already know to current render bin,
// so need to add it.
cv->getCurrentRenderBin()->addStateGraph(rg);
}
#ifdef USE_TIMER
t3 = timer.tick();
#endif
LightPointDrawable* drawable = NULL;
osg::Referenced* object = rg->getUserData();
if (object)
{
if (typeid(*object)==typeid(LightPointDrawable))
{
// resuse the user data attached to the render graph.
drawable = static_cast<LightPointDrawable*>(object);
}
else if (typeid(*object)==typeid(LightPointSpriteDrawable))
{
drawable = static_cast<LightPointSpriteDrawable*>(object);
}
else
{
// will need to replace UserData.
osg::notify(osg::WARN) << "Warning: Replacing osgUtil::StateGraph::_userData to support osgSim::LightPointNode, may have undefined results."<<std::endl;
}
}
if (!drawable)
{
drawable = _pointSprites ? new LightPointSpriteDrawable : new LightPointDrawable;
rg->setUserData(drawable);
if (cv->getFrameStamp())
{
drawable->setSimulationTime(cv->getFrameStamp()->getSimulationTime());
}
}
// search for a drawable in the RenderLead list equal to the attached the one attached to StateGraph user data
// as this will be our special light point drawable.
osgUtil::StateGraph::LeafList::iterator litr;
for(litr = rg->_leaves.begin();
litr != rg->_leaves.end() && (*litr)->_drawable!=drawable;
++litr)
{}
if (litr == rg->_leaves.end())
{
// havn't found the drawable added in the RenderLeaf list, there this my be the
// first time through LightPointNode in this frame, so need to add drawable into the StateGraph RenderLeaf list
// and update its time signatures.
drawable->reset();
rg->addLeaf(new osgUtil::RenderLeaf(drawable,&projection,NULL,FLT_MAX));
// need to update the drawable's frame count.
if (cv->getFrameStamp())
{
drawable->updateSimulationTime(cv->getFrameStamp()->getSimulationTime());
}
}
#ifdef USE_TIMER
t4 = timer.tick();
#endif
#ifdef USE_TIMER
t7 = timer.tick();
#endif
if (cv->getComputeNearFarMode() != osgUtil::CullVisitor::DO_NOT_COMPUTE_NEAR_FAR)
cv->updateCalculatedNearFar(matrix,_bbox);
const float minimumIntensity = 1.0f/256.0f;
const osg::Vec3 eyePoint = cv->getEyeLocal();
double time=drawable->getSimulationTime();
double timeInterval=drawable->getSimulationTimeInterval();
const osg::Polytope clipvol(cv->getCurrentCullingSet().getFrustum());
const bool computeClipping = false;//(clipvol.getCurrentMask()!=0);
//LightPointDrawable::ColorPosition cp;
for(LightPointList::iterator itr=_lightPointList.begin();
itr!=_lightPointList.end();
++itr)
{
const LightPoint& lp = *itr;
if (!lp._on) continue;
const osg::Vec3& position = lp._position;
// skip light point if it is not contianed in the view frustum.
if (computeClipping && !clipvol.contains(position)) continue;
// delta vector between eyepoint and light point.
osg::Vec3 dv(eyePoint-position);
float intensity = (_lightSystem.valid()) ? _lightSystem->getIntensity() : lp._intensity;
// slip light point if it is intensity is 0.0 or negative.
if (intensity<=minimumIntensity) continue;
// (SIB) Clip on distance, if close to limit, add transparancy
float distanceFactor = 1.0f;
if (_maxVisibleDistance2!=FLT_MAX)
{
if (dv.length2()>_maxVisibleDistance2) continue;
else if (_maxVisibleDistance2 > 0)
distanceFactor = 1.0f - osg::square(dv.length2() / _maxVisibleDistance2);
}
osg::Vec4 color = lp._color;
// check the sector.
if (lp._sector.valid())
{
intensity *= (*lp._sector)(dv);
// slip light point if it is intensity is 0.0 or negative.
if (intensity<=minimumIntensity) continue;
}
// temporary accounting of intensity.
//color *= intensity;
// check the blink sequence.
bool doBlink = lp._blinkSequence.valid();
if (doBlink && _lightSystem.valid())
doBlink = (_lightSystem->getAnimationState() == LightPointSystem::ANIMATION_ON);
if (doBlink)
{
osg::Vec4 bs = lp._blinkSequence->color(time,timeInterval);
color[0] *= bs[0];
color[1] *= bs[1];
color[2] *= bs[2];
color[3] *= bs[3];
}
// if alpha value is less than the min intentsive then skip
if (color[3]<=minimumIntensity) continue;
float pixelSize = cv->pixelSize(position,lp._radius);
// cout << "pixelsize = "<<pixelSize<<endl;
// adjust pixel size to account for intensity.
if (intensity!=1.0) pixelSize *= sqrt(intensity);
// adjust alfa to account for max range (Fade on distance)
color[3] *= distanceFactor;
// round up to the minimum pixel size if required.
float orgPixelSize = pixelSize;
if (pixelSize<_minPixelSize) pixelSize = _minPixelSize;
osg::Vec3 xpos(position*matrix);
if (lp._blendingMode==LightPoint::BLENDED)
{
if (pixelSize<1.0f)
{
// need to use alpha blending...
color[3] *= pixelSize;
// color[3] *= osg::square(pixelSize);
if (color[3]<=minimumIntensity) continue;
drawable->addBlendedLightPoint(0, xpos,color);
}
else if (pixelSize<_maxPixelSize)
{
unsigned int lowerBoundPixelSize = (unsigned int)pixelSize;
float remainder = osg::square(pixelSize-(float)lowerBoundPixelSize);
// (SIB) Add transparency if pixel is clamped to minpixelsize
if (orgPixelSize<_minPixelSize)
color[3] *= (2.0/3.0) + (1.0/3.0) * sqrt(orgPixelSize / pixelSize);
drawable->addBlendedLightPoint(lowerBoundPixelSize-1, xpos,color);
color[3] *= remainder;
drawable->addBlendedLightPoint(lowerBoundPixelSize, xpos,color);
}
else // use a billboard geometry.
{
drawable->addBlendedLightPoint((unsigned int)(_maxPixelSize-1.0), xpos,color);
}
}
else // ADDITIVE blending.
{
if (pixelSize<1.0f)
{
// need to use alpha blending...
color[3] *= pixelSize;
// color[3] *= osg::square(pixelSize);
if (color[3]<=minimumIntensity) continue;
drawable->addAdditiveLightPoint(0, xpos,color);
}
else if (pixelSize<_maxPixelSize)
{
unsigned int lowerBoundPixelSize = (unsigned int)pixelSize;
float remainder = osg::square(pixelSize-(float)lowerBoundPixelSize);
// (SIB) Add transparency if pixel is clamped to minpixelsize
if (orgPixelSize<_minPixelSize)
color[3] *= (2.0/3.0) + (1.0/3.0) * sqrt(orgPixelSize / pixelSize);
float alpha = color[3];
color[3] = alpha*(1.0f-remainder);
drawable->addAdditiveLightPoint(lowerBoundPixelSize-1, xpos,color);
color[3] = alpha*remainder;
drawable->addAdditiveLightPoint(lowerBoundPixelSize, xpos,color);
}
else // use a billboard geometry.
{
drawable->addAdditiveLightPoint((unsigned int)(_maxPixelSize-1.0), xpos,color);
}
}
}
#ifdef USE_TIMER
t8 = timer.tick();
#endif
}
#ifdef USE_TIMER
cout << "compute"<<endl;
cout << " t2-t1="<<t2-t1<<endl;
cout << " t4-t3="<<t4-t3<<endl;
cout << " t6-t5="<<t6-t5<<endl;
cout << " t8-t7="<<t8-t7<<endl;
cout << "_lightPointList.size()="<<_lightPointList.size()<<endl;
cout << " t8-t7/size = "<<(float)(t8-t7)/(float)_lightPointList.size()<<endl;
#endif
}
} // end of namespace
<|endoftext|> |
<commit_before>#ifndef _SDD_MEM_CACHE_HH_
#define _SDD_MEM_CACHE_HH_
#include "sdd/mem/cache_entry.hh"
#include "sdd/mem/hash_table.hh"
#include "sdd/mem/interrupt.hh"
#include "sdd/mem/lru_list.hh"
#include "sdd/util/hash.hh"
namespace sdd { namespace mem {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Used by cache to know if an operation should be cached or not.
///
/// A filter should always return the same result for the same operation.
template <typename T, typename... Filters>
struct apply_filters;
/// @internal
/// @brief Base case.
///
/// All filters have been applied and they all accepted the operation.
template <typename T>
struct apply_filters<T>
{
constexpr
bool
operator()(const T&)
const
{
return true;
}
};
/// @internal
/// @brief Recursive case.
///
/// Chain filters calls: as soon as a filter reject an operation, the evaluation is stopped.
template <typename T, typename Filter, typename... Filters>
struct apply_filters<T, Filter, Filters...>
{
bool
operator()(const T& op)
const
{
return Filter()(op) ? apply_filters<T, Filters...>()(op) : false;
}
};
/*------------------------------------------------------------------------------------------------*/
namespace /* anonymous */ {
/// @internal
/// @brief The statistics of a cache.
struct cache_statistics
{
/// @brief The number of entries.
std::size_t size;
/// @brief The number of hits.
std::size_t hits;
/// @brief The number of misses.
std::size_t misses;
/// @brief The number of filtered entries.
std::size_t filtered;
/// @brief The number of entries discarded by the LRU policy.
std::size_t discarded;
/// @brief The number of collisions in the underlying hash table.
std::size_t collisions;
/// @brief The number of buckets in the underlying hash table.
std::size_t buckets;
/// @brief The load factor of the underlying hash table.
double load_factor;
};
} // namespace anonymous
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief A generic cache.
/// @tparam Operation is the operation type.
/// @tparam EvaluationError is the exception that the evaluation of an Operation can throw.
/// @tparam Filters is a list of filters that reject some operations.
///
/// It uses the LRU strategy to cleanup old entries.
template < typename Context, typename Operation, typename EvaluationError
, typename... Filters>
class cache
{
// Can't copy a cache.
cache(const cache&) = delete;
cache* operator=(const cache&) = delete;
private:
/// @brief The type of the context of this cache.
using context_type = Context;
/// @brief The type of the result of an operation stored in the cache.
using result_type = typename Operation::result_type;
/// @brief The of an entry that stores an operation and its result.
using cache_entry_type = cache_entry<Operation, result_type>;
/// @brief An intrusive hash table.
using set_type = mem::hash_table<cache_entry_type>;
/// @brief This cache's context.
context_type& cxt_;
/// @brief The wanted load factor for the underlying hash table.
static constexpr double max_load_factor = 0.85;
/// @brief The actual storage of caches entries.
set_type set_;
/// @brief The the container that sorts cache entries by last access date.
lru_list<Operation, result_type> lru_list_;
/// @brief The maximum size this cache is authorized to grow to.
std::size_t max_size_;
/// @brief The statistics of this cache.
mutable cache_statistics stats_;
public:
/// @brief Construct a cache.
/// @param context This cache's context.
/// @param name Give a name to this cache.
/// @param size tells how many cache entries are keeped in the cache.
///
/// When the maximal size is reached, a cleanup is launched: half of the cache is removed,
/// using a LRU strategy. This cache will never perform a rehash, therefore it allocates
/// all the memory it needs at its construction.
cache(context_type& context, std::size_t size)
: cxt_(context)
, set_(size, max_load_factor, true /* no rehash */)
, lru_list_()
, max_size_(set_.bucket_count() * max_load_factor)
, stats_()
{}
/// @brief Destructor.
~cache()
{
clear();
}
/// @brief Cache lookup.
result_type
operator()(Operation&& op)
{
// Check if the current operation should not be cached.
if (not apply_filters<Operation, Filters...>()(op))
{
++stats_.filtered;
try
{
return op(cxt_);
}
catch (EvaluationError& e)
{
--stats_.filtered;
e.add_step(std::move(op));
throw;
}
}
// Lookup for op.
typename set_type::insert_commit_data commit_data;
auto insertion = set_.insert_check( op
, std::hash<Operation>()
, [](const Operation& lhs, const cache_entry_type& rhs)
{return lhs == rhs.operation;}
, commit_data);
// Check if op has already been computed.
if (not insertion.second)
{
++stats_.hits;
// Move cache entry to the end of the LRU list.
lru_list_.splice(lru_list_.end(), lru_list_, insertion.first->lru_cit_);
return insertion.first->result;
}
++stats_.misses;
cache_entry_type* entry;
try
{
entry = new cache_entry_type(std::move(op), op(cxt_));
}
catch (EvaluationError& e)
{
--stats_.misses;
e.add_step(std::move(op));
throw;
}
// Clean up the cache, if necessary.
while (set_.size() > max_size_)
{
auto oldest = lru_list_.front();
set_.erase(*oldest);
delete oldest;
lru_list_.pop_front();
++stats_.discarded;
}
// Add the new cache entry to the end of the LRU list.
entry->lru_cit_ = lru_list_.insert(lru_list_.end(), entry);
// Finally, set the result associated to op.
set_.insert_commit(*entry, commit_data); // doesn't throw
return entry->result;
}
/// @brief Remove all entries of the cache.
void
clear()
noexcept
{
set_.clear_and_dispose([](cache_entry_type* x){delete x;});
}
/// @brief Get the number of cached operations.
std::size_t
size()
const noexcept
{
return set_.size();
}
/// @brief Get the statistics of this cache.
const cache_statistics&
statistics()
const noexcept
{
stats_.size = size();
stats_.collisions = set_.collisions();
stats_.buckets = set_.bucket_count();
stats_.load_factor = set_.load_factor();
return stats_;
}
};
/*------------------------------------------------------------------------------------------------*/
}} // namespace sdd::mem
#endif // _SDD_MEM_CACHE_HH_
<commit_msg>Documentation.<commit_after>#ifndef _SDD_MEM_CACHE_HH_
#define _SDD_MEM_CACHE_HH_
#include "sdd/mem/cache_entry.hh"
#include "sdd/mem/hash_table.hh"
#include "sdd/mem/interrupt.hh"
#include "sdd/mem/lru_list.hh"
#include "sdd/util/hash.hh"
namespace sdd { namespace mem {
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief Used by cache to know if an operation should be cached or not.
///
/// A filter should always return the same result for the same operation.
template <typename T, typename... Filters>
struct apply_filters;
/// @internal
/// @brief Base case.
///
/// All filters have been applied and they all accepted the operation.
template <typename T>
struct apply_filters<T>
{
constexpr
bool
operator()(const T&)
const
{
return true;
}
};
/// @internal
/// @brief Recursive case.
///
/// Chain filters calls: as soon as a filter reject an operation, the evaluation is stopped.
template <typename T, typename Filter, typename... Filters>
struct apply_filters<T, Filter, Filters...>
{
bool
operator()(const T& op)
const
{
return Filter()(op) ? apply_filters<T, Filters...>()(op) : false;
}
};
/*------------------------------------------------------------------------------------------------*/
namespace /* anonymous */ {
/// @internal
/// @brief The statistics of a cache.
struct cache_statistics
{
/// @brief The number of entries.
std::size_t size;
/// @brief The number of hits.
std::size_t hits;
/// @brief The number of misses.
std::size_t misses;
/// @brief The number of filtered entries.
std::size_t filtered;
/// @brief The number of entries discarded by the LRU policy.
std::size_t discarded;
/// @brief The number of collisions in the underlying hash table.
std::size_t collisions;
/// @brief The number of buckets in the underlying hash table.
std::size_t buckets;
/// @brief The load factor of the underlying hash table.
double load_factor;
};
} // namespace anonymous
/*------------------------------------------------------------------------------------------------*/
/// @internal
/// @brief A generic cache.
/// @tparam Operation is the operation type.
/// @tparam EvaluationError is the exception that the evaluation of an Operation can throw.
/// @tparam Filters is a list of filters that reject some operations.
///
/// It uses the LRU strategy to cleanup old entries.
template < typename Context, typename Operation, typename EvaluationError
, typename... Filters>
class cache
{
// Can't copy a cache.
cache(const cache&) = delete;
cache* operator=(const cache&) = delete;
private:
/// @brief The type of the context of this cache.
using context_type = Context;
/// @brief The type of the result of an operation stored in the cache.
using result_type = typename Operation::result_type;
/// @brief The of an entry that stores an operation and its result.
using cache_entry_type = cache_entry<Operation, result_type>;
/// @brief An intrusive hash table.
using set_type = mem::hash_table<cache_entry_type>;
/// @brief This cache's context.
context_type& cxt_;
/// @brief The wanted load factor for the underlying hash table.
static constexpr double max_load_factor = 0.85;
/// @brief The actual storage of caches entries.
set_type set_;
/// @brief The the container that sorts cache entries by last access date.
lru_list<Operation, result_type> lru_list_;
/// @brief The maximum size this cache is authorized to grow to.
std::size_t max_size_;
/// @brief The statistics of this cache.
mutable cache_statistics stats_;
public:
/// @brief Construct a cache.
/// @param context This cache's context.
/// @param size tells how many cache entries are keeped in the cache.
///
/// When the maximal size is reached, a cleanup is launched: half of the cache is removed,
/// using a LRU strategy. This cache will never perform a rehash, therefore it allocates
/// all the memory it needs at its construction.
cache(context_type& context, std::size_t size)
: cxt_(context)
, set_(size, max_load_factor, true /* no rehash */)
, lru_list_()
, max_size_(set_.bucket_count() * max_load_factor)
, stats_()
{}
/// @brief Destructor.
~cache()
{
clear();
}
/// @brief Cache lookup.
result_type
operator()(Operation&& op)
{
// Check if the current operation should not be cached.
if (not apply_filters<Operation, Filters...>()(op))
{
++stats_.filtered;
try
{
return op(cxt_);
}
catch (EvaluationError& e)
{
--stats_.filtered;
e.add_step(std::move(op));
throw;
}
}
// Lookup for op.
typename set_type::insert_commit_data commit_data;
auto insertion = set_.insert_check( op
, std::hash<Operation>()
, [](const Operation& lhs, const cache_entry_type& rhs)
{return lhs == rhs.operation;}
, commit_data);
// Check if op has already been computed.
if (not insertion.second)
{
++stats_.hits;
// Move cache entry to the end of the LRU list.
lru_list_.splice(lru_list_.end(), lru_list_, insertion.first->lru_cit_);
return insertion.first->result;
}
++stats_.misses;
cache_entry_type* entry;
try
{
entry = new cache_entry_type(std::move(op), op(cxt_));
}
catch (EvaluationError& e)
{
--stats_.misses;
e.add_step(std::move(op));
throw;
}
// Clean up the cache, if necessary.
while (set_.size() > max_size_)
{
auto oldest = lru_list_.front();
set_.erase(*oldest);
delete oldest;
lru_list_.pop_front();
++stats_.discarded;
}
// Add the new cache entry to the end of the LRU list.
entry->lru_cit_ = lru_list_.insert(lru_list_.end(), entry);
// Finally, set the result associated to op.
set_.insert_commit(*entry, commit_data); // doesn't throw
return entry->result;
}
/// @brief Remove all entries of the cache.
void
clear()
noexcept
{
set_.clear_and_dispose([](cache_entry_type* x){delete x;});
}
/// @brief Get the number of cached operations.
std::size_t
size()
const noexcept
{
return set_.size();
}
/// @brief Get the statistics of this cache.
const cache_statistics&
statistics()
const noexcept
{
stats_.size = size();
stats_.collisions = set_.collisions();
stats_.buckets = set_.bucket_count();
stats_.load_factor = set_.load_factor();
return stats_;
}
};
/*------------------------------------------------------------------------------------------------*/
}} // namespace sdd::mem
#endif // _SDD_MEM_CACHE_HH_
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006 Volker Krause <volker.krause@rwth-aachen.de>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "monitor.h"
#include "notificationmanagerinterface.h"
#include <QDBusInterface>
#include <QDBusConnection>
#include <QDebug>
using namespace PIM;
class PIM::MonitorPrivate
{
public:
org::kde::Akonadi::NotificationManager *nm;
QList<QByteArray> collections;
bool isCollectionMonitored( const QByteArray &path )
{
foreach ( const QByteArray ba, collections ) {
if ( path.startsWith( ba ) )
return true;
}
return false;
}
};
PIM::Monitor::Monitor( QObject *parent ) :
QObject( parent ),
d( new MonitorPrivate() )
{
d->nm = 0;
connectToNotificationManager();
}
PIM::Monitor::~Monitor()
{
delete d;
}
void PIM::Monitor::monitorCollection( const QByteArray & path )
{
d->collections.append( path );
if ( connectToNotificationManager() )
d->nm->monitorCollection( path );
}
void PIM::Monitor::monitorItem( const DataReference & ref )
{
if ( connectToNotificationManager() )
d->nm->monitorItem( ref.persistanceID().toLatin1() );
}
void PIM::Monitor::slotItemChanged( const QByteArray & uid, const QByteArray & collection )
{
if ( d->isCollectionMonitored( collection ) )
emit itemChanged( DataReference( uid, QString() ) );
}
void PIM::Monitor::slotItemAdded( const QByteArray & uid, const QByteArray & collection )
{
if ( d->isCollectionMonitored( collection ) )
emit itemAdded( DataReference( uid, QString() ) );
}
void PIM::Monitor::slotItemRemoved( const QByteArray & uid, const QByteArray & collection )
{
if ( d->isCollectionMonitored( collection ) )
emit itemRemoved( DataReference( uid, QString() ) );
}
void PIM::Monitor::slotCollectionChanged( const QByteArray & path )
{
if ( d->isCollectionMonitored( path ) )
emit collectionChanged( path );
}
void PIM::Monitor::slotCollectionAdded( const QByteArray & path )
{
if ( d->isCollectionMonitored( path ) )
emit collectionAdded( path );
}
void PIM::Monitor::slotCollectionRemoved( const QByteArray & path )
{
if ( d->isCollectionMonitored( path ) )
emit collectionRemoved( path );
}
bool PIM::Monitor::connectToNotificationManager( )
{
if ( !d->nm )
d->nm = new org::kde::Akonadi::NotificationManager("org.kde.Akonadi.NotificationManager",
"/", QDBus::sessionBus(), this );
else
return true;
if ( !d->nm ) {
qWarning() << "Unable to connect to notification manager";
} else {
connect( d->nm, SIGNAL(itemChanged(QByteArray,QByteArray)), SLOT(slotItemChanged(QByteArray,QByteArray)) );
connect( d->nm, SIGNAL(itemAdded(QByteArray,QByteArray)), SLOT(slotItemAdded(QByteArray,QByteArray)) );
connect( d->nm, SIGNAL(itemRemoved(QByteArray,QByteArray)), SLOT(slotItemRemoved(QByteArray,QByteArray)) );
connect( d->nm, SIGNAL(collectionChanged(QByteArray)), SLOT(slotCollectionChanged(QByteArray)) );
connect( d->nm, SIGNAL(collectionAdded(QByteArray)), SLOT(slotCollectionAdded(QByteArray)) );
connect( d->nm, SIGNAL(collectionRemoved(QByteArray)), SLOT(slotCollectionRemoved(QByteArray)) );
return true;
}
return false;
}
#include "monitor.moc"
<commit_msg>fix DBus connection to the notification manager.<commit_after>/*
Copyright (c) 2006 Volker Krause <volker.krause@rwth-aachen.de>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "monitor.h"
#include "notificationmanagerinterface.h"
#include <QDBusInterface>
#include <QDBusConnection>
#include <QDebug>
using namespace PIM;
class PIM::MonitorPrivate
{
public:
org::kde::Akonadi::NotificationManager *nm;
QList<QByteArray> collections;
bool isCollectionMonitored( const QByteArray &path )
{
foreach ( const QByteArray ba, collections ) {
if ( path.startsWith( ba ) )
return true;
}
return false;
}
};
PIM::Monitor::Monitor( QObject *parent ) :
QObject( parent ),
d( new MonitorPrivate() )
{
d->nm = 0;
connectToNotificationManager();
}
PIM::Monitor::~Monitor()
{
delete d;
}
void PIM::Monitor::monitorCollection( const QByteArray & path )
{
d->collections.append( path );
if ( connectToNotificationManager() )
d->nm->monitorCollection( path );
}
void PIM::Monitor::monitorItem( const DataReference & ref )
{
if ( connectToNotificationManager() )
d->nm->monitorItem( ref.persistanceID().toLatin1() );
}
void PIM::Monitor::slotItemChanged( const QByteArray & uid, const QByteArray & collection )
{
if ( d->isCollectionMonitored( collection ) )
emit itemChanged( DataReference( uid, QString() ) );
}
void PIM::Monitor::slotItemAdded( const QByteArray & uid, const QByteArray & collection )
{
if ( d->isCollectionMonitored( collection ) )
emit itemAdded( DataReference( uid, QString() ) );
}
void PIM::Monitor::slotItemRemoved( const QByteArray & uid, const QByteArray & collection )
{
if ( d->isCollectionMonitored( collection ) )
emit itemRemoved( DataReference( uid, QString() ) );
}
void PIM::Monitor::slotCollectionChanged( const QByteArray & path )
{
if ( d->isCollectionMonitored( path ) )
emit collectionChanged( path );
}
void PIM::Monitor::slotCollectionAdded( const QByteArray & path )
{
if ( d->isCollectionMonitored( path ) )
emit collectionAdded( path );
}
void PIM::Monitor::slotCollectionRemoved( const QByteArray & path )
{
if ( d->isCollectionMonitored( path ) )
emit collectionRemoved( path );
}
bool PIM::Monitor::connectToNotificationManager( )
{
if ( !d->nm )
d->nm = new org::kde::Akonadi::NotificationManager("org.kde.Akonadi",
"/notifications", QDBus::sessionBus(), this );
else
return true;
if ( !d->nm ) {
qWarning() << "Unable to connect to notification manager";
} else {
connect( d->nm, SIGNAL(itemChanged(QByteArray,QByteArray)), SLOT(slotItemChanged(QByteArray,QByteArray)) );
connect( d->nm, SIGNAL(itemAdded(QByteArray,QByteArray)), SLOT(slotItemAdded(QByteArray,QByteArray)) );
connect( d->nm, SIGNAL(itemRemoved(QByteArray,QByteArray)), SLOT(slotItemRemoved(QByteArray,QByteArray)) );
connect( d->nm, SIGNAL(collectionChanged(QByteArray)), SLOT(slotCollectionChanged(QByteArray)) );
connect( d->nm, SIGNAL(collectionAdded(QByteArray)), SLOT(slotCollectionAdded(QByteArray)) );
connect( d->nm, SIGNAL(collectionRemoved(QByteArray)), SLOT(slotCollectionRemoved(QByteArray)) );
return true;
}
return false;
}
#include "monitor.moc"
<|endoftext|> |
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2013, 2014
Raffaello D. Di Napoli
This file is part of Application-Building Components (henceforth referred to as ABC).
ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License along with ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abc/testing/core.hxx>
#include <abc/testing/test_case.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case
namespace abc {
namespace testing {
test_case::test_case() {
}
/*virtual*/ test_case::~test_case() {
}
void test_case::init(runner * prunner) {
ABC_TRACE_FN((this, prunner));
m_prunner = prunner;
}
void test_case::assert_does_not_throw(
source_location const & srcloc, std::function<void ()> fnExpr, istr const & sExpr
) {
ABC_TRACE_FN((this, srcloc, /*fnExpr, */sExpr));
istr sCaughtWhat;
try {
fnExpr();
} catch (::std::exception const & x) {
sCaughtWhat = istr(SL("throws {}")).format(x.what());
} catch (...) {
sCaughtWhat = SL("unknown type");
}
m_prunner->log_assertion(srcloc, !sCaughtWhat, sExpr, istr(), SL("does not throw"), sCaughtWhat);
}
void test_case::assert_false(source_location const & srcloc, bool bActual, istr const & sExpr) {
ABC_TRACE_FN((this, srcloc, bActual, sExpr));
m_prunner->log_assertion(
srcloc, !bActual, sExpr, istr(), !bActual ? istr() : SL("false"), SL("true")
);
}
void test_case::assert_true(source_location const & srcloc, bool bActual, istr const & sExpr) {
ABC_TRACE_FN((this, srcloc, bActual, sExpr));
m_prunner->log_assertion(
srcloc, bActual, sExpr, istr(), bActual ? istr() : SL("true"), SL("false")
);
}
void test_case::assert_throws(
source_location const & srcloc, std::function<void ()> fnExpr, istr const & sExpr,
std::function<bool (std::exception const &)> fnMatchType, char const * pszExpectedWhat
) {
ABC_TRACE_FN((this, srcloc, /*fnExpr, */sExpr, /*fnMatchType, */pszExpectedWhat));
bool bPass(false);
istr sCaughtWhat;
try {
fnExpr();
sCaughtWhat = SL("does not throw");
} catch (::std::exception const & x) {
if (fnMatchType(x)) {
bPass = true;
} else {
sCaughtWhat = istr(SL("throws {}")).format(c_str_to_str_adapter(x.what()));
}
} catch (...) {
sCaughtWhat = SL("unknown type");
}
this->m_prunner->log_assertion(
srcloc, bPass, sExpr, istr(),
istr(SL("throws {}")).format(c_str_to_str_adapter(pszExpectedWhat)), sCaughtWhat
);
}
} //namespace testing
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case_factory_impl
namespace abc {
namespace testing {
/*static*/ test_case_factory_impl::list_item * test_case_factory_impl::sm_pliHead(nullptr);
// MSC16 BUG: for some reason, this will be parsed as a function declaration if written as a
// constructor call.
/*static*/ test_case_factory_impl::list_item ** test_case_factory_impl::sm_ppliTailNext = nullptr;
test_case_factory_impl::test_case_factory_impl(list_item * pli) {
if (sm_pliHead) {
// We have a head and therefore a tail as well: add *pli as the new tail.
*sm_ppliTailNext = pli;
} else {
// We don’t have a head yet: set it up now.
sm_pliHead = pli;
}
// Save the “next” pointer of *pli for the next call.
sm_ppliTailNext = &pli->pliNext;
}
} //namespace testing
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
<commit_msg>Remove unnecessary this-> qualifier<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2013, 2014
Raffaello D. Di Napoli
This file is part of Application-Building Components (henceforth referred to as ABC).
ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.
You should have received a copy of the GNU General Public License along with ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/
#include <abc/testing/core.hxx>
#include <abc/testing/test_case.hxx>
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case
namespace abc {
namespace testing {
test_case::test_case() {
}
/*virtual*/ test_case::~test_case() {
}
void test_case::init(runner * prunner) {
ABC_TRACE_FN((this, prunner));
m_prunner = prunner;
}
void test_case::assert_does_not_throw(
source_location const & srcloc, std::function<void ()> fnExpr, istr const & sExpr
) {
ABC_TRACE_FN((this, srcloc, /*fnExpr, */sExpr));
istr sCaughtWhat;
try {
fnExpr();
} catch (::std::exception const & x) {
sCaughtWhat = istr(SL("throws {}")).format(x.what());
} catch (...) {
sCaughtWhat = SL("unknown type");
}
m_prunner->log_assertion(srcloc, !sCaughtWhat, sExpr, istr(), SL("does not throw"), sCaughtWhat);
}
void test_case::assert_false(source_location const & srcloc, bool bActual, istr const & sExpr) {
ABC_TRACE_FN((this, srcloc, bActual, sExpr));
m_prunner->log_assertion(
srcloc, !bActual, sExpr, istr(), !bActual ? istr() : SL("false"), SL("true")
);
}
void test_case::assert_true(source_location const & srcloc, bool bActual, istr const & sExpr) {
ABC_TRACE_FN((this, srcloc, bActual, sExpr));
m_prunner->log_assertion(
srcloc, bActual, sExpr, istr(), bActual ? istr() : SL("true"), SL("false")
);
}
void test_case::assert_throws(
source_location const & srcloc, std::function<void ()> fnExpr, istr const & sExpr,
std::function<bool (std::exception const &)> fnMatchType, char const * pszExpectedWhat
) {
ABC_TRACE_FN((this, srcloc, /*fnExpr, */sExpr, /*fnMatchType, */pszExpectedWhat));
bool bPass(false);
istr sCaughtWhat;
try {
fnExpr();
sCaughtWhat = SL("does not throw");
} catch (::std::exception const & x) {
if (fnMatchType(x)) {
bPass = true;
} else {
sCaughtWhat = istr(SL("throws {}")).format(c_str_to_str_adapter(x.what()));
}
} catch (...) {
sCaughtWhat = SL("unknown type");
}
m_prunner->log_assertion(
srcloc, bPass, sExpr, istr(),
istr(SL("throws {}")).format(c_str_to_str_adapter(pszExpectedWhat)), sCaughtWhat
);
}
} //namespace testing
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::testing::test_case_factory_impl
namespace abc {
namespace testing {
/*static*/ test_case_factory_impl::list_item * test_case_factory_impl::sm_pliHead(nullptr);
// MSC16 BUG: for some reason, this will be parsed as a function declaration if written as a
// constructor call.
/*static*/ test_case_factory_impl::list_item ** test_case_factory_impl::sm_ppliTailNext = nullptr;
test_case_factory_impl::test_case_factory_impl(list_item * pli) {
if (sm_pliHead) {
// We have a head and therefore a tail as well: add *pli as the new tail.
*sm_ppliTailNext = pli;
} else {
// We don’t have a head yet: set it up now.
sm_pliHead = pli;
}
// Save the “next” pointer of *pli for the next call.
sm_ppliTailNext = &pli->pliNext;
}
} //namespace testing
} //namespace abc
////////////////////////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>// Source : https://leetcode.com/problems/set-matrix-zeroes/
// Author : Siyuan Xu
// Date : 2015-08-12
/**********************************************************************************
*
* Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
*
* click to show follow up.
*
* Follow up:
*
* Did you use extra space?
* A straight forward solution using O(mn) space is probably a bad idea.
* A simple improvement uses O(m + n) space, but still not the best solution.
* Could you devise a constant space solution?
*
*
**********************************************************************************/
//in place
//88ms(good)
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
bool colZero = false;
for (int i = 0; i < m; i++) {
if (matrix[i][0] == 0) colZero = true;
for (int j = 1; j < n; j++) {
if (matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
}
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 1; j--) {
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
}
if (colZero) {
matrix[i][0] = 0;
}
}
}
};
//helper space
//84ms(best)
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
if (matrix.empty()) return;
int m = matrix.size(), n = matrix[0].size();
vector<bool> row(m, false);
vector<bool> col(n, false);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0)
row[i] = col[j] = true;
}
}
for (int i = 0; i < m; i++) {
if (row[i]) {
fill(matrix[i].begin(), matrix[i].end(), 0);
}
}
for (int j = 0; j < n; j++) {
if (col[j]) {
for (int i = 0; i < m; i++) {
matrix[i][j] = 0;
}
}
}
}
};
<commit_msg>Update setMatrixZeroes.cpp<commit_after>// Source : https://leetcode.com/problems/set-matrix-zeroes/
// Author : Siyuan Xu
// Date : 2015-08-12
/**********************************************************************************
*
* Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
*
* click to show follow up.
*
* Follow up:
*
* Did you use extra space?
* A straight forward solution using O(mn) space is probably a bad idea.
* A simple improvement uses O(m + n) space, but still not the best solution.
* Could you devise a constant space solution?
*
*
**********************************************************************************/
//in place
//88ms(good)
class Solution1 {
public:
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
bool colZero = false;
for (int i = 0; i < m; i++) {
if (matrix[i][0] == 0) colZero = true;
for (int j = 1; j < n; j++) {
if (matrix[i][j] == 0)
matrix[i][0] = matrix[0][j] = 0;
}
}
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 1; j--) {
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
}
if (colZero) {
matrix[i][0] = 0;
}
}
}
};
//helper space
//84ms(best)
class Solution2 {
public:
void setZeroes(vector<vector<int>>& matrix) {
if (matrix.empty()) return;
int m = matrix.size(), n = matrix[0].size();
vector<bool> row(m, false);
vector<bool> col(n, false);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0)
row[i] = col[j] = true;
}
}
for (int i = 0; i < m; i++) {
if (row[i]) {
fill(matrix[i].begin(), matrix[i].end(), 0);
}
}
for (int j = 0; j < n; j++) {
if (col[j]) {
for (int i = 0; i < m; i++) {
matrix[i][j] = 0;
}
}
}
}
};
<|endoftext|> |
<commit_before>#include "AudioNodeOutput.h"
AudioNodeOutput::AudioNodeOutput(AudioNode* owner, int* ptr) : AudioNode() {
_owner = owner;
_ptr = ptr;
_output = NULL;
_value = 0;
}
void AudioNodeOutput::connect(AudioNode* destination) {
}
void AudioNodeOutput::disconnect(AudioNode* destination) {
}
void AudioNodeOutput::process(int& sample) {
_value = 0;
_owner->process();
_value = *_ptr;
// if(_value > 0x7FFFFFFF) _value = 0x7FFFFFFF; //truncate to upper limit of 32bit signed integers
// else if(_value < -0x80000000) _value = -0x80000000; //truncate to lower limit of 32bit signed integers
sample = _value;
}
int AudioNodeOutput::getValue() {
return _value;
}
AudioNode* AudioNodeOutput::getOutput() {
return _output;
}<commit_msg>added connect and disconnect to AudioNodeOutput<commit_after>#include "AudioNodeOutput.h"
AudioNodeOutput::AudioNodeOutput(AudioNode* owner, int* ptr) : AudioNode() {
_owner = owner;
_ptr = ptr;
_output = NULL;
_value = 0;
}
void AudioNodeOutput::connect(AudioNode* destination) {
_output = destination;
destination->hook(this);
}
void AudioNodeOutput::disconnect(AudioNode* destination) {
if(destination == _output) destination->unhook(this);
}
void AudioNodeOutput::process(int& sample) {
_value = 0;
_owner->process();
_value = *_ptr;
// if(_value > 0x7FFFFFFF) _value = 0x7FFFFFFF; //truncate to upper limit of 32bit signed integers
// else if(_value < -0x80000000) _value = -0x80000000; //truncate to lower limit of 32bit signed integers
sample = _value;
}
int AudioNodeOutput::getValue() {
return _value;
}
AudioNode* AudioNodeOutput::getOutput() {
return _output;
}<|endoftext|> |
<commit_before>#include <nan.h>
#include <string>
#include <cstring>
#include <vector>
#include <stdlib.h> // atoi
#include "node_blf.h"
#define NODE_LESS_THAN (!(NODE_VERSION_AT_LEAST(0, 5, 4)))
using namespace v8;
using namespace node;
namespace {
bool ValidateSalt(const char* salt) {
if (!salt || *salt != '$') {
return false;
}
// discard $
salt++;
if (*salt > BCRYPT_VERSION) {
return false;
}
if (salt[1] != '$') {
switch (salt[1]) {
case 'a':
salt++;
break;
default:
return false;
}
}
// discard version + $
salt += 2;
if (salt[2] != '$') {
return false;
}
int n = atoi(salt);
if (n > 31 || n < 0) {
return false;
}
if (((uint8_t)1 << (uint8_t)n) < BCRYPT_MINROUNDS) {
return false;
}
salt += 3;
if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT) {
return false;
}
return true;
}
/* SALT GENERATION */
class SaltAsyncWorker : public NanAsyncWorker {
public:
SaltAsyncWorker(NanCallback *callback, std::string seed, ssize_t rounds)
: NanAsyncWorker(callback), seed(seed), rounds(rounds) {
}
~SaltAsyncWorker() {}
void Execute() {
char salt[_SALT_LEN];
bcrypt_gensalt(rounds, (u_int8_t *)&seed[0], salt);
this->salt = std::string(salt);
}
void HandleOKCallback() {
NanScope();
Handle<Value> argv[2];
argv[0] = NanUndefined();
argv[1] = Encode(salt.c_str(), salt.size(), BINARY);
callback->Call(2, argv);
}
private:
std::string seed;
std::string salt;
ssize_t rounds;
};
NAN_METHOD(GenerateSalt) {
NanScope();
if (args.Length() < 3) {
NanThrowError(Exception::TypeError(NanNew("3 arguments expected")));
NanReturnUndefined();
}
if (!Buffer::HasInstance(args[1]) || Buffer::Length(args[1].As<Object>()) != 16) {
NanThrowError(Exception::TypeError(NanNew("Second argument must be a 16 byte Buffer")));
NanReturnUndefined();
}
const ssize_t rounds = args[0]->Int32Value();
Local<Object> seed = args[1].As<Object>();
Local<Function> callback = Local<Function>::Cast(args[2]);
SaltAsyncWorker* saltWorker = new SaltAsyncWorker(new NanCallback(callback),
std::string(Buffer::Data(seed), 16), rounds);
NanAsyncQueueWorker(saltWorker);
NanReturnUndefined();
}
NAN_METHOD(GenerateSaltSync) {
NanScope();
if (args.Length() < 2) {
NanThrowError(Exception::TypeError(NanNew("2 arguments expected")));
NanReturnUndefined();
}
if (!Buffer::HasInstance(args[1]) || Buffer::Length(args[1].As<Object>()) != 16) {
NanThrowError(Exception::TypeError(NanNew("Second argument must be a 16 byte Buffer")));
NanReturnUndefined();
}
const ssize_t rounds = args[0]->Int32Value();
u_int8_t* seed = (u_int8_t*)Buffer::Data(args[1].As<Object>());
char salt[_SALT_LEN];
bcrypt_gensalt(rounds, seed, salt);
NanReturnValue(Encode(salt, strlen(salt), BINARY));
}
/* ENCRYPT DATA - USED TO BE HASHPW */
class EncryptAsyncWorker : public NanAsyncWorker {
public:
EncryptAsyncWorker(NanCallback *callback, std::string input, std::string salt)
: NanAsyncWorker(callback), input(input), salt(salt) {
}
~EncryptAsyncWorker() {}
void Execute() {
if (!(ValidateSalt(salt.c_str()))) {
error = "Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue";
}
char bcrypted[_PASSWORD_LEN];
bcrypt(input.c_str(), salt.c_str(), bcrypted);
output = std::string(bcrypted);
}
void HandleOKCallback() {
NanScope();
Handle<Value> argv[2];
if (!error.empty()) {
argv[0] = Exception::Error(NanNew(error.c_str()));
argv[1] = NanUndefined();
} else {
argv[0] = NanUndefined();
argv[1] = Encode(output.c_str(), output.size(), BINARY);
}
callback->Call(2, argv);
}
private:
std::string input;
std::string salt;
std::string error;
std::string output;
};
NAN_METHOD(Encrypt) {
NanScope();
if (args.Length() < 3) {
NanThrowError(Exception::TypeError(NanNew("3 arguments expected")));
NanReturnUndefined();
}
String::Utf8Value data(args[0]->ToString());
String::Utf8Value salt(args[1]->ToString());
Local<Function> callback = Local<Function>::Cast(args[2]);
EncryptAsyncWorker* encryptWorker = new EncryptAsyncWorker(new NanCallback(callback),
std::string(*data), std::string(*salt));
NanAsyncQueueWorker(encryptWorker);
NanReturnUndefined();
}
NAN_METHOD(EncryptSync) {
NanScope();
if (args.Length() < 2) {
NanThrowError(Exception::TypeError(NanNew("2 arguments expected")));
NanReturnUndefined();
}
String::Utf8Value data(args[0]->ToString());
String::Utf8Value salt(args[1]->ToString());
if (!(ValidateSalt(*salt))) {
NanThrowError("Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue");
NanReturnUndefined();
}
char bcrypted[_PASSWORD_LEN];
bcrypt(*data, *salt, bcrypted);
NanReturnValue(Encode(bcrypted, strlen(bcrypted), BINARY));
}
/* COMPARATOR */
NAN_INLINE bool CompareStrings(const char* s1, const char* s2) {
bool eq = true;
int s1_len = strlen(s1);
int s2_len = strlen(s2);
if (s1_len != s2_len) {
eq = false;
}
const int max_len = (s2_len < s1_len) ? s1_len : s2_len;
// to prevent timing attacks, should check entire string
// don't exit after found to be false
for (int i = 0; i < max_len; ++i) {
if (s1_len >= i && s2_len >= i && s1[i] != s2[i]) {
eq = false;
}
}
return eq;
}
class CompareAsyncWorker : public NanAsyncWorker {
public:
CompareAsyncWorker(NanCallback *callback, std::string input, std::string encrypted)
: NanAsyncWorker(callback), input(input), encrypted(encrypted) {
result = false;
}
~CompareAsyncWorker() {}
void Execute() {
char bcrypted[_PASSWORD_LEN];
if (ValidateSalt(encrypted.c_str())) {
bcrypt(input.c_str(), encrypted.c_str(), bcrypted);
result = CompareStrings(bcrypted, encrypted.c_str());
}
}
void HandleOKCallback() {
NanScope();
Handle<Value> argv[2];
argv[0] = NanUndefined();
argv[1] = NanNew<Boolean>(result);
callback->Call(2, argv);
}
private:
std::string input;
std::string encrypted;
bool result;
};
NAN_METHOD(Compare) {
NanScope();
if (args.Length() < 3) {
NanThrowError(Exception::TypeError(NanNew("3 arguments expected")));
NanReturnUndefined();
}
String::Utf8Value input(args[0]->ToString());
String::Utf8Value encrypted(args[1]->ToString());
Local<Function> callback = Local<Function>::Cast(args[2]);
CompareAsyncWorker* compareWorker = new CompareAsyncWorker(new NanCallback(callback),
std::string(*input), std::string(*encrypted));
NanAsyncQueueWorker(compareWorker);
NanReturnUndefined();
}
NAN_METHOD(CompareSync) {
NanScope();
if (args.Length() < 2) {
NanThrowError(Exception::TypeError(NanNew("2 arguments expected")));
NanReturnUndefined();
}
String::Utf8Value pw(args[0]->ToString());
String::Utf8Value hash(args[1]->ToString());
char bcrypted[_PASSWORD_LEN];
if (ValidateSalt(*hash)) {
bcrypt(*pw, *hash, bcrypted);
NanReturnValue(NanNew<Boolean>(CompareStrings(bcrypted, *hash)));
} else {
NanReturnValue(NanFalse());
}
}
NAN_METHOD(GetRounds) {
NanScope();
if (args.Length() < 1) {
NanThrowError(Exception::TypeError(NanNew("1 argument expected")));
NanReturnUndefined();
}
String::Utf8Value hash(args[0]->ToString());
u_int32_t rounds;
if (!(rounds = bcrypt_get_rounds(*hash))) {
NanThrowError("invalid hash provided");
NanReturnUndefined();
}
NanReturnValue(NanNew(rounds));
}
} // anonymous namespace
// bind the bcrypt module
extern "C" void init(Handle<Object> target) {
NanScope();
NODE_SET_METHOD(target, "gen_salt_sync", GenerateSaltSync);
NODE_SET_METHOD(target, "encrypt_sync", EncryptSync);
NODE_SET_METHOD(target, "compare_sync", CompareSync);
NODE_SET_METHOD(target, "get_rounds", GetRounds);
NODE_SET_METHOD(target, "gen_salt", GenerateSalt);
NODE_SET_METHOD(target, "encrypt", Encrypt);
NODE_SET_METHOD(target, "compare", Compare);
};
NODE_MODULE(bcrypt_lib, init);
<commit_msg>fixed deprecated warning for the Encode API<commit_after>#include <nan.h>
#include <string>
#include <cstring>
#include <vector>
#include <stdlib.h> // atoi
#include "node_blf.h"
#define NODE_LESS_THAN (!(NODE_VERSION_AT_LEAST(0, 5, 4)))
using namespace v8;
using namespace node;
namespace {
bool ValidateSalt(const char* salt) {
if (!salt || *salt != '$') {
return false;
}
// discard $
salt++;
if (*salt > BCRYPT_VERSION) {
return false;
}
if (salt[1] != '$') {
switch (salt[1]) {
case 'a':
salt++;
break;
default:
return false;
}
}
// discard version + $
salt += 2;
if (salt[2] != '$') {
return false;
}
int n = atoi(salt);
if (n > 31 || n < 0) {
return false;
}
if (((uint8_t)1 << (uint8_t)n) < BCRYPT_MINROUNDS) {
return false;
}
salt += 3;
if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT) {
return false;
}
return true;
}
/* SALT GENERATION */
class SaltAsyncWorker : public NanAsyncWorker {
public:
SaltAsyncWorker(NanCallback *callback, std::string seed, ssize_t rounds)
: NanAsyncWorker(callback), seed(seed), rounds(rounds) {
}
~SaltAsyncWorker() {}
void Execute() {
char salt[_SALT_LEN];
bcrypt_gensalt(rounds, (u_int8_t *)&seed[0], salt);
this->salt = std::string(salt);
}
void HandleOKCallback() {
NanScope();
Handle<Value> argv[2];
argv[0] = NanUndefined();
argv[1] = NanEncode(salt.c_str(), salt.size(), Nan::BINARY);
callback->Call(2, argv);
}
private:
std::string seed;
std::string salt;
ssize_t rounds;
};
NAN_METHOD(GenerateSalt) {
NanScope();
if (args.Length() < 3) {
NanThrowError(Exception::TypeError(NanNew("3 arguments expected")));
NanReturnUndefined();
}
if (!Buffer::HasInstance(args[1]) || Buffer::Length(args[1].As<Object>()) != 16) {
NanThrowError(Exception::TypeError(NanNew("Second argument must be a 16 byte Buffer")));
NanReturnUndefined();
}
const ssize_t rounds = args[0]->Int32Value();
Local<Object> seed = args[1].As<Object>();
Local<Function> callback = Local<Function>::Cast(args[2]);
SaltAsyncWorker* saltWorker = new SaltAsyncWorker(new NanCallback(callback),
std::string(Buffer::Data(seed), 16), rounds);
NanAsyncQueueWorker(saltWorker);
NanReturnUndefined();
}
NAN_METHOD(GenerateSaltSync) {
NanScope();
if (args.Length() < 2) {
NanThrowError(Exception::TypeError(NanNew("2 arguments expected")));
NanReturnUndefined();
}
if (!Buffer::HasInstance(args[1]) || Buffer::Length(args[1].As<Object>()) != 16) {
NanThrowError(Exception::TypeError(NanNew("Second argument must be a 16 byte Buffer")));
NanReturnUndefined();
}
const ssize_t rounds = args[0]->Int32Value();
u_int8_t* seed = (u_int8_t*)Buffer::Data(args[1].As<Object>());
char salt[_SALT_LEN];
bcrypt_gensalt(rounds, seed, salt);
NanReturnValue(NanEncode(salt, strlen(salt), Nan::BINARY));
}
/* ENCRYPT DATA - USED TO BE HASHPW */
class EncryptAsyncWorker : public NanAsyncWorker {
public:
EncryptAsyncWorker(NanCallback *callback, std::string input, std::string salt)
: NanAsyncWorker(callback), input(input), salt(salt) {
}
~EncryptAsyncWorker() {}
void Execute() {
if (!(ValidateSalt(salt.c_str()))) {
error = "Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue";
}
char bcrypted[_PASSWORD_LEN];
bcrypt(input.c_str(), salt.c_str(), bcrypted);
output = std::string(bcrypted);
}
void HandleOKCallback() {
NanScope();
Handle<Value> argv[2];
if (!error.empty()) {
argv[0] = Exception::Error(NanNew(error.c_str()));
argv[1] = NanUndefined();
} else {
argv[0] = NanUndefined();
argv[1] = NanEncode(output.c_str(), output.size(), Nan::BINARY);
}
callback->Call(2, argv);
}
private:
std::string input;
std::string salt;
std::string error;
std::string output;
};
NAN_METHOD(Encrypt) {
NanScope();
if (args.Length() < 3) {
NanThrowError(Exception::TypeError(NanNew("3 arguments expected")));
NanReturnUndefined();
}
String::Utf8Value data(args[0]->ToString());
String::Utf8Value salt(args[1]->ToString());
Local<Function> callback = Local<Function>::Cast(args[2]);
EncryptAsyncWorker* encryptWorker = new EncryptAsyncWorker(new NanCallback(callback),
std::string(*data), std::string(*salt));
NanAsyncQueueWorker(encryptWorker);
NanReturnUndefined();
}
NAN_METHOD(EncryptSync) {
NanScope();
if (args.Length() < 2) {
NanThrowError(Exception::TypeError(NanNew("2 arguments expected")));
NanReturnUndefined();
}
String::Utf8Value data(args[0]->ToString());
String::Utf8Value salt(args[1]->ToString());
if (!(ValidateSalt(*salt))) {
NanThrowError("Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue");
NanReturnUndefined();
}
char bcrypted[_PASSWORD_LEN];
bcrypt(*data, *salt, bcrypted);
NanReturnValue(NanEncode(bcrypted, strlen(bcrypted), Nan::BINARY));
}
/* COMPARATOR */
NAN_INLINE bool CompareStrings(const char* s1, const char* s2) {
bool eq = true;
int s1_len = strlen(s1);
int s2_len = strlen(s2);
if (s1_len != s2_len) {
eq = false;
}
const int max_len = (s2_len < s1_len) ? s1_len : s2_len;
// to prevent timing attacks, should check entire string
// don't exit after found to be false
for (int i = 0; i < max_len; ++i) {
if (s1_len >= i && s2_len >= i && s1[i] != s2[i]) {
eq = false;
}
}
return eq;
}
class CompareAsyncWorker : public NanAsyncWorker {
public:
CompareAsyncWorker(NanCallback *callback, std::string input, std::string encrypted)
: NanAsyncWorker(callback), input(input), encrypted(encrypted) {
result = false;
}
~CompareAsyncWorker() {}
void Execute() {
char bcrypted[_PASSWORD_LEN];
if (ValidateSalt(encrypted.c_str())) {
bcrypt(input.c_str(), encrypted.c_str(), bcrypted);
result = CompareStrings(bcrypted, encrypted.c_str());
}
}
void HandleOKCallback() {
NanScope();
Handle<Value> argv[2];
argv[0] = NanUndefined();
argv[1] = NanNew<Boolean>(result);
callback->Call(2, argv);
}
private:
std::string input;
std::string encrypted;
bool result;
};
NAN_METHOD(Compare) {
NanScope();
if (args.Length() < 3) {
NanThrowError(Exception::TypeError(NanNew("3 arguments expected")));
NanReturnUndefined();
}
String::Utf8Value input(args[0]->ToString());
String::Utf8Value encrypted(args[1]->ToString());
Local<Function> callback = Local<Function>::Cast(args[2]);
CompareAsyncWorker* compareWorker = new CompareAsyncWorker(new NanCallback(callback),
std::string(*input), std::string(*encrypted));
NanAsyncQueueWorker(compareWorker);
NanReturnUndefined();
}
NAN_METHOD(CompareSync) {
NanScope();
if (args.Length() < 2) {
NanThrowError(Exception::TypeError(NanNew("2 arguments expected")));
NanReturnUndefined();
}
String::Utf8Value pw(args[0]->ToString());
String::Utf8Value hash(args[1]->ToString());
char bcrypted[_PASSWORD_LEN];
if (ValidateSalt(*hash)) {
bcrypt(*pw, *hash, bcrypted);
NanReturnValue(NanNew<Boolean>(CompareStrings(bcrypted, *hash)));
} else {
NanReturnValue(NanFalse());
}
}
NAN_METHOD(GetRounds) {
NanScope();
if (args.Length() < 1) {
NanThrowError(Exception::TypeError(NanNew("1 argument expected")));
NanReturnUndefined();
}
String::Utf8Value hash(args[0]->ToString());
u_int32_t rounds;
if (!(rounds = bcrypt_get_rounds(*hash))) {
NanThrowError("invalid hash provided");
NanReturnUndefined();
}
NanReturnValue(NanNew(rounds));
}
} // anonymous namespace
// bind the bcrypt module
extern "C" void init(Handle<Object> target) {
NanScope();
NODE_SET_METHOD(target, "gen_salt_sync", GenerateSaltSync);
NODE_SET_METHOD(target, "encrypt_sync", EncryptSync);
NODE_SET_METHOD(target, "compare_sync", CompareSync);
NODE_SET_METHOD(target, "get_rounds", GetRounds);
NODE_SET_METHOD(target, "gen_salt", GenerateSalt);
NODE_SET_METHOD(target, "encrypt", Encrypt);
NODE_SET_METHOD(target, "compare", Compare);
};
NODE_MODULE(bcrypt_lib, init);
<|endoftext|> |
<commit_before>//======- X86RetpolineThunks.cpp - Construct retpoline thunks for x86 --=====//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// Pass that injects an MI thunk implementing a "retpoline". This is
/// a RET-implemented trampoline that is used to lower indirect calls in a way
/// that prevents speculation on some x86 processors and can be used to mitigate
/// security vulnerabilities due to targeted speculative execution and side
/// channels such as CVE-2017-5715.
///
/// TODO(chandlerc): All of this code could use better comments and
/// documentation.
///
//===----------------------------------------------------------------------===//
#include "X86.h"
#include "X86InstrBuilder.h"
#include "X86Subtarget.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "x86-retpoline-thunks"
static const char ThunkNamePrefix[] = "__llvm_retpoline_";
static const char R11ThunkName[] = "__llvm_retpoline_r11";
static const char EAXThunkName[] = "__llvm_retpoline_eax";
static const char ECXThunkName[] = "__llvm_retpoline_ecx";
static const char EDXThunkName[] = "__llvm_retpoline_edx";
static const char EDIThunkName[] = "__llvm_retpoline_edi";
namespace {
class X86RetpolineThunks : public MachineFunctionPass {
public:
static char ID;
X86RetpolineThunks() : MachineFunctionPass(ID) {}
StringRef getPassName() const override { return "X86 Retpoline Thunks"; }
bool doInitialization(Module &M) override;
bool runOnMachineFunction(MachineFunction &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
MachineFunctionPass::getAnalysisUsage(AU);
AU.addRequired<MachineModuleInfo>();
AU.addPreserved<MachineModuleInfo>();
}
private:
MachineModuleInfo *MMI;
const TargetMachine *TM;
bool Is64Bit;
const X86Subtarget *STI;
const X86InstrInfo *TII;
bool InsertedThunks;
void createThunkFunction(Module &M, StringRef Name);
void insertRegReturnAddrClobber(MachineBasicBlock &MBB, unsigned Reg);
void insert32BitPushReturnAddrClobber(MachineBasicBlock &MBB);
void populateThunk(MachineFunction &MF, Optional<unsigned> Reg = None);
};
} // end anonymous namespace
FunctionPass *llvm::createX86RetpolineThunksPass() {
return new X86RetpolineThunks();
}
char X86RetpolineThunks::ID = 0;
bool X86RetpolineThunks::doInitialization(Module &M) {
InsertedThunks = false;
return false;
}
bool X86RetpolineThunks::runOnMachineFunction(MachineFunction &MF) {
DEBUG(dbgs() << getPassName() << '\n');
TM = &MF.getTarget();;
STI = &MF.getSubtarget<X86Subtarget>();
TII = STI->getInstrInfo();
Is64Bit = TM->getTargetTriple().getArch() == Triple::x86_64;
MMI = &getAnalysis<MachineModuleInfo>();
Module &M = const_cast<Module &>(*MMI->getModule());
// If this function is not a thunk, check to see if we need to insert
// a thunk.
if (!MF.getName().startswith(ThunkNamePrefix)) {
// If we've already inserted a thunk, nothing else to do.
if (InsertedThunks)
return false;
// Only add a thunk if one of the functions has the retpoline feature
// enabled in its subtarget, and doesn't enable external thunks.
// FIXME: Conditionalize on indirect calls so we don't emit a thunk when
// nothing will end up calling it.
// FIXME: It's a little silly to look at every function just to enumerate
// the subtargets, but eventually we'll want to look at them for indirect
// calls, so maybe this is OK.
if (!STI->useRetpoline() || STI->useRetpolineExternalThunk())
return false;
// Otherwise, we need to insert the thunk.
// WARNING: This is not really a well behaving thing to do in a function
// pass. We extract the module and insert a new function (and machine
// function) directly into the module.
if (Is64Bit)
createThunkFunction(M, R11ThunkName);
else
for (StringRef Name :
{EAXThunkName, ECXThunkName, EDXThunkName, EDIThunkName})
createThunkFunction(M, Name);
InsertedThunks = true;
return true;
}
// If this *is* a thunk function, we need to populate it with the correct MI.
if (Is64Bit) {
assert(MF.getName() == "__llvm_retpoline_r11" &&
"Should only have an r11 thunk on 64-bit targets");
// __llvm_retpoline_r11:
// callq .Lr11_call_target
// .Lr11_capture_spec:
// pause
// lfence
// jmp .Lr11_capture_spec
// .align 16
// .Lr11_call_target:
// movq %r11, (%rsp)
// retq
populateThunk(MF, X86::R11);
} else {
// For 32-bit targets we need to emit a collection of thunks for various
// possible scratch registers as well as a fallback that uses EDI, which is
// normally callee saved.
// __llvm_retpoline_eax:
// calll .Leax_call_target
// .Leax_capture_spec:
// pause
// jmp .Leax_capture_spec
// .align 16
// .Leax_call_target:
// movl %eax, (%esp) # Clobber return addr
// retl
//
// __llvm_retpoline_ecx:
// ... # Same setup
// movl %ecx, (%esp)
// retl
//
// __llvm_retpoline_edx:
// ... # Same setup
// movl %edx, (%esp)
// retl
//
// __llvm_retpoline_edi:
// ... # Same setup
// movl %edi, (%esp)
// retl
if (MF.getName() == EAXThunkName)
populateThunk(MF, X86::EAX);
else if (MF.getName() == ECXThunkName)
populateThunk(MF, X86::ECX);
else if (MF.getName() == EDXThunkName)
populateThunk(MF, X86::EDX);
else if (MF.getName() == EDIThunkName)
populateThunk(MF, X86::EDI);
else
llvm_unreachable("Invalid thunk name on x86-32!");
}
return true;
}
void X86RetpolineThunks::createThunkFunction(Module &M, StringRef Name) {
assert(Name.startswith(ThunkNamePrefix) &&
"Created a thunk with an unexpected prefix!");
LLVMContext &Ctx = M.getContext();
auto Type = FunctionType::get(Type::getVoidTy(Ctx), false);
Function *F =
Function::Create(Type, GlobalValue::LinkOnceODRLinkage, Name, &M);
F->setVisibility(GlobalValue::HiddenVisibility);
F->setComdat(M.getOrInsertComdat(Name));
// Add Attributes so that we don't create a frame, unwind information, or
// inline.
AttrBuilder B;
B.addAttribute(llvm::Attribute::NoUnwind);
B.addAttribute(llvm::Attribute::Naked);
F->addAttributes(llvm::AttributeList::FunctionIndex, B);
// Populate our function a bit so that we can verify.
BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
IRBuilder<> Builder(Entry);
Builder.CreateRetVoid();
}
void X86RetpolineThunks::insertRegReturnAddrClobber(MachineBasicBlock &MBB,
unsigned Reg) {
const unsigned MovOpc = Is64Bit ? X86::MOV64mr : X86::MOV32mr;
const unsigned SPReg = Is64Bit ? X86::RSP : X86::ESP;
addRegOffset(BuildMI(&MBB, DebugLoc(), TII->get(MovOpc)), SPReg, false, 0)
.addReg(Reg);
}
void X86RetpolineThunks::insert32BitPushReturnAddrClobber(
MachineBasicBlock &MBB) {
// The instruction sequence we use to replace the return address without
// a scratch register is somewhat complicated:
// # Clear capture_spec from return address.
// addl $4, %esp
// # Top of stack words are: Callee, RA. Exchange Callee and RA.
// pushl 4(%esp) # Push callee
// pushl 4(%esp) # Push RA
// popl 8(%esp) # Pop RA to final RA
// popl (%esp) # Pop callee to next top of stack
// retl # Ret to callee
BuildMI(&MBB, DebugLoc(), TII->get(X86::ADD32ri), X86::ESP)
.addReg(X86::ESP)
.addImm(4);
addRegOffset(BuildMI(&MBB, DebugLoc(), TII->get(X86::PUSH32rmm)), X86::ESP,
false, 4);
addRegOffset(BuildMI(&MBB, DebugLoc(), TII->get(X86::PUSH32rmm)), X86::ESP,
false, 4);
addRegOffset(BuildMI(&MBB, DebugLoc(), TII->get(X86::POP32rmm)), X86::ESP,
false, 8);
addRegOffset(BuildMI(&MBB, DebugLoc(), TII->get(X86::POP32rmm)), X86::ESP,
false, 0);
}
void X86RetpolineThunks::populateThunk(MachineFunction &MF,
Optional<unsigned> Reg) {
// Set MF properties. We never use vregs...
MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
MachineBasicBlock *Entry = &MF.front();
Entry->clear();
MachineBasicBlock *CaptureSpec = MF.CreateMachineBasicBlock(Entry->getBasicBlock());
MachineBasicBlock *CallTarget = MF.CreateMachineBasicBlock(Entry->getBasicBlock());
MF.push_back(CaptureSpec);
MF.push_back(CallTarget);
const unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
const unsigned RetOpc = Is64Bit ? X86::RETQ : X86::RETL;
BuildMI(Entry, DebugLoc(), TII->get(CallOpc)).addMBB(CallTarget);
Entry->addSuccessor(CallTarget);
Entry->addSuccessor(CaptureSpec);
CallTarget->setHasAddressTaken();
// In the capture loop for speculation, we want to stop the processor from
// speculating as fast as possible. On Intel processors, the PAUSE instruction
// will block speculation without consuming any execution resources. On AMD
// processors, the PAUSE instruction is (essentially) a nop, so we also use an
// LFENCE instruction which they have advised will stop speculation as well
// with minimal resource utilization. We still end the capture with a jump to
// form an infinite loop to fully guarantee that no matter what implementation
// of the x86 ISA, speculating this code path never escapes.
BuildMI(CaptureSpec, DebugLoc(), TII->get(X86::PAUSE));
BuildMI(CaptureSpec, DebugLoc(), TII->get(X86::LFENCE));
BuildMI(CaptureSpec, DebugLoc(), TII->get(X86::JMP_1)).addMBB(CaptureSpec);
CaptureSpec->setHasAddressTaken();
CaptureSpec->addSuccessor(CaptureSpec);
CallTarget->setAlignment(4);
insertRegReturnAddrClobber(*CallTarget, *Reg);
BuildMI(CallTarget, DebugLoc(), TII->get(RetOpc));
}
<commit_msg>Merging r325085: ------------------------------------------------------------------------ r325085 | rnk | 2018-02-13 16:24:29 -0800 (Tue, 13 Feb 2018) | 3 lines<commit_after>//======- X86RetpolineThunks.cpp - Construct retpoline thunks for x86 --=====//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// Pass that injects an MI thunk implementing a "retpoline". This is
/// a RET-implemented trampoline that is used to lower indirect calls in a way
/// that prevents speculation on some x86 processors and can be used to mitigate
/// security vulnerabilities due to targeted speculative execution and side
/// channels such as CVE-2017-5715.
///
/// TODO(chandlerc): All of this code could use better comments and
/// documentation.
///
//===----------------------------------------------------------------------===//
#include "X86.h"
#include "X86InstrBuilder.h"
#include "X86Subtarget.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "x86-retpoline-thunks"
static const char ThunkNamePrefix[] = "__llvm_retpoline_";
static const char R11ThunkName[] = "__llvm_retpoline_r11";
static const char EAXThunkName[] = "__llvm_retpoline_eax";
static const char ECXThunkName[] = "__llvm_retpoline_ecx";
static const char EDXThunkName[] = "__llvm_retpoline_edx";
static const char EDIThunkName[] = "__llvm_retpoline_edi";
namespace {
class X86RetpolineThunks : public MachineFunctionPass {
public:
static char ID;
X86RetpolineThunks() : MachineFunctionPass(ID) {}
StringRef getPassName() const override { return "X86 Retpoline Thunks"; }
bool doInitialization(Module &M) override;
bool runOnMachineFunction(MachineFunction &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
MachineFunctionPass::getAnalysisUsage(AU);
AU.addRequired<MachineModuleInfo>();
AU.addPreserved<MachineModuleInfo>();
}
private:
MachineModuleInfo *MMI;
const TargetMachine *TM;
bool Is64Bit;
const X86Subtarget *STI;
const X86InstrInfo *TII;
bool InsertedThunks;
void createThunkFunction(Module &M, StringRef Name);
void insertRegReturnAddrClobber(MachineBasicBlock &MBB, unsigned Reg);
void populateThunk(MachineFunction &MF, Optional<unsigned> Reg = None);
};
} // end anonymous namespace
FunctionPass *llvm::createX86RetpolineThunksPass() {
return new X86RetpolineThunks();
}
char X86RetpolineThunks::ID = 0;
bool X86RetpolineThunks::doInitialization(Module &M) {
InsertedThunks = false;
return false;
}
bool X86RetpolineThunks::runOnMachineFunction(MachineFunction &MF) {
DEBUG(dbgs() << getPassName() << '\n');
TM = &MF.getTarget();;
STI = &MF.getSubtarget<X86Subtarget>();
TII = STI->getInstrInfo();
Is64Bit = TM->getTargetTriple().getArch() == Triple::x86_64;
MMI = &getAnalysis<MachineModuleInfo>();
Module &M = const_cast<Module &>(*MMI->getModule());
// If this function is not a thunk, check to see if we need to insert
// a thunk.
if (!MF.getName().startswith(ThunkNamePrefix)) {
// If we've already inserted a thunk, nothing else to do.
if (InsertedThunks)
return false;
// Only add a thunk if one of the functions has the retpoline feature
// enabled in its subtarget, and doesn't enable external thunks.
// FIXME: Conditionalize on indirect calls so we don't emit a thunk when
// nothing will end up calling it.
// FIXME: It's a little silly to look at every function just to enumerate
// the subtargets, but eventually we'll want to look at them for indirect
// calls, so maybe this is OK.
if (!STI->useRetpoline() || STI->useRetpolineExternalThunk())
return false;
// Otherwise, we need to insert the thunk.
// WARNING: This is not really a well behaving thing to do in a function
// pass. We extract the module and insert a new function (and machine
// function) directly into the module.
if (Is64Bit)
createThunkFunction(M, R11ThunkName);
else
for (StringRef Name :
{EAXThunkName, ECXThunkName, EDXThunkName, EDIThunkName})
createThunkFunction(M, Name);
InsertedThunks = true;
return true;
}
// If this *is* a thunk function, we need to populate it with the correct MI.
if (Is64Bit) {
assert(MF.getName() == "__llvm_retpoline_r11" &&
"Should only have an r11 thunk on 64-bit targets");
// __llvm_retpoline_r11:
// callq .Lr11_call_target
// .Lr11_capture_spec:
// pause
// lfence
// jmp .Lr11_capture_spec
// .align 16
// .Lr11_call_target:
// movq %r11, (%rsp)
// retq
populateThunk(MF, X86::R11);
} else {
// For 32-bit targets we need to emit a collection of thunks for various
// possible scratch registers as well as a fallback that uses EDI, which is
// normally callee saved.
// __llvm_retpoline_eax:
// calll .Leax_call_target
// .Leax_capture_spec:
// pause
// jmp .Leax_capture_spec
// .align 16
// .Leax_call_target:
// movl %eax, (%esp) # Clobber return addr
// retl
//
// __llvm_retpoline_ecx:
// ... # Same setup
// movl %ecx, (%esp)
// retl
//
// __llvm_retpoline_edx:
// ... # Same setup
// movl %edx, (%esp)
// retl
//
// __llvm_retpoline_edi:
// ... # Same setup
// movl %edi, (%esp)
// retl
if (MF.getName() == EAXThunkName)
populateThunk(MF, X86::EAX);
else if (MF.getName() == ECXThunkName)
populateThunk(MF, X86::ECX);
else if (MF.getName() == EDXThunkName)
populateThunk(MF, X86::EDX);
else if (MF.getName() == EDIThunkName)
populateThunk(MF, X86::EDI);
else
llvm_unreachable("Invalid thunk name on x86-32!");
}
return true;
}
void X86RetpolineThunks::createThunkFunction(Module &M, StringRef Name) {
assert(Name.startswith(ThunkNamePrefix) &&
"Created a thunk with an unexpected prefix!");
LLVMContext &Ctx = M.getContext();
auto Type = FunctionType::get(Type::getVoidTy(Ctx), false);
Function *F =
Function::Create(Type, GlobalValue::LinkOnceODRLinkage, Name, &M);
F->setVisibility(GlobalValue::HiddenVisibility);
F->setComdat(M.getOrInsertComdat(Name));
// Add Attributes so that we don't create a frame, unwind information, or
// inline.
AttrBuilder B;
B.addAttribute(llvm::Attribute::NoUnwind);
B.addAttribute(llvm::Attribute::Naked);
F->addAttributes(llvm::AttributeList::FunctionIndex, B);
// Populate our function a bit so that we can verify.
BasicBlock *Entry = BasicBlock::Create(Ctx, "entry", F);
IRBuilder<> Builder(Entry);
Builder.CreateRetVoid();
}
void X86RetpolineThunks::insertRegReturnAddrClobber(MachineBasicBlock &MBB,
unsigned Reg) {
const unsigned MovOpc = Is64Bit ? X86::MOV64mr : X86::MOV32mr;
const unsigned SPReg = Is64Bit ? X86::RSP : X86::ESP;
addRegOffset(BuildMI(&MBB, DebugLoc(), TII->get(MovOpc)), SPReg, false, 0)
.addReg(Reg);
}
void X86RetpolineThunks::populateThunk(MachineFunction &MF,
Optional<unsigned> Reg) {
// Set MF properties. We never use vregs...
MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
MachineBasicBlock *Entry = &MF.front();
Entry->clear();
MachineBasicBlock *CaptureSpec = MF.CreateMachineBasicBlock(Entry->getBasicBlock());
MachineBasicBlock *CallTarget = MF.CreateMachineBasicBlock(Entry->getBasicBlock());
MF.push_back(CaptureSpec);
MF.push_back(CallTarget);
const unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
const unsigned RetOpc = Is64Bit ? X86::RETQ : X86::RETL;
BuildMI(Entry, DebugLoc(), TII->get(CallOpc)).addMBB(CallTarget);
Entry->addSuccessor(CallTarget);
Entry->addSuccessor(CaptureSpec);
CallTarget->setHasAddressTaken();
// In the capture loop for speculation, we want to stop the processor from
// speculating as fast as possible. On Intel processors, the PAUSE instruction
// will block speculation without consuming any execution resources. On AMD
// processors, the PAUSE instruction is (essentially) a nop, so we also use an
// LFENCE instruction which they have advised will stop speculation as well
// with minimal resource utilization. We still end the capture with a jump to
// form an infinite loop to fully guarantee that no matter what implementation
// of the x86 ISA, speculating this code path never escapes.
BuildMI(CaptureSpec, DebugLoc(), TII->get(X86::PAUSE));
BuildMI(CaptureSpec, DebugLoc(), TII->get(X86::LFENCE));
BuildMI(CaptureSpec, DebugLoc(), TII->get(X86::JMP_1)).addMBB(CaptureSpec);
CaptureSpec->setHasAddressTaken();
CaptureSpec->addSuccessor(CaptureSpec);
CallTarget->setAlignment(4);
insertRegReturnAddrClobber(*CallTarget, *Reg);
BuildMI(CallTarget, DebugLoc(), TII->get(RetOpc));
}
<|endoftext|> |
<commit_before>/**
* @file dem_stream_file.hpp
* @author Robin Dietrich <me (at) invokr (dot) org>
* @version 1.0
*
* @par License
* Alice Replay Parser
* Copyright 2014 Robin Dietrich
*
* 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 <snappy.h>
#include <alice/demo.pb.h>
#include <alice/dem_stream_file.hpp>
namespace dota {
void dem_stream_file::open(std::string path) {
// open stream
stream.open(path.c_str(), std::ifstream::in | std::ifstream::binary);
// check if it was successful
if (!stream.is_open())
BOOST_THROW_EXCEPTION(demFileNotAccessible()
<< EArg<1>::info(path)
);
// check filesize
const std::streampos fstart = stream.tellg();
stream.seekg (0, std::ios::end);
std::streampos fsize = stream.tellg() - fstart;
stream.seekg(fstart);
if (fsize < sizeof(demHeader_t))
BOOST_THROW_EXCEPTION((demFileTooSmall()
<< EArg<1>::info(path)
<< EArgT<2, std::streampos>::info(fsize)
<< EArgT<3, std::size_t>::info(sizeof(demHeader_t))
));
// verify the header
demHeader_t head;
stream.read((char*) &head, sizeof(demHeader_t));
if(strcmp(head.headerid, DOTA_DEMHEADERID))
BOOST_THROW_EXCEPTION(demHeaderMismatch()
<< EArg<1>::info(path)
<< EArg<2>::info(std::string(head.headerid, 8))
<< EArg<3>::info(std::string(DOTA_DEMHEADERID))
);
// save path for later
file = path;
}
demMessage_t dem_stream_file::read(bool skip) {
// Make sure the buffers has been allocated
assert(buffer != nullptr);
assert(bufferSnappy != nullptr);
// Get type / tick / size
uint32_t type = readVarInt();
const bool compressed = type & DEM_IsCompressed;
type = (type & ~DEM_IsCompressed);
uint32_t tick = readVarInt();
uint32_t size = readVarInt();
// Check if this is the last message
if (parsingState == 1) parsingState = 2;
if (type == 0) parsingState = 1; // marks the message before the laste one
// skip messages if skip is set
if (skip) {
stream.seekg(size, std::ios::cur); // seek forward
return demMessage_t{false, 0, 0, nullptr, 0}; // return empty msg
}
// read into char array and convert to string
if (size > DOTA_DEM_BUFSIZE)
BOOST_THROW_EXCEPTION((demMessageToBig()
<< EArgT<1, std::size_t>::info(size)
));
demMessage_t msg {compressed, tick, type, nullptr, 0}; // return msg
stream.read(buffer, size);
// Check if we need to uncompress
if (compressed && snappy::IsValidCompressedBuffer(buffer, size)) {
std::size_t uSize;
// Check if we can get the output length
if (!snappy::GetUncompressedLength(buffer, size, &uSize)) {
BOOST_THROW_EXCEPTION((demInvalidCompression()
<< EArg<1>::info(file)
<< EArgT<2, std::streampos>::info(stream.gcount())
<< EArgT<3, std::size_t>::info(size)
<< EArgT<4, uint32_t>::info(type)
));
}
// Check if it fits in the buffer
if (uSize > DOTA_DEM_BUFSIZE)
BOOST_THROW_EXCEPTION((demMessageToBig()
<< EArgT<1, std::size_t>::info(uSize)
));
// Make sure its uncompressed
if (!snappy::RawUncompress(buffer, size, bufferSnappy))
BOOST_THROW_EXCEPTION((demInvalidCompression()
<< EArg<1>::info(file)
<< EArgT<2, std::streampos>::info(stream.gcount())
<< EArgT<3, std::size_t>::info(size)
<< EArgT<4, uint32_t>::info(type)
));
msg.msg = bufferSnappy;
msg.size = uSize;
} else {
msg.msg = buffer;
msg.size = size;
}
return msg;
}
uint32_t dem_stream_file::readVarInt() {
char buffer;
uint32_t count = 0;
uint32_t result = 0;
do {
if (count == 5) {
BOOST_THROW_EXCEPTION(demCorrupted()
<< EArg<1>::info(file)
);
} else if (!good()) {
BOOST_THROW_EXCEPTION(demUnexpectedEOF()
<< EArg<1>::info(file)
);
} else {
buffer = stream.get();
result |= (uint32_t)(buffer & 0x7F) << ( 7 * count );
++count;
}
} while (buffer & 0x80);
return result;
}
}<commit_msg>typo in header<commit_after>/**
* @file dem_stream_file.cpp
* @author Robin Dietrich <me (at) invokr (dot) org>
* @version 1.0
*
* @par License
* Alice Replay Parser
* Copyright 2014 Robin Dietrich
*
* 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 <snappy.h>
#include <alice/demo.pb.h>
#include <alice/dem_stream_file.hpp>
namespace dota {
void dem_stream_file::open(std::string path) {
// open stream
stream.open(path.c_str(), std::ifstream::in | std::ifstream::binary);
// check if it was successful
if (!stream.is_open())
BOOST_THROW_EXCEPTION(demFileNotAccessible()
<< EArg<1>::info(path)
);
// check filesize
const std::streampos fstart = stream.tellg();
stream.seekg (0, std::ios::end);
std::streampos fsize = stream.tellg() - fstart;
stream.seekg(fstart);
if (fsize < sizeof(demHeader_t))
BOOST_THROW_EXCEPTION((demFileTooSmall()
<< EArg<1>::info(path)
<< EArgT<2, std::streampos>::info(fsize)
<< EArgT<3, std::size_t>::info(sizeof(demHeader_t))
));
// verify the header
demHeader_t head;
stream.read((char*) &head, sizeof(demHeader_t));
if(strcmp(head.headerid, DOTA_DEMHEADERID))
BOOST_THROW_EXCEPTION(demHeaderMismatch()
<< EArg<1>::info(path)
<< EArg<2>::info(std::string(head.headerid, 8))
<< EArg<3>::info(std::string(DOTA_DEMHEADERID))
);
// save path for later
file = path;
}
demMessage_t dem_stream_file::read(bool skip) {
// Make sure the buffers has been allocated
assert(buffer != nullptr);
assert(bufferSnappy != nullptr);
// Get type / tick / size
uint32_t type = readVarInt();
const bool compressed = type & DEM_IsCompressed;
type = (type & ~DEM_IsCompressed);
uint32_t tick = readVarInt();
uint32_t size = readVarInt();
// Check if this is the last message
if (parsingState == 1) parsingState = 2;
if (type == 0) parsingState = 1; // marks the message before the laste one
// skip messages if skip is set
if (skip) {
stream.seekg(size, std::ios::cur); // seek forward
return demMessage_t{false, 0, 0, nullptr, 0}; // return empty msg
}
// read into char array and convert to string
if (size > DOTA_DEM_BUFSIZE)
BOOST_THROW_EXCEPTION((demMessageToBig()
<< EArgT<1, std::size_t>::info(size)
));
demMessage_t msg {compressed, tick, type, nullptr, 0}; // return msg
stream.read(buffer, size);
// Check if we need to uncompress
if (compressed && snappy::IsValidCompressedBuffer(buffer, size)) {
std::size_t uSize;
// Check if we can get the output length
if (!snappy::GetUncompressedLength(buffer, size, &uSize)) {
BOOST_THROW_EXCEPTION((demInvalidCompression()
<< EArg<1>::info(file)
<< EArgT<2, std::streampos>::info(stream.gcount())
<< EArgT<3, std::size_t>::info(size)
<< EArgT<4, uint32_t>::info(type)
));
}
// Check if it fits in the buffer
if (uSize > DOTA_DEM_BUFSIZE)
BOOST_THROW_EXCEPTION((demMessageToBig()
<< EArgT<1, std::size_t>::info(uSize)
));
// Make sure its uncompressed
if (!snappy::RawUncompress(buffer, size, bufferSnappy))
BOOST_THROW_EXCEPTION((demInvalidCompression()
<< EArg<1>::info(file)
<< EArgT<2, std::streampos>::info(stream.gcount())
<< EArgT<3, std::size_t>::info(size)
<< EArgT<4, uint32_t>::info(type)
));
msg.msg = bufferSnappy;
msg.size = uSize;
} else {
msg.msg = buffer;
msg.size = size;
}
return msg;
}
uint32_t dem_stream_file::readVarInt() {
char buffer;
uint32_t count = 0;
uint32_t result = 0;
do {
if (count == 5) {
BOOST_THROW_EXCEPTION(demCorrupted()
<< EArg<1>::info(file)
);
} else if (!good()) {
BOOST_THROW_EXCEPTION(demUnexpectedEOF()
<< EArg<1>::info(file)
);
} else {
buffer = stream.get();
result |= (uint32_t)(buffer & 0x7F) << ( 7 * count );
++count;
}
} while (buffer & 0x80);
return result;
}
}<|endoftext|> |
<commit_before>
/*
* Copyright 2008 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkFontHost.h"
SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,
const char famillyName[],
SkTypeface::Style style) {
SkDEBUGFAIL("SkFontHost::FindTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream*) {
SkDEBUGFAIL("SkFontHost::CreateTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::CreateTypefaceFromFile(char const*) {
SkDEBUGFAIL("SkFontHost::CreateTypefaceFromFile unimplemented");
return NULL;
}
// static
SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
uint32_t fontID,
SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
const uint32_t* glyphIDs,
uint32_t glyphIDsCount) {
SkDEBUGFAIL("SkFontHost::GetAdvancedTypefaceMetrics unimplemented");
return NULL;
}
void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
}
///////////////////////////////////////////////////////////////////////////////
SkStream* SkFontHost::OpenStream(uint32_t uniqueID) {
SkDEBUGFAIL("SkFontHost::OpenStream unimplemented");
return NULL;
}
size_t SkFontHost::GetFileName(SkFontID fontID, char path[], size_t length,
int32_t* index) {
SkDebugf("SkFontHost::GetFileName unimplemented\n");
return 0;
}
///////////////////////////////////////////////////////////////////////////////
void SkFontHost::Serialize(const SkTypeface* face, SkWStream* stream) {
SkDEBUGFAIL("SkFontHost::Serialize unimplemented");
}
SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
SkDEBUGFAIL("SkFontHost::Deserialize unimplemented");
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
SkDEBUGFAIL("SkFontHost::CreateScalarContext unimplemented");
return NULL;
}
SkFontID SkFontHost::NextLogicalFont(SkFontID currFontID, SkFontID origFontID) {
return 0;
}
<commit_msg>Fix compile error in SkFontHost_none.cpp Review URL: https://codereview.appspot.com/6501083<commit_after>
/*
* Copyright 2008 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkFontHost.h"
#include "SkScalerContext.h"
SkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,
const char famillyName[],
SkTypeface::Style style) {
SkDEBUGFAIL("SkFontHost::FindTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream*) {
SkDEBUGFAIL("SkFontHost::CreateTypeface unimplemented");
return NULL;
}
SkTypeface* SkFontHost::CreateTypefaceFromFile(char const*) {
SkDEBUGFAIL("SkFontHost::CreateTypefaceFromFile unimplemented");
return NULL;
}
// static
SkAdvancedTypefaceMetrics* SkFontHost::GetAdvancedTypefaceMetrics(
uint32_t fontID,
SkAdvancedTypefaceMetrics::PerGlyphInfo perGlyphInfo,
const uint32_t* glyphIDs,
uint32_t glyphIDsCount) {
SkDEBUGFAIL("SkFontHost::GetAdvancedTypefaceMetrics unimplemented");
return NULL;
}
void SkFontHost::FilterRec(SkScalerContext::Rec* rec) {
}
///////////////////////////////////////////////////////////////////////////////
SkStream* SkFontHost::OpenStream(uint32_t uniqueID) {
SkDEBUGFAIL("SkFontHost::OpenStream unimplemented");
return NULL;
}
size_t SkFontHost::GetFileName(SkFontID fontID, char path[], size_t length,
int32_t* index) {
SkDebugf("SkFontHost::GetFileName unimplemented\n");
return 0;
}
///////////////////////////////////////////////////////////////////////////////
void SkFontHost::Serialize(const SkTypeface* face, SkWStream* stream) {
SkDEBUGFAIL("SkFontHost::Serialize unimplemented");
}
SkTypeface* SkFontHost::Deserialize(SkStream* stream) {
SkDEBUGFAIL("SkFontHost::Deserialize unimplemented");
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
SkScalerContext* SkFontHost::CreateScalerContext(const SkDescriptor* desc) {
SkDEBUGFAIL("SkFontHost::CreateScalarContext unimplemented");
return NULL;
}
SkFontID SkFontHost::NextLogicalFont(SkFontID currFontID, SkFontID origFontID) {
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
*
* Released under the MIT license, see LICENSE.txt
*/
#include <string>
#include <cstring>
#include <sstream>
#include <set>
#include <iostream>
#include "hdf5Sequence.h"
#include "hdf5DNAIterator.h"
#include "defaultTopSegmentIterator.h"
#include "defaultBottomSegmentIterator.h"
#include "defaultColumnIterator.h"
#include "defaultRearrangement.h"
#include "defaultGappedTopSegmentIterator.h"
#include "defaultGappedBottomSegmentIterator.h"
using namespace std;
using namespace H5;
using namespace hal;
const size_t HDF5Sequence::startOffset = 0;
const size_t HDF5Sequence::lengthOffset = sizeof(hal_size_t);
const size_t HDF5Sequence::numTopSegmentsOffset = lengthOffset + sizeof(hal_size_t);
const size_t HDF5Sequence::numBottomSegmentsOffset = numTopSegmentsOffset + sizeof(hal_size_t);
const size_t HDF5Sequence::topSegmentArrayIndexOffset = numBottomSegmentsOffset + sizeof(hal_size_t);
const size_t HDF5Sequence::bottomSegmentArrayIndexOffset = topSegmentArrayIndexOffset + sizeof(hal_size_t);
const size_t HDF5Sequence::nameOffset = bottomSegmentArrayIndexOffset + sizeof(hal_size_t);
HDF5Sequence::HDF5Sequence(HDF5Genome* genome,
HDF5ExternalArray* array,
hal_index_t index) :
_array(array),
_index(index),
_genome(genome),
_cacheIndex(NULL_INDEX),
_startCache(NULL_INDEX),
_lengthCache(0)
{
}
HDF5Sequence::~HDF5Sequence()
{
}
// Some tools (ie maf export) access the same sequence
// info over and over again deep inside a loop. So I hack
// in a little cache, mostly to avoid copying the same string
// (name) out of hdf5.
inline void HDF5Sequence::refreshCache() const
{
if (_index != _cacheIndex)
{
_nameCache = _array->get(_index) + nameOffset;
_fullNameCache = _genome->getName() + '.' + _nameCache;
_startCache = _array->getValue<hal_size_t>(_index, startOffset);
_lengthCache = _array->getValue<hal_size_t>(_index, lengthOffset);
_cacheIndex = _index;
}
}
H5::CompType HDF5Sequence::dataType(hal_size_t maxNameLength)
{
// the in-memory representations and hdf5 representations
// don't necessarily have to be the same, but it simplifies
// testing for now.
assert(PredType::NATIVE_HSIZE.getSize() == sizeof(hal_size_t));
assert(PredType::NATIVE_CHAR.getSize() == sizeof(char));
StrType strType(PredType::NATIVE_CHAR, (maxNameLength + 1) * sizeof(char));
CompType dataType(nameOffset + strType.getSize());
dataType.insertMember("start", startOffset, PredType::NATIVE_HSIZE);
dataType.insertMember("length", lengthOffset, PredType::NATIVE_HSIZE);
dataType.insertMember("numSequences", numTopSegmentsOffset,
PredType::NATIVE_HSIZE);
dataType.insertMember("numBottomSegments", numBottomSegmentsOffset,
PredType::NATIVE_HSIZE);
dataType.insertMember("topSegmentArrayIndexOffset", topSegmentArrayIndexOffset,
PredType::NATIVE_HSIZE);
dataType.insertMember("bottomSegmentArrayIndexOffset", bottomSegmentArrayIndexOffset,
PredType::NATIVE_HSIZE);
dataType.insertMember("name", nameOffset, strType);
return dataType;
}
// SEQUENCE INTERFACE
const string& HDF5Sequence::getName() const
{
refreshCache();
return _nameCache;
}
const string& HDF5Sequence::getFullName() const
{
refreshCache();
return _fullNameCache;
}
const Genome* HDF5Sequence::getGenome() const
{
return _genome;
}
Genome* HDF5Sequence::getGenome()
{
return _genome;
}
hal_size_t HDF5Sequence::getStartPosition() const
{
refreshCache();
return _startCache;
}
hal_index_t HDF5Sequence::getArrayIndex() const
{
return _index;
}
hal_index_t HDF5Sequence::getTopSegmentArrayIndex() const
{
return (hal_index_t)
_array->getValue<hal_size_t>(_index, topSegmentArrayIndexOffset);
}
hal_index_t HDF5Sequence::getBottomSegmentArrayIndex() const
{
return (hal_index_t)
_array->getValue<hal_size_t>(_index, bottomSegmentArrayIndexOffset);
}
// SEGMENTED SEQUENCE INTERFACE
hal_size_t HDF5Sequence::getSequenceLength() const
{
refreshCache();
return _lengthCache;
}
hal_size_t HDF5Sequence::getNumTopSegments() const
{
return _array->getValue<hal_size_t>(_index, numTopSegmentsOffset);
}
hal_size_t HDF5Sequence::getNumBottomSegments() const
{
return _array->getValue<hal_size_t>(_index, numBottomSegmentsOffset);
}
TopSegmentIteratorPtr HDF5Sequence::getTopSegmentIterator(
hal_index_t position)
{
hal_size_t idx = position + getTopSegmentArrayIndex();
return _genome->getTopSegmentIterator(idx);
}
TopSegmentIteratorConstPtr HDF5Sequence::getTopSegmentIterator(
hal_index_t position) const
{
hal_size_t idx = position + getTopSegmentArrayIndex();
return _genome->getTopSegmentIterator(idx);
}
TopSegmentIteratorConstPtr HDF5Sequence::getTopSegmentEndIterator() const
{
return getTopSegmentIterator(getNumTopSegments());
}
BottomSegmentIteratorPtr HDF5Sequence::getBottomSegmentIterator(
hal_index_t position)
{
hal_size_t idx = position + getBottomSegmentArrayIndex();
return _genome->getBottomSegmentIterator(idx);
}
BottomSegmentIteratorConstPtr HDF5Sequence::getBottomSegmentIterator(
hal_index_t position) const
{
hal_size_t idx = position + getBottomSegmentArrayIndex();
return _genome->getBottomSegmentIterator(idx);
}
BottomSegmentIteratorConstPtr HDF5Sequence::getBottomSegmentEndIterator() const
{
return getBottomSegmentIterator(getNumBottomSegments());
}
DNAIteratorPtr HDF5Sequence::getDNAIterator(hal_index_t position)
{
hal_size_t idx = position + getStartPosition();
HDF5DNAIterator* newIt = new HDF5DNAIterator(_genome, idx);
return DNAIteratorPtr(newIt);
}
DNAIteratorConstPtr HDF5Sequence::getDNAIterator(hal_index_t position) const
{
hal_size_t idx = position + getStartPosition();
HDF5Genome* genome = const_cast<HDF5Genome*>(_genome);
const HDF5DNAIterator* newIt = new HDF5DNAIterator(genome, idx);
return DNAIteratorConstPtr(newIt);
}
DNAIteratorConstPtr HDF5Sequence::getDNAEndIterator() const
{
return getDNAIterator(getSequenceLength());
}
ColumnIteratorConstPtr HDF5Sequence::getColumnIterator(
const std::set<const Genome*>* targets, hal_size_t maxInsertLength,
hal_index_t position, hal_index_t lastPosition, bool noDupes,
bool noAncestors) const
{
hal_index_t idx = (hal_index_t)(position + getStartPosition());
hal_index_t lastIdx;
if (lastPosition == NULL_INDEX)
{
lastIdx = (hal_index_t)(getStartPosition() + getSequenceLength() - 1);
}
else
{
lastIdx = (hal_index_t)(lastPosition + getStartPosition());
}
if (position < 0 ||
lastPosition >= (hal_index_t)(getStartPosition() + getSequenceLength()))
{
stringstream ss;
ss << "HDF5Sequence::getColumnIterators: input indices "
<< "(" << position << ", " << lastPosition << ") out of bounds";
throw hal_exception(ss.str());
}
const DefaultColumnIterator* newIt =
new DefaultColumnIterator(getGenome(), targets, idx, lastIdx,
maxInsertLength, noDupes, noAncestors);
return ColumnIteratorConstPtr(newIt);
}
void HDF5Sequence::getString(std::string& outString) const
{
getSubString(outString, 0, getSequenceLength());
}
void HDF5Sequence::setString(const std::string& inString)
{
setSubString(inString, 0, getSequenceLength());
}
void HDF5Sequence::getSubString(std::string& outString, hal_size_t start,
hal_size_t length) const
{
hal_size_t idx = start + getStartPosition();
outString.resize(length);
HDF5DNAIterator dnaIt(const_cast<HDF5Genome*>(_genome), idx);
dnaIt.readString(outString, length);
}
void HDF5Sequence::setSubString(const std::string& inString,
hal_size_t start,
hal_size_t length)
{
if (length != inString.length())
{
stringstream ss;
ss << "setString: input string of length " << inString.length()
<< " has length different from target string in sequence " << getName()
<< " which is of length " << length;
throw hal_exception(ss.str());
}
hal_size_t idx = start + getStartPosition();
HDF5DNAIterator dnaIt(_genome, idx);
dnaIt.writeString(inString, length);
}
RearrangementPtr HDF5Sequence::getRearrangement(hal_index_t position,
hal_size_t gapLengthThreshold,
double nThreshold,
bool atomic) const
{
TopSegmentIteratorConstPtr top = getTopSegmentIterator(position);
DefaultRearrangement* rea = new DefaultRearrangement(getGenome(),
gapLengthThreshold,
nThreshold,
atomic);
rea->identifyFromLeftBreakpoint(top);
return RearrangementPtr(rea);
}
GappedTopSegmentIteratorConstPtr HDF5Sequence::getGappedTopSegmentIterator(
hal_index_t i, hal_size_t gapThreshold, bool atomic) const
{
TopSegmentIteratorConstPtr top = getTopSegmentIterator(i);
DefaultGappedTopSegmentIterator* gt =
new DefaultGappedTopSegmentIterator(top, gapThreshold, atomic);
return GappedTopSegmentIteratorConstPtr(gt);
}
GappedBottomSegmentIteratorConstPtr
HDF5Sequence::getGappedBottomSegmentIterator(
hal_index_t i, hal_size_t childIdx, hal_size_t gapThreshold,
bool atomic) const
{
BottomSegmentIteratorConstPtr bot = getBottomSegmentIterator(i);
DefaultGappedBottomSegmentIterator* gb =
new DefaultGappedBottomSegmentIterator(bot, childIdx, gapThreshold,
atomic);
return GappedBottomSegmentIteratorConstPtr(gb);
}
// LOCAL
void HDF5Sequence::set(hal_size_t startPosition,
const Sequence::Info& sequenceInfo,
hal_size_t topSegmentStartIndex,
hal_size_t bottomSegmentStartIndex)
{
_array->setValue(_index, startOffset, startPosition);
_array->setValue(_index, lengthOffset, sequenceInfo._length);
_array->setValue(_index, numTopSegmentsOffset, sequenceInfo._numTopSegments);
_array->setValue(_index, numBottomSegmentsOffset,
sequenceInfo._numBottomSegments);
_array->setValue(_index, topSegmentArrayIndexOffset, topSegmentStartIndex);
_array->setValue(_index, bottomSegmentArrayIndexOffset,
bottomSegmentStartIndex);
char* arrayBuffer = _array->getUpdate(_index) + nameOffset;
strcpy(arrayBuffer, sequenceInfo._name.c_str());
// keep cache for frequently used queries.
_cacheIndex = NULL_INDEX;
refreshCache();
}
void HDF5Sequence::setNumTopSegments(hal_size_t numTopSegments)
{
_array->setValue(_index, numTopSegmentsOffset, numTopSegments);
}
void HDF5Sequence::setNumBottomSegments(hal_size_t numBottomSegments)
{
_array->setValue(_index, numBottomSegmentsOffset, numBottomSegments);
}
void HDF5Sequence::setTopSegmentArrayIndex(hal_size_t topIndex)
{
_array->setValue(_index, topSegmentArrayIndexOffset, topIndex);
}
void HDF5Sequence::setBottomSegmentArrayIndex(hal_size_t bottomIndex)
{
_array->setValue(_index, bottomSegmentArrayIndexOffset, bottomIndex);
}
<commit_msg>allow genome to be null in sequence for unit tests...<commit_after>/*
* Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
*
* Released under the MIT license, see LICENSE.txt
*/
#include <string>
#include <cstring>
#include <sstream>
#include <set>
#include <iostream>
#include "hdf5Sequence.h"
#include "hdf5DNAIterator.h"
#include "defaultTopSegmentIterator.h"
#include "defaultBottomSegmentIterator.h"
#include "defaultColumnIterator.h"
#include "defaultRearrangement.h"
#include "defaultGappedTopSegmentIterator.h"
#include "defaultGappedBottomSegmentIterator.h"
using namespace std;
using namespace H5;
using namespace hal;
const size_t HDF5Sequence::startOffset = 0;
const size_t HDF5Sequence::lengthOffset = sizeof(hal_size_t);
const size_t HDF5Sequence::numTopSegmentsOffset = lengthOffset + sizeof(hal_size_t);
const size_t HDF5Sequence::numBottomSegmentsOffset = numTopSegmentsOffset + sizeof(hal_size_t);
const size_t HDF5Sequence::topSegmentArrayIndexOffset = numBottomSegmentsOffset + sizeof(hal_size_t);
const size_t HDF5Sequence::bottomSegmentArrayIndexOffset = topSegmentArrayIndexOffset + sizeof(hal_size_t);
const size_t HDF5Sequence::nameOffset = bottomSegmentArrayIndexOffset + sizeof(hal_size_t);
HDF5Sequence::HDF5Sequence(HDF5Genome* genome,
HDF5ExternalArray* array,
hal_index_t index) :
_array(array),
_index(index),
_genome(genome),
_cacheIndex(NULL_INDEX),
_startCache(NULL_INDEX),
_lengthCache(0)
{
}
HDF5Sequence::~HDF5Sequence()
{
}
// Some tools (ie maf export) access the same sequence
// info over and over again deep inside a loop. So I hack
// in a little cache, mostly to avoid copying the same string
// (name) out of hdf5.
inline void HDF5Sequence::refreshCache() const
{
if (_index != _cacheIndex)
{
_nameCache = _array->get(_index) + nameOffset;
// genome can be null in unit tests so we hack to not crash.
if (_genome != NULL)
{
_fullNameCache = _genome->getName() + '.' + _nameCache;
}
else
{
_fullNameCache = _nameCache;
}
_startCache = _array->getValue<hal_size_t>(_index, startOffset);
_lengthCache = _array->getValue<hal_size_t>(_index, lengthOffset);
_cacheIndex = _index;
}
}
H5::CompType HDF5Sequence::dataType(hal_size_t maxNameLength)
{
// the in-memory representations and hdf5 representations
// don't necessarily have to be the same, but it simplifies
// testing for now.
assert(PredType::NATIVE_HSIZE.getSize() == sizeof(hal_size_t));
assert(PredType::NATIVE_CHAR.getSize() == sizeof(char));
StrType strType(PredType::NATIVE_CHAR, (maxNameLength + 1) * sizeof(char));
CompType dataType(nameOffset + strType.getSize());
dataType.insertMember("start", startOffset, PredType::NATIVE_HSIZE);
dataType.insertMember("length", lengthOffset, PredType::NATIVE_HSIZE);
dataType.insertMember("numSequences", numTopSegmentsOffset,
PredType::NATIVE_HSIZE);
dataType.insertMember("numBottomSegments", numBottomSegmentsOffset,
PredType::NATIVE_HSIZE);
dataType.insertMember("topSegmentArrayIndexOffset", topSegmentArrayIndexOffset,
PredType::NATIVE_HSIZE);
dataType.insertMember("bottomSegmentArrayIndexOffset", bottomSegmentArrayIndexOffset,
PredType::NATIVE_HSIZE);
dataType.insertMember("name", nameOffset, strType);
return dataType;
}
// SEQUENCE INTERFACE
const string& HDF5Sequence::getName() const
{
refreshCache();
return _nameCache;
}
const string& HDF5Sequence::getFullName() const
{
refreshCache();
return _fullNameCache;
}
const Genome* HDF5Sequence::getGenome() const
{
return _genome;
}
Genome* HDF5Sequence::getGenome()
{
return _genome;
}
hal_size_t HDF5Sequence::getStartPosition() const
{
refreshCache();
return _startCache;
}
hal_index_t HDF5Sequence::getArrayIndex() const
{
return _index;
}
hal_index_t HDF5Sequence::getTopSegmentArrayIndex() const
{
return (hal_index_t)
_array->getValue<hal_size_t>(_index, topSegmentArrayIndexOffset);
}
hal_index_t HDF5Sequence::getBottomSegmentArrayIndex() const
{
return (hal_index_t)
_array->getValue<hal_size_t>(_index, bottomSegmentArrayIndexOffset);
}
// SEGMENTED SEQUENCE INTERFACE
hal_size_t HDF5Sequence::getSequenceLength() const
{
refreshCache();
return _lengthCache;
}
hal_size_t HDF5Sequence::getNumTopSegments() const
{
return _array->getValue<hal_size_t>(_index, numTopSegmentsOffset);
}
hal_size_t HDF5Sequence::getNumBottomSegments() const
{
return _array->getValue<hal_size_t>(_index, numBottomSegmentsOffset);
}
TopSegmentIteratorPtr HDF5Sequence::getTopSegmentIterator(
hal_index_t position)
{
hal_size_t idx = position + getTopSegmentArrayIndex();
return _genome->getTopSegmentIterator(idx);
}
TopSegmentIteratorConstPtr HDF5Sequence::getTopSegmentIterator(
hal_index_t position) const
{
hal_size_t idx = position + getTopSegmentArrayIndex();
return _genome->getTopSegmentIterator(idx);
}
TopSegmentIteratorConstPtr HDF5Sequence::getTopSegmentEndIterator() const
{
return getTopSegmentIterator(getNumTopSegments());
}
BottomSegmentIteratorPtr HDF5Sequence::getBottomSegmentIterator(
hal_index_t position)
{
hal_size_t idx = position + getBottomSegmentArrayIndex();
return _genome->getBottomSegmentIterator(idx);
}
BottomSegmentIteratorConstPtr HDF5Sequence::getBottomSegmentIterator(
hal_index_t position) const
{
hal_size_t idx = position + getBottomSegmentArrayIndex();
return _genome->getBottomSegmentIterator(idx);
}
BottomSegmentIteratorConstPtr HDF5Sequence::getBottomSegmentEndIterator() const
{
return getBottomSegmentIterator(getNumBottomSegments());
}
DNAIteratorPtr HDF5Sequence::getDNAIterator(hal_index_t position)
{
hal_size_t idx = position + getStartPosition();
HDF5DNAIterator* newIt = new HDF5DNAIterator(_genome, idx);
return DNAIteratorPtr(newIt);
}
DNAIteratorConstPtr HDF5Sequence::getDNAIterator(hal_index_t position) const
{
hal_size_t idx = position + getStartPosition();
HDF5Genome* genome = const_cast<HDF5Genome*>(_genome);
const HDF5DNAIterator* newIt = new HDF5DNAIterator(genome, idx);
return DNAIteratorConstPtr(newIt);
}
DNAIteratorConstPtr HDF5Sequence::getDNAEndIterator() const
{
return getDNAIterator(getSequenceLength());
}
ColumnIteratorConstPtr HDF5Sequence::getColumnIterator(
const std::set<const Genome*>* targets, hal_size_t maxInsertLength,
hal_index_t position, hal_index_t lastPosition, bool noDupes,
bool noAncestors) const
{
hal_index_t idx = (hal_index_t)(position + getStartPosition());
hal_index_t lastIdx;
if (lastPosition == NULL_INDEX)
{
lastIdx = (hal_index_t)(getStartPosition() + getSequenceLength() - 1);
}
else
{
lastIdx = (hal_index_t)(lastPosition + getStartPosition());
}
if (position < 0 ||
lastPosition >= (hal_index_t)(getStartPosition() + getSequenceLength()))
{
stringstream ss;
ss << "HDF5Sequence::getColumnIterators: input indices "
<< "(" << position << ", " << lastPosition << ") out of bounds";
throw hal_exception(ss.str());
}
const DefaultColumnIterator* newIt =
new DefaultColumnIterator(getGenome(), targets, idx, lastIdx,
maxInsertLength, noDupes, noAncestors);
return ColumnIteratorConstPtr(newIt);
}
void HDF5Sequence::getString(std::string& outString) const
{
getSubString(outString, 0, getSequenceLength());
}
void HDF5Sequence::setString(const std::string& inString)
{
setSubString(inString, 0, getSequenceLength());
}
void HDF5Sequence::getSubString(std::string& outString, hal_size_t start,
hal_size_t length) const
{
hal_size_t idx = start + getStartPosition();
outString.resize(length);
HDF5DNAIterator dnaIt(const_cast<HDF5Genome*>(_genome), idx);
dnaIt.readString(outString, length);
}
void HDF5Sequence::setSubString(const std::string& inString,
hal_size_t start,
hal_size_t length)
{
if (length != inString.length())
{
stringstream ss;
ss << "setString: input string of length " << inString.length()
<< " has length different from target string in sequence " << getName()
<< " which is of length " << length;
throw hal_exception(ss.str());
}
hal_size_t idx = start + getStartPosition();
HDF5DNAIterator dnaIt(_genome, idx);
dnaIt.writeString(inString, length);
}
RearrangementPtr HDF5Sequence::getRearrangement(hal_index_t position,
hal_size_t gapLengthThreshold,
double nThreshold,
bool atomic) const
{
TopSegmentIteratorConstPtr top = getTopSegmentIterator(position);
DefaultRearrangement* rea = new DefaultRearrangement(getGenome(),
gapLengthThreshold,
nThreshold,
atomic);
rea->identifyFromLeftBreakpoint(top);
return RearrangementPtr(rea);
}
GappedTopSegmentIteratorConstPtr HDF5Sequence::getGappedTopSegmentIterator(
hal_index_t i, hal_size_t gapThreshold, bool atomic) const
{
TopSegmentIteratorConstPtr top = getTopSegmentIterator(i);
DefaultGappedTopSegmentIterator* gt =
new DefaultGappedTopSegmentIterator(top, gapThreshold, atomic);
return GappedTopSegmentIteratorConstPtr(gt);
}
GappedBottomSegmentIteratorConstPtr
HDF5Sequence::getGappedBottomSegmentIterator(
hal_index_t i, hal_size_t childIdx, hal_size_t gapThreshold,
bool atomic) const
{
BottomSegmentIteratorConstPtr bot = getBottomSegmentIterator(i);
DefaultGappedBottomSegmentIterator* gb =
new DefaultGappedBottomSegmentIterator(bot, childIdx, gapThreshold,
atomic);
return GappedBottomSegmentIteratorConstPtr(gb);
}
// LOCAL
void HDF5Sequence::set(hal_size_t startPosition,
const Sequence::Info& sequenceInfo,
hal_size_t topSegmentStartIndex,
hal_size_t bottomSegmentStartIndex)
{
_array->setValue(_index, startOffset, startPosition);
_array->setValue(_index, lengthOffset, sequenceInfo._length);
_array->setValue(_index, numTopSegmentsOffset, sequenceInfo._numTopSegments);
_array->setValue(_index, numBottomSegmentsOffset,
sequenceInfo._numBottomSegments);
_array->setValue(_index, topSegmentArrayIndexOffset, topSegmentStartIndex);
_array->setValue(_index, bottomSegmentArrayIndexOffset,
bottomSegmentStartIndex);
char* arrayBuffer = _array->getUpdate(_index) + nameOffset;
strcpy(arrayBuffer, sequenceInfo._name.c_str());
// keep cache for frequently used queries.
_cacheIndex = NULL_INDEX;
refreshCache();
}
void HDF5Sequence::setNumTopSegments(hal_size_t numTopSegments)
{
_array->setValue(_index, numTopSegmentsOffset, numTopSegments);
}
void HDF5Sequence::setNumBottomSegments(hal_size_t numBottomSegments)
{
_array->setValue(_index, numBottomSegmentsOffset, numBottomSegments);
}
void HDF5Sequence::setTopSegmentArrayIndex(hal_size_t topIndex)
{
_array->setValue(_index, topSegmentArrayIndexOffset, topIndex);
}
void HDF5Sequence::setBottomSegmentArrayIndex(hal_size_t bottomIndex)
{
_array->setValue(_index, bottomSegmentArrayIndexOffset, bottomIndex);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 David Wicks, sansumbrella.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "puptent/ExpiresSystem.h"
#include "pockets/CollectionUtilities.hpp"
using namespace puptent;
using namespace std;
void ExpiresSystem::configure(shared_ptr<entityx::EventManager> events)
{
events->subscribe<ComponentAddedEvent<Expires>>( *this );
events->subscribe<ComponentRemovedEvent<Expires>>( *this );
}
void ExpiresSystem::receive( const ComponentAddedEvent<puptent::Expires> &event )
{
mEntities.push_back( event.entity );
}
void ExpiresSystem::receive( const ComponentRemovedEvent<puptent::Expires> &event )
{
vector_remove( &mEntities, event.entity );
}
void ExpiresSystem::update(shared_ptr<entityx::EntityManager> es, shared_ptr<entityx::EventManager> events, double dt)
{
for( auto entity : mEntities )
{
auto expires = entity.component<Expires>();
expires->time -= dt;
if( expires->time <= 0.0 )
{
entity.destroy();
}
}
vector_erase_if( &mEntities, []( const Entity &entity ){ return !entity.valid(); });
/*
// the following doesn't work because the query somehow doesn't get all elements
// collecting in events is faster, but this should work
vector<Entity> dead_entities;
for( auto entity : es->entities_with_components<Expires>() )
{
auto expire = entity.component<Expires>();
expire->time -= dt;
if( expire->time <= 0.0 )
{
dead_entities.push_back( entity );
}
}
for( auto entity : dead_entities )
{
entity.destroy();
}
//*/
}
<commit_msg>Expires won't iterate through invalid elements any more.<commit_after>/*
* Copyright (c) 2013 David Wicks, sansumbrella.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "puptent/ExpiresSystem.h"
#include "pockets/CollectionUtilities.hpp"
using namespace puptent;
using namespace std;
void ExpiresSystem::configure(shared_ptr<entityx::EventManager> events)
{
events->subscribe<ComponentAddedEvent<Expires>>( *this );
events->subscribe<ComponentRemovedEvent<Expires>>( *this );
}
void ExpiresSystem::receive( const ComponentAddedEvent<puptent::Expires> &event )
{
mEntities.push_back( event.entity );
}
void ExpiresSystem::receive( const ComponentRemovedEvent<puptent::Expires> &event )
{
vector_remove( &mEntities, event.entity );
}
void ExpiresSystem::update(shared_ptr<entityx::EntityManager> es, shared_ptr<entityx::EventManager> events, double dt)
{
// remove invalid entities first
vector_erase_if( &mEntities, []( const Entity &entity ){ return !entity.valid(); });
for( auto entity : mEntities )
{
auto expires = entity.component<Expires>();
expires->time -= dt;
if( expires->time <= 0.0 )
{
entity.destroy();
}
}
/*
// the following doesn't work because the query somehow doesn't get all elements
// collecting in events is faster, but this should work
vector<Entity> dead_entities;
for( auto entity : es->entities_with_components<Expires>() )
{
auto expire = entity.component<Expires>();
expire->time -= dt;
if( expire->time <= 0.0 )
{
dead_entities.push_back( entity );
}
}
for( auto entity : dead_entities )
{
entity.destroy();
}
//*/
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fileidentifierconverter.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: ihi $ $Date: 2007-06-05 14:49:32 $
*
* 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 _UCBHELPER_FILEIDENTIFIERCONVERTER_HXX_
#define _UCBHELPER_FILEIDENTIFIERCONVERTER_HXX_
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef INCLUDED_UCBHELPERDLLAPI_H
#include "ucbhelper/ucbhelperdllapi.h"
#endif
namespace com { namespace sun { namespace star { namespace ucb {
class XContentProviderManager;
} } } }
namespace rtl { class OUString; }
namespace ucbhelper {
//============================================================================
/** Get a 'root' URL for the most 'local' file content provider.
@descr
The result can be used as the rBaseURL parameter of
ucb::getFileURLFromSystemPath().
@param rManager
A content provider manager. Must not be null.
@returns
either a 'root' URL for the most 'local' file content provider, or an
empty string, if no such URL can meaningfully be constructed.
*/
UCBHELPER_DLLPUBLIC rtl::OUString getLocalFileURL(
com::sun::star::uno::Reference<
com::sun::star::ucb::XContentProviderManager > const &
rManager)
SAL_THROW((com::sun::star::uno::RuntimeException));
//============================================================================
/** Using a specific content provider manager, convert a file path in system
dependent notation to a (file) URL.
@param rManager
A content provider manager. Must not be null.
@param rBaseURL
See the corresponding parameter of
com::sun::star::ucb::XFileIdentifierConverter::getFileURLFromSystemPath().
@param rURL
See the corresponding parameter of
com::sun::star::ucb::XFileIdentifierConverter::getFileURLFromSystemPath().
@returns
a URL, if the content provider registered at the content provider manager
that is responsible for the base URL returns a URL when calling
com::sun::star::ucb::XFileIdentiferConverter::getFileURLFromSystemPath()
on it. Otherwise, an empty string is returned.
@see
com::sun::star::ucb::XFileIdentiferConverter::getFileURLFromSystemPath().
*/
UCBHELPER_DLLPUBLIC rtl::OUString
getFileURLFromSystemPath(
com::sun::star::uno::Reference<
com::sun::star::ucb::XContentProviderManager > const &
rManager,
rtl::OUString const & rBaseURL,
rtl::OUString const & rSystemPath)
SAL_THROW((com::sun::star::uno::RuntimeException));
//============================================================================
/** Using a specific content provider manager, convert a (file) URL to a
file path in system dependent notation.
@param rManager
A content provider manager. Must not be null.
@param rURL
See the corresponding parameter of
com::sun::star::ucb::XFileIdentiferConverter::getSystemPathFromFileURL().
@returns
a system path, if the content provider registered at the content provider
manager that is responsible for the base URL returns a system path when
calling
com::sun::star::ucb::XFileIdentiferConverter::getSystemPathFromFileURL()
on it. Otherwise, an empty string is returned.
@see
com::sun::star::ucb::XFileIdentiferConverter::getSystemPathFromFileURL().
*/
UCBHELPER_DLLPUBLIC rtl::OUString
getSystemPathFromFileURL(
com::sun::star::uno::Reference<
com::sun::star::ucb::XContentProviderManager > const &
rManager,
rtl::OUString const & rURL)
SAL_THROW((com::sun::star::uno::RuntimeException));
}
#endif // _UCBHELPER_FILEIDENTIFIERCONVERTER_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.7.42); FILE MERGED 2008/04/01 16:02:44 thb 1.7.42.3: #i85898# Stripping all external header guards 2008/04/01 12:58:43 thb 1.7.42.2: #i85898# Stripping all external header guards 2008/03/31 15:31:28 rt 1.7.42.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fileidentifierconverter.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _UCBHELPER_FILEIDENTIFIERCONVERTER_HXX_
#define _UCBHELPER_FILEIDENTIFIERCONVERTER_HXX_
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <sal/types.h>
#include "ucbhelper/ucbhelperdllapi.h"
namespace com { namespace sun { namespace star { namespace ucb {
class XContentProviderManager;
} } } }
namespace rtl { class OUString; }
namespace ucbhelper {
//============================================================================
/** Get a 'root' URL for the most 'local' file content provider.
@descr
The result can be used as the rBaseURL parameter of
ucb::getFileURLFromSystemPath().
@param rManager
A content provider manager. Must not be null.
@returns
either a 'root' URL for the most 'local' file content provider, or an
empty string, if no such URL can meaningfully be constructed.
*/
UCBHELPER_DLLPUBLIC rtl::OUString getLocalFileURL(
com::sun::star::uno::Reference<
com::sun::star::ucb::XContentProviderManager > const &
rManager)
SAL_THROW((com::sun::star::uno::RuntimeException));
//============================================================================
/** Using a specific content provider manager, convert a file path in system
dependent notation to a (file) URL.
@param rManager
A content provider manager. Must not be null.
@param rBaseURL
See the corresponding parameter of
com::sun::star::ucb::XFileIdentifierConverter::getFileURLFromSystemPath().
@param rURL
See the corresponding parameter of
com::sun::star::ucb::XFileIdentifierConverter::getFileURLFromSystemPath().
@returns
a URL, if the content provider registered at the content provider manager
that is responsible for the base URL returns a URL when calling
com::sun::star::ucb::XFileIdentiferConverter::getFileURLFromSystemPath()
on it. Otherwise, an empty string is returned.
@see
com::sun::star::ucb::XFileIdentiferConverter::getFileURLFromSystemPath().
*/
UCBHELPER_DLLPUBLIC rtl::OUString
getFileURLFromSystemPath(
com::sun::star::uno::Reference<
com::sun::star::ucb::XContentProviderManager > const &
rManager,
rtl::OUString const & rBaseURL,
rtl::OUString const & rSystemPath)
SAL_THROW((com::sun::star::uno::RuntimeException));
//============================================================================
/** Using a specific content provider manager, convert a (file) URL to a
file path in system dependent notation.
@param rManager
A content provider manager. Must not be null.
@param rURL
See the corresponding parameter of
com::sun::star::ucb::XFileIdentiferConverter::getSystemPathFromFileURL().
@returns
a system path, if the content provider registered at the content provider
manager that is responsible for the base URL returns a system path when
calling
com::sun::star::ucb::XFileIdentiferConverter::getSystemPathFromFileURL()
on it. Otherwise, an empty string is returned.
@see
com::sun::star::ucb::XFileIdentiferConverter::getSystemPathFromFileURL().
*/
UCBHELPER_DLLPUBLIC rtl::OUString
getSystemPathFromFileURL(
com::sun::star::uno::Reference<
com::sun::star::ucb::XContentProviderManager > const &
rManager,
rtl::OUString const & rURL)
SAL_THROW((com::sun::star::uno::RuntimeException));
}
#endif // _UCBHELPER_FILEIDENTIFIERCONVERTER_HXX_
<|endoftext|> |
<commit_before>#include "FrontCameraVision.h"
#include "SimpleImageThresholder.h"
#include "ThreadedImageThresholder.h"
#include "ParallelImageThresholder.h"
#include "TBBImageThresholder.h"
#include "GateFinder.h"
#include "BallFinder.h"
#include "AutoCalibrator.h"
#include <queue> // std::priority_queue
#include <functional> // std::greater
#include "kdNode2D.h"
#include "DistanceCalculator.h"
extern DistanceCalculator gDistanceCalculator;
FrontCameraVision::FrontCameraVision(ICamera *pCamera, IDisplay *pDisplay, FieldState *pFieldState) : ConfigurableModule("FrontCameraVision")
{
m_pCamera = pCamera;
m_pDisplay = pDisplay;
m_pState = pFieldState;
ADD_BOOL_SETTING(gaussianBlurEnabled);
ADD_BOOL_SETTING(greenAreaDetectionEnabled);
ADD_BOOL_SETTING(gateObstructionDetectionEnabled);
ADD_BOOL_SETTING(borderDetectionEnabled);
ADD_BOOL_SETTING(nightVisionEnabled);
LoadSettings();
Start();
}
FrontCameraVision::~FrontCameraVision()
{
WaitForStop();
}
void FrontCameraVision::Run() {
ThresholdedImages thresholdedImages;
try {
CalibrationConfReader calibrator;
for (int i = 0; i < NUMBER_OF_OBJECTS; i++) {
objectThresholds[(OBJECT)i] = calibrator.GetObjectThresholds(i, OBJECT_LABELS[(OBJECT)i]);
}
}
catch (...){
std::cout << "Calibration data is missing!" << std::endl;
}
TBBImageThresholder thresholder(thresholdedImages, objectThresholds);
GateFinder blueGateFinder;
GateFinder yellowGateFinder;
BallFinder ballFinder;
auto frameSize = m_pCamera->GetFrameSize();
/*
m_pState->blueGate.setFrameSize(frameSize);
m_pState->yellowGate.setFrameSize(frameSize);
*/
cv::Mat white(frameSize.height, frameSize.width, CV_8UC3, cv::Scalar(255, 255, 255));
cv::Mat black(frameSize.height, frameSize.width, CV_8UC3, cv::Scalar(40, 40, 40));
cv::Mat green(frameSize.height, frameSize.width, CV_8UC3, cv::Scalar(21, 188, 80));
cv::Mat yellow(frameSize.height, frameSize.width, CV_8UC3, cv::Scalar(61, 255, 244));
cv::Mat blue(frameSize.height, frameSize.width, CV_8UC3, cv::Scalar(236, 137, 48));
cv::Mat orange(frameSize.height, frameSize.width, CV_8UC3, cv::Scalar(48, 154, 236));
bool notEnoughtGreen = false;
int mouseControl = 0;
bool somethingOnWay = false;
while (!stop_thread){
cv::Mat frameBGR = m_pCamera->Capture();
/**************************************************/
/* STEP 1. Convert picture to HSV colorspace */
/**************************************************/
if (gaussianBlurEnabled) {
cv::GaussianBlur(frameBGR, frameBGR, cv::Size(3, 3), 4);
}
cvtColor(frameBGR, frameHSV, cv::COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
/**************************************************/
/* STEP 2. thresholding in parallel */
/**************************************************/
thresholder.Start(frameHSV, { BALL, BLUE_GATE, YELLOW_GATE/*, FIELD, INNER_BORDER, OUTER_BORDER*/ });
/**************************************************/
/* STEP 3. check that path to gate is clean */
/* this is done here, because finding contures */
/* corrupts thresholded imagees */
/**************************************************/
if (false && gateObstructionDetectionEnabled) {
cv::Mat selected(frameSize.height, frameSize.width, CV_8U, cv::Scalar::all(0));
cv::Mat mask(frameSize.height, frameSize.width, CV_8U, cv::Scalar::all(0));
cv::Mat tmp(frameSize.height, frameSize.width, CV_8U, cv::Scalar::all(0));
//cv::line(mask, cv::Point(frameSize.width / 2, 200), cv::Point(frameSize.width / 2 - 40, frameSize.height - 100), cv::Scalar(255, 255, 255), 40);
//cv::line(mask, cv::Point(frameSize.width / 2, 200), cv::Point(frameSize.width / 2 + 40, frameSize.height - 100), cv::Scalar(255, 255, 255), 40);
std::vector<cv::Point2i> triangle;
triangle.push_back(cv::Point(frameSize.width / 2, 50));
triangle.push_back(cv::Point(frameSize.width / 2 - 80, frameSize.height - 100));
triangle.push_back(cv::Point(frameSize.width / 2 + 80, frameSize.height - 100));
cv::fillConvexPoly(mask, triangle, cv::Scalar::all(255));
tmp = 255 - (thresholdedImages[INNER_BORDER] + thresholdedImages[OUTER_BORDER] + thresholdedImages[FIELD]);
tmp.copyTo(selected, mask); // perhaps use field and inner border
thresholdedImages[SIGHT_MASK] = selected;
//sightObstructed = countNonZero(selected) > 10;
}
/**************************************************/
/* STEP 4. extract closest ball and gate positions*/
/**************************************************/
cv::Point2f r1[4], r2[4];
cv::Point g1, g2;
//Blue gate pos
bool found = blueGateFinder.Locate(thresholdedImages[BLUE_GATE], frameHSV, frameBGR, g1, r1);
if (!found) {
m_pDisplay->ShowImage(frameBGR);
continue; // nothing to do :(
}
//Yellow gate pos
found = yellowGateFinder.Locate(thresholdedImages[YELLOW_GATE], frameHSV, frameBGR, g2, r2);
if (!found) {
m_pDisplay->ShowImage(frameBGR);
continue; // nothing to do :(
}
// ajust gate positions to ..
// find closest points to opposite gate centre
auto min_i1 = 0, min_j1 = 0, min_i2 = 0, min_j2 = 0;
double min_dist1 = INT_MAX, min_dist2 = INT_MAX;
for (int i = 0; i < 4; i++){
double dist1 = cv::norm(r1[i] - (cv::Point2f)g2);
double dist2 = cv::norm(r2[i] - (cv::Point2f)g1);
if (dist1 < min_dist1) {
min_dist1 = dist1;
min_i1 = i;
}
if (dist2 < min_dist2) {
min_dist2 = dist2;
min_j1 = i;
}
}
auto next = (min_i1 + 1) % 4;
auto prev = (min_i1 + 3) % 4;
// find longest side
min_i2 = (cv::norm(r1[min_i1] - r1[next]) > cv::norm(r1[min_i1] - r1[prev])) ? next : prev;
next = (min_j1 + 1) % 4;
prev = (min_j1 + 3) % 4;
// find longest side
min_j2 = (cv::norm(r2[min_j1] - r2[next]) > cv::norm(r2[min_j1] - r2[prev])) ? next : prev;
cv::Scalar color4(0, 0, 0);
cv::Scalar color2(0, 0, 255);
auto c1 = (r1[min_i1] + r1[min_i2]) / 2;
circle(frameBGR, c1, 12, color4, -1, 12, 0);
auto c2 = (r2[min_j1] + r2[min_j2]) / 2;
circle(frameBGR, c2, 7, color2, -1, 8, 0);
m_pState->blueGate.updateRawCoordinates(c1, cv::Point2d(frameBGR.size() / 2));
m_pState->yellowGate.updateRawCoordinates(c2, cv::Point2d(frameBGR.size() / 2));
m_pState->self.updateFieldCoords();
//Balls pos
cv::Mat rotMat = getRotationMatrix2D(cv::Point(0,0), -m_pState->self.getAngle(), 1);
cv::Mat balls(3, NUMBER_OF_BALLS, CV_64FC1);
found = ballFinder.Locate(thresholdedImages[BALL], frameHSV, frameBGR, balls);
if (found) {
balls.row(0) -= frameBGR.size().width / 2;
balls.row(1) -= frameBGR.size().height / 2;
cv::Mat rotatedBalls(balls.size(), balls.type());
//std::cout << CV_64FC1 << ", " << rotMat.type() << ", " << balls.type() << std::endl;
//std::cout << rotMat << std::endl;
//std::cout << balls << std::endl;
//cv::warpAffine(balls, rotatedBalls, rotMat, balls.size());
rotatedBalls = rotMat * balls;
//std::cout << rotatedBalls << std::endl;
m_pState->resetBallsUpdateState();
/*
for (int i = 0; i < rotatedBalls.cols; i++){
cv::Point2d pos = gDistanceCalculator.getFieldCoordinates(cv::Point(rotatedBalls.col(i)), cv::Point(0, 0)) + (cv::Point2d)m_pState->self.getFieldPos();
std::cout << pos << std::endl;
}
std::cout << "==============" << std::endl;
for (int i = 0; i < NUMBER_OF_BALLS; i++){
std::cout << m_pState->balls[i].fieldCoords << std::endl;
}
*/
/*
kdNode2D sortedballs(m_pState->balls, NUMBER_OF_BALLS);
std::cout << "##################" << std::endl;
for (int i = 0; i < rotatedBalls.cols; i++){
std::cout << "=============" << std::endl;
cv::Point pos = gDistanceCalculator.getFieldCoordinates(cv::Point(rotatedBalls.col(i)), cv::Point(0, 0)) + (cv::Point2d)m_pState->self.getFieldPos();
auto nearest = sortedballs.nearest(pos);
std::cout << "nearest: " << nearest.second->id << " " << pos << " ->" << nearest.second->fieldCoords << std::endl;
assert(nearest.second);
nearest.second->updateRawCoordinates(cv::Point(rotatedBalls.col(i)), cv::Point(0, 0));
nearest.second->updateFieldCoords(m_pState->self.getFieldPos());
nearest.second->isUpdated = true;
}
*/
std::vector<int> newBalls; // new balls that are too far from existing ones
/* find balls that are close by */
for (int i = 0; i < rotatedBalls.cols; i++){
cv::Point2d pos = gDistanceCalculator.getFieldCoordinates(cv::Point2d(rotatedBalls.col(i)), cv::Point(0, 0)) + (cv::Point2d)m_pState->self.getFieldPos();
bool ball_found = false;
for (int j = 0; j < NUMBER_OF_BALLS; j++) {
if (!m_pState->balls[j].isUpdated && cv::norm(pos - m_pState->balls[j].fieldCoords) < 50) {
m_pState->balls[j].updateRawCoordinates(cv::Point2d(rotatedBalls.col(i)), cv::Point(0, 0));
m_pState->balls[j].updateFieldCoords(m_pState->self.getFieldPos());
m_pState->balls[j].polarMetricCoords.y -= m_pState->self.getAngle(); // rotate balls back
m_pState->balls[j].isUpdated = true;
ball_found = true;
break;
}
}
if (!ball_found) {
newBalls.push_back(i);
}
}
// now update empty slots with new balls
for (auto newBall : newBalls){
for (int j = 0; j < NUMBER_OF_BALLS; j++) {
if (!m_pState->balls[j].isUpdated) {
m_pState->balls[j].updateRawCoordinates(cv::Point(rotatedBalls.col(newBall)), cv::Point(0, 0));
m_pState->balls[j].updateFieldCoords(m_pState->self.getFieldPos());
m_pState->balls[j].isUpdated = true;
break;
}
}
}
}
/*
ObjectPosition *targetGatePos = 0;
if (targetGate == BLUE_GATE && BlueGateFound) targetGatePos = &blueGatePos;
else if (targetGate == YELLOW_GATE && YellowGateFound) targetGatePos = &yellowGatePos;
// else leave to NULL
*/
if (gateObstructionDetectionEnabled) {
// step 3.2
int count = countNonZero(thresholdedImages[SIGHT_MASK]);
std::ostringstream osstr;
osstr << "nonzero :" << count;
m_pState->gateObstructed = count > 900;
//cv::putText(thresholdedImages[SIGHT_MASK], osstr.str(), cv::Point(20, 20), cv::FONT_HERSHEY_DUPLEX, 0.5, cv::Scalar(255, 255, 255));
//cv::imshow("mmm", thresholdedImages[SIGHT_MASK]);
}
else {
m_pState->gateObstructed = false;
}
notEnoughtGreen = false;
if (greenAreaDetectionEnabled) {
notEnoughtGreen = countNonZero(thresholdedImages[FIELD]) < 640 * 120;
somethingOnWay |= notEnoughtGreen;
}
// copy thresholded images before they are destroyed
if (nightVisionEnabled) {
green.copyTo(frameBGR, thresholdedImages[FIELD]);
white.copyTo(frameBGR, thresholdedImages[INNER_BORDER]);
black.copyTo(frameBGR, thresholdedImages[OUTER_BORDER]);
orange.copyTo(frameBGR, thresholdedImages[BALL]);
yellow.copyTo(frameBGR, thresholdedImages[YELLOW_GATE]);
blue.copyTo(frameBGR, thresholdedImages[BLUE_GATE]);
}
cv::line(frameBGR, (frameSize / 2) + cv::Size(0, -30), (frameSize / 2) + cv::Size(0, 30), cv::Scalar(0, 0, 255), 3, 8, 0);
cv::line(frameBGR, (frameSize / 2) + cv::Size(-30, 0), (frameSize / 2) + cv::Size(30,0), cv::Scalar(0, 0, 255), 3, 8, 0);
m_pDisplay->ShowImage(frameBGR);
}
}<commit_msg>cleanup<commit_after>#include "FrontCameraVision.h"
#include "SimpleImageThresholder.h"
#include "ThreadedImageThresholder.h"
#include "ParallelImageThresholder.h"
#include "TBBImageThresholder.h"
#include "GateFinder.h"
#include "BallFinder.h"
#include "AutoCalibrator.h"
#include <queue> // std::priority_queue
#include <functional> // std::greater
#include "kdNode2D.h"
#include "DistanceCalculator.h"
extern DistanceCalculator gDistanceCalculator;
FrontCameraVision::FrontCameraVision(ICamera *pCamera, IDisplay *pDisplay, FieldState *pFieldState) : ConfigurableModule("FrontCameraVision")
{
m_pCamera = pCamera;
m_pDisplay = pDisplay;
m_pState = pFieldState;
ADD_BOOL_SETTING(gaussianBlurEnabled);
ADD_BOOL_SETTING(greenAreaDetectionEnabled);
ADD_BOOL_SETTING(gateObstructionDetectionEnabled);
ADD_BOOL_SETTING(borderDetectionEnabled);
ADD_BOOL_SETTING(nightVisionEnabled);
LoadSettings();
Start();
}
FrontCameraVision::~FrontCameraVision()
{
WaitForStop();
}
void FrontCameraVision::Run() {
ThresholdedImages thresholdedImages;
try {
CalibrationConfReader calibrator;
for (int i = 0; i < NUMBER_OF_OBJECTS; i++) {
objectThresholds[(OBJECT)i] = calibrator.GetObjectThresholds(i, OBJECT_LABELS[(OBJECT)i]);
}
}
catch (...){
std::cout << "Calibration data is missing!" << std::endl;
}
TBBImageThresholder thresholder(thresholdedImages, objectThresholds);
GateFinder blueGateFinder;
GateFinder yellowGateFinder;
BallFinder ballFinder;
auto frameSize = m_pCamera->GetFrameSize();
/*
m_pState->blueGate.setFrameSize(frameSize);
m_pState->yellowGate.setFrameSize(frameSize);
*/
cv::Mat white(frameSize.height, frameSize.width, CV_8UC3, cv::Scalar(255, 255, 255));
cv::Mat black(frameSize.height, frameSize.width, CV_8UC3, cv::Scalar(40, 40, 40));
cv::Mat green(frameSize.height, frameSize.width, CV_8UC3, cv::Scalar(21, 188, 80));
cv::Mat yellow(frameSize.height, frameSize.width, CV_8UC3, cv::Scalar(61, 255, 244));
cv::Mat blue(frameSize.height, frameSize.width, CV_8UC3, cv::Scalar(236, 137, 48));
cv::Mat orange(frameSize.height, frameSize.width, CV_8UC3, cv::Scalar(48, 154, 236));
bool notEnoughtGreen = false;
int mouseControl = 0;
bool somethingOnWay = false;
while (!stop_thread){
cv::Mat frameBGR = m_pCamera->Capture();
/**************************************************/
/* STEP 1. Convert picture to HSV colorspace */
/**************************************************/
if (gaussianBlurEnabled) {
cv::GaussianBlur(frameBGR, frameBGR, cv::Size(3, 3), 4);
}
cvtColor(frameBGR, frameHSV, cv::COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
/**************************************************/
/* STEP 2. thresholding in parallel */
/**************************************************/
thresholder.Start(frameHSV, { BALL, BLUE_GATE, YELLOW_GATE/*, FIELD, INNER_BORDER, OUTER_BORDER*/ });
/**************************************************/
/* STEP 3. check that path to gate is clean */
/* this is done here, because finding contures */
/* corrupts thresholded imagees */
/**************************************************/
if (false && gateObstructionDetectionEnabled) {
cv::Mat selected(frameSize.height, frameSize.width, CV_8U, cv::Scalar::all(0));
cv::Mat mask(frameSize.height, frameSize.width, CV_8U, cv::Scalar::all(0));
cv::Mat tmp(frameSize.height, frameSize.width, CV_8U, cv::Scalar::all(0));
//cv::line(mask, cv::Point(frameSize.width / 2, 200), cv::Point(frameSize.width / 2 - 40, frameSize.height - 100), cv::Scalar(255, 255, 255), 40);
//cv::line(mask, cv::Point(frameSize.width / 2, 200), cv::Point(frameSize.width / 2 + 40, frameSize.height - 100), cv::Scalar(255, 255, 255), 40);
std::vector<cv::Point2i> triangle;
triangle.push_back(cv::Point(frameSize.width / 2, 50));
triangle.push_back(cv::Point(frameSize.width / 2 - 80, frameSize.height - 100));
triangle.push_back(cv::Point(frameSize.width / 2 + 80, frameSize.height - 100));
cv::fillConvexPoly(mask, triangle, cv::Scalar::all(255));
tmp = 255 - (thresholdedImages[INNER_BORDER] + thresholdedImages[OUTER_BORDER] + thresholdedImages[FIELD]);
tmp.copyTo(selected, mask); // perhaps use field and inner border
thresholdedImages[SIGHT_MASK] = selected;
//sightObstructed = countNonZero(selected) > 10;
}
/**************************************************/
/* STEP 4. extract closest ball and gate positions*/
/**************************************************/
cv::Point2f r1[4], r2[4];
cv::Point g1, g2;
//Blue gate pos
bool found = blueGateFinder.Locate(thresholdedImages[BLUE_GATE], frameHSV, frameBGR, g1, r1);
if (!found) {
m_pDisplay->ShowImage(frameBGR);
continue; // nothing to do :(
}
//Yellow gate pos
found = yellowGateFinder.Locate(thresholdedImages[YELLOW_GATE], frameHSV, frameBGR, g2, r2);
if (!found) {
m_pDisplay->ShowImage(frameBGR);
continue; // nothing to do :(
}
// ajust gate positions to ..
// find closest points to opposite gate centre
auto min_i1 = 0, min_j1 = 0, min_i2 = 0, min_j2 = 0;
double min_dist1 = INT_MAX, min_dist2 = INT_MAX;
for (int i = 0; i < 4; i++){
double dist1 = cv::norm(r1[i] - (cv::Point2f)g2);
double dist2 = cv::norm(r2[i] - (cv::Point2f)g1);
if (dist1 < min_dist1) {
min_dist1 = dist1;
min_i1 = i;
}
if (dist2 < min_dist2) {
min_dist2 = dist2;
min_j1 = i;
}
}
auto next = (min_i1 + 1) % 4;
auto prev = (min_i1 + 3) % 4;
// find longest side
min_i2 = (cv::norm(r1[min_i1] - r1[next]) > cv::norm(r1[min_i1] - r1[prev])) ? next : prev;
next = (min_j1 + 1) % 4;
prev = (min_j1 + 3) % 4;
// find longest side
min_j2 = (cv::norm(r2[min_j1] - r2[next]) > cv::norm(r2[min_j1] - r2[prev])) ? next : prev;
cv::Scalar color4(0, 0, 0);
cv::Scalar color2(0, 0, 255);
auto c1 = (r1[min_i1] + r1[min_i2]) / 2;
circle(frameBGR, c1, 12, color4, -1, 12, 0);
auto c2 = (r2[min_j1] + r2[min_j2]) / 2;
circle(frameBGR, c2, 7, color2, -1, 8, 0);
m_pState->blueGate.updateRawCoordinates(c1, cv::Point2d(frameBGR.size() / 2));
m_pState->yellowGate.updateRawCoordinates(c2, cv::Point2d(frameBGR.size() / 2));
m_pState->self.updateFieldCoords();
//Balls pos
cv::Mat rotMat = getRotationMatrix2D(cv::Point(0,0), -m_pState->self.getAngle(), 1);
cv::Mat balls(3, NUMBER_OF_BALLS, CV_64FC1);
found = ballFinder.Locate(thresholdedImages[BALL], frameHSV, frameBGR, balls);
if (found) {
balls.row(0) -= frameBGR.size().width / 2;
balls.row(1) -= frameBGR.size().height / 2;
cv::Mat rotatedBalls(balls.size(), balls.type());
rotatedBalls = rotMat * balls;
m_pState->resetBallsUpdateState();
/* find balls that are close by */
for (int j = 0; j < rotatedBalls.cols; j++){
m_pState->balls[j].updateRawCoordinates(cv::Point2d(rotatedBalls.col(j)), cv::Point(0, 0));
m_pState->balls[j].updateFieldCoords(m_pState->self.getFieldPos());
m_pState->balls[j].polarMetricCoords.y -= m_pState->self.getAngle(); // rotate balls back
m_pState->balls[j].isUpdated = true;
}
}
/*
ObjectPosition *targetGatePos = 0;
if (targetGate == BLUE_GATE && BlueGateFound) targetGatePos = &blueGatePos;
else if (targetGate == YELLOW_GATE && YellowGateFound) targetGatePos = &yellowGatePos;
// else leave to NULL
*/
if (gateObstructionDetectionEnabled) {
// step 3.2
int count = countNonZero(thresholdedImages[SIGHT_MASK]);
std::ostringstream osstr;
osstr << "nonzero :" << count;
m_pState->gateObstructed = count > 900;
//cv::putText(thresholdedImages[SIGHT_MASK], osstr.str(), cv::Point(20, 20), cv::FONT_HERSHEY_DUPLEX, 0.5, cv::Scalar(255, 255, 255));
//cv::imshow("mmm", thresholdedImages[SIGHT_MASK]);
}
else {
m_pState->gateObstructed = false;
}
notEnoughtGreen = false;
if (greenAreaDetectionEnabled) {
notEnoughtGreen = countNonZero(thresholdedImages[FIELD]) < 640 * 120;
somethingOnWay |= notEnoughtGreen;
}
// copy thresholded images before they are destroyed
if (nightVisionEnabled) {
green.copyTo(frameBGR, thresholdedImages[FIELD]);
white.copyTo(frameBGR, thresholdedImages[INNER_BORDER]);
black.copyTo(frameBGR, thresholdedImages[OUTER_BORDER]);
orange.copyTo(frameBGR, thresholdedImages[BALL]);
yellow.copyTo(frameBGR, thresholdedImages[YELLOW_GATE]);
blue.copyTo(frameBGR, thresholdedImages[BLUE_GATE]);
}
cv::line(frameBGR, (frameSize / 2) + cv::Size(0, -30), (frameSize / 2) + cv::Size(0, 30), cv::Scalar(0, 0, 255), 3, 8, 0);
cv::line(frameBGR, (frameSize / 2) + cv::Size(-30, 0), (frameSize / 2) + cv::Size(30,0), cv::Scalar(0, 0, 255), 3, 8, 0);
m_pDisplay->ShowImage(frameBGR);
}
}<|endoftext|> |
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_PATHSPEC_HPP_
#define RDB_PROTOCOL_PATHSPEC_HPP_
#include "errors.hpp"
#include <boost/variant.hpp>
#include "rdb_protocol/datum.hpp"
namespace ql {
class pathspec_t {
public:
pathspec_t(const pathspec_t &other);
pathspec_t& operator=(const pathspec_t &other);
explicit pathspec_t(const std::string &str);
explicit pathspec_t(const std::map<std::string, pathspec_t> &map);
explicit pathspec_t(counted_t<const datum_t> datum);
~pathspec_t();
const std::string *as_str() const {
return (type == STR ? str : NULL);
}
const std::vector<pathspec_t> *as_vec() const {
return (type == VEC ? vec: NULL);
}
const std::map<std::string, pathspec_t> *as_map() const {
return (type == MAP ? map : NULL);
}
class malformed_pathspec_exc_t : public std::exception {
const char *what() const throw () {
return "Couldn't compile pathspec.";
}
};
std::string print_tabs(int tabs) const {
std::string res;
while (tabs --> 0) { res += "\t"; }
return res;
}
std::string print(int tabs = 0) const {
std::string res;
switch (type) {
case STR:
res += print_tabs(tabs) + strprintf("STR: %s\n", str->c_str());
break;
case VEC:
res += print_tabs(tabs) + strprintf("VEC:\n");
for (auto it = vec->begin(); it != vec->end(); ++it) {
res += it->print(tabs + 1);
}
break;
case MAP:
res += print_tabs(tabs) + strprintf("MAP:\n");
for (auto it = map->begin(); it != map->end(); ++it) {
res += print_tabs(tabs + 1) + strprintf("%s:\n", it->first.c_str());
res += it->second.print(tabs + 2);
}
break;
default:
unreachable();
break;
}
return res;
}
private:
enum type_t {
STR,
VEC,
MAP
} type;
union {
std::string *str;
std::vector<pathspec_t> *vec;
std::map<std::string, pathspec_t> *map;
};
void init_from(const pathspec_t &other);
};
enum recurse_flag_t {
RECURSE,
DONT_RECURSE
};
/* Limit the datum to only the paths specified by the pathspec. */
counted_t<const datum_t> project(counted_t<const datum_t> datum,
const pathspec_t &pathspec, recurse_flag_t recurse);
/* Limit the datum to only the paths not specified by the pathspec. */
counted_t<const datum_t> unproject(counted_t<const datum_t> datum,
const pathspec_t &pathspec, recurse_flag_t recurse);
/* Return whether or not ALL of the paths in the pathspec exist in the datum. */
bool contains(counted_t<const datum_t> datum,
const pathspec_t &pathspec, recurse_flag_t recurse);
} //namespace ql
#endif
<commit_msg>Remove print tabs function.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_PATHSPEC_HPP_
#define RDB_PROTOCOL_PATHSPEC_HPP_
#include "errors.hpp"
#include <boost/variant.hpp>
#include "rdb_protocol/datum.hpp"
namespace ql {
class pathspec_t {
public:
pathspec_t(const pathspec_t &other);
pathspec_t& operator=(const pathspec_t &other);
explicit pathspec_t(const std::string &str);
explicit pathspec_t(const std::map<std::string, pathspec_t> &map);
explicit pathspec_t(counted_t<const datum_t> datum);
~pathspec_t();
const std::string *as_str() const {
return (type == STR ? str : NULL);
}
const std::vector<pathspec_t> *as_vec() const {
return (type == VEC ? vec: NULL);
}
const std::map<std::string, pathspec_t> *as_map() const {
return (type == MAP ? map : NULL);
}
class malformed_pathspec_exc_t : public std::exception {
const char *what() const throw () {
return "Couldn't compile pathspec.";
}
};
std::string print(int tabs = 0) const {
std::string res;
switch (type) {
case STR:
res += std::string(tabs * 2, ' ') + strprintf("STR: %s\n", str->c_str());
break;
case VEC:
res += std::string(tabs * 2, ' ') + strprintf("VEC:\n");
for (auto it = vec->begin(); it != vec->end(); ++it) {
res += it->print(tabs + 1);
}
break;
case MAP:
res += std::string(tabs * 2, ' ') + strprintf("MAP:\n");
for (auto it = map->begin(); it != map->end(); ++it) {
res += std::string(tabs * 2, ' ') + strprintf("%s:\n", it->first.c_str());
res += it->second.print(tabs + 2);
}
break;
default:
unreachable();
break;
}
return res;
}
private:
enum type_t {
STR,
VEC,
MAP
} type;
union {
std::string *str;
std::vector<pathspec_t> *vec;
std::map<std::string, pathspec_t> *map;
};
void init_from(const pathspec_t &other);
};
enum recurse_flag_t {
RECURSE,
DONT_RECURSE
};
/* Limit the datum to only the paths specified by the pathspec. */
counted_t<const datum_t> project(counted_t<const datum_t> datum,
const pathspec_t &pathspec, recurse_flag_t recurse);
/* Limit the datum to only the paths not specified by the pathspec. */
counted_t<const datum_t> unproject(counted_t<const datum_t> datum,
const pathspec_t &pathspec, recurse_flag_t recurse);
/* Return whether or not ALL of the paths in the pathspec exist in the datum. */
bool contains(counted_t<const datum_t> datum,
const pathspec_t &pathspec, recurse_flag_t recurse);
} //namespace ql
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#ifndef REALM_SORT_DESCRIPTOR_HPP
#define REALM_SORT_DESCRIPTOR_HPP
#include <vector>
#include <unordered_set>
#include <realm/cluster.hpp>
#include <realm/mixed.hpp>
namespace realm {
class SortDescriptor;
class ConstTableRef;
class Group;
enum class DescriptorType { Sort, Distinct, Limit};
struct LinkPathPart {
// Constructor for forward links
LinkPathPart(ColKey col_key)
: column_key(col_key)
{
}
// Constructor for backward links. Source table must be a valid table.
LinkPathPart(ColKey col_key, ConstTableRef source);
// Each step in the path can be a forward or a backward link.
// In case of a backlink, the column_key indicates the origin link column
// (the forward link column in the origin table), not the backlink column
// itself.
ColKey column_key;
// "from" is omitted to indicate forward links, if it is valid then
// this path describes a backlink originating from the column from[column_key]
TableKey from;
};
class BaseDescriptor {
public:
struct IndexPair {
IndexPair(ObjKey k, size_t i)
: key_for_object(k)
, index_in_view(i)
{
}
bool operator<(const IndexPair& other) const
{
return index_in_view < other.index_in_view;
}
ObjKey key_for_object;
size_t index_in_view;
Mixed cached_value;
};
class IndexPairs : public std::vector<BaseDescriptor::IndexPair> {
public:
size_t m_removed_by_limit = 0;
};
class Sorter {
public:
Sorter(std::vector<std::vector<ColKey>> const& columns, std::vector<bool> const& ascending,
Table const& root_table, const IndexPairs& indexes);
Sorter()
{
}
bool operator()(IndexPair i, IndexPair j, bool total_ordering = true) const;
bool has_links() const
{
return std::any_of(m_columns.begin(), m_columns.end(),
[](auto&& col) { return !col.translated_keys.empty(); });
}
bool any_is_null(IndexPair i) const
{
return std::any_of(m_columns.begin(), m_columns.end(), [=](auto&& col) {
return col.is_null.empty() ? false : col.is_null[i.index_in_view];
});
}
void cache_first_column(IndexPairs& v);
private:
struct SortColumn {
SortColumn(const Table* t, ColKey c, bool a)
: table(t)
, col_key(c)
, ascending(a)
{
}
std::vector<bool> is_null;
std::vector<ObjKey> translated_keys;
const Table* table;
ColKey col_key;
bool ascending;
};
std::vector<SortColumn> m_columns;
friend class ObjList;
};
BaseDescriptor() = default;
virtual ~BaseDescriptor() = default;
virtual bool is_valid() const noexcept = 0;
virtual std::string get_description(ConstTableRef attached_table) const = 0;
virtual std::unique_ptr<BaseDescriptor> clone() const = 0;
virtual DescriptorType get_type() const = 0;
virtual void collect_dependencies(const Table* table, std::vector<TableKey>& table_keys) const = 0;
virtual Sorter sorter(Table const& table, const IndexPairs& indexes) const = 0;
// Do what you have to do
virtual void execute(IndexPairs& v, const Sorter& predicate, const BaseDescriptor* next) const = 0;
};
// ColumnsDescriptor encapsulates a reference to a set of columns (possibly over
// links), which is used to indicate the criteria columns for sort and distinct.
class ColumnsDescriptor : public BaseDescriptor {
public:
ColumnsDescriptor() = default;
// Create a descriptor for the given columns on the given table.
// Each vector in `column_keys` represents a chain of columns, where
// all but the last are Link columns (n.b.: LinkList and Backlink are not
// supported), and the final is any column type that can be sorted on.
// `column_keys` must be non-empty, and each vector within it must also
// be non-empty.
ColumnsDescriptor(std::vector<std::vector<ColKey>> column_keys);
// returns whether this descriptor is valid and can be used for sort or distinct
bool is_valid() const noexcept override
{
return !m_column_keys.empty();
}
void collect_dependencies(const Table* table, std::vector<TableKey>& table_keys) const override;
protected:
std::vector<std::vector<ColKey>> m_column_keys;
};
class DistinctDescriptor : public ColumnsDescriptor {
public:
DistinctDescriptor() = default;
DistinctDescriptor(std::vector<std::vector<ColKey>> column_keys)
: ColumnsDescriptor(std::move(column_keys))
{
}
std::unique_ptr<BaseDescriptor> clone() const override;
DescriptorType get_type() const override
{
return DescriptorType::Distinct;
}
Sorter sorter(Table const& table, const IndexPairs& indexes) const override;
void execute(IndexPairs& v, const Sorter& predicate, const BaseDescriptor* next) const override;
std::string get_description(ConstTableRef attached_table) const override;
};
class SortDescriptor : public ColumnsDescriptor {
public:
// Create a sort descriptor for the given columns on the given table.
// See ColumnsDescriptor for restrictions on `column_keys`.
// The sort order can be specified by using `ascending` which must either be
// empty or have one entry for each column index chain.
SortDescriptor(std::vector<std::vector<ColKey>> column_indices, std::vector<bool> ascending = {});
SortDescriptor() = default;
~SortDescriptor() = default;
std::unique_ptr<BaseDescriptor> clone() const override;
DescriptorType get_type() const override
{
return DescriptorType::Sort;
}
util::Optional<bool> is_ascending(size_t ndx) const
{
if (ndx < m_ascending.size()) {
return util::Optional<bool>(m_ascending[ndx]);
}
return util::none;
}
enum class MergeMode {
/// If another sort has just been applied, merge before it, so it takes primary precedence
/// this is used for time based scenarios where building the last applied sort is the most important
/// default historical behaviour
append,
/// If another sort has just been applied, merge after it to take secondary precedence
/// this is used to construct sorts in a builder pattern where the first applied sort remains the most
/// important
prepend,
/// Replace this sort descriptor with another
replace
};
void merge(SortDescriptor&& other, MergeMode mode);
Sorter sorter(Table const& table, const IndexPairs& indexes) const override;
void execute(IndexPairs& v, const Sorter& predicate, const BaseDescriptor* next) const override;
std::string get_description(ConstTableRef attached_table) const override;
private:
std::vector<bool> m_ascending;
};
class LimitDescriptor : public BaseDescriptor {
public:
LimitDescriptor(size_t limit)
: m_limit(limit)
{
}
LimitDescriptor() = default;
~LimitDescriptor() = default;
bool is_valid() const noexcept override
{
return m_limit != size_t(-1);
}
std::string get_description(ConstTableRef attached_table) const override;
std::unique_ptr<BaseDescriptor> clone() const override;
size_t get_limit() const noexcept
{
return m_limit;
}
DescriptorType get_type() const override
{
return DescriptorType::Limit;
}
Sorter sorter(Table const&, const IndexPairs&) const override
{
return Sorter();
}
void collect_dependencies(const Table*, std::vector<TableKey>&) const override
{
}
void execute(IndexPairs& v, const Sorter& predicate, const BaseDescriptor* next) const override;
private:
size_t m_limit = size_t(-1);
};
class DescriptorOrdering {
public:
DescriptorOrdering() = default;
DescriptorOrdering(const DescriptorOrdering&);
DescriptorOrdering(DescriptorOrdering&&) = default;
DescriptorOrdering& operator=(const DescriptorOrdering&);
DescriptorOrdering& operator=(DescriptorOrdering&&) = default;
void append_sort(SortDescriptor sort, SortDescriptor::MergeMode mode = SortDescriptor::MergeMode::prepend);
void append_distinct(DistinctDescriptor distinct);
void append_limit(LimitDescriptor limit);
realm::util::Optional<size_t> get_min_limit() const;
/// Remove all LIMIT statements from this descriptor ordering, returning the
/// minimum LIMIT value that existed. If there was no LIMIT statement,
/// returns `none`.
util::Optional<size_t> remove_all_limits();
bool will_limit_to_zero() const;
DescriptorType get_type(size_t index) const;
bool is_empty() const
{
return m_descriptors.empty();
}
size_t size() const
{
return m_descriptors.size();
}
const BaseDescriptor* operator[](size_t ndx) const;
bool will_apply_sort() const;
bool will_apply_distinct() const;
bool will_apply_limit() const;
std::string get_description(ConstTableRef target_table) const;
void collect_dependencies(const Table* table);
void get_versions(const Group* group, TableVersions& versions) const;
private:
std::vector<std::unique_ptr<BaseDescriptor>> m_descriptors;
std::vector<TableKey> m_dependencies;
};
}
#endif /* REALM_SORT_DESCRIPTOR_HPP */
<commit_msg>Update src/realm/sort_descriptor.hpp<commit_after>/*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#ifndef REALM_SORT_DESCRIPTOR_HPP
#define REALM_SORT_DESCRIPTOR_HPP
#include <vector>
#include <unordered_set>
#include <realm/cluster.hpp>
#include <realm/mixed.hpp>
namespace realm {
class SortDescriptor;
class ConstTableRef;
class Group;
enum class DescriptorType { Sort, Distinct, Limit };
struct LinkPathPart {
// Constructor for forward links
LinkPathPart(ColKey col_key)
: column_key(col_key)
{
}
// Constructor for backward links. Source table must be a valid table.
LinkPathPart(ColKey col_key, ConstTableRef source);
// Each step in the path can be a forward or a backward link.
// In case of a backlink, the column_key indicates the origin link column
// (the forward link column in the origin table), not the backlink column
// itself.
ColKey column_key;
// "from" is omitted to indicate forward links, if it is valid then
// this path describes a backlink originating from the column from[column_key]
TableKey from;
};
class BaseDescriptor {
public:
struct IndexPair {
IndexPair(ObjKey k, size_t i)
: key_for_object(k)
, index_in_view(i)
{
}
bool operator<(const IndexPair& other) const
{
return index_in_view < other.index_in_view;
}
ObjKey key_for_object;
size_t index_in_view;
Mixed cached_value;
};
class IndexPairs : public std::vector<BaseDescriptor::IndexPair> {
public:
size_t m_removed_by_limit = 0;
};
class Sorter {
public:
Sorter(std::vector<std::vector<ColKey>> const& columns, std::vector<bool> const& ascending,
Table const& root_table, const IndexPairs& indexes);
Sorter()
{
}
bool operator()(IndexPair i, IndexPair j, bool total_ordering = true) const;
bool has_links() const
{
return std::any_of(m_columns.begin(), m_columns.end(),
[](auto&& col) { return !col.translated_keys.empty(); });
}
bool any_is_null(IndexPair i) const
{
return std::any_of(m_columns.begin(), m_columns.end(), [=](auto&& col) {
return col.is_null.empty() ? false : col.is_null[i.index_in_view];
});
}
void cache_first_column(IndexPairs& v);
private:
struct SortColumn {
SortColumn(const Table* t, ColKey c, bool a)
: table(t)
, col_key(c)
, ascending(a)
{
}
std::vector<bool> is_null;
std::vector<ObjKey> translated_keys;
const Table* table;
ColKey col_key;
bool ascending;
};
std::vector<SortColumn> m_columns;
friend class ObjList;
};
BaseDescriptor() = default;
virtual ~BaseDescriptor() = default;
virtual bool is_valid() const noexcept = 0;
virtual std::string get_description(ConstTableRef attached_table) const = 0;
virtual std::unique_ptr<BaseDescriptor> clone() const = 0;
virtual DescriptorType get_type() const = 0;
virtual void collect_dependencies(const Table* table, std::vector<TableKey>& table_keys) const = 0;
virtual Sorter sorter(Table const& table, const IndexPairs& indexes) const = 0;
// Do what you have to do
virtual void execute(IndexPairs& v, const Sorter& predicate, const BaseDescriptor* next) const = 0;
};
// ColumnsDescriptor encapsulates a reference to a set of columns (possibly over
// links), which is used to indicate the criteria columns for sort and distinct.
class ColumnsDescriptor : public BaseDescriptor {
public:
ColumnsDescriptor() = default;
// Create a descriptor for the given columns on the given table.
// Each vector in `column_keys` represents a chain of columns, where
// all but the last are Link columns (n.b.: LinkList and Backlink are not
// supported), and the final is any column type that can be sorted on.
// `column_keys` must be non-empty, and each vector within it must also
// be non-empty.
ColumnsDescriptor(std::vector<std::vector<ColKey>> column_keys);
// returns whether this descriptor is valid and can be used for sort or distinct
bool is_valid() const noexcept override
{
return !m_column_keys.empty();
}
void collect_dependencies(const Table* table, std::vector<TableKey>& table_keys) const override;
protected:
std::vector<std::vector<ColKey>> m_column_keys;
};
class DistinctDescriptor : public ColumnsDescriptor {
public:
DistinctDescriptor() = default;
DistinctDescriptor(std::vector<std::vector<ColKey>> column_keys)
: ColumnsDescriptor(std::move(column_keys))
{
}
std::unique_ptr<BaseDescriptor> clone() const override;
DescriptorType get_type() const override
{
return DescriptorType::Distinct;
}
Sorter sorter(Table const& table, const IndexPairs& indexes) const override;
void execute(IndexPairs& v, const Sorter& predicate, const BaseDescriptor* next) const override;
std::string get_description(ConstTableRef attached_table) const override;
};
class SortDescriptor : public ColumnsDescriptor {
public:
// Create a sort descriptor for the given columns on the given table.
// See ColumnsDescriptor for restrictions on `column_keys`.
// The sort order can be specified by using `ascending` which must either be
// empty or have one entry for each column index chain.
SortDescriptor(std::vector<std::vector<ColKey>> column_indices, std::vector<bool> ascending = {});
SortDescriptor() = default;
~SortDescriptor() = default;
std::unique_ptr<BaseDescriptor> clone() const override;
DescriptorType get_type() const override
{
return DescriptorType::Sort;
}
util::Optional<bool> is_ascending(size_t ndx) const
{
if (ndx < m_ascending.size()) {
return util::Optional<bool>(m_ascending[ndx]);
}
return util::none;
}
enum class MergeMode {
/// If another sort has just been applied, merge before it, so it takes primary precedence
/// this is used for time based scenarios where building the last applied sort is the most important
/// default historical behaviour
append,
/// If another sort has just been applied, merge after it to take secondary precedence
/// this is used to construct sorts in a builder pattern where the first applied sort remains the most
/// important
prepend,
/// Replace this sort descriptor with another
replace
};
void merge(SortDescriptor&& other, MergeMode mode);
Sorter sorter(Table const& table, const IndexPairs& indexes) const override;
void execute(IndexPairs& v, const Sorter& predicate, const BaseDescriptor* next) const override;
std::string get_description(ConstTableRef attached_table) const override;
private:
std::vector<bool> m_ascending;
};
class LimitDescriptor : public BaseDescriptor {
public:
LimitDescriptor(size_t limit)
: m_limit(limit)
{
}
LimitDescriptor() = default;
~LimitDescriptor() = default;
bool is_valid() const noexcept override
{
return m_limit != size_t(-1);
}
std::string get_description(ConstTableRef attached_table) const override;
std::unique_ptr<BaseDescriptor> clone() const override;
size_t get_limit() const noexcept
{
return m_limit;
}
DescriptorType get_type() const override
{
return DescriptorType::Limit;
}
Sorter sorter(Table const&, const IndexPairs&) const override
{
return Sorter();
}
void collect_dependencies(const Table*, std::vector<TableKey>&) const override
{
}
void execute(IndexPairs& v, const Sorter& predicate, const BaseDescriptor* next) const override;
private:
size_t m_limit = size_t(-1);
};
class DescriptorOrdering {
public:
DescriptorOrdering() = default;
DescriptorOrdering(const DescriptorOrdering&);
DescriptorOrdering(DescriptorOrdering&&) = default;
DescriptorOrdering& operator=(const DescriptorOrdering&);
DescriptorOrdering& operator=(DescriptorOrdering&&) = default;
void append_sort(SortDescriptor sort, SortDescriptor::MergeMode mode = SortDescriptor::MergeMode::prepend);
void append_distinct(DistinctDescriptor distinct);
void append_limit(LimitDescriptor limit);
realm::util::Optional<size_t> get_min_limit() const;
/// Remove all LIMIT statements from this descriptor ordering, returning the
/// minimum LIMIT value that existed. If there was no LIMIT statement,
/// returns `none`.
util::Optional<size_t> remove_all_limits();
bool will_limit_to_zero() const;
DescriptorType get_type(size_t index) const;
bool is_empty() const
{
return m_descriptors.empty();
}
size_t size() const
{
return m_descriptors.size();
}
const BaseDescriptor* operator[](size_t ndx) const;
bool will_apply_sort() const;
bool will_apply_distinct() const;
bool will_apply_limit() const;
std::string get_description(ConstTableRef target_table) const;
void collect_dependencies(const Table* table);
void get_versions(const Group* group, TableVersions& versions) const;
private:
std::vector<std::unique_ptr<BaseDescriptor>> m_descriptors;
std::vector<TableKey> m_dependencies;
};
}
#endif /* REALM_SORT_DESCRIPTOR_HPP */
<|endoftext|> |
<commit_before>#include "atrac1_bitalloc.h"
#include "atrac1_scale.h"
#include "atrac1.h"
#include <math.h>
#include <cassert>
#include "../bitstream/bitstream.h"
namespace NAtrac1 {
using std::vector;
using std::cerr;
using std::endl;
static const uint32_t FixedBitAllocTableLong[MAX_BFUS] = {
7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 6,
6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4,
4, 4, 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 1, 0, 0, 0
};
//returns 1 for tone-like, 0 - noise-like
static double AnalizeSpread(const std::vector<TScaledBlock>& scaledBlocks) {
double s = 0.0;
for (int i = 0; i < scaledBlocks.size(); ++i) {
s += scaledBlocks[i].ScaleFactorIndex;
}
s /= scaledBlocks.size();
double sigma = 0.0;
double xxx = 0.0;
for (int i = 0; i < scaledBlocks.size(); ++i) {
xxx = (scaledBlocks[i].ScaleFactorIndex - s);
xxx *= xxx;
sigma += xxx;
}
sigma /= scaledBlocks.size();
sigma = sqrt(sigma);
if (sigma > 14.0)
sigma = 14.0;
return sigma/14.0;
}
vector<uint32_t> TAtrac1SimpleBitAlloc::CalcBitsAllocation(const std::vector<TScaledBlock>& scaledBlocks, const uint32_t bfuNum, const double spread, const double shift) {
vector<uint32_t> bitsPerEachBlock(bfuNum);
for (int i = 0; i < bitsPerEachBlock.size(); ++i) {
int tmp = spread * ( (double)scaledBlocks[i].ScaleFactorIndex/3.2) + (1.0 - spread) * (FixedBitAllocTableLong[i]) - shift;
if (tmp > 16) {
bitsPerEachBlock[i] = 16;
} else if (tmp < 2) {
bitsPerEachBlock[i] = 0;
} else {
bitsPerEachBlock[i] = tmp;
}
}
return bitsPerEachBlock;
}
uint32_t TAtrac1SimpleBitAlloc::GetMaxUsedBfuId(const vector<uint32_t>& bitsPerEachBlock) {
uint32_t idx = 7;
for (;;) {
uint32_t bfuNum = BfuAmountTab[idx];
if (bfuNum > bitsPerEachBlock.size()) {
idx--;
} else if (idx != 0) {
assert(bfuNum == bitsPerEachBlock.size());
uint32_t i = 0;
while (idx && bitsPerEachBlock[bfuNum - 1 - i] == 0) {
if (++i >= (BfuAmountTab[idx] - BfuAmountTab[idx-1])) {
idx--;
bfuNum -= i;
i = 0;
}
assert(bfuNum - i >= 1);
}
break;
} else {
break;
}
}
return idx;
}
uint32_t TAtrac1SimpleBitAlloc::CheckBfuUsage(bool* changed, uint32_t curBfuId, const vector<uint32_t>& bitsPerEachBlock)
{
uint32_t usedBfuId = GetMaxUsedBfuId(bitsPerEachBlock);
if (usedBfuId < curBfuId) {
*changed = true;
curBfuId = FastBfuNumSearch ? usedBfuId : (curBfuId - 1);
}
return curBfuId;
}
uint32_t TAtrac1SimpleBitAlloc::Write(const std::vector<TScaledBlock>& scaledBlocks) {
uint32_t bfuIdx = BfuIdxConst ? BfuIdxConst - 1 : 7;
bool autoBfu = !BfuIdxConst;
double spread = AnalizeSpread(scaledBlocks);
vector<uint32_t> bitsPerEachBlock(BfuAmountTab[bfuIdx]);
for (;;) {
bitsPerEachBlock.resize(BfuAmountTab[bfuIdx]);
const uint32_t bitsAvaliablePerBfus = SoundUnitSize * 8 - BitsPerBfuAmountTabIdx - 32 - 2 - 3 - bitsPerEachBlock.size() * (BitsPerIDWL + BitsPerIDSF);
double maxShift = 6;
double minShift = -2;
double shift = 3.0;
const uint32_t maxBits = bitsAvaliablePerBfus;
const uint32_t minBits = bitsAvaliablePerBfus - 110;
bool bfuNumChanged = false;
for (;;) {
const vector<uint32_t>& tmpAlloc = CalcBitsAllocation(scaledBlocks, BfuAmountTab[bfuIdx], spread, shift);
uint32_t bitsUsed = 0;
for (int i = 0; i < tmpAlloc.size(); i++) {
bitsUsed += SpecsPerBlock[i] * tmpAlloc[i];
}
//std::cout << spread << " bitsUsed: " << bitsUsed << " min " << minBits << " max " << maxBits << endl;
if (bitsUsed < minBits) {
if (maxShift - minShift < 0.1) {
if (autoBfu) {
bfuIdx = CheckBfuUsage(&bfuNumChanged, bfuIdx, tmpAlloc);
}
if (!bfuNumChanged) {
bitsPerEachBlock = tmpAlloc;
}
break;
}
maxShift = shift;
shift -= (shift - minShift) / 2;
} else if (bitsUsed > maxBits) {
minShift = shift;
shift += (maxShift - shift) / 2;
} else {
if (autoBfu) {
bfuIdx = CheckBfuUsage(&bfuNumChanged, bfuIdx, tmpAlloc);
}
if (!bfuNumChanged) {
bitsPerEachBlock = tmpAlloc;
}
break;
}
}
if (!bfuNumChanged)
break;
}
WriteBitStream(bitsPerEachBlock, scaledBlocks, bfuIdx);
return BfuAmountTab[bfuIdx];
}
void TAtrac1BitStreamWriter::WriteBitStream(const vector<uint32_t>& bitsPerEachBlock, const std::vector<TScaledBlock>& scaledBlocks, uint32_t bfuAmountIdx) {
NBitStream::TBitStream bitStream;
int bitUsed = 0;
if (bfuAmountIdx >= (1 << BitsPerBfuAmountTabIdx)) {
cerr << "Wrong bfuAmountIdx (" << bfuAmountIdx << "), frame skiped" << endl;
return;
}
bitStream.Write(0x2, 2);
bitUsed+=2;
bitStream.Write(0x2, 2);
bitUsed+=2;
bitStream.Write(0x3, 2);
bitStream.Write(0, 2);
bitUsed+=4;
bitStream.Write(bfuAmountIdx, BitsPerBfuAmountTabIdx);
bitUsed += BitsPerBfuAmountTabIdx;
bitStream.Write(0, 2);
bitStream.Write(0, 3);
bitUsed+= 5;
for (const auto wordLength : bitsPerEachBlock) {
const auto tmp = wordLength ? (wordLength - 1) : 0;
bitStream.Write(tmp, 4);
bitUsed+=4;
}
for (int i = 0; i < bitsPerEachBlock.size(); ++i) {
bitStream.Write(scaledBlocks[i].ScaleFactorIndex, 6);
bitUsed+=6;
}
for (int i = 0; i < bitsPerEachBlock.size(); ++i) {
const auto wordLength = bitsPerEachBlock[i];
if (wordLength == 0 || wordLength == 1)
continue;
const double multiple = ((1 << (wordLength - 1)) - 1);
for (const double val : scaledBlocks[i].Values) {
const int tmp = round(val * multiple);
const int testwl = bitsPerEachBlock[i] ? (bitsPerEachBlock[i] - 1) : 0;
const int a = !!testwl + testwl;
if (a != wordLength) {
cerr << "wordlen error " << a << " " << wordLength << endl;
abort();
}
bitStream.Write(NBitStream::MakeSign(tmp, wordLength), wordLength);
bitUsed+=wordLength;
}
}
bitStream.Write(0x0, 8);
bitStream.Write(0x0, 8);
bitUsed+=16;
bitStream.Write(0x0, 8);
bitUsed+=8;
if (bitUsed > SoundUnitSize * 8) {
cerr << "ATRAC1 bitstream corrupted, used: " << bitUsed << " exp: " << SoundUnitSize * 8 << endl;
abort();
}
Container->WriteFrame(bitStream.GetBytes());
}
}
<commit_msg>fix bitrate shift constant.<commit_after>#include "atrac1_bitalloc.h"
#include "atrac1_scale.h"
#include "atrac1.h"
#include <math.h>
#include <cassert>
#include "../bitstream/bitstream.h"
namespace NAtrac1 {
using std::vector;
using std::cerr;
using std::endl;
static const uint32_t FixedBitAllocTableLong[MAX_BFUS] = {
7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 6,
6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4,
4, 4, 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 1, 0, 0, 0
};
//returns 1 for tone-like, 0 - noise-like
static double AnalizeSpread(const std::vector<TScaledBlock>& scaledBlocks) {
double s = 0.0;
for (int i = 0; i < scaledBlocks.size(); ++i) {
s += scaledBlocks[i].ScaleFactorIndex;
}
s /= scaledBlocks.size();
double sigma = 0.0;
double xxx = 0.0;
for (int i = 0; i < scaledBlocks.size(); ++i) {
xxx = (scaledBlocks[i].ScaleFactorIndex - s);
xxx *= xxx;
sigma += xxx;
}
sigma /= scaledBlocks.size();
sigma = sqrt(sigma);
if (sigma > 14.0)
sigma = 14.0;
return sigma/14.0;
}
vector<uint32_t> TAtrac1SimpleBitAlloc::CalcBitsAllocation(const std::vector<TScaledBlock>& scaledBlocks, const uint32_t bfuNum, const double spread, const double shift) {
vector<uint32_t> bitsPerEachBlock(bfuNum);
for (int i = 0; i < bitsPerEachBlock.size(); ++i) {
int tmp = spread * ( (double)scaledBlocks[i].ScaleFactorIndex/3.2) + (1.0 - spread) * (FixedBitAllocTableLong[i]) - shift;
if (tmp > 16) {
bitsPerEachBlock[i] = 16;
} else if (tmp < 2) {
bitsPerEachBlock[i] = 0;
} else {
bitsPerEachBlock[i] = tmp;
}
}
return bitsPerEachBlock;
}
uint32_t TAtrac1SimpleBitAlloc::GetMaxUsedBfuId(const vector<uint32_t>& bitsPerEachBlock) {
uint32_t idx = 7;
for (;;) {
uint32_t bfuNum = BfuAmountTab[idx];
if (bfuNum > bitsPerEachBlock.size()) {
idx--;
} else if (idx != 0) {
assert(bfuNum == bitsPerEachBlock.size());
uint32_t i = 0;
while (idx && bitsPerEachBlock[bfuNum - 1 - i] == 0) {
if (++i >= (BfuAmountTab[idx] - BfuAmountTab[idx-1])) {
idx--;
bfuNum -= i;
i = 0;
}
assert(bfuNum - i >= 1);
}
break;
} else {
break;
}
}
return idx;
}
uint32_t TAtrac1SimpleBitAlloc::CheckBfuUsage(bool* changed, uint32_t curBfuId, const vector<uint32_t>& bitsPerEachBlock)
{
uint32_t usedBfuId = GetMaxUsedBfuId(bitsPerEachBlock);
if (usedBfuId < curBfuId) {
*changed = true;
curBfuId = FastBfuNumSearch ? usedBfuId : (curBfuId - 1);
}
return curBfuId;
}
uint32_t TAtrac1SimpleBitAlloc::Write(const std::vector<TScaledBlock>& scaledBlocks) {
uint32_t bfuIdx = BfuIdxConst ? BfuIdxConst - 1 : 7;
bool autoBfu = !BfuIdxConst;
double spread = AnalizeSpread(scaledBlocks);
vector<uint32_t> bitsPerEachBlock(BfuAmountTab[bfuIdx]);
for (;;) {
bitsPerEachBlock.resize(BfuAmountTab[bfuIdx]);
const uint32_t bitsAvaliablePerBfus = SoundUnitSize * 8 - BitsPerBfuAmountTabIdx - 32 - 2 - 3 - bitsPerEachBlock.size() * (BitsPerIDWL + BitsPerIDSF);
double maxShift = 9;
double minShift = -2;
double shift = 3.0;
const uint32_t maxBits = bitsAvaliablePerBfus;
const uint32_t minBits = bitsAvaliablePerBfus - 110;
bool bfuNumChanged = false;
for (;;) {
const vector<uint32_t>& tmpAlloc = CalcBitsAllocation(scaledBlocks, BfuAmountTab[bfuIdx], spread, shift);
uint32_t bitsUsed = 0;
for (int i = 0; i < tmpAlloc.size(); i++) {
bitsUsed += SpecsPerBlock[i] * tmpAlloc[i];
}
//std::cout << spread << " bitsUsed: " << bitsUsed << " min " << minBits << " max " << maxBits << endl;
if (bitsUsed < minBits) {
if (maxShift - minShift < 0.1) {
if (autoBfu) {
bfuIdx = CheckBfuUsage(&bfuNumChanged, bfuIdx, tmpAlloc);
}
if (!bfuNumChanged) {
bitsPerEachBlock = tmpAlloc;
}
break;
}
maxShift = shift;
shift -= (shift - minShift) / 2;
} else if (bitsUsed > maxBits) {
minShift = shift;
shift += (maxShift - shift) / 2;
} else {
if (autoBfu) {
bfuIdx = CheckBfuUsage(&bfuNumChanged, bfuIdx, tmpAlloc);
}
if (!bfuNumChanged) {
bitsPerEachBlock = tmpAlloc;
}
break;
}
}
if (!bfuNumChanged)
break;
}
WriteBitStream(bitsPerEachBlock, scaledBlocks, bfuIdx);
return BfuAmountTab[bfuIdx];
}
void TAtrac1BitStreamWriter::WriteBitStream(const vector<uint32_t>& bitsPerEachBlock, const std::vector<TScaledBlock>& scaledBlocks, uint32_t bfuAmountIdx) {
NBitStream::TBitStream bitStream;
int bitUsed = 0;
if (bfuAmountIdx >= (1 << BitsPerBfuAmountTabIdx)) {
cerr << "Wrong bfuAmountIdx (" << bfuAmountIdx << "), frame skiped" << endl;
return;
}
bitStream.Write(0x2, 2);
bitUsed+=2;
bitStream.Write(0x2, 2);
bitUsed+=2;
bitStream.Write(0x3, 2);
bitStream.Write(0, 2);
bitUsed+=4;
bitStream.Write(bfuAmountIdx, BitsPerBfuAmountTabIdx);
bitUsed += BitsPerBfuAmountTabIdx;
bitStream.Write(0, 2);
bitStream.Write(0, 3);
bitUsed+= 5;
for (const auto wordLength : bitsPerEachBlock) {
const auto tmp = wordLength ? (wordLength - 1) : 0;
bitStream.Write(tmp, 4);
bitUsed+=4;
}
for (int i = 0; i < bitsPerEachBlock.size(); ++i) {
bitStream.Write(scaledBlocks[i].ScaleFactorIndex, 6);
bitUsed+=6;
}
for (int i = 0; i < bitsPerEachBlock.size(); ++i) {
const auto wordLength = bitsPerEachBlock[i];
if (wordLength == 0 || wordLength == 1)
continue;
const double multiple = ((1 << (wordLength - 1)) - 1);
for (const double val : scaledBlocks[i].Values) {
const int tmp = round(val * multiple);
const int testwl = bitsPerEachBlock[i] ? (bitsPerEachBlock[i] - 1) : 0;
const int a = !!testwl + testwl;
if (a != wordLength) {
cerr << "wordlen error " << a << " " << wordLength << endl;
abort();
}
bitStream.Write(NBitStream::MakeSign(tmp, wordLength), wordLength);
bitUsed+=wordLength;
}
}
bitStream.Write(0x0, 8);
bitStream.Write(0x0, 8);
bitUsed+=16;
bitStream.Write(0x0, 8);
bitUsed+=8;
if (bitUsed > SoundUnitSize * 8) {
cerr << "ATRAC1 bitstream corrupted, used: " << bitUsed << " exp: " << SoundUnitSize * 8 << endl;
abort();
}
Container->WriteFrame(bitStream.GetBytes());
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "vbacommandbarcontrol.hxx"
#include "vbacommandbarcontrols.hxx"
#include <vbahelper/vbahelper.hxx>
#include <filter/msfilter/msvbahelper.hxx>
using namespace com::sun::star;
using namespace ooo::vba;
ScVbaCommandBarControl::ScVbaCommandBarControl( const css::uno::Reference< ov::XHelperInterface >& xParent, const css::uno::Reference< css::uno::XComponentContext >& xContext, const css::uno::Reference< css::container::XIndexAccess >& xSettings, VbaCommandBarHelperRef pHelper, const css::uno::Reference< css::container::XIndexAccess >& xBarSettings, const rtl::OUString& sResourceUrl ) throw (css::uno::RuntimeException) : CommandBarControl_BASE( xParent, xContext ), pCBarHelper( pHelper ), m_sResourceUrl( sResourceUrl ), m_xCurrentSettings( xSettings ), m_xBarSettings( xBarSettings ), m_nPosition( 0 ), m_bTemporary( sal_True )
{
}
ScVbaCommandBarControl::ScVbaCommandBarControl( const css::uno::Reference< ov::XHelperInterface >& xParent, const css::uno::Reference< css::uno::XComponentContext >& xContext, const css::uno::Reference< css::container::XIndexAccess >& xSettings, VbaCommandBarHelperRef pHelper, const css::uno::Reference< css::container::XIndexAccess >& xBarSettings, const rtl::OUString& sResourceUrl, sal_Int32 nPosition, sal_Bool bTemporary ) throw (css::uno::RuntimeException) : CommandBarControl_BASE( xParent, xContext ), pCBarHelper( pHelper ), m_sResourceUrl( sResourceUrl ), m_xCurrentSettings( xSettings ), m_xBarSettings( xBarSettings ), m_nPosition( nPosition ), m_bTemporary( bTemporary )
{
m_xCurrentSettings->getByIndex( nPosition ) >>= m_aPropertyValues;
}
void ScVbaCommandBarControl::ApplyChange() throw ( uno::RuntimeException )
{
uno::Reference< container::XIndexContainer > xIndexContainer( m_xCurrentSettings, uno::UNO_QUERY_THROW );
xIndexContainer->replaceByIndex( m_nPosition, uno::makeAny( m_aPropertyValues ) );
pCBarHelper->ApplyChange( m_sResourceUrl, m_xBarSettings );
}
::rtl::OUString SAL_CALL
ScVbaCommandBarControl::getCaption() throw ( uno::RuntimeException )
{
// "Label" always empty
rtl::OUString sCaption;
getPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("Label") ) >>= sCaption;
return sCaption;
}
void SAL_CALL
ScVbaCommandBarControl::setCaption( const ::rtl::OUString& _caption ) throw (uno::RuntimeException)
{
rtl::OUString sCaption = _caption.replace('&','~');
setPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("Label"), uno::makeAny( sCaption ) );
ApplyChange();
}
::rtl::OUString SAL_CALL
ScVbaCommandBarControl::getOnAction() throw (uno::RuntimeException)
{
rtl::OUString sCommandURL;
getPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("CommandURL") ) >>= sCommandURL;
return sCommandURL;
}
void SAL_CALL
ScVbaCommandBarControl::setOnAction( const ::rtl::OUString& _onaction ) throw (uno::RuntimeException)
{
// get the current model
uno::Reference< frame::XModel > xModel( pCBarHelper->getModel() );
VBAMacroResolvedInfo aResolvedMacro = ooo::vba::resolveVBAMacro( getSfxObjShell( xModel ), _onaction, true );
if ( aResolvedMacro.IsResolved() )
{
rtl::OUString aCommandURL = ooo::vba::makeMacroURL( aResolvedMacro.ResolvedMacro() );
OSL_TRACE(" ScVbaCommandBarControl::setOnAction: %s", rtl::OUStringToOString( aCommandURL, RTL_TEXTENCODING_UTF8 ).getStr() );
setPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("CommandURL"), uno::makeAny( aCommandURL ) );
ApplyChange();
}
}
::sal_Bool SAL_CALL
ScVbaCommandBarControl::getVisible() throw (uno::RuntimeException)
{
sal_Bool bVisible = sal_True;
uno::Any aValue = getPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("IsVisible") );
if( aValue.hasValue() )
aValue >>= bVisible;
return bVisible;
}
void SAL_CALL
ScVbaCommandBarControl::setVisible( ::sal_Bool _visible ) throw (uno::RuntimeException)
{
uno::Any aValue = getPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("IsVisible") );
if( aValue.hasValue() )
{
setPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("IsVisible"), uno::makeAny( _visible ) );
ApplyChange();
}
}
::sal_Bool SAL_CALL
ScVbaCommandBarControl::getEnabled() throw (uno::RuntimeException)
{
sal_Bool bEnabled = sal_True;
if( m_xParentMenu.is() )
{
// currently only the menu in the MenuBat support Enable/Disable
// FIXME: how to support the menu item in Toolbar
bEnabled = m_xParentMenu->isItemEnabled( m_xParentMenu->getItemId( sal::static_int_cast< sal_Int16 >( m_nPosition ) ) );
}
else
{
// emulated with Visible
bEnabled = getVisible();
}
return bEnabled;
}
void SAL_CALL
ScVbaCommandBarControl::setEnabled( sal_Bool _enabled ) throw (uno::RuntimeException)
{
if( m_xParentMenu.is() )
{
// currently only the menu in the MenuBat support Enable/Disable
m_xParentMenu->enableItem( m_xParentMenu->getItemId( sal::static_int_cast< sal_Int16 >( m_nPosition ) ), _enabled );
}
else
{
// emulated with Visible
setVisible( _enabled );
}
}
::sal_Bool SAL_CALL
ScVbaCommandBarControl::getBeginGroup() throw (css::uno::RuntimeException)
{
// TODO: need to check if the item before this item is of type 'separator'
return sal_False;
}
void SAL_CALL
ScVbaCommandBarControl::setBeginGroup( ::sal_Bool _begin ) throw (css::uno::RuntimeException)
{
if( getBeginGroup() != _begin )
{
// TODO: need to insert or remove an item of type 'separator' before this item
}
}
void SAL_CALL
ScVbaCommandBarControl::Delete( ) throw (script::BasicErrorException, uno::RuntimeException)
{
if( m_xCurrentSettings.is() )
{
uno::Reference< container::XIndexContainer > xIndexContainer( m_xCurrentSettings, uno::UNO_QUERY_THROW );
xIndexContainer->removeByIndex( m_nPosition );
pCBarHelper->ApplyChange( m_sResourceUrl, m_xBarSettings );
}
}
uno::Any SAL_CALL
ScVbaCommandBarControl::Controls( const uno::Any& aIndex ) throw (script::BasicErrorException, uno::RuntimeException)
{
// only Popup Menu has controls
uno::Reference< container::XIndexAccess > xSubMenu;
getPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii( ITEM_DESCRIPTOR_CONTAINER ) ) >>= xSubMenu;
if( !xSubMenu.is() )
throw uno::RuntimeException();
uno::Reference< awt::XMenu > xMenu;
if( m_xParentMenu.is() )
{
sal_Int16 nItemId = m_xParentMenu->getItemId( sal::static_int_cast< sal_Int16 >( m_nPosition ) );
xMenu.set( m_xParentMenu->getPopupMenu( nItemId ), uno::UNO_QUERY );
}
uno::Reference< XCommandBarControls > xCommandBarControls( new ScVbaCommandBarControls( this, mxContext, xSubMenu, pCBarHelper, m_xBarSettings, m_sResourceUrl, xMenu ) );
if( aIndex.hasValue() )
{
return xCommandBarControls->Item( aIndex, uno::Any() );
}
return uno::makeAny( xCommandBarControls );
}
rtl::OUString&
ScVbaCommandBarControl::getServiceImplName()
{
static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("ScVbaCommandBarControl") );
return sImplName;
}
uno::Sequence<rtl::OUString>
ScVbaCommandBarControl::getServiceNames()
{
static uno::Sequence< rtl::OUString > aServiceNames;
if ( aServiceNames.getLength() == 0 )
{
aServiceNames.realloc( 1 );
aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.CommandBarControl" ) );
}
return aServiceNames;
}
//////////// ScVbaCommandBarPopup //////////////////////////////
ScVbaCommandBarPopup::ScVbaCommandBarPopup( const css::uno::Reference< ov::XHelperInterface >& xParent, const css::uno::Reference< css::uno::XComponentContext >& xContext, const css::uno::Reference< css::container::XIndexAccess >& xSettings, VbaCommandBarHelperRef pHelper, const css::uno::Reference< css::container::XIndexAccess >& xBarSettings, const rtl::OUString& sResourceUrl, sal_Int32 nPosition, sal_Bool bTemporary, const css::uno::Reference< css::awt::XMenu >& xMenu ) throw (css::uno::RuntimeException) : CommandBarPopup_BASE( xParent, xContext, xSettings, pHelper, xBarSettings, sResourceUrl )
{
m_nPosition = nPosition;
m_bTemporary = bTemporary;
m_xCurrentSettings->getByIndex( m_nPosition ) >>= m_aPropertyValues;
m_xParentMenu = xMenu;
}
rtl::OUString&
ScVbaCommandBarPopup::getServiceImplName()
{
static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("ScVbaCommandBarPopup") );
return sImplName;
}
uno::Sequence<rtl::OUString>
ScVbaCommandBarPopup::getServiceNames()
{
static uno::Sequence< rtl::OUString > aServiceNames;
if ( aServiceNames.getLength() == 0 )
{
aServiceNames.realloc( 1 );
aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.CommandBarPopup" ) );
}
return aServiceNames;
}
//////////// ScVbaCommandBarButton //////////////////////////////
ScVbaCommandBarButton::ScVbaCommandBarButton( const css::uno::Reference< ov::XHelperInterface >& xParent, const css::uno::Reference< css::uno::XComponentContext >& xContext, const css::uno::Reference< css::container::XIndexAccess >& xSettings, VbaCommandBarHelperRef pHelper, const css::uno::Reference< css::container::XIndexAccess >& xBarSettings, const rtl::OUString& sResourceUrl, sal_Int32 nPosition, sal_Bool bTemporary, const css::uno::Reference< css::awt::XMenu >& xMenu ) throw (css::uno::RuntimeException) : CommandBarButton_BASE( xParent, xContext, xSettings, pHelper, xBarSettings, sResourceUrl )
{
m_nPosition = nPosition;
m_bTemporary = bTemporary;
m_xCurrentSettings->getByIndex( m_nPosition ) >>= m_aPropertyValues;
m_xParentMenu = xMenu;
}
rtl::OUString&
ScVbaCommandBarButton::getServiceImplName()
{
static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("ScVbaCommandBarButton") );
return sImplName;
}
uno::Sequence<rtl::OUString>
ScVbaCommandBarButton::getServiceNames()
{
static uno::Sequence< rtl::OUString > aServiceNames;
if ( aServiceNames.getLength() == 0 )
{
aServiceNames.realloc( 1 );
aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.CommandBarButton" ) );
}
return aServiceNames;
}
<commit_msg>mib19: #163532# fix for enabling and disabling custom menue entries via vba.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "vbacommandbarcontrol.hxx"
#include "vbacommandbarcontrols.hxx"
#include <vbahelper/vbahelper.hxx>
#include <filter/msfilter/msvbahelper.hxx>
using namespace com::sun::star;
using namespace ooo::vba;
ScVbaCommandBarControl::ScVbaCommandBarControl( const css::uno::Reference< ov::XHelperInterface >& xParent, const css::uno::Reference< css::uno::XComponentContext >& xContext, const css::uno::Reference< css::container::XIndexAccess >& xSettings, VbaCommandBarHelperRef pHelper, const css::uno::Reference< css::container::XIndexAccess >& xBarSettings, const rtl::OUString& sResourceUrl ) throw (css::uno::RuntimeException) : CommandBarControl_BASE( xParent, xContext ), pCBarHelper( pHelper ), m_sResourceUrl( sResourceUrl ), m_xCurrentSettings( xSettings ), m_xBarSettings( xBarSettings ), m_nPosition( 0 ), m_bTemporary( sal_True )
{
}
ScVbaCommandBarControl::ScVbaCommandBarControl( const css::uno::Reference< ov::XHelperInterface >& xParent, const css::uno::Reference< css::uno::XComponentContext >& xContext, const css::uno::Reference< css::container::XIndexAccess >& xSettings, VbaCommandBarHelperRef pHelper, const css::uno::Reference< css::container::XIndexAccess >& xBarSettings, const rtl::OUString& sResourceUrl, sal_Int32 nPosition, sal_Bool bTemporary ) throw (css::uno::RuntimeException) : CommandBarControl_BASE( xParent, xContext ), pCBarHelper( pHelper ), m_sResourceUrl( sResourceUrl ), m_xCurrentSettings( xSettings ), m_xBarSettings( xBarSettings ), m_nPosition( nPosition ), m_bTemporary( bTemporary )
{
m_xCurrentSettings->getByIndex( nPosition ) >>= m_aPropertyValues;
}
void ScVbaCommandBarControl::ApplyChange() throw ( uno::RuntimeException )
{
uno::Reference< container::XIndexContainer > xIndexContainer( m_xCurrentSettings, uno::UNO_QUERY_THROW );
xIndexContainer->replaceByIndex( m_nPosition, uno::makeAny( m_aPropertyValues ) );
pCBarHelper->ApplyChange( m_sResourceUrl, m_xBarSettings );
}
::rtl::OUString SAL_CALL
ScVbaCommandBarControl::getCaption() throw ( uno::RuntimeException )
{
// "Label" always empty
rtl::OUString sCaption;
getPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("Label") ) >>= sCaption;
return sCaption;
}
void SAL_CALL
ScVbaCommandBarControl::setCaption( const ::rtl::OUString& _caption ) throw (uno::RuntimeException)
{
rtl::OUString sCaption = _caption.replace('&','~');
setPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("Label"), uno::makeAny( sCaption ) );
ApplyChange();
}
::rtl::OUString SAL_CALL
ScVbaCommandBarControl::getOnAction() throw (uno::RuntimeException)
{
rtl::OUString sCommandURL;
getPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("CommandURL") ) >>= sCommandURL;
return sCommandURL;
}
void SAL_CALL
ScVbaCommandBarControl::setOnAction( const ::rtl::OUString& _onaction ) throw (uno::RuntimeException)
{
// get the current model
uno::Reference< frame::XModel > xModel( pCBarHelper->getModel() );
VBAMacroResolvedInfo aResolvedMacro = ooo::vba::resolveVBAMacro( getSfxObjShell( xModel ), _onaction, true );
if ( aResolvedMacro.IsResolved() )
{
rtl::OUString aCommandURL = ooo::vba::makeMacroURL( aResolvedMacro.ResolvedMacro() );
OSL_TRACE(" ScVbaCommandBarControl::setOnAction: %s", rtl::OUStringToOString( aCommandURL, RTL_TEXTENCODING_UTF8 ).getStr() );
setPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("CommandURL"), uno::makeAny( aCommandURL ) );
ApplyChange();
}
}
::sal_Bool SAL_CALL
ScVbaCommandBarControl::getVisible() throw (uno::RuntimeException)
{
sal_Bool bVisible = sal_True;
uno::Any aValue = getPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("IsVisible") );
if( aValue.hasValue() )
aValue >>= bVisible;
return bVisible;
}
void SAL_CALL
ScVbaCommandBarControl::setVisible( ::sal_Bool _visible ) throw (uno::RuntimeException)
{
uno::Any aValue = getPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("IsVisible") );
if( aValue.hasValue() )
{
setPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("IsVisible"), uno::makeAny( _visible ) );
ApplyChange();
}
}
::sal_Bool SAL_CALL
ScVbaCommandBarControl::getEnabled() throw (uno::RuntimeException)
{
sal_Bool bEnabled = sal_True;
rtl::OUString aCommandURLappendix = rtl::OUString::createFromAscii("___");
rtl::OUString aCommandURL ;
if( m_xParentMenu.is() )
{
// currently only the menu in the MenuBat support Enable/Disable
// FIXME: how to support the menu item in Toolbar
bEnabled = m_xParentMenu->isItemEnabled( m_xParentMenu->getItemId( sal::static_int_cast< sal_Int16 >( m_nPosition ) ) );
}
else
{
// emulated with Visible
//bEnabled = getVisible();
uno::Any aValue = getPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("CommandURL") );
if (aValue >>= aCommandURL){
if (0 == aCommandURL.indexOf(aCommandURLappendix)){
bEnabled = sal_False;
}
}
}
return bEnabled;
}
void SAL_CALL
ScVbaCommandBarControl::setEnabled( sal_Bool _enabled ) throw (uno::RuntimeException)
{
rtl::OUString aCommandURL ;
rtl::OUString aCommandURLappendix = rtl::OUString::createFromAscii("___");
rtl::OUStringBuffer aCommandURLSringBuffer;
if( m_xParentMenu.is() )
{
// currently only the menu in the MenuBat support Enable/Disable
m_xParentMenu->enableItem( m_xParentMenu->getItemId( sal::static_int_cast< sal_Int16 >( m_nPosition ) ), _enabled );
}
else
{
uno::Any aValue = getPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("CommandURL") );
if (aValue >>= aCommandURL){
if (0 == aCommandURL.indexOf(aCommandURLappendix)){
aCommandURL = aCommandURL.copy(3);
}
if (false == _enabled){
aCommandURLSringBuffer = aCommandURLappendix;
}
aCommandURLSringBuffer.append(aCommandURL);
setPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii("CommandURL"), uno::makeAny( aCommandURLSringBuffer.makeStringAndClear()) );
ApplyChange();
}
// emulated with Visible
//setVisible( _enabled );
}
}
::sal_Bool SAL_CALL
ScVbaCommandBarControl::getBeginGroup() throw (css::uno::RuntimeException)
{
// TODO: need to check if the item before this item is of type 'separator'
return sal_False;
}
void SAL_CALL
ScVbaCommandBarControl::setBeginGroup( ::sal_Bool _begin ) throw (css::uno::RuntimeException)
{
if( getBeginGroup() != _begin )
{
// TODO: need to insert or remove an item of type 'separator' before this item
}
}
void SAL_CALL
ScVbaCommandBarControl::Delete( ) throw (script::BasicErrorException, uno::RuntimeException)
{
if( m_xCurrentSettings.is() )
{
uno::Reference< container::XIndexContainer > xIndexContainer( m_xCurrentSettings, uno::UNO_QUERY_THROW );
xIndexContainer->removeByIndex( m_nPosition );
pCBarHelper->ApplyChange( m_sResourceUrl, m_xBarSettings );
}
}
uno::Any SAL_CALL
ScVbaCommandBarControl::Controls( const uno::Any& aIndex ) throw (script::BasicErrorException, uno::RuntimeException)
{
// only Popup Menu has controls
uno::Reference< container::XIndexAccess > xSubMenu;
getPropertyValue( m_aPropertyValues, rtl::OUString::createFromAscii( ITEM_DESCRIPTOR_CONTAINER ) ) >>= xSubMenu;
if( !xSubMenu.is() )
throw uno::RuntimeException();
uno::Reference< awt::XMenu > xMenu;
if( m_xParentMenu.is() )
{
sal_Int16 nItemId = m_xParentMenu->getItemId( sal::static_int_cast< sal_Int16 >( m_nPosition ) );
xMenu.set( m_xParentMenu->getPopupMenu( nItemId ), uno::UNO_QUERY );
}
uno::Reference< XCommandBarControls > xCommandBarControls( new ScVbaCommandBarControls( this, mxContext, xSubMenu, pCBarHelper, m_xBarSettings, m_sResourceUrl, xMenu ) );
if( aIndex.hasValue() )
{
return xCommandBarControls->Item( aIndex, uno::Any() );
}
return uno::makeAny( xCommandBarControls );
}
rtl::OUString&
ScVbaCommandBarControl::getServiceImplName()
{
static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("ScVbaCommandBarControl") );
return sImplName;
}
uno::Sequence<rtl::OUString>
ScVbaCommandBarControl::getServiceNames()
{
static uno::Sequence< rtl::OUString > aServiceNames;
if ( aServiceNames.getLength() == 0 )
{
aServiceNames.realloc( 1 );
aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.CommandBarControl" ) );
}
return aServiceNames;
}
//////////// ScVbaCommandBarPopup //////////////////////////////
ScVbaCommandBarPopup::ScVbaCommandBarPopup( const css::uno::Reference< ov::XHelperInterface >& xParent, const css::uno::Reference< css::uno::XComponentContext >& xContext, const css::uno::Reference< css::container::XIndexAccess >& xSettings, VbaCommandBarHelperRef pHelper, const css::uno::Reference< css::container::XIndexAccess >& xBarSettings, const rtl::OUString& sResourceUrl, sal_Int32 nPosition, sal_Bool bTemporary, const css::uno::Reference< css::awt::XMenu >& xMenu ) throw (css::uno::RuntimeException) : CommandBarPopup_BASE( xParent, xContext, xSettings, pHelper, xBarSettings, sResourceUrl )
{
m_nPosition = nPosition;
m_bTemporary = bTemporary;
m_xCurrentSettings->getByIndex( m_nPosition ) >>= m_aPropertyValues;
m_xParentMenu = xMenu;
}
rtl::OUString&
ScVbaCommandBarPopup::getServiceImplName()
{
static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("ScVbaCommandBarPopup") );
return sImplName;
}
uno::Sequence<rtl::OUString>
ScVbaCommandBarPopup::getServiceNames()
{
static uno::Sequence< rtl::OUString > aServiceNames;
if ( aServiceNames.getLength() == 0 )
{
aServiceNames.realloc( 1 );
aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.CommandBarPopup" ) );
}
return aServiceNames;
}
//////////// ScVbaCommandBarButton //////////////////////////////
ScVbaCommandBarButton::ScVbaCommandBarButton( const css::uno::Reference< ov::XHelperInterface >& xParent, const css::uno::Reference< css::uno::XComponentContext >& xContext, const css::uno::Reference< css::container::XIndexAccess >& xSettings, VbaCommandBarHelperRef pHelper, const css::uno::Reference< css::container::XIndexAccess >& xBarSettings, const rtl::OUString& sResourceUrl, sal_Int32 nPosition, sal_Bool bTemporary, const css::uno::Reference< css::awt::XMenu >& xMenu ) throw (css::uno::RuntimeException) : CommandBarButton_BASE( xParent, xContext, xSettings, pHelper, xBarSettings, sResourceUrl )
{
m_nPosition = nPosition;
m_bTemporary = bTemporary;
m_xCurrentSettings->getByIndex( m_nPosition ) >>= m_aPropertyValues;
m_xParentMenu = xMenu;
}
rtl::OUString&
ScVbaCommandBarButton::getServiceImplName()
{
static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("ScVbaCommandBarButton") );
return sImplName;
}
uno::Sequence<rtl::OUString>
ScVbaCommandBarButton::getServiceNames()
{
static uno::Sequence< rtl::OUString > aServiceNames;
if ( aServiceNames.getLength() == 0 )
{
aServiceNames.realloc( 1 );
aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.CommandBarButton" ) );
}
return aServiceNames;
}
<|endoftext|> |
<commit_before>#ifndef __DUMMY_BDD_HPP__
#define __DUMMY_BDD_HPP__
#include <string>
#include "core.h"
namespace dummy
{
class Describe
{
public:
Describe( const char* subject );
Describe& it( const char* behaviour, dummyTestFunction fn );
private:
std::string m_Subject;
};
// ---- implementation ----
Describe::Describe( const char* subject ) :
m_Subject(subject)
{
}
Describe& Describe::it( const char* behaviour, dummyTestFunction fn )
{
dummyAddTest((m_Subject+" "+behaviour).c_str(), fn);
return *this;
}
}
#endif
<commit_msg>Fixed bdd<commit_after>#ifndef __DUMMY_BDD_HPP__
#define __DUMMY_BDD_HPP__
#include <string>
#include "core.h"
namespace dummy
{
class Describe
{
public:
Describe( const char* subject ) : m_Subject(subject) {}
Describe& it( const char* behaviour, dummyTestFunction fn )
{
dummyAddTest((m_Subject+" "+behaviour).c_str(), fn);
return *this;
}
private:
std::string m_Subject;
};
}
#endif
<|endoftext|> |
<commit_before>I#include "dmx.h"
#include "pins_arduino.h"
#pragma region 상수
const char COMMAND_DELIMITER = ':';
const char COMMAND_TOKEN = '#';
const char COMMAND_FTOKEN = '+';
#pragma endregion
#pragma region 변수
byte value[512] = {0, };
int DMX_PIN;
#pragma endregion
#pragma region 사용자 함수
void dmx::setPin(int _pin)
{
DMX_PIN = _pin;
pinMode(_pin, OUTPUT);
}
void dmx::write(String command)
{
Serial.print(command);
int *CommandValue = dmx::parseCommand(command);
dmx::execute(CommandValue);
}
#pragma endregion
#pragma region 내부 함수
int * dmx::parseCommand(String command)
{
int *param;
char tmp[4];
int i;
for (i = 3; i <= 6; i++)
{
if (command[i] == COMMAND_DELIMITER)
{
command.substring(3, i+1).toCharArray(tmp,4);
param[1] = atoi(tmp);
break;
}
else
{
}
}
for (int j = i+1; j <= 11; j++)
{
if (command[j] == COMMAND_TOKEN)
{
command.substring(i+1, j+1).toCharArray(tmp,4);
param[2] = atoi(tmp);
break;
}
}
//?
param[0] = command[1];
Serial.print(" : ");
Serial.print(param[0]);
Serial.print(", ");
Serial.print(param[1]);
Serial.print(", ");
Serial.print(param[2]);
Serial.println();
return param;
}
void dmx::execute (int *CommandValue)
{
if (CommandValue[0] == 'e')
{
dmx::update(CommandValue[1], CommandValue[2]);
} else if (CommandValue[0] == 'd')
{
delay(CommandValue[2]);
}
}
void dmx::update(int chan, int val)
{
digitalWrite(DMX_PIN, LOW);
delay(1);
dmx::shiftOut(DMX_PIN, 0);
value[chan-1] = val;
for (int i = 0; i < 32; i++)
{
dmx::shiftOut(DMX_PIN, value[i]);
}
Serial.print(" : ");
Serial.print(chan);
Serial.print(", ");
Serial.println(val);
}
void dmx::shiftOut(int pin, int theByte)
{
int port_to_output[] = {
NOT_A_PORT,
NOT_A_PORT,
_SFR_IO_ADDR(PORTB),
_SFR_IO_ADDR(PORTC),
_SFR_IO_ADDR(PORTD)
};
int portNumber = port_to_output[digitalPinToPort(pin)];
int pinMask = digitalPinToBitMask(pin);
// the first thing we do is to write te pin to high
// it will be the mark between bytes. It may be also
// high from before
_SFR_BYTE(_SFR_IO8(portNumber)) |= pinMask;
delayMicroseconds(10);
// disable interrupts, otherwise the timer 0 overflow interrupt that
// tracks milliseconds will make us delay longer than we want.
cli();
// DMX starts with a start-bit that must always be zero
_SFR_BYTE(_SFR_IO8(portNumber)) &= ~pinMask;
// we need a delay of 4us (then one bit is transfered)
// this seems more stable then using delayMicroseconds
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
for (int i = 0; i < 8; i++)
{
if (theByte & 01)
{
_SFR_BYTE(_SFR_IO8(portNumber)) |= pinMask;
}
else
{
_SFR_BYTE(_SFR_IO8(portNumber)) &= ~pinMask;
}
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
theByte >>= 1;
}
// the last thing we do is to write the pin to high
// it will be the mark between bytes. (this break is have to be between 8 us and 1 sec)
_SFR_BYTE(_SFR_IO8(portNumber)) |= pinMask;
// reenable interrupts.
sei();
}
#pragma endregion
<commit_msg>[Arduino] err?<commit_after>#include "dmx.h"
#include "pins_arduino.h"
#pragma region 상수
const char COMMAND_DELIMITER = ':';
const char COMMAND_TOKEN = '#';
const char COMMAND_FTOKEN = '+';
#pragma endregion
#pragma region 변수
byte value[512] = {0, };
int DMX_PIN;
#pragma endregion
#pragma region 사용자 함수
void dmx::setPin(int _pin)
{
DMX_PIN = _pin;
pinMode(_pin, OUTPUT);
}
void dmx::write(String command)
{
Serial.print(command);
int *CommandValue = dmx::parseCommand(command);
dmx::execute(CommandValue);
}
#pragma endregion
#pragma region 내부 함수
int * dmx::parseCommand(String command)
{
int *param;
char tmp[4];
int i;
for (i = 3; i <= 6; i++)
{
if (command[i] == COMMAND_DELIMITER)
{
command.substring(3, i+1).toCharArray(tmp,4);
param[1] = atoi(tmp);
break;
}
else
{
}
}
for (int j = i+1; j <= 11; j++)
{
if (command[j] == COMMAND_TOKEN)
{
command.substring(i+1, j+1).toCharArray(tmp,4);
param[2] = atoi(tmp);
break;
}
}
//?
param[0] = command[1];
Serial.print(" : ");
Serial.print(param[0]);
Serial.print(", ");
Serial.print(param[1]);
Serial.print(", ");
Serial.print(param[2]);
Serial.println();
return param;
}
void dmx::execute (int *CommandValue)
{
if (CommandValue[0] == 'e')
{
dmx::update(CommandValue[1], CommandValue[2]);
} else if (CommandValue[0] == 'd')
{
delay(CommandValue[2]);
}
}
void dmx::update(int chan, int val)
{
digitalWrite(DMX_PIN, LOW);
delay(1);
dmx::shiftOut(DMX_PIN, 0);
value[chan-1] = val;
for (int i = 0; i < 32; i++)
{
dmx::shiftOut(DMX_PIN, value[i]);
}
Serial.print(" : ");
Serial.print(chan);
Serial.print(", ");
Serial.println(val);
}
void dmx::shiftOut(int pin, int theByte)
{
int port_to_output[] = {
NOT_A_PORT,
NOT_A_PORT,
_SFR_IO_ADDR(PORTB),
_SFR_IO_ADDR(PORTC),
_SFR_IO_ADDR(PORTD)
};
int portNumber = port_to_output[digitalPinToPort(pin)];
int pinMask = digitalPinToBitMask(pin);
// the first thing we do is to write te pin to high
// it will be the mark between bytes. It may be also
// high from before
_SFR_BYTE(_SFR_IO8(portNumber)) |= pinMask;
delayMicroseconds(10);
// disable interrupts, otherwise the timer 0 overflow interrupt that
// tracks milliseconds will make us delay longer than we want.
cli();
// DMX starts with a start-bit that must always be zero
_SFR_BYTE(_SFR_IO8(portNumber)) &= ~pinMask;
// we need a delay of 4us (then one bit is transfered)
// this seems more stable then using delayMicroseconds
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
for (int i = 0; i < 8; i++)
{
if (theByte & 01)
{
_SFR_BYTE(_SFR_IO8(portNumber)) |= pinMask;
}
else
{
_SFR_BYTE(_SFR_IO8(portNumber)) &= ~pinMask;
}
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
asm("nop\n nop\n nop\n nop\n nop\n nop\n nop\n nop\n");
theByte >>= 1;
}
// the last thing we do is to write the pin to high
// it will be the mark between bytes. (this break is have to be between 8 us and 1 sec)
_SFR_BYTE(_SFR_IO8(portNumber)) |= pinMask;
// reenable interrupts.
sei();
}
#pragma endregion
<|endoftext|> |
<commit_before><?hh // strict
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/HttpService.hh *
* *
* hprose http service library for hack. *
* *
* LastModified: Mar 29, 2015 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose {
class HttpService extends Service {
private bool $crossDomain = false;
private bool $P3P = false;
private bool $get = true;
private Map<string, bool> $origins = Map {};
public ?(function(\stdClass): void) $onSendHeader = null;
private function sendHeader(\stdClass $context): void {
if ($this->onSendHeader !== null) {
$sendHeader = $this->onSendHeader;
$sendHeader($context);
}
header("Content-Type: text/plain");
if ($this->P3P) {
header('P3P: CP="CAO DSP COR CUR ADM DEV TAI PSA PSD ' .
'IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi ' .
'UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV ' .
'INT DEM CNT STA POL HEA PRE GOV"');
}
if ($this->crossDomain) {
// UNSAFE
if (array_key_exists('HTTP_ORIGIN', $_SERVER) &&
$_SERVER['HTTP_ORIGIN'] != "null") {
$origin = $_SERVER['HTTP_ORIGIN'];
if (count($this->origins) === 0 || $this->origins->contains(strtolower($origin))) {
header("Access-Control-Allow-Origin: " . $origin);
header("Access-Control-Allow-Credentials: true");
}
}
else {
header('Access-Control-Allow-Origin: *');
}
}
}
public function isCrossDomainEnabled(): bool {
return $this->crossDomain;
}
public function setCrossDomainEnabled(bool $enable = true): void {
$this->crossDomain = $enable;
}
public function isP3PEnabled(): bool {
return $this->P3P;
}
public function setP3PEnabled(bool $enable = true): void {
$this->P3P = $enable;
}
public function isGetEnabled(): bool {
return $this->get;
}
public function setGetEnabled(bool $enable = true): void {
$this->get = $enable;
}
public function addAccessControlAllowOrigin(string $origin): void {
$count = count($origin);
if (($count > 0) && ($origin[$count - 1] === "/")) {
$origin = substr($origin, 0, -1);
}
$this->origins[strtolower($origin)] = true;
}
public function removeAccessControlAllowOrigin(string $origin): void {
$count = count($origin);
if (($count > 0) && ($origin[$count - 1] === "/")) {
$origin = substr($origin, 0, -1);
}
$this->origins->remove(strtolower($origin));
}
public function handle(): void {
$request = file_get_contents("php://input");
$context = new \stdClass();
$context->server = $this;
$context->userdata = new \stdClass();
set_error_handler(($errno, $errstr, $errfile, $errline) ==> {
if ($this->debug) {
$errstr .= " in $errfile on line $errline";
}
$error = self::$errorTable[$errno] . ": " . $errstr;
echo $this->sendError($error, $context);
}, $this->error_types);
ob_start($data ==> {
$match = array();
if (preg_match('/<b>.*? error<\/b>:(.*?)<br/', $data, $match)) {
if ($this->debug) {
$error = preg_replace('/<.*?>/', '', $match[1]);
}
else {
$error = preg_replace('/ in <b>.*<\/b>$/', '', $match[1]);
}
return $this->sendError(trim($error), $context);
}
});
ob_implicit_flush(0);
$this->sendHeader($context);
$result = '';
// UNSAFE
if (array_key_exists('REQUEST_METHOD', $_SERVER)) {
if (($_SERVER['REQUEST_METHOD'] == 'GET') && $this->get) {
$result = $this->doFunctionList($context);
}
elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
$result = $this->defaultHandle($request, $context);
}
}
else {
$result = $this->doFunctionList($context);
}
@ob_clean();
@ob_end_flush();
echo $result;
}
}
class HttpServer extends HttpService {
public function start(): void {
$this->handle();
}
}
}
<commit_msg>Removed unnecessary @<commit_after><?hh // strict
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Hprose/HttpService.hh *
* *
* hprose http service library for hack. *
* *
* LastModified: Mar 29, 2015 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
namespace Hprose {
class HttpService extends Service {
private bool $crossDomain = false;
private bool $P3P = false;
private bool $get = true;
private Map<string, bool> $origins = Map {};
public ?(function(\stdClass): void) $onSendHeader = null;
private function sendHeader(\stdClass $context): void {
if ($this->onSendHeader !== null) {
$sendHeader = $this->onSendHeader;
$sendHeader($context);
}
header("Content-Type: text/plain");
if ($this->P3P) {
header('P3P: CP="CAO DSP COR CUR ADM DEV TAI PSA PSD ' .
'IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi ' .
'UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV ' .
'INT DEM CNT STA POL HEA PRE GOV"');
}
if ($this->crossDomain) {
// UNSAFE
if (array_key_exists('HTTP_ORIGIN', $_SERVER) &&
$_SERVER['HTTP_ORIGIN'] != "null") {
$origin = $_SERVER['HTTP_ORIGIN'];
if (count($this->origins) === 0 || $this->origins->contains(strtolower($origin))) {
header("Access-Control-Allow-Origin: " . $origin);
header("Access-Control-Allow-Credentials: true");
}
}
else {
header('Access-Control-Allow-Origin: *');
}
}
}
public function isCrossDomainEnabled(): bool {
return $this->crossDomain;
}
public function setCrossDomainEnabled(bool $enable = true): void {
$this->crossDomain = $enable;
}
public function isP3PEnabled(): bool {
return $this->P3P;
}
public function setP3PEnabled(bool $enable = true): void {
$this->P3P = $enable;
}
public function isGetEnabled(): bool {
return $this->get;
}
public function setGetEnabled(bool $enable = true): void {
$this->get = $enable;
}
public function addAccessControlAllowOrigin(string $origin): void {
$count = count($origin);
if (($count > 0) && ($origin[$count - 1] === "/")) {
$origin = substr($origin, 0, -1);
}
$this->origins[strtolower($origin)] = true;
}
public function removeAccessControlAllowOrigin(string $origin): void {
$count = count($origin);
if (($count > 0) && ($origin[$count - 1] === "/")) {
$origin = substr($origin, 0, -1);
}
$this->origins->remove(strtolower($origin));
}
public function handle(): void {
$request = file_get_contents("php://input");
$context = new \stdClass();
$context->server = $this;
$context->userdata = new \stdClass();
set_error_handler(($errno, $errstr, $errfile, $errline) ==> {
if ($this->debug) {
$errstr .= " in $errfile on line $errline";
}
$error = self::$errorTable[$errno] . ": " . $errstr;
echo $this->sendError($error, $context);
}, $this->error_types);
ob_start($data ==> {
$match = array();
if (preg_match('/<b>.*? error<\/b>:(.*?)<br/', $data, $match)) {
if ($this->debug) {
$error = preg_replace('/<.*?>/', '', $match[1]);
}
else {
$error = preg_replace('/ in <b>.*<\/b>$/', '', $match[1]);
}
return $this->sendError(trim($error), $context);
}
});
ob_implicit_flush(0);
$this->sendHeader($context);
$result = '';
// UNSAFE
if (array_key_exists('REQUEST_METHOD', $_SERVER)) {
if (($_SERVER['REQUEST_METHOD'] == 'GET') && $this->get) {
$result = $this->doFunctionList($context);
}
elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
$result = $this->defaultHandle($request, $context);
}
}
else {
$result = $this->doFunctionList($context);
}
ob_clean();
ob_end_flush();
echo $result;
}
}
class HttpServer extends HttpService {
public function start(): void {
$this->handle();
}
}
}
<|endoftext|> |
<commit_before>/// \file DboxOptions.cpp
//-----------------------------------------------------------------------------
#include "PasswordSafe.h"
#include "ThisMfcApp.h"
#if defined(POCKET_PC)
#include "pocketpc/resource.h"
#else
#include "resource.h"
#endif
#include "corelib/PWSprefs.h"
// dialog boxen
#include "DboxMain.h"
#include "OptionsSecurity.h"
#include "OptionsDisplay.h"
#include "OptionsUsername.h"
#include "OptionsPasswordPolicy.h"
#include "OptionsMisc.h"
#include <afxpriv.h>
void
DboxMain::OnOptions()
{
CPropertySheet optionsDlg(_T("Options"), this);
COptionsDisplay display;
COptionsSecurity security;
COptionsPasswordPolicy passwordpolicy;
COptionsUsername username;
COptionsMisc misc;
PWSprefs *prefs = PWSprefs::GetInstance();
/*
** Initialize the property pages values.
*/
display.m_alwaysontop = m_bAlwaysOnTop;
display.m_pwshowinedit = prefs->
GetPref(PWSprefs::BoolPrefs::ShowPWDefault) ? TRUE : FALSE;
display.m_pwshowinlist = prefs->
GetPref(PWSprefs::BoolPrefs::ShowPWInList) ? TRUE : FALSE;
#if defined(POCKET_PC)
display.m_dcshowspassword = prefs->
GetPref(PWSprefs::BoolPrefs::DCShowsPassword) ? TRUE : FALSE;
#endif
display.m_usesystemtray = prefs->
GetPref(PWSprefs::BoolPrefs::UseSystemTray) ? TRUE : FALSE;
security.m_clearclipboard = prefs->
GetPref(PWSprefs::BoolPrefs::DontAskMinimizeClearYesNo) ? TRUE : FALSE;
security.m_lockdatabase = prefs->
GetPref(PWSprefs::BoolPrefs::DatabaseClear) ? TRUE : FALSE;
security.m_confirmsaveonminimize = prefs->
GetPref(PWSprefs::BoolPrefs::DontAskSaveMinimize) ? FALSE : TRUE;
security.m_confirmcopy = prefs->
GetPref(PWSprefs::BoolPrefs::DontAskQuestion) ? FALSE : TRUE;
security.m_LockOnWindowLock = prefs->
GetPref(PWSprefs::BoolPrefs::LockOnWindowLock) ? TRUE : FALSE;
passwordpolicy.m_pwlendefault = prefs->
GetPref(PWSprefs::IntPrefs::PWLenDefault);
passwordpolicy.m_pwuselowercase = prefs->
GetPref(PWSprefs::BoolPrefs::PWUseLowercase);
passwordpolicy.m_pwuseuppercase = prefs->
GetPref(PWSprefs::BoolPrefs::PWUseUppercase);
passwordpolicy.m_pwusedigits = prefs->
GetPref(PWSprefs::BoolPrefs::PWUseDigits);
passwordpolicy.m_pwusesymbols = prefs->
GetPref(PWSprefs::BoolPrefs::PWUseSymbols);
passwordpolicy.m_pwusehexdigits = prefs->
GetPref(PWSprefs::BoolPrefs::PWUseHexDigits);
passwordpolicy.m_pweasyvision = prefs->
GetPref(PWSprefs::BoolPrefs::PWEasyVision);
username.m_usedefuser = prefs->
GetPref(PWSprefs::BoolPrefs::UseDefUser);
username.m_defusername = CString(prefs->
GetPref(PWSprefs::StringPrefs::DefUserName));
username.m_querysetdef = prefs->
GetPref(PWSprefs::BoolPrefs::QuerySetDef);
misc.m_confirmdelete = prefs->
GetPref(PWSprefs::BoolPrefs::DeleteQuestion) ? FALSE : TRUE;
misc.m_saveimmediately = prefs->
GetPref(PWSprefs::BoolPrefs::SaveImmediately) ? TRUE : FALSE;
optionsDlg.AddPage( &display );
optionsDlg.AddPage( &security );
optionsDlg.AddPage( &passwordpolicy );
optionsDlg.AddPage( &username );
optionsDlg.AddPage( &misc );
/*
** Remove the "Apply Now" button.
*/
optionsDlg.m_psh.dwFlags |= PSH_NOAPPLYNOW;
int rc = optionsDlg.DoModal();
if (rc == IDOK)
{
/*
** First save all the options.
*/
prefs->SetPref(PWSprefs::BoolPrefs::AlwaysOnTop,
display.m_alwaysontop == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::ShowPWDefault,
display.m_pwshowinedit == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::ShowPWInList,
display.m_pwshowinlist == TRUE);
#if defined(POCKET_PC)
prefs->SetPref(PWSprefs::BoolPrefs::DCShowsPassword,
display.m_dcshowspassword == TRUE);
#endif
prefs->SetPref(PWSprefs::BoolPrefs::UseSystemTray,
display.m_usesystemtray == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::DontAskMinimizeClearYesNo,
security.m_clearclipboard == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::DatabaseClear,
security.m_lockdatabase == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::DontAskSaveMinimize,
security.m_confirmsaveonminimize == FALSE);
prefs->SetPref(PWSprefs::BoolPrefs::DontAskQuestion,
security.m_confirmcopy == FALSE);
prefs->SetPref(PWSprefs::BoolPrefs::LockOnWindowLock,
security.m_LockOnWindowLock == TRUE);
prefs->SetPref(PWSprefs::IntPrefs::PWLenDefault,
passwordpolicy.m_pwlendefault);
prefs->SetPref(PWSprefs::BoolPrefs::PWUseLowercase,
passwordpolicy.m_pwuselowercase == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::PWUseUppercase,
passwordpolicy.m_pwuseuppercase == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::PWUseDigits,
passwordpolicy.m_pwusedigits == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::PWUseSymbols,
passwordpolicy.m_pwusesymbols == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::PWUseHexDigits,
passwordpolicy.m_pwusehexdigits == TRUE);
prefs-> SetPref(PWSprefs::BoolPrefs::PWEasyVision,
passwordpolicy.m_pweasyvision == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::UseDefUser,
username.m_usedefuser == TRUE);
prefs->SetPref(PWSprefs::StringPrefs::DefUserName,
username.m_defusername);
prefs->SetPref(PWSprefs::BoolPrefs::QuerySetDef,
username.m_querysetdef == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::DeleteQuestion,
misc.m_confirmdelete == FALSE);
prefs->SetPref(PWSprefs::BoolPrefs::SaveImmediately,
misc.m_saveimmediately == TRUE);
/*
** Now update the application according to the options.
*/
m_bAlwaysOnTop = display.m_alwaysontop == TRUE;
UpdateAlwaysOnTop();
bool bOldShowPasswordInList = m_bShowPasswordInList;
m_bShowPasswordInList = prefs->
GetPref(PWSprefs::BoolPrefs::ShowPWInList);
if (bOldShowPasswordInList != m_bShowPasswordInList)
RefreshList();
#if 0
if (display.m_usesystemtray == TRUE) {
if (m_TrayIcon.Visible() == FALSE)
m_TrayIcon.ShowIcon();
} else { // user doesn't want to display
if (m_TrayIcon.Visible() == TRUE)
m_TrayIcon.HideIcon();
}
#endif
/*
* Here are the old (pre 2.0) semantics:
* The username entered in this dialog box will be added to all the entries
* in the username-less database that you just opened. Click Ok to add the
* username or Cancel to leave them as is.
*
* You can also set this username to be the default username by clicking the
* check box. In this case, you will not see the username that you just added
* in the main dialog (though it is still part of the entries), and it will
* automatically be inserted in the Add dialog for new entries.
*
* To me (ronys), these seem too complicated, and not useful once password files
* have been converted to the old (username-less) format to 1.9 (with usernames).
* (Not to mention 2.0).
* Therefore, the username will now only be a default value to be used in new entries,
* and in converting pre-2.0 databases.
*/
m_core.SetDefUsername(username.m_defusername);
m_core.SetUseDefUser(username.m_usedefuser == TRUE ? true : false);
}
else if (rc == IDCANCEL)
{
}
}
<commit_msg>Changing the "put icon in system tray" checkbox now adds/removes the icon in the systemtray<commit_after>/// \file DboxOptions.cpp
//-----------------------------------------------------------------------------
#include "PasswordSafe.h"
#include "ThisMfcApp.h"
#if defined(POCKET_PC)
#include "pocketpc/resource.h"
#else
#include "resource.h"
#endif
#include "corelib/PWSprefs.h"
// dialog boxen
#include "DboxMain.h"
#include "OptionsSecurity.h"
#include "OptionsDisplay.h"
#include "OptionsUsername.h"
#include "OptionsPasswordPolicy.h"
#include "OptionsMisc.h"
#include <afxpriv.h>
void
DboxMain::OnOptions()
{
CPropertySheet optionsDlg(_T("Options"), this);
COptionsDisplay display;
COptionsSecurity security;
COptionsPasswordPolicy passwordpolicy;
COptionsUsername username;
COptionsMisc misc;
PWSprefs *prefs = PWSprefs::GetInstance();
/*
** Initialize the property pages values.
*/
display.m_alwaysontop = m_bAlwaysOnTop;
display.m_pwshowinedit = prefs->
GetPref(PWSprefs::BoolPrefs::ShowPWDefault) ? TRUE : FALSE;
display.m_pwshowinlist = prefs->
GetPref(PWSprefs::BoolPrefs::ShowPWInList) ? TRUE : FALSE;
#if defined(POCKET_PC)
display.m_dcshowspassword = prefs->
GetPref(PWSprefs::BoolPrefs::DCShowsPassword) ? TRUE : FALSE;
#endif
display.m_usesystemtray = prefs->
GetPref(PWSprefs::BoolPrefs::UseSystemTray) ? TRUE : FALSE;
security.m_clearclipboard = prefs->
GetPref(PWSprefs::BoolPrefs::DontAskMinimizeClearYesNo) ? TRUE : FALSE;
security.m_lockdatabase = prefs->
GetPref(PWSprefs::BoolPrefs::DatabaseClear) ? TRUE : FALSE;
security.m_confirmsaveonminimize = prefs->
GetPref(PWSprefs::BoolPrefs::DontAskSaveMinimize) ? FALSE : TRUE;
security.m_confirmcopy = prefs->
GetPref(PWSprefs::BoolPrefs::DontAskQuestion) ? FALSE : TRUE;
security.m_LockOnWindowLock = prefs->
GetPref(PWSprefs::BoolPrefs::LockOnWindowLock) ? TRUE : FALSE;
passwordpolicy.m_pwlendefault = prefs->
GetPref(PWSprefs::IntPrefs::PWLenDefault);
passwordpolicy.m_pwuselowercase = prefs->
GetPref(PWSprefs::BoolPrefs::PWUseLowercase);
passwordpolicy.m_pwuseuppercase = prefs->
GetPref(PWSprefs::BoolPrefs::PWUseUppercase);
passwordpolicy.m_pwusedigits = prefs->
GetPref(PWSprefs::BoolPrefs::PWUseDigits);
passwordpolicy.m_pwusesymbols = prefs->
GetPref(PWSprefs::BoolPrefs::PWUseSymbols);
passwordpolicy.m_pwusehexdigits = prefs->
GetPref(PWSprefs::BoolPrefs::PWUseHexDigits);
passwordpolicy.m_pweasyvision = prefs->
GetPref(PWSprefs::BoolPrefs::PWEasyVision);
username.m_usedefuser = prefs->
GetPref(PWSprefs::BoolPrefs::UseDefUser);
username.m_defusername = CString(prefs->
GetPref(PWSprefs::StringPrefs::DefUserName));
username.m_querysetdef = prefs->
GetPref(PWSprefs::BoolPrefs::QuerySetDef);
misc.m_confirmdelete = prefs->
GetPref(PWSprefs::BoolPrefs::DeleteQuestion) ? FALSE : TRUE;
misc.m_saveimmediately = prefs->
GetPref(PWSprefs::BoolPrefs::SaveImmediately) ? TRUE : FALSE;
optionsDlg.AddPage( &display );
optionsDlg.AddPage( &security );
optionsDlg.AddPage( &passwordpolicy );
optionsDlg.AddPage( &username );
optionsDlg.AddPage( &misc );
/*
** Remove the "Apply Now" button.
*/
optionsDlg.m_psh.dwFlags |= PSH_NOAPPLYNOW;
int rc = optionsDlg.DoModal();
if (rc == IDOK)
{
/*
** First save all the options.
*/
prefs->SetPref(PWSprefs::BoolPrefs::AlwaysOnTop,
display.m_alwaysontop == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::ShowPWDefault,
display.m_pwshowinedit == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::ShowPWInList,
display.m_pwshowinlist == TRUE);
#if defined(POCKET_PC)
prefs->SetPref(PWSprefs::BoolPrefs::DCShowsPassword,
display.m_dcshowspassword == TRUE);
#endif
prefs->SetPref(PWSprefs::BoolPrefs::UseSystemTray,
display.m_usesystemtray == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::DontAskMinimizeClearYesNo,
security.m_clearclipboard == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::DatabaseClear,
security.m_lockdatabase == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::DontAskSaveMinimize,
security.m_confirmsaveonminimize == FALSE);
prefs->SetPref(PWSprefs::BoolPrefs::DontAskQuestion,
security.m_confirmcopy == FALSE);
prefs->SetPref(PWSprefs::BoolPrefs::LockOnWindowLock,
security.m_LockOnWindowLock == TRUE);
prefs->SetPref(PWSprefs::IntPrefs::PWLenDefault,
passwordpolicy.m_pwlendefault);
prefs->SetPref(PWSprefs::BoolPrefs::PWUseLowercase,
passwordpolicy.m_pwuselowercase == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::PWUseUppercase,
passwordpolicy.m_pwuseuppercase == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::PWUseDigits,
passwordpolicy.m_pwusedigits == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::PWUseSymbols,
passwordpolicy.m_pwusesymbols == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::PWUseHexDigits,
passwordpolicy.m_pwusehexdigits == TRUE);
prefs-> SetPref(PWSprefs::BoolPrefs::PWEasyVision,
passwordpolicy.m_pweasyvision == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::UseDefUser,
username.m_usedefuser == TRUE);
prefs->SetPref(PWSprefs::StringPrefs::DefUserName,
username.m_defusername);
prefs->SetPref(PWSprefs::BoolPrefs::QuerySetDef,
username.m_querysetdef == TRUE);
prefs->SetPref(PWSprefs::BoolPrefs::DeleteQuestion,
misc.m_confirmdelete == FALSE);
prefs->SetPref(PWSprefs::BoolPrefs::SaveImmediately,
misc.m_saveimmediately == TRUE);
/*
** Now update the application according to the options.
*/
m_bAlwaysOnTop = display.m_alwaysontop == TRUE;
UpdateAlwaysOnTop();
bool bOldShowPasswordInList = m_bShowPasswordInList;
m_bShowPasswordInList = prefs->
GetPref(PWSprefs::BoolPrefs::ShowPWInList);
if (bOldShowPasswordInList != m_bShowPasswordInList)
RefreshList();
if (display.m_usesystemtray == TRUE) {
if (app.m_TrayIcon.Visible() == FALSE)
app.m_TrayIcon.ShowIcon();
} else { // user doesn't want to display
if (app.m_TrayIcon.Visible() == TRUE)
app.m_TrayIcon.HideIcon();
}
/*
* Here are the old (pre 2.0) semantics:
* The username entered in this dialog box will be added to all the entries
* in the username-less database that you just opened. Click Ok to add the
* username or Cancel to leave them as is.
*
* You can also set this username to be the default username by clicking the
* check box. In this case, you will not see the username that you just added
* in the main dialog (though it is still part of the entries), and it will
* automatically be inserted in the Add dialog for new entries.
*
* To me (ronys), these seem too complicated, and not useful once password files
* have been converted to the old (username-less) format to 1.9 (with usernames).
* (Not to mention 2.0).
* Therefore, the username will now only be a default value to be used in new entries,
* and in converting pre-2.0 databases.
*/
m_core.SetDefUsername(username.m_defusername);
m_core.SetUseDefUser(username.m_usedefuser == TRUE ? true : false);
}
else if (rc == IDCANCEL)
{
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "extractor.hpp"
#include "extraction_containers.hpp"
#include "extraction_node.hpp"
#include "extraction_way.hpp"
#include "extractor_callbacks.hpp"
#include "extractor_options.hpp"
#include "restriction_parser.hpp"
#include "scripting_environment.hpp"
#include "../Util/GitDescription.h"
#include "../Util/IniFileUtil.h"
#include "../Util/OSRMException.h"
#include "../Util/simple_logger.hpp"
#include "../Util/TimingUtil.h"
#include "../Util/make_unique.hpp"
#include "../typedefs.h"
#include <luabind/luabind.hpp>
#include <osmium/io/any_input.hpp>
#include <tbb/parallel_for.h>
#include <tbb/task_scheduler_init.h>
#include <variant/optional.hpp>
#include <cstdlib>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
#include <unordered_map>
#include <vector>
int Extractor::Run(int argc, char *argv[])
{
ExtractorConfig extractor_config;
try
{
LogPolicy::GetInstance().Unmute();
TIMER_START(extracting);
if (!ExtractorOptions::ParseArguments(argc, argv, extractor_config))
{
return 0;
}
ExtractorOptions::GenerateOutputFilesNames(extractor_config);
if (1 > extractor_config.requested_num_threads)
{
SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger";
return 1;
}
if (!boost::filesystem::is_regular_file(extractor_config.input_path))
{
SimpleLogger().Write(logWARNING)
<< "Input file " << extractor_config.input_path.string() << " not found!";
return 1;
}
if (!boost::filesystem::is_regular_file(extractor_config.profile_path))
{
SimpleLogger().Write(logWARNING) << "Profile " << extractor_config.profile_path.string()
<< " not found!";
return 1;
}
const unsigned recommended_num_threads = tbb::task_scheduler_init::default_num_threads();
const auto number_of_threads = std::min(recommended_num_threads, extractor_config.requested_num_threads);
tbb::task_scheduler_init init(number_of_threads);
SimpleLogger().Write() << "Input file: " << extractor_config.input_path.filename().string();
SimpleLogger().Write() << "Profile: " << extractor_config.profile_path.filename().string();
SimpleLogger().Write() << "Threads: " << number_of_threads;
// setup scripting environment
ScriptingEnvironment scripting_environment(extractor_config.profile_path.string().c_str());
std::unordered_map<std::string, NodeID> string_map;
string_map[""] = 0;
ExtractionContainers extraction_containers;
auto extractor_callbacks =
osrm::make_unique<ExtractorCallbacks>(extraction_containers, string_map);
osmium::io::File input_file(extractor_config.input_path.string());
osmium::io::Reader reader(input_file);
osmium::io::Header header = reader.header();
unsigned number_of_nodes = 0;
unsigned number_of_ways = 0;
unsigned number_of_relations = 0;
unsigned number_of_others = 0;
SimpleLogger().Write() << "Parsing in progress..";
TIMER_START(parsing);
std::string generator = header.get("generator");
if (generator.empty())
{
generator = "unknown tool";
}
SimpleLogger().Write() << "input file generated by " << generator;
// write .timestamp data file
std::string timestamp = header.get("osmosis_replication_timestamp");
if (timestamp.empty())
{
timestamp = "n/a";
}
SimpleLogger().Write() << "timestamp: " << timestamp;
boost::filesystem::ofstream timestamp_out(extractor_config.timestamp_file_name);
timestamp_out.write(timestamp.c_str(), timestamp.length());
timestamp_out.close();
// initialize vectors holding parsed objects
tbb::concurrent_vector<std::pair<std::size_t, ExtractionNode>> resulting_nodes;
tbb::concurrent_vector<std::pair<std::size_t, ExtractionWay>> resulting_ways;
tbb::concurrent_vector<mapbox::util::optional<InputRestrictionContainer>>
resulting_restrictions;
// setup restriction parser
RestrictionParser restriction_parser(scripting_environment.getLuaState());
while (osmium::memory::Buffer buffer = reader.read())
{
// create a vector of iterators into the buffer
std::vector<osmium::memory::Buffer::iterator> osm_elements;
osmium::memory::Buffer::iterator iter = std::begin(buffer);
while (iter != std::end(buffer))
{
osm_elements.push_back(iter);
iter = std::next(iter);
}
// clear resulting vectors
resulting_nodes.clear();
resulting_ways.clear();
resulting_restrictions.clear();
// parse OSM entities in parallel, store in resulting vectors
tbb::parallel_for(tbb::blocked_range<std::size_t>(0, osm_elements.size()),
[&](const tbb::blocked_range<std::size_t> &range)
{
for (auto x = range.begin(); x != range.end(); ++x)
{
auto entity = osm_elements[x];
ExtractionNode result_node;
ExtractionWay result_way;
switch (entity->type())
{
case osmium::item_type::node:
++number_of_nodes;
luabind::call_function<void>(
scripting_environment.getLuaState(),
"node_function",
boost::cref(static_cast<osmium::Node &>(*entity)),
boost::ref(result_node));
resulting_nodes.push_back(std::make_pair(x, result_node));
break;
case osmium::item_type::way:
++number_of_ways;
luabind::call_function<void>(
scripting_environment.getLuaState(),
"way_function",
boost::cref(static_cast<osmium::Way &>(*entity)),
boost::ref(result_way));
resulting_ways.push_back(std::make_pair(x, result_way));
break;
case osmium::item_type::relation:
++number_of_relations;
resulting_restrictions.push_back(
restriction_parser.TryParse(static_cast<osmium::Relation &>(*entity)));
break;
default:
++number_of_others;
break;
}
}
});
// put parsed objects thru extractor callbacks
for (const auto &result : resulting_nodes)
{
extractor_callbacks->ProcessNode(
static_cast<osmium::Node &>(*(osm_elements[result.first])), result.second);
}
for (const auto &result : resulting_ways)
{
extractor_callbacks->ProcessWay(
static_cast<osmium::Way &>(*(osm_elements[result.first])), result.second);
}
for (const auto &result : resulting_restrictions)
{
extractor_callbacks->ProcessRestriction(result);
}
}
TIMER_STOP(parsing);
SimpleLogger().Write() << "Parsing finished after " << TIMER_SEC(parsing) << " seconds";
SimpleLogger().Write() << "Raw input contains " << number_of_nodes << " nodes, "
<< number_of_ways << " ways, and " << number_of_relations
<< " relations, and " << number_of_others << " unknown entities";
extractor_callbacks.reset();
if (extraction_containers.all_edges_list.empty())
{
SimpleLogger().Write(logWARNING) << "The input data is empty, exiting.";
return 1;
}
extraction_containers.PrepareData(extractor_config.output_file_name,
extractor_config.restriction_file_name);
TIMER_STOP(extracting);
SimpleLogger().Write() << "extraction finished after " << TIMER_SEC(extracting) << "s";
SimpleLogger().Write() << "To prepare the data for routing, run: "
<< "./osrm-prepare " << extractor_config.output_file_name
<< std::endl;
}
catch (std::exception &e)
{
SimpleLogger().Write(logWARNING) << e.what();
return 1;
}
return 0;
}
<commit_msg>Use atomics for counters.<commit_after>/*
Copyright (c) 2014, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "extractor.hpp"
#include "extraction_containers.hpp"
#include "extraction_node.hpp"
#include "extraction_way.hpp"
#include "extractor_callbacks.hpp"
#include "extractor_options.hpp"
#include "restriction_parser.hpp"
#include "scripting_environment.hpp"
#include "../Util/GitDescription.h"
#include "../Util/IniFileUtil.h"
#include "../Util/OSRMException.h"
#include "../Util/simple_logger.hpp"
#include "../Util/TimingUtil.h"
#include "../Util/make_unique.hpp"
#include "../typedefs.h"
#include <luabind/luabind.hpp>
#include <osmium/io/any_input.hpp>
#include <tbb/parallel_for.h>
#include <tbb/task_scheduler_init.h>
#include <variant/optional.hpp>
#include <cstdlib>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
#include <unordered_map>
#include <vector>
int Extractor::Run(int argc, char *argv[])
{
ExtractorConfig extractor_config;
try
{
LogPolicy::GetInstance().Unmute();
TIMER_START(extracting);
if (!ExtractorOptions::ParseArguments(argc, argv, extractor_config))
{
return 0;
}
ExtractorOptions::GenerateOutputFilesNames(extractor_config);
if (1 > extractor_config.requested_num_threads)
{
SimpleLogger().Write(logWARNING) << "Number of threads must be 1 or larger";
return 1;
}
if (!boost::filesystem::is_regular_file(extractor_config.input_path))
{
SimpleLogger().Write(logWARNING)
<< "Input file " << extractor_config.input_path.string() << " not found!";
return 1;
}
if (!boost::filesystem::is_regular_file(extractor_config.profile_path))
{
SimpleLogger().Write(logWARNING) << "Profile " << extractor_config.profile_path.string()
<< " not found!";
return 1;
}
const unsigned recommended_num_threads = tbb::task_scheduler_init::default_num_threads();
const auto number_of_threads = std::min(recommended_num_threads, extractor_config.requested_num_threads);
tbb::task_scheduler_init init(number_of_threads);
SimpleLogger().Write() << "Input file: " << extractor_config.input_path.filename().string();
SimpleLogger().Write() << "Profile: " << extractor_config.profile_path.filename().string();
SimpleLogger().Write() << "Threads: " << number_of_threads;
// setup scripting environment
ScriptingEnvironment scripting_environment(extractor_config.profile_path.string().c_str());
std::unordered_map<std::string, NodeID> string_map;
string_map[""] = 0;
ExtractionContainers extraction_containers;
auto extractor_callbacks =
osrm::make_unique<ExtractorCallbacks>(extraction_containers, string_map);
osmium::io::File input_file(extractor_config.input_path.string());
osmium::io::Reader reader(input_file);
osmium::io::Header header = reader.header();
std::atomic<unsigned> number_of_nodes {0};
std::atomic<unsigned> number_of_ways {0};
std::atomic<unsigned> number_of_relations {0};
std::atomic<unsigned> number_of_others {0};
SimpleLogger().Write() << "Parsing in progress..";
TIMER_START(parsing);
std::string generator = header.get("generator");
if (generator.empty())
{
generator = "unknown tool";
}
SimpleLogger().Write() << "input file generated by " << generator;
// write .timestamp data file
std::string timestamp = header.get("osmosis_replication_timestamp");
if (timestamp.empty())
{
timestamp = "n/a";
}
SimpleLogger().Write() << "timestamp: " << timestamp;
boost::filesystem::ofstream timestamp_out(extractor_config.timestamp_file_name);
timestamp_out.write(timestamp.c_str(), timestamp.length());
timestamp_out.close();
// initialize vectors holding parsed objects
tbb::concurrent_vector<std::pair<std::size_t, ExtractionNode>> resulting_nodes;
tbb::concurrent_vector<std::pair<std::size_t, ExtractionWay>> resulting_ways;
tbb::concurrent_vector<mapbox::util::optional<InputRestrictionContainer>>
resulting_restrictions;
// setup restriction parser
RestrictionParser restriction_parser(scripting_environment.getLuaState());
while (osmium::memory::Buffer buffer = reader.read())
{
// create a vector of iterators into the buffer
std::vector<osmium::memory::Buffer::iterator> osm_elements;
osmium::memory::Buffer::iterator iter = std::begin(buffer);
while (iter != std::end(buffer))
{
osm_elements.push_back(iter);
iter = std::next(iter);
}
// clear resulting vectors
resulting_nodes.clear();
resulting_ways.clear();
resulting_restrictions.clear();
// parse OSM entities in parallel, store in resulting vectors
tbb::parallel_for(tbb::blocked_range<std::size_t>(0, osm_elements.size()),
[&](const tbb::blocked_range<std::size_t> &range)
{
for (auto x = range.begin(); x != range.end(); ++x)
{
auto entity = osm_elements[x];
ExtractionNode result_node;
ExtractionWay result_way;
switch (entity->type())
{
case osmium::item_type::node:
++number_of_nodes;
luabind::call_function<void>(
scripting_environment.getLuaState(),
"node_function",
boost::cref(static_cast<osmium::Node &>(*entity)),
boost::ref(result_node));
resulting_nodes.push_back(std::make_pair(x, result_node));
break;
case osmium::item_type::way:
++number_of_ways;
luabind::call_function<void>(
scripting_environment.getLuaState(),
"way_function",
boost::cref(static_cast<osmium::Way &>(*entity)),
boost::ref(result_way));
resulting_ways.push_back(std::make_pair(x, result_way));
break;
case osmium::item_type::relation:
++number_of_relations;
resulting_restrictions.push_back(
restriction_parser.TryParse(static_cast<osmium::Relation &>(*entity)));
break;
default:
++number_of_others;
break;
}
}
});
// put parsed objects thru extractor callbacks
for (const auto &result : resulting_nodes)
{
extractor_callbacks->ProcessNode(
static_cast<osmium::Node &>(*(osm_elements[result.first])), result.second);
}
for (const auto &result : resulting_ways)
{
extractor_callbacks->ProcessWay(
static_cast<osmium::Way &>(*(osm_elements[result.first])), result.second);
}
for (const auto &result : resulting_restrictions)
{
extractor_callbacks->ProcessRestriction(result);
}
}
TIMER_STOP(parsing);
SimpleLogger().Write() << "Parsing finished after " << TIMER_SEC(parsing) << " seconds";
unsigned nn = number_of_nodes;
unsigned nw = number_of_ways;
unsigned nr = number_of_relations;
unsigned no = number_of_others;
SimpleLogger().Write() << "Raw input contains "
<< nn << " nodes, "
<< nw << " ways, and "
<< nr << " relations, and "
<< no << " unknown entities";
extractor_callbacks.reset();
if (extraction_containers.all_edges_list.empty())
{
SimpleLogger().Write(logWARNING) << "The input data is empty, exiting.";
return 1;
}
extraction_containers.PrepareData(extractor_config.output_file_name,
extractor_config.restriction_file_name);
TIMER_STOP(extracting);
SimpleLogger().Write() << "extraction finished after " << TIMER_SEC(extracting) << "s";
SimpleLogger().Write() << "To prepare the data for routing, run: "
<< "./osrm-prepare " << extractor_config.output_file_name
<< std::endl;
}
catch (std::exception &e)
{
SimpleLogger().Write(logWARNING) << e.what();
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* 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 <assert.h>
#include <stdint.h>
#include <stdio.h>
#include "image.hpp"
#include "json.hpp"
#include "d3d9imports.hpp"
#include "d3dstate.hpp"
namespace d3dstate {
static image::Image *
getSurfaceImage(IDirect3DDevice9 *pDevice,
IDirect3DSurface9 *pSurface) {
image::Image *image = NULL;
D3DSURFACE_DESC Desc;
D3DLOCKED_RECT LockedRect;
const unsigned char *src;
unsigned char *dst;
HRESULT hr;
if (!pSurface) {
return NULL;
}
hr = pSurface->GetDesc(&Desc);
assert(SUCCEEDED(hr));
unsigned numChannels;
image::ChannelType channelType;
switch (Desc.Format) {
case D3DFMT_X8R8G8B8:
case D3DFMT_A8R8G8B8:
case D3DFMT_R5G6B5:
numChannels = 3;
channelType = image::TYPE_UNORM8;
break;
case D3DFMT_D16:
case D3DFMT_D16_LOCKABLE:
numChannels = 1;
channelType = image::TYPE_FLOAT;
break;
default:
std::cerr << "warning: unsupported D3DFORMAT " << Desc.Format << "\n";
goto no_lock;
}
hr = pSurface->LockRect(&LockedRect, NULL, D3DLOCK_READONLY);
if (FAILED(hr)) {
goto no_lock;
}
image = new image::Image(Desc.Width, Desc.Height, numChannels, true, channelType);
if (!image) {
goto no_image;
}
dst = image->start();
src = (const unsigned char *)LockedRect.pBits;
for (unsigned y = 0; y < Desc.Height; ++y) {
switch (Desc.Format) {
case D3DFMT_R5G6B5:
for (unsigned x = 0; x < Desc.Width; ++x) {
uint32_t pixel = ((const uint16_t *)src)[x];
dst[3*x + 0] = (( pixel & 0x1f) * (2*0xff) + 0x1f) / (2*0x1f);
dst[3*x + 1] = (((pixel >> 5) & 0x3f) * (2*0xff) + 0x3f) / (2*0x3f);
dst[3*x + 2] = (( pixel >> 11 ) * (2*0xff) + 0x1f) / (2*0x1f);
}
break;
case D3DFMT_X8R8G8B8:
case D3DFMT_A8R8G8B8:
for (unsigned x = 0; x < Desc.Width; ++x) {
dst[3*x + 0] = src[4*x + 2];
dst[3*x + 1] = src[4*x + 1];
dst[3*x + 2] = src[4*x + 0];
}
break;
case D3DFMT_D16:
case D3DFMT_D16_LOCKABLE:
for (unsigned x = 0; x < Desc.Width; ++x) {
((float *)dst)[x] = ((const uint16_t *)src)[x] * (1.0f / 0xffff);
}
break;
default:
assert(0);
break;
}
src += LockedRect.Pitch;
dst += image->stride();
}
no_image:
pSurface->UnlockRect();
no_lock:
return image;
}
static image::Image *
getRenderTargetImage(IDirect3DDevice9 *pDevice,
IDirect3DSurface9 *pRenderTarget) {
image::Image *image = NULL;
D3DSURFACE_DESC Desc;
IDirect3DSurface9 *pStagingSurface = NULL;
HRESULT hr;
if (!pRenderTarget) {
return NULL;
}
hr = pRenderTarget->GetDesc(&Desc);
assert(SUCCEEDED(hr));
hr = pDevice->CreateOffscreenPlainSurface(Desc.Width, Desc.Height, Desc.Format, D3DPOOL_SYSTEMMEM, &pStagingSurface, NULL);
if (FAILED(hr)) {
goto no_staging;
}
hr = pDevice->GetRenderTargetData(pRenderTarget, pStagingSurface);
if (FAILED(hr)) {
goto no_rendertargetdata;
}
image = getSurfaceImage(pDevice, pStagingSurface);
no_rendertargetdata:
pStagingSurface->Release();
no_staging:
return image;
}
image::Image *
getRenderTargetImage(IDirect3DDevice9 *pDevice) {
HRESULT hr;
IDirect3DSurface9 *pRenderTarget = NULL;
hr = pDevice->GetRenderTarget(0, &pRenderTarget);
if (FAILED(hr)) {
return NULL;
}
assert(pRenderTarget);
image::Image *image = NULL;
if (pRenderTarget) {
image = getRenderTargetImage(pDevice, pRenderTarget);
pRenderTarget->Release();
}
return image;
}
void
dumpFramebuffer(JSONWriter &json, IDirect3DDevice9 *pDevice)
{
HRESULT hr;
json.beginMember("framebuffer");
json.beginObject();
D3DCAPS9 Caps;
pDevice->GetDeviceCaps(&Caps);
for (UINT i = 0; i < Caps.NumSimultaneousRTs; ++i) {
IDirect3DSurface9 *pRenderTarget = NULL;
hr = pDevice->GetRenderTarget(i, &pRenderTarget);
if (FAILED(hr)) {
continue;
}
if (!pRenderTarget) {
continue;
}
image::Image *image;
image = getRenderTargetImage(pDevice, pRenderTarget);
if (image) {
char label[64];
_snprintf(label, sizeof label, "RENDER_TARGET_%u", i);
json.beginMember(label);
json.writeImage(image, "UNKNOWN");
json.endMember(); // RENDER_TARGET_*
}
pRenderTarget->Release();
}
IDirect3DSurface9 *pDepthStencil = NULL;
hr = pDevice->GetDepthStencilSurface(&pDepthStencil);
if (SUCCEEDED(hr) && pDepthStencil) {
image::Image *image;
image = getSurfaceImage(pDevice, pDepthStencil);
if (image) {
json.beginMember("DEPTH_STENCIL");
json.writeImage(image, "UNKNOWN");
json.endMember(); // RENDER_TARGET_*
}
}
json.endObject();
json.endMember(); // framebuffer
}
} /* namespace d3dstate */
<commit_msg>d3dretrace: Dump D3DFMT_D32F_LOCKABLE too.<commit_after>/**************************************************************************
*
* Copyright 2011 Jose Fonseca
* All Rights Reserved.
*
* 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 <assert.h>
#include <stdint.h>
#include <stdio.h>
#include "image.hpp"
#include "json.hpp"
#include "d3d9imports.hpp"
#include "d3dstate.hpp"
namespace d3dstate {
static image::Image *
getSurfaceImage(IDirect3DDevice9 *pDevice,
IDirect3DSurface9 *pSurface) {
image::Image *image = NULL;
D3DSURFACE_DESC Desc;
D3DLOCKED_RECT LockedRect;
const unsigned char *src;
unsigned char *dst;
HRESULT hr;
if (!pSurface) {
return NULL;
}
hr = pSurface->GetDesc(&Desc);
assert(SUCCEEDED(hr));
unsigned numChannels;
image::ChannelType channelType;
switch (Desc.Format) {
case D3DFMT_X8R8G8B8:
case D3DFMT_A8R8G8B8:
case D3DFMT_R5G6B5:
numChannels = 3;
channelType = image::TYPE_UNORM8;
break;
case D3DFMT_D16:
case D3DFMT_D16_LOCKABLE:
case D3DFMT_D32F_LOCKABLE:
numChannels = 1;
channelType = image::TYPE_FLOAT;
break;
default:
std::cerr << "warning: unsupported D3DFORMAT " << Desc.Format << "\n";
goto no_lock;
}
hr = pSurface->LockRect(&LockedRect, NULL, D3DLOCK_READONLY);
if (FAILED(hr)) {
goto no_lock;
}
image = new image::Image(Desc.Width, Desc.Height, numChannels, true, channelType);
if (!image) {
goto no_image;
}
dst = image->start();
src = (const unsigned char *)LockedRect.pBits;
for (unsigned y = 0; y < Desc.Height; ++y) {
switch (Desc.Format) {
case D3DFMT_R5G6B5:
for (unsigned x = 0; x < Desc.Width; ++x) {
uint32_t pixel = ((const uint16_t *)src)[x];
dst[3*x + 0] = (( pixel & 0x1f) * (2*0xff) + 0x1f) / (2*0x1f);
dst[3*x + 1] = (((pixel >> 5) & 0x3f) * (2*0xff) + 0x3f) / (2*0x3f);
dst[3*x + 2] = (( pixel >> 11 ) * (2*0xff) + 0x1f) / (2*0x1f);
}
break;
case D3DFMT_X8R8G8B8:
case D3DFMT_A8R8G8B8:
for (unsigned x = 0; x < Desc.Width; ++x) {
dst[3*x + 0] = src[4*x + 2];
dst[3*x + 1] = src[4*x + 1];
dst[3*x + 2] = src[4*x + 0];
}
break;
case D3DFMT_D16:
case D3DFMT_D16_LOCKABLE:
for (unsigned x = 0; x < Desc.Width; ++x) {
((float *)dst)[x] = ((const uint16_t *)src)[x] * (1.0f / 0xffff);
}
break;
case D3DFMT_D32F_LOCKABLE:
memcpy(dst, src, Desc.Width * sizeof(float));
break;
default:
assert(0);
break;
}
src += LockedRect.Pitch;
dst += image->stride();
}
no_image:
pSurface->UnlockRect();
no_lock:
return image;
}
static image::Image *
getRenderTargetImage(IDirect3DDevice9 *pDevice,
IDirect3DSurface9 *pRenderTarget) {
image::Image *image = NULL;
D3DSURFACE_DESC Desc;
IDirect3DSurface9 *pStagingSurface = NULL;
HRESULT hr;
if (!pRenderTarget) {
return NULL;
}
hr = pRenderTarget->GetDesc(&Desc);
assert(SUCCEEDED(hr));
hr = pDevice->CreateOffscreenPlainSurface(Desc.Width, Desc.Height, Desc.Format, D3DPOOL_SYSTEMMEM, &pStagingSurface, NULL);
if (FAILED(hr)) {
goto no_staging;
}
hr = pDevice->GetRenderTargetData(pRenderTarget, pStagingSurface);
if (FAILED(hr)) {
goto no_rendertargetdata;
}
image = getSurfaceImage(pDevice, pStagingSurface);
no_rendertargetdata:
pStagingSurface->Release();
no_staging:
return image;
}
image::Image *
getRenderTargetImage(IDirect3DDevice9 *pDevice) {
HRESULT hr;
IDirect3DSurface9 *pRenderTarget = NULL;
hr = pDevice->GetRenderTarget(0, &pRenderTarget);
if (FAILED(hr)) {
return NULL;
}
assert(pRenderTarget);
image::Image *image = NULL;
if (pRenderTarget) {
image = getRenderTargetImage(pDevice, pRenderTarget);
pRenderTarget->Release();
}
return image;
}
void
dumpFramebuffer(JSONWriter &json, IDirect3DDevice9 *pDevice)
{
HRESULT hr;
json.beginMember("framebuffer");
json.beginObject();
D3DCAPS9 Caps;
pDevice->GetDeviceCaps(&Caps);
for (UINT i = 0; i < Caps.NumSimultaneousRTs; ++i) {
IDirect3DSurface9 *pRenderTarget = NULL;
hr = pDevice->GetRenderTarget(i, &pRenderTarget);
if (FAILED(hr)) {
continue;
}
if (!pRenderTarget) {
continue;
}
image::Image *image;
image = getRenderTargetImage(pDevice, pRenderTarget);
if (image) {
char label[64];
_snprintf(label, sizeof label, "RENDER_TARGET_%u", i);
json.beginMember(label);
json.writeImage(image, "UNKNOWN");
json.endMember(); // RENDER_TARGET_*
}
pRenderTarget->Release();
}
IDirect3DSurface9 *pDepthStencil = NULL;
hr = pDevice->GetDepthStencilSurface(&pDepthStencil);
if (SUCCEEDED(hr) && pDepthStencil) {
image::Image *image;
image = getSurfaceImage(pDevice, pDepthStencil);
if (image) {
json.beginMember("DEPTH_STENCIL");
json.writeImage(image, "UNKNOWN");
json.endMember(); // RENDER_TARGET_*
}
}
json.endObject();
json.endMember(); // framebuffer
}
} /* namespace d3dstate */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: rscpar.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: pl $ $Date: 2001-11-05 14:44:05 $
*
* 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): _______________________________________
*
*
************************************************************************/
/****************** I N C L U D E S **************************************/
#pragma hdrstop
// C and C++ Includes.
#include <string.h>
#ifndef _RSCPAR_HXX
#include <rscpar.hxx>
#endif
#ifndef _RSCDB_HXX
#include <rscdb.hxx>
#endif
/****************** R s c F i l e I n s t ********************************/
/****************** C O D E **********************************************/
/*************************************************************************
|*
|* RscFileInst::Init()
|*
|* Beschreibung
|* Ersterstellung MM 05.11.91
|* Letzte Aenderung MM 17.02.93
|*
*************************************************************************/
void RscFileInst::Init()
{
nLineNo = 0;
nLineBufLen = 256;
pLine = (char *)RscMem::Malloc( nLineBufLen );
*pLine = '\0';
nScanPos = 0;
cLastChar = '\0';
bEof = FALSE;
};
/*************************************************************************
|*
|* RscFileInst::RscFileInst()
|*
|* Beschreibung
|* Ersterstellung MM 06.06.91
|* Letzte Aenderung MM 06.06.91
|*
*************************************************************************/
RscFileInst::RscFileInst( RscTypCont * pTC, ULONG lIndexSrc,
ULONG lFIndex, FILE * fFile )
{
pTypCont = pTC;
Init();
lFileIndex = lFIndex;
lSrcIndex = lIndexSrc;
fInputFile = fFile;
//Status: Zeiger am Ende des Lesepuffers
nInputPos = nInputEndPos = nInputBufLen = READBUFFER_MAX;
pInput = (char *)RscMem::Malloc( nInputBufLen );
}
RscFileInst::RscFileInst( RscTypCont * pTC, ULONG lIndexSrc,
ULONG lFIndex, const ByteString& rBuf )
{
pTypCont = pTC;
Init();
lFileIndex = lFIndex;
lSrcIndex = lIndexSrc;
fInputFile = NULL;
nInputPos = 0;
nInputEndPos = rBuf.Len();
// Muss groesser sein wegen Eingabeende bei nInputBufLen < nInputEndPos
nInputBufLen = nInputEndPos +1;
pInput = (char *)RscMem::Malloc( nInputBufLen +100 );
memcpy( pInput, rBuf.GetBuffer(), nInputEndPos );
}
/*************************************************************************
|*
|* RscFileInst::~RscFileInst()
|*
|* Beschreibung
|* Ersterstellung MM 06.06.91
|* Letzte Aenderung MM 06.06.91
|*
*************************************************************************/
RscFileInst::~RscFileInst(){
if( pInput )
RscMem::Free( pInput );
if( pLine )
RscMem::Free( pLine );
}
/*************************************************************************
|*
|* RscFileInst::GetChar()
|*
|* Beschreibung
|* Ersterstellung MM 01.06.91
|* Letzte Aenderung MM 09.08.91
|*
*************************************************************************/
int RscFileInst::GetChar()
{
if( pLine[ nScanPos ] )
return( pLine[ nScanPos++ ] );
else if( nInputPos >= nInputEndPos && nInputEndPos != nInputBufLen )
{
// Dateiende
bEof = TRUE;
return 0;
}
else
{
GetNewLine();
return( '\n' );
}
}
/*************************************************************************
|*
|* RscFileInst::GetNewLine()
|*
|* Beschreibung
|* Ersterstellung MM 06.06.91
|* Letzte Aenderung MM 06.06.91
|*
*************************************************************************/
void RscFileInst::GetNewLine()
{
nLineNo++;
nScanPos = 0;
//laeuft bis Dateiende
USHORT nLen = 0;
while( (nInputPos < nInputEndPos) || (nInputEndPos == nInputBufLen) )
{
if( (nInputPos >= nInputEndPos) && fInputFile )
{
nInputEndPos = fread( pInput, 1, nInputBufLen, fInputFile );
nInputPos = 0;
}
while( nInputPos < nInputEndPos )
{
//immer eine Zeile lesen
if( nLen >= nLineBufLen )
{
nLineBufLen += 256;
// einen dazu fuer '\0'
pLine = RscMem::Realloc( pLine, nLineBufLen +1 );
}
// cr lf, lf cr, lf oder cr wird '\0'
if( pInput[ nInputPos ] == '\n' ){
nInputPos++;
if( cLastChar != '\r' ){
cLastChar = '\n';
pLine[ nLen++ ] = '\0';
goto END;
}
}
else if( pInput[ nInputPos ] == '\r' ){
nInputPos++;
if( cLastChar != '\n' ){
cLastChar = '\r';
pLine[ nLen++ ] = '\0';
goto END;
}
}
else
pLine[ nLen++ ] = pInput[ nInputPos++ ];
};
};
// Abbruch ueber EOF
pLine[ nLen ] = '\0';
END:
if( pTypCont->pEH->GetListFile() ){
char buf[ 10 ];
sprintf( buf, "%5d ", GetLineNo() );
pTypCont->pEH->LstOut( buf );
pTypCont->pEH->LstOut( GetLine() );
pTypCont->pEH->LstOut( "\n" );
}
}
/*************************************************************************
|*
|* RscFileInst::SetError()
|*
|* Beschreibung
|* Ersterstellung MM 05.11.91
|* Letzte Aenderung MM 05.11.91
|*
*************************************************************************/
void RscFileInst::SetError( ERRTYPE aError )
{
if( aError.IsOk() )
{
aFirstError = aError;
nErrorLine = GetLineNo();
nErrorPos = GetScanPos() -1;
};
};
<commit_msg>INTEGRATION: CWS vcl27 (1.3.142); FILE MERGED 2004/09/02 16:30:53 pl 1.3.142.1: #i33565# recognize and ignore UTF-8 BOM<commit_after>/*************************************************************************
*
* $RCSfile: rscpar.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2004-10-13 08:24:23 $
*
* 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): _______________________________________
*
*
************************************************************************/
/****************** I N C L U D E S **************************************/
#pragma hdrstop
// C and C++ Includes.
#include <string.h>
#ifndef _RSCPAR_HXX
#include <rscpar.hxx>
#endif
#ifndef _RSCDB_HXX
#include <rscdb.hxx>
#endif
/****************** R s c F i l e I n s t ********************************/
/****************** C O D E **********************************************/
/*************************************************************************
|*
|* RscFileInst::Init()
|*
|* Beschreibung
|* Ersterstellung MM 05.11.91
|* Letzte Aenderung MM 17.02.93
|*
*************************************************************************/
void RscFileInst::Init()
{
nLineNo = 0;
nLineBufLen = 256;
pLine = (char *)RscMem::Malloc( nLineBufLen );
*pLine = '\0';
nScanPos = 0;
cLastChar = '\0';
bEof = FALSE;
};
/*************************************************************************
|*
|* RscFileInst::RscFileInst()
|*
|* Beschreibung
|* Ersterstellung MM 06.06.91
|* Letzte Aenderung MM 06.06.91
|*
*************************************************************************/
RscFileInst::RscFileInst( RscTypCont * pTC, ULONG lIndexSrc,
ULONG lFIndex, FILE * fFile )
{
pTypCont = pTC;
Init();
lFileIndex = lFIndex;
lSrcIndex = lIndexSrc;
fInputFile = fFile;
//Status: Zeiger am Ende des Lesepuffers
nInputPos = nInputEndPos = nInputBufLen = READBUFFER_MAX;
pInput = (char *)RscMem::Malloc( nInputBufLen );
}
RscFileInst::RscFileInst( RscTypCont * pTC, ULONG lIndexSrc,
ULONG lFIndex, const ByteString& rBuf )
{
pTypCont = pTC;
Init();
lFileIndex = lFIndex;
lSrcIndex = lIndexSrc;
fInputFile = NULL;
nInputPos = 0;
nInputEndPos = rBuf.Len();
// Muss groesser sein wegen Eingabeende bei nInputBufLen < nInputEndPos
nInputBufLen = nInputEndPos +1;
pInput = (char *)RscMem::Malloc( nInputBufLen +100 );
memcpy( pInput, rBuf.GetBuffer(), nInputEndPos );
}
/*************************************************************************
|*
|* RscFileInst::~RscFileInst()
|*
|* Beschreibung
|* Ersterstellung MM 06.06.91
|* Letzte Aenderung MM 06.06.91
|*
*************************************************************************/
RscFileInst::~RscFileInst(){
if( pInput )
RscMem::Free( pInput );
if( pLine )
RscMem::Free( pLine );
}
/*************************************************************************
|*
|* RscFileInst::GetChar()
|*
|* Beschreibung
|* Ersterstellung MM 01.06.91
|* Letzte Aenderung MM 09.08.91
|*
*************************************************************************/
int RscFileInst::GetChar()
{
if( pLine[ nScanPos ] )
return( pLine[ nScanPos++ ] );
else if( nInputPos >= nInputEndPos && nInputEndPos != nInputBufLen )
{
// Dateiende
bEof = TRUE;
return 0;
}
else
{
GetNewLine();
return( '\n' );
}
}
/*************************************************************************
|*
|* RscFileInst::GetNewLine()
|*
|* Beschreibung
|* Ersterstellung MM 06.06.91
|* Letzte Aenderung MM 06.06.91
|*
*************************************************************************/
void RscFileInst::GetNewLine()
{
nLineNo++;
nScanPos = 0;
//laeuft bis Dateiende
USHORT nLen = 0;
while( (nInputPos < nInputEndPos) || (nInputEndPos == nInputBufLen) )
{
if( (nInputPos >= nInputEndPos) && fInputFile )
{
nInputEndPos = fread( pInput, 1, nInputBufLen, fInputFile );
nInputPos = 0;
}
while( nInputPos < nInputEndPos )
{
//immer eine Zeile lesen
if( nLen >= nLineBufLen )
{
nLineBufLen += 256;
// einen dazu fuer '\0'
pLine = RscMem::Realloc( pLine, nLineBufLen +1 );
}
// cr lf, lf cr, lf oder cr wird '\0'
if( pInput[ nInputPos ] == '\n' ){
nInputPos++;
if( cLastChar != '\r' ){
cLastChar = '\n';
pLine[ nLen++ ] = '\0';
goto END;
}
}
else if( pInput[ nInputPos ] == '\r' ){
nInputPos++;
if( cLastChar != '\n' ){
cLastChar = '\r';
pLine[ nLen++ ] = '\0';
goto END;
}
}
else
{
pLine[ nLen++ ] = pInput[ nInputPos++ ];
if( nLen > 2 )
{
if( pLine[nLen-3] == (char)0xef &&
pLine[nLen-2] == (char)0xbb &&
pLine[nLen-1] == (char)0xbf )
{
nLen -= 3;
}
}
}
};
};
// Abbruch ueber EOF
pLine[ nLen ] = '\0';
END:
if( pTypCont->pEH->GetListFile() ){
char buf[ 10 ];
sprintf( buf, "%5d ", GetLineNo() );
pTypCont->pEH->LstOut( buf );
pTypCont->pEH->LstOut( GetLine() );
pTypCont->pEH->LstOut( "\n" );
}
}
/*************************************************************************
|*
|* RscFileInst::SetError()
|*
|* Beschreibung
|* Ersterstellung MM 05.11.91
|* Letzte Aenderung MM 05.11.91
|*
*************************************************************************/
void RscFileInst::SetError( ERRTYPE aError )
{
if( aError.IsOk() )
{
aFirstError = aError;
nErrorLine = GetLineNo();
nErrorPos = GetScanPos() -1;
};
};
<|endoftext|> |
<commit_before><commit_msg>detection must look into file if typename was empty<commit_after><|endoftext|> |
<commit_before><commit_msg>#81744#: save some properties, new medium may be killed<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// This file contains the WebRTC suppressions for ThreadSanitizer.
// Please refer to
// http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for more info.
#if defined(THREAD_SANITIZER)
// Please make sure the code below declares a single string variable
// kTSanDefaultSuppressions contains TSan suppressions delimited by newlines.
// See http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for the instructions on writing suppressions.
char kTSanDefaultSuppressions[] =
// WebRTC specific suppressions.
// Split up suppressions covered previously by thread.cc and messagequeue.cc.
"race:rtc::MessageQueue::Quit\n"
"race:FileVideoCapturerTest::VideoCapturerListener::OnFrameCaptured\n"
"race:vp8cx_remove_encoder_threads\n"
"race:third_party/libvpx/source/libvpx/vp9/common/vp9_scan.h\n"
// Usage of trace callback and trace level is racy in libjingle_media_unittests.
// https://code.google.com/p/webrtc/issues/detail?id=3372
"race:webrtc::TraceImpl::WriteToFile\n"
"race:webrtc::VideoEngine::SetTraceFilter\n"
"race:webrtc::VoiceEngine::SetTraceFilter\n"
"race:webrtc::Trace::set_level_filter\n"
"race:webrtc::GetStaticInstance<webrtc::TraceImpl>\n"
// Audio processing
// https://code.google.com/p/webrtc/issues/detail?id=2521 for details.
"race:webrtc/modules/audio_processing/aec/aec_core.c\n"
"race:webrtc/modules/audio_processing/aec/aec_rdft.c\n"
// rtc_unittest
// https://code.google.com/p/webrtc/issues/detail?id=3911 for details.
"race:rtc::AsyncInvoker::OnMessage\n"
"race:rtc::FireAndForgetAsyncClosure<FunctorB>::Execute\n"
"race:rtc::MessageQueueManager::Clear\n"
"race:rtc::Thread::Clear\n"
// https://code.google.com/p/webrtc/issues/detail?id=2080
"race:webrtc/base/logging.cc\n"
"race:webrtc/base/sharedexclusivelock_unittest.cc\n"
"race:webrtc/base/signalthread_unittest.cc\n"
// https://code.google.com/p/webrtc/issues/detail?id=4456
"deadlock:rtc::MessageQueueManager::Clear\n"
"deadlock:rtc::MessageQueueManager::ClearInternal\n"
// libjingle_p2p_unittest
// https://code.google.com/p/webrtc/issues/detail?id=2079
"race:webrtc/base/testclient.cc\n"
"race:webrtc/base/virtualsocketserver.cc\n"
"race:talk/p2p/base/stunserver_unittest.cc\n"
// third_party/usrsctp
// TODO(jiayl): https://code.google.com/p/webrtc/issues/detail?id=3492
"race:user_sctp_timer_iterate\n"
// Potential deadlocks detected after roll in r6516.
// https://code.google.com/p/webrtc/issues/detail?id=3509
"deadlock:webrtc::ProcessThreadImpl::RegisterModule\n"
"deadlock:webrtc::RTCPReceiver::SetSsrcs\n"
"deadlock:webrtc::test::UdpSocketManagerPosixImpl::RemoveSocket\n"
"deadlock:webrtc::vcm::VideoReceiver::RegisterPacketRequestCallback\n"
"deadlock:webrtc::ViECaptureImpl::ConnectCaptureDevice\n"
"deadlock:webrtc::ViEChannel::StartSend\n"
"deadlock:webrtc::ViECodecImpl::GetSendSideDelay\n"
"deadlock:webrtc::ViEEncoder::OnLocalSsrcChanged\n"
"deadlock:webrtc::ViESender::RegisterSendTransport\n"
// TODO(pbos): Trace events are racy due to lack of proper POD atomics.
// https://code.google.com/p/webrtc/issues/detail?id=2497
"race:*trace_event_unique_catstatic*\n"
// End of suppressions.
; // Please keep this semicolon.
#endif // THREAD_SANITIZER
<commit_msg>Suppress data races in libjingle_peerconnection_unittest<commit_after>/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// This file contains the WebRTC suppressions for ThreadSanitizer.
// Please refer to
// http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for more info.
#if defined(THREAD_SANITIZER)
// Please make sure the code below declares a single string variable
// kTSanDefaultSuppressions contains TSan suppressions delimited by newlines.
// See http://dev.chromium.org/developers/testing/threadsanitizer-tsan-v2
// for the instructions on writing suppressions.
char kTSanDefaultSuppressions[] =
// WebRTC specific suppressions.
// Split up suppressions covered previously by thread.cc and messagequeue.cc.
"race:rtc::MessageQueue::Quit\n"
"race:FileVideoCapturerTest::VideoCapturerListener::OnFrameCaptured\n"
"race:vp8cx_remove_encoder_threads\n"
"race:third_party/libvpx/source/libvpx/vp9/common/vp9_scan.h\n"
// Usage of trace callback and trace level is racy in libjingle_media_unittests.
// https://code.google.com/p/webrtc/issues/detail?id=3372
"race:webrtc::TraceImpl::WriteToFile\n"
"race:webrtc::VideoEngine::SetTraceFilter\n"
"race:webrtc::VoiceEngine::SetTraceFilter\n"
"race:webrtc::Trace::set_level_filter\n"
"race:webrtc::GetStaticInstance<webrtc::TraceImpl>\n"
// Audio processing
// https://code.google.com/p/webrtc/issues/detail?id=2521 for details.
"race:webrtc/modules/audio_processing/aec/aec_core.c\n"
"race:webrtc/modules/audio_processing/aec/aec_rdft.c\n"
// rtc_unittest
// https://code.google.com/p/webrtc/issues/detail?id=3911 for details.
"race:rtc::AsyncInvoker::OnMessage\n"
"race:rtc::FireAndForgetAsyncClosure<FunctorB>::Execute\n"
"race:rtc::MessageQueueManager::Clear\n"
"race:rtc::Thread::Clear\n"
// https://code.google.com/p/webrtc/issues/detail?id=2080
"race:webrtc/base/logging.cc\n"
"race:webrtc/base/sharedexclusivelock_unittest.cc\n"
"race:webrtc/base/signalthread_unittest.cc\n"
// https://code.google.com/p/webrtc/issues/detail?id=4456
"deadlock:rtc::MessageQueueManager::Clear\n"
"deadlock:rtc::MessageQueueManager::ClearInternal\n"
// libjingle_peerconnection_unittest
// https://code.google.com/p/webrtc/issues/detail?id=4488
"race:webrtc::voe::ChannelOwner::~ChannelOwner\n"
"race:cricket::ChannelManager::Terminate_w()\n"
// libjingle_p2p_unittest
// https://code.google.com/p/webrtc/issues/detail?id=2079
"race:webrtc/base/testclient.cc\n"
"race:webrtc/base/virtualsocketserver.cc\n"
"race:talk/p2p/base/stunserver_unittest.cc\n"
// third_party/usrsctp
// TODO(jiayl): https://code.google.com/p/webrtc/issues/detail?id=3492
"race:user_sctp_timer_iterate\n"
// Potential deadlocks detected after roll in r6516.
// https://code.google.com/p/webrtc/issues/detail?id=3509
"deadlock:webrtc::ProcessThreadImpl::RegisterModule\n"
"deadlock:webrtc::RTCPReceiver::SetSsrcs\n"
"deadlock:webrtc::test::UdpSocketManagerPosixImpl::RemoveSocket\n"
"deadlock:webrtc::vcm::VideoReceiver::RegisterPacketRequestCallback\n"
"deadlock:webrtc::ViECaptureImpl::ConnectCaptureDevice\n"
"deadlock:webrtc::ViEChannel::StartSend\n"
"deadlock:webrtc::ViECodecImpl::GetSendSideDelay\n"
"deadlock:webrtc::ViEEncoder::OnLocalSsrcChanged\n"
"deadlock:webrtc::ViESender::RegisterSendTransport\n"
// TODO(pbos): Trace events are racy due to lack of proper POD atomics.
// https://code.google.com/p/webrtc/issues/detail?id=2497
"race:*trace_event_unique_catstatic*\n"
// End of suppressions.
; // Please keep this semicolon.
#endif // THREAD_SANITIZER
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 <random>
#include <type_traits>
#include "paddle/framework/op_registry.h"
#include "paddle/framework/operator.h"
namespace paddle {
namespace operators {
// It seems that Eigen::Tensor::random in GPU will SEGFAULT.
// Use std::random and thrust::random(thrust is a std library in CUDA) to
// implement uniform random.
template <typename T>
class CPUUniformRandomKernel : public framework::OpKernel {
public:
void Compute(const framework::ExecutionContext& context) const override {
auto* tensor = context.Output<framework::Tensor>(0);
T* data = tensor->mutable_data<T>(context.GetPlace());
unsigned int seed =
static_cast<unsigned int>(context.op_.GetAttr<int>("seed"));
std::minstd_rand engine;
if (seed == 0) {
seed = std::random_device()();
}
engine.seed(seed);
std::uniform_real_distribution<T> dist(
static_cast<T>(context.op_.GetAttr<float>("min")),
static_cast<T>(context.op_.GetAttr<float>("max")));
for (ssize_t i = 0; i < framework::product(tensor->dims()); ++i) {
data[i] = dist(engine);
}
}
};
class UniformRandomOp : public framework::OperatorWithKernel {
protected:
void InferShape(const framework::InferShapeContext& ctx) const override {
PADDLE_ENFORCE(GetAttr<float>("min") < GetAttr<float>("max"),
"uniform_random's min must less then max");
auto tensor = ctx.Output<framework::Tensor>(0);
auto dims = GetAttr<std::vector<int>>("dims");
tensor->Resize(framework::make_ddim(dims));
}
};
class UniformRandomOpMaker : public framework::OpProtoAndCheckerMaker {
public:
UniformRandomOpMaker(framework::OpProto* proto,
framework::OpAttrChecker* op_checker)
: framework::OpProtoAndCheckerMaker(proto, op_checker) {
AddOutput("Out", "The output tensor of uniform random op");
AddComment(R"DOC(Uniform random operator.
Used to initialize tensor with uniform random generator.
)DOC");
AddAttr<std::vector<int>>("dims", "the dimension of random tensor");
AddAttr<float>("min", "Minimum value of uniform random").SetDefault(-1.0f);
AddAttr<float>("max", "Maximun value of uniform random").SetDefault(1.0f);
AddAttr<int>("seed",
"Random seed of uniform random. "
"0 means generate a seed by system")
.SetDefault(0);
}
};
} // namespace operators
} // namespace paddle
REGISTER_OP(uniform_random, paddle::operators::UniformRandomOp,
paddle::operators::UniformRandomOpMaker);
REGISTER_OP_CPU_KERNEL(uniform_random,
paddle::operators::CPUUniformRandomKernel<float>);
<commit_msg>Follow comments, change auto -> auto*<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 <random>
#include <type_traits>
#include "paddle/framework/op_registry.h"
#include "paddle/framework/operator.h"
namespace paddle {
namespace operators {
// It seems that Eigen::Tensor::random in GPU will SEGFAULT.
// Use std::random and thrust::random(thrust is a std library in CUDA) to
// implement uniform random.
template <typename T>
class CPUUniformRandomKernel : public framework::OpKernel {
public:
void Compute(const framework::ExecutionContext& context) const override {
auto* tensor = context.Output<framework::Tensor>(0);
T* data = tensor->mutable_data<T>(context.GetPlace());
unsigned int seed =
static_cast<unsigned int>(context.op_.GetAttr<int>("seed"));
std::minstd_rand engine;
if (seed == 0) {
seed = std::random_device()();
}
engine.seed(seed);
std::uniform_real_distribution<T> dist(
static_cast<T>(context.op_.GetAttr<float>("min")),
static_cast<T>(context.op_.GetAttr<float>("max")));
for (ssize_t i = 0; i < framework::product(tensor->dims()); ++i) {
data[i] = dist(engine);
}
}
};
class UniformRandomOp : public framework::OperatorWithKernel {
protected:
void InferShape(const framework::InferShapeContext& ctx) const override {
PADDLE_ENFORCE(GetAttr<float>("min") < GetAttr<float>("max"),
"uniform_random's min must less then max");
auto* tensor = ctx.Output<framework::Tensor>(0);
auto dims = GetAttr<std::vector<int>>("dims");
tensor->Resize(framework::make_ddim(dims));
}
};
class UniformRandomOpMaker : public framework::OpProtoAndCheckerMaker {
public:
UniformRandomOpMaker(framework::OpProto* proto,
framework::OpAttrChecker* op_checker)
: framework::OpProtoAndCheckerMaker(proto, op_checker) {
AddOutput("Out", "The output tensor of uniform random op");
AddComment(R"DOC(Uniform random operator.
Used to initialize tensor with uniform random generator.
)DOC");
AddAttr<std::vector<int>>("dims", "the dimension of random tensor");
AddAttr<float>("min", "Minimum value of uniform random").SetDefault(-1.0f);
AddAttr<float>("max", "Maximun value of uniform random").SetDefault(1.0f);
AddAttr<int>("seed",
"Random seed of uniform random. "
"0 means generate a seed by system")
.SetDefault(0);
}
};
} // namespace operators
} // namespace paddle
REGISTER_OP(uniform_random, paddle::operators::UniformRandomOp,
paddle::operators::UniformRandomOpMaker);
REGISTER_OP_CPU_KERNEL(uniform_random,
paddle::operators::CPUUniformRandomKernel<float>);
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkMarchingContourFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
THIS CLASS IS PATENTED UNDER UNITED STATES PATENT NUMBER 4,710,876
"System and Method for the Display of Surface Structures Contained
Within the Interior Region of a Solid Body".
Application of this software for commercial purposes requires
a license grant from GE. Contact:
Jerald Roehling
GE Licensing
One Independence Way
PO Box 2023
Princeton, N.J. 08540
phone 609-734-9823
e-mail:Roehlinj@gerlmo.ge.com
for more information.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkMarchingContourFilter.h"
#include "vtkScalars.h"
#include "vtkCell.h"
#include "vtkMergePoints.h"
#include "vtkContourValues.h"
#include "vtkScalarTree.h"
#include "vtkContourFilter.h"
#include "vtkMarchingSquares.h"
#include "vtkMarchingCubes.h"
#include "vtkImageMarchingCubes.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkMarchingContourFilter* vtkMarchingContourFilter::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkMarchingContourFilter");
if(ret)
{
return (vtkMarchingContourFilter*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkMarchingContourFilter;
}
// Construct object with initial range (0,1) and single contour value
// of 0.0.
vtkMarchingContourFilter::vtkMarchingContourFilter()
{
this->ContourValues = vtkContourValues::New();
this->ComputeNormals = 1;
this->ComputeGradients = 0;
this->ComputeScalars = 1;
this->Locator = NULL;
this->UseScalarTree = 0;
this->ScalarTree = NULL;
}
vtkMarchingContourFilter::~vtkMarchingContourFilter()
{
this->ContourValues->Delete();
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( this->ScalarTree )
{
this->ScalarTree->Delete();
}
}
// Overload standard modified time function. If contour values are modified,
// then this object is modified as well.
unsigned long vtkMarchingContourFilter::GetMTime()
{
unsigned long mTime=this->vtkDataSetToPolyDataFilter::GetMTime();
unsigned long time;
if (this->ContourValues)
{
time = this->ContourValues->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
if (this->Locator)
{
time = this->Locator->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
return mTime;
}
//
// General contouring filter. Handles arbitrary input.
//
void vtkMarchingContourFilter::Execute()
{
vtkScalars *inScalars;
vtkDataSet *input=this->GetInput();
vtkPolyData *output=this->GetOutput();
int numCells;
vtkPointData *inPd, *outPd=output->GetPointData();
vtkCellData *inCd, *outCd=output->GetCellData();
int numContours=this->ContourValues->GetNumberOfContours();
float *values=this->ContourValues->GetValues();
vtkDebugMacro(<< "Executing marching contour filter");
if (input == NULL)
{
vtkErrorMacro(<<"Input is NULL");
return;
}
inPd=input->GetPointData();
inCd=input->GetCellData();
numCells = input->GetNumberOfCells();
inScalars = input->GetPointData()->GetScalars();
if ( ! inScalars || numCells < 1 )
{
vtkErrorMacro(<<"No data to contour");
return;
}
// If structured points, use more efficient algorithms
if ( (input->GetDataObjectType() == VTK_STRUCTURED_POINTS))
{
if (inScalars->GetDataType() != VTK_BIT)
{
int dim = input->GetCell(0)->GetCellDimension();
if ( input->GetCell(0)->GetCellDimension() >= 2 )
{
vtkDebugMacro(<< "Structured Points");
this->StructuredPointsContour(dim);
return;
}
}
}
if ( (input->GetDataObjectType() == VTK_IMAGE_DATA))
{
if (inScalars->GetDataType() != VTK_BIT)
{
int dim = input->GetCell(0)->GetCellDimension();
if ( input->GetCell(0)->GetCellDimension() >= 2 )
{
vtkDebugMacro(<< "Image");
this->ImageContour(dim);
return;
}
}
}
vtkDebugMacro(<< "Unoptimized");
this->DataSetContour();
}
void vtkMarchingContourFilter::StructuredPointsContour(int dim)
{
vtkPolyData *output;
vtkPolyData *thisOutput = this->GetOutput();
int numContours=this->ContourValues->GetNumberOfContours();
float *values=this->ContourValues->GetValues();
if ( dim == 2 ) //marching squares
{
vtkMarchingSquares *msquares;
int i;
msquares = vtkMarchingSquares::New();
msquares->SetInput((vtkStructuredPoints *)this->GetInput());
msquares->SetDebug(this->Debug);
msquares->SetNumberOfContours(numContours);
for (i=0; i < numContours; i++)
{
msquares->SetValue(i,values[i]);
}
msquares->Update();
output = msquares->GetOutput();
output->Register(this);
msquares->Delete();
}
else //marching cubes
{
vtkMarchingCubes *mcubes;
int i;
mcubes = vtkMarchingCubes::New();
mcubes->SetInput((vtkStructuredPoints *)this->GetInput());
mcubes->SetComputeNormals (this->ComputeNormals);
mcubes->SetComputeGradients (this->ComputeGradients);
mcubes->SetComputeScalars (this->ComputeScalars);
mcubes->SetDebug(this->Debug);
mcubes->SetNumberOfContours(numContours);
for (i=0; i < numContours; i++)
{
mcubes->SetValue(i,values[i]);
}
mcubes->Update();
output = mcubes->GetOutput();
output->Register(this);
mcubes->Delete();
}
thisOutput->CopyStructure(output);
thisOutput->GetPointData()->ShallowCopy(output->GetPointData());
output->UnRegister(this);
}
void vtkMarchingContourFilter::DataSetContour()
{
vtkPolyData *output = this->GetOutput();
vtkPolyData *thisOutput = this->GetOutput();
int numContours=this->ContourValues->GetNumberOfContours();
float *values=this->ContourValues->GetValues();
vtkContourFilter *contour = vtkContourFilter::New();
contour->SetInput((vtkImageData *)this->GetInput());
contour->SetOutput(output);
contour->SetComputeNormals (this->ComputeNormals);
contour->SetComputeGradients (this->ComputeGradients);
contour->SetComputeScalars (this->ComputeScalars);
contour->SetDebug(this->Debug);
contour->SetNumberOfContours(numContours);
for (int i=0; i < numContours; i++)
{
contour->SetValue(i,values[i]);
}
contour->Update();
this->SetOutput(output);
contour->Delete();
}
void vtkMarchingContourFilter::ImageContour(int dim)
{
vtkPolyData *output = this->GetOutput();
vtkPolyData *thisOutput = this->GetOutput();
int numContours=this->ContourValues->GetNumberOfContours();
float *values=this->ContourValues->GetValues();
if ( dim == 2 ) //marching squares
{
vtkMarchingSquares *msquares;
int i;
msquares = vtkMarchingSquares::New();
msquares->SetInput((vtkImageData *)this->GetInput());
msquares->SetOutput(output);
msquares->SetDebug(this->Debug);
msquares->SetNumberOfContours(numContours);
for (i=0; i < numContours; i++)
{
msquares->SetValue(i,values[i]);
}
msquares->Update();
this->SetOutput(output);
msquares->Delete();
}
else //image marching cubes
{
vtkImageMarchingCubes *mcubes;
int i;
mcubes = vtkImageMarchingCubes::New();
mcubes->SetInput((vtkImageData *)this->GetInput());
mcubes->SetOutput(output);
mcubes->SetComputeNormals (this->ComputeNormals);
mcubes->SetComputeGradients (this->ComputeGradients);
mcubes->SetComputeScalars (this->ComputeScalars);
mcubes->SetDebug(this->Debug);
mcubes->SetNumberOfContours(numContours);
for (i=0; i < numContours; i++)
{
mcubes->SetValue(i,values[i]);
}
mcubes->Update();
this->SetOutput(output);
mcubes->Delete();
}
}
// Specify a spatial locator for merging points. By default,
// an instance of vtkMergePoints is used.
void vtkMarchingContourFilter::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator == locator )
{
return;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( locator )
{
locator->Register(this);
}
this->Locator = locator;
this->Modified();
}
void vtkMarchingContourFilter::CreateDefaultLocator()
{
if ( this->Locator == NULL )
{
this->Locator = vtkMergePoints::New();
}
}
void vtkMarchingContourFilter::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDataSetToPolyDataFilter::PrintSelf(os,indent);
os << indent << "Compute Gradients: " << (this->ComputeGradients ? "On\n" : "Off\n");
os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n");
os << indent << "Compute Scalars: " << (this->ComputeScalars ? "On\n" : "Off\n");
os << indent << "Use Scalar Tree: " << (this->UseScalarTree ? "On\n" : "Off\n");
this->ContourValues->PrintSelf(os,indent);
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
}
<commit_msg>ERR: removed warnings.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkMarchingContourFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.
THIS CLASS IS PATENTED UNDER UNITED STATES PATENT NUMBER 4,710,876
"System and Method for the Display of Surface Structures Contained
Within the Interior Region of a Solid Body".
Application of this software for commercial purposes requires
a license grant from GE. Contact:
Jerald Roehling
GE Licensing
One Independence Way
PO Box 2023
Princeton, N.J. 08540
phone 609-734-9823
e-mail:Roehlinj@gerlmo.ge.com
for more information.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkMarchingContourFilter.h"
#include "vtkScalars.h"
#include "vtkCell.h"
#include "vtkMergePoints.h"
#include "vtkContourValues.h"
#include "vtkScalarTree.h"
#include "vtkContourFilter.h"
#include "vtkMarchingSquares.h"
#include "vtkMarchingCubes.h"
#include "vtkImageMarchingCubes.h"
#include "vtkObjectFactory.h"
//------------------------------------------------------------------------------
vtkMarchingContourFilter* vtkMarchingContourFilter::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkMarchingContourFilter");
if(ret)
{
return (vtkMarchingContourFilter*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkMarchingContourFilter;
}
// Construct object with initial range (0,1) and single contour value
// of 0.0.
vtkMarchingContourFilter::vtkMarchingContourFilter()
{
this->ContourValues = vtkContourValues::New();
this->ComputeNormals = 1;
this->ComputeGradients = 0;
this->ComputeScalars = 1;
this->Locator = NULL;
this->UseScalarTree = 0;
this->ScalarTree = NULL;
}
vtkMarchingContourFilter::~vtkMarchingContourFilter()
{
this->ContourValues->Delete();
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( this->ScalarTree )
{
this->ScalarTree->Delete();
}
}
// Overload standard modified time function. If contour values are modified,
// then this object is modified as well.
unsigned long vtkMarchingContourFilter::GetMTime()
{
unsigned long mTime=this->vtkDataSetToPolyDataFilter::GetMTime();
unsigned long time;
if (this->ContourValues)
{
time = this->ContourValues->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
if (this->Locator)
{
time = this->Locator->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
return mTime;
}
//
// General contouring filter. Handles arbitrary input.
//
void vtkMarchingContourFilter::Execute()
{
vtkScalars *inScalars;
vtkDataSet *input=this->GetInput();
vtkPolyData *output=this->GetOutput();
int numCells;
vtkPointData *outPd=output->GetPointData();
vtkCellData *outCd=output->GetCellData();
int numContours=this->ContourValues->GetNumberOfContours();
float *values=this->ContourValues->GetValues();
vtkDebugMacro(<< "Executing marching contour filter");
if (input == NULL)
{
vtkErrorMacro(<<"Input is NULL");
return;
}
numCells = input->GetNumberOfCells();
inScalars = input->GetPointData()->GetScalars();
if ( ! inScalars || numCells < 1 )
{
vtkErrorMacro(<<"No data to contour");
return;
}
// If structured points, use more efficient algorithms
if ( (input->GetDataObjectType() == VTK_STRUCTURED_POINTS))
{
if (inScalars->GetDataType() != VTK_BIT)
{
int dim = input->GetCell(0)->GetCellDimension();
if ( input->GetCell(0)->GetCellDimension() >= 2 )
{
vtkDebugMacro(<< "Structured Points");
this->StructuredPointsContour(dim);
return;
}
}
}
if ( (input->GetDataObjectType() == VTK_IMAGE_DATA))
{
if (inScalars->GetDataType() != VTK_BIT)
{
int dim = input->GetCell(0)->GetCellDimension();
if ( input->GetCell(0)->GetCellDimension() >= 2 )
{
vtkDebugMacro(<< "Image");
this->ImageContour(dim);
return;
}
}
}
vtkDebugMacro(<< "Unoptimized");
this->DataSetContour();
}
void vtkMarchingContourFilter::StructuredPointsContour(int dim)
{
vtkPolyData *output;
vtkPolyData *thisOutput = this->GetOutput();
int numContours=this->ContourValues->GetNumberOfContours();
float *values=this->ContourValues->GetValues();
if ( dim == 2 ) //marching squares
{
vtkMarchingSquares *msquares;
int i;
msquares = vtkMarchingSquares::New();
msquares->SetInput((vtkStructuredPoints *)this->GetInput());
msquares->SetDebug(this->Debug);
msquares->SetNumberOfContours(numContours);
for (i=0; i < numContours; i++)
{
msquares->SetValue(i,values[i]);
}
msquares->Update();
output = msquares->GetOutput();
output->Register(this);
msquares->Delete();
}
else //marching cubes
{
vtkMarchingCubes *mcubes;
int i;
mcubes = vtkMarchingCubes::New();
mcubes->SetInput((vtkStructuredPoints *)this->GetInput());
mcubes->SetComputeNormals (this->ComputeNormals);
mcubes->SetComputeGradients (this->ComputeGradients);
mcubes->SetComputeScalars (this->ComputeScalars);
mcubes->SetDebug(this->Debug);
mcubes->SetNumberOfContours(numContours);
for (i=0; i < numContours; i++)
{
mcubes->SetValue(i,values[i]);
}
mcubes->Update();
output = mcubes->GetOutput();
output->Register(this);
mcubes->Delete();
}
thisOutput->CopyStructure(output);
thisOutput->GetPointData()->ShallowCopy(output->GetPointData());
output->UnRegister(this);
}
void vtkMarchingContourFilter::DataSetContour()
{
vtkPolyData *output = this->GetOutput();
vtkPolyData *thisOutput = this->GetOutput();
int numContours=this->ContourValues->GetNumberOfContours();
float *values=this->ContourValues->GetValues();
vtkContourFilter *contour = vtkContourFilter::New();
contour->SetInput((vtkImageData *)this->GetInput());
contour->SetOutput(output);
contour->SetComputeNormals (this->ComputeNormals);
contour->SetComputeGradients (this->ComputeGradients);
contour->SetComputeScalars (this->ComputeScalars);
contour->SetDebug(this->Debug);
contour->SetNumberOfContours(numContours);
for (int i=0; i < numContours; i++)
{
contour->SetValue(i,values[i]);
}
contour->Update();
this->SetOutput(output);
contour->Delete();
}
void vtkMarchingContourFilter::ImageContour(int dim)
{
vtkPolyData *output = this->GetOutput();
vtkPolyData *thisOutput = this->GetOutput();
int numContours=this->ContourValues->GetNumberOfContours();
float *values=this->ContourValues->GetValues();
if ( dim == 2 ) //marching squares
{
vtkMarchingSquares *msquares;
int i;
msquares = vtkMarchingSquares::New();
msquares->SetInput((vtkImageData *)this->GetInput());
msquares->SetOutput(output);
msquares->SetDebug(this->Debug);
msquares->SetNumberOfContours(numContours);
for (i=0; i < numContours; i++)
{
msquares->SetValue(i,values[i]);
}
msquares->Update();
this->SetOutput(output);
msquares->Delete();
}
else //image marching cubes
{
vtkImageMarchingCubes *mcubes;
int i;
mcubes = vtkImageMarchingCubes::New();
mcubes->SetInput((vtkImageData *)this->GetInput());
mcubes->SetOutput(output);
mcubes->SetComputeNormals (this->ComputeNormals);
mcubes->SetComputeGradients (this->ComputeGradients);
mcubes->SetComputeScalars (this->ComputeScalars);
mcubes->SetDebug(this->Debug);
mcubes->SetNumberOfContours(numContours);
for (i=0; i < numContours; i++)
{
mcubes->SetValue(i,values[i]);
}
mcubes->Update();
this->SetOutput(output);
mcubes->Delete();
}
}
// Specify a spatial locator for merging points. By default,
// an instance of vtkMergePoints is used.
void vtkMarchingContourFilter::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator == locator )
{
return;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( locator )
{
locator->Register(this);
}
this->Locator = locator;
this->Modified();
}
void vtkMarchingContourFilter::CreateDefaultLocator()
{
if ( this->Locator == NULL )
{
this->Locator = vtkMergePoints::New();
}
}
void vtkMarchingContourFilter::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDataSetToPolyDataFilter::PrintSelf(os,indent);
os << indent << "Compute Gradients: " << (this->ComputeGradients ? "On\n" : "Off\n");
os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n");
os << indent << "Compute Scalars: " << (this->ComputeScalars ? "On\n" : "Off\n");
os << indent << "Use Scalar Tree: " << (this->UseScalarTree ? "On\n" : "Off\n");
this->ContourValues->PrintSelf(os,indent);
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************\
* *
* FILENAME: windef.h *
* *
* CONTENTS: Windows-like definitions *
* *
* Author: Jean-Francois Larvoire 94/05/14 *
* *
* Notes: Contains a limited subset of WINDOWS.H, for use by *
* applications that will run under DOS, but that want *
* to be easily portable to Windows. *
* *
* History: *
* 95/02/16 JFL Added support for C++. *
* Moved functions definitions to PMODE.H. *
* *
* (c) Copyright 1994-2017 Hewlett Packard Enterprise Development LP *
* Licensed under the Apache 2.0 license - www.apache.org/licenses/LICENSE-2.0 *
\*****************************************************************************/
#ifndef _WINDEF_H
#define EXPORT // Must not be exported under DOS
#define _WINDEF_H
#ifdef __cplusplus
extern "C" {
#endif
/****** Common definitions and typedefs ******/
#define VOID void
#define NEAR _near
#define FAR _far
#define PASCAL _pascal
#define CDECL _cdecl
#define WINAPI _pascal
#define CALLBACK _far _pascal
/****** Simple types & common helper macros ******/
typedef int BOOL;
#define FALSE 0
#define TRUE 1
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned long DWORD;
typedef unsigned int UINT;
typedef signed long LONG;
#define LOBYTE(x) ((BYTE)(x))
#define HIBYTE(x) ((BYTE)(((WORD)(x)) >> 8))
#define LOWORD(x) ((WORD)(DWORD)(x))
#define HIWORD(x) ((WORD)(((DWORD)(x)) >> 16))
#define MAKELONG(low, high) ((LONG)( ((WORD)(low)) \
| (((DWORD)((WORD)(high))) << 16) ))
/****** Common pointer types ******/
#ifndef NULL
#define NULL 0
#endif
typedef VOID FAR *LPVOID;
#define MAKELP(sel, off) ((LPVOID)MAKELONG((off), (sel)))
#define SELECTOROF(lp) HIWORD(lp)
#define OFFSETOF(lp) LOWORD(lp)
/****** Common handle types ******/
typedef UINT HANDLE;
typedef UINT HWND;
typedef UINT HGLOBAL;
typedef void (CALLBACK *FARPROC)(void);
#ifdef __cplusplus
}
#endif
#endif
<commit_msg>Include the real windef.h if it's available.<commit_after>/*****************************************************************************\
* *
* Filename: windef.h *
* *
* Description: Windows-like definitions *
* *
* Notes: Contains a limited subset of WINDOWS.H, for use by *
* applications that will run under DOS, but that want *
* to be easily portable to Windows. *
* *
* History: *
* 1994-05-14 JFL Jean-Francois Larvoire created this file. *
* 1995-02-16 JFL Added support for C++. *
* Moved functions definitions to PMODE.H. *
* 2017-06-29 JFL Include the real windef.h if it's available. *
* *
* (C) Copyright 1994-2017 Hewlett Packard Enterprise Development LP *
* Licensed under the Apache 2.0 license - www.apache.org/licenses/LICENSE-2.0 *
\*****************************************************************************/
#ifndef _WINDEF_H
#ifdef _H2INC
#define _MSDOS /* The h2inc.exe tool is for generating 16-bits DOS code */
#endif
#ifndef WSDKINCLUDE /* Windows SDK include directory pathname */
#define EXPORT /* Must not be exported under DOS */
#define _WINDEF_H
#ifdef __cplusplus
extern "C" {
#endif
/****** Common definitions and typedefs ******/
#define VOID void
#undef NEAR
#undef FAR
#undef PASCAL
#undef CDECL
#undef WINAPI
#define NEAR _near
#define FAR _far
#define PASCAL _pascal
#define CDECL _cdecl
#define WINAPI _pascal
#define CALLBACK _far _pascal
/****** Simple types & common helper macros ******/
typedef int BOOL;
#define FALSE 0
#define TRUE 1
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned long DWORD;
typedef unsigned int UINT;
typedef signed long LONG;
#define LOBYTE(x) ((BYTE)(x))
#define HIBYTE(x) ((BYTE)(((WORD)(x)) >> 8))
#define LOWORD(x) ((WORD)(DWORD)(x))
#define HIWORD(x) ((WORD)(((DWORD)(x)) >> 16))
#define MAKELONG(low, high) ((LONG)( ((WORD)(low)) \
| (((DWORD)((WORD)(high))) << 16) ))
/****** Common pointer types ******/
#ifndef NULL
#define NULL 0
#endif
typedef VOID FAR *LPVOID;
#define MAKELP(sel, off) ((LPVOID)MAKELONG((off), (sel)))
#define SELECTOROF(lp) HIWORD(lp)
#define OFFSETOF(lp) LOWORD(lp)
/****** Common handle types ******/
typedef UINT HANDLE;
typedef UINT HWND;
typedef UINT HGLOBAL;
typedef void (CALLBACK *FARPROC)(void);
#ifdef __cplusplus
}
#endif
#else /* defined(WSDKINCLUDE) */
/* Then use the actual windef.h from the Windows SDK */
/* Macros for working around the lack of a #include_next directive */
#define WINDEF_CONCAT1(a,b) a##b /* Concatenate the raw arguments */
#define WINDEF_CONCAT(a,b) WINDEF_CONCAT1(a,b) /* Substitute the arguments, then concatenate the values */
#define WINDEF_STRINGIZE1(x) #x /* Convert the raw argument to a string */
#define WINDEF_STRINGIZE(x) WINDEF_STRINGIZE1(x) /* Substitute the argument, then convert its value to a string */
#define WINSDK_INCLUDE_FILE(relpath) WINDEF_STRINGIZE(WINDEF_CONCAT(WSDKINCLUDE,WINDEF_CONCAT(/,relpath))) /* Windows SDK include files */
#define REAL_WINDEF WINSDK_INCLUDE_FILE(windef.h)
#pragma message("#include \"" REAL_WINDEF "\"")
#include REAL_WINDEF
#endif /* !defined(WSDKINCLUDE) */
#endif /* _WINDEF_H */
<|endoftext|> |
<commit_before>#include "EngineCommand.h"
#include <maya/MArgDatabase.h>
#include <maya/MArgList.h>
#include <maya/MStatus.h>
#include <HAPI/HAPI.h>
#include "SubCommand.h"
#define kHoudiniVersionFlag "-hv"
#define kHoudiniVersionFlagLong "-houdiniVersion"
#define kSaveHIPFlag "-sh"
#define kSaveHIPFlagLong "-saveHIP"
const char* EngineCommand::commandName = "houdiniEngine";
class EngineSubCommandSaveHIPFile : public SubCommand
{
public:
EngineSubCommandSaveHIPFile(const MString &hipFilePath) :
myHIPFilePath(hipFilePath)
{
}
virtual MStatus doIt()
{
HAPI_SaveHIPFile(myHIPFilePath.asChar());
return MStatus::kSuccess;
}
protected:
MString myHIPFilePath;
};
class EngineSubCommandHoudiniVersion : public SubCommand
{
public:
virtual MStatus doIt()
{
int major, minor, build;
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_MAJOR, &major);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_MINOR, &minor);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_BUILD, &build);
MString version_string;
version_string.format(
"^1s.^2s.^3s",
MString() + major,
MString() + minor,
MString() + build
);
MPxCommand::setResult(version_string);
return MStatus::kSuccess;
}
};
void* EngineCommand::creator()
{
return new EngineCommand();
}
MSyntax
EngineCommand::newSyntax()
{
MSyntax syntax;
// -houdiniVersion returns the Houdini version that's being used.
CHECK_MSTATUS(syntax.addFlag(kHoudiniVersionFlag, kHoudiniVersionFlagLong));
// -saveHIP saves the contents of the current Houdini scene as a hip file
// expected arguments: hip_file_name - the name of the hip file to save
CHECK_MSTATUS(syntax.addFlag(kSaveHIPFlag, kSaveHIPFlagLong, MSyntax::kString));
return syntax;
}
EngineCommand::EngineCommand() :
mySubCommand(NULL)
{
}
EngineCommand::~EngineCommand()
{
delete mySubCommand;
}
MStatus
EngineCommand::parseArgs(const MArgList &args)
{
MStatus status;
MArgDatabase argData(syntax(), args, &status);
if(!status)
{
return status;
}
if(!(
argData.isFlagSet(kHoudiniVersionFlag)
^ argData.isFlagSet(kSaveHIPFlag)
))
{
displayError("Exactly one of these flags must be specified:\n"
kSaveHIPFlagLong "\n"
);
return MStatus::kInvalidParameter;
}
if(argData.isFlagSet(kHoudiniVersionFlag))
{
mySubCommand = new EngineSubCommandHoudiniVersion();
}
if(argData.isFlagSet(kSaveHIPFlag))
{
MString hipFilePath;
{
status = argData.getFlagArgument(kSaveHIPFlag, 0, hipFilePath);
if(!status)
{
displayError("Invalid argument for \"" kSaveHIPFlagLong "\".");
return status;
}
}
mySubCommand = new EngineSubCommandSaveHIPFile(hipFilePath);
}
return MStatus::kSuccess;
}
MStatus EngineCommand::doIt(const MArgList& args)
{
MStatus status;
status = parseArgs(args);
if(!status)
{
return status;
}
return mySubCommand->doIt();
}
MStatus EngineCommand::redoIt()
{
return mySubCommand->redoIt();
}
MStatus EngineCommand::undoIt()
{
return mySubCommand->undoIt();
}
bool EngineCommand::isUndoable() const
{
return mySubCommand->isUndoable();
}
<commit_msg>Add "houdiniEngine -houdiniEngineVersion" to retrieve the Houdini Engine version<commit_after>#include "EngineCommand.h"
#include <maya/MArgDatabase.h>
#include <maya/MArgList.h>
#include <maya/MStatus.h>
#include <HAPI/HAPI.h>
#include "SubCommand.h"
#define kHoudiniVersionFlag "-hv"
#define kHoudiniVersionFlagLong "-houdiniVersion"
#define kHoudiniEngineVersionFlag "-hev"
#define kHoudiniEngineVersionFlagLong "-houdiniEngineVersion"
#define kSaveHIPFlag "-sh"
#define kSaveHIPFlagLong "-saveHIP"
const char* EngineCommand::commandName = "houdiniEngine";
class EngineSubCommandSaveHIPFile : public SubCommand
{
public:
EngineSubCommandSaveHIPFile(const MString &hipFilePath) :
myHIPFilePath(hipFilePath)
{
}
virtual MStatus doIt()
{
HAPI_SaveHIPFile(myHIPFilePath.asChar());
return MStatus::kSuccess;
}
protected:
MString myHIPFilePath;
};
class EngineSubCommandHoudiniVersion : public SubCommand
{
public:
virtual MStatus doIt()
{
int major, minor, build;
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_MAJOR, &major);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_MINOR, &minor);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_BUILD, &build);
MString version_string;
version_string.format(
"^1s.^2s.^3s",
MString() + major,
MString() + minor,
MString() + build
);
MPxCommand::setResult(version_string);
return MStatus::kSuccess;
}
};
class EngineSubCommandHoudiniEngineVersion : public SubCommand
{
public:
virtual MStatus doIt()
{
int major, minor, api;
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MAJOR, &major);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_MINOR, &minor);
HAPI_GetEnvInt(HAPI_ENVINT_VERSION_HOUDINI_ENGINE_API, &api);
MString version_string;
version_string.format(
"^1s.^2s (API: ^3s)",
MString() + major,
MString() + minor,
MString() + api
);
MPxCommand::setResult(version_string);
return MStatus::kSuccess;
}
};
void* EngineCommand::creator()
{
return new EngineCommand();
}
MSyntax
EngineCommand::newSyntax()
{
MSyntax syntax;
// -houdiniVersion returns the Houdini version that's being used.
CHECK_MSTATUS(syntax.addFlag(kHoudiniVersionFlag, kHoudiniVersionFlagLong));
// -houdiniVersion returns the Houdini version that's being used.
CHECK_MSTATUS(syntax.addFlag(kHoudiniEngineVersionFlag, kHoudiniEngineVersionFlagLong));
// -saveHIP saves the contents of the current Houdini scene as a hip file
// expected arguments: hip_file_name - the name of the hip file to save
CHECK_MSTATUS(syntax.addFlag(kSaveHIPFlag, kSaveHIPFlagLong, MSyntax::kString));
return syntax;
}
EngineCommand::EngineCommand() :
mySubCommand(NULL)
{
}
EngineCommand::~EngineCommand()
{
delete mySubCommand;
}
MStatus
EngineCommand::parseArgs(const MArgList &args)
{
MStatus status;
MArgDatabase argData(syntax(), args, &status);
if(!status)
{
return status;
}
if(!(
argData.isFlagSet(kHoudiniVersionFlag)
^ argData.isFlagSet(kHoudiniEngineVersionFlag)
^ argData.isFlagSet(kSaveHIPFlag)
))
{
displayError("Exactly one of these flags must be specified:\n"
kSaveHIPFlagLong "\n"
);
return MStatus::kInvalidParameter;
}
if(argData.isFlagSet(kHoudiniVersionFlag))
{
mySubCommand = new EngineSubCommandHoudiniVersion();
}
if(argData.isFlagSet(kHoudiniEngineVersionFlag))
{
mySubCommand = new EngineSubCommandHoudiniEngineVersion();
}
if(argData.isFlagSet(kSaveHIPFlag))
{
MString hipFilePath;
{
status = argData.getFlagArgument(kSaveHIPFlag, 0, hipFilePath);
if(!status)
{
displayError("Invalid argument for \"" kSaveHIPFlagLong "\".");
return status;
}
}
mySubCommand = new EngineSubCommandSaveHIPFile(hipFilePath);
}
return MStatus::kSuccess;
}
MStatus EngineCommand::doIt(const MArgList& args)
{
MStatus status;
status = parseArgs(args);
if(!status)
{
return status;
}
return mySubCommand->doIt();
}
MStatus EngineCommand::redoIt()
{
return mySubCommand->redoIt();
}
MStatus EngineCommand::undoIt()
{
return mySubCommand->undoIt();
}
bool EngineCommand::isUndoable() const
{
return mySubCommand->isUndoable();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/detail/MemoryIdler.h>
#include <folly/Logging.h>
#include <folly/Portability.h>
#include <folly/ScopeGuard.h>
#include <folly/concurrency/CacheLocality.h>
#include <folly/memory/MallctlHelper.h>
#include <folly/memory/Malloc.h>
#include <folly/portability/PThread.h>
#include <folly/portability/SysMman.h>
#include <folly/portability/Unistd.h>
#include <folly/synchronization/CallOnce.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <utility>
namespace folly {
namespace detail {
AtomicStruct<std::chrono::steady_clock::duration>
MemoryIdler::defaultIdleTimeout(std::chrono::seconds(5));
void MemoryIdler::flushLocalMallocCaches() {
if (!usingJEMalloc()) {
return;
}
if (!mallctl || !mallctlnametomib || !mallctlbymib) {
FB_LOG_EVERY_MS(ERROR, 10000) << "mallctl* weak link failed";
return;
}
try {
// Not using mallctlCall as this will fail if tcache is disabled.
mallctl("thread.tcache.flush", nullptr, nullptr, nullptr, 0);
// By default jemalloc has 4 arenas per cpu, and then assigns each
// thread to one of those arenas. This means that in any service
// that doesn't perform a lot of context switching, the chances that
// another thread will be using the current thread's arena (and hence
// doing the appropriate dirty-page purging) are low. Some good
// tuned configurations (such as that used by hhvm) use fewer arenas
// and then pin threads to avoid contended access. In that case,
// purging the arenas is counter-productive. We use the heuristic
// that if narenas <= 2 * num_cpus then we shouldn't do anything here,
// which detects when the narenas has been reduced from the default
unsigned narenas;
unsigned arenaForCurrent;
size_t mib[3];
size_t miblen = 3;
mallctlRead("opt.narenas", &narenas);
mallctlRead("thread.arena", &arenaForCurrent);
if (narenas > 2 * CacheLocality::system().numCpus &&
mallctlnametomib("arena.0.purge", mib, &miblen) == 0) {
mib[1] = static_cast<size_t>(arenaForCurrent);
mallctlbymib(mib, miblen, nullptr, nullptr, nullptr, 0);
}
} catch (const std::runtime_error& ex) {
FB_LOG_EVERY_MS(WARNING, 10000) << ex.what();
}
}
// Stack madvise isn't Linux or glibc specific, but the system calls
// and arithmetic (and bug compatibility) are not portable. The set of
// platforms could be increased if it was useful.
#if (FOLLY_X64 || FOLLY_PPC64) && defined(_GNU_SOURCE) && \
defined(__linux__) && !FOLLY_MOBILE && !FOLLY_SANITIZE_ADDRESS
static FOLLY_TLS uintptr_t tls_stackLimit;
static FOLLY_TLS size_t tls_stackSize;
static size_t pageSize() {
static const size_t s_pageSize = sysconf(_SC_PAGESIZE);
return s_pageSize;
}
static void fetchStackLimits() {
int err;
pthread_attr_t attr;
if ((err = pthread_getattr_np(pthread_self(), &attr))) {
// some restricted environments can't access /proc
static folly::once_flag flag;
folly::call_once(flag, [err]() {
LOG(WARNING) << "pthread_getaddr_np failed errno=" << err;
});
tls_stackSize = 1;
return;
}
SCOPE_EXIT {
pthread_attr_destroy(&attr);
};
void* addr;
size_t rawSize;
if ((err = pthread_attr_getstack(&attr, &addr, &rawSize))) {
// unexpected, but it is better to continue in prod than do nothing
FB_LOG_EVERY_MS(ERROR, 10000) << "pthread_attr_getstack error " << err;
assert(false);
tls_stackSize = 1;
return;
}
if (rawSize >= 4UL * 1024 * 1024 * 1024) {
// Avoid unmapping huge swaths of memory if there is an insane stack
// size. If we went into /proc to find the actual contiguous mapped
// pages before unmapping we wouldn't care about the size at all, but
// our current strategy is to unmap even pages that are not mapped.
// We will warn (because it is a bug) but better not to crash.
FB_LOG_EVERY_MS(ERROR, 10000)
<< "pthread_attr_getstack returned insane stack size " << rawSize;
assert(false);
tls_stackSize = 1;
return;
}
assert(addr != nullptr);
assert(rawSize >= PTHREAD_STACK_MIN);
// glibc subtracts guard page from stack size, even though pthread docs
// seem to imply the opposite
size_t guardSize;
if (pthread_attr_getguardsize(&attr, &guardSize) != 0) {
guardSize = 0;
}
assert(rawSize > guardSize);
// stack goes down, so guard page adds to the base addr
tls_stackLimit = reinterpret_cast<uintptr_t>(addr) + guardSize;
tls_stackSize = rawSize - guardSize;
assert((tls_stackLimit & (pageSize() - 1)) == 0);
}
FOLLY_NOINLINE static uintptr_t getStackPtr() {
char marker;
auto rv = reinterpret_cast<uintptr_t>(&marker);
return rv;
}
void MemoryIdler::unmapUnusedStack(size_t retain) {
if (tls_stackSize == 0) {
fetchStackLimits();
}
if (tls_stackSize <= std::max(static_cast<size_t>(1), retain)) {
// covers both missing stack info, and impossibly large retain
return;
}
auto sp = getStackPtr();
assert(sp >= tls_stackLimit);
assert(sp - tls_stackLimit < tls_stackSize);
auto end = (sp - retain) & ~(pageSize() - 1);
if (end <= tls_stackLimit) {
// no pages are eligible for unmapping
return;
}
size_t len = end - tls_stackLimit;
assert((len & (pageSize() - 1)) == 0);
if (madvise((void*)tls_stackLimit, len, MADV_DONTNEED) != 0) {
// It is likely that the stack vma hasn't been fully grown. In this
// case madvise will apply dontneed to the present vmas, then return
// errno of ENOMEM. We can also get an EAGAIN, theoretically.
// EINVAL means either an invalid alignment or length, or that some
// of the pages are locked or shared. Neither should occur.
assert(errno == EAGAIN || errno == ENOMEM);
}
}
#else
void MemoryIdler::unmapUnusedStack(size_t /* retain */) {}
#endif
} // namespace detail
} // namespace folly
<commit_msg>fix MemoryIdler constant for 64-bit windows<commit_after>/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/detail/MemoryIdler.h>
#include <folly/Logging.h>
#include <folly/Portability.h>
#include <folly/ScopeGuard.h>
#include <folly/concurrency/CacheLocality.h>
#include <folly/memory/MallctlHelper.h>
#include <folly/memory/Malloc.h>
#include <folly/portability/PThread.h>
#include <folly/portability/SysMman.h>
#include <folly/portability/Unistd.h>
#include <folly/synchronization/CallOnce.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <utility>
namespace folly {
namespace detail {
AtomicStruct<std::chrono::steady_clock::duration>
MemoryIdler::defaultIdleTimeout(std::chrono::seconds(5));
void MemoryIdler::flushLocalMallocCaches() {
if (!usingJEMalloc()) {
return;
}
if (!mallctl || !mallctlnametomib || !mallctlbymib) {
FB_LOG_EVERY_MS(ERROR, 10000) << "mallctl* weak link failed";
return;
}
try {
// Not using mallctlCall as this will fail if tcache is disabled.
mallctl("thread.tcache.flush", nullptr, nullptr, nullptr, 0);
// By default jemalloc has 4 arenas per cpu, and then assigns each
// thread to one of those arenas. This means that in any service
// that doesn't perform a lot of context switching, the chances that
// another thread will be using the current thread's arena (and hence
// doing the appropriate dirty-page purging) are low. Some good
// tuned configurations (such as that used by hhvm) use fewer arenas
// and then pin threads to avoid contended access. In that case,
// purging the arenas is counter-productive. We use the heuristic
// that if narenas <= 2 * num_cpus then we shouldn't do anything here,
// which detects when the narenas has been reduced from the default
unsigned narenas;
unsigned arenaForCurrent;
size_t mib[3];
size_t miblen = 3;
mallctlRead("opt.narenas", &narenas);
mallctlRead("thread.arena", &arenaForCurrent);
if (narenas > 2 * CacheLocality::system().numCpus &&
mallctlnametomib("arena.0.purge", mib, &miblen) == 0) {
mib[1] = static_cast<size_t>(arenaForCurrent);
mallctlbymib(mib, miblen, nullptr, nullptr, nullptr, 0);
}
} catch (const std::runtime_error& ex) {
FB_LOG_EVERY_MS(WARNING, 10000) << ex.what();
}
}
// Stack madvise isn't Linux or glibc specific, but the system calls
// and arithmetic (and bug compatibility) are not portable. The set of
// platforms could be increased if it was useful.
#if (FOLLY_X64 || FOLLY_PPC64) && defined(_GNU_SOURCE) && \
defined(__linux__) && !FOLLY_MOBILE && !FOLLY_SANITIZE_ADDRESS
static FOLLY_TLS uintptr_t tls_stackLimit;
static FOLLY_TLS size_t tls_stackSize;
static size_t pageSize() {
static const size_t s_pageSize = sysconf(_SC_PAGESIZE);
return s_pageSize;
}
static void fetchStackLimits() {
int err;
pthread_attr_t attr;
if ((err = pthread_getattr_np(pthread_self(), &attr))) {
// some restricted environments can't access /proc
static folly::once_flag flag;
folly::call_once(flag, [err]() {
LOG(WARNING) << "pthread_getaddr_np failed errno=" << err;
});
tls_stackSize = 1;
return;
}
SCOPE_EXIT {
pthread_attr_destroy(&attr);
};
void* addr;
size_t rawSize;
if ((err = pthread_attr_getstack(&attr, &addr, &rawSize))) {
// unexpected, but it is better to continue in prod than do nothing
FB_LOG_EVERY_MS(ERROR, 10000) << "pthread_attr_getstack error " << err;
assert(false);
tls_stackSize = 1;
return;
}
if (rawSize >= (1ULL << 32)) {
// Avoid unmapping huge swaths of memory if there is an insane
// stack size. The boundary of sanity is somewhat arbitrary: 4GB.
//
// If we went into /proc to find the actual contiguous mapped pages
// before unmapping we wouldn't care about the stack size at all,
// but our current strategy is to unmap the entire range that might
// be used for the stack even if it hasn't been fully faulted-in.
//
// Very large stack size is a bug (hence the assert), but we can
// carry on if we are in prod.
FB_LOG_EVERY_MS(ERROR, 10000)
<< "pthread_attr_getstack returned insane stack size " << rawSize;
assert(false);
tls_stackSize = 1;
return;
}
assert(addr != nullptr);
assert(rawSize >= PTHREAD_STACK_MIN);
// glibc subtracts guard page from stack size, even though pthread docs
// seem to imply the opposite
size_t guardSize;
if (pthread_attr_getguardsize(&attr, &guardSize) != 0) {
guardSize = 0;
}
assert(rawSize > guardSize);
// stack goes down, so guard page adds to the base addr
tls_stackLimit = reinterpret_cast<uintptr_t>(addr) + guardSize;
tls_stackSize = rawSize - guardSize;
assert((tls_stackLimit & (pageSize() - 1)) == 0);
}
FOLLY_NOINLINE static uintptr_t getStackPtr() {
char marker;
auto rv = reinterpret_cast<uintptr_t>(&marker);
return rv;
}
void MemoryIdler::unmapUnusedStack(size_t retain) {
if (tls_stackSize == 0) {
fetchStackLimits();
}
if (tls_stackSize <= std::max(static_cast<size_t>(1), retain)) {
// covers both missing stack info, and impossibly large retain
return;
}
auto sp = getStackPtr();
assert(sp >= tls_stackLimit);
assert(sp - tls_stackLimit < tls_stackSize);
auto end = (sp - retain) & ~(pageSize() - 1);
if (end <= tls_stackLimit) {
// no pages are eligible for unmapping
return;
}
size_t len = end - tls_stackLimit;
assert((len & (pageSize() - 1)) == 0);
if (madvise((void*)tls_stackLimit, len, MADV_DONTNEED) != 0) {
// It is likely that the stack vma hasn't been fully grown. In this
// case madvise will apply dontneed to the present vmas, then return
// errno of ENOMEM. We can also get an EAGAIN, theoretically.
// EINVAL means either an invalid alignment or length, or that some
// of the pages are locked or shared. Neither should occur.
assert(errno == EAGAIN || errno == ENOMEM);
}
}
#else
void MemoryIdler::unmapUnusedStack(size_t /* retain */) {}
#endif
} // namespace detail
} // namespace folly
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/portability/Memory.h>
#include <folly/portability/Config.h>
namespace folly {
namespace detail {
#if _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600 || \
(defined(__ANDROID__) && (__ANDROID_API__ > 15)) || \
(defined(__APPLE__) && (__MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_6 || \
__IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_0))
#include <errno.h>
// Use posix_memalign, but mimic the behaviour of memalign
void* aligned_malloc(size_t size, size_t align) {
void* ptr = nullptr;
int rc = posix_memalign(&ptr, align, size);
if (rc == 0) {
return ptr;
}
errno = rc;
return nullptr;
}
void aligned_free(void* aligned_ptr) {
free(aligned_ptr);
}
#elif defined(_WIN32)
#include <malloc.h> // nolint
void* aligned_malloc(size_t size, size_t align) {
return _aligned_malloc(size, align);
}
void aligned_free(void* aligned_ptr) {
_aligned_free(aligned_ptr);
}
#else
#include <malloc.h> // nolint
void* aligned_malloc(size_t size, size_t align) {
return memalign(align, size);
}
void aligned_free(void* aligned_ptr) {
free(aligned_ptr);
}
#endif
}
}
<commit_msg>folly/portability/Memory.cpp: restructure preprocessor conditionals so includes are at top level<commit_after>/*
* Copyright 2017 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/portability/Memory.h>
#include <folly/portability/Config.h>
#include <folly/portability/Malloc.h>
#include <errno.h>
namespace folly {
namespace detail {
#if _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600 || \
(defined(__ANDROID__) && (__ANDROID_API__ > 15)) || \
(defined(__APPLE__) && (__MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_6 || \
__IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_0))
// Use posix_memalign, but mimic the behaviour of memalign
void* aligned_malloc(size_t size, size_t align) {
void* ptr = nullptr;
int rc = posix_memalign(&ptr, align, size);
if (rc == 0) {
return ptr;
}
errno = rc;
return nullptr;
}
void aligned_free(void* aligned_ptr) {
free(aligned_ptr);
}
#elif defined(_WIN32)
void* aligned_malloc(size_t size, size_t align) {
return _aligned_malloc(size, align);
}
void aligned_free(void* aligned_ptr) {
_aligned_free(aligned_ptr);
}
#else
void* aligned_malloc(size_t size, size_t align) {
return memalign(align, size);
}
void aligned_free(void* aligned_ptr) {
free(aligned_ptr);
}
#endif
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// We need to prevent winnt.h from defining the core STATUS codes,
// otherwise they will conflict with what we're getting from ntstatus.h
#define UMDF_USING_NTSTATUS
#include <folly/portability/Unistd.h>
#ifdef _WIN32
#include <cstdio>
#include <fcntl.h>
#include <folly/portability/Sockets.h>
#include <folly/portability/Windows.h>
// Including ntdef.h requires building as a driver, but all we want
// is a status code, but we need NTSTATUS defined for that. Luckily
// bcrypt.h also defines NTSTATUS, so we'll use that one instead.
#include <bcrypt.h>
#include <ntstatus.h>
// Generic wrapper for the p* family of functions.
template <class F, class... Args>
static int wrapPositional(F f, int fd, off_t offset, Args... args) {
off_t origLoc = lseek(fd, 0, SEEK_CUR);
if (origLoc == (off_t)-1) {
return -1;
}
if (lseek(fd, offset, SEEK_SET) == (off_t)-1) {
return -1;
}
int res = (int)f(fd, args...);
int curErrNo = errno;
if (lseek(fd, origLoc, SEEK_SET) == (off_t)-1) {
if (res == -1) {
errno = curErrNo;
}
return -1;
}
errno = curErrNo;
return res;
}
namespace folly {
namespace portability {
namespace unistd {
int access(char const* fn, int am) { return _access(fn, am); }
int chdir(const char* path) { return _chdir(path); }
int close(int fh) {
if (folly::portability::sockets::is_fh_socket(fh)) {
SOCKET h = (SOCKET)_get_osfhandle(fh);
// If we were to just call _close on the descriptor, it would
// close the HANDLE, but it wouldn't free any of the resources
// associated to the SOCKET, and we can't call _close after
// calling closesocket, because closesocket has already closed
// the HANDLE, and _close would attempt to close the HANDLE
// again, resulting in a double free.
// We can however protect the HANDLE from actually being closed
// long enough to close the file descriptor, then close the
// socket itself.
constexpr DWORD protectFlag = HANDLE_FLAG_PROTECT_FROM_CLOSE;
DWORD handleFlags = 0;
if (!GetHandleInformation((HANDLE)h, &handleFlags)) {
return -1;
}
if (!SetHandleInformation((HANDLE)h, protectFlag, protectFlag)) {
return -1;
}
int c = 0;
__try {
// We expect this to fail. It still closes the file descriptor though.
c = _close(fh);
// We just have to catch the SEH exception that gets thrown when we do
// this with a debugger attached -_-....
} __except (
GetExceptionCode() == STATUS_HANDLE_NOT_CLOSABLE
? EXCEPTION_CONTINUE_EXECUTION
: EXCEPTION_CONTINUE_SEARCH) {
// We told it to continue execution, so there's nothing here would
// be run anyways.
}
// We're at the core, we don't get the luxery of SCOPE_EXIT because
// of circular dependencies.
if (!SetHandleInformation((HANDLE)h, protectFlag, handleFlags)) {
return -1;
}
if (c != -1) {
return -1;
}
return closesocket(h);
}
return _close(fh);
}
int dup(int fh) { return _dup(fh); }
int dup2(int fhs, int fhd) { return _dup2(fhs, fhd); }
int fsync(int fd) {
HANDLE h = (HANDLE)_get_osfhandle(fd);
if (h == INVALID_HANDLE_VALUE) {
return -1;
}
if (!FlushFileBuffers(h)) {
return -1;
}
return 0;
}
int ftruncate(int fd, off_t len) {
if (_lseek(fd, len, SEEK_SET) == -1) {
return -1;
}
HANDLE h = (HANDLE)_get_osfhandle(fd);
if (h == INVALID_HANDLE_VALUE) {
return -1;
}
if (!SetEndOfFile(h)) {
return -1;
}
return 0;
}
char* getcwd(char* buf, int sz) { return _getcwd(buf, sz); }
int getdtablesize() { return _getmaxstdio(); }
int getgid() { return 1; }
pid_t getpid() { return (pid_t)uint64_t(GetCurrentProcessId()); }
// No major need to implement this, and getting a non-potentially
// stale ID on windows is a bit involved.
pid_t getppid() { return (pid_t)1; }
int getuid() { return 1; }
int isatty(int fh) { return _isatty(fh); }
int lockf(int fd, int cmd, off_t len) { return _locking(fd, cmd, len); }
off_t lseek(int fh, off_t off, int orig) {
return _lseek(fh, off, orig);
}
int rmdir(const char* path) { return _rmdir(path); }
int pipe(int pth[2]) {
// We need to be able to listen to pipes with
// libevent, so they need to be actual sockets.
return socketpair(PF_UNIX, SOCK_STREAM, 0, pth);
}
ssize_t pread(int fd, void* buf, size_t count, off_t offset) {
return wrapPositional(_read, fd, offset, buf, (unsigned int)count);
}
ssize_t pwrite(int fd, const void* buf, size_t count, off_t offset) {
return wrapPositional(_write, fd, offset, buf, (unsigned int)count);
}
ssize_t read(int fh, void* buf, size_t count) {
if (folly::portability::sockets::is_fh_socket(fh)) {
SOCKET s = (SOCKET)_get_osfhandle(fh);
if (s != INVALID_SOCKET) {
auto r = folly::portability::sockets::recv(fh, buf, count, 0);
if (r == -1 && WSAGetLastError() == WSAEWOULDBLOCK) {
errno = EAGAIN;
}
return r;
}
}
auto r = _read(fh, buf, unsigned int(count));
if (r == -1 && GetLastError() == ERROR_NO_DATA) {
// This only happens if the file was non-blocking and
// no data was present. We have to translate the error
// to a form that the rest of the world is expecting.
errno = EAGAIN;
}
return r;
}
ssize_t readlink(const char* path, char* buf, size_t buflen) {
if (!buflen) {
return -1;
}
HANDLE h = CreateFile(path,
GENERIC_READ,
FILE_SHARE_READ,
nullptr,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
nullptr);
if (h == INVALID_HANDLE_VALUE) {
return -1;
}
DWORD ret =
GetFinalPathNameByHandleA(h, buf, DWORD(buflen - 1), VOLUME_NAME_DOS);
if (ret >= buflen || ret >= MAX_PATH || !ret) {
CloseHandle(h);
return -1;
}
CloseHandle(h);
buf[ret] = '\0';
return ret;
}
void* sbrk(intptr_t /* i */) {
return (void*)-1;
}
unsigned int sleep(unsigned int seconds) {
Sleep((DWORD)(seconds * 1000));
return 0;
}
long sysconf(int tp) {
switch (tp) {
case _SC_PAGESIZE: {
SYSTEM_INFO inf;
GetSystemInfo(&inf);
return (long)inf.dwPageSize;
}
case _SC_NPROCESSORS_ONLN: {
SYSTEM_INFO inf;
GetSystemInfo(&inf);
return (long)inf.dwNumberOfProcessors;
}
default:
return -1L;
}
}
int truncate(const char* path, off_t len) {
int fd = _open(path, O_WRONLY);
if (!fd) {
return -1;
}
if (ftruncate(fd, len)) {
_close(fd);
return -1;
}
return _close(fd) ? -1 : 0;
}
int usleep(unsigned int ms) {
Sleep((DWORD)(ms / 1000));
return 0;
}
ssize_t write(int fh, void const* buf, size_t count) {
if (folly::portability::sockets::is_fh_socket(fh)) {
SOCKET s = (SOCKET)_get_osfhandle(fh);
if (s != INVALID_SOCKET) {
auto r = folly::portability::sockets::send(fh, buf, (size_t)count, 0);
if (r == -1 && WSAGetLastError() == WSAEWOULDBLOCK) {
errno = EAGAIN;
}
return r;
}
}
auto r = _write(fh, buf, unsigned int(count));
if ((r > 0 && size_t(r) != count) || (r == -1 && errno == ENOSPC)) {
// Writing to a pipe with a full buffer doesn't generate
// any error type, unless it caused us to write exactly 0
// bytes, so we have to see if we have a pipe first. We
// don't touch the errno for anything else.
HANDLE h = (HANDLE)_get_osfhandle(fh);
if (GetFileType(h) == FILE_TYPE_PIPE) {
DWORD state = 0;
if (GetNamedPipeHandleState(
h, &state, nullptr, nullptr, nullptr, nullptr, 0)) {
if ((state & PIPE_NOWAIT) == PIPE_NOWAIT) {
errno = EAGAIN;
return -1;
}
}
}
}
return r;
}
}
}
}
#endif
<commit_msg>Explicitly use CreateFileA in readlink<commit_after>/*
* Copyright 2017 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// We need to prevent winnt.h from defining the core STATUS codes,
// otherwise they will conflict with what we're getting from ntstatus.h
#define UMDF_USING_NTSTATUS
#include <folly/portability/Unistd.h>
#ifdef _WIN32
#include <cstdio>
#include <fcntl.h>
#include <folly/portability/Sockets.h>
#include <folly/portability/Windows.h>
// Including ntdef.h requires building as a driver, but all we want
// is a status code, but we need NTSTATUS defined for that. Luckily
// bcrypt.h also defines NTSTATUS, so we'll use that one instead.
#include <bcrypt.h>
#include <ntstatus.h>
// Generic wrapper for the p* family of functions.
template <class F, class... Args>
static int wrapPositional(F f, int fd, off_t offset, Args... args) {
off_t origLoc = lseek(fd, 0, SEEK_CUR);
if (origLoc == (off_t)-1) {
return -1;
}
if (lseek(fd, offset, SEEK_SET) == (off_t)-1) {
return -1;
}
int res = (int)f(fd, args...);
int curErrNo = errno;
if (lseek(fd, origLoc, SEEK_SET) == (off_t)-1) {
if (res == -1) {
errno = curErrNo;
}
return -1;
}
errno = curErrNo;
return res;
}
namespace folly {
namespace portability {
namespace unistd {
int access(char const* fn, int am) { return _access(fn, am); }
int chdir(const char* path) { return _chdir(path); }
int close(int fh) {
if (folly::portability::sockets::is_fh_socket(fh)) {
SOCKET h = (SOCKET)_get_osfhandle(fh);
// If we were to just call _close on the descriptor, it would
// close the HANDLE, but it wouldn't free any of the resources
// associated to the SOCKET, and we can't call _close after
// calling closesocket, because closesocket has already closed
// the HANDLE, and _close would attempt to close the HANDLE
// again, resulting in a double free.
// We can however protect the HANDLE from actually being closed
// long enough to close the file descriptor, then close the
// socket itself.
constexpr DWORD protectFlag = HANDLE_FLAG_PROTECT_FROM_CLOSE;
DWORD handleFlags = 0;
if (!GetHandleInformation((HANDLE)h, &handleFlags)) {
return -1;
}
if (!SetHandleInformation((HANDLE)h, protectFlag, protectFlag)) {
return -1;
}
int c = 0;
__try {
// We expect this to fail. It still closes the file descriptor though.
c = _close(fh);
// We just have to catch the SEH exception that gets thrown when we do
// this with a debugger attached -_-....
} __except (
GetExceptionCode() == STATUS_HANDLE_NOT_CLOSABLE
? EXCEPTION_CONTINUE_EXECUTION
: EXCEPTION_CONTINUE_SEARCH) {
// We told it to continue execution, so there's nothing here would
// be run anyways.
}
// We're at the core, we don't get the luxery of SCOPE_EXIT because
// of circular dependencies.
if (!SetHandleInformation((HANDLE)h, protectFlag, handleFlags)) {
return -1;
}
if (c != -1) {
return -1;
}
return closesocket(h);
}
return _close(fh);
}
int dup(int fh) { return _dup(fh); }
int dup2(int fhs, int fhd) { return _dup2(fhs, fhd); }
int fsync(int fd) {
HANDLE h = (HANDLE)_get_osfhandle(fd);
if (h == INVALID_HANDLE_VALUE) {
return -1;
}
if (!FlushFileBuffers(h)) {
return -1;
}
return 0;
}
int ftruncate(int fd, off_t len) {
if (_lseek(fd, len, SEEK_SET) == -1) {
return -1;
}
HANDLE h = (HANDLE)_get_osfhandle(fd);
if (h == INVALID_HANDLE_VALUE) {
return -1;
}
if (!SetEndOfFile(h)) {
return -1;
}
return 0;
}
char* getcwd(char* buf, int sz) { return _getcwd(buf, sz); }
int getdtablesize() { return _getmaxstdio(); }
int getgid() { return 1; }
pid_t getpid() { return (pid_t)uint64_t(GetCurrentProcessId()); }
// No major need to implement this, and getting a non-potentially
// stale ID on windows is a bit involved.
pid_t getppid() { return (pid_t)1; }
int getuid() { return 1; }
int isatty(int fh) { return _isatty(fh); }
int lockf(int fd, int cmd, off_t len) { return _locking(fd, cmd, len); }
off_t lseek(int fh, off_t off, int orig) {
return _lseek(fh, off, orig);
}
int rmdir(const char* path) { return _rmdir(path); }
int pipe(int pth[2]) {
// We need to be able to listen to pipes with
// libevent, so they need to be actual sockets.
return socketpair(PF_UNIX, SOCK_STREAM, 0, pth);
}
ssize_t pread(int fd, void* buf, size_t count, off_t offset) {
return wrapPositional(_read, fd, offset, buf, (unsigned int)count);
}
ssize_t pwrite(int fd, const void* buf, size_t count, off_t offset) {
return wrapPositional(_write, fd, offset, buf, (unsigned int)count);
}
ssize_t read(int fh, void* buf, size_t count) {
if (folly::portability::sockets::is_fh_socket(fh)) {
SOCKET s = (SOCKET)_get_osfhandle(fh);
if (s != INVALID_SOCKET) {
auto r = folly::portability::sockets::recv(fh, buf, count, 0);
if (r == -1 && WSAGetLastError() == WSAEWOULDBLOCK) {
errno = EAGAIN;
}
return r;
}
}
auto r = _read(fh, buf, unsigned int(count));
if (r == -1 && GetLastError() == ERROR_NO_DATA) {
// This only happens if the file was non-blocking and
// no data was present. We have to translate the error
// to a form that the rest of the world is expecting.
errno = EAGAIN;
}
return r;
}
ssize_t readlink(const char* path, char* buf, size_t buflen) {
if (!buflen) {
return -1;
}
HANDLE h = CreateFileA(
path,
GENERIC_READ,
FILE_SHARE_READ,
nullptr,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
nullptr);
if (h == INVALID_HANDLE_VALUE) {
return -1;
}
DWORD ret =
GetFinalPathNameByHandleA(h, buf, DWORD(buflen - 1), VOLUME_NAME_DOS);
if (ret >= buflen || ret >= MAX_PATH || !ret) {
CloseHandle(h);
return -1;
}
CloseHandle(h);
buf[ret] = '\0';
return ret;
}
void* sbrk(intptr_t /* i */) {
return (void*)-1;
}
unsigned int sleep(unsigned int seconds) {
Sleep((DWORD)(seconds * 1000));
return 0;
}
long sysconf(int tp) {
switch (tp) {
case _SC_PAGESIZE: {
SYSTEM_INFO inf;
GetSystemInfo(&inf);
return (long)inf.dwPageSize;
}
case _SC_NPROCESSORS_ONLN: {
SYSTEM_INFO inf;
GetSystemInfo(&inf);
return (long)inf.dwNumberOfProcessors;
}
default:
return -1L;
}
}
int truncate(const char* path, off_t len) {
int fd = _open(path, O_WRONLY);
if (!fd) {
return -1;
}
if (ftruncate(fd, len)) {
_close(fd);
return -1;
}
return _close(fd) ? -1 : 0;
}
int usleep(unsigned int ms) {
Sleep((DWORD)(ms / 1000));
return 0;
}
ssize_t write(int fh, void const* buf, size_t count) {
if (folly::portability::sockets::is_fh_socket(fh)) {
SOCKET s = (SOCKET)_get_osfhandle(fh);
if (s != INVALID_SOCKET) {
auto r = folly::portability::sockets::send(fh, buf, (size_t)count, 0);
if (r == -1 && WSAGetLastError() == WSAEWOULDBLOCK) {
errno = EAGAIN;
}
return r;
}
}
auto r = _write(fh, buf, unsigned int(count));
if ((r > 0 && size_t(r) != count) || (r == -1 && errno == ENOSPC)) {
// Writing to a pipe with a full buffer doesn't generate
// any error type, unless it caused us to write exactly 0
// bytes, so we have to see if we have a pipe first. We
// don't touch the errno for anything else.
HANDLE h = (HANDLE)_get_osfhandle(fh);
if (GetFileType(h) == FILE_TYPE_PIPE) {
DWORD state = 0;
if (GetNamedPipeHandleState(
h, &state, nullptr, nullptr, nullptr, nullptr, 0)) {
if ((state & PIPE_NOWAIT) == PIPE_NOWAIT) {
errno = EAGAIN;
return -1;
}
}
}
}
return r;
}
}
}
}
#endif
<|endoftext|> |
<commit_before>#pragma once
#include <opencv2/core/core.hpp>
cv::Mat sepia(cv::Mat& image);
cv::Mat tint(cv::Mat& image, int hue, float sat);
int glow(cv::Mat& image);<commit_msg>Add Boost Color implementation<commit_after>#pragma once
#include <opencv2/core/core.hpp>
cv::Mat sepia(cv::Mat& image);
cv::Mat tint(cv::Mat& image, int hue, float sat);
int glow(cv::Mat& image);
int boost_color(cv::Mat& image);
<|endoftext|> |
<commit_before>/******************************************************************************\
This file is part of the C! library. A.K.A the cbang library.
Copyright (c) 2003-2019, Cauldron Development LLC
Copyright (c) 2003-2017, Stanford University
All rights reserved.
The C! 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.
The C! 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 the C! library. If not, see
<http://www.gnu.org/licenses/>.
In addition, BSD licensing may be granted on a case by case basis
by written permission from at least one of the copyright holders.
You may request written permission by emailing the authors.
For information regarding this software email:
Joseph Coffland
joseph@cauldrondevelopment.com
\******************************************************************************/
#include "YAMLReader.h"
#include "Builder.h"
#include "TeeSink.h"
#include "YAMLMergeSink.h"
#include "Dict.h"
#include <cbang/Math.h>
#include <cbang/io/StringInputSource.h>
#include <cbang/util/Regex.h>
#include <cbang/os/SystemUtilities.h>
#include <cbang/log/Logger.h>
#include <yaml.h>
using namespace std;
using namespace cb;
using namespace cb::JSON;
namespace {
int _yaml_read_handler(void *data, unsigned char *buffer, size_t size,
size_t *size_read) {
istream *stream = (istream *)data;
if (stream->eof()) {
*size_read = 0;
return 1;
}
if (stream->fail()) return 0;
stream->read((char *)buffer, size);
*size_read = stream->gcount();
return 1;
}
const char *_yaml_event_type_str(yaml_event_type_t t) {
switch (t) {
case YAML_NO_EVENT: return "NO";
case YAML_STREAM_START_EVENT: return "STREAM_START";
case YAML_STREAM_END_EVENT: return "STREAM_END";
case YAML_DOCUMENT_START_EVENT: return "DOCUMENT_START";
case YAML_DOCUMENT_END_EVENT: return "DOCUMENT_END";
case YAML_ALIAS_EVENT: return "ALIAS";
case YAML_SCALAR_EVENT: return "SCALAR";
case YAML_SEQUENCE_START_EVENT: return "SEQUENCE_START";
case YAML_SEQUENCE_END_EVENT: return "SEQUENCE_END";
case YAML_MAPPING_START_EVENT: return "MAPPING_START";
case YAML_MAPPING_END_EVENT: return "MAPPING_END";
}
return "INVALID";
}
}
class YAMLReader::Private {
public:
yaml_parser_t parser;
Private(istream &stream) {
if (!yaml_parser_initialize(&parser))
THROW("Failed to initialize YAML parser");
yaml_parser_set_input(&parser, _yaml_read_handler, &stream);
}
~Private() {yaml_parser_delete(&parser);}
void parse(yaml_event_t &event) {
if (!yaml_parser_parse(&parser, &event))
PARSE_ERROR("Parser error " << parser.error << ": "
<< parser.problem);
}
};
// See YAML spec: http://yaml.org/spec/1.2/spec.html#id2805071
Regex YAMLReader::nullRE("([Nn]ull)|(NULL)|~|()");
Regex YAMLReader::boolRE("([Tt]rue)|(TRUE)|([Ff]alse)|(FALSE)");
Regex YAMLReader::intRE("([-+]?[0-9]+)|(0o[0-7]+)|(0x[0-9a-fA-F]+)");
Regex YAMLReader::floatRE("[-+]?((\\.[0-9]+)|([0-9]+(\\.[0-9]*)?))"
"([eE][-+]?[0-9]+)?");
Regex YAMLReader::infRE("[-+]?\\.(([Ii]nf)|(INF))");
Regex YAMLReader::nanRE("\\.(([Nn]an)|(NAN))");
YAMLReader::YAMLReader(const InputSource &src) :
src(src), pri(new Private(src.getStream())) {}
void YAMLReader::parse(Sink &sink) {
struct Frame {
yaml_event_type_t event;
string anchor;
Frame(yaml_event_type_t event, const string &anchor = string()) :
event(event), anchor(anchor) {}
};
vector<Frame> stack;
JSON::Dict anchors;
yaml_event_t event;
bool haveKey = false;
SmartPointer<Sink> target = SmartPointer<Sink>::Phony(&sink);
auto close_merge =
[&] () {
if (target.isInstance<YAMLMergeSink>()) {
auto sink = target.cast<YAMLMergeSink>();
if (!sink->getDepth()) {
target = sink->getTarget();
LOG_DEBUG(5, "YAML: merge closed");
}
}
};
auto close_anchor =
[&] () {
if (!stack.back().anchor.empty()) {
auto tee = target.cast<TeeSink>();
auto builder = tee->getRight().cast<Builder>();
anchors.insert(stack.back().anchor, builder->getRoot());
target = tee->getLeft();
LOG_DEBUG(5, "YAML: anchor '" << stack.back().anchor << "' closed");
}
};
while (true) {
pri->parse(event);
LOG_DEBUG(5, "YAML: " << _yaml_event_type_str(event.type));
// Handle anchors & tags
yaml_char_t *_anchor = 0;
yaml_char_t *_tag = 0;
switch (event.type) {
case YAML_SEQUENCE_START_EVENT:
_anchor = event.data.sequence_start.anchor;
_tag = event.data.sequence_start.tag;
break;
case YAML_MAPPING_START_EVENT:
_anchor = event.data.mapping_start.anchor;
_tag = event.data.mapping_start.tag;
break;
case YAML_SCALAR_EVENT:
_anchor = event.data.scalar.anchor;
_tag = event.data.scalar.tag;
break;
default: break;
}
string tag;
if (_tag) {
tag = (const char *)_tag;
LOG_DEBUG(5, "YAML: scalar tag=" << tag);
}
string anchor;
if (_anchor) {
anchor = (const char *)_anchor;
LOG_DEBUG(5, "YAML: anchor=" << anchor);
}
Frame *frame = stack.empty() ? 0 : &stack.back();
// Begin append
if (frame && frame->event == YAML_SEQUENCE_START_EVENT)
switch (event.type) {
case YAML_SEQUENCE_START_EVENT:
case YAML_MAPPING_START_EVENT:
case YAML_SCALAR_EVENT:
case YAML_ALIAS_EVENT:
target->beginAppend();
break;
default: break;
}
// Must be after begin append
if (!anchor.empty()) target = new TeeSink(target, new Builder);
switch (event.type) {
case YAML_NO_EVENT: PARSE_ERROR("YAML No event");
case YAML_STREAM_START_EVENT: yaml_event_delete(&event); continue;
case YAML_STREAM_END_EVENT: yaml_event_delete(&event); return;
case YAML_DOCUMENT_START_EVENT: yaml_event_delete(&event); continue;
case YAML_DOCUMENT_END_EVENT: yaml_event_delete(&event); return;
case YAML_SEQUENCE_START_EVENT:
target->beginList();
stack.push_back(Frame(event.type, anchor));
haveKey = false;
break;
case YAML_SEQUENCE_END_EVENT:
if (!frame || frame->event != YAML_SEQUENCE_START_EVENT)
PARSE_ERROR("Invalid YAML end sequence");
target->endList();
close_anchor();
stack.pop_back();
break;
case YAML_MAPPING_START_EVENT:
target->beginDict();
stack.push_back(Frame(event.type, anchor));
haveKey = false;
break;
case YAML_MAPPING_END_EVENT:
if (!frame || frame->event != YAML_MAPPING_START_EVENT)
PARSE_ERROR("Invalid YAML end mapping");
target->endDict();
close_anchor();
stack.pop_back();
break;
case YAML_ALIAS_EVENT: {
string anchor = (const char *)event.data.alias.anchor;
int i = anchors.indexOf(anchor);
if (i == -1) PARSE_ERROR("Invalid anchor '" << anchor << "'");
anchors.get(i)->write(*target);
haveKey = false;
break;
}
case YAML_SCALAR_EVENT: {
string value = string((const char *)event.data.scalar.value,
event.data.scalar.length);
if (anchors.size() && value.find('%') != string::npos)
value = anchors.format(value);
if (frame && frame->event == YAML_MAPPING_START_EVENT && !haveKey) {
// Handle special merge key but allow it to be quoted
if (value == "<<" && !event.data.scalar.quoted_implicit) {
target = new YAMLMergeSink(target);
LOG_DEBUG(5, "YAML: merge");
haveKey = true;
yaml_event_delete(&event);
continue;
} else {
// Mapping key
if (target->has(value))
PARSE_ERROR("Key '" << value << "' already in mapping");
target->beginInsert(value);
haveKey = true;
yaml_event_delete(&event);
continue;
}
}
if (!tag.empty() && !event.data.scalar.plain_implicit) {
if (tag == YAML_INT_TAG) target->write(String::parseS64(value));
else if (tag == YAML_FLOAT_TAG)
target->write(String::parseDouble(value));
else if (tag == YAML_BOOL_TAG)
target->writeBoolean(String::parseBool(value));
else if (tag == YAML_NULL_TAG) target->writeNull();
else if (tag == "!include") {
string path = SystemUtilities::absolute(src.getName(), value);
LOG_DEBUG(5, "YAML: !include " << path);
YAMLReader reader(path);
reader.parse(*target);
} else target->write(value);
} else {
// Resolve implicit tags
if (event.data.scalar.quoted_implicit) target->write(value);
else if (nullRE.match(value)) target->writeNull();
else if (boolRE.match(value))
target->writeBoolean(String::parseBool(value));
else if (intRE.match(value)) {
if (value[0] == '-') target->write(String::parseS64(value));
else target->write(String::parseU64(value));
} else if (floatRE.match(value))
target->write(String::parseDouble(value));
else if (infRE.match(value)) {
if (value[0] == '-') target->write(-INFINITY);
else target->write(INFINITY);
} else if (nanRE.match(value)) target->write(NAN);
else target->write(value);
}
// Close scaler anchor
if (!anchor.empty()) {
auto tee = target.cast<TeeSink>();
auto builder = tee->getRight().cast<Builder>();
anchors.insert(anchor, builder->getRoot());
target = tee->getLeft();
}
break;
}
}
close_merge();
haveKey = false;
yaml_event_delete(&event);
}
}
ValuePtr YAMLReader::parse() {
Builder builder;
parse(builder);
return builder.getRoot();
}
SmartPointer<Value> YAMLReader::parse(const InputSource &src) {
return YAMLReader(src).parse();
}
SmartPointer<Value> YAMLReader::parseString(const string &s) {
return parse(StringInputSource(s));
}
void YAMLReader::parse(docs_t &docs) {
while (true) {
ValuePtr doc = parse();
if (doc.isNull()) break;
docs.push_back(doc);
}
}
void YAMLReader::parse(const InputSource &src, docs_t &docs) {
YAMLReader(src).parse(docs);
}
void YAMLReader::parseString(const string &s, docs_t &docs) {
parse(StringInputSource(s), docs);
}
<commit_msg>Added YAML include-raw tag<commit_after>/******************************************************************************\
This file is part of the C! library. A.K.A the cbang library.
Copyright (c) 2003-2019, Cauldron Development LLC
Copyright (c) 2003-2017, Stanford University
All rights reserved.
The C! 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.
The C! 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 the C! library. If not, see
<http://www.gnu.org/licenses/>.
In addition, BSD licensing may be granted on a case by case basis
by written permission from at least one of the copyright holders.
You may request written permission by emailing the authors.
For information regarding this software email:
Joseph Coffland
joseph@cauldrondevelopment.com
\******************************************************************************/
#include "YAMLReader.h"
#include "Builder.h"
#include "TeeSink.h"
#include "YAMLMergeSink.h"
#include "Dict.h"
#include <cbang/Math.h>
#include <cbang/io/StringInputSource.h>
#include <cbang/util/Regex.h>
#include <cbang/os/SystemUtilities.h>
#include <cbang/log/Logger.h>
#include <yaml.h>
using namespace std;
using namespace cb;
using namespace cb::JSON;
namespace {
int _yaml_read_handler(void *data, unsigned char *buffer, size_t size,
size_t *size_read) {
istream *stream = (istream *)data;
if (stream->eof()) {
*size_read = 0;
return 1;
}
if (stream->fail()) return 0;
stream->read((char *)buffer, size);
*size_read = stream->gcount();
return 1;
}
const char *_yaml_event_type_str(yaml_event_type_t t) {
switch (t) {
case YAML_NO_EVENT: return "NO";
case YAML_STREAM_START_EVENT: return "STREAM_START";
case YAML_STREAM_END_EVENT: return "STREAM_END";
case YAML_DOCUMENT_START_EVENT: return "DOCUMENT_START";
case YAML_DOCUMENT_END_EVENT: return "DOCUMENT_END";
case YAML_ALIAS_EVENT: return "ALIAS";
case YAML_SCALAR_EVENT: return "SCALAR";
case YAML_SEQUENCE_START_EVENT: return "SEQUENCE_START";
case YAML_SEQUENCE_END_EVENT: return "SEQUENCE_END";
case YAML_MAPPING_START_EVENT: return "MAPPING_START";
case YAML_MAPPING_END_EVENT: return "MAPPING_END";
}
return "INVALID";
}
}
class YAMLReader::Private {
public:
yaml_parser_t parser;
Private(istream &stream) {
if (!yaml_parser_initialize(&parser))
THROW("Failed to initialize YAML parser");
yaml_parser_set_input(&parser, _yaml_read_handler, &stream);
}
~Private() {yaml_parser_delete(&parser);}
void parse(yaml_event_t &event) {
if (!yaml_parser_parse(&parser, &event))
PARSE_ERROR("Parser error " << parser.error << ": "
<< parser.problem);
}
};
// See YAML spec: http://yaml.org/spec/1.2/spec.html#id2805071
Regex YAMLReader::nullRE("([Nn]ull)|(NULL)|~|()");
Regex YAMLReader::boolRE("([Tt]rue)|(TRUE)|([Ff]alse)|(FALSE)");
Regex YAMLReader::intRE("([-+]?[0-9]+)|(0o[0-7]+)|(0x[0-9a-fA-F]+)");
Regex YAMLReader::floatRE("[-+]?((\\.[0-9]+)|([0-9]+(\\.[0-9]*)?))"
"([eE][-+]?[0-9]+)?");
Regex YAMLReader::infRE("[-+]?\\.(([Ii]nf)|(INF))");
Regex YAMLReader::nanRE("\\.(([Nn]an)|(NAN))");
YAMLReader::YAMLReader(const InputSource &src) :
src(src), pri(new Private(src.getStream())) {}
void YAMLReader::parse(Sink &sink) {
struct Frame {
yaml_event_type_t event;
string anchor;
Frame(yaml_event_type_t event, const string &anchor = string()) :
event(event), anchor(anchor) {}
};
vector<Frame> stack;
JSON::Dict anchors;
yaml_event_t event;
bool haveKey = false;
SmartPointer<Sink> target = SmartPointer<Sink>::Phony(&sink);
auto close_merge =
[&] () {
if (target.isInstance<YAMLMergeSink>()) {
auto sink = target.cast<YAMLMergeSink>();
if (!sink->getDepth()) {
target = sink->getTarget();
LOG_DEBUG(5, "YAML: merge closed");
}
}
};
auto close_anchor =
[&] () {
if (!stack.back().anchor.empty()) {
auto tee = target.cast<TeeSink>();
auto builder = tee->getRight().cast<Builder>();
anchors.insert(stack.back().anchor, builder->getRoot());
target = tee->getLeft();
LOG_DEBUG(5, "YAML: anchor '" << stack.back().anchor << "' closed");
}
};
while (true) {
pri->parse(event);
LOG_DEBUG(5, "YAML: " << _yaml_event_type_str(event.type));
// Handle anchors & tags
yaml_char_t *_anchor = 0;
yaml_char_t *_tag = 0;
switch (event.type) {
case YAML_SEQUENCE_START_EVENT:
_anchor = event.data.sequence_start.anchor;
_tag = event.data.sequence_start.tag;
break;
case YAML_MAPPING_START_EVENT:
_anchor = event.data.mapping_start.anchor;
_tag = event.data.mapping_start.tag;
break;
case YAML_SCALAR_EVENT:
_anchor = event.data.scalar.anchor;
_tag = event.data.scalar.tag;
break;
default: break;
}
string tag;
if (_tag) {
tag = (const char *)_tag;
LOG_DEBUG(5, "YAML: scalar tag=" << tag);
}
string anchor;
if (_anchor) {
anchor = (const char *)_anchor;
LOG_DEBUG(5, "YAML: anchor=" << anchor);
}
Frame *frame = stack.empty() ? 0 : &stack.back();
// Begin append
if (frame && frame->event == YAML_SEQUENCE_START_EVENT)
switch (event.type) {
case YAML_SEQUENCE_START_EVENT:
case YAML_MAPPING_START_EVENT:
case YAML_SCALAR_EVENT:
case YAML_ALIAS_EVENT:
target->beginAppend();
break;
default: break;
}
// Must be after begin append
if (!anchor.empty()) target = new TeeSink(target, new Builder);
switch (event.type) {
case YAML_NO_EVENT: PARSE_ERROR("YAML No event");
case YAML_STREAM_START_EVENT: yaml_event_delete(&event); continue;
case YAML_STREAM_END_EVENT: yaml_event_delete(&event); return;
case YAML_DOCUMENT_START_EVENT: yaml_event_delete(&event); continue;
case YAML_DOCUMENT_END_EVENT: yaml_event_delete(&event); return;
case YAML_SEQUENCE_START_EVENT:
target->beginList();
stack.push_back(Frame(event.type, anchor));
haveKey = false;
break;
case YAML_SEQUENCE_END_EVENT:
if (!frame || frame->event != YAML_SEQUENCE_START_EVENT)
PARSE_ERROR("Invalid YAML end sequence");
target->endList();
close_anchor();
stack.pop_back();
break;
case YAML_MAPPING_START_EVENT:
target->beginDict();
stack.push_back(Frame(event.type, anchor));
haveKey = false;
break;
case YAML_MAPPING_END_EVENT:
if (!frame || frame->event != YAML_MAPPING_START_EVENT)
PARSE_ERROR("Invalid YAML end mapping");
target->endDict();
close_anchor();
stack.pop_back();
break;
case YAML_ALIAS_EVENT: {
string anchor = (const char *)event.data.alias.anchor;
int i = anchors.indexOf(anchor);
if (i == -1) PARSE_ERROR("Invalid anchor '" << anchor << "'");
anchors.get(i)->write(*target);
haveKey = false;
break;
}
case YAML_SCALAR_EVENT: {
string value = string((const char *)event.data.scalar.value,
event.data.scalar.length);
if (anchors.size() && value.find('%') != string::npos)
value = anchors.format(value);
if (frame && frame->event == YAML_MAPPING_START_EVENT && !haveKey) {
// Handle special merge key but allow it to be quoted
if (value == "<<" && !event.data.scalar.quoted_implicit) {
target = new YAMLMergeSink(target);
LOG_DEBUG(5, "YAML: merge");
haveKey = true;
yaml_event_delete(&event);
continue;
} else {
// Mapping key
if (target->has(value))
PARSE_ERROR("Key '" << value << "' already in mapping");
target->beginInsert(value);
haveKey = true;
yaml_event_delete(&event);
continue;
}
}
if (!tag.empty() && !event.data.scalar.plain_implicit) {
if (tag == YAML_INT_TAG) target->write(String::parseS64(value));
else if (tag == YAML_FLOAT_TAG)
target->write(String::parseDouble(value));
else if (tag == YAML_BOOL_TAG)
target->writeBoolean(String::parseBool(value));
else if (tag == YAML_NULL_TAG) target->writeNull();
else if (tag == "!include-raw") {
string path = SystemUtilities::absolute(src.getName(), value);
LOG_DEBUG(5, "YAML: !include-raw " << path);
target->write(SystemUtilities::read(path));
} else if (tag == "!include") {
string path = SystemUtilities::absolute(src.getName(), value);
LOG_DEBUG(5, "YAML: !include " << path);
YAMLReader reader(path);
reader.parse(*target);
} else target->write(value);
} else {
// Resolve implicit tags
if (event.data.scalar.quoted_implicit) target->write(value);
else if (nullRE.match(value)) target->writeNull();
else if (boolRE.match(value))
target->writeBoolean(String::parseBool(value));
else if (intRE.match(value)) {
if (value[0] == '-') target->write(String::parseS64(value));
else target->write(String::parseU64(value));
} else if (floatRE.match(value))
target->write(String::parseDouble(value));
else if (infRE.match(value)) {
if (value[0] == '-') target->write(-INFINITY);
else target->write(INFINITY);
} else if (nanRE.match(value)) target->write(NAN);
else target->write(value);
}
// Close scaler anchor
if (!anchor.empty()) {
auto tee = target.cast<TeeSink>();
auto builder = tee->getRight().cast<Builder>();
anchors.insert(anchor, builder->getRoot());
target = tee->getLeft();
}
break;
}
}
close_merge();
haveKey = false;
yaml_event_delete(&event);
}
}
ValuePtr YAMLReader::parse() {
Builder builder;
parse(builder);
return builder.getRoot();
}
SmartPointer<Value> YAMLReader::parse(const InputSource &src) {
return YAMLReader(src).parse();
}
SmartPointer<Value> YAMLReader::parseString(const string &s) {
return parse(StringInputSource(s));
}
void YAMLReader::parse(docs_t &docs) {
while (true) {
ValuePtr doc = parse();
if (doc.isNull()) break;
docs.push_back(doc);
}
}
void YAMLReader::parse(const InputSource &src, docs_t &docs) {
YAMLReader(src).parse(docs);
}
void YAMLReader::parseString(const string &s, docs_t &docs) {
parse(StringInputSource(s), docs);
}
<|endoftext|> |
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2006/03/14
// Author: Sriram Rao
//
// Copyright 2008 Quantcast Corp.
// Copyright 2006-2008 Kosmix Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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 <sys/poll.h>
#include <cerrno>
#include <boost/scoped_array.hpp>
#include "NetManager.h"
#include "TcpSocket.h"
#include "Globals.h"
#include "common/log.h"
using std::mem_fun;
using std::list;
using namespace KFS;
using namespace KFS::libkfsio;
NetManager::NetManager() : mDiskOverloaded(false), mNetworkOverloaded(false), mMaxOutgoingBacklog(0)
{
pthread_mutexattr_t mutexAttr;
int rval;
rval = pthread_mutexattr_init(&mutexAttr);
assert(rval == 0);
rval = pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE);
assert(rval == 0);
mSelectTimeout.tv_sec = 10;
mSelectTimeout.tv_usec = 0;
}
NetManager::NetManager(const struct timeval &selectTimeout) :
mDiskOverloaded(false), mNetworkOverloaded(false), mMaxOutgoingBacklog(0)
{
mSelectTimeout.tv_sec = selectTimeout.tv_sec;
mSelectTimeout.tv_usec = selectTimeout.tv_usec;
}
NetManager::~NetManager()
{
NetConnectionListIter_t iter;
NetConnectionPtr conn;
mTimeoutHandlers.clear();
mConnections.clear();
}
void
NetManager::AddConnection(NetConnectionPtr &conn)
{
mConnections.push_back(conn);
}
void
NetManager::RegisterTimeoutHandler(ITimeout *handler)
{
mTimeoutHandlers.push_back(handler);
}
void
NetManager::UnRegisterTimeoutHandler(ITimeout *handler)
{
list<ITimeout *>::iterator iter;
ITimeout *tm;
if (handler == NULL)
return;
for (iter = mTimeoutHandlers.begin(); iter != mTimeoutHandlers.end();
++iter) {
tm = *iter;
if (tm == handler) {
mUnregisteredTimeoutHandlers.push_back(tm);
return;
}
}
KFS_LOG_VA_WARN("Unable to find registered handler for %x", handler);
}
void
NetManager::RemoveUnregisteredTimeoutHandlers()
{
list<ITimeout *>::iterator iter1, iter2;
ITimeout *i1, *i2;
for (iter1 = mUnregisteredTimeoutHandlers.begin(); iter1 != mUnregisteredTimeoutHandlers.end(); ++iter1) {
for (iter2 = mTimeoutHandlers.begin(); iter2 != mTimeoutHandlers.end(); ++iter2) {
i1 = *iter1;
i2 = *iter2;
if (i1 == i2) {
mTimeoutHandlers.erase(iter2);
break;
}
}
}
mUnregisteredTimeoutHandlers.clear();
}
void
NetManager::MainLoop()
{
boost::scoped_array<struct pollfd> pollfds;
uint32_t pollFdSize = 1024;
int numPollFds, fd, res;
NetConnectionPtr conn;
NetConnectionListIter_t iter, eltToRemove;
int pollTimeoutMs;
// if we have too many bytes to send, throttle incoming
int64_t totalNumBytesToSend = 0;
bool overloaded = false;
pollfds.reset(new struct pollfd[pollFdSize]);
while (1) {
if (mConnections.size() > pollFdSize) {
pollFdSize = mConnections.size();
pollfds.reset(new struct pollfd[pollFdSize]);
}
// build poll vector:
// make sure we are listening to the net kicker
fd = globals().netKicker.GetFd();
pollfds[0].fd = fd;
pollfds[0].events = POLLIN;
pollfds[0].revents = 0;
numPollFds = 1;
overloaded = IsOverloaded(totalNumBytesToSend);
int numBytesToSend;
totalNumBytesToSend = 0;
for (iter = mConnections.begin(); iter != mConnections.end(); ++iter) {
conn = *iter;
fd = conn->GetFd();
if (fd < 0) {
// we'll get rid of this connection in the while loop below
conn->mPollVectorIndex = -2;
continue;
}
if (fd == globals().netKicker.GetFd()) {
conn->mPollVectorIndex = -1;
continue;
}
conn->mPollVectorIndex = numPollFds;
pollfds[numPollFds].fd = fd;
pollfds[numPollFds].events = 0;
pollfds[numPollFds].revents = 0;
if (conn->IsReadReady(overloaded)) {
// By default, each connection is read ready. We
// expect there to be 2-way data transmission, and so
// we are read ready. In overloaded state, we only
// add the fd to the poll vector if the fd is given a
// special pass
pollfds[numPollFds].events |= POLLIN;
}
numBytesToSend = conn->GetNumBytesToWrite();
if (numBytesToSend > 0) {
totalNumBytesToSend += numBytesToSend;
// An optimization: if we are not sending any data for
// this fd in this round of poll, don't bother adding
// it to the poll vector.
pollfds[numPollFds].events |= POLLOUT;
}
numPollFds++;
}
if (!overloaded) {
overloaded = IsOverloaded(totalNumBytesToSend);
if (overloaded)
continue;
}
struct timeval startTime, endTime;
gettimeofday(&startTime, NULL);
pollTimeoutMs = mSelectTimeout.tv_sec * 1000;
res = poll(pollfds.get(), numPollFds, pollTimeoutMs);
if ((res < 0) && (errno != EINTR)) {
perror("poll(): ");
continue;
}
gettimeofday(&endTime, NULL);
// list of timeout handlers...call them back
fd = globals().netKicker.GetFd();
if (pollfds[0].revents & POLLIN) {
globals().netKicker.Drain();
globals().diskManager.ReapCompletedIOs();
}
RemoveUnregisteredTimeoutHandlers();
//
// This call can cause a handler to unregister itself. Doing
// that while we are iterating thru this list is fatal.
// Hence, when a handler unregisters itself, we put that
// handler into a separate list. After we called all the
// handlers, we cleanout the unregistered handlers.
//
for_each (mTimeoutHandlers.begin(), mTimeoutHandlers.end(),
mem_fun(&ITimeout::TimerExpired));
RemoveUnregisteredTimeoutHandlers();
iter = mConnections.begin();
while (iter != mConnections.end()) {
conn = *iter;
// Something happened and the connection has closed. So,
// remove the connection from our list.
if (conn->GetFd() < 0) {
eltToRemove = iter;
++iter;
mConnections.erase(eltToRemove);
continue;
}
if ((conn->GetFd() == globals().netKicker.GetFd()) ||
(conn->mPollVectorIndex < 0)) {
++iter;
continue;
}
if (pollfds[conn->mPollVectorIndex].revents & POLLIN) {
fd = conn->GetFd();
if (fd > 0) {
conn->HandleReadEvent(overloaded);
}
}
// conn could have closed due to errors during read. so,
// need to re-get the fd and check that all is good
if (pollfds[conn->mPollVectorIndex].revents & POLLOUT) {
fd = conn->GetFd();
if (fd > 0) {
conn->HandleWriteEvent();
}
}
if ((pollfds[conn->mPollVectorIndex].revents & POLLERR) ||
(pollfds[conn->mPollVectorIndex].revents & POLLHUP)) {
fd = conn->GetFd();
if (fd > 0) {
conn->HandleErrorEvent();
}
}
++iter;
}
}
}
bool
NetManager::IsOverloaded(int64_t numBytesToSend)
{
static bool wasOverloaded = false;
if (mMaxOutgoingBacklog > 0) {
if (!mNetworkOverloaded) {
mNetworkOverloaded = (numBytesToSend > mMaxOutgoingBacklog);
} else if (numBytesToSend <= mMaxOutgoingBacklog / 2) {
// network was overloaded and that has now cleared
mNetworkOverloaded = false;
}
}
bool isOverloaded = mDiskOverloaded || mNetworkOverloaded;
if (!wasOverloaded && isOverloaded) {
KFS_LOG_VA_INFO("System is now in overloaded state (%ld bytes to send; %d disk IO's) ",
numBytesToSend, globals().diskManager.NumDiskIOOutstanding());
} else if (wasOverloaded && !isOverloaded) {
KFS_LOG_VA_INFO("Clearing system overload state (%ld bytes to send; %d disk IO's)",
numBytesToSend, globals().diskManager.NumDiskIOOutstanding());
}
wasOverloaded = isOverloaded;
return isOverloaded;
}
void
NetManager::ChangeDiskOverloadState(bool v)
{
if (mDiskOverloaded == v)
return;
mDiskOverloaded = v;
}
<commit_msg> -- Took out a debug message when unregistering a timeout handler. The problem is that log4cpp may get unloaded prematurely during an exit() call and this can cause random crashes.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2006/03/14
// Author: Sriram Rao
//
// Copyright 2008 Quantcast Corp.
// Copyright 2006-2008 Kosmix Corp.
//
// This file is part of Kosmos File System (KFS).
//
// 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 <sys/poll.h>
#include <cerrno>
#include <boost/scoped_array.hpp>
#include "NetManager.h"
#include "TcpSocket.h"
#include "Globals.h"
#include "common/log.h"
using std::mem_fun;
using std::list;
using namespace KFS;
using namespace KFS::libkfsio;
NetManager::NetManager() : mDiskOverloaded(false), mNetworkOverloaded(false), mMaxOutgoingBacklog(0)
{
pthread_mutexattr_t mutexAttr;
int rval;
rval = pthread_mutexattr_init(&mutexAttr);
assert(rval == 0);
rval = pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE);
assert(rval == 0);
mSelectTimeout.tv_sec = 10;
mSelectTimeout.tv_usec = 0;
}
NetManager::NetManager(const struct timeval &selectTimeout) :
mDiskOverloaded(false), mNetworkOverloaded(false), mMaxOutgoingBacklog(0)
{
mSelectTimeout.tv_sec = selectTimeout.tv_sec;
mSelectTimeout.tv_usec = selectTimeout.tv_usec;
}
NetManager::~NetManager()
{
NetConnectionListIter_t iter;
NetConnectionPtr conn;
mTimeoutHandlers.clear();
mConnections.clear();
}
void
NetManager::AddConnection(NetConnectionPtr &conn)
{
mConnections.push_back(conn);
}
void
NetManager::RegisterTimeoutHandler(ITimeout *handler)
{
mTimeoutHandlers.push_back(handler);
}
void
NetManager::UnRegisterTimeoutHandler(ITimeout *handler)
{
list<ITimeout *>::iterator iter;
ITimeout *tm;
if (handler == NULL)
return;
for (iter = mTimeoutHandlers.begin(); iter != mTimeoutHandlers.end();
++iter) {
tm = *iter;
if (tm == handler) {
mUnregisteredTimeoutHandlers.push_back(tm);
return;
}
}
}
void
NetManager::RemoveUnregisteredTimeoutHandlers()
{
list<ITimeout *>::iterator iter1, iter2;
ITimeout *i1, *i2;
for (iter1 = mUnregisteredTimeoutHandlers.begin(); iter1 != mUnregisteredTimeoutHandlers.end(); ++iter1) {
for (iter2 = mTimeoutHandlers.begin(); iter2 != mTimeoutHandlers.end(); ++iter2) {
i1 = *iter1;
i2 = *iter2;
if (i1 == i2) {
mTimeoutHandlers.erase(iter2);
break;
}
}
}
mUnregisteredTimeoutHandlers.clear();
}
void
NetManager::MainLoop()
{
boost::scoped_array<struct pollfd> pollfds;
uint32_t pollFdSize = 1024;
int numPollFds, fd, res;
NetConnectionPtr conn;
NetConnectionListIter_t iter, eltToRemove;
int pollTimeoutMs;
// if we have too many bytes to send, throttle incoming
int64_t totalNumBytesToSend = 0;
bool overloaded = false;
pollfds.reset(new struct pollfd[pollFdSize]);
while (1) {
if (mConnections.size() > pollFdSize) {
pollFdSize = mConnections.size();
pollfds.reset(new struct pollfd[pollFdSize]);
}
// build poll vector:
// make sure we are listening to the net kicker
fd = globals().netKicker.GetFd();
pollfds[0].fd = fd;
pollfds[0].events = POLLIN;
pollfds[0].revents = 0;
numPollFds = 1;
overloaded = IsOverloaded(totalNumBytesToSend);
int numBytesToSend;
totalNumBytesToSend = 0;
for (iter = mConnections.begin(); iter != mConnections.end(); ++iter) {
conn = *iter;
fd = conn->GetFd();
if (fd < 0) {
// we'll get rid of this connection in the while loop below
conn->mPollVectorIndex = -2;
continue;
}
if (fd == globals().netKicker.GetFd()) {
conn->mPollVectorIndex = -1;
continue;
}
conn->mPollVectorIndex = numPollFds;
pollfds[numPollFds].fd = fd;
pollfds[numPollFds].events = 0;
pollfds[numPollFds].revents = 0;
if (conn->IsReadReady(overloaded)) {
// By default, each connection is read ready. We
// expect there to be 2-way data transmission, and so
// we are read ready. In overloaded state, we only
// add the fd to the poll vector if the fd is given a
// special pass
pollfds[numPollFds].events |= POLLIN;
}
numBytesToSend = conn->GetNumBytesToWrite();
if (numBytesToSend > 0) {
totalNumBytesToSend += numBytesToSend;
// An optimization: if we are not sending any data for
// this fd in this round of poll, don't bother adding
// it to the poll vector.
pollfds[numPollFds].events |= POLLOUT;
}
numPollFds++;
}
if (!overloaded) {
overloaded = IsOverloaded(totalNumBytesToSend);
if (overloaded)
continue;
}
struct timeval startTime, endTime;
gettimeofday(&startTime, NULL);
pollTimeoutMs = mSelectTimeout.tv_sec * 1000;
res = poll(pollfds.get(), numPollFds, pollTimeoutMs);
if ((res < 0) && (errno != EINTR)) {
perror("poll(): ");
continue;
}
gettimeofday(&endTime, NULL);
// list of timeout handlers...call them back
fd = globals().netKicker.GetFd();
if (pollfds[0].revents & POLLIN) {
globals().netKicker.Drain();
globals().diskManager.ReapCompletedIOs();
}
RemoveUnregisteredTimeoutHandlers();
//
// This call can cause a handler to unregister itself. Doing
// that while we are iterating thru this list is fatal.
// Hence, when a handler unregisters itself, we put that
// handler into a separate list. After we called all the
// handlers, we cleanout the unregistered handlers.
//
for_each (mTimeoutHandlers.begin(), mTimeoutHandlers.end(),
mem_fun(&ITimeout::TimerExpired));
RemoveUnregisteredTimeoutHandlers();
iter = mConnections.begin();
while (iter != mConnections.end()) {
conn = *iter;
// Something happened and the connection has closed. So,
// remove the connection from our list.
if (conn->GetFd() < 0) {
eltToRemove = iter;
++iter;
mConnections.erase(eltToRemove);
continue;
}
if ((conn->GetFd() == globals().netKicker.GetFd()) ||
(conn->mPollVectorIndex < 0)) {
++iter;
continue;
}
if (pollfds[conn->mPollVectorIndex].revents & POLLIN) {
fd = conn->GetFd();
if (fd > 0) {
conn->HandleReadEvent(overloaded);
}
}
// conn could have closed due to errors during read. so,
// need to re-get the fd and check that all is good
if (pollfds[conn->mPollVectorIndex].revents & POLLOUT) {
fd = conn->GetFd();
if (fd > 0) {
conn->HandleWriteEvent();
}
}
if ((pollfds[conn->mPollVectorIndex].revents & POLLERR) ||
(pollfds[conn->mPollVectorIndex].revents & POLLHUP)) {
fd = conn->GetFd();
if (fd > 0) {
conn->HandleErrorEvent();
}
}
++iter;
}
}
}
bool
NetManager::IsOverloaded(int64_t numBytesToSend)
{
static bool wasOverloaded = false;
if (mMaxOutgoingBacklog > 0) {
if (!mNetworkOverloaded) {
mNetworkOverloaded = (numBytesToSend > mMaxOutgoingBacklog);
} else if (numBytesToSend <= mMaxOutgoingBacklog / 2) {
// network was overloaded and that has now cleared
mNetworkOverloaded = false;
}
}
bool isOverloaded = mDiskOverloaded || mNetworkOverloaded;
if (!wasOverloaded && isOverloaded) {
KFS_LOG_VA_INFO("System is now in overloaded state (%ld bytes to send; %d disk IO's) ",
numBytesToSend, globals().diskManager.NumDiskIOOutstanding());
} else if (wasOverloaded && !isOverloaded) {
KFS_LOG_VA_INFO("Clearing system overload state (%ld bytes to send; %d disk IO's)",
numBytesToSend, globals().diskManager.NumDiskIOOutstanding());
}
wasOverloaded = isOverloaded;
return isOverloaded;
}
void
NetManager::ChangeDiskOverloadState(bool v)
{
if (mDiskOverloaded == v)
return;
mDiskOverloaded = v;
}
<|endoftext|> |
<commit_before>/*
* GfxSaveSurface.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 03.12.09.
* code under LGPL
*
*/
#include <SDL.h>
#include "GfxPrimitives.h"
#include "Options.h"
#include "FindFile.h"
#ifndef DEDICATED_ONLY
#include <gd.h>
#endif
#ifndef DEDICATED_ONLY
///////////////////////
// Converts the SDL_surface to gdImagePtr
static gdImagePtr SDLSurface2GDImage(SDL_Surface* src) {
if(src->format->BitsPerPixel == 8) {
gdImagePtr gd_image = gdImageCreatePalette(src->w, src->h);
if(!gd_image) return NULL;
LockSurface(src);
for(int y = 0; y < src->h; ++y) {
for(int x = 0; x < src->w; ++x)
gd_image->pixels[y][x] = GetPixel(src, x, y);
}
UnlockSurface(src);
return gd_image;
}
gdImagePtr gd_image = gdImageCreateTrueColor(src->w,src->h);
if(!gd_image)
return NULL;
Uint32 rmask, gmask, bmask;
// format of gdImage
rmask=0x00FF0000; gmask=0x0000FF00; bmask=0x000000FF;
SmartPointer<SDL_Surface> formated = SDL_CreateRGBSurface(SDL_SWSURFACE, src->w, src->h, 32, rmask, gmask, bmask, 0);
if(!formated.get())
return NULL;
#ifdef DEBUG
//printf("SDLSurface2GDImage() %p\n", formated.get() );
#endif
// convert it to the new format (32 bpp)
CopySurface(formated.get(), src, 0, 0, 0, 0, src->w, src->h);
if (!LockSurface(formated))
return NULL;
for(int y = 0; y < src->h; y++) {
memcpy(gd_image->tpixels[y], (uchar*)formated.get()->pixels + y*formated.get()->pitch, formated.get()->pitch);
}
UnlockSurface(formated);
return gd_image;
}
#endif //DEDICATED_ONLY
///////////////////////
// Saves the surface into the specified file with the specified format
bool SaveSurface(SDL_Surface * image, const std::string& FileName, int Format, const std::string& Data)
{
//
// BMP
//
// We use standard SDL function for saving BMPs
if (Format == FMT_BMP) {
// Save the image
std::string abs_fn = GetWriteFullFileName (FileName, true); // SDL requires full paths
SDL_SaveBMP(image, abs_fn.c_str());
// Append any additional data
if (!Data.empty()) {
FILE *f = OpenGameFile (FileName, "ab");
if (!f)
return false;
fwrite(Data.data(), 1, Data.size(), f);
fclose (f);
}
return true;
}
#ifdef DEDICATED_ONLY
warnings << "SaveSurface: cannot use something else than BMP in dedicated-only-mode" << endl;
return false;
#else
//
// JPG, PNG, GIF
//
// We use GD for saving these formats
gdImagePtr gd_image = NULL;
// Convert the surface
gd_image = SDLSurface2GDImage ( image );
if ( !gd_image )
return false;
// Save the image
int s;
char *data = NULL;
FILE *out = OpenGameFile (FileName, "wb");
if ( !out )
return false;
// Get the data depending on the format
switch (Format)
{
case FMT_PNG:
data = ( char * ) gdImagePngPtr ( gd_image, &s );
break;
case FMT_JPG:
data = ( char * ) gdImageJpegPtr ( gd_image, &s,tLXOptions->iJpegQuality );
break;
case FMT_GIF:
data = ( char * ) gdImageGifPtr ( gd_image, &s );
break;
default:
data = ( char * ) gdImagePngPtr ( gd_image, &s );
break;
}
// Check
if (!data)
return false;
// Size of the data
size_t size = s > 0 ? s : -s;
// Write the image data
if (fwrite(data, 1, size, out) != size)
return false;
// Write any additional data
if (!Data.empty())
fwrite(Data.data(), 1, Data.size(), out);
// Free everything
gdFree ( data );
gdImageDestroy ( gd_image );
// Close the file and quit
return fclose(out) == 0;
#endif // !DEDICATED_ONLY
}
<commit_msg>small fix<commit_after>/*
* GfxSaveSurface.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 03.12.09.
* code under LGPL
*
*/
#include <SDL.h>
#include "GfxPrimitives.h"
#include "Options.h"
#include "FindFile.h"
#ifndef DEDICATED_ONLY
#include <gd.h>
#endif
#ifndef DEDICATED_ONLY
///////////////////////
// Converts the SDL_surface to gdImagePtr
static gdImagePtr SDLSurface2GDImage(SDL_Surface* src) {
if(src->format->BitsPerPixel == 8) {
gdImagePtr gd_image = gdImageCreatePalette(src->w, src->h);
if(!gd_image) return NULL;
// we must allocate 255 colors in the palette so that it becomes an 8bit gdImage
for(int i = 0; i < 255; ++i)
gdImageColorAllocate(gd_image, i, i, i);
LockSurface(src);
for(int y = 0; y < src->h; ++y) {
for(int x = 0; x < src->w; ++x)
gd_image->pixels[y][x] = GetPixel(src, x, y);
}
UnlockSurface(src);
return gd_image;
}
gdImagePtr gd_image = gdImageCreateTrueColor(src->w,src->h);
if(!gd_image)
return NULL;
Uint32 rmask, gmask, bmask;
// format of gdImage
rmask=0x00FF0000; gmask=0x0000FF00; bmask=0x000000FF;
SmartPointer<SDL_Surface> formated = SDL_CreateRGBSurface(SDL_SWSURFACE, src->w, src->h, 32, rmask, gmask, bmask, 0);
if(!formated.get())
return NULL;
#ifdef DEBUG
//printf("SDLSurface2GDImage() %p\n", formated.get() );
#endif
// convert it to the new format (32 bpp)
CopySurface(formated.get(), src, 0, 0, 0, 0, src->w, src->h);
if (!LockSurface(formated))
return NULL;
for(int y = 0; y < src->h; y++) {
memcpy(gd_image->tpixels[y], (uchar*)formated.get()->pixels + y*formated.get()->pitch, formated.get()->pitch);
}
UnlockSurface(formated);
return gd_image;
}
#endif //DEDICATED_ONLY
///////////////////////
// Saves the surface into the specified file with the specified format
bool SaveSurface(SDL_Surface * image, const std::string& FileName, int Format, const std::string& Data)
{
//
// BMP
//
// We use standard SDL function for saving BMPs
if (Format == FMT_BMP) {
// Save the image
std::string abs_fn = GetWriteFullFileName (FileName, true); // SDL requires full paths
SDL_SaveBMP(image, abs_fn.c_str());
// Append any additional data
if (!Data.empty()) {
FILE *f = OpenGameFile (FileName, "ab");
if (!f)
return false;
fwrite(Data.data(), 1, Data.size(), f);
fclose (f);
}
return true;
}
#ifdef DEDICATED_ONLY
warnings << "SaveSurface: cannot use something else than BMP in dedicated-only-mode" << endl;
return false;
#else
//
// JPG, PNG, GIF
//
// We use GD for saving these formats
gdImagePtr gd_image = NULL;
// Convert the surface
gd_image = SDLSurface2GDImage ( image );
if ( !gd_image )
return false;
// Save the image
int s;
char *data = NULL;
FILE *out = OpenGameFile (FileName, "wb");
if ( !out )
return false;
// Get the data depending on the format
switch (Format)
{
case FMT_PNG:
data = ( char * ) gdImagePngPtr ( gd_image, &s );
break;
case FMT_JPG:
data = ( char * ) gdImageJpegPtr ( gd_image, &s,tLXOptions->iJpegQuality );
break;
case FMT_GIF:
data = ( char * ) gdImageGifPtr ( gd_image, &s );
break;
default:
data = ( char * ) gdImagePngPtr ( gd_image, &s );
break;
}
// Check
if (!data)
return false;
// Size of the data
size_t size = s > 0 ? s : -s;
// Write the image data
if (fwrite(data, 1, size, out) != size)
return false;
// Write any additional data
if (!Data.empty())
fwrite(Data.data(), 1, Data.size(), out);
// Free everything
gdFree ( data );
gdImageDestroy ( gd_image );
// Close the file and quit
return fclose(out) == 0;
#endif // !DEDICATED_ONLY
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <algorithm>
#include "TFile.h"
#include "TLegend.h"
#include "PlotStack.h"
ClassImp(PlotStack)
//--------------------------------------------------------------------
PlotStack::PlotStack() :
fTreeName("events"),
fAllHist("htotal"),
fLuminosity(2110.0),
fDataContainer(0),
fMCContainer(0),
fMCWeights(""),
fDebug(false)
{
fFriends.resize(0);
fDataFiles.resize(0);
fMCFiles.resize(0);
fXSecs.resize(0);
fStackEntries.resize(0);
fStackColors.resize(0);
}
//--------------------------------------------------------------------
PlotStack::~PlotStack()
{}
//--------------------------------------------------------------------
void
PlotStack::ReadMCConfig(TString config, TString fileDir)
{
if (fileDir != "" && !fileDir.EndsWith("/"))
fileDir = fileDir + "/";
std::ifstream configFile;
configFile.open(config.Data());
TString FileName;
TString XSec;
TString LegendEntry;
TString ColorEntry;
while (!configFile.eof()) {
configFile >> FileName >> XSec >> LegendEntry >> ColorEntry;
if (ColorEntry != "" && !FileName.BeginsWith('#'))
AddMCFile(fileDir + FileName, XSec.Atof(), LegendEntry, ColorEntry.Atoi());
}
}
//--------------------------------------------------------------------
std::vector<TH1D*>
PlotStack::GetHistList(Int_t NumXBins, Double_t *XBins, Bool_t isMC)
{
std::vector<TString> FileList;
TreeContainer *tempContainer = NULL;
TString tempCutHolder;
if (isMC) {
FileList = fMCFiles;
tempContainer = fMCContainer;
if (fMCWeights != "") {
tempCutHolder = fDefaultCut;
SetDefaultWeight(TString("(") + tempCutHolder + TString(")*(") + fMCWeights + TString(")"));
}
}
else {
FileList = fDataFiles;
tempContainer = fDataContainer;
}
for (UInt_t iFile = 0; iFile < FileList.size(); iFile++)
tempContainer->AddFile(FileList[iFile]);
SetTreeList(tempContainer->ReturnTreeList());
std::vector<TFile*> theFiles = tempContainer->ReturnFileList();
std::vector<TH1D*> theHists = MakeHists(NumXBins,XBins);
if (isMC && fMCWeights != "")
SetDefaultWeight(tempCutHolder);
for (UInt_t iFile = 0; iFile < theFiles.size(); iFile++) {
if (isMC) {
TH1D *allHist = (TH1D*) theFiles[iFile]->FindObjectAny(fAllHist);
if (fDebug) {
std::cout << "Integral before " << theHists[iFile]->Integral() << std::endl;
std::cout << "Scale factor " << fLuminosity*fXSecs[iFile]/allHist->GetBinContent(1) << std::endl;
}
theHists[iFile]->Scale(fLuminosity*fXSecs[iFile]/allHist->GetBinContent(1));
SetZeroError(theHists[iFile]);
if (fDebug)
std::cout << "Integral after " << theHists[iFile]->Integral() << std::endl;
}
else if (fDebug)
std::cout << "Data yield " << theHists[iFile]->Integral() << std::endl;
}
return theHists;
}
//--------------------------------------------------------------------
void
PlotStack::MakeCanvas(TString FileBase, Int_t NumXBins, Double_t *XBins,
TString XLabel, TString YLabel, Bool_t logY)
{
fDataContainer = new TreeContainer();
fDataContainer->SetTreeName(fTreeName);
fMCContainer = new TreeContainer();
fMCContainer->SetTreeName(fTreeName);
for (UInt_t iFriend = 0; iFriend != fFriends.size(); ++iFriend) {
fDataContainer->AddFriendName(fFriends[iFriend]);
fMCContainer->AddFriendName(fFriends[iFriend]);
}
std::vector<TH1D*> DataHists = GetHistList(NumXBins,XBins,false);
std::vector<TH1D*> MCHists = GetHistList(NumXBins,XBins,true);
std::vector<TH1D*> theHists;
SetRatioIndex(0);
SetOnlyRatioWithData(true);
SetLegendFill(true);
TH1D *DataHist = (TH1D*) DataHists[0]->Clone("DataHist");
DataHist->Reset("M");
for (UInt_t iHist = 0; iHist < DataHists.size(); iHist++)
DataHist->Add(DataHists[iHist]);
TString previousEntry = "";
TH1D *tempMCHist = 0;
HistHolder *tempHistHolder = 0;
std::vector<HistHolder*> HistHolders;
HistHolders.resize(0);
for (UInt_t iHist = 0; iHist != MCHists.size(); ++iHist) {
if (fStackEntries[iHist] != previousEntry) {
previousEntry = fStackEntries[iHist];
TString tempName;
tempName.Format("StackedHist_%d",iHist);
tempMCHist = (TH1D*) MCHists[iHist]->Clone(tempName);
tempHistHolder = new HistHolder(tempMCHist,fStackEntries[iHist],fStackColors[iHist]);
HistHolders.push_back(tempHistHolder);
}
else
tempMCHist->Add(MCHists[iHist]);
}
std::sort(HistHolders.begin(),HistHolders.end(),SortHistHolders);
std::vector<TH1D*> AllHists;
for (UInt_t iLarger = 0; iLarger != HistHolders.size(); ++iLarger) {
for (UInt_t iSmaller = iLarger + 1; iSmaller != HistHolders.size(); ++iSmaller)
HistHolders[iLarger]->fHist->Add(HistHolders[iSmaller]->fHist);
AllHists.push_back(HistHolders[iLarger]->fHist);
AddLegendEntry(HistHolders[iLarger]->fEntry,HistHolders[iLarger]->fColor,1,1);
}
AddLegendEntry("Data",1);
SetDataIndex(int(AllHists.size()));
AllHists.push_back(DataHist);
BaseCanvas(FileBase,AllHists,XLabel,YLabel,logY);
for (UInt_t iHist = 0; iHist != AllHists.size(); ++iHist)
delete AllHists[iHist];
for (UInt_t iHist = 0; iHist != MCHists.size(); ++iHist)
delete MCHists[iHist];
for (UInt_t iHist = 0; iHist != DataHists.size(); ++iHist)
delete DataHists[iHist];
delete fDataContainer;
delete fMCContainer;
}
//--------------------------------------------------------------------
void
PlotStack::MakeCanvas(TString FileBase, Int_t NumXBins, Double_t MinX, Double_t MaxX,
TString XLabel, TString YLabel, Bool_t logY)
{
Double_t XBins[NumXBins+1];
ConvertToArray(NumXBins,MinX,MaxX,XBins);
MakeCanvas(FileBase,NumXBins,XBins,XLabel,YLabel,logY);
}
<commit_msg>Fixed data error bar scaling bug.<commit_after>#include <fstream>
#include <iostream>
#include <algorithm>
#include "TFile.h"
#include "TLegend.h"
#include "PlotStack.h"
ClassImp(PlotStack)
//--------------------------------------------------------------------
PlotStack::PlotStack() :
fTreeName("events"),
fAllHist("htotal"),
fLuminosity(2110.0),
fDataContainer(0),
fMCContainer(0),
fMCWeights(""),
fDebug(false)
{
fFriends.resize(0);
fDataFiles.resize(0);
fMCFiles.resize(0);
fXSecs.resize(0);
fStackEntries.resize(0);
fStackColors.resize(0);
}
//--------------------------------------------------------------------
PlotStack::~PlotStack()
{}
//--------------------------------------------------------------------
void
PlotStack::ReadMCConfig(TString config, TString fileDir)
{
if (fileDir != "" && !fileDir.EndsWith("/"))
fileDir = fileDir + "/";
std::ifstream configFile;
configFile.open(config.Data());
TString FileName;
TString XSec;
TString LegendEntry;
TString ColorEntry;
while (!configFile.eof()) {
configFile >> FileName >> XSec >> LegendEntry >> ColorEntry;
if (ColorEntry != "" && !FileName.BeginsWith('#'))
AddMCFile(fileDir + FileName, XSec.Atof(), LegendEntry, ColorEntry.Atoi());
}
}
//--------------------------------------------------------------------
std::vector<TH1D*>
PlotStack::GetHistList(Int_t NumXBins, Double_t *XBins, Bool_t isMC)
{
std::vector<TString> FileList;
TreeContainer *tempContainer = NULL;
TString tempCutHolder;
if (isMC) {
FileList = fMCFiles;
tempContainer = fMCContainer;
if (fMCWeights != "") {
tempCutHolder = fDefaultCut;
SetDefaultWeight(TString("(") + tempCutHolder + TString(")*(") + fMCWeights + TString(")"));
}
}
else {
FileList = fDataFiles;
tempContainer = fDataContainer;
}
for (UInt_t iFile = 0; iFile < FileList.size(); iFile++)
tempContainer->AddFile(FileList[iFile]);
SetTreeList(tempContainer->ReturnTreeList());
std::vector<TFile*> theFiles = tempContainer->ReturnFileList();
std::vector<TH1D*> theHists = MakeHists(NumXBins,XBins);
if (isMC && fMCWeights != "")
SetDefaultWeight(tempCutHolder);
for (UInt_t iFile = 0; iFile < theFiles.size(); iFile++) {
if (isMC) {
TH1D *allHist = (TH1D*) theFiles[iFile]->FindObjectAny(fAllHist);
if (fDebug) {
std::cout << "Integral before " << theHists[iFile]->Integral() << std::endl;
std::cout << "Scale factor " << fLuminosity*fXSecs[iFile]/allHist->GetBinContent(1) << std::endl;
}
theHists[iFile]->Scale(fLuminosity*fXSecs[iFile]/allHist->GetBinContent(1));
SetZeroError(theHists[iFile]);
if (fDebug)
std::cout << "Integral after " << theHists[iFile]->Integral() << std::endl;
}
else if (fDebug)
std::cout << "Data yield " << theHists[iFile]->Integral() << std::endl;
}
return theHists;
}
//--------------------------------------------------------------------
void
PlotStack::MakeCanvas(TString FileBase, Int_t NumXBins, Double_t *XBins,
TString XLabel, TString YLabel, Bool_t logY)
{
fDataContainer = new TreeContainer();
fDataContainer->SetTreeName(fTreeName);
fMCContainer = new TreeContainer();
fMCContainer->SetTreeName(fTreeName);
for (UInt_t iFriend = 0; iFriend != fFriends.size(); ++iFriend) {
fDataContainer->AddFriendName(fFriends[iFriend]);
fMCContainer->AddFriendName(fFriends[iFriend]);
}
SetIncludeErrorBars(true);
std::vector<TH1D*> DataHists = GetHistList(NumXBins,XBins,false);
SetIncludeErrorBars(false);
std::vector<TH1D*> MCHists = GetHistList(NumXBins,XBins,true);
std::vector<TH1D*> theHists;
SetRatioIndex(0);
SetOnlyRatioWithData(true);
SetLegendFill(true);
TH1D *DataHist = (TH1D*) DataHists[0]->Clone("DataHist");
DataHist->Reset("M");
for (UInt_t iHist = 0; iHist < DataHists.size(); iHist++)
DataHist->Add(DataHists[iHist]);
TString previousEntry = "";
TH1D *tempMCHist = 0;
HistHolder *tempHistHolder = 0;
std::vector<HistHolder*> HistHolders;
HistHolders.resize(0);
for (UInt_t iHist = 0; iHist != MCHists.size(); ++iHist) {
if (fStackEntries[iHist] != previousEntry) {
previousEntry = fStackEntries[iHist];
TString tempName;
tempName.Format("StackedHist_%d",iHist);
tempMCHist = (TH1D*) MCHists[iHist]->Clone(tempName);
tempHistHolder = new HistHolder(tempMCHist,fStackEntries[iHist],fStackColors[iHist]);
HistHolders.push_back(tempHistHolder);
}
else
tempMCHist->Add(MCHists[iHist]);
}
std::sort(HistHolders.begin(),HistHolders.end(),SortHistHolders);
std::vector<TH1D*> AllHists;
for (UInt_t iLarger = 0; iLarger != HistHolders.size(); ++iLarger) {
for (UInt_t iSmaller = iLarger + 1; iSmaller != HistHolders.size(); ++iSmaller)
HistHolders[iLarger]->fHist->Add(HistHolders[iSmaller]->fHist);
AllHists.push_back(HistHolders[iLarger]->fHist);
AddLegendEntry(HistHolders[iLarger]->fEntry,HistHolders[iLarger]->fColor,1,1);
}
AddLegendEntry("Data",1);
SetDataIndex(int(AllHists.size()));
AllHists.push_back(DataHist);
BaseCanvas(FileBase,AllHists,XLabel,YLabel,logY);
for (UInt_t iHist = 0; iHist != AllHists.size(); ++iHist)
delete AllHists[iHist];
for (UInt_t iHist = 0; iHist != MCHists.size(); ++iHist)
delete MCHists[iHist];
for (UInt_t iHist = 0; iHist != DataHists.size(); ++iHist)
delete DataHists[iHist];
delete fDataContainer;
delete fMCContainer;
}
//--------------------------------------------------------------------
void
PlotStack::MakeCanvas(TString FileBase, Int_t NumXBins, Double_t MinX, Double_t MaxX,
TString XLabel, TString YLabel, Bool_t logY)
{
Double_t XBins[NumXBins+1];
ConvertToArray(NumXBins,MinX,MaxX,XBins);
MakeCanvas(FileBase,NumXBins,XBins,XLabel,YLabel,logY);
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "avmplus.h"
namespace avmplus
{
DomainMgrFP10::DomainMgrFP10(AvmCore* _core) : core(_core)
{
}
DomainMgrFP10::~DomainMgrFP10()
{
}
void DomainMgrFP10::addNamedTraits(PoolObject* pool, Stringp name, Namespacep ns, Traits* traits)
{
// look for class in VM-wide type table, *without* recursion
// (don't look for traits in pool, ever.)
Traits* t = (Traits*)pool->domain->m_namedTraits->get(name, ns);
if (t == NULL)
{
pool->domain->m_namedTraits->add(name, ns, (Binding)traits);
}
}
void DomainMgrFP10::addNamedInstanceTraits(PoolObject* pool, Stringp name, Namespacep ns, Traits* itraits)
{
// look for class in VM-wide type table, *without* recursion
Traits* t = (Traits*)pool->domain->m_namedTraits->get(name, ns);
// look for class in current pool
if (t == NULL)
{
t = (Traits*)pool->m_namedTraits->get(name, ns);
}
if (t == NULL)
{
pool->m_namedTraits->add(name, ns, (Binding)itraits);
}
}
Traits* DomainMgrFP10::findBuiltinTraitsByName(PoolObject* pool, Stringp name)
{
return (Traits*)pool->m_namedTraits->getName(name);
}
Traits* DomainMgrFP10::findTraitsInDomainByNameAndNSImpl(Domain* domain, Stringp name, Namespacep ns)
{
Traits* traits = NULL;
for (uint32_t i = domain->m_baseCount; i > 0; --i)
{
Domain* d = domain->m_bases[i-1];
traits = (Traits*)d->m_namedTraits->get(name, ns);
if (traits != NULL)
break;
}
return traits;
}
Traits* DomainMgrFP10::findTraitsInPoolByNameAndNSImpl(PoolObject* pool, Stringp name, Namespacep ns)
{
// look for class in VM-wide type table
Traits* t = findTraitsInDomainByNameAndNSImpl(pool->domain, name, ns);
// look for class in current ABC file
if (t == NULL)
{
t = (Traits*)pool->m_namedTraits->get(name, ns);
}
return t;
}
Traits* DomainMgrFP10::findTraitsInPoolByNameAndNS(PoolObject* pool, Stringp name, Namespacep ns)
{
return findTraitsInPoolByNameAndNSImpl(pool, name, ns);
}
Traits* DomainMgrFP10::findTraitsInPoolByMultiname(PoolObject* pool, const Multiname& multiname)
{
// do full lookup of multiname, error if more than 1 match
// return Traits if 1 match, NULL if 0 match, BIND_AMBIGUOUS >1 match
Traits* found = NULL;
if (multiname.isBinding())
{
// multiname must not be an attr name, have wildcards, or have runtime parts.
for (int32_t i=0, n=multiname.namespaceCount(); i < n; i++)
{
Traits* t = findTraitsInPoolByNameAndNSImpl(pool, multiname.getName(), multiname.getNamespace(i));
if (t != NULL)
{
if (found == NULL)
{
found = t;
}
else if (found != t)
{
// ambiguity
return (Traits*)BIND_AMBIGUOUS;
}
}
}
}
return found;
}
static void addScript(Stringp name, Namespacep ns, MethodInfo* script, List<MethodInfo*>& scriptList, MultinameHashtable* scriptMap)
{
scriptList.add(script);
// note that this is idx+1 -- can't use idx=0 since that's BIND_NONE
uint32_t idx = scriptList.size();
scriptMap->add(name, ns, Binding(idx));
}
void DomainMgrFP10::addNamedScript(PoolObject* pool, Stringp name, Namespacep ns, MethodInfo* script)
{
if (ns->isPrivate())
{
addScript(name, ns, script, pool->m_namedScriptsList, pool->m_namedScriptsMap);
}
else
{
Domain* domain = pool->domain;
MethodInfo* s = findScriptInDomainByNameAndNSImpl(domain, name, ns);
if (s == NULL)
{
addScript(name, ns, script, domain->m_namedScriptsList, domain->m_namedScriptsMap);
}
}
}
MethodInfo* DomainMgrFP10::findScriptInDomainByNameAndNSImpl(Domain* domain, Stringp name, Namespacep ns)
{
for (uint32_t i = domain->m_baseCount; i > 0; --i)
{
Domain* d = domain->m_bases[i-1];
Binding b = d->m_namedScriptsMap->get(name, ns);
if (b != BIND_NONE)
{
// BIND_AMBIGUOUS not possible here
return d->m_namedScriptsList.get(uint32_t(uintptr_t(b))-1);
}
}
return NULL;
}
MethodInfo* DomainMgrFP10::findScriptInDomainByMultinameImpl(Domain* domain, const Multiname& multiname)
{
for (uint32_t i = domain->m_baseCount; i > 0; --i)
{
Domain* d = domain->m_bases[i-1];
Binding b = d->m_namedScriptsMap->getMulti(multiname);
if (b != BIND_NONE)
{
return (b == BIND_AMBIGUOUS) ?
(MethodInfo*)BIND_AMBIGUOUS :
d->m_namedScriptsList.get(uint32_t(uintptr_t(b))-1);
}
}
return NULL;
}
MethodInfo* DomainMgrFP10::findScriptInPoolByNameAndNSImpl(PoolObject* pool, Stringp name, Namespacep ns)
{
MethodInfo* f = findScriptInDomainByNameAndNSImpl(pool->domain, name, ns);
if (f == NULL)
{
Binding b = pool->m_namedScriptsMap->get(name, ns);
if (b != BIND_NONE)
{
// BIND_AMBIGUOUS not possible here
f = pool->m_namedScriptsList.get(uint32_t(uintptr_t(b))-1);
}
}
return f;
}
MethodInfo* DomainMgrFP10::findScriptInPoolByMultiname(PoolObject* pool, const Multiname& multiname)
{
MethodInfo* f = findScriptInDomainByMultinameImpl(pool->domain, multiname);
if (f == NULL)
{
Binding b = pool->m_namedScriptsMap->getMulti(multiname);
if (b != BIND_NONE)
{
f = (b == BIND_AMBIGUOUS) ?
(MethodInfo*)BIND_AMBIGUOUS :
pool->m_namedScriptsList.get(uint32_t(uintptr_t(b))-1);
}
}
return f;
}
void DomainMgrFP10::addNamedScriptEnvs(AbcEnv* abcEnv, const List<ScriptEnv*>& envs)
{
HeapHashtable* ht = new(core->GetGC()) HeapHashtable(core->GetGC());
for (uint32_t i = 0, n = envs.size(); i < n; ++i)
{
ScriptEnv* se = envs[i];
AvmAssert(se->abcEnv() == abcEnv);
MethodInfo* mi = se->method;
ht->add((Atom)mi, (Atom)se);
}
AvmAssert(abcEnv->m_namedScriptEnvsList.size() == 0);
PoolObject* pool = abcEnv->pool();
abcEnv->m_namedScriptEnvsList.ensureCapacity(pool->m_namedScriptsList.size());
for (uint32_t i = 0, n = pool->m_namedScriptsList.size(); i < n; ++i)
{
MethodInfo* mi = pool->m_namedScriptsList[i];
AvmAssert(mi->pool() == abcEnv->pool());
ScriptEnv* se = (ScriptEnv*)ht->get((Atom)mi);
AvmAssert(se != (ScriptEnv*)undefinedAtom);
abcEnv->m_namedScriptEnvsList.set(i, se);
}
// since a DomainEnv can be shared among several AbcEnv's,
// its list might not be empty.
Domain* domain = pool->domain;
DomainEnv* domainEnv = abcEnv->domainEnv();
domainEnv->m_namedScriptEnvsList.ensureCapacity(domainEnv->m_namedScriptEnvsList.size() + domain->m_namedScriptsList.size());
for (uint32_t i = 0, n = domain->m_namedScriptsList.size(); i < n; ++i)
{
MethodInfo* mi = domain->m_namedScriptsList[i];
if (mi->pool() != abcEnv->pool())
continue;
ScriptEnv* se = (ScriptEnv*)ht->get((Atom)mi);
AvmAssert(se != (ScriptEnv*)undefinedAtom);
AvmAssert(i >= domainEnv->m_namedScriptEnvsList.size() || domainEnv->m_namedScriptEnvsList.get(i) == 0);
domainEnv->m_namedScriptEnvsList.set(i, se);
}
#ifdef _DEBUG
// final reality check.
AvmAssert(domainEnv->m_namedScriptEnvsList.size() == domainEnv->m_namedScriptEnvsList.size());
for (uint32_t i = 0, n = domain->m_namedScriptsList.size(); i < n; ++i)
{
MethodInfo* mi = domain->m_namedScriptsList[i];
ScriptEnv* se = domainEnv->m_namedScriptEnvsList[i];
AvmAssert(mi != NULL && se != NULL);
AvmAssert(se->method == mi);
}
#endif
delete ht;
#ifdef VMCFG_LOOKUP_CACHE
// Adding scripts to a domain always invalidates the lookup cache.
core->invalidateLookupCache();
#endif
}
ScriptEnv* DomainMgrFP10::findScriptEnvInDomainEnvByMultinameImpl(DomainEnv* domainEnv, const Multiname& multiname)
{
for (uint32_t i = domainEnv->m_baseCount; i > 0; --i)
{
DomainEnv* d = domainEnv->m_bases[i-1];
Binding b = d->domain()->m_namedScriptsMap->getMulti(multiname);
if (b != BIND_NONE)
{
return (b == BIND_AMBIGUOUS) ?
(ScriptEnv*)BIND_AMBIGUOUS :
d->m_namedScriptEnvsList.get(uint32_t(uintptr_t(b))-1);
}
}
return NULL;
}
ScriptEnv* DomainMgrFP10::findScriptEnvInDomainEnvByMultiname(DomainEnv* domainEnv, const Multiname& multiname)
{
return findScriptEnvInDomainEnvByMultinameImpl(domainEnv, multiname);
}
ScriptEnv* DomainMgrFP10::findScriptEnvInAbcEnvByMultiname(AbcEnv* abcEnv, const Multiname& multiname)
{
// note, lookup order must match findNamedScript!
ScriptEnv* se = findScriptEnvInDomainEnvByMultinameImpl(abcEnv->domainEnv(), multiname);
if (se == NULL)
{
Binding b = abcEnv->pool()->m_namedScriptsMap->getMulti(multiname);
if (b != BIND_NONE)
{
se = (b == BIND_AMBIGUOUS) ?
(ScriptEnv*)BIND_AMBIGUOUS :
abcEnv->m_namedScriptEnvsList.get(uint32_t(uintptr_t(b))-1);
}
}
return se;
}
#ifdef DEBUGGER
ScriptEnv* DomainMgrFP10::findScriptEnvInDomainEnvByNameOnlyImpl(DomainEnv* domainEnv, Stringp name)
{
for (uint32_t i = domainEnv->m_baseCount; i > 0; --i)
{
DomainEnv* d = domainEnv->m_bases[i-1];
Binding b = d->domain()->m_namedScriptsMap->getName(name);
if (b != BIND_NONE)
{
ScriptEnv* f = (ScriptEnv*)d->m_namedScriptEnvsList.get(uint32_t(uintptr_t(b))-1);
return f;
}
}
return NULL;
}
ScriptEnv* DomainMgrFP10::findScriptEnvInAbcEnvByNameOnly(AbcEnv* abcEnv, Stringp name)
{
ScriptEnv* se = findScriptEnvInDomainEnvByNameOnlyImpl(abcEnv->domainEnv(), name);
if (se == NULL)
{
Binding b = abcEnv->pool()->m_namedScriptsMap->getName(name);
if (b != BIND_NONE)
{
se = abcEnv->m_namedScriptEnvsList.get(uint32_t(uintptr_t(b))-1);
}
}
return se;
}
#endif // DEBUGGER
} // namespace avmplus
<commit_msg>fix trivial error in DomainMgr assertion test (r=me)<commit_after>/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */
/* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "avmplus.h"
namespace avmplus
{
DomainMgrFP10::DomainMgrFP10(AvmCore* _core) : core(_core)
{
}
DomainMgrFP10::~DomainMgrFP10()
{
}
void DomainMgrFP10::addNamedTraits(PoolObject* pool, Stringp name, Namespacep ns, Traits* traits)
{
// look for class in VM-wide type table, *without* recursion
// (don't look for traits in pool, ever.)
Traits* t = (Traits*)pool->domain->m_namedTraits->get(name, ns);
if (t == NULL)
{
pool->domain->m_namedTraits->add(name, ns, (Binding)traits);
}
}
void DomainMgrFP10::addNamedInstanceTraits(PoolObject* pool, Stringp name, Namespacep ns, Traits* itraits)
{
// look for class in VM-wide type table, *without* recursion
Traits* t = (Traits*)pool->domain->m_namedTraits->get(name, ns);
// look for class in current pool
if (t == NULL)
{
t = (Traits*)pool->m_namedTraits->get(name, ns);
}
if (t == NULL)
{
pool->m_namedTraits->add(name, ns, (Binding)itraits);
}
}
Traits* DomainMgrFP10::findBuiltinTraitsByName(PoolObject* pool, Stringp name)
{
return (Traits*)pool->m_namedTraits->getName(name);
}
Traits* DomainMgrFP10::findTraitsInDomainByNameAndNSImpl(Domain* domain, Stringp name, Namespacep ns)
{
Traits* traits = NULL;
for (uint32_t i = domain->m_baseCount; i > 0; --i)
{
Domain* d = domain->m_bases[i-1];
traits = (Traits*)d->m_namedTraits->get(name, ns);
if (traits != NULL)
break;
}
return traits;
}
Traits* DomainMgrFP10::findTraitsInPoolByNameAndNSImpl(PoolObject* pool, Stringp name, Namespacep ns)
{
// look for class in VM-wide type table
Traits* t = findTraitsInDomainByNameAndNSImpl(pool->domain, name, ns);
// look for class in current ABC file
if (t == NULL)
{
t = (Traits*)pool->m_namedTraits->get(name, ns);
}
return t;
}
Traits* DomainMgrFP10::findTraitsInPoolByNameAndNS(PoolObject* pool, Stringp name, Namespacep ns)
{
return findTraitsInPoolByNameAndNSImpl(pool, name, ns);
}
Traits* DomainMgrFP10::findTraitsInPoolByMultiname(PoolObject* pool, const Multiname& multiname)
{
// do full lookup of multiname, error if more than 1 match
// return Traits if 1 match, NULL if 0 match, BIND_AMBIGUOUS >1 match
Traits* found = NULL;
if (multiname.isBinding())
{
// multiname must not be an attr name, have wildcards, or have runtime parts.
for (int32_t i=0, n=multiname.namespaceCount(); i < n; i++)
{
Traits* t = findTraitsInPoolByNameAndNSImpl(pool, multiname.getName(), multiname.getNamespace(i));
if (t != NULL)
{
if (found == NULL)
{
found = t;
}
else if (found != t)
{
// ambiguity
return (Traits*)BIND_AMBIGUOUS;
}
}
}
}
return found;
}
static void addScript(Stringp name, Namespacep ns, MethodInfo* script, List<MethodInfo*>& scriptList, MultinameHashtable* scriptMap)
{
scriptList.add(script);
// note that this is idx+1 -- can't use idx=0 since that's BIND_NONE
uint32_t idx = scriptList.size();
scriptMap->add(name, ns, Binding(idx));
}
void DomainMgrFP10::addNamedScript(PoolObject* pool, Stringp name, Namespacep ns, MethodInfo* script)
{
if (ns->isPrivate())
{
addScript(name, ns, script, pool->m_namedScriptsList, pool->m_namedScriptsMap);
}
else
{
Domain* domain = pool->domain;
MethodInfo* s = findScriptInDomainByNameAndNSImpl(domain, name, ns);
if (s == NULL)
{
addScript(name, ns, script, domain->m_namedScriptsList, domain->m_namedScriptsMap);
}
}
}
MethodInfo* DomainMgrFP10::findScriptInDomainByNameAndNSImpl(Domain* domain, Stringp name, Namespacep ns)
{
for (uint32_t i = domain->m_baseCount; i > 0; --i)
{
Domain* d = domain->m_bases[i-1];
Binding b = d->m_namedScriptsMap->get(name, ns);
if (b != BIND_NONE)
{
// BIND_AMBIGUOUS not possible here
return d->m_namedScriptsList.get(uint32_t(uintptr_t(b))-1);
}
}
return NULL;
}
MethodInfo* DomainMgrFP10::findScriptInDomainByMultinameImpl(Domain* domain, const Multiname& multiname)
{
for (uint32_t i = domain->m_baseCount; i > 0; --i)
{
Domain* d = domain->m_bases[i-1];
Binding b = d->m_namedScriptsMap->getMulti(multiname);
if (b != BIND_NONE)
{
return (b == BIND_AMBIGUOUS) ?
(MethodInfo*)BIND_AMBIGUOUS :
d->m_namedScriptsList.get(uint32_t(uintptr_t(b))-1);
}
}
return NULL;
}
MethodInfo* DomainMgrFP10::findScriptInPoolByNameAndNSImpl(PoolObject* pool, Stringp name, Namespacep ns)
{
MethodInfo* f = findScriptInDomainByNameAndNSImpl(pool->domain, name, ns);
if (f == NULL)
{
Binding b = pool->m_namedScriptsMap->get(name, ns);
if (b != BIND_NONE)
{
// BIND_AMBIGUOUS not possible here
f = pool->m_namedScriptsList.get(uint32_t(uintptr_t(b))-1);
}
}
return f;
}
MethodInfo* DomainMgrFP10::findScriptInPoolByMultiname(PoolObject* pool, const Multiname& multiname)
{
MethodInfo* f = findScriptInDomainByMultinameImpl(pool->domain, multiname);
if (f == NULL)
{
Binding b = pool->m_namedScriptsMap->getMulti(multiname);
if (b != BIND_NONE)
{
f = (b == BIND_AMBIGUOUS) ?
(MethodInfo*)BIND_AMBIGUOUS :
pool->m_namedScriptsList.get(uint32_t(uintptr_t(b))-1);
}
}
return f;
}
void DomainMgrFP10::addNamedScriptEnvs(AbcEnv* abcEnv, const List<ScriptEnv*>& envs)
{
HeapHashtable* ht = new(core->GetGC()) HeapHashtable(core->GetGC());
for (uint32_t i = 0, n = envs.size(); i < n; ++i)
{
ScriptEnv* se = envs[i];
AvmAssert(se->abcEnv() == abcEnv);
MethodInfo* mi = se->method;
ht->add((Atom)mi, (Atom)se);
}
AvmAssert(abcEnv->m_namedScriptEnvsList.size() == 0);
PoolObject* pool = abcEnv->pool();
abcEnv->m_namedScriptEnvsList.ensureCapacity(pool->m_namedScriptsList.size());
for (uint32_t i = 0, n = pool->m_namedScriptsList.size(); i < n; ++i)
{
MethodInfo* mi = pool->m_namedScriptsList[i];
AvmAssert(mi->pool() == abcEnv->pool());
ScriptEnv* se = (ScriptEnv*)ht->get((Atom)mi);
AvmAssert(se != (ScriptEnv*)undefinedAtom);
abcEnv->m_namedScriptEnvsList.set(i, se);
}
// since a DomainEnv can be shared among several AbcEnv's,
// its list might not be empty.
Domain* domain = pool->domain;
DomainEnv* domainEnv = abcEnv->domainEnv();
domainEnv->m_namedScriptEnvsList.ensureCapacity(domainEnv->m_namedScriptEnvsList.size() + domain->m_namedScriptsList.size());
for (uint32_t i = 0, n = domain->m_namedScriptsList.size(); i < n; ++i)
{
MethodInfo* mi = domain->m_namedScriptsList[i];
if (mi->pool() != abcEnv->pool())
continue;
ScriptEnv* se = (ScriptEnv*)ht->get((Atom)mi);
AvmAssert(se != (ScriptEnv*)undefinedAtom);
AvmAssert(i >= domainEnv->m_namedScriptEnvsList.size() || domainEnv->m_namedScriptEnvsList.get(i) == 0);
domainEnv->m_namedScriptEnvsList.set(i, se);
}
#ifdef _DEBUG
// final reality check.
AvmAssert(domain->m_namedScriptsList.size() == domainEnv->m_namedScriptEnvsList.size());
for (uint32_t i = 0, n = domain->m_namedScriptsList.size(); i < n; ++i)
{
MethodInfo* mi = domain->m_namedScriptsList[i];
ScriptEnv* se = domainEnv->m_namedScriptEnvsList[i];
AvmAssert(mi != NULL && se != NULL);
AvmAssert(se->method == mi);
}
#endif
delete ht;
#ifdef VMCFG_LOOKUP_CACHE
// Adding scripts to a domain always invalidates the lookup cache.
core->invalidateLookupCache();
#endif
}
ScriptEnv* DomainMgrFP10::findScriptEnvInDomainEnvByMultinameImpl(DomainEnv* domainEnv, const Multiname& multiname)
{
for (uint32_t i = domainEnv->m_baseCount; i > 0; --i)
{
DomainEnv* d = domainEnv->m_bases[i-1];
Binding b = d->domain()->m_namedScriptsMap->getMulti(multiname);
if (b != BIND_NONE)
{
return (b == BIND_AMBIGUOUS) ?
(ScriptEnv*)BIND_AMBIGUOUS :
d->m_namedScriptEnvsList.get(uint32_t(uintptr_t(b))-1);
}
}
return NULL;
}
ScriptEnv* DomainMgrFP10::findScriptEnvInDomainEnvByMultiname(DomainEnv* domainEnv, const Multiname& multiname)
{
return findScriptEnvInDomainEnvByMultinameImpl(domainEnv, multiname);
}
ScriptEnv* DomainMgrFP10::findScriptEnvInAbcEnvByMultiname(AbcEnv* abcEnv, const Multiname& multiname)
{
// note, lookup order must match findNamedScript!
ScriptEnv* se = findScriptEnvInDomainEnvByMultinameImpl(abcEnv->domainEnv(), multiname);
if (se == NULL)
{
Binding b = abcEnv->pool()->m_namedScriptsMap->getMulti(multiname);
if (b != BIND_NONE)
{
se = (b == BIND_AMBIGUOUS) ?
(ScriptEnv*)BIND_AMBIGUOUS :
abcEnv->m_namedScriptEnvsList.get(uint32_t(uintptr_t(b))-1);
}
}
return se;
}
#ifdef DEBUGGER
ScriptEnv* DomainMgrFP10::findScriptEnvInDomainEnvByNameOnlyImpl(DomainEnv* domainEnv, Stringp name)
{
for (uint32_t i = domainEnv->m_baseCount; i > 0; --i)
{
DomainEnv* d = domainEnv->m_bases[i-1];
Binding b = d->domain()->m_namedScriptsMap->getName(name);
if (b != BIND_NONE)
{
ScriptEnv* f = (ScriptEnv*)d->m_namedScriptEnvsList.get(uint32_t(uintptr_t(b))-1);
return f;
}
}
return NULL;
}
ScriptEnv* DomainMgrFP10::findScriptEnvInAbcEnvByNameOnly(AbcEnv* abcEnv, Stringp name)
{
ScriptEnv* se = findScriptEnvInDomainEnvByNameOnlyImpl(abcEnv->domainEnv(), name);
if (se == NULL)
{
Binding b = abcEnv->pool()->m_namedScriptsMap->getName(name);
if (b != BIND_NONE)
{
se = abcEnv->m_namedScriptEnvsList.get(uint32_t(uintptr_t(b))-1);
}
}
return se;
}
#endif // DEBUGGER
} // namespace avmplus
<|endoftext|> |
<commit_before>/* GNE - Game Networking Engine, a portable multithreaded networking library.
* Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)
* Project website: http://www.rit.edu/~jpw9607/
*
* 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 "gneintern.h"
#include "ServerConnection.h"
namespace GNE {
//##ModelId=3B075381027A
ServerConnection::ServerConnection(int outRate, int inRate, NLsocket rsocket2)
: Connection(outRate, inRate) {
rsocket = rsocket2;
}
//##ModelId=3B075381027E
ServerConnection::~ServerConnection() {
}
//##ModelId=3B0753810280
void ServerConnection::run() {
assert(rsocket != NL_INVALID);
onNewConn();
}
//##ModelId=3B0753810283
void ServerConnection::onConnFailure(Connection::FailureType errorType) {
}
}
<commit_msg>More documentation.<commit_after>/* GNE - Game Networking Engine, a portable multithreaded networking library.
* Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu)
* Project website: http://www.rit.edu/~jpw9607/
*
* 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 "gneintern.h"
#include "ServerConnection.h"
namespace GNE {
//##ModelId=3B075381027A
ServerConnection::ServerConnection(int outRate, int inRate, NLsocket rsocket2)
: Connection(outRate, inRate) {
rsocket = rsocket2;
}
//##ModelId=3B075381027E
ServerConnection::~ServerConnection() {
}
/**
* \todo implement negotiation
* \bug this function relies on the fact that mutexes are recursive, which is
* not true over all pthreads implementations. When
* ConnectionEventGenerator lauches each onReceive event in a new thread,
* then this problem will go away.
*/
//##ModelId=3B0753810280
void ServerConnection::run() {
assert(rsocket != NL_INVALID);
//Do connection negotiaion here, and create the PacketStream
onNewConn();
}
//##ModelId=3B0753810283
void ServerConnection::onConnFailure(Connection::FailureType errorType) {
}
}
<|endoftext|> |
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGPropeller.cpp
Author: Jon S. Berndt
Date started: 08/24/00
Purpose: Encapsulates the propeller object
------------- Copyright (C) 2000 Jon S. Berndt (jsb@hal-pc.org) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
08/24/00 JSB Created
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGPropeller.h"
static const char *IdSrc = "$Header: /cvsroot/jsbsim/JSBSim/Attic/FGPropeller.cpp,v 1.15 2001/02/05 13:05:24 jsb Exp $";
static const char *IdHdr = ID_PROPELLER;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGPropeller::FGPropeller(FGFDMExec* exec, FGConfigFile* Prop_cfg) : FGThruster(exec)
{
string token;
int rows, cols;
PropName = Prop_cfg->GetValue("NAME");
cout << "\n Propeller Name: " << PropName << endl;
Prop_cfg->GetNextConfigLine();
while (Prop_cfg->GetValue() != "/PROPELLER") {
*Prop_cfg >> token;
if (token == "IXX") {
*Prop_cfg >> Ixx;
cout << " IXX = " << Ixx << endl;
} else if (token == "DIAMETER") {
*Prop_cfg >> Diameter;
Diameter /= 12.0;
cout << " Diameter = " << Diameter << " ft." << endl;
} else if (token == "NUMBLADES") {
*Prop_cfg >> numBlades;
cout << " Number of Blades = " << numBlades << endl;
} else if (token == "EFFICIENCY") {
*Prop_cfg >> rows >> cols;
if (cols == 1) Efficiency = new FGTable(rows);
else Efficiency = new FGTable(rows, cols);
*Efficiency << *Prop_cfg;
cout << " Efficiency: " << endl;
Efficiency->Print();
} else if (token == "C_THRUST") {
*Prop_cfg >> rows >> cols;
if (cols == 1) cThrust = new FGTable(rows);
else cThrust = new FGTable(rows, cols);
*cThrust << *Prop_cfg;
cout << " Thrust Coefficient: " << endl;
cThrust->Print();
} else if (token == "C_POWER") {
*Prop_cfg >> rows >> cols;
if (cols == 1) cPower = new FGTable(rows);
else cPower = new FGTable(rows, cols);
*cPower << *Prop_cfg;
cout << " Power Coefficient: " << endl;
cPower->Print();
} else {
cout << "Unhandled token in Propeller config file: " << token << endl;
}
}
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGPropeller::~FGPropeller(void)
{
if (Efficiency) delete Efficiency;
if (cThrust) delete cThrust;
if (cPower) delete cPower;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// We must be getting the aerodynamic velocity here, NOT the inertial velocity.
// We need the velocity with respect to the wind.
//
// Note that PowerAvailable is the excess power available after the drag of the
// propeller has been subtracted. At equilibrium, PowerAvailable will be zero -
// indicating that the propeller will not accelerate or decelerate.
// Remembering that Torque * omega = Power, we can derive the torque on the
// propeller and its acceleration to give a new RPM. The current RPM will be
// used to calculate thrust.
//
// Because RPM could be zero, we need to be creative about what RPM is stated as.
float FGPropeller::Calculate(float PowerAvailable)
{
float J, C_Thrust, omega;
float Vel = (fdmex->GetTranslation()->GetUVW())(1);
float rho = fdmex->GetAtmosphere()->GetDensity();
float RPS = RPM/60.0;
if (RPM > 0.10) {
J = Vel / (Diameter * RPM / 60.0);
} else {
J = 0.0;
}
if (MaxPitch == MinPitch) { // Fixed pitch prop
C_Thrust = cThrust->GetValue(J);
} else { // Variable pitch prop
C_Thrust = cThrust->GetValue(J, Pitch);
}
Thrust = C_Thrust*RPS*RPS*Diameter*Diameter*Diameter*Diameter*rho;
vFn(1) = Thrust;
omega = RPS*2.0*M_PI;
if (omega <= 500) omega = 1.0;
Torque = PowerAvailable / omega;
RPM = (RPS + ((Torque / Ixx) / (2.0 * M_PI)) * deltaT) * 60.0;
return Thrust; // return thrust in pounds
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
float FGPropeller::GetPowerRequired(void)
{
if (RPM <= 0.10) return 0.0; // If the prop ain't turnin', the fuel ain't burnin'.
float cPReq, RPS = RPM / 60.0;
float J = (fdmex->GetTranslation()->GetUVW())(1) / (Diameter * RPS);
float rho = fdmex->GetAtmosphere()->GetDensity();
if (MaxPitch == MinPitch) { // Fixed pitch prop
cPReq = cPower->GetValue(J);
} else { // Variable pitch prop
cPReq = cPower->GetValue(J, Pitch);
}
PowerRequired = cPReq*RPS*RPS*RPS*Diameter*Diameter*Diameter*Diameter
*Diameter*rho;
return PowerRequired;
}
<commit_msg>Corrected PROPELLER identifier to FG_PROPELLER<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGPropeller.cpp
Author: Jon S. Berndt
Date started: 08/24/00
Purpose: Encapsulates the propeller object
------------- Copyright (C) 2000 Jon S. Berndt (jsb@hal-pc.org) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
08/24/00 JSB Created
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGPropeller.h"
static const char *IdSrc = "$Header: /cvsroot/jsbsim/JSBSim/Attic/FGPropeller.cpp,v 1.16 2001/02/14 15:41:25 jberndt Exp $";
static const char *IdHdr = ID_PROPELLER;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGPropeller::FGPropeller(FGFDMExec* exec, FGConfigFile* Prop_cfg) : FGThruster(exec)
{
string token;
int rows, cols;
PropName = Prop_cfg->GetValue("NAME");
cout << "\n Propeller Name: " << PropName << endl;
Prop_cfg->GetNextConfigLine();
while (Prop_cfg->GetValue() != "/FG_PROPELLER") {
*Prop_cfg >> token;
if (token == "IXX") {
*Prop_cfg >> Ixx;
cout << " IXX = " << Ixx << endl;
} else if (token == "DIAMETER") {
*Prop_cfg >> Diameter;
Diameter /= 12.0;
cout << " Diameter = " << Diameter << " ft." << endl;
} else if (token == "NUMBLADES") {
*Prop_cfg >> numBlades;
cout << " Number of Blades = " << numBlades << endl;
} else if (token == "EFFICIENCY") {
*Prop_cfg >> rows >> cols;
if (cols == 1) Efficiency = new FGTable(rows);
else Efficiency = new FGTable(rows, cols);
*Efficiency << *Prop_cfg;
cout << " Efficiency: " << endl;
Efficiency->Print();
} else if (token == "C_THRUST") {
*Prop_cfg >> rows >> cols;
if (cols == 1) cThrust = new FGTable(rows);
else cThrust = new FGTable(rows, cols);
*cThrust << *Prop_cfg;
cout << " Thrust Coefficient: " << endl;
cThrust->Print();
} else if (token == "C_POWER") {
*Prop_cfg >> rows >> cols;
if (cols == 1) cPower = new FGTable(rows);
else cPower = new FGTable(rows, cols);
*cPower << *Prop_cfg;
cout << " Power Coefficient: " << endl;
cPower->Print();
} else {
cout << "Unhandled token in Propeller config file: " << token << endl;
}
}
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGPropeller::~FGPropeller(void)
{
if (Efficiency) delete Efficiency;
if (cThrust) delete cThrust;
if (cPower) delete cPower;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// We must be getting the aerodynamic velocity here, NOT the inertial velocity.
// We need the velocity with respect to the wind.
//
// Note that PowerAvailable is the excess power available after the drag of the
// propeller has been subtracted. At equilibrium, PowerAvailable will be zero -
// indicating that the propeller will not accelerate or decelerate.
// Remembering that Torque * omega = Power, we can derive the torque on the
// propeller and its acceleration to give a new RPM. The current RPM will be
// used to calculate thrust.
//
// Because RPM could be zero, we need to be creative about what RPM is stated as.
float FGPropeller::Calculate(float PowerAvailable)
{
float J, C_Thrust, omega;
float Vel = (fdmex->GetTranslation()->GetUVW())(1);
float rho = fdmex->GetAtmosphere()->GetDensity();
float RPS = RPM/60.0;
if (RPM > 0.10) {
J = Vel / (Diameter * RPM / 60.0);
} else {
J = 0.0;
}
if (MaxPitch == MinPitch) { // Fixed pitch prop
C_Thrust = cThrust->GetValue(J);
} else { // Variable pitch prop
C_Thrust = cThrust->GetValue(J, Pitch);
}
Thrust = C_Thrust*RPS*RPS*Diameter*Diameter*Diameter*Diameter*rho;
vFn(1) = Thrust;
omega = RPS*2.0*M_PI;
if (omega <= 500) omega = 1.0;
Torque = PowerAvailable / omega;
RPM = (RPS + ((Torque / Ixx) / (2.0 * M_PI)) * deltaT) * 60.0;
return Thrust; // return thrust in pounds
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
float FGPropeller::GetPowerRequired(void)
{
if (RPM <= 0.10) return 0.0; // If the prop ain't turnin', the fuel ain't burnin'.
float cPReq, RPS = RPM / 60.0;
float J = (fdmex->GetTranslation()->GetUVW())(1) / (Diameter * RPS);
float rho = fdmex->GetAtmosphere()->GetDensity();
if (MaxPitch == MinPitch) { // Fixed pitch prop
cPReq = cPower->GetValue(J);
} else { // Variable pitch prop
cPReq = cPower->GetValue(J, Pitch);
}
PowerRequired = cPReq*RPS*RPS*RPS*Diameter*Diameter*Diameter*Diameter
*Diameter*rho;
return PowerRequired;
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// table_factory.cpp
//
// Identification: src/storage/table_factory.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "storage/table_factory.h"
#include "common/exception.h"
#include "common/logger.h"
#include "index/index.h"
#include "storage/data_table.h"
#include "storage/storage_manager.h"
#include "storage/temp_table.h"
namespace peloton {
namespace storage {
DataTable *TableFactory::GetDataTable(oid_t database_id, oid_t relation_id,
catalog::Schema *schema,
std::string table_name,
size_t tuples_per_tilegroup_count,
bool own_schema, bool adapt_table,
bool is_catalog) {
DataTable *table = new DataTable(schema, table_name, database_id, relation_id,
tuples_per_tilegroup_count, own_schema,
adapt_table, is_catalog);
return table;
}
TempTable *TableFactory::GetTempTable(catalog::Schema *schema,
bool own_schema) {
TempTable *table = new TempTable(INVALID_OID, schema, own_schema);
return (table);
}
bool TableFactory::DropDataTable(oid_t database_oid, oid_t table_oid) {
auto storage_manager = storage::StorageManager::GetInstance();
try {
DataTable *table = (DataTable *)storage_manager->GetTableWithOid(
database_oid, table_oid);
delete table;
} catch (CatalogException &e) {
return false;
}
return true;
}
} // namespace storage
} // namespace peloton
<commit_msg>Removing other unused headers<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// table_factory.cpp
//
// Identification: src/storage/table_factory.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "storage/table_factory.h"
#include "common/exception.h"
#include "storage/data_table.h"
#include "storage/storage_manager.h"
#include "storage/temp_table.h"
namespace peloton {
namespace storage {
DataTable *TableFactory::GetDataTable(oid_t database_id, oid_t relation_id,
catalog::Schema *schema,
std::string table_name,
size_t tuples_per_tilegroup_count,
bool own_schema, bool adapt_table,
bool is_catalog) {
DataTable *table = new DataTable(schema, table_name, database_id, relation_id,
tuples_per_tilegroup_count, own_schema,
adapt_table, is_catalog);
return table;
}
TempTable *TableFactory::GetTempTable(catalog::Schema *schema,
bool own_schema) {
TempTable *table = new TempTable(INVALID_OID, schema, own_schema);
return (table);
}
bool TableFactory::DropDataTable(oid_t database_oid, oid_t table_oid) {
auto storage_manager = storage::StorageManager::GetInstance();
try {
DataTable *table = (DataTable *)storage_manager->GetTableWithOid(
database_oid, table_oid);
delete table;
} catch (CatalogException &e) {
return false;
}
return true;
}
} // namespace storage
} // namespace peloton
<|endoftext|> |
<commit_before><commit_msg>darray: use larger growth heuristic<commit_after><|endoftext|> |
<commit_before>/*
ESP8266 Simple Service Discovery
Copyright (c) 2015 Hristo Gochkov
Original (Arduino) version by Filippo Sallemi, July 23, 2014.
Can be found at: https://github.com/nomadnt/uSSDP
License (MIT license):
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.
*/
#define LWIP_OPEN_SRC
#include <functional>
#include "ESP8266SSDP.h"
#include "WiFiUdp.h"
#include "debug.h"
extern "C" {
#include "osapi.h"
#include "ets_sys.h"
#include "user_interface.h"
}
#include "lwip/opt.h"
#include "lwip/udp.h"
#include "lwip/inet.h"
#include "lwip/igmp.h"
#include "lwip/mem.h"
#include "include/UdpContext.h"
// #define DEBUG_SSDP Serial
#define SSDP_INTERVAL 1200
#define SSDP_PORT 1900
#define SSDP_METHOD_SIZE 10
#define SSDP_URI_SIZE 2
#define SSDP_BUFFER_SIZE 64
#define SSDP_MULTICAST_TTL 2
static const IPAddress SSDP_MULTICAST_ADDR(239, 255, 255, 250);
static const char* _ssdp_response_template =
"HTTP/1.1 200 OK\r\n"
"EXT:\r\n";
static const char* _ssdp_notify_template =
"NOTIFY * HTTP/1.1\r\n"
"HOST: 239.255.255.250:1900\r\n"
"NTS: ssdp:alive\r\n";
static const char* _ssdp_packet_template =
"%s" // _ssdp_response_template / _ssdp_notify_template
"CACHE-CONTROL: max-age=%u\r\n" // SSDP_INTERVAL
"SERVER: Arduino/1.0 UPNP/1.1 %s/%s\r\n" // _modelName, _modelNumber
"USN: uuid:%s\r\n" // _uuid
"%s: %s\r\n" // "NT" or "ST", _deviceType
"LOCATION: http://%u.%u.%u.%u:%u/%s\r\n" // WiFi.localIP(), _port, _schemaURL
"\r\n";
static const char* _ssdp_schema_template =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/xml\r\n"
"Connection: close\r\n"
"Access-Control-Allow-Origin: *\r\n"
"\r\n"
"<?xml version=\"1.0\"?>"
"<root xmlns=\"urn:schemas-upnp-org:device-1-0\">"
"<specVersion>"
"<major>1</major>"
"<minor>0</minor>"
"</specVersion>"
"<URLBase>http://%u.%u.%u.%u:%u/</URLBase>" // WiFi.localIP(), _port
"<device>"
"<deviceType>%s</deviceType>"
"<friendlyName>%s</friendlyName>"
"<presentationURL>%s</presentationURL>"
"<serialNumber>%s</serialNumber>"
"<modelName>%s</modelName>"
"<modelNumber>%s</modelNumber>"
"<modelURL>%s</modelURL>"
"<manufacturer>%s</manufacturer>"
"<manufacturerURL>%s</manufacturerURL>"
"<UDN>uuid:%s</UDN>"
"</device>"
// "<iconList>"
// "<icon>"
// "<mimetype>image/png</mimetype>"
// "<height>48</height>"
// "<width>48</width>"
// "<depth>24</depth>"
// "<url>icon48.png</url>"
// "</icon>"
// "<icon>"
// "<mimetype>image/png</mimetype>"
// "<height>120</height>"
// "<width>120</width>"
// "<depth>24</depth>"
// "<url>icon120.png</url>"
// "</icon>"
// "</iconList>"
"</root>\r\n"
"\r\n";
struct SSDPTimer {
ETSTimer timer;
};
SSDPClass::SSDPClass() :
_server(0),
_timer(new SSDPTimer),
_port(80),
_ttl(SSDP_MULTICAST_TTL),
_respondToPort(0),
_pending(false),
_delay(0),
_process_time(0),
_notify_time(0)
{
_uuid[0] = '\0';
_modelNumber[0] = '\0';
sprintf(_deviceType, "urn:schemas-upnp-org:device:Basic:1");
_friendlyName[0] = '\0';
_presentationURL[0] = '\0';
_serialNumber[0] = '\0';
_modelName[0] = '\0';
_modelURL[0] = '\0';
_manufacturer[0] = '\0';
_manufacturerURL[0] = '\0';
sprintf(_schemaURL, "ssdp/schema.xml");
}
SSDPClass::~SSDPClass(){
delete _timer;
}
bool SSDPClass::begin(){
_pending = false;
uint32_t chipId = ESP.getChipId();
sprintf(_uuid, "38323636-4558-4dda-9188-cda0e6%02x%02x%02x",
(uint16_t) ((chipId >> 16) & 0xff),
(uint16_t) ((chipId >> 8) & 0xff),
(uint16_t) chipId & 0xff );
#ifdef DEBUG_SSDP
DEBUG_SSDP.printf("SSDP UUID: %s\n", (char *)_uuid);
#endif
if (_server) {
_server->unref();
_server = 0;
}
_server = new UdpContext;
_server->ref();
ip_addr_t ifaddr;
ifaddr.addr = WiFi.localIP();
ip_addr_t multicast_addr;
multicast_addr.addr = (uint32_t) SSDP_MULTICAST_ADDR;
if (igmp_joingroup(&ifaddr, &multicast_addr) != ERR_OK ) {
DEBUGV("SSDP failed to join igmp group");
return false;
}
if (!_server->listen(*IP_ADDR_ANY, SSDP_PORT)) {
return false;
}
_server->setMulticastInterface(ifaddr);
_server->setMulticastTTL(_ttl);
_server->onRx(std::bind(&SSDPClass::_update, this));
if (!_server->connect(multicast_addr, SSDP_PORT)) {
return false;
}
_startTimer();
return true;
}
void SSDPClass::_send(ssdp_method_t method){
char buffer[1460];
uint32_t ip = WiFi.localIP();
int len = snprintf(buffer, sizeof(buffer),
_ssdp_packet_template,
(method == NONE)?_ssdp_response_template:_ssdp_notify_template,
SSDP_INTERVAL,
_modelName, _modelNumber,
(method == NONE)?"ST":"NT",
_deviceType,
_uuid,
IP2STR(&ip), _port, _schemaURL
);
_server->append(buffer, len);
ip_addr_t remoteAddr;
uint16_t remotePort;
if(method == NONE) {
remoteAddr.addr = _respondToAddr;
remotePort = _respondToPort;
#ifdef DEBUG_SSDP
DEBUG_SSDP.print("Sending Response to ");
#endif
} else {
remoteAddr.addr = SSDP_MULTICAST_ADDR;
remotePort = SSDP_PORT;
#ifdef DEBUG_SSDP
DEBUG_SSDP.println("Sending Notify to ");
#endif
}
#ifdef DEBUG_SSDP
DEBUG_SSDP.print(IPAddress(remoteAddr.addr));
DEBUG_SSDP.print(":");
DEBUG_SSDP.println(remotePort);
#endif
_server->send(&remoteAddr, remotePort);
}
void SSDPClass::schema(WiFiClient client){
uint32_t ip = WiFi.localIP();
client.printf(_ssdp_schema_template,
IP2STR(&ip), _port,
_deviceType,
_friendlyName,
_presentationURL,
_serialNumber,
_modelName,
_modelNumber,
_modelURL,
_manufacturer,
_manufacturerURL,
_uuid
);
}
void SSDPClass::_update(){
if(!_pending && _server->next()) {
ssdp_method_t method = NONE;
_respondToAddr = _server->getRemoteAddress();
_respondToPort = _server->getRemotePort();
typedef enum {METHOD, URI, PROTO, KEY, VALUE, ABORT} states;
states state = METHOD;
typedef enum {START, MAN, ST, MX} headers;
headers header = START;
uint8_t cursor = 0;
uint8_t cr = 0;
char buffer[SSDP_BUFFER_SIZE] = {0};
while(_server->getSize() > 0){
char c = _server->read();
(c == '\r' || c == '\n') ? cr++ : cr = 0;
switch(state){
case METHOD:
if(c == ' '){
if(strcmp(buffer, "M-SEARCH") == 0) method = SEARCH;
else if(strcmp(buffer, "NOTIFY") == 0) method = NOTIFY;
if(method == NONE) state = ABORT;
else state = URI;
cursor = 0;
} else if(cursor < SSDP_METHOD_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
break;
case URI:
if(c == ' '){
if(strcmp(buffer, "*")) state = ABORT;
else state = PROTO;
cursor = 0;
} else if(cursor < SSDP_URI_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
break;
case PROTO:
if(cr == 2){ state = KEY; cursor = 0; }
break;
case KEY:
if(cr == 4){ _pending = true; _process_time = millis(); }
else if(c == ' '){ cursor = 0; state = VALUE; }
else if(c != '\r' && c != '\n' && c != ':' && cursor < SSDP_BUFFER_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
break;
case VALUE:
if(cr == 2){
switch(header){
case START:
break;
case MAN:
#ifdef DEBUG_SSDP
DEBUG_SSDP.printf("MAN: %s\n", (char *)buffer);
#endif
break;
case ST:
if(strcmp(buffer, "ssdp:all")){
state = ABORT;
#ifdef DEBUG_SSDP
DEBUG_SSDP.printf("REJECT: %s\n", (char *)buffer);
#endif
}
// if the search type matches our type, we should respond instead of ABORT
if(strcmp(buffer, _deviceType) == 0){
_pending = true;
_process_time = millis();
state = KEY;
}
break;
case MX:
_delay = random(0, atoi(buffer)) * 1000L;
break;
}
if(state != ABORT){ state = KEY; header = START; cursor = 0; }
} else if(c != '\r' && c != '\n'){
if(header == START){
if(strncmp(buffer, "MA", 2) == 0) header = MAN;
else if(strcmp(buffer, "ST") == 0) header = ST;
else if(strcmp(buffer, "MX") == 0) header = MX;
}
if(cursor < SSDP_BUFFER_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
}
break;
case ABORT:
_pending = false; _delay = 0;
break;
}
}
}
if(_pending && (millis() - _process_time) > _delay){
_pending = false; _delay = 0;
_send(NONE);
} else if(_notify_time == 0 || (millis() - _notify_time) > (SSDP_INTERVAL * 1000L)){
_notify_time = millis();
_send(NOTIFY);
}
if (_pending) {
while (_server->next())
_server->flush();
}
}
void SSDPClass::setSchemaURL(const char *url){
strlcpy(_schemaURL, url, sizeof(_schemaURL));
}
void SSDPClass::setHTTPPort(uint16_t port){
_port = port;
}
void SSDPClass::setDeviceType(const char *deviceType){
strlcpy(_deviceType, deviceType, sizeof(_deviceType));
}
void SSDPClass::setName(const char *name){
strlcpy(_friendlyName, name, sizeof(_friendlyName));
}
void SSDPClass::setURL(const char *url){
strlcpy(_presentationURL, url, sizeof(_presentationURL));
}
void SSDPClass::setSerialNumber(const char *serialNumber){
strlcpy(_serialNumber, serialNumber, sizeof(_serialNumber));
}
void SSDPClass::setSerialNumber(const uint32_t serialNumber){
snprintf(_serialNumber, sizeof(uint32_t)*2+1, "%08X", serialNumber);
}
void SSDPClass::setModelName(const char *name){
strlcpy(_modelName, name, sizeof(_modelName));
}
void SSDPClass::setModelNumber(const char *num){
strlcpy(_modelNumber, num, sizeof(_modelNumber));
}
void SSDPClass::setModelURL(const char *url){
strlcpy(_modelURL, url, sizeof(_modelURL));
}
void SSDPClass::setManufacturer(const char *name){
strlcpy(_manufacturer, name, sizeof(_manufacturer));
}
void SSDPClass::setManufacturerURL(const char *url){
strlcpy(_manufacturerURL, url, sizeof(_manufacturerURL));
}
void SSDPClass::setTTL(const uint8_t ttl){
_ttl = ttl;
}
void SSDPClass::_onTimerStatic(SSDPClass* self) {
self->_update();
}
void SSDPClass::_startTimer() {
ETSTimer* tm = &(_timer->timer);
const int interval = 1000;
os_timer_disarm(tm);
os_timer_setfn(tm, reinterpret_cast<ETSTimerFunc*>(&SSDPClass::_onTimerStatic), reinterpret_cast<void*>(this));
os_timer_arm(tm, interval, 1 /* repeat */);
}
SSDPClass SSDP;
<commit_msg>Switch SSDP send arguments around<commit_after>/*
ESP8266 Simple Service Discovery
Copyright (c) 2015 Hristo Gochkov
Original (Arduino) version by Filippo Sallemi, July 23, 2014.
Can be found at: https://github.com/nomadnt/uSSDP
License (MIT license):
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.
*/
#define LWIP_OPEN_SRC
#include <functional>
#include "ESP8266SSDP.h"
#include "WiFiUdp.h"
#include "debug.h"
extern "C" {
#include "osapi.h"
#include "ets_sys.h"
#include "user_interface.h"
}
#include "lwip/opt.h"
#include "lwip/udp.h"
#include "lwip/inet.h"
#include "lwip/igmp.h"
#include "lwip/mem.h"
#include "include/UdpContext.h"
// #define DEBUG_SSDP Serial
#define SSDP_INTERVAL 1200
#define SSDP_PORT 1900
#define SSDP_METHOD_SIZE 10
#define SSDP_URI_SIZE 2
#define SSDP_BUFFER_SIZE 64
#define SSDP_MULTICAST_TTL 2
static const IPAddress SSDP_MULTICAST_ADDR(239, 255, 255, 250);
static const char* _ssdp_response_template =
"HTTP/1.1 200 OK\r\n"
"EXT:\r\n";
static const char* _ssdp_notify_template =
"NOTIFY * HTTP/1.1\r\n"
"HOST: 239.255.255.250:1900\r\n"
"NTS: ssdp:alive\r\n";
static const char* _ssdp_packet_template =
"%s" // _ssdp_response_template / _ssdp_notify_template
"CACHE-CONTROL: max-age=%u\r\n" // SSDP_INTERVAL
"SERVER: Arduino/1.0 UPNP/1.1 %s/%s\r\n" // _modelName, _modelNumber
"USN: uuid:%s\r\n" // _uuid
"%s: %s\r\n" // "NT" or "ST", _deviceType
"LOCATION: http://%u.%u.%u.%u:%u/%s\r\n" // WiFi.localIP(), _port, _schemaURL
"\r\n";
static const char* _ssdp_schema_template =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/xml\r\n"
"Connection: close\r\n"
"Access-Control-Allow-Origin: *\r\n"
"\r\n"
"<?xml version=\"1.0\"?>"
"<root xmlns=\"urn:schemas-upnp-org:device-1-0\">"
"<specVersion>"
"<major>1</major>"
"<minor>0</minor>"
"</specVersion>"
"<URLBase>http://%u.%u.%u.%u:%u/</URLBase>" // WiFi.localIP(), _port
"<device>"
"<deviceType>%s</deviceType>"
"<friendlyName>%s</friendlyName>"
"<presentationURL>%s</presentationURL>"
"<serialNumber>%s</serialNumber>"
"<modelName>%s</modelName>"
"<modelNumber>%s</modelNumber>"
"<modelURL>%s</modelURL>"
"<manufacturer>%s</manufacturer>"
"<manufacturerURL>%s</manufacturerURL>"
"<UDN>uuid:%s</UDN>"
"</device>"
// "<iconList>"
// "<icon>"
// "<mimetype>image/png</mimetype>"
// "<height>48</height>"
// "<width>48</width>"
// "<depth>24</depth>"
// "<url>icon48.png</url>"
// "</icon>"
// "<icon>"
// "<mimetype>image/png</mimetype>"
// "<height>120</height>"
// "<width>120</width>"
// "<depth>24</depth>"
// "<url>icon120.png</url>"
// "</icon>"
// "</iconList>"
"</root>\r\n"
"\r\n";
struct SSDPTimer {
ETSTimer timer;
};
SSDPClass::SSDPClass() :
_server(0),
_timer(new SSDPTimer),
_port(80),
_ttl(SSDP_MULTICAST_TTL),
_respondToPort(0),
_pending(false),
_delay(0),
_process_time(0),
_notify_time(0)
{
_uuid[0] = '\0';
_modelNumber[0] = '\0';
sprintf(_deviceType, "urn:schemas-upnp-org:device:Basic:1");
_friendlyName[0] = '\0';
_presentationURL[0] = '\0';
_serialNumber[0] = '\0';
_modelName[0] = '\0';
_modelURL[0] = '\0';
_manufacturer[0] = '\0';
_manufacturerURL[0] = '\0';
sprintf(_schemaURL, "ssdp/schema.xml");
}
SSDPClass::~SSDPClass(){
delete _timer;
}
bool SSDPClass::begin(){
_pending = false;
uint32_t chipId = ESP.getChipId();
sprintf(_uuid, "38323636-4558-4dda-9188-cda0e6%02x%02x%02x",
(uint16_t) ((chipId >> 16) & 0xff),
(uint16_t) ((chipId >> 8) & 0xff),
(uint16_t) chipId & 0xff );
#ifdef DEBUG_SSDP
DEBUG_SSDP.printf("SSDP UUID: %s\n", (char *)_uuid);
#endif
if (_server) {
_server->unref();
_server = 0;
}
_server = new UdpContext;
_server->ref();
ip_addr_t ifaddr;
ifaddr.addr = WiFi.localIP();
ip_addr_t multicast_addr;
multicast_addr.addr = (uint32_t) SSDP_MULTICAST_ADDR;
if (igmp_joingroup(&ifaddr, &multicast_addr) != ERR_OK ) {
DEBUGV("SSDP failed to join igmp group");
return false;
}
if (!_server->listen(*IP_ADDR_ANY, SSDP_PORT)) {
return false;
}
_server->setMulticastInterface(ifaddr);
_server->setMulticastTTL(_ttl);
_server->onRx(std::bind(&SSDPClass::_update, this));
if (!_server->connect(multicast_addr, SSDP_PORT)) {
return false;
}
_startTimer();
return true;
}
void SSDPClass::_send(ssdp_method_t method){
char buffer[1460];
uint32_t ip = WiFi.localIP();
int len = snprintf(buffer, sizeof(buffer),
_ssdp_packet_template,
(method == NONE)?_ssdp_response_template:_ssdp_notify_template,
SSDP_INTERVAL,
_modelName, _modelNumber,
_uuid,
(method == NONE)?"ST":"NT",
_deviceType,
IP2STR(&ip), _port, _schemaURL
);
_server->append(buffer, len);
ip_addr_t remoteAddr;
uint16_t remotePort;
if(method == NONE) {
remoteAddr.addr = _respondToAddr;
remotePort = _respondToPort;
#ifdef DEBUG_SSDP
DEBUG_SSDP.print("Sending Response to ");
#endif
} else {
remoteAddr.addr = SSDP_MULTICAST_ADDR;
remotePort = SSDP_PORT;
#ifdef DEBUG_SSDP
DEBUG_SSDP.println("Sending Notify to ");
#endif
}
#ifdef DEBUG_SSDP
DEBUG_SSDP.print(IPAddress(remoteAddr.addr));
DEBUG_SSDP.print(":");
DEBUG_SSDP.println(remotePort);
#endif
_server->send(&remoteAddr, remotePort);
}
void SSDPClass::schema(WiFiClient client){
uint32_t ip = WiFi.localIP();
client.printf(_ssdp_schema_template,
IP2STR(&ip), _port,
_deviceType,
_friendlyName,
_presentationURL,
_serialNumber,
_modelName,
_modelNumber,
_modelURL,
_manufacturer,
_manufacturerURL,
_uuid
);
}
void SSDPClass::_update(){
if(!_pending && _server->next()) {
ssdp_method_t method = NONE;
_respondToAddr = _server->getRemoteAddress();
_respondToPort = _server->getRemotePort();
typedef enum {METHOD, URI, PROTO, KEY, VALUE, ABORT} states;
states state = METHOD;
typedef enum {START, MAN, ST, MX} headers;
headers header = START;
uint8_t cursor = 0;
uint8_t cr = 0;
char buffer[SSDP_BUFFER_SIZE] = {0};
while(_server->getSize() > 0){
char c = _server->read();
(c == '\r' || c == '\n') ? cr++ : cr = 0;
switch(state){
case METHOD:
if(c == ' '){
if(strcmp(buffer, "M-SEARCH") == 0) method = SEARCH;
else if(strcmp(buffer, "NOTIFY") == 0) method = NOTIFY;
if(method == NONE) state = ABORT;
else state = URI;
cursor = 0;
} else if(cursor < SSDP_METHOD_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
break;
case URI:
if(c == ' '){
if(strcmp(buffer, "*")) state = ABORT;
else state = PROTO;
cursor = 0;
} else if(cursor < SSDP_URI_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
break;
case PROTO:
if(cr == 2){ state = KEY; cursor = 0; }
break;
case KEY:
if(cr == 4){ _pending = true; _process_time = millis(); }
else if(c == ' '){ cursor = 0; state = VALUE; }
else if(c != '\r' && c != '\n' && c != ':' && cursor < SSDP_BUFFER_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
break;
case VALUE:
if(cr == 2){
switch(header){
case START:
break;
case MAN:
#ifdef DEBUG_SSDP
DEBUG_SSDP.printf("MAN: %s\n", (char *)buffer);
#endif
break;
case ST:
if(strcmp(buffer, "ssdp:all")){
state = ABORT;
#ifdef DEBUG_SSDP
DEBUG_SSDP.printf("REJECT: %s\n", (char *)buffer);
#endif
}
// if the search type matches our type, we should respond instead of ABORT
if(strcmp(buffer, _deviceType) == 0){
_pending = true;
_process_time = millis();
state = KEY;
}
break;
case MX:
_delay = random(0, atoi(buffer)) * 1000L;
break;
}
if(state != ABORT){ state = KEY; header = START; cursor = 0; }
} else if(c != '\r' && c != '\n'){
if(header == START){
if(strncmp(buffer, "MA", 2) == 0) header = MAN;
else if(strcmp(buffer, "ST") == 0) header = ST;
else if(strcmp(buffer, "MX") == 0) header = MX;
}
if(cursor < SSDP_BUFFER_SIZE - 1){ buffer[cursor++] = c; buffer[cursor] = '\0'; }
}
break;
case ABORT:
_pending = false; _delay = 0;
break;
}
}
}
if(_pending && (millis() - _process_time) > _delay){
_pending = false; _delay = 0;
_send(NONE);
} else if(_notify_time == 0 || (millis() - _notify_time) > (SSDP_INTERVAL * 1000L)){
_notify_time = millis();
_send(NOTIFY);
}
if (_pending) {
while (_server->next())
_server->flush();
}
}
void SSDPClass::setSchemaURL(const char *url){
strlcpy(_schemaURL, url, sizeof(_schemaURL));
}
void SSDPClass::setHTTPPort(uint16_t port){
_port = port;
}
void SSDPClass::setDeviceType(const char *deviceType){
strlcpy(_deviceType, deviceType, sizeof(_deviceType));
}
void SSDPClass::setName(const char *name){
strlcpy(_friendlyName, name, sizeof(_friendlyName));
}
void SSDPClass::setURL(const char *url){
strlcpy(_presentationURL, url, sizeof(_presentationURL));
}
void SSDPClass::setSerialNumber(const char *serialNumber){
strlcpy(_serialNumber, serialNumber, sizeof(_serialNumber));
}
void SSDPClass::setSerialNumber(const uint32_t serialNumber){
snprintf(_serialNumber, sizeof(uint32_t)*2+1, "%08X", serialNumber);
}
void SSDPClass::setModelName(const char *name){
strlcpy(_modelName, name, sizeof(_modelName));
}
void SSDPClass::setModelNumber(const char *num){
strlcpy(_modelNumber, num, sizeof(_modelNumber));
}
void SSDPClass::setModelURL(const char *url){
strlcpy(_modelURL, url, sizeof(_modelURL));
}
void SSDPClass::setManufacturer(const char *name){
strlcpy(_manufacturer, name, sizeof(_manufacturer));
}
void SSDPClass::setManufacturerURL(const char *url){
strlcpy(_manufacturerURL, url, sizeof(_manufacturerURL));
}
void SSDPClass::setTTL(const uint8_t ttl){
_ttl = ttl;
}
void SSDPClass::_onTimerStatic(SSDPClass* self) {
self->_update();
}
void SSDPClass::_startTimer() {
ETSTimer* tm = &(_timer->timer);
const int interval = 1000;
os_timer_disarm(tm);
os_timer_setfn(tm, reinterpret_cast<ETSTimerFunc*>(&SSDPClass::_onTimerStatic), reinterpret_cast<void*>(this));
os_timer_arm(tm, interval, 1 /* repeat */);
}
SSDPClass SSDP;
<|endoftext|> |
<commit_before>//
// main.cpp
// Euchre
//
// Created by Dillon Hammond on 9/12/14.
// Copyright (c) 2014 Learning. All rights reserved.
//
#define GLEW_STATIC
#include "GL/glew.h"
#include <SDL2/SDL.h>
#include "SOIL.h"
#define GLM_FORCE_RADIANS
#include "glm.hpp"
#include <iostream>
#include <fstream>
GLuint LoadShaders(const char* vertex_file_path, const char* fragment_file_path) {
// Create the shaders
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
// Read the Vertex Shader code from the file
std::string VertexShaderCode;
std::ifstream VertexShaderStream;
VertexShaderStream.open(vertex_file_path);
if(VertexShaderStream.is_open())
{
std::string Line = "";
while(getline(VertexShaderStream, Line))
VertexShaderCode += "\n" + Line;
VertexShaderStream.close();
}
// Read the Fragment Shader code from the file
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in);
if(FragmentShaderStream.is_open()){
std::string Line = "";
while(getline(FragmentShaderStream, Line))
FragmentShaderCode += "\n" + Line;
FragmentShaderStream.close();
}
GLint Result;
// Compile Vertex Shader
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
glCompileShader(VertexShaderID);
glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
if (Result == GL_TRUE) {
std::cout << "NOOOV" << std::endl;
std::cout << VertexSourcePointer << std::endl;
}
// Compile Fragment Shader
char const * FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
glCompileShader(FragmentShaderID);
glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
if (Result == GL_TRUE) {
std::cout << "NOOOF" << std::endl;
std::cout << FragmentSourcePointer << std::endl;
}
// Link the program
GLuint ProgramID = glCreateProgram();
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return ProgramID;
}
SDL_Window* createWindow(const char* title, int x, int y, int w, int h, Uint32 flags) {
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_Window *window = SDL_CreateWindow(title, x, y, w, h, flags);
return window;
}
void LoadTextures(GLuint textures[], const char* filename, const GLchar* texName, GLuint shaderProgram, int texNum) {
int width, height;
unsigned char* image;
glActiveTexture(GL_TEXTURE0 + texNum);
glBindTexture(GL_TEXTURE_2D, textures[texNum]);
image = SOIL_load_image(filename, &width, &height, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
SOIL_free_image_data(image);
glUniform1i(glGetUniformLocation(shaderProgram, "backGround"), texNum);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
int main() {
SDL_Window* window = createWindow("Euchre", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
SDL_GLContext context = SDL_GL_CreateContext(window);
// Initialize GLEW
glewExperimental = GL_TRUE;
glewInit();
// Initialize Depth Testing
glEnable(GL_DEPTH_TEST);
// Create Vertex Array Object
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// Create a Vertex Buffer Object and copy the vertex data to it
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
GLuint shaderProgram = LoadShaders("./Resources/vertexShader.txt", "./Resources/fragmentShader.txt");
glUseProgram(shaderProgram);
GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord");
glEnableVertexAttribArray(texAttrib);
glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), reinterpret_cast<void*>(6 * sizeof(GLfloat)));
// Load texture
GLuint textures[1];
glGenTextures(1, textures);
LoadTextures(textures, "./Resources/Background.png", "backGround", shaderProgram, 0);
SDL_Event windowEvent;
while (true) {
if (SDL_PollEvent(&windowEvent)) {
if (windowEvent.type == SDL_QUIT) {
break;
}
}
// Clear screen to black
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
SDL_GL_SwapWindow(window);
}
glDeleteTextures(2, textures);
glDeleteProgram(shaderProgram);
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
SDL_GL_DeleteContext(context);
return 0;
}<commit_msg>Draws colored rectangle<commit_after>//
// main.cpp
// Euchre
//
// Created by Dillon Hammond on 9/12/14.
// Copyright (c) 2014 Learning. All rights reserved.
//
#define GLEW_STATIC
#include "GL/glew.h"
#include <SDL2/SDL.h>
#include "SOIL.h"
#define GLM_FORCE_RADIANS
#include "glm.hpp"
#include <iostream>
#include <fstream>
GLuint LoadShaders(const char* vertex_file_path, const char* fragment_file_path) {
// Create the shaders
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
// Read the Vertex Shader code from the file
std::string VertexShaderCode;
std::ifstream VertexShaderStream;
VertexShaderStream.open(vertex_file_path);
if(VertexShaderStream.is_open())
{
std::string Line = "";
while(getline(VertexShaderStream, Line))
VertexShaderCode += "\n" + Line;
VertexShaderStream.close();
}
// Read the Fragment Shader code from the file
std::string FragmentShaderCode;
std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in);
if(FragmentShaderStream.is_open()){
std::string Line = "";
while(getline(FragmentShaderStream, Line))
FragmentShaderCode += "\n" + Line;
FragmentShaderStream.close();
}
GLint Result;
// Compile Vertex Shader
char const * VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
glCompileShader(VertexShaderID);
glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
if (Result == GL_FALSE) {
std::cout << "NOOOV" << std::endl;
std::cout << VertexSourcePointer << std::endl;
}
// Compile Fragment Shader
char const * FragmentSourcePointer = FragmentShaderCode.c_str();
glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
glCompileShader(FragmentShaderID);
glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
if (Result == GL_FALSE) {
std::cout << "NOOOF" << std::endl;
std::cout << FragmentSourcePointer << std::endl;
}
// Link the program
GLuint ProgramID = glCreateProgram();
glAttachShader(ProgramID, VertexShaderID);
glAttachShader(ProgramID, FragmentShaderID);
glLinkProgram(ProgramID);
glDeleteShader(VertexShaderID);
glDeleteShader(FragmentShaderID);
return ProgramID;
}
SDL_Window* createWindow(const char* title, int x, int y, int w, int h, Uint32 flags) {
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_Window *window = SDL_CreateWindow(title, x, y, w, h, flags);
return window;
}
void LoadTextures(GLuint textures[], const char* filename, const GLchar* texName, GLuint shaderProgram, int texNum) {
int width, height;
unsigned char* image;
glActiveTexture(GL_TEXTURE0 + texNum);
glBindTexture(GL_TEXTURE_2D, textures[texNum]);
image = SOIL_load_image(filename, &width, &height, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
SOIL_free_image_data(image);
glUniform1i(glGetUniformLocation(shaderProgram, "backGround"), texNum);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
int main() {
SDL_Window* window = createWindow("Euchre", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
SDL_GLContext context = SDL_GL_CreateContext(window);
// Initialize GLEW
glewExperimental = GL_TRUE;
glewInit();
// Initialize Depth Testing
glEnable(GL_DEPTH_TEST);
// Create Vertex Array Object
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// Create a Vertex Buffer Object and copy the vertex data to it
GLuint vbo;
glGenBuffers(1, &vbo);
GLfloat vertices[] = {
-0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // Top-left
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // Top-right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
-0.5f, -0.5f, 1.0f, 1.0f, 1.0f // Bottom-left
};
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Create an element array
GLuint ebo;
glGenBuffers(1, &ebo);
GLuint elements[] = {
0, 1, 2,
2, 3, 0
};
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
GLuint shaderProgram = LoadShaders("./Resources/vertexShader.txt", "./Resources/fragmentShader.txt");
glUseProgram(shaderProgram);
// Specify the layout of the vertex data
GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), 0);
GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
glEnableVertexAttribArray(colAttrib);
glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (void*)(2 * sizeof(GLfloat)));
SDL_Event windowEvent;
while (true) {
if (SDL_PollEvent(&windowEvent)) {
if (windowEvent.type == SDL_QUIT) {
break;
}
}
// Clear the screen to black
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
// Draw a rectangle from the 2 triangles using 6 indices
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
SDL_GL_SwapWindow(window);
}
glDeleteProgram(shaderProgram);
glDeleteBuffers(1, &ebo);
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
SDL_GL_DeleteContext(context);
return 0;
}<|endoftext|> |
<commit_before><commit_msg>Make Future<T>::delayed complete on correct executor 2/n: Apply codemod future delayed to delayed unsafe<commit_after><|endoftext|> |
<commit_before>#include "pgDal.h"
#include <capnp/message.h>
#include <capnp/pretty-print.h>
#include <kj/debug.h>
#include <iostream>
#include "fact_util.h"
namespace holmes {
void PgDAL::initDB() {
pqxx::work work(conn);
work.exec("create schema if not exists facts");
auto res = work.exec("select table_name, udt_name from information_schema.columns where table_schema = 'facts' ORDER BY table_name, ordinal_position");
work.commit();
for (auto line : res) {
std::string name = line[0].c_str();
if (types.find(name) == types.end()) {
std::vector<Holmes::HType> sig;
types[name] = sig;
}
Holmes::HType typ;
std::string type_string = line[1].c_str();
if (type_string == "int8") {
typ = Holmes::HType::ADDR;
} else if (type_string == "varchar") {
typ = Holmes::HType::STRING;
} else if (type_string == "bytea") {
typ = Holmes::HType::BLOB;
} else if (type_string == "jsonb") {
typ = Holmes::HType::JSON;
} else {
std::cerr << "Type parse failure: " << type_string << std::endl;
exit(1);
}
types[name].push_back(typ);
}
for (auto type : types) {
registerPrepared(type.first, type.second.size());
}
}
void PgDAL::registerPrepared(std::string name, size_t n) {
std::string argVals = "(";
for (size_t i = 1; i <= n; i++) {
argVals += "$" + std::to_string(i);
if (i != n) {
argVals += ", ";
} else {
argVals += ")";
}
}
conn.prepare(name + ".insert", "INSERT INTO facts." + name + " VALUES " + argVals);
}
size_t PgDAL::setFacts(capnp::List<Holmes::Fact>::Reader facts) {
std::lock_guard<std::mutex> lock(mutex);
pqxx::work work(conn);
std::vector<pqxx::result> res;
for (auto fact : facts) {
if (!typecheck(types, fact)) {
LOG(ERROR) << "Bad fact: " << kj::str(capnp::prettyPrint(fact)).cStr();
throw "Fact Type Error";
}
std::string name = fact.getFactName();
auto query = work.prepared(name + ".insert");
for (auto arg : fact.getArgs()) {
switch (arg.which()) {
case Holmes::Val::JSON_VAL:
query(std::string(arg.getJsonVal()));
break;
case Holmes::Val::STRING_VAL:
query(std::string(arg.getStringVal()));
break;
case Holmes::Val::ADDR_VAL:
//PgSQL is bad, and only has a signed int type
query((int64_t)arg.getAddrVal());
break;
case Holmes::Val::BLOB_VAL:
capnp::Data::Reader data = arg.getBlobVal();
pqxx::binarystring blob(data.begin(), data.size());
query(blob);
break;
}
}
res.push_back(query.exec());
}
work.commit();
size_t affected = 0;
for (auto r : res) {
affected += r.affected_rows();
}
return affected;
}
std::string htype_to_sqltype(Holmes::HType hType) {
switch (hType) {
case Holmes::HType::JSON:
return "jsonb";
case Holmes::HType::STRING:
return "varchar";
case Holmes::HType::ADDR:
return "bigint";
case Holmes::HType::BLOB:
return "bytea";
}
return "unknown";
}
bool valid_name(std::string s) {
for (auto c : s) {
if (c == '_') {
continue;
}
if ((c >= 'a') && (c <= 'z')) {
continue;
}
if ((c >= '0') && (c <= '9')) {
continue;
}
return false;
}
return true;
}
bool PgDAL::addType(std::string name, capnp::List<Holmes::HType>::Reader argTypes) {
std::lock_guard<std::mutex> lock(mutex);
//We're using this for a table name, so we have restrictions
if (!valid_name(name)) {
return false;
}
auto itt = types.find(name);
if (itt != types.end()) {
if (argTypes.size() != itt->second.size()) {
return false;
}
for (size_t i = 0; i < argTypes.size(); i++) {
if (argTypes[i] != itt->second[i]) {
return false;
}
}
return true;
} else {
std::vector<Holmes::HType> sig;
std::string tableSpec = "(";
for (size_t i = 0; i < argTypes.size(); i++) {
tableSpec += "arg" + std::to_string(i) + " " + htype_to_sqltype(argTypes[i]);
sig.push_back(argTypes[i]);
if (i == argTypes.size() - 1) {
tableSpec += ")";
} else {
tableSpec += ", ";
}
}
pqxx::work work(conn);
work.exec("CREATE TABLE facts." + name + " " + tableSpec);
work.commit();
types[name] = sig;
registerPrepared(name, sig.size());
return true;
}
}
std::string quoteVal(pqxx::work& w, Holmes::Val::Reader v) {
switch (v.which()) {
case Holmes::Val::JSON_VAL:
return w.quote(std::string(v.getJsonVal()));
case Holmes::Val::STRING_VAL:
return w.quote(std::string(v.getStringVal()));
case Holmes::Val::BLOB_VAL:
//You probably don't want to do this... but for completeness sake
return w.quote_raw(v.getBlobVal().begin(), v.getBlobVal().size());
case Holmes::Val::ADDR_VAL:
//Postgres doesn't support uint64_t
return w.quote((int64_t)v.getAddrVal());
}
throw "Failed to quote value";
}
void buildFromDB(Holmes::HType typ, Holmes::Val::Builder val, pqxx::result::field dbVal) {
switch (typ) {
case Holmes::HType::JSON:
val.setJsonVal(dbVal.as<std::string>());
break;
case Holmes::HType::ADDR:
val.setAddrVal(dbVal.as<int64_t>());
break;
case Holmes::HType::STRING:
val.setStringVal(dbVal.as<std::string>());
break;
case Holmes::HType::BLOB:
pqxx::binarystring bs(dbVal);
auto bb = val.initBlobVal(bs.size());
for (size_t k = 0; k < bs.size(); ++k) {
bb[k] = bs[k];
}
}
}
std::vector<DAL::Context> PgDAL::getFacts(
capnp::List<Holmes::FactTemplate>::Reader clauses) {
std::lock_guard<std::mutex> lock(mutex);
pqxx::work work(conn);
std::vector<std::string> whereClause; //Concrete values
std::vector<std::string> bindName;
std::vector<Holmes::HType> bindType;
std::vector<bool> bindAll;
std::string query = "";
for (auto itc = clauses.begin(); itc != clauses.end(); ++itc) {
std::string tableName = "facts.";
tableName += itc->getFactName();
if (itc == clauses.begin()) {
query += " FROM ";
} else if (itc != clauses.end()) {
query += " JOIN ";
}
query += tableName;
if (itc != clauses.begin()) {
query += " ON ";
}
auto args = itc->getArgs();
bool onClause = true;
for (size_t i = 0; i < args.size(); ++i) {
switch (args[i].which()) {
case Holmes::TemplateVal::EXACT_VAL:
whereClause.push_back(tableName + ".arg" + std::to_string(i) + "=" + quoteVal(work, args[i].getExactVal()));
break;
case Holmes::TemplateVal::BOUND:
case Holmes::TemplateVal::FORALL:
{
uint32_t var;
if (args[i].which() == Holmes::TemplateVal::BOUND) {
var = args[i].getBound();
} else {
var = args[i].getForall();
}
auto argName = tableName + ".arg" + std::to_string(i);
if (var >= bindName.size()) {
//The variable is mentioned for the first time, this is its
//cannonical name
bindName.push_back(argName);
bindType.push_back(types[itc->getFactName()][i]);
bindAll.push_back(args[i].which() == Holmes::TemplateVal::FORALL);
} else {
//This is a repeat, it needs to be unified
std::string cond = argName + "=" + bindName[var];
if (itc == clauses.begin()) {
//First table has no on clause, stash these in the where clause
whereClause.push_back(cond);
} else {
if (onClause) {
onClause = false;
} else {
query += " AND ";
}
query += cond + " ";
}
}
}
break;
case Holmes::TemplateVal::UNBOUND:
break;
}
}
}
for (auto itw = whereClause.begin(); itw != whereClause.end(); ++itw) {
if (itw == whereClause.begin()) {
query += " WHERE ";
} else {
query += " AND ";
}
query += *itw;
}
std::string select = "SELECT ";
std::string groupBy = " GROUP BY ";
for (size_t i = 0; i < bindName.size(); i++) {
if (bindAll[i]) {
select += "array_agg(" + bindName[i] + ")";
} else {
select += bindName[i];
groupBy += bindName[i] + ",";
}
if (i + 1 < bindName.size()) {
select += ", ";
}
}
groupBy.erase(groupBy.size()-1);
query = select + query + groupBy;
DLOG(INFO) << "Executing join query: " << query;
auto res = work.exec(query);
work.commit();
DLOG(INFO) << "Query complete";
std::vector<Context> ctxs;
for (auto soln : res) {
Context ctx;
for (int i = 0; i < bindType.size(); i++) {
auto val = ctx.init();
if (bindAll[i]) {
//This is an array, and we need to make a list and bind it all.
//For now, let's return a string just to show it working
buildFromDB(Holmes::HType::STRING, val, soln[i]);
} else {
buildFromDB(bindType[i], val, soln[i]);
}
}
ctxs.push_back(ctx);
}
return ctxs;
}
}
<commit_msg>Allow multiple instances of same fact<commit_after>#include "pgDal.h"
#include <capnp/message.h>
#include <capnp/pretty-print.h>
#include <kj/debug.h>
#include <iostream>
#include "fact_util.h"
namespace holmes {
void PgDAL::initDB() {
pqxx::work work(conn);
work.exec("create schema if not exists facts");
auto res = work.exec("select table_name, udt_name from information_schema.columns where table_schema = 'facts' ORDER BY table_name, ordinal_position");
work.commit();
for (auto line : res) {
std::string name = line[0].c_str();
if (types.find(name) == types.end()) {
std::vector<Holmes::HType> sig;
types[name] = sig;
}
Holmes::HType typ;
std::string type_string = line[1].c_str();
if (type_string == "int8") {
typ = Holmes::HType::ADDR;
} else if (type_string == "varchar") {
typ = Holmes::HType::STRING;
} else if (type_string == "bytea") {
typ = Holmes::HType::BLOB;
} else if (type_string == "jsonb") {
typ = Holmes::HType::JSON;
} else {
std::cerr << "Type parse failure: " << type_string << std::endl;
exit(1);
}
types[name].push_back(typ);
}
for (auto type : types) {
registerPrepared(type.first, type.second.size());
}
}
void PgDAL::registerPrepared(std::string name, size_t n) {
std::string argVals = "(";
for (size_t i = 1; i <= n; i++) {
argVals += "$" + std::to_string(i);
if (i != n) {
argVals += ", ";
} else {
argVals += ")";
}
}
conn.prepare(name + ".insert", "INSERT INTO facts." + name + " VALUES " + argVals);
}
size_t PgDAL::setFacts(capnp::List<Holmes::Fact>::Reader facts) {
std::lock_guard<std::mutex> lock(mutex);
pqxx::work work(conn);
std::vector<pqxx::result> res;
for (auto fact : facts) {
if (!typecheck(types, fact)) {
LOG(ERROR) << "Bad fact: " << kj::str(capnp::prettyPrint(fact)).cStr();
throw "Fact Type Error";
}
std::string name = fact.getFactName();
auto query = work.prepared(name + ".insert");
for (auto arg : fact.getArgs()) {
switch (arg.which()) {
case Holmes::Val::JSON_VAL:
query(std::string(arg.getJsonVal()));
break;
case Holmes::Val::STRING_VAL:
query(std::string(arg.getStringVal()));
break;
case Holmes::Val::ADDR_VAL:
//PgSQL is bad, and only has a signed int type
query((int64_t)arg.getAddrVal());
break;
case Holmes::Val::BLOB_VAL:
capnp::Data::Reader data = arg.getBlobVal();
pqxx::binarystring blob(data.begin(), data.size());
query(blob);
break;
}
}
res.push_back(query.exec());
}
work.commit();
size_t affected = 0;
for (auto r : res) {
affected += r.affected_rows();
}
return affected;
}
std::string htype_to_sqltype(Holmes::HType hType) {
switch (hType) {
case Holmes::HType::JSON:
return "jsonb";
case Holmes::HType::STRING:
return "varchar";
case Holmes::HType::ADDR:
return "bigint";
case Holmes::HType::BLOB:
return "bytea";
}
return "unknown";
}
bool valid_name(std::string s) {
for (auto c : s) {
if (c == '_') {
continue;
}
if ((c >= 'a') && (c <= 'z')) {
continue;
}
if ((c >= '0') && (c <= '9')) {
continue;
}
return false;
}
return true;
}
bool PgDAL::addType(std::string name, capnp::List<Holmes::HType>::Reader argTypes) {
std::lock_guard<std::mutex> lock(mutex);
//We're using this for a table name, so we have restrictions
if (!valid_name(name)) {
return false;
}
auto itt = types.find(name);
if (itt != types.end()) {
if (argTypes.size() != itt->second.size()) {
return false;
}
for (size_t i = 0; i < argTypes.size(); i++) {
if (argTypes[i] != itt->second[i]) {
return false;
}
}
return true;
} else {
std::vector<Holmes::HType> sig;
std::string tableSpec = "(";
for (size_t i = 0; i < argTypes.size(); i++) {
tableSpec += "arg" + std::to_string(i) + " " + htype_to_sqltype(argTypes[i]);
sig.push_back(argTypes[i]);
if (i == argTypes.size() - 1) {
tableSpec += ")";
} else {
tableSpec += ", ";
}
}
pqxx::work work(conn);
work.exec("CREATE TABLE facts." + name + " " + tableSpec);
work.commit();
types[name] = sig;
registerPrepared(name, sig.size());
return true;
}
}
std::string quoteVal(pqxx::work& w, Holmes::Val::Reader v) {
switch (v.which()) {
case Holmes::Val::JSON_VAL:
return w.quote(std::string(v.getJsonVal()));
case Holmes::Val::STRING_VAL:
return w.quote(std::string(v.getStringVal()));
case Holmes::Val::BLOB_VAL:
//You probably don't want to do this... but for completeness sake
return w.quote_raw(v.getBlobVal().begin(), v.getBlobVal().size());
case Holmes::Val::ADDR_VAL:
//Postgres doesn't support uint64_t
return w.quote((int64_t)v.getAddrVal());
}
throw "Failed to quote value";
}
void buildFromDB(Holmes::HType typ, Holmes::Val::Builder val, pqxx::result::field dbVal) {
switch (typ) {
case Holmes::HType::JSON:
val.setJsonVal(dbVal.as<std::string>());
break;
case Holmes::HType::ADDR:
val.setAddrVal(dbVal.as<int64_t>());
break;
case Holmes::HType::STRING:
val.setStringVal(dbVal.as<std::string>());
break;
case Holmes::HType::BLOB:
pqxx::binarystring bs(dbVal);
auto bb = val.initBlobVal(bs.size());
for (size_t k = 0; k < bs.size(); ++k) {
bb[k] = bs[k];
}
}
}
std::vector<DAL::Context> PgDAL::getFacts(
capnp::List<Holmes::FactTemplate>::Reader clauses) {
std::lock_guard<std::mutex> lock(mutex);
pqxx::work work(conn);
std::vector<std::string> whereClause; //Concrete values
std::vector<std::string> bindName;
std::vector<Holmes::HType> bindType;
std::vector<bool> bindAll;
std::string query = "";
size_t clauseN = 0;
for (auto itc = clauses.begin(); itc != clauses.end(); ++itc, ++clauseN) {
std::string tableName = "facts.";
tableName += itc->getFactName();
std::string tableVar = "tbl" + std::to_string(clauseN);
if (itc == clauses.begin()) {
query += " FROM ";
} else if (itc != clauses.end()) {
query += " JOIN ";
}
query += tableName + " " + tableVar;
if (itc != clauses.begin()) {
query += " ON ";
}
auto args = itc->getArgs();
bool onClause = true;
for (size_t i = 0; i < args.size(); ++i) {
switch (args[i].which()) {
case Holmes::TemplateVal::EXACT_VAL:
whereClause.push_back(tableVar + ".arg" + std::to_string(i) + "=" + quoteVal(work, args[i].getExactVal()));
break;
case Holmes::TemplateVal::BOUND:
case Holmes::TemplateVal::FORALL:
{
uint32_t var;
if (args[i].which() == Holmes::TemplateVal::BOUND) {
var = args[i].getBound();
} else {
var = args[i].getForall();
}
auto argName = tableVar + ".arg" + std::to_string(i);
if (var >= bindName.size()) {
//The variable is mentioned for the first time, this is its
//cannonical name
bindName.push_back(argName);
bindType.push_back(types[itc->getFactName()][i]);
bindAll.push_back(args[i].which() == Holmes::TemplateVal::FORALL);
} else {
//This is a repeat, it needs to be unified
std::string cond = argName + "=" + bindName[var];
if (itc == clauses.begin()) {
//First table has no on clause, stash these in the where clause
whereClause.push_back(cond);
} else {
if (onClause) {
onClause = false;
} else {
query += " AND ";
}
query += cond + " ";
}
}
}
break;
case Holmes::TemplateVal::UNBOUND:
break;
}
}
}
for (auto itw = whereClause.begin(); itw != whereClause.end(); ++itw) {
if (itw == whereClause.begin()) {
query += " WHERE ";
} else {
query += " AND ";
}
query += *itw;
}
std::string select = "SELECT ";
std::string groupBy = " GROUP BY ";
for (size_t i = 0; i < bindName.size(); i++) {
if (bindAll[i]) {
select += "array_agg(" + bindName[i] + ")";
} else {
select += bindName[i];
groupBy += bindName[i] + ",";
}
if (i + 1 < bindName.size()) {
select += ", ";
}
}
groupBy.erase(groupBy.size()-1);
query = select + query + groupBy;
DLOG(INFO) << "Executing join query: " << query;
auto res = work.exec(query);
work.commit();
DLOG(INFO) << "Query complete";
std::vector<Context> ctxs;
for (auto soln : res) {
Context ctx;
for (int i = 0; i < bindType.size(); i++) {
auto val = ctx.init();
if (bindAll[i]) {
//This is an array, and we need to make a list and bind it all.
//For now, let's return a string just to show it working
buildFromDB(Holmes::HType::STRING, val, soln[i]);
} else {
buildFromDB(bindType[i], val, soln[i]);
}
}
ctxs.push_back(ctx);
}
return ctxs;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019-2020 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 <chainparams.h>
#include <coins.h>
#include <consensus/tx_check.h>
#include <consensus/tx_verify.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <core_memusage.h>
#include <policy/policy.h>
#include <policy/settings.h>
#include <primitives/transaction.h>
#include <streams.h>
#include <test/fuzz/fuzz.h>
#include <univalue.h>
#include <util/rbf.h>
#include <validation.h>
#include <version.h>
#include <cassert>
void initialize_transaction()
{
SelectParams(CBaseChainParams::REGTEST);
}
FUZZ_TARGET_INIT(transaction, initialize_transaction)
{
CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
try {
int nVersion;
ds >> nVersion;
ds.SetVersion(nVersion);
} catch (const std::ios_base::failure&) {
return;
}
bool valid_tx = true;
const CTransaction tx = [&] {
try {
return CTransaction(deserialize, ds);
} catch (const std::ios_base::failure&) {
valid_tx = false;
return CTransaction{CMutableTransaction{}};
}
}();
bool valid_mutable_tx = true;
CDataStream ds_mtx(buffer, SER_NETWORK, INIT_PROTO_VERSION);
CMutableTransaction mutable_tx;
try {
int nVersion;
ds_mtx >> nVersion;
ds_mtx.SetVersion(nVersion);
ds_mtx >> mutable_tx;
} catch (const std::ios_base::failure&) {
valid_mutable_tx = false;
}
assert(valid_tx == valid_mutable_tx);
if (!valid_tx) {
return;
}
{
TxValidationState state_with_dupe_check;
const bool res{CheckTransaction(tx, state_with_dupe_check)};
Assert(res == state_with_dupe_check.IsValid());
}
const CFeeRate dust_relay_fee{DUST_RELAY_TX_FEE};
std::string reason;
const bool is_standard_with_permit_bare_multisig = IsStandardTx(tx, /* permit_bare_multisig= */ true, dust_relay_fee, reason);
const bool is_standard_without_permit_bare_multisig = IsStandardTx(tx, /* permit_bare_multisig= */ false, dust_relay_fee, reason);
if (is_standard_without_permit_bare_multisig) {
assert(is_standard_with_permit_bare_multisig);
}
(void)tx.GetHash();
(void)tx.GetTotalSize();
try {
(void)tx.GetValueOut();
} catch (const std::runtime_error&) {
}
(void)tx.GetWitnessHash();
(void)tx.HasWitness();
(void)tx.IsCoinBase();
(void)tx.IsNull();
(void)tx.ToString();
(void)EncodeHexTx(tx);
(void)GetLegacySigOpCount(tx);
(void)GetTransactionWeight(tx);
(void)GetVirtualTransactionSize(tx);
(void)IsFinalTx(tx, /* nBlockHeight= */ 1024, /* nBlockTime= */ 1024);
(void)IsStandardTx(tx, reason);
(void)RecursiveDynamicUsage(tx);
(void)SignalsOptInRBF(tx);
CCoinsView coins_view;
const CCoinsViewCache coins_view_cache(&coins_view);
(void)AreInputsStandard(tx, coins_view_cache, false);
(void)AreInputsStandard(tx, coins_view_cache, true);
(void)IsWitnessStandard(tx, coins_view_cache);
UniValue u(UniValue::VOBJ);
TxToUniv(tx, /* hashBlock */ {}, /* include_addresses */ true, u);
TxToUniv(tx, /* hashBlock */ {}, /* include_addresses */ false, u);
static const uint256 u256_max(uint256S("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"));
TxToUniv(tx, u256_max, /* include_addresses */ true, u);
TxToUniv(tx, u256_max, /* include_addresses */ false, u);
}
<commit_msg>fuzz: Speed up transaction fuzz target<commit_after>// Copyright (c) 2019-2020 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 <chainparams.h>
#include <coins.h>
#include <consensus/tx_check.h>
#include <consensus/tx_verify.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <core_memusage.h>
#include <policy/policy.h>
#include <policy/settings.h>
#include <primitives/transaction.h>
#include <streams.h>
#include <test/fuzz/fuzz.h>
#include <univalue.h>
#include <util/rbf.h>
#include <validation.h>
#include <version.h>
#include <cassert>
void initialize_transaction()
{
SelectParams(CBaseChainParams::REGTEST);
}
FUZZ_TARGET_INIT(transaction, initialize_transaction)
{
CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
try {
int nVersion;
ds >> nVersion;
ds.SetVersion(nVersion);
} catch (const std::ios_base::failure&) {
return;
}
bool valid_tx = true;
const CTransaction tx = [&] {
try {
return CTransaction(deserialize, ds);
} catch (const std::ios_base::failure&) {
valid_tx = false;
return CTransaction{CMutableTransaction{}};
}
}();
bool valid_mutable_tx = true;
CDataStream ds_mtx(buffer, SER_NETWORK, INIT_PROTO_VERSION);
CMutableTransaction mutable_tx;
try {
int nVersion;
ds_mtx >> nVersion;
ds_mtx.SetVersion(nVersion);
ds_mtx >> mutable_tx;
} catch (const std::ios_base::failure&) {
valid_mutable_tx = false;
}
assert(valid_tx == valid_mutable_tx);
if (!valid_tx) {
return;
}
{
TxValidationState state_with_dupe_check;
const bool res{CheckTransaction(tx, state_with_dupe_check)};
Assert(res == state_with_dupe_check.IsValid());
}
const CFeeRate dust_relay_fee{DUST_RELAY_TX_FEE};
std::string reason;
const bool is_standard_with_permit_bare_multisig = IsStandardTx(tx, /* permit_bare_multisig= */ true, dust_relay_fee, reason);
const bool is_standard_without_permit_bare_multisig = IsStandardTx(tx, /* permit_bare_multisig= */ false, dust_relay_fee, reason);
if (is_standard_without_permit_bare_multisig) {
assert(is_standard_with_permit_bare_multisig);
}
(void)tx.GetHash();
(void)tx.GetTotalSize();
try {
(void)tx.GetValueOut();
} catch (const std::runtime_error&) {
}
(void)tx.GetWitnessHash();
(void)tx.HasWitness();
(void)tx.IsCoinBase();
(void)tx.IsNull();
(void)tx.ToString();
(void)EncodeHexTx(tx);
(void)GetLegacySigOpCount(tx);
(void)GetTransactionWeight(tx);
(void)GetVirtualTransactionSize(tx);
(void)IsFinalTx(tx, /* nBlockHeight= */ 1024, /* nBlockTime= */ 1024);
(void)IsStandardTx(tx, reason);
(void)RecursiveDynamicUsage(tx);
(void)SignalsOptInRBF(tx);
CCoinsView coins_view;
const CCoinsViewCache coins_view_cache(&coins_view);
(void)AreInputsStandard(tx, coins_view_cache, false);
(void)AreInputsStandard(tx, coins_view_cache, true);
(void)IsWitnessStandard(tx, coins_view_cache);
UniValue u(UniValue::VOBJ);
TxToUniv(tx, /* hashBlock */ uint256::ZERO, /* include_addresses */ true, u);
TxToUniv(tx, /* hashBlock */ uint256::ONE, /* include_addresses */ false, u);
}
<|endoftext|> |
<commit_before>#include "geodrawer_plugin.h"
#include "visualizationmanager.h"
//#include "geodrawer.h"
#include <qqml.h>
#include "geometries.h"
#include "iooptions.h"
#include "drawers/drawerfactory.h"
#include "selectiondrawer.h"
#include "layersview.h"
void GeodrawerPlugin::registerTypes(const char *uri)
{
// @uri n52.org.ilwisobjects
qmlRegisterType<LayersView>(uri, 1, 0, "LayersView");
Ilwis::Geodrawer::DrawerFactory::registerDrawer("SelectionDrawer", Ilwis::Geodrawer::SelectionDrawer::create);
}
<commit_msg>renamed include<commit_after>#include "geodrawer_plugin.h"
#include "layermanager.h"
//#include "geodrawer.h"
#include <qqml.h>
#include "geometries.h"
#include "iooptions.h"
#include "drawers/drawerfactory.h"
#include "selectiondrawer.h"
#include "layersview.h"
void GeodrawerPlugin::registerTypes(const char *uri)
{
// @uri n52.org.ilwisobjects
qmlRegisterType<LayersView>(uri, 1, 0, "LayersView");
Ilwis::Geodrawer::DrawerFactory::registerDrawer("SelectionDrawer", Ilwis::Geodrawer::SelectionDrawer::create);
}
<|endoftext|> |
<commit_before>
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2012-2016 Igor Mironchik
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.
*/
// Qt include.
#include <QCoreApplication>
#include <QFileInfo>
#include <QFile>
#include <QTextStream>
// QtArg include.
#include <QtArg/Arg>
#include <QtArg/Help>
#include <QtArg/CmdLine>
#include <QtArg/Exceptions>
// QtConfFile include.
#include <QtConfFile/Utils>
// Generator include.
#include "generator.hpp"
//
// ForGeneration
//
//! Data uses to generate.
class ForGeneration {
public:
ForGeneration()
{
}
ForGeneration( const QString & inputFile, const QString & outputFile )
: m_inputFileName( inputFile )
, m_outputFileName( outputFile )
{
}
~ForGeneration()
{
}
ForGeneration( const ForGeneration & other )
: m_inputFileName( other.inputFile() )
, m_outputFileName( other.outputFile() )
{
}
ForGeneration & operator = ( const ForGeneration & other )
{
if( this != &other )
{
m_inputFileName = other.inputFile();
m_outputFileName = other.outputFile();
}
return *this;
}
//! \return Input file name.
const QString & inputFile() const
{
return m_inputFileName;
}
//! \return Output file name.
const QString & outputFile() const
{
return m_outputFileName;
}
private:
//! Input file name.
QString m_inputFileName;
//! Output file name.
QString m_outputFileName;
}; // class ForGeneration
//
// parseCommandLineArguments
//
static inline ForGeneration parseCommandLineArguments( int argc, char ** argv )
{
QtArg input( QLatin1Char( 'i' ), QLatin1String( "input" ),
QLatin1String( "Input file name" ), true, true );
QtArg output( QLatin1Char( 'o' ), QLatin1String( "output" ),
QLatin1String( "Output file name" ), true, true );
QtArgCmdLine cmd( argc, argv );
QtArgHelp help( &cmd );
help.printer()->setProgramDescription(
QLatin1String( "C++ header generator for QtConfFile." ) );
help.printer()->setExecutableName( QLatin1String( argv[ 0 ] ) );
cmd.addArg( &input );
cmd.addArg( &output );
cmd.addArg( &help );
cmd.parse();
ForGeneration data( input.value().toString(),
output.value().toString() );
QTextStream stream( stdout );
if( data.inputFile().isEmpty() )
{
stream << QLatin1String( "Please specify input file." ) << endl;
exit( 1 );
}
if( !QFileInfo( data.inputFile() ).exists() )
{
stream << QLatin1String( "Specified input file doesn't exist." ) << endl;
exit( 1 );
}
if( data.outputFile().isEmpty() )
{
stream << QLatin1String( "Please specify output file." ) << endl;
exit( 1 );
}
return data;
}
int main( int argc, char ** argv )
{
ForGeneration data;
try {
data = parseCommandLineArguments( argc, argv );
}
catch( const QtArgHelpHasPrintedEx & x )
{
return 0;
}
catch( const QtArgBaseException & x )
{
QTextStream stream( stdout );
stream << x.whatAsQString() << endl;
return 1;
}
QtConfFile::Generator::Cfg::Model model;
try {
QtConfFile::Generator::Cfg::TagModel tag;
QtConfFile::readQtConfFile( tag, data.inputFile(),
QTextCodec::codecForName( "UTF-8" ) );
model = tag.cfg();
model.prepare();
model.check();
}
catch( const QtConfFile::Exception & x )
{
QTextStream stream( stdout );
stream << x.whatAsQString() << endl;
return 1;
}
QFile output( data.outputFile() );
if( output.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
{
QTextStream stream( &output );
QtConfFile::Generator::CppGenerator gen( model );
gen.generate( stream );
output.close();
return 0;
}
else
{
QTextStream stream( stdout );
stream << QLatin1String( "Couldn't open output file for writting." )
<< endl;
return 1;
}
}
<commit_msg>Fixed compillation warning.<commit_after>
/*!
\file
\author Igor Mironchik (igor.mironchik at gmail dot com).
Copyright (c) 2012-2016 Igor Mironchik
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.
*/
// Qt include.
#include <QCoreApplication>
#include <QFileInfo>
#include <QFile>
#include <QTextStream>
// QtArg include.
#include <QtArg/Arg>
#include <QtArg/Help>
#include <QtArg/CmdLine>
#include <QtArg/Exceptions>
// QtConfFile include.
#include <QtConfFile/Utils>
// Generator include.
#include "generator.hpp"
//
// ForGeneration
//
//! Data uses to generate.
class ForGeneration {
public:
ForGeneration()
{
}
ForGeneration( const QString & inputFile, const QString & outputFile )
: m_inputFileName( inputFile )
, m_outputFileName( outputFile )
{
}
~ForGeneration()
{
}
ForGeneration( const ForGeneration & other )
: m_inputFileName( other.inputFile() )
, m_outputFileName( other.outputFile() )
{
}
ForGeneration & operator = ( const ForGeneration & other )
{
if( this != &other )
{
m_inputFileName = other.inputFile();
m_outputFileName = other.outputFile();
}
return *this;
}
//! \return Input file name.
const QString & inputFile() const
{
return m_inputFileName;
}
//! \return Output file name.
const QString & outputFile() const
{
return m_outputFileName;
}
private:
//! Input file name.
QString m_inputFileName;
//! Output file name.
QString m_outputFileName;
}; // class ForGeneration
//
// parseCommandLineArguments
//
static inline ForGeneration parseCommandLineArguments( int argc, char ** argv )
{
QtArg input( QLatin1Char( 'i' ), QLatin1String( "input" ),
QLatin1String( "Input file name" ), true, true );
QtArg output( QLatin1Char( 'o' ), QLatin1String( "output" ),
QLatin1String( "Output file name" ), true, true );
QtArgCmdLine cmd( argc, argv );
QtArgHelp help( &cmd );
help.printer()->setProgramDescription(
QLatin1String( "C++ header generator for QtConfFile." ) );
help.printer()->setExecutableName( QLatin1String( argv[ 0 ] ) );
cmd.addArg( &input );
cmd.addArg( &output );
cmd.addArg( &help );
cmd.parse();
ForGeneration data( input.value().toString(),
output.value().toString() );
QTextStream stream( stdout );
if( data.inputFile().isEmpty() )
{
stream << QLatin1String( "Please specify input file." ) << endl;
exit( 1 );
}
if( !QFileInfo( data.inputFile() ).exists() )
{
stream << QLatin1String( "Specified input file doesn't exist." ) << endl;
exit( 1 );
}
if( data.outputFile().isEmpty() )
{
stream << QLatin1String( "Please specify output file." ) << endl;
exit( 1 );
}
return data;
}
int main( int argc, char ** argv )
{
ForGeneration data;
try {
data = parseCommandLineArguments( argc, argv );
}
catch( const QtArgHelpHasPrintedEx & )
{
return 0;
}
catch( const QtArgBaseException & x )
{
QTextStream stream( stdout );
stream << x.whatAsQString() << endl;
return 1;
}
QtConfFile::Generator::Cfg::Model model;
try {
QtConfFile::Generator::Cfg::TagModel tag;
QtConfFile::readQtConfFile( tag, data.inputFile(),
QTextCodec::codecForName( "UTF-8" ) );
model = tag.cfg();
model.prepare();
model.check();
}
catch( const QtConfFile::Exception & x )
{
QTextStream stream( stdout );
stream << x.whatAsQString() << endl;
return 1;
}
QFile output( data.outputFile() );
if( output.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
{
QTextStream stream( &output );
QtConfFile::Generator::CppGenerator gen( model );
gen.generate( stream );
output.close();
return 0;
}
else
{
QTextStream stream( stdout );
stream << QLatin1String( "Couldn't open output file for writting." )
<< endl;
return 1;
}
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ts/ts.h>
#include <stdlib.h>
#include <strings.h>
// The name of the debug request header. This should probably be configurable.
#define X_DEBUG_HEADER "X-Debug"
#define XHEADER_X_CACHE_KEY 0x0004u
static int XArgIndex = 0;
static TSCont XInjectHeadersCont = NULL;
// Return the length of a string literal.
template <int N> unsigned
lengthof(const char (&str)[N]) {
return N - 1;
}
static TSMLoc
FindOrMakeHdrField(TSMBuffer buffer, TSMLoc hdr, const char * name, unsigned len)
{
TSMLoc field;
field = TSMimeHdrFieldFind(buffer, hdr, name, len);
if (field == TS_NULL_MLOC) {
if (TSMimeHdrFieldCreateNamed(buffer, hdr, name, len, &field) == TS_SUCCESS) {
TSReleaseAssert(TSMimeHdrFieldAppend(buffer, hdr, field) == TS_SUCCESS);
}
}
return field;
}
static void
InjectCacheKeyHeader(TSHttpTxn txn, TSMBuffer buffer, TSMLoc hdr)
{
TSMLoc url = TS_NULL_MLOC;
TSMLoc dst = TS_NULL_MLOC;
struct { char * ptr; int len; } strval = { NULL, 0 };
TSDebug("xdebug", "attempting to inject X-Cache-Key header");
if (TSUrlCreate(buffer, &url) != TS_SUCCESS) {
goto done;
}
if (TSHttpTxnCacheLookupUrlGet(txn, buffer, url) != TS_SUCCESS) {
goto done;
}
strval.ptr = TSUrlStringGet(buffer, url, &strval.len);
if (strval.ptr == NULL || strval.len == 0) {
goto done;
}
// Create a new response header field.
dst = FindOrMakeHdrField(buffer, hdr, "X-Cache-Key", lengthof("X-Cache-Key"));
if (dst == TS_NULL_MLOC) {
goto done;
}
// Now copy the cache lookup URL into the response header.
TSReleaseAssert(
TSMimeHdrFieldValueStringInsert(buffer, hdr, dst, 0 /* idx */, strval.ptr, strval.len) == TS_SUCCESS
);
done:
if (dst != TS_NULL_MLOC) {
TSHandleMLocRelease(buffer, hdr, dst);
}
if (url != TS_NULL_MLOC) {
TSHandleMLocRelease(buffer, TS_NULL_MLOC, url);
}
TSfree(strval.ptr);
}
static int
XInjectResponseHeaders(TSCont contp, TSEvent event, void * edata)
{
TSHttpTxn txn = (TSHttpTxn)edata;
intptr_t xheaders = 0;
TSMBuffer buffer;
TSMLoc hdr;
TSReleaseAssert(event == TS_EVENT_HTTP_SEND_RESPONSE_HDR);
xheaders = (intptr_t)TSHttpTxnArgGet(txn, XArgIndex);
if (xheaders == 0) {
goto done;
}
if (TSHttpTxnClientRespGet(txn, &buffer, &hdr) == TS_ERROR) {
goto done;
}
if (xheaders & XHEADER_X_CACHE_KEY) {
InjectCacheKeyHeader(txn, buffer, hdr);
}
done:
TSHttpTxnReenable(txn, TS_EVENT_HTTP_CONTINUE);
return TS_EVENT_NONE;
}
// Scan the client request headers and determine which debug headers they
// want in the response.
static int
XScanRequestHeaders(TSCont contp, TSEvent event, void * edata)
{
TSHttpTxn txn = (TSHttpTxn)edata;
intptr_t xheaders = 0;
TSMLoc field, next;
TSMBuffer buffer;
TSMLoc hdr;
TSReleaseAssert(event == TS_EVENT_HTTP_READ_REQUEST_HDR);
if (TSHttpTxnClientReqGet(txn, &buffer, &hdr) == TS_ERROR) {
goto done;
}
TSDebug("xdebug", "scanning for %s header values", X_DEBUG_HEADER);
// Walk the X-Debug header values and determine what to inject into the response.
field = TSMimeHdrFieldFind(buffer, hdr, X_DEBUG_HEADER, lengthof(X_DEBUG_HEADER));
while (field != TS_NULL_MLOC) {
int count = TSMimeHdrFieldValuesCount(buffer, hdr, field);
for (int i = 0; i < count; ++i) {
const char * value;
int vsize;
value = TSMimeHdrFieldValueStringGet(buffer, hdr, field, i, &vsize);
if (value == NULL || vsize == 0) {
continue;
}
if (strncasecmp("x-cache-key", value, vsize) == 0) {
xheaders |= XHEADER_X_CACHE_KEY;
} else if (strncasecmp("via", value, vsize) == 0) {
// If the client requests the Via header, enable verbose Via debugging for this transaction.
TSHttpTxnConfigIntSet(txn, TS_CONFIG_HTTP_INSERT_RESPONSE_VIA_STR, 3);
} else {
TSDebug("xdebug", "ignoring unrecognized debug tag '%.*s'", vsize, value);
}
}
// Get the next duplicate.
next = TSMimeHdrFieldNextDup(buffer, hdr, field);
// Destroy the current field that we have. We don't want this to go through and potentially confuse the origin.
TSMimeHdrFieldRemove(buffer, hdr, field);
TSMimeHdrFieldDestroy(buffer, hdr, field);
// Now release our reference.
TSHandleMLocRelease(buffer, hdr, field);
// And go to the next field.
field = next;
}
if (xheaders) {
TSHttpTxnHookAdd(txn, TS_HTTP_SEND_RESPONSE_HDR_HOOK, XInjectHeadersCont);
TSHttpTxnArgSet(txn, XArgIndex, (void *)xheaders);
}
done:
TSHttpTxnReenable(txn, TS_EVENT_HTTP_CONTINUE);
return TS_EVENT_NONE;
}
void
TSPluginInit(int argc, const char *argv[])
{
TSPluginRegistrationInfo info;
info.plugin_name = (char *)"xdebug";
info.vendor_name = (char *)"Apache Software Foundation";
info.support_email = (char *)"dev@trafficserver.apache.org";
if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) {
TSError("xdebug plugin registration failed");
}
TSReleaseAssert(
TSHttpArgIndexReserve("xdebug", "xdebug header requests" , &XArgIndex) == TS_SUCCESS
);
TSReleaseAssert(
XInjectHeadersCont = TSContCreate(XInjectResponseHeaders, NULL)
);
TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, TSContCreate(XScanRequestHeaders, NULL));
}
// vim: set ts=2 sw=2 et :
<commit_msg>TS-2426: fix unused variable warnings<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <ts/ts.h>
#include <stdlib.h>
#include <strings.h>
// The name of the debug request header. This should probably be configurable.
#define X_DEBUG_HEADER "X-Debug"
#define XHEADER_X_CACHE_KEY 0x0004u
static int XArgIndex = 0;
static TSCont XInjectHeadersCont = NULL;
// Return the length of a string literal.
template <int N> unsigned
lengthof(const char (&)[N]) {
return N - 1;
}
static TSMLoc
FindOrMakeHdrField(TSMBuffer buffer, TSMLoc hdr, const char * name, unsigned len)
{
TSMLoc field;
field = TSMimeHdrFieldFind(buffer, hdr, name, len);
if (field == TS_NULL_MLOC) {
if (TSMimeHdrFieldCreateNamed(buffer, hdr, name, len, &field) == TS_SUCCESS) {
TSReleaseAssert(TSMimeHdrFieldAppend(buffer, hdr, field) == TS_SUCCESS);
}
}
return field;
}
static void
InjectCacheKeyHeader(TSHttpTxn txn, TSMBuffer buffer, TSMLoc hdr)
{
TSMLoc url = TS_NULL_MLOC;
TSMLoc dst = TS_NULL_MLOC;
struct { char * ptr; int len; } strval = { NULL, 0 };
TSDebug("xdebug", "attempting to inject X-Cache-Key header");
if (TSUrlCreate(buffer, &url) != TS_SUCCESS) {
goto done;
}
if (TSHttpTxnCacheLookupUrlGet(txn, buffer, url) != TS_SUCCESS) {
goto done;
}
strval.ptr = TSUrlStringGet(buffer, url, &strval.len);
if (strval.ptr == NULL || strval.len == 0) {
goto done;
}
// Create a new response header field.
dst = FindOrMakeHdrField(buffer, hdr, "X-Cache-Key", lengthof("X-Cache-Key"));
if (dst == TS_NULL_MLOC) {
goto done;
}
// Now copy the cache lookup URL into the response header.
TSReleaseAssert(
TSMimeHdrFieldValueStringInsert(buffer, hdr, dst, 0 /* idx */, strval.ptr, strval.len) == TS_SUCCESS
);
done:
if (dst != TS_NULL_MLOC) {
TSHandleMLocRelease(buffer, hdr, dst);
}
if (url != TS_NULL_MLOC) {
TSHandleMLocRelease(buffer, TS_NULL_MLOC, url);
}
TSfree(strval.ptr);
}
static int
XInjectResponseHeaders(TSCont /* contp */, TSEvent event, void * edata)
{
TSHttpTxn txn = (TSHttpTxn)edata;
intptr_t xheaders = 0;
TSMBuffer buffer;
TSMLoc hdr;
TSReleaseAssert(event == TS_EVENT_HTTP_SEND_RESPONSE_HDR);
xheaders = (intptr_t)TSHttpTxnArgGet(txn, XArgIndex);
if (xheaders == 0) {
goto done;
}
if (TSHttpTxnClientRespGet(txn, &buffer, &hdr) == TS_ERROR) {
goto done;
}
if (xheaders & XHEADER_X_CACHE_KEY) {
InjectCacheKeyHeader(txn, buffer, hdr);
}
done:
TSHttpTxnReenable(txn, TS_EVENT_HTTP_CONTINUE);
return TS_EVENT_NONE;
}
// Scan the client request headers and determine which debug headers they
// want in the response.
static int
XScanRequestHeaders(TSCont /* contp */, TSEvent event, void * edata)
{
TSHttpTxn txn = (TSHttpTxn)edata;
intptr_t xheaders = 0;
TSMLoc field, next;
TSMBuffer buffer;
TSMLoc hdr;
TSReleaseAssert(event == TS_EVENT_HTTP_READ_REQUEST_HDR);
if (TSHttpTxnClientReqGet(txn, &buffer, &hdr) == TS_ERROR) {
goto done;
}
TSDebug("xdebug", "scanning for %s header values", X_DEBUG_HEADER);
// Walk the X-Debug header values and determine what to inject into the response.
field = TSMimeHdrFieldFind(buffer, hdr, X_DEBUG_HEADER, lengthof(X_DEBUG_HEADER));
while (field != TS_NULL_MLOC) {
int count = TSMimeHdrFieldValuesCount(buffer, hdr, field);
for (int i = 0; i < count; ++i) {
const char * value;
int vsize;
value = TSMimeHdrFieldValueStringGet(buffer, hdr, field, i, &vsize);
if (value == NULL || vsize == 0) {
continue;
}
if (strncasecmp("x-cache-key", value, vsize) == 0) {
xheaders |= XHEADER_X_CACHE_KEY;
} else if (strncasecmp("via", value, vsize) == 0) {
// If the client requests the Via header, enable verbose Via debugging for this transaction.
TSHttpTxnConfigIntSet(txn, TS_CONFIG_HTTP_INSERT_RESPONSE_VIA_STR, 3);
} else {
TSDebug("xdebug", "ignoring unrecognized debug tag '%.*s'", vsize, value);
}
}
// Get the next duplicate.
next = TSMimeHdrFieldNextDup(buffer, hdr, field);
// Destroy the current field that we have. We don't want this to go through and potentially confuse the origin.
TSMimeHdrFieldRemove(buffer, hdr, field);
TSMimeHdrFieldDestroy(buffer, hdr, field);
// Now release our reference.
TSHandleMLocRelease(buffer, hdr, field);
// And go to the next field.
field = next;
}
if (xheaders) {
TSHttpTxnHookAdd(txn, TS_HTTP_SEND_RESPONSE_HDR_HOOK, XInjectHeadersCont);
TSHttpTxnArgSet(txn, XArgIndex, (void *)xheaders);
}
done:
TSHttpTxnReenable(txn, TS_EVENT_HTTP_CONTINUE);
return TS_EVENT_NONE;
}
void
TSPluginInit(int /* argc */, const char * /*argv */ [])
{
TSPluginRegistrationInfo info;
info.plugin_name = (char *)"xdebug";
info.vendor_name = (char *)"Apache Software Foundation";
info.support_email = (char *)"dev@trafficserver.apache.org";
if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) {
TSError("xdebug plugin registration failed");
}
TSReleaseAssert(
TSHttpArgIndexReserve("xdebug", "xdebug header requests" , &XArgIndex) == TS_SUCCESS
);
TSReleaseAssert(
XInjectHeadersCont = TSContCreate(XInjectResponseHeaders, NULL)
);
TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, TSContCreate(XScanRequestHeaders, NULL));
}
// vim: set ts=2 sw=2 et :
<|endoftext|> |
<commit_before><commit_msg>Use world coordinates when rendering transformation gizmo<commit_after><|endoftext|> |
<commit_before><commit_msg>added missing include guard to disk_io_thread.hpp<commit_after><|endoftext|> |
<commit_before>#pragma once
#include <string>
#include <blackhole/detail/datetime.hpp>
#include "../global.hpp"
class generator_test_case_t : public Test {
protected:
std::tm tm;
suseconds_t usec;
void SetUp() {
tm = std::tm();
usec = 0;
}
std::string generate(const std::string& pattern) const {
std::string str;
blackhole::aux::attachable_basic_ostringstream<char> stream(str);
blackhole::aux::datetime::generator_t generator =
blackhole::aux::datetime::generator_factory_t::make(pattern);
generator(stream, tm, usec);
return stream.str();
}
};
namespace common {
inline std::string using_strftime(const std::string& format, const std::tm& tm) {
char buffer[64];
std::strftime(buffer, 64, format.c_str(), &tm);
return buffer;
}
} // namespace common
<commit_msg>[Bug Fix] Fixed possible conditional jump.<commit_after>#pragma once
#include <string>
#include <blackhole/detail/datetime.hpp>
#include "../global.hpp"
class generator_test_case_t : public Test {
protected:
std::tm tm;
suseconds_t usec;
void SetUp() {
tm = std::tm();
usec = 0;
}
std::string generate(const std::string& pattern) const {
std::string str;
blackhole::aux::attachable_basic_ostringstream<char> stream(str);
blackhole::aux::datetime::generator_t generator =
blackhole::aux::datetime::generator_factory_t::make(pattern);
generator(stream, tm, usec);
return stream.str();
}
};
namespace common {
template<std::size_t N>
inline std::string using_strftime(const char(&format)[N], const std::tm& tm) {
char buffer[128];
std::size_t ret = std::strftime(buffer, sizeof(buffer), format, &tm);
BOOST_ASSERT(ret > 0);
return buffer;
}
} // namespace common
<|endoftext|> |
<commit_before>/*
* ConstructKDTree.cpp
* Copyright (C) 2019 by MegaMol Team
* Alle Rechte vorbehalten.
*/
#include "ConstructKDTree.h"
#include <limits>
#include "CallKDTree.h"
#include "adios_plugin/CallADIOSData.h"
#include "mmcore/moldyn/MultiParticleDataCall.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/param/FlexEnumParam.h"
#include "mmcore/param/FloatParam.h"
#include "normal_3d_omp.h"
#include <atomic>
namespace megamol {
namespace probe {
ConstructKDTree::ConstructKDTree()
: Module()
, _getDataCall("getData", "")
, _deployFullDataTree("deployFullDataTree", "")
, _xSlot("x", "")
, _ySlot("y", "")
, _zSlot("z", "")
, _xyzSlot("xyz", "")
, _formatSlot("format", "") {
core::param::EnumParam* fp = new core::param::EnumParam(0);
fp->SetTypePair(0, "separated");
fp->SetTypePair(1, "interleaved");
this->_formatSlot << fp;
this->_formatSlot.SetUpdateCallback(&ConstructKDTree::toggleFormat);
this->MakeSlotAvailable(&this->_formatSlot);
core::param::FlexEnumParam* xEp = new core::param::FlexEnumParam("undef");
this->_xSlot << xEp;
this->MakeSlotAvailable(&this->_xSlot);
core::param::FlexEnumParam* yEp = new core::param::FlexEnumParam("undef");
this->_ySlot << yEp;
this->MakeSlotAvailable(&this->_ySlot);
core::param::FlexEnumParam* zEp = new core::param::FlexEnumParam("undef");
this->_zSlot << zEp;
this->MakeSlotAvailable(&this->_zSlot);
core::param::FlexEnumParam* xyzEp = new core::param::FlexEnumParam("undef");
this->_xyzSlot << xyzEp;
xyzEp->SetGUIVisible(false);
this->MakeSlotAvailable(&this->_xyzSlot);
this->_deployFullDataTree.SetCallback(CallKDTree::ClassName(), CallKDTree::FunctionName(0), &ConstructKDTree::getData);
this->_deployFullDataTree.SetCallback(
CallKDTree::ClassName(), CallKDTree::FunctionName(1), &ConstructKDTree::getMetaData);
this->MakeSlotAvailable(&this->_deployFullDataTree);
this->_getDataCall.SetCompatibleCall<adios::CallADIOSDataDescription>();
this->MakeSlotAvailable(&this->_getDataCall);
}
ConstructKDTree::~ConstructKDTree() { this->Release(); }
bool ConstructKDTree::create() { return true; }
void ConstructKDTree::release() {}
bool ConstructKDTree::InterfaceIsDirty() { return this->_formatSlot.IsDirty(); }
bool ConstructKDTree::createPointCloud(std::vector<std::string>& vars) {
auto cd = this->_getDataCall.CallAs<adios::CallADIOSData>();
if (cd == nullptr) return false;
if (vars.empty()) return false;
const auto count = cd->getData(vars[0])->size();
_cloud.points.resize(count);
for (auto var : vars) {
if (this->_formatSlot.Param<core::param::EnumParam>()->Value() == 0) {
auto x =
cd->getData(std::string(this->_xSlot.Param<core::param::FlexEnumParam>()->ValueString()))->GetAsFloat();
auto y =
cd->getData(std::string(this->_ySlot.Param<core::param::FlexEnumParam>()->ValueString()))->GetAsFloat();
auto z =
cd->getData(std::string(this->_zSlot.Param<core::param::FlexEnumParam>()->ValueString()))->GetAsFloat();
auto xminmax = std::minmax_element(x.begin(), x.end());
auto yminmax = std::minmax_element(y.begin(), y.end());
auto zminmax = std::minmax_element(z.begin(), z.end());
_bbox.SetBoundingBox(
*xminmax.first, *yminmax.first, *zminmax.second, *xminmax.second, *yminmax.second, *zminmax.first);
for (unsigned long long i = 0; i < count; i++) {
_cloud.points[i].x = x[i];
_cloud.points[i].y = y[i];
_cloud.points[i].z = z[i];
}
} else {
//auto xyz = cd->getData(std::string(this->_xyzSlot.Param<core::param::FlexEnumParam>()->ValueString()))
// ->GetAsFloat();
int coarse_factor = 30;
auto xyz = cd->getData(std::string(this->_xyzSlot.Param<core::param::FlexEnumParam>()->ValueString()))
->GetAsDouble();
float xmin = std::numeric_limits<float>::max();
float xmax = std::numeric_limits<float>::min();
float ymin = std::numeric_limits<float>::max();
float ymax = std::numeric_limits<float>::min();
float zmin = std::numeric_limits<float>::max();
float zmax = std::numeric_limits<float>::min();
_cloud.points.resize(count/coarse_factor);
for (unsigned long long i = 0; i < count/(3*coarse_factor); i++) {
_cloud.points[i].x = xyz[3 * (i*coarse_factor) + 0];
_cloud.points[i].y = xyz[3 * (i*coarse_factor) + 1];
_cloud.points[i].z = xyz[3 * (i*coarse_factor) + 2];
xmin = std::min(xmin, _cloud.points[i].x);
xmax = std::max(xmax, _cloud.points[i].x);
ymin = std::min(ymin, _cloud.points[i].y);
ymax = std::max(ymax, _cloud.points[i].y);
zmin = std::min(zmin, _cloud.points[i].z);
zmax = std::max(zmax, _cloud.points[i].z);
}
_bbox.SetBoundingBox(xmin, ymin, zmax, xmax, ymax, zmin);
}
}
return true;
}
bool ConstructKDTree::getMetaData(core::Call& call) {
auto ct = dynamic_cast<CallKDTree*>(&call);
if (ct == nullptr) return false;
auto cd = this->_getDataCall.CallAs<adios::CallADIOSData>();
if (cd == nullptr) return false;
auto meta_data = ct->getMetaData();
if (cd->getDataHash() == _old_datahash && meta_data.m_frame_ID == cd->getFrameIDtoLoad()) return true;
// get metadata from adios
cd->setFrameIDtoLoad(meta_data.m_frame_ID);
if (!(*cd)(1)) return false;
auto vars = cd->getAvailableVars();
for (auto var : vars) {
this->_xSlot.Param<core::param::FlexEnumParam>()->AddValue(var);
this->_ySlot.Param<core::param::FlexEnumParam>()->AddValue(var);
this->_zSlot.Param<core::param::FlexEnumParam>()->AddValue(var);
this->_xyzSlot.Param<core::param::FlexEnumParam>()->AddValue(var);
}
// put metadata in mesh call
meta_data.m_frame_cnt = cd->getFrameCount();
ct->setMetaData(meta_data);
return true;
}
bool ConstructKDTree::getData(core::Call& call) {
auto ct = dynamic_cast<CallKDTree*>(&call);
if (ct == nullptr) return false;
auto cd = this->_getDataCall.CallAs<adios::CallADIOSData>();
if (cd == nullptr) return false;
auto meta_data = ct->getMetaData();
std::vector<std::string> toInq;
toInq.clear();
if (this->_formatSlot.Param<core::param::EnumParam>()->Value() == 0) {
toInq.emplace_back(std::string(this->_xSlot.Param<core::param::FlexEnumParam>()->ValueString()));
toInq.emplace_back(std::string(this->_ySlot.Param<core::param::FlexEnumParam>()->ValueString()));
toInq.emplace_back(std::string(this->_zSlot.Param<core::param::FlexEnumParam>()->ValueString()));
} else {
toInq.emplace_back(std::string(this->_xyzSlot.Param<core::param::FlexEnumParam>()->ValueString()));
}
// get data from adios
for (auto var : toInq) {
if (!cd->inquire(var)) return false;
}
if (cd->getDataHash() != _old_datahash) {
if (!(*cd)(0)) return false;
if (!this->createPointCloud(toInq)) return false;
meta_data.m_bboxs = _bbox;
ct->setMetaData(meta_data);
// Extract the kd tree for easy sampling of the data
_inputCloud = std::make_shared<pcl::PointCloud<pcl::PointXYZ>>(_cloud);
this->_full_data_tree = std::make_shared<pcl::KdTreeFLANN<pcl::PointXYZ>>();
this->_full_data_tree->setInputCloud(_inputCloud, nullptr);
this->_version++;
_old_datahash = cd->getDataHash();
}
ct->setData(this->_full_data_tree, this->_version);
return true;
}
bool ConstructKDTree::toggleFormat(core::param::ParamSlot& p) {
if (this->_formatSlot.Param<core::param::EnumParam>()->Value() == 0) {
this->_xSlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(true);
this->_ySlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(true);
this->_zSlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(true);
this->_xyzSlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(false);
} else {
this->_xSlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(false);
this->_ySlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(false);
this->_zSlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(false);
this->_xyzSlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(true);
}
return true;
}
} // namespace probe
} // namespace megamol
<commit_msg>Fix adios loading in kd-tree ?<commit_after>/*
* ConstructKDTree.cpp
* Copyright (C) 2019 by MegaMol Team
* Alle Rechte vorbehalten.
*/
#include "ConstructKDTree.h"
#include <limits>
#include "CallKDTree.h"
#include "adios_plugin/CallADIOSData.h"
#include "mmcore/moldyn/MultiParticleDataCall.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/param/FlexEnumParam.h"
#include "mmcore/param/FloatParam.h"
#include "normal_3d_omp.h"
#include <atomic>
namespace megamol {
namespace probe {
ConstructKDTree::ConstructKDTree()
: Module()
, _getDataCall("getData", "")
, _deployFullDataTree("deployFullDataTree", "")
, _xSlot("x", "")
, _ySlot("y", "")
, _zSlot("z", "")
, _xyzSlot("xyz", "")
, _formatSlot("format", "") {
core::param::EnumParam* fp = new core::param::EnumParam(0);
fp->SetTypePair(0, "separated");
fp->SetTypePair(1, "interleaved");
this->_formatSlot << fp;
this->_formatSlot.SetUpdateCallback(&ConstructKDTree::toggleFormat);
this->MakeSlotAvailable(&this->_formatSlot);
core::param::FlexEnumParam* xEp = new core::param::FlexEnumParam("undef");
this->_xSlot << xEp;
this->MakeSlotAvailable(&this->_xSlot);
core::param::FlexEnumParam* yEp = new core::param::FlexEnumParam("undef");
this->_ySlot << yEp;
this->MakeSlotAvailable(&this->_ySlot);
core::param::FlexEnumParam* zEp = new core::param::FlexEnumParam("undef");
this->_zSlot << zEp;
this->MakeSlotAvailable(&this->_zSlot);
core::param::FlexEnumParam* xyzEp = new core::param::FlexEnumParam("undef");
this->_xyzSlot << xyzEp;
xyzEp->SetGUIVisible(false);
this->MakeSlotAvailable(&this->_xyzSlot);
this->_deployFullDataTree.SetCallback(CallKDTree::ClassName(), CallKDTree::FunctionName(0), &ConstructKDTree::getData);
this->_deployFullDataTree.SetCallback(
CallKDTree::ClassName(), CallKDTree::FunctionName(1), &ConstructKDTree::getMetaData);
this->MakeSlotAvailable(&this->_deployFullDataTree);
this->_getDataCall.SetCompatibleCall<adios::CallADIOSDataDescription>();
this->MakeSlotAvailable(&this->_getDataCall);
}
ConstructKDTree::~ConstructKDTree() { this->Release(); }
bool ConstructKDTree::create() { return true; }
void ConstructKDTree::release() {}
bool ConstructKDTree::InterfaceIsDirty() { return this->_formatSlot.IsDirty(); }
bool ConstructKDTree::createPointCloud(std::vector<std::string>& vars) {
auto cd = this->_getDataCall.CallAs<adios::CallADIOSData>();
if (cd == nullptr) return false;
if (vars.empty()) return false;
const auto count = cd->getData(vars[0])->size();
_cloud.points.resize(count);
for (auto var : vars) {
if (this->_formatSlot.Param<core::param::EnumParam>()->Value() == 0) {
auto x =
cd->getData(std::string(this->_xSlot.Param<core::param::FlexEnumParam>()->ValueString()))->GetAsFloat();
auto y =
cd->getData(std::string(this->_ySlot.Param<core::param::FlexEnumParam>()->ValueString()))->GetAsFloat();
auto z =
cd->getData(std::string(this->_zSlot.Param<core::param::FlexEnumParam>()->ValueString()))->GetAsFloat();
auto xminmax = std::minmax_element(x.begin(), x.end());
auto yminmax = std::minmax_element(y.begin(), y.end());
auto zminmax = std::minmax_element(z.begin(), z.end());
_bbox.SetBoundingBox(
*xminmax.first, *yminmax.first, *zminmax.second, *xminmax.second, *yminmax.second, *zminmax.first);
for (unsigned long long i = 0; i < count; i++) {
_cloud.points[i].x = x[i];
_cloud.points[i].y = y[i];
_cloud.points[i].z = z[i];
}
} else {
//auto xyz = cd->getData(std::string(this->_xyzSlot.Param<core::param::FlexEnumParam>()->ValueString()))
// ->GetAsFloat();
int coarse_factor = 30;
auto xyz = cd->getData(std::string(this->_xyzSlot.Param<core::param::FlexEnumParam>()->ValueString()))
->GetAsDouble();
float xmin = std::numeric_limits<float>::max();
float xmax = std::numeric_limits<float>::min();
float ymin = std::numeric_limits<float>::max();
float ymax = std::numeric_limits<float>::min();
float zmin = std::numeric_limits<float>::max();
float zmax = std::numeric_limits<float>::min();
_cloud.points.resize(count/coarse_factor);
for (unsigned long long i = 0; i < count/(3*coarse_factor); i++) {
_cloud.points[i].x = xyz[3 * (i*coarse_factor) + 0];
_cloud.points[i].y = xyz[3 * (i*coarse_factor) + 1];
_cloud.points[i].z = xyz[3 * (i*coarse_factor) + 2];
xmin = std::min(xmin, _cloud.points[i].x);
xmax = std::max(xmax, _cloud.points[i].x);
ymin = std::min(ymin, _cloud.points[i].y);
ymax = std::max(ymax, _cloud.points[i].y);
zmin = std::min(zmin, _cloud.points[i].z);
zmax = std::max(zmax, _cloud.points[i].z);
}
_bbox.SetBoundingBox(xmin, ymin, zmax, xmax, ymax, zmin);
}
}
return true;
}
bool ConstructKDTree::getMetaData(core::Call& call) {
auto ct = dynamic_cast<CallKDTree*>(&call);
if (ct == nullptr) return false;
auto cd = this->_getDataCall.CallAs<adios::CallADIOSData>();
if (cd == nullptr) return false;
auto meta_data = ct->getMetaData();
//if (cd->getDataHash() == _old_datahash && meta_data.m_frame_ID == cd->getFrameIDtoLoad()) return true;
// get metadata from adios
cd->setFrameIDtoLoad(meta_data.m_frame_ID);
if (!(*cd)(1)) return false;
if (cd->getDataHash() == _old_datahash) {
auto vars = cd->getAvailableVars();
for (auto var : vars) {
this->_xSlot.Param<core::param::FlexEnumParam>()->AddValue(var);
this->_ySlot.Param<core::param::FlexEnumParam>()->AddValue(var);
this->_zSlot.Param<core::param::FlexEnumParam>()->AddValue(var);
this->_xyzSlot.Param<core::param::FlexEnumParam>()->AddValue(var);
}
}
// put metadata in mesh call
meta_data.m_frame_cnt = cd->getFrameCount();
ct->setMetaData(meta_data);
return true;
}
bool ConstructKDTree::getData(core::Call& call) {
auto ct = dynamic_cast<CallKDTree*>(&call);
if (ct == nullptr) return false;
auto cd = this->_getDataCall.CallAs<adios::CallADIOSData>();
if (cd == nullptr) return false;
auto meta_data = ct->getMetaData();
std::vector<std::string> toInq;
toInq.clear();
if (this->_formatSlot.Param<core::param::EnumParam>()->Value() == 0) {
toInq.emplace_back(std::string(this->_xSlot.Param<core::param::FlexEnumParam>()->ValueString()));
toInq.emplace_back(std::string(this->_ySlot.Param<core::param::FlexEnumParam>()->ValueString()));
toInq.emplace_back(std::string(this->_zSlot.Param<core::param::FlexEnumParam>()->ValueString()));
} else {
toInq.emplace_back(std::string(this->_xyzSlot.Param<core::param::FlexEnumParam>()->ValueString()));
}
// get data from adios
for (auto var : toInq) {
if (!cd->inquire(var)) return false;
}
if (cd->getDataHash() != _old_datahash) {
if (!(*cd)(0)) return false;
if (!this->createPointCloud(toInq)) return false;
meta_data.m_bboxs = _bbox;
ct->setMetaData(meta_data);
// Extract the kd tree for easy sampling of the data
_inputCloud = std::make_shared<pcl::PointCloud<pcl::PointXYZ>>(_cloud);
this->_full_data_tree = std::make_shared<pcl::KdTreeFLANN<pcl::PointXYZ>>();
this->_full_data_tree->setInputCloud(_inputCloud, nullptr);
this->_version++;
_old_datahash = cd->getDataHash();
}
ct->setData(this->_full_data_tree, this->_version);
return true;
}
bool ConstructKDTree::toggleFormat(core::param::ParamSlot& p) {
if (this->_formatSlot.Param<core::param::EnumParam>()->Value() == 0) {
this->_xSlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(true);
this->_ySlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(true);
this->_zSlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(true);
this->_xyzSlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(false);
} else {
this->_xSlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(false);
this->_ySlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(false);
this->_zSlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(false);
this->_xyzSlot.Param<core::param::FlexEnumParam>()->SetGUIVisible(true);
}
return true;
}
} // namespace probe
} // namespace megamol
<|endoftext|> |
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "alarmdockwindow.h"
#include "koalarmclient.h"
#include <kactioncollection.h>
#include <kdebug.h>
#include <kdeversion.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kiconeffect.h>
#include <kconfig.h>
#include <kconfiggroup.h>
#include <kurl.h>
#include <kstandarddirs.h>
#include <kmenu.h>
#include <kmessagebox.h>
#include <kaction.h>
#include <kstandardaction.h>
#include <ktoolinvocation.h>
#include <kglobal.h>
#include <QFile>
#include <QMouseEvent>
#include <stdlib.h>
AlarmDockWindow::AlarmDockWindow()
: KSystemTrayIcon( 0 )
{
// Read the autostart status from the config file
KConfigGroup config( KGlobal::config(), "General" );
bool autostart = config.readEntry( "Autostart", true );
bool alarmsEnabled = config.readEntry( "Enabled", true );
mName = i18n( "KOrganizer Reminder Daemon" );
setToolTip( mName );
// Set up icons
KIconLoader::global()->addAppDir( "korgac" );
mIconEnabled = loadIcon( "korgac" );
if ( mIconEnabled.isNull() ) {
KMessageBox::sorry( parentWidget(),
i18nc( "@info", "Cannot load system tray icon." ) );
} else {
KIconLoader loader;
QImage iconDisabled =
mIconEnabled.pixmap( loader.currentSize( KIconLoader::Panel ) ).toImage();
KIconEffect::toGray( iconDisabled, 1.0 );
mIconDisabled = QIcon( QPixmap::fromImage( iconDisabled ) );
}
setIcon( alarmsEnabled ? mIconEnabled : mIconDisabled );
// Set up the context menu
mSuspendAll = contextMenu()->addAction( i18n( "Suspend All" ),
this, SLOT(slotSuspendAll()) );
mDismissAll = contextMenu()->addAction( i18n( "Dismiss All" ),
this, SLOT(slotDismissAll()) );
mSuspendAll->setEnabled( false );
mDismissAll->setEnabled( false );
contextMenu()->addSeparator();
mAlarmsEnabled = contextMenu()->addAction( i18n( "Reminders Enabled" ), this,
SLOT(toggleAlarmsEnabled()) );
mAutostart = contextMenu()->addAction( i18n( "Start Reminder Daemon at Login" ),
this, SLOT(toggleAutostart()) );
mAutostart->setEnabled( autostart );
mAlarmsEnabled->setEnabled( alarmsEnabled );
// Disable standard quit behaviour. We have to intercept the quit even, if the
// main window is hidden.
KActionCollection *ac = actionCollection();
const char *quitName = KStandardAction::name( KStandardAction::Quit );
QAction *quit = ac->action( quitName );
if ( !quit ) {
kDebug(5890) << "No Quit standard action.";
} else {
quit->disconnect( SIGNAL(activated()), this, SLOT(maybeQuit()) );
connect( quit, SIGNAL(activated()), SLOT(slotQuit()) );
}
connect( this, SIGNAL(activated( QSystemTrayIcon::ActivationReason )),
SLOT(slotActivated( QSystemTrayIcon::ActivationReason )) );
setToolTip( mName );
}
AlarmDockWindow::~AlarmDockWindow()
{
}
void AlarmDockWindow::slotUpdate( int reminders )
{
mSuspendAll->setEnabled( reminders > 0 );
mDismissAll->setEnabled( reminders > 0 );
if ( reminders > 0 ) {
setToolTip( i18np( "There is 1 active reminder.",
"There are %1 active reminders.", reminders ) );
} else {
setToolTip( mName );
}
}
void AlarmDockWindow::toggleAlarmsEnabled()
{
kDebug(5890) << "AlarmDockWindow::toggleAlarmsEnabled()";
KConfigGroup config( KGlobal::config(), "General" );
bool enabled = !mAlarmsEnabled->isChecked();
mAlarmsEnabled->setChecked( enabled );
setIcon( enabled ? mIconEnabled : mIconDisabled );
config.writeEntry( "Enabled", enabled );
config.sync();
}
void AlarmDockWindow::toggleAutostart()
{
bool autostart = !mAutostart->isChecked();
enableAutostart( autostart );
}
void AlarmDockWindow::slotSuspendAll()
{
emit suspendAllSignal();
}
void AlarmDockWindow::slotDismissAll()
{
emit dismissAllSignal();
}
void AlarmDockWindow::enableAutostart( bool enable )
{
KConfigGroup config( KGlobal::config(), "General" );
config.writeEntry( "Autostart", enable );
config.sync();
mAutostart->setChecked( enable );
}
void AlarmDockWindow::slotActivated( QSystemTrayIcon::ActivationReason reason )
{
if ( reason == QSystemTrayIcon::Trigger ) {
KToolInvocation::startServiceByDesktopName( "korganizer", QString() );
}
}
void AlarmDockWindow::slotQuit()
{
int result = KMessageBox::questionYesNoCancel(
parentWidget(),
i18n( "Do you want to start the KOrganizer reminder daemon at login "
"(note that you will not get reminders whilst the daemon is not running)?" ),
i18n( "Close KOrganizer Reminder Daemon" ),
KGuiItem( i18nc( "@action:button start the reminder daemon", "Start" ) ), KGuiItem( i18nc( "@action:button do not start the reminder daemon", "Do Not Start" ) ), KStandardGuiItem::cancel(),
QString::fromLatin1( "AskForStartAtLogin" ) );
bool autostart = true;
if ( result == KMessageBox::No ) {
autostart = false;
}
enableAutostart( autostart );
if ( result != KMessageBox::Cancel ) {
emit quitSignal();
}
}
#include "alarmdockwindow.moc"
<commit_msg>quit action is connected to triggered(bool) now really intercept signal<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "alarmdockwindow.h"
#include "koalarmclient.h"
#include <kactioncollection.h>
#include <kdebug.h>
#include <kdeversion.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kiconeffect.h>
#include <kconfig.h>
#include <kconfiggroup.h>
#include <kurl.h>
#include <kstandarddirs.h>
#include <kmenu.h>
#include <kmessagebox.h>
#include <kaction.h>
#include <kstandardaction.h>
#include <ktoolinvocation.h>
#include <kglobal.h>
#include <QFile>
#include <QMouseEvent>
#include <stdlib.h>
AlarmDockWindow::AlarmDockWindow()
: KSystemTrayIcon( 0 )
{
// Read the autostart status from the config file
KConfigGroup config( KGlobal::config(), "General" );
bool autostart = config.readEntry( "Autostart", true );
bool alarmsEnabled = config.readEntry( "Enabled", true );
mName = i18n( "KOrganizer Reminder Daemon" );
setToolTip( mName );
// Set up icons
KIconLoader::global()->addAppDir( "korgac" );
mIconEnabled = loadIcon( "korgac" );
if ( mIconEnabled.isNull() ) {
KMessageBox::sorry( parentWidget(),
i18nc( "@info", "Cannot load system tray icon." ) );
} else {
KIconLoader loader;
QImage iconDisabled =
mIconEnabled.pixmap( loader.currentSize( KIconLoader::Panel ) ).toImage();
KIconEffect::toGray( iconDisabled, 1.0 );
mIconDisabled = QIcon( QPixmap::fromImage( iconDisabled ) );
}
setIcon( alarmsEnabled ? mIconEnabled : mIconDisabled );
// Set up the context menu
mSuspendAll = contextMenu()->addAction( i18n( "Suspend All" ),
this, SLOT(slotSuspendAll()) );
mDismissAll = contextMenu()->addAction( i18n( "Dismiss All" ),
this, SLOT(slotDismissAll()) );
mSuspendAll->setEnabled( false );
mDismissAll->setEnabled( false );
contextMenu()->addSeparator();
mAlarmsEnabled = contextMenu()->addAction( i18n( "Reminders Enabled" ), this,
SLOT(toggleAlarmsEnabled()) );
mAutostart = contextMenu()->addAction( i18n( "Start Reminder Daemon at Login" ),
this, SLOT(toggleAutostart()) );
mAutostart->setEnabled( autostart );
mAlarmsEnabled->setEnabled( alarmsEnabled );
// Disable standard quit behaviour. We have to intercept the quit even, if the
// main window is hidden.
KActionCollection *ac = actionCollection();
const char *quitName = KStandardAction::name( KStandardAction::Quit );
QAction *quit = ac->action( quitName );
if ( !quit ) {
kDebug(5890) << "No Quit standard action.";
} else {
quit->disconnect( SIGNAL(triggered(bool)), this, SLOT(maybeQuit()) );
connect( quit, SIGNAL(activated()), SLOT(slotQuit()) );
}
connect( this, SIGNAL(activated( QSystemTrayIcon::ActivationReason )),
SLOT(slotActivated( QSystemTrayIcon::ActivationReason )) );
setToolTip( mName );
}
AlarmDockWindow::~AlarmDockWindow()
{
}
void AlarmDockWindow::slotUpdate( int reminders )
{
mSuspendAll->setEnabled( reminders > 0 );
mDismissAll->setEnabled( reminders > 0 );
if ( reminders > 0 ) {
setToolTip( i18np( "There is 1 active reminder.",
"There are %1 active reminders.", reminders ) );
} else {
setToolTip( mName );
}
}
void AlarmDockWindow::toggleAlarmsEnabled()
{
kDebug(5890) << "AlarmDockWindow::toggleAlarmsEnabled()";
KConfigGroup config( KGlobal::config(), "General" );
bool enabled = !mAlarmsEnabled->isChecked();
mAlarmsEnabled->setChecked( enabled );
setIcon( enabled ? mIconEnabled : mIconDisabled );
config.writeEntry( "Enabled", enabled );
config.sync();
}
void AlarmDockWindow::toggleAutostart()
{
bool autostart = !mAutostart->isChecked();
enableAutostart( autostart );
}
void AlarmDockWindow::slotSuspendAll()
{
emit suspendAllSignal();
}
void AlarmDockWindow::slotDismissAll()
{
emit dismissAllSignal();
}
void AlarmDockWindow::enableAutostart( bool enable )
{
KConfigGroup config( KGlobal::config(), "General" );
config.writeEntry( "Autostart", enable );
config.sync();
mAutostart->setChecked( enable );
}
void AlarmDockWindow::slotActivated( QSystemTrayIcon::ActivationReason reason )
{
if ( reason == QSystemTrayIcon::Trigger ) {
KToolInvocation::startServiceByDesktopName( "korganizer", QString() );
}
}
void AlarmDockWindow::slotQuit()
{
int result = KMessageBox::questionYesNoCancel(
parentWidget(),
i18n( "Do you want to start the KOrganizer reminder daemon at login "
"(note that you will not get reminders whilst the daemon is not running)?" ),
i18n( "Close KOrganizer Reminder Daemon" ),
KGuiItem( i18nc( "@action:button start the reminder daemon", "Start" ) ), KGuiItem( i18nc( "@action:button do not start the reminder daemon", "Do Not Start" ) ), KStandardGuiItem::cancel(),
QString::fromLatin1( "AskForStartAtLogin" ) );
bool autostart = true;
if ( result == KMessageBox::No ) {
autostart = false;
}
enableAutostart( autostart );
if ( result != KMessageBox::Cancel ) {
emit quitSignal();
}
}
#include "alarmdockwindow.moc"
<|endoftext|> |
<commit_before>#include "Application.hpp"
#include "log.hpp"
#include "lua/State.hpp"
#include "Build.hpp"
#include "bind.hpp"
#include "quote.hpp"
#include "commands.hpp"
#include "Filesystem.hpp"
#include "Process.hpp"
#include "generators.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
#include <algorithm>
#include <iostream>
#include <map>
namespace fs = boost::filesystem;
namespace configure {
namespace {
std::vector<std::string> args_to_vector(int ac, char ** av)
{
std::vector<std::string> res;
for (int i = 0; i < ac; ++i)
res.push_back(av[i]);
return res;
}
bool is_project_directory(fs::path const& dir)
{
for (auto&& p: Build::possible_configure_files())
if (fs::is_regular_file(dir / p))
return true;
return false;
}
bool is_build_directory(fs::path const& dir)
{
return fs::is_regular_file(dir / ".build" / "env");
}
}
struct Application::Impl
{
fs::path program_name;
std::vector<std::string> args;
path_t current_directory;
std::vector<path_t> build_directories;
path_t project_directory;
std::map<std::string, std::string> build_variables;
bool dump_graph_mode;
bool dump_options;
bool dump_env;
bool dump_targets;
bool build_mode;
std::string build_target;
std::vector<std::string> builtin_command_args;
std::string print_var;
Impl(std::vector<std::string> args)
: program_name(args.at(0))
, args(std::move(args))
, current_directory(fs::current_path())
, build_directories()
, project_directory()
, build_variables()
, dump_graph_mode(false)
, dump_options(false)
, dump_env(false)
, dump_targets(false)
, build_mode(false)
, build_target()
, builtin_command_args()
{ this->args.erase(this->args.begin()); }
};
Application::Application(int ac, char** av)
: Application(args_to_vector(ac, av))
{}
Application::Application(std::vector<std::string> args)
: _this(new Impl(std::move(args)))
{ _parse_args(); }
Application::~Application() {}
void Application::run()
{
if (!_this->builtin_command_args.empty())
return commands::execute(_this->builtin_command_args);
log::debug("Current directory:", _this->current_directory);
log::debug("Program name:", _this->program_name);
if (_this->build_directories.empty())
throw std::runtime_error("No build directory specified");
fs::path project_file = Build::find_project_file(_this->project_directory);
fs::path package;
char const* lib = ::getenv("CONFIGURE_LIBRARY_DIR");
if (lib != nullptr)
package = lib;
else
package = fs::canonical(
_this->program_name.parent_path().parent_path()
/ "share" / "configure" / "lib"
);
package /= "?.lua";
lua::State lua;
bind(lua);
lua.global("configure_library_dir", package.string());
lua.load(
"require 'package'\n"
"package.path = configure_library_dir\n"
);
for (auto const& directory: _this->build_directories)
{
Build build(lua, directory, _this->build_variables);
build.configure(_this->project_directory);
if (_this->dump_graph_mode)
build.dump_graphviz(std::cout);
if (!_this->print_var.empty())
{
if (!build.env().has(_this->print_var))
CONFIGURE_THROW(error::InvalidKey(_this->print_var));
std::cout << build.env().as_string(_this->print_var) << std::endl;
continue;
}
log::debug("Generating the build files in", build.directory());
auto generator = this->_generator(build);
assert(generator != nullptr);
generator->prepare();
generator->generate();
log::status("Build files generated successfully in",
build.directory(), "(", generator->name(), ")");
if (_this->dump_options)
{
std::cout << "Available options:\n";
build.dump_options(std::cout);
}
if (_this->dump_env)
{
std::cout << "Environment variables:\n";
build.dump_env(std::cout);
}
if (_this->dump_targets)
{
std::cout << "Build targets:\n";
build.dump_targets(std::cout);
}
if (_this->build_mode)
{
log::status("Starting build in", build.directory());
auto cmd = generator->build_command(_this->build_target);
int res = Process::call(cmd);
if (res != 0)
CONFIGURE_THROW(
error::BuildError("Build failed with exit code " + std::to_string(res))
<< error::path(build.directory())
<< error::command(cmd)
);
}
}
}
fs::path const& Application::program_name() const
{ return _this->program_name; }
fs::path const& Application::project_directory() const
{ return _this->project_directory; }
std::vector<fs::path> const& Application::build_directories() const
{ return _this->build_directories; }
std::unique_ptr<Generator> Application::_generator(Build& build) const
{
std::string name = build.option<std::string>(
"GENERATOR",
"Generator to use",
generators::first_available(build)
);
return generators::from_name(
name,
build,
_this->project_directory,
*build.fs().which(_this->program_name.string())
);
}
void Application::print_help()
{
std::cout
<< "Usage: " << _this->program_name
<< " [OPTION]... [BUILD_DIR]... [KEY=VALUE]...\n"
<< "\n"
<< " Configure your project's builds in one or more directories.\n"
<< "\n"
<< "Positional arguments:\n"
<< " BUILD_DIR" << " "
<< "Build directory to configure\n"
<< " KEY=VALUE" << " "
<< "Set a variable for selected build directories\n"
<< "\n"
<< "Optional arguments:\n"
<< " -G, --generator NAME" << " "
<< "Specify the generator to use (alternative to variable GENERATOR)\n"
<< " -p, --project PATH" << " "
<< "Specify the project to configure instead of detecting it\n"
<< " --dump-graph" << " "
<< "Dump the build graph\n"
<< " --dump-options" << " "
<< "Dump all options\n"
<< " --dump-env" << " "
<< "Dump all environment variables\n"
<< " -P, --print-var" << " "
<< "Print a variable and exit\n"
<< " --dump-targets" << " "
<< "Dump all targets\n"
<< " -d, --debug" << " "
<< "Enable debug output\n"
<< " -v, --verbose" << " "
<< "Enable verbose output\n"
<< " --version" << " "
<< "Print version\n"
<< " -h, --help" << " "
<< "Show this help and exit\n"
<< " -b,--build" << " "
<< "Start a build in specified directories\n"
<< " -t,--target" << " "
<< "Specify the target to build\n"
<< " -E,--execute" << " "
<< "Execute a builtin command\n"
;
}
void Application::exit()
{
::exit(0);
}
void Application::_parse_args()
{
// Searching help and version flags first (ignoring command line errors
// if any).
for (auto const& arg: _this->args)
{
if (arg == "-h" || arg == "--help")
{
this->print_help();
this->exit();
}
if (arg == "--version")
{
#ifndef CONFIGURE_VERSION_STRING
# define CONFIGURE_VERSION_STRING "unknown"
#endif
log::print("configure version", CONFIGURE_VERSION_STRING);
this->exit();
}
}
bool has_project = false;
enum class NextArg {
project, generator, target, builtin_command, print_var, other
};
NextArg next_arg = NextArg::other;
for (auto const& arg: _this->args)
{
if (next_arg == NextArg::project)
{
if (!is_project_directory(arg))
throw std::runtime_error{"Invalid project directory"};
if (!has_project)
{
_this->project_directory = fs::canonical(arg);
has_project = true;
}
else if (_this->project_directory == fs::canonical(arg))
{
std::cerr << "Warning: Project directory specified more than once.\n";
}
else
{
throw std::runtime_error{"Cannot operate on multiple projects"};
}
next_arg = NextArg::other;
}
else if (next_arg == NextArg::generator)
{
_this->build_variables["GENERATOR"] = arg;
next_arg = NextArg::other;
}
else if (next_arg == NextArg::target)
{
_this->build_target = arg;
next_arg = NextArg::other;
}
else if (next_arg == NextArg::print_var)
{
_this->print_var = arg;
next_arg = NextArg::other;
log::level() = log::Level::error;
}
else if (next_arg == NextArg::builtin_command)
_this->builtin_command_args.push_back(arg);
else if (arg == "-p" || arg == "--project")
next_arg = NextArg::project;
else if (arg == "--dump-graph")
_this->dump_graph_mode = true;
else if (arg == "--dump-options")
_this->dump_options = true;
else if (arg == "--dump-env")
_this->dump_env = true;
else if (arg == "-P" || arg == "--print-var")
next_arg = NextArg::print_var;
else if (arg == "--dump-targets")
_this->dump_targets = true;
else if (arg == "-G" || arg == "--generator")
next_arg = NextArg::generator;
else if (arg == "-d" || arg == "--debug")
log::level() = log::Level::debug;
else if (arg == "-v" || arg == "--verbose")
log::level() = log::Level::verbose;
else if (arg == "-t" || arg == "--target")
next_arg = NextArg::target;
else if (arg == "-b" || arg == "--build")
_this->build_mode = true;
else if (arg == "-E" || arg == "--execute")
next_arg = NextArg::builtin_command;
else if (arg.find('=') != std::string::npos)
{
auto it = arg.find('=');
if (it != std::string::npos)
{
_this->build_variables[arg.substr(0, it)] =
arg.substr(it + 1, std::string::npos);
continue;
}
}
else if (is_build_directory(arg) ||
!fs::exists(arg) ||
(fs::is_directory(arg) && fs::is_empty(arg)))
{
_this->build_directories.push_back(fs::absolute(arg));
}
else
{
CONFIGURE_THROW(
error::InvalidArgument("Unknown argument '" + arg + "'")
);
}
}
if (next_arg != NextArg::other && next_arg != NextArg::builtin_command)
{
CONFIGURE_THROW(
error::InvalidArgument(
"Missing argument for flag '" + _this->args.back() + "'"
)
);
}
if (!has_project && _this->builtin_command_args.empty())
{
if (is_project_directory(_this->current_directory))
_this->project_directory = _this->current_directory;
else
throw std::runtime_error{"No project to configure"};
}
}
}
<commit_msg>Make missing configure library error explicit.<commit_after>#include "Application.hpp"
#include "log.hpp"
#include "lua/State.hpp"
#include "Build.hpp"
#include "bind.hpp"
#include "quote.hpp"
#include "commands.hpp"
#include "Filesystem.hpp"
#include "Process.hpp"
#include "generators.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
#include <algorithm>
#include <iostream>
#include <map>
namespace fs = boost::filesystem;
namespace configure {
namespace {
std::vector<std::string> args_to_vector(int ac, char ** av)
{
std::vector<std::string> res;
for (int i = 0; i < ac; ++i)
res.push_back(av[i]);
return res;
}
bool is_project_directory(fs::path const& dir)
{
for (auto&& p: Build::possible_configure_files())
if (fs::is_regular_file(dir / p))
return true;
return false;
}
bool is_build_directory(fs::path const& dir)
{
return fs::is_regular_file(dir / ".build" / "env");
}
}
struct Application::Impl
{
fs::path program_name;
std::vector<std::string> args;
path_t current_directory;
std::vector<path_t> build_directories;
path_t project_directory;
std::map<std::string, std::string> build_variables;
bool dump_graph_mode;
bool dump_options;
bool dump_env;
bool dump_targets;
bool build_mode;
std::string build_target;
std::vector<std::string> builtin_command_args;
std::string print_var;
Impl(std::vector<std::string> args)
: program_name(args.at(0))
, args(std::move(args))
, current_directory(fs::current_path())
, build_directories()
, project_directory()
, build_variables()
, dump_graph_mode(false)
, dump_options(false)
, dump_env(false)
, dump_targets(false)
, build_mode(false)
, build_target()
, builtin_command_args()
{ this->args.erase(this->args.begin()); }
};
Application::Application(int ac, char** av)
: Application(args_to_vector(ac, av))
{}
Application::Application(std::vector<std::string> args)
: _this(new Impl(std::move(args)))
{ _parse_args(); }
Application::~Application() {}
void Application::run()
{
if (!_this->builtin_command_args.empty())
return commands::execute(_this->builtin_command_args);
log::debug("Current directory:", _this->current_directory);
log::debug("Program name:", _this->program_name);
if (_this->build_directories.empty())
throw std::runtime_error("No build directory specified");
fs::path project_file = Build::find_project_file(_this->project_directory);
fs::path package;
char const* lib = ::getenv("CONFIGURE_LIBRARY_DIR");
if (lib != nullptr)
package = lib;
else
package = fs::absolute(
_this->program_name.parent_path().parent_path()
/ "share" / "configure" / "lib"
);
if (!fs::is_directory(package))
{
CONFIGURE_THROW(
error::BuildError("Cannot find configure library")
<< error::path(package)
);
}
package = fs::canonical(package);
package /= "?.lua";
lua::State lua;
bind(lua);
lua.global("configure_library_dir", package.string());
lua.load(
"require 'package'\n"
"package.path = configure_library_dir\n"
);
for (auto const& directory: _this->build_directories)
{
Build build(lua, directory, _this->build_variables);
build.configure(_this->project_directory);
if (_this->dump_graph_mode)
build.dump_graphviz(std::cout);
if (!_this->print_var.empty())
{
if (!build.env().has(_this->print_var))
CONFIGURE_THROW(error::InvalidKey(_this->print_var));
std::cout << build.env().as_string(_this->print_var) << std::endl;
continue;
}
log::debug("Generating the build files in", build.directory());
auto generator = this->_generator(build);
assert(generator != nullptr);
generator->prepare();
generator->generate();
log::status("Build files generated successfully in",
build.directory(), "(", generator->name(), ")");
if (_this->dump_options)
{
std::cout << "Available options:\n";
build.dump_options(std::cout);
}
if (_this->dump_env)
{
std::cout << "Environment variables:\n";
build.dump_env(std::cout);
}
if (_this->dump_targets)
{
std::cout << "Build targets:\n";
build.dump_targets(std::cout);
}
if (_this->build_mode)
{
log::status("Starting build in", build.directory());
auto cmd = generator->build_command(_this->build_target);
int res = Process::call(cmd);
if (res != 0)
CONFIGURE_THROW(
error::BuildError("Build failed with exit code " + std::to_string(res))
<< error::path(build.directory())
<< error::command(cmd)
);
}
}
}
fs::path const& Application::program_name() const
{ return _this->program_name; }
fs::path const& Application::project_directory() const
{ return _this->project_directory; }
std::vector<fs::path> const& Application::build_directories() const
{ return _this->build_directories; }
std::unique_ptr<Generator> Application::_generator(Build& build) const
{
std::string name = build.option<std::string>(
"GENERATOR",
"Generator to use",
generators::first_available(build)
);
return generators::from_name(
name,
build,
_this->project_directory,
*build.fs().which(_this->program_name.string())
);
}
void Application::print_help()
{
std::cout
<< "Usage: " << _this->program_name
<< " [OPTION]... [BUILD_DIR]... [KEY=VALUE]...\n"
<< "\n"
<< " Configure your project's builds in one or more directories.\n"
<< "\n"
<< "Positional arguments:\n"
<< " BUILD_DIR" << " "
<< "Build directory to configure\n"
<< " KEY=VALUE" << " "
<< "Set a variable for selected build directories\n"
<< "\n"
<< "Optional arguments:\n"
<< " -G, --generator NAME" << " "
<< "Specify the generator to use (alternative to variable GENERATOR)\n"
<< " -p, --project PATH" << " "
<< "Specify the project to configure instead of detecting it\n"
<< " --dump-graph" << " "
<< "Dump the build graph\n"
<< " --dump-options" << " "
<< "Dump all options\n"
<< " --dump-env" << " "
<< "Dump all environment variables\n"
<< " -P, --print-var" << " "
<< "Print a variable and exit\n"
<< " --dump-targets" << " "
<< "Dump all targets\n"
<< " -d, --debug" << " "
<< "Enable debug output\n"
<< " -v, --verbose" << " "
<< "Enable verbose output\n"
<< " --version" << " "
<< "Print version\n"
<< " -h, --help" << " "
<< "Show this help and exit\n"
<< " -b,--build" << " "
<< "Start a build in specified directories\n"
<< " -t,--target" << " "
<< "Specify the target to build\n"
<< " -E,--execute" << " "
<< "Execute a builtin command\n"
;
}
void Application::exit()
{
::exit(0);
}
void Application::_parse_args()
{
// Searching help and version flags first (ignoring command line errors
// if any).
for (auto const& arg: _this->args)
{
if (arg == "-h" || arg == "--help")
{
this->print_help();
this->exit();
}
if (arg == "--version")
{
#ifndef CONFIGURE_VERSION_STRING
# define CONFIGURE_VERSION_STRING "unknown"
#endif
log::print("configure version", CONFIGURE_VERSION_STRING);
this->exit();
}
}
bool has_project = false;
enum class NextArg {
project, generator, target, builtin_command, print_var, other
};
NextArg next_arg = NextArg::other;
for (auto const& arg: _this->args)
{
if (next_arg == NextArg::project)
{
if (!is_project_directory(arg))
throw std::runtime_error{"Invalid project directory"};
if (!has_project)
{
_this->project_directory = fs::canonical(arg);
has_project = true;
}
else if (_this->project_directory == fs::canonical(arg))
{
std::cerr << "Warning: Project directory specified more than once.\n";
}
else
{
throw std::runtime_error{"Cannot operate on multiple projects"};
}
next_arg = NextArg::other;
}
else if (next_arg == NextArg::generator)
{
_this->build_variables["GENERATOR"] = arg;
next_arg = NextArg::other;
}
else if (next_arg == NextArg::target)
{
_this->build_target = arg;
next_arg = NextArg::other;
}
else if (next_arg == NextArg::print_var)
{
_this->print_var = arg;
next_arg = NextArg::other;
log::level() = log::Level::error;
}
else if (next_arg == NextArg::builtin_command)
_this->builtin_command_args.push_back(arg);
else if (arg == "-p" || arg == "--project")
next_arg = NextArg::project;
else if (arg == "--dump-graph")
_this->dump_graph_mode = true;
else if (arg == "--dump-options")
_this->dump_options = true;
else if (arg == "--dump-env")
_this->dump_env = true;
else if (arg == "-P" || arg == "--print-var")
next_arg = NextArg::print_var;
else if (arg == "--dump-targets")
_this->dump_targets = true;
else if (arg == "-G" || arg == "--generator")
next_arg = NextArg::generator;
else if (arg == "-d" || arg == "--debug")
log::level() = log::Level::debug;
else if (arg == "-v" || arg == "--verbose")
log::level() = log::Level::verbose;
else if (arg == "-t" || arg == "--target")
next_arg = NextArg::target;
else if (arg == "-b" || arg == "--build")
_this->build_mode = true;
else if (arg == "-E" || arg == "--execute")
next_arg = NextArg::builtin_command;
else if (arg.find('=') != std::string::npos)
{
auto it = arg.find('=');
if (it != std::string::npos)
{
_this->build_variables[arg.substr(0, it)] =
arg.substr(it + 1, std::string::npos);
continue;
}
}
else if (is_build_directory(arg) ||
!fs::exists(arg) ||
(fs::is_directory(arg) && fs::is_empty(arg)))
{
_this->build_directories.push_back(fs::absolute(arg));
}
else
{
CONFIGURE_THROW(
error::InvalidArgument("Unknown argument '" + arg + "'")
);
}
}
if (next_arg != NextArg::other && next_arg != NextArg::builtin_command)
{
CONFIGURE_THROW(
error::InvalidArgument(
"Missing argument for flag '" + _this->args.back() + "'"
)
);
}
if (!has_project && _this->builtin_command_args.empty())
{
if (is_project_directory(_this->current_directory))
_this->project_directory = _this->current_directory;
else
throw std::runtime_error{"No project to configure"};
}
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (people-users@projects.maemo.org)
**
** This file is part of contactsd.
**
** If you have questions regarding the use of this file, please contact
** Nokia at people-users@projects.maemo.org.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "contactsdpluginloader.h"
#include "contactsdplugininterface.h"
#include <QDebug>
#include <QDir>
#include <QPluginLoader>
#include <QVariant>
ContactsdPluginLoader::ContactsdPluginLoader()
{
(void) new ImportNotifierAdaptor(this);
registerNotificationService();
}
ContactsdPluginLoader::~ContactsdPluginLoader()
{
PluginStore::const_iterator it = mPluginStore.constBegin();
PluginStore::const_iterator end = mPluginStore.constEnd();
while (it != end) {
it.value()->unload();
it.value()->deleteLater();
++it;
}
mPluginStore.clear();
}
void ContactsdPluginLoader::loadPlugins(const QStringList &plugins)
{
QStringList pluginsDirs;
QString pluginsDirsEnv = QString::fromLocal8Bit(
qgetenv("CONTACTSD_PLUGINS_DIRS"));
if (pluginsDirsEnv.isEmpty()) {
pluginsDirs << CONTACTSD_PLUGINS_DIR;
} else {
pluginsDirs << pluginsDirsEnv.split(':');
}
foreach (const QString &pluginsDir, pluginsDirs) {
loadPlugins(pluginsDir, plugins);
}
}
void ContactsdPluginLoader::loadPlugins(const QString &pluginsDir,
const QStringList &plugins)
{
QPluginLoader *loader;
QDir dir(pluginsDir);
dir.setFilter(QDir::Files | QDir::NoSymLinks);
foreach (const QString &fileName, dir.entryList()) {
QString absFileName(dir.absoluteFilePath(fileName));
qDebug() << "Trying to load plugin" << absFileName;
loader = new QPluginLoader(absFileName);
if (!loader->load()) {
qWarning() << "Error loading plugin" << absFileName <<
"-" << loader->errorString();
delete loader;
continue;
}
QObject *basePlugin = loader->instance();
ContactsdPluginInterface *plugin =
qobject_cast<ContactsdPluginInterface *>(basePlugin);
if (!plugin) {
qWarning() << "Error loading plugin" << absFileName << "- does not "
"implement ContactsdPluginInterface";
loader->unload();
delete loader;
continue;
}
ContactsdPluginInterface::PluginMetaData metaData = plugin->metaData();
if (!metaData.contains(CONTACTSD_PLUGIN_NAME)) {
qWarning() << "Error loading plugin" << absFileName <<
"- invalid plugin metadata";
loader->unload();
delete loader;
continue;
}
QString pluginName = metaData[CONTACTSD_PLUGIN_NAME].toString();
if (!plugins.contains(pluginName)) {
qWarning() << "Ignoring plugin" << absFileName;
loader->unload();
delete loader;
continue;
}
if (mPluginStore.contains(pluginName)) {
qWarning() << "Ignoring plugin" << absFileName <<
"- plugin with name" << pluginName << "already registered";
loader->unload();
delete loader;
continue;
}
qDebug() << "Plugin" << pluginName << "loaded";
mPluginStore.insert(pluginName, loader);
connect(basePlugin,
SIGNAL(importStarted()),
SIGNAL(importStarted()));
connect(basePlugin,
SIGNAL(importEnded(int, int, int)),
SIGNAL(importEnded(int, int, int)));
plugin->init();
}
}
QStringList ContactsdPluginLoader::loadedPlugins() const
{
return mPluginStore.keys();
}
bool ContactsdPluginLoader::hasActiveImports()
{
foreach (const QString &pluginName, loadedPlugins()) {
QPluginLoader *loader = mPluginStore[pluginName];
QObject *basePlugin = loader->instance();
ContactsdPluginInterface *plugin =
qobject_cast<ContactsdPluginInterface *>(basePlugin);
if (plugin->hasActiveImports()) {
return true;
}
}
return false;
}
void ContactsdPluginLoader::registerNotificationService()
{
QDBusConnection connection = QDBusConnection::sessionBus();
if (!connection.isConnected()) {
qWarning() << "Could not connect to DBus:" << connection.lastError();
}
if (!connection.registerService("com.nokia.contacts.importprogress")) {
qWarning() << "Could not register DBus service "
"'com.nokia.contacts.importprogress':" << connection.lastError();
}
if (!connection.registerObject("/", this)) {
qWarning() << "Could not register DBus object '/':" <<
connection.lastError();
}
}
<commit_msg>ContactsdPluginLoader: Load all plugins if none is specified in the command line.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (people-users@projects.maemo.org)
**
** This file is part of contactsd.
**
** If you have questions regarding the use of this file, please contact
** Nokia at people-users@projects.maemo.org.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "contactsdpluginloader.h"
#include "contactsdplugininterface.h"
#include <QDebug>
#include <QDir>
#include <QPluginLoader>
#include <QVariant>
ContactsdPluginLoader::ContactsdPluginLoader()
{
(void) new ImportNotifierAdaptor(this);
registerNotificationService();
}
ContactsdPluginLoader::~ContactsdPluginLoader()
{
PluginStore::const_iterator it = mPluginStore.constBegin();
PluginStore::const_iterator end = mPluginStore.constEnd();
while (it != end) {
it.value()->unload();
it.value()->deleteLater();
++it;
}
mPluginStore.clear();
}
void ContactsdPluginLoader::loadPlugins(const QStringList &plugins)
{
QStringList pluginsDirs;
QString pluginsDirsEnv = QString::fromLocal8Bit(
qgetenv("CONTACTSD_PLUGINS_DIRS"));
if (pluginsDirsEnv.isEmpty()) {
pluginsDirs << CONTACTSD_PLUGINS_DIR;
} else {
pluginsDirs << pluginsDirsEnv.split(':');
}
foreach (const QString &pluginsDir, pluginsDirs) {
loadPlugins(pluginsDir, plugins);
}
}
void ContactsdPluginLoader::loadPlugins(const QString &pluginsDir,
const QStringList &plugins)
{
QPluginLoader *loader;
QDir dir(pluginsDir);
dir.setFilter(QDir::Files | QDir::NoSymLinks);
foreach (const QString &fileName, dir.entryList()) {
QString absFileName(dir.absoluteFilePath(fileName));
qDebug() << "Trying to load plugin" << absFileName;
loader = new QPluginLoader(absFileName);
if (!loader->load()) {
qWarning() << "Error loading plugin" << absFileName <<
"-" << loader->errorString();
delete loader;
continue;
}
QObject *basePlugin = loader->instance();
ContactsdPluginInterface *plugin =
qobject_cast<ContactsdPluginInterface *>(basePlugin);
if (!plugin) {
qWarning() << "Error loading plugin" << absFileName << "- does not "
"implement ContactsdPluginInterface";
loader->unload();
delete loader;
continue;
}
ContactsdPluginInterface::PluginMetaData metaData = plugin->metaData();
if (!metaData.contains(CONTACTSD_PLUGIN_NAME)) {
qWarning() << "Error loading plugin" << absFileName <<
"- invalid plugin metadata";
loader->unload();
delete loader;
continue;
}
QString pluginName = metaData[CONTACTSD_PLUGIN_NAME].toString();
if (!plugins.isEmpty() && !plugins.contains(pluginName)) {
qWarning() << "Ignoring plugin" << absFileName;
loader->unload();
delete loader;
continue;
}
if (mPluginStore.contains(pluginName)) {
qWarning() << "Ignoring plugin" << absFileName <<
"- plugin with name" << pluginName << "already registered";
loader->unload();
delete loader;
continue;
}
qDebug() << "Plugin" << pluginName << "loaded";
mPluginStore.insert(pluginName, loader);
connect(basePlugin,
SIGNAL(importStarted()),
SIGNAL(importStarted()));
connect(basePlugin,
SIGNAL(importEnded(int, int, int)),
SIGNAL(importEnded(int, int, int)));
plugin->init();
}
}
QStringList ContactsdPluginLoader::loadedPlugins() const
{
return mPluginStore.keys();
}
bool ContactsdPluginLoader::hasActiveImports()
{
foreach (const QString &pluginName, loadedPlugins()) {
QPluginLoader *loader = mPluginStore[pluginName];
QObject *basePlugin = loader->instance();
ContactsdPluginInterface *plugin =
qobject_cast<ContactsdPluginInterface *>(basePlugin);
if (plugin->hasActiveImports()) {
return true;
}
}
return false;
}
void ContactsdPluginLoader::registerNotificationService()
{
QDBusConnection connection = QDBusConnection::sessionBus();
if (!connection.isConnected()) {
qWarning() << "Could not connect to DBus:" << connection.lastError();
}
if (!connection.registerService("com.nokia.contacts.importprogress")) {
qWarning() << "Could not register DBus service "
"'com.nokia.contacts.importprogress':" << connection.lastError();
}
if (!connection.registerObject("/", this)) {
qWarning() << "Could not register DBus object '/':" <<
connection.lastError();
}
}
<|endoftext|> |
<commit_before>/*
* ALURE OpenAL utility library
* Copyright (c) 2009-2010 by Chris Robinson.
*
* 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 "config.h"
#include "main.h"
#include <string.h>
#include <assert.h>
#include <istream>
#include <FLAC/all.h>
#ifdef _WIN32
#define FLAC_LIB "libFLAC.dll"
#elif defined(__APPLE__)
#define FLAC_LIB "libFLAC.8.dylib"
#else
#define FLAC_LIB "libFLAC.so.8"
#endif
static void *flac_handle;
#define MAKE_FUNC(x) static typeof(x)* p##x
MAKE_FUNC(FLAC__stream_decoder_get_state);
MAKE_FUNC(FLAC__stream_decoder_finish);
MAKE_FUNC(FLAC__stream_decoder_new);
MAKE_FUNC(FLAC__stream_decoder_seek_absolute);
MAKE_FUNC(FLAC__stream_decoder_delete);
MAKE_FUNC(FLAC__stream_decoder_get_total_samples);
MAKE_FUNC(FLAC__stream_decoder_process_single);
MAKE_FUNC(FLAC__stream_decoder_init_stream);
#undef MAKE_FUNC
struct flacStream : public alureStream {
private:
FLAC__StreamDecoder *flacFile;
ALenum format;
ALuint samplerate;
ALuint blockAlign;
ALboolean useFloat;
std::vector<ALubyte> initialData;
ALubyte *outBytes;
ALuint outMax;
ALuint outLen;
public:
static void Init()
{
flac_handle = OpenLib(FLAC_LIB);
if(!flac_handle) return;
LOAD_FUNC(flac_handle, FLAC__stream_decoder_get_state);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_finish);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_new);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_seek_absolute);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_delete);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_get_total_samples);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_process_single);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_init_stream);
}
static void Deinit()
{
if(flac_handle)
CloseLib(flac_handle);
flac_handle = NULL;
}
virtual bool IsValid()
{ return flacFile != NULL; }
virtual bool GetFormat(ALenum *fmt, ALuint *frequency, ALuint *blockalign)
{
*fmt = format;
*frequency = samplerate;
*blockalign = blockAlign;
return true;
}
virtual ALuint GetData(ALubyte *data, ALuint bytes)
{
outBytes = data;
outLen = 0;
outMax = bytes;
if(initialData.size() > 0)
{
size_t rem = std::min(initialData.size(), (size_t)bytes);
memcpy(data, &initialData[0], rem);
outLen += rem;
initialData.erase(initialData.begin(), initialData.begin()+rem);
}
while(outLen < outMax)
{
if(pFLAC__stream_decoder_process_single(flacFile) == false ||
pFLAC__stream_decoder_get_state(flacFile) == FLAC__STREAM_DECODER_END_OF_STREAM)
break;
}
return outLen;
}
virtual bool Rewind()
{
if(pFLAC__stream_decoder_seek_absolute(flacFile, 0) != false)
{
initialData.clear();
return true;
}
SetError("Seek failed");
return false;
}
virtual alureInt64 GetLength()
{
return pFLAC__stream_decoder_get_total_samples(flacFile);
}
flacStream(std::istream *_fstream)
: alureStream(_fstream), flacFile(NULL), format(AL_NONE), samplerate(0),
blockAlign(0), useFloat(AL_FALSE)
{
if(!flac_handle) return;
flacFile = pFLAC__stream_decoder_new();
if(flacFile)
{
if(pFLAC__stream_decoder_init_stream(flacFile, ReadCallback, SeekCallback, TellCallback, LengthCallback, EofCallback, WriteCallback, MetadataCallback, ErrorCallback, this) == FLAC__STREAM_DECODER_INIT_STATUS_OK)
{
if(InitFlac())
{
// all ok
return;
}
pFLAC__stream_decoder_finish(flacFile);
}
pFLAC__stream_decoder_delete(flacFile);
flacFile = NULL;
}
}
virtual ~flacStream()
{
if(flacFile)
{
pFLAC__stream_decoder_finish(flacFile);
pFLAC__stream_decoder_delete(flacFile);
flacFile = NULL;
}
}
private:
bool InitFlac()
{
// We need to decode some data to be able to get the channel count, bit
// depth, and sample rate. It also ensures the file has FLAC data, as
// the FLAC__stream_decoder_init_* functions can succeed on non-FLAC
// Ogg files.
outBytes = NULL;
outMax = 0;
outLen = 0;
while(initialData.size() == 0)
{
if(pFLAC__stream_decoder_process_single(flacFile) == false ||
pFLAC__stream_decoder_get_state(flacFile) == FLAC__STREAM_DECODER_END_OF_STREAM)
break;
}
if(initialData.size() > 0)
return true;
return false;
}
template<ALuint shift, ALint offset, typename T>
static void CopySamples(T *data, const FLAC__int32 *const buffer[], ALuint off, ALuint todo, ALuint channels)
{
for(ALuint i = 0;i < todo;i++)
{
for(ALuint c = 0;c < channels;c++)
*(data++) = (buffer[c][off+i]>>shift) + offset;
}
}
template<ALuint bits>
static void CopySamplesFloat(ALfloat *data, const FLAC__int32 *const buffer[], ALuint off, ALuint todo, ALuint channels)
{
for(ALuint i = 0;i < todo;i++)
{
for(ALuint c = 0;c < channels;c++)
*(data++) = buffer[c][off+i] * (1./((1u<<(bits-1))-1));
}
}
static FLAC__StreamDecoderWriteStatus WriteCallback(const FLAC__StreamDecoder*, const FLAC__Frame *frame, const FLAC__int32 *const buffer[], void *client_data)
{
flacStream *self = static_cast<flacStream*>(client_data);
if(self->format == AL_NONE)
{
ALuint bps = frame->header.bits_per_sample;
if(bps == 24 || bps == 32)
{
self->format = GetSampleFormat(frame->header.channels, 32, true);
if(self->format != AL_NONE)
{
self->useFloat = AL_TRUE;
bps = 32;
}
else bps = 16;
}
if(self->format == AL_NONE)
self->format = GetSampleFormat(frame->header.channels, bps, false);
self->blockAlign = frame->header.channels * bps/8;
self->samplerate = frame->header.sample_rate;
}
ALubyte *data = self->outBytes + self->outLen;
ALuint todo = std::min<ALuint>((self->outMax-self->outLen) / self->blockAlign,
frame->header.blocksize);
if(frame->header.bits_per_sample == 8)
CopySamples<0,128>((ALubyte*)data, buffer, 0,
todo, frame->header.channels);
else if(frame->header.bits_per_sample == 16)
CopySamples<0,0>((ALshort*)data, buffer, 0,
todo, frame->header.channels);
else if(frame->header.bits_per_sample == 24)
{
if(self->useFloat)
CopySamplesFloat<24>((ALfloat*)data, buffer, 0,
todo, frame->header.channels);
else
CopySamples<8,0>((ALshort*)data, buffer, 0,
todo, frame->header.channels);
}
else if(frame->header.bits_per_sample == 32)
{
if(self->useFloat)
CopySamplesFloat<32>((ALfloat*)data, buffer, 0,
todo, frame->header.channels);
else
CopySamples<16,0>((ALshort*)data, buffer, 0,
todo, frame->header.channels);
}
self->outLen += self->blockAlign * todo;
if(todo < frame->header.blocksize)
{
ALuint offset = todo;
todo = frame->header.blocksize - todo;
ALuint blocklen = todo * self->blockAlign;
ALuint start = self->initialData.size();
self->initialData.resize(start+blocklen);
data = &self->initialData[start];
if(frame->header.bits_per_sample == 8)
CopySamples<0,128>((ALubyte*)data, buffer, offset,
todo, frame->header.channels);
else if(frame->header.bits_per_sample == 16)
CopySamples<0,0>((ALshort*)data, buffer, offset,
todo, frame->header.channels);
else if(frame->header.bits_per_sample == 24)
{
if(self->useFloat)
CopySamplesFloat<24>((ALfloat*)data, buffer, offset,
todo, frame->header.channels);
else
CopySamples<8,0>((ALshort*)data, buffer, offset,
todo, frame->header.channels);
}
else if(frame->header.bits_per_sample == 32)
{
if(self->useFloat)
CopySamplesFloat<32>((ALfloat*)data, buffer, offset,
todo, frame->header.channels);
else
CopySamples<16,0>((ALshort*)data, buffer, offset,
todo, frame->header.channels);
}
}
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
}
static void MetadataCallback(const FLAC__StreamDecoder*,const FLAC__StreamMetadata*,void*)
{
}
static void ErrorCallback(const FLAC__StreamDecoder*,FLAC__StreamDecoderErrorStatus,void*)
{
}
static FLAC__StreamDecoderReadStatus ReadCallback(const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t *bytes, void *client_data)
{
std::istream *stream = static_cast<flacStream*>(client_data)->fstream;
stream->clear();
if(*bytes <= 0)
return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
stream->read(reinterpret_cast<char*>(buffer), *bytes);
*bytes = stream->gcount();
if(*bytes == 0 && stream->eof())
return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
}
static FLAC__StreamDecoderSeekStatus SeekCallback(const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void *client_data)
{
std::istream *stream = static_cast<flacStream*>(client_data)->fstream;
stream->clear();
if(!stream->seekg(absolute_byte_offset))
return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
}
static FLAC__StreamDecoderTellStatus TellCallback(const FLAC__StreamDecoder*, FLAC__uint64 *absolute_byte_offset, void *client_data)
{
std::istream *stream = static_cast<flacStream*>(client_data)->fstream;
stream->clear();
*absolute_byte_offset = stream->tellg();
return FLAC__STREAM_DECODER_TELL_STATUS_OK;
}
static FLAC__StreamDecoderLengthStatus LengthCallback(const FLAC__StreamDecoder*, FLAC__uint64 *stream_length, void *client_data)
{
std::istream *stream = static_cast<flacStream*>(client_data)->fstream;
stream->clear();
std::streampos pos = stream->tellg();
if(stream->seekg(0, std::ios_base::end))
{
*stream_length = stream->tellg();
stream->seekg(pos);
}
if(!stream->good())
return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
}
static FLAC__bool EofCallback(const FLAC__StreamDecoder*, void *client_data)
{
std::istream *stream = static_cast<flacStream*>(client_data)->fstream;
return (stream->eof()) ? true : false;
}
};
// Priority = 1, so it's preferred over libsndfile
static DecoderDecl<flacStream,1> flacStream_decoder;
Decoder &alure_init_flac(void)
{ return flacStream_decoder; }
<commit_msg>Avoid calling function pointers for FLAC directly<commit_after>/*
* ALURE OpenAL utility library
* Copyright (c) 2009-2010 by Chris Robinson.
*
* 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 "config.h"
#include "main.h"
#include <string.h>
#include <assert.h>
#include <istream>
#include <FLAC/all.h>
#ifdef DYNLOAD
static void *flac_handle;
#define MAKE_FUNC(x) static typeof(x)* p##x
MAKE_FUNC(FLAC__stream_decoder_get_state);
MAKE_FUNC(FLAC__stream_decoder_finish);
MAKE_FUNC(FLAC__stream_decoder_new);
MAKE_FUNC(FLAC__stream_decoder_seek_absolute);
MAKE_FUNC(FLAC__stream_decoder_delete);
MAKE_FUNC(FLAC__stream_decoder_get_total_samples);
MAKE_FUNC(FLAC__stream_decoder_process_single);
MAKE_FUNC(FLAC__stream_decoder_init_stream);
#undef MAKE_FUNC
#define FLAC__stream_decoder_get_state pFLAC__stream_decoder_get_state
#define FLAC__stream_decoder_finish pFLAC__stream_decoder_finish
#define FLAC__stream_decoder_new pFLAC__stream_decoder_new
#define FLAC__stream_decoder_seek_absolute pFLAC__stream_decoder_seek_absolute
#define FLAC__stream_decoder_delete pFLAC__stream_decoder_delete
#define FLAC__stream_decoder_get_total_samples pFLAC__stream_decoder_get_total_samples
#define FLAC__stream_decoder_process_single pFLAC__stream_decoder_process_single
#define FLAC__stream_decoder_init_stream pFLAC__stream_decoder_init_stream
#else
#define flac_handle 1
#endif
struct flacStream : public alureStream {
private:
FLAC__StreamDecoder *flacFile;
ALenum format;
ALuint samplerate;
ALuint blockAlign;
ALboolean useFloat;
std::vector<ALubyte> initialData;
ALubyte *outBytes;
ALuint outMax;
ALuint outLen;
public:
#ifdef DYNLOAD
static void Init()
{
#ifdef _WIN32
#define FLAC_LIB "libFLAC.dll"
#elif defined(__APPLE__)
#define FLAC_LIB "libFLAC.8.dylib"
#else
#define FLAC_LIB "libFLAC.so.8"
#endif
flac_handle = OpenLib(FLAC_LIB);
if(!flac_handle) return;
LOAD_FUNC(flac_handle, FLAC__stream_decoder_get_state);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_finish);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_new);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_seek_absolute);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_delete);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_get_total_samples);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_process_single);
LOAD_FUNC(flac_handle, FLAC__stream_decoder_init_stream);
}
static void Deinit()
{
if(flac_handle)
CloseLib(flac_handle);
flac_handle = NULL;
}
#else
static void Init() { }
static void Deinit() { }
#endif
virtual bool IsValid()
{ return flacFile != NULL; }
virtual bool GetFormat(ALenum *fmt, ALuint *frequency, ALuint *blockalign)
{
*fmt = format;
*frequency = samplerate;
*blockalign = blockAlign;
return true;
}
virtual ALuint GetData(ALubyte *data, ALuint bytes)
{
outBytes = data;
outLen = 0;
outMax = bytes;
if(initialData.size() > 0)
{
size_t rem = std::min(initialData.size(), (size_t)bytes);
memcpy(data, &initialData[0], rem);
outLen += rem;
initialData.erase(initialData.begin(), initialData.begin()+rem);
}
while(outLen < outMax)
{
if(FLAC__stream_decoder_process_single(flacFile) == false ||
FLAC__stream_decoder_get_state(flacFile) == FLAC__STREAM_DECODER_END_OF_STREAM)
break;
}
return outLen;
}
virtual bool Rewind()
{
if(FLAC__stream_decoder_seek_absolute(flacFile, 0) != false)
{
initialData.clear();
return true;
}
SetError("Seek failed");
return false;
}
virtual alureInt64 GetLength()
{
return FLAC__stream_decoder_get_total_samples(flacFile);
}
flacStream(std::istream *_fstream)
: alureStream(_fstream), flacFile(NULL), format(AL_NONE), samplerate(0),
blockAlign(0), useFloat(AL_FALSE)
{
if(!flac_handle) return;
flacFile = FLAC__stream_decoder_new();
if(flacFile)
{
if(FLAC__stream_decoder_init_stream(flacFile, ReadCallback, SeekCallback, TellCallback, LengthCallback, EofCallback, WriteCallback, MetadataCallback, ErrorCallback, this) == FLAC__STREAM_DECODER_INIT_STATUS_OK)
{
if(InitFlac())
{
// all ok
return;
}
FLAC__stream_decoder_finish(flacFile);
}
FLAC__stream_decoder_delete(flacFile);
flacFile = NULL;
}
}
virtual ~flacStream()
{
if(flacFile)
{
FLAC__stream_decoder_finish(flacFile);
FLAC__stream_decoder_delete(flacFile);
flacFile = NULL;
}
}
private:
bool InitFlac()
{
// We need to decode some data to be able to get the channel count, bit
// depth, and sample rate. It also ensures the file has FLAC data, as
// the FLAC__stream_decoder_init_* functions can succeed on non-FLAC
// Ogg files.
outBytes = NULL;
outMax = 0;
outLen = 0;
while(initialData.size() == 0)
{
if(FLAC__stream_decoder_process_single(flacFile) == false ||
FLAC__stream_decoder_get_state(flacFile) == FLAC__STREAM_DECODER_END_OF_STREAM)
break;
}
if(initialData.size() > 0)
return true;
return false;
}
template<ALuint shift, ALint offset, typename T>
static void CopySamples(T *data, const FLAC__int32 *const buffer[], ALuint off, ALuint todo, ALuint channels)
{
for(ALuint i = 0;i < todo;i++)
{
for(ALuint c = 0;c < channels;c++)
*(data++) = (buffer[c][off+i]>>shift) + offset;
}
}
template<ALuint bits>
static void CopySamplesFloat(ALfloat *data, const FLAC__int32 *const buffer[], ALuint off, ALuint todo, ALuint channels)
{
for(ALuint i = 0;i < todo;i++)
{
for(ALuint c = 0;c < channels;c++)
*(data++) = buffer[c][off+i] * (1./((1u<<(bits-1))-1));
}
}
static FLAC__StreamDecoderWriteStatus WriteCallback(const FLAC__StreamDecoder*, const FLAC__Frame *frame, const FLAC__int32 *const buffer[], void *client_data)
{
flacStream *self = static_cast<flacStream*>(client_data);
if(self->format == AL_NONE)
{
ALuint bps = frame->header.bits_per_sample;
if(bps == 24 || bps == 32)
{
self->format = GetSampleFormat(frame->header.channels, 32, true);
if(self->format != AL_NONE)
{
self->useFloat = AL_TRUE;
bps = 32;
}
else bps = 16;
}
if(self->format == AL_NONE)
self->format = GetSampleFormat(frame->header.channels, bps, false);
self->blockAlign = frame->header.channels * bps/8;
self->samplerate = frame->header.sample_rate;
}
ALubyte *data = self->outBytes + self->outLen;
ALuint todo = std::min<ALuint>((self->outMax-self->outLen) / self->blockAlign,
frame->header.blocksize);
if(frame->header.bits_per_sample == 8)
CopySamples<0,128>((ALubyte*)data, buffer, 0,
todo, frame->header.channels);
else if(frame->header.bits_per_sample == 16)
CopySamples<0,0>((ALshort*)data, buffer, 0,
todo, frame->header.channels);
else if(frame->header.bits_per_sample == 24)
{
if(self->useFloat)
CopySamplesFloat<24>((ALfloat*)data, buffer, 0,
todo, frame->header.channels);
else
CopySamples<8,0>((ALshort*)data, buffer, 0,
todo, frame->header.channels);
}
else if(frame->header.bits_per_sample == 32)
{
if(self->useFloat)
CopySamplesFloat<32>((ALfloat*)data, buffer, 0,
todo, frame->header.channels);
else
CopySamples<16,0>((ALshort*)data, buffer, 0,
todo, frame->header.channels);
}
self->outLen += self->blockAlign * todo;
if(todo < frame->header.blocksize)
{
ALuint offset = todo;
todo = frame->header.blocksize - todo;
ALuint blocklen = todo * self->blockAlign;
ALuint start = self->initialData.size();
self->initialData.resize(start+blocklen);
data = &self->initialData[start];
if(frame->header.bits_per_sample == 8)
CopySamples<0,128>((ALubyte*)data, buffer, offset,
todo, frame->header.channels);
else if(frame->header.bits_per_sample == 16)
CopySamples<0,0>((ALshort*)data, buffer, offset,
todo, frame->header.channels);
else if(frame->header.bits_per_sample == 24)
{
if(self->useFloat)
CopySamplesFloat<24>((ALfloat*)data, buffer, offset,
todo, frame->header.channels);
else
CopySamples<8,0>((ALshort*)data, buffer, offset,
todo, frame->header.channels);
}
else if(frame->header.bits_per_sample == 32)
{
if(self->useFloat)
CopySamplesFloat<32>((ALfloat*)data, buffer, offset,
todo, frame->header.channels);
else
CopySamples<16,0>((ALshort*)data, buffer, offset,
todo, frame->header.channels);
}
}
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
}
static void MetadataCallback(const FLAC__StreamDecoder*,const FLAC__StreamMetadata*,void*)
{
}
static void ErrorCallback(const FLAC__StreamDecoder*,FLAC__StreamDecoderErrorStatus,void*)
{
}
static FLAC__StreamDecoderReadStatus ReadCallback(const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t *bytes, void *client_data)
{
std::istream *stream = static_cast<flacStream*>(client_data)->fstream;
stream->clear();
if(*bytes <= 0)
return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
stream->read(reinterpret_cast<char*>(buffer), *bytes);
*bytes = stream->gcount();
if(*bytes == 0 && stream->eof())
return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
}
static FLAC__StreamDecoderSeekStatus SeekCallback(const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void *client_data)
{
std::istream *stream = static_cast<flacStream*>(client_data)->fstream;
stream->clear();
if(!stream->seekg(absolute_byte_offset))
return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
}
static FLAC__StreamDecoderTellStatus TellCallback(const FLAC__StreamDecoder*, FLAC__uint64 *absolute_byte_offset, void *client_data)
{
std::istream *stream = static_cast<flacStream*>(client_data)->fstream;
stream->clear();
*absolute_byte_offset = stream->tellg();
return FLAC__STREAM_DECODER_TELL_STATUS_OK;
}
static FLAC__StreamDecoderLengthStatus LengthCallback(const FLAC__StreamDecoder*, FLAC__uint64 *stream_length, void *client_data)
{
std::istream *stream = static_cast<flacStream*>(client_data)->fstream;
stream->clear();
std::streampos pos = stream->tellg();
if(stream->seekg(0, std::ios_base::end))
{
*stream_length = stream->tellg();
stream->seekg(pos);
}
if(!stream->good())
return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
}
static FLAC__bool EofCallback(const FLAC__StreamDecoder*, void *client_data)
{
std::istream *stream = static_cast<flacStream*>(client_data)->fstream;
return (stream->eof()) ? true : false;
}
};
// Priority = 1, so it's preferred over libsndfile
static DecoderDecl<flacStream,1> flacStream_decoder;
Decoder &alure_init_flac(void)
{ return flacStream_decoder; }
<|endoftext|> |
<commit_before>/**
* logger_metrics_test.cc
* Mich, 2014-11-17
* Copyright (c) 2014 Datacratic Inc. All rights reserved.
*
* Manual test for the logger metrics. Provide the proper json config and
* run.
**/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include "mongo/bson/bson.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/client/dbclient.h"
#include "jml/utils/filter_streams.h"
#include "soa/service/testing/mongo_temporary_server.h"
#include "soa/logger/logger_metrics_interface.h"
using namespace ML;
using namespace Datacratic;
using namespace std;
BOOST_AUTO_TEST_CASE( test_logger_metrics ) {
Mongo::MongoTemporaryServer mongo;
setenv("CONFIG", "logger/testing/logger_metrics_config.json", 1);
shared_ptr<ILoggerMetrics> logger =
ILoggerMetrics::setup("metricsLogger", "lalmetrics", "test");
logger->logMeta({"a", "b"}, "taratapom");
Json::Value config;
filter_istream cfgStream("logger/testing/logger_metrics_config.json");
cfgStream >> config;
Json::Value metricsLogger = config["metricsLogger"];
auto conn = std::make_shared<mongo::DBClientConnection>();
conn->connect(metricsLogger["hostAndPort"].asString());
string err;
if (!conn->auth(metricsLogger["database"].asString(),
metricsLogger["user"].asString(),
metricsLogger["pwd"].asString(), err)) {
throw ML::Exception("Failed to log to mongo tmp server: %s",
err.c_str());
}
BOOST_CHECK_EQUAL(conn->count("test.lalmetrics"), 1);
auto cursor = conn->query("test.lalmetrics", mongo::BSONObj());
BOOST_CHECK(cursor->more());
{
mongo::BSONObj p = cursor->next();
BOOST_CHECK_EQUAL(p.getFieldDotted("meta.a.b").String(), "taratapom");
}
logger->logMetrics({"fooValue"}, 123);
ML::sleep(1); // Leave time for async write
cursor = conn->query("test.lalmetrics", mongo::BSONObj());
BOOST_CHECK(cursor->more());
{
mongo::BSONObj p = cursor->next();
BOOST_CHECK_EQUAL(p["metrics"]["fooValue"].Number(), 123);
}
Json::Value block;
block["alpha"] = 1;
block["beta"] = 2;
block["coco"] = Json::objectValue;
block["coco"]["sanchez"] = 3;
logger->logMetrics(block);
ML::sleep(1); // Leave time for async write
cursor = conn->query("test.lalmetrics", mongo::BSONObj());
BOOST_CHECK(cursor->more());
{
mongo::BSONObj p = cursor->next();
BOOST_CHECK_EQUAL(p["metrics"]["coco"]["sanchez"].Number(), 3);
}
}
<commit_msg>logger_metrics_test: fixed filename<commit_after>/**
* logger_metrics_test.cc
* Mich, 2014-11-17
* Copyright (c) 2014 Datacratic Inc. All rights reserved.
*
* Manual test for the logger metrics. Provide the proper json config and
* run.
**/
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include "mongo/bson/bson.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/client/dbclient.h"
#include "jml/utils/filter_streams.h"
#include "soa/service/testing/mongo_temporary_server.h"
#include "soa/logger/logger_metrics_interface.h"
using namespace ML;
using namespace Datacratic;
using namespace std;
BOOST_AUTO_TEST_CASE( test_logger_metrics ) {
Mongo::MongoTemporaryServer mongo;
setenv("CONFIG", "soa/logger/testing/logger_metrics_config.json", 1);
shared_ptr<ILoggerMetrics> logger =
ILoggerMetrics::setup("metricsLogger", "lalmetrics", "test");
logger->logMeta({"a", "b"}, "taratapom");
Json::Value config;
filter_istream cfgStream("soa/logger/testing/logger_metrics_config.json");
cfgStream >> config;
Json::Value metricsLogger = config["metricsLogger"];
auto conn = std::make_shared<mongo::DBClientConnection>();
conn->connect(metricsLogger["hostAndPort"].asString());
string err;
if (!conn->auth(metricsLogger["database"].asString(),
metricsLogger["user"].asString(),
metricsLogger["pwd"].asString(), err)) {
throw ML::Exception("Failed to log to mongo tmp server: %s",
err.c_str());
}
BOOST_CHECK_EQUAL(conn->count("test.lalmetrics"), 1);
auto cursor = conn->query("test.lalmetrics", mongo::BSONObj());
BOOST_CHECK(cursor->more());
{
mongo::BSONObj p = cursor->next();
BOOST_CHECK_EQUAL(p.getFieldDotted("meta.a.b").String(), "taratapom");
}
logger->logMetrics({"fooValue"}, 123);
ML::sleep(1); // Leave time for async write
cursor = conn->query("test.lalmetrics", mongo::BSONObj());
BOOST_CHECK(cursor->more());
{
mongo::BSONObj p = cursor->next();
BOOST_CHECK_EQUAL(p["metrics"]["fooValue"].Number(), 123);
}
Json::Value block;
block["alpha"] = 1;
block["beta"] = 2;
block["coco"] = Json::objectValue;
block["coco"]["sanchez"] = 3;
logger->logMetrics(block);
ML::sleep(1); // Leave time for async write
cursor = conn->query("test.lalmetrics", mongo::BSONObj());
BOOST_CHECK(cursor->more());
{
mongo::BSONObj p = cursor->next();
BOOST_CHECK_EQUAL(p["metrics"]["coco"]["sanchez"].Number(), 3);
}
}
<|endoftext|> |
<commit_before>#include <composite.hpp>
#include <sphere.hpp>
#include <box.hpp>
#include <triangle.hpp>
#include <shape.hpp>
Composite::Composite() :
Shape{{{INFINITY,INFINITY,INFINITY},{-INFINITY,-INFINITY,-INFINITY}}},
shapes_{}
{}
Composite::Composite(std::string const& name) :
Shape{Material{}, name, {{INFINITY,INFINITY,INFINITY},{-INFINITY,-INFINITY,-INFINITY}}},
shapes_{}
{}
Composite::~Composite() {}
void Composite::add(std::shared_ptr<Shape>& shape) {
shapes_.insert(shapes_.begin(),std::pair<std::string,std::shared_ptr<Shape>>(shape->name(),shape));
}
void Composite::remove(std::string const& name) {
shapes_.erase(name);
}
std::ostream& Composite::print(std::ostream& os) const {
for(auto element : shapes_) {
element.second->print(os);
}
return os;
}
std::map<std::string, std::shared_ptr<Shape>> Composite::get_children() {
return shapes_;
}<commit_msg>composite update<commit_after>#include <composite.hpp>
Composite::Composite() :
Shape{},
shapes_{}{}
Composite::Composite(std::string const& name) :
Shape{name, Material{}},
shapes_{}{}
Composite::~Composite(){}
void Composite::add(std::shared_ptr<Shape>& shape) {
shapes_.insert(shapes_.begin(),std::pair<std::string,std::shared_ptr<Shape>>(shape->name(),shape));
}
void Composite::remove(std::string const& name) {
shapes_.erase(name);
}
std::ostream& Composite::print(std::ostream& os) const {
for(auto element : shapes_) {
element.second->print(os);
}
return os;
}
std::map<std::string, std::shared_ptr<Shape>> Composite::get_children() {
return shapes_;
}<|endoftext|> |
<commit_before>/*****************************************************************************/
/* Csv.cpp Copyright (c) Ladislav Zezula 2019 */
/*---------------------------------------------------------------------------*/
/* Implementation for the CSV handler class */
/*---------------------------------------------------------------------------*/
/* Date Ver Who Comment */
/* -------- ---- --- ------- */
/* 24.05.19 1.00 Lad Created */
/*****************************************************************************/
#define __CASCLIB_SELF__
#include "../CascLib.h"
#include "../CascCommon.h"
//-----------------------------------------------------------------------------
// Local variables
static const CASC_CSV_LINE NullLine;
#define NullColumn NullLine.Columns[0];
//-----------------------------------------------------------------------------
// Local functions
static char * NextLine_Default(void * /* pvUserData */, char * szLine)
{
// Find the end of the line
while(szLine[0] != 0 && szLine[0] != 0x0A && szLine[0] != 0x0D)
szLine++;
// Terminate the line
while(szLine[0] == 0x0A || szLine[0] == 0x0D)
*szLine++ = 0;
// If there's an end-of-string, it's over
return (szLine[0] != 0) ? szLine : NULL;
}
static char * NextColumn_Default(void * /* pvUserData */, char * szColumn)
{
// Find the end of the column
while(szColumn[0] != 0 && szColumn[0] != '|')
szColumn++;
// Terminate the column
if (szColumn[0] == '|')
{
*szColumn++ = 0;
return szColumn;
}
// If there's an end-of-string, it's over
return NULL;
}
static size_t CalcHashValue(const char * szString)
{
size_t dwHash = 0x7EEE7EEE;
// Hash the string itself
while(szString[0] != 0)
{
dwHash = (dwHash >> 24) ^ (dwHash << 5) ^ dwHash ^ szString[0];
szString++;
}
// Return the hash limited by the table size
return dwHash;
}
static BYTE HashToIndex(size_t dwHashValue)
{
return (BYTE)(dwHashValue & (CSV_HASH_TABLE_SIZE - 1));
}
//-----------------------------------------------------------------------------
// Class for CSV line
CASC_CSV_LINE::CASC_CSV_LINE()
{
m_pParent = NULL;
m_nColumns = 0;
}
CASC_CSV_LINE::~CASC_CSV_LINE()
{}
bool CASC_CSV_LINE::SetLine(CASC_CSV * pParent, char * szCsvLine)
{
CASC_CSV_NEXTPROC PfnNextColumn = pParent->GetNextColumnProc();
char * szCsvColumn;
size_t nHdrColumns = 0;
size_t nColumns = 0;
// Reset the number of column to zero
m_pParent = pParent;
m_nColumns = 0;
// Parse each column
while(szCsvLine != NULL && nColumns < CSV_MAX_COLUMNS)
{
// Get current line and the next one
szCsvColumn = szCsvLine;
szCsvLine = PfnNextColumn(pParent->GetUserData(), szCsvLine);
// Save the current line
Columns[nColumns].szValue = szCsvColumn;
Columns[nColumns].nLength = strlen(szCsvColumn);
nColumns++;
}
// Columns overflow
if(nColumns >= CSV_MAX_COLUMNS)
{
assert(false);
return false;
}
// If the parent has header lines, then the number of columns must match
// In the case of mismatched column count, ignore the line
nHdrColumns = pParent->GetHeaderColumns();
if(nHdrColumns != 0 && nColumns != nHdrColumns)
return false;
// All OK
m_nColumns = nColumns;
return true;
}
const CASC_CSV_COLUMN & CASC_CSV_LINE::operator[](const char * szColumnName) const
{
size_t nIndex;
// The column must have a hash table
if(m_pParent != NULL)
{
nIndex = m_pParent->GetColumnIndex(szColumnName);
if(nIndex != CSV_INVALID_INDEX && nIndex < m_nColumns)
{
return Columns[nIndex];
}
}
return NullColumn;
}
const CASC_CSV_COLUMN & CASC_CSV_LINE::operator[](size_t nIndex) const
{
return (nIndex < m_nColumns) ? Columns[nIndex] : NullColumn;
}
//-----------------------------------------------------------------------------
// Class for CSV object
CASC_CSV::CASC_CSV(size_t nLinesMax, bool bHasHeader)
{
// Initialize the class variables
memset(HashTable, 0xFF, sizeof(HashTable));
m_pvUserData = NULL;
m_szCsvFile = NULL;
m_szCsvPtr = NULL;
m_nCsvFile = 0;
m_nLines = 0;
m_bHasHeader = bHasHeader;
// Initialize the "NextLine" function that will serve for finding next line in the text
PfnNextLine = NextLine_Default;
PfnNextColumn = NextColumn_Default;
// Nonzero number of lines means a finite CSV handler. The CSV will be loaded at once.
// Zero means that the user needs to call LoadNextLine() and then the line data
if(nLinesMax != 0)
{
m_pLines = new CASC_CSV_LINE[nLinesMax];
m_nLinesMax = nLinesMax;
m_bHasAllLines = true;
}
else
{
m_pLines = new CASC_CSV_LINE[1];
m_nLinesMax = 1;
m_bHasAllLines = false;
}
}
CASC_CSV::~CASC_CSV()
{
if(m_pLines != NULL)
delete[] m_pLines;
if(m_szCsvFile != NULL)
delete [] m_szCsvFile;
m_szCsvFile = NULL;
}
DWORD CASC_CSV::SetNextLineProc(CASC_CSV_NEXTPROC PfnNextLineProc, CASC_CSV_NEXTPROC PfnNextColProc, void * pvUserData)
{
// Set the procedure for next line parsing
if(PfnNextLineProc != NULL)
PfnNextLine = PfnNextLineProc;
// Set procedure for next columne parsing
if(PfnNextColProc != NULL)
PfnNextColumn = PfnNextColProc;
// Save the user data
m_pvUserData = pvUserData;
return ERROR_SUCCESS;
}
DWORD CASC_CSV::Load(LPCTSTR szFileName)
{
DWORD cbFileData = 0;
DWORD dwErrCode = ERROR_SUCCESS;
m_szCsvFile = (char *)LoadFileToMemory(szFileName, &cbFileData);
if (m_szCsvFile != NULL)
{
// Assign the data to the CSV object
m_szCsvPtr = m_szCsvFile;
m_nCsvFile = cbFileData;
// Parse the data
dwErrCode = ParseCsvData() ? ERROR_SUCCESS : ERROR_BAD_FORMAT;
}
else
{
dwErrCode = GetCascError();
}
return dwErrCode;
}
DWORD CASC_CSV::Load(LPBYTE pbData, size_t cbData)
{
DWORD dwErrCode = ERROR_NOT_ENOUGH_MEMORY;
m_szCsvFile = new char[cbData + 1];
if (m_szCsvFile != NULL)
{
// Copy the entire data and terminate them with zero
memcpy(m_szCsvFile, pbData, cbData);
m_szCsvFile[cbData] = 0;
m_szCsvPtr = m_szCsvFile;
m_nCsvFile = cbData;
// Parse the data
dwErrCode = ParseCsvData() ? ERROR_SUCCESS : ERROR_BAD_FORMAT;
}
return dwErrCode;
}
bool CASC_CSV::LoadNextLine()
{
bool bResult = false;
// Only endless CSV handler can do this
if(m_bHasAllLines == false)
{
// A few checks
assert(m_pLines != NULL);
assert(m_nLinesMax == 1);
// Reset the current line and load it
bResult = LoadNextLine(m_pLines[0]);
m_nLines = (bResult) ? 1 : 0;
}
return bResult;
}
bool CASC_CSV::InitializeHashTable()
{
// Create the hash table of HeaderText -> ColumnIndex
for(size_t i = 0; i < Header.GetColumnCount(); i++)
{
// Calculate the start slot and the current slot
size_t nStartIndex = HashToIndex(CalcHashValue(Header[i].szValue));
size_t nHashIndex = nStartIndex;
// Go as long as there is not a free space
while(HashTable[nHashIndex] != 0xFF)
{
nHashIndex = HashToIndex(nHashIndex + 1);
}
// Set the slot
HashTable[nHashIndex] = (BYTE)i;
}
return true;
}
bool CASC_CSV::LoadNextLine(CASC_CSV_LINE & Line)
{
// Overwatch ROOT's header begins with "#"
if(m_szCsvPtr == m_szCsvFile && m_szCsvPtr[0] == '#')
m_szCsvPtr++;
// Parse the entire line
while(m_szCsvPtr != NULL && m_szCsvPtr[0] != 0)
{
char * szCsvLine = m_szCsvPtr;
// Get the next line
m_szCsvPtr = PfnNextLine(m_pvUserData, m_szCsvPtr);
// Initialize the line
if (Line.SetLine(this, szCsvLine))
return true;
}
// End-of-file found
return false;
}
bool CASC_CSV::ParseCsvData()
{
// Sanity checks
assert(m_nLines == 0);
// If we have header, then parse it and set the pointer to the next line
if(m_bHasHeader)
{
// Load the current line to the header
if (!LoadNextLine(Header))
return false;
// Initialize the hash table
if(!InitializeHashTable())
return false;
}
// Are we supposed to load all lines?
if(m_bHasAllLines)
{
// Parse each line
for(size_t i = 0; i < m_nLinesMax; i++)
{
if(!LoadNextLine(m_pLines[i]))
break;
m_nLines++;
}
}
return true;
}
const CASC_CSV_COLUMN & CASC_CSV::operator[](const char * szColumnName) const
{
if (m_pLines == NULL || m_nLines == 0)
return NullColumn;
return m_pLines[0][GetColumnIndex(szColumnName)];
}
const CASC_CSV_LINE & CASC_CSV::operator[](size_t nIndex) const
{
if (m_pLines == NULL || nIndex >= m_nLines)
return NullLine;
return m_pLines[nIndex];
}
size_t CASC_CSV::GetHeaderColumns() const
{
return (m_bHasHeader) ? Header.GetColumnCount() : 0;
}
size_t CASC_CSV::GetColumnIndex(const char * szColumnName) const
{
if(m_bHasHeader)
{
// Calculate the start slot and the current slot
size_t nStartIndex = HashToIndex(CalcHashValue(szColumnName));
size_t nHashIndex = nStartIndex;
size_t nIndex;
// Go as long as there is not a free space
while((nIndex = HashTable[nHashIndex]) != 0xFF)
{
// Compare the string
if(!strcmp(Header[nIndex].szValue, szColumnName))
return nIndex;
// Move to the next column
nHashIndex = HashToIndex(nHashIndex + 1);
}
}
return CSV_INVALID_INDEX;
}
<commit_msg>Don't mix C malloc with C++ delete.<commit_after>/*****************************************************************************/
/* Csv.cpp Copyright (c) Ladislav Zezula 2019 */
/*---------------------------------------------------------------------------*/
/* Implementation for the CSV handler class */
/*---------------------------------------------------------------------------*/
/* Date Ver Who Comment */
/* -------- ---- --- ------- */
/* 24.05.19 1.00 Lad Created */
/*****************************************************************************/
#define __CASCLIB_SELF__
#include "../CascLib.h"
#include "../CascCommon.h"
//-----------------------------------------------------------------------------
// Local variables
static const CASC_CSV_LINE NullLine;
#define NullColumn NullLine.Columns[0];
//-----------------------------------------------------------------------------
// Local functions
static char * NextLine_Default(void * /* pvUserData */, char * szLine)
{
// Find the end of the line
while(szLine[0] != 0 && szLine[0] != 0x0A && szLine[0] != 0x0D)
szLine++;
// Terminate the line
while(szLine[0] == 0x0A || szLine[0] == 0x0D)
*szLine++ = 0;
// If there's an end-of-string, it's over
return (szLine[0] != 0) ? szLine : NULL;
}
static char * NextColumn_Default(void * /* pvUserData */, char * szColumn)
{
// Find the end of the column
while(szColumn[0] != 0 && szColumn[0] != '|')
szColumn++;
// Terminate the column
if (szColumn[0] == '|')
{
*szColumn++ = 0;
return szColumn;
}
// If there's an end-of-string, it's over
return NULL;
}
static size_t CalcHashValue(const char * szString)
{
size_t dwHash = 0x7EEE7EEE;
// Hash the string itself
while(szString[0] != 0)
{
dwHash = (dwHash >> 24) ^ (dwHash << 5) ^ dwHash ^ szString[0];
szString++;
}
// Return the hash limited by the table size
return dwHash;
}
static BYTE HashToIndex(size_t dwHashValue)
{
return (BYTE)(dwHashValue & (CSV_HASH_TABLE_SIZE - 1));
}
//-----------------------------------------------------------------------------
// Class for CSV line
CASC_CSV_LINE::CASC_CSV_LINE()
{
m_pParent = NULL;
m_nColumns = 0;
}
CASC_CSV_LINE::~CASC_CSV_LINE()
{}
bool CASC_CSV_LINE::SetLine(CASC_CSV * pParent, char * szCsvLine)
{
CASC_CSV_NEXTPROC PfnNextColumn = pParent->GetNextColumnProc();
char * szCsvColumn;
size_t nHdrColumns = 0;
size_t nColumns = 0;
// Reset the number of column to zero
m_pParent = pParent;
m_nColumns = 0;
// Parse each column
while(szCsvLine != NULL && nColumns < CSV_MAX_COLUMNS)
{
// Get current line and the next one
szCsvColumn = szCsvLine;
szCsvLine = PfnNextColumn(pParent->GetUserData(), szCsvLine);
// Save the current line
Columns[nColumns].szValue = szCsvColumn;
Columns[nColumns].nLength = strlen(szCsvColumn);
nColumns++;
}
// Columns overflow
if(nColumns >= CSV_MAX_COLUMNS)
{
assert(false);
return false;
}
// If the parent has header lines, then the number of columns must match
// In the case of mismatched column count, ignore the line
nHdrColumns = pParent->GetHeaderColumns();
if(nHdrColumns != 0 && nColumns != nHdrColumns)
return false;
// All OK
m_nColumns = nColumns;
return true;
}
const CASC_CSV_COLUMN & CASC_CSV_LINE::operator[](const char * szColumnName) const
{
size_t nIndex;
// The column must have a hash table
if(m_pParent != NULL)
{
nIndex = m_pParent->GetColumnIndex(szColumnName);
if(nIndex != CSV_INVALID_INDEX && nIndex < m_nColumns)
{
return Columns[nIndex];
}
}
return NullColumn;
}
const CASC_CSV_COLUMN & CASC_CSV_LINE::operator[](size_t nIndex) const
{
return (nIndex < m_nColumns) ? Columns[nIndex] : NullColumn;
}
//-----------------------------------------------------------------------------
// Class for CSV object
CASC_CSV::CASC_CSV(size_t nLinesMax, bool bHasHeader)
{
// Initialize the class variables
memset(HashTable, 0xFF, sizeof(HashTable));
m_pvUserData = NULL;
m_szCsvFile = NULL;
m_szCsvPtr = NULL;
m_nCsvFile = 0;
m_nLines = 0;
m_bHasHeader = bHasHeader;
// Initialize the "NextLine" function that will serve for finding next line in the text
PfnNextLine = NextLine_Default;
PfnNextColumn = NextColumn_Default;
// Nonzero number of lines means a finite CSV handler. The CSV will be loaded at once.
// Zero means that the user needs to call LoadNextLine() and then the line data
if(nLinesMax != 0)
{
m_pLines = new CASC_CSV_LINE[nLinesMax];
m_nLinesMax = nLinesMax;
m_bHasAllLines = true;
}
else
{
m_pLines = new CASC_CSV_LINE[1];
m_nLinesMax = 1;
m_bHasAllLines = false;
}
}
CASC_CSV::~CASC_CSV()
{
if(m_pLines != NULL)
delete[] m_pLines;
CASC_FREE(m_szCsvFile);
}
DWORD CASC_CSV::SetNextLineProc(CASC_CSV_NEXTPROC PfnNextLineProc, CASC_CSV_NEXTPROC PfnNextColProc, void * pvUserData)
{
// Set the procedure for next line parsing
if(PfnNextLineProc != NULL)
PfnNextLine = PfnNextLineProc;
// Set procedure for next columne parsing
if(PfnNextColProc != NULL)
PfnNextColumn = PfnNextColProc;
// Save the user data
m_pvUserData = pvUserData;
return ERROR_SUCCESS;
}
DWORD CASC_CSV::Load(LPCTSTR szFileName)
{
DWORD cbFileData = 0;
DWORD dwErrCode = ERROR_SUCCESS;
m_szCsvFile = (char *)LoadFileToMemory(szFileName, &cbFileData);
if (m_szCsvFile != NULL)
{
// Assign the data to the CSV object
m_szCsvPtr = m_szCsvFile;
m_nCsvFile = cbFileData;
// Parse the data
dwErrCode = ParseCsvData() ? ERROR_SUCCESS : ERROR_BAD_FORMAT;
}
else
{
dwErrCode = GetCascError();
}
return dwErrCode;
}
DWORD CASC_CSV::Load(LPBYTE pbData, size_t cbData)
{
DWORD dwErrCode = ERROR_NOT_ENOUGH_MEMORY;
m_szCsvFile = new char[cbData + 1];
if (m_szCsvFile != NULL)
{
// Copy the entire data and terminate them with zero
memcpy(m_szCsvFile, pbData, cbData);
m_szCsvFile[cbData] = 0;
m_szCsvPtr = m_szCsvFile;
m_nCsvFile = cbData;
// Parse the data
dwErrCode = ParseCsvData() ? ERROR_SUCCESS : ERROR_BAD_FORMAT;
}
return dwErrCode;
}
bool CASC_CSV::LoadNextLine()
{
bool bResult = false;
// Only endless CSV handler can do this
if(m_bHasAllLines == false)
{
// A few checks
assert(m_pLines != NULL);
assert(m_nLinesMax == 1);
// Reset the current line and load it
bResult = LoadNextLine(m_pLines[0]);
m_nLines = (bResult) ? 1 : 0;
}
return bResult;
}
bool CASC_CSV::InitializeHashTable()
{
// Create the hash table of HeaderText -> ColumnIndex
for(size_t i = 0; i < Header.GetColumnCount(); i++)
{
// Calculate the start slot and the current slot
size_t nStartIndex = HashToIndex(CalcHashValue(Header[i].szValue));
size_t nHashIndex = nStartIndex;
// Go as long as there is not a free space
while(HashTable[nHashIndex] != 0xFF)
{
nHashIndex = HashToIndex(nHashIndex + 1);
}
// Set the slot
HashTable[nHashIndex] = (BYTE)i;
}
return true;
}
bool CASC_CSV::LoadNextLine(CASC_CSV_LINE & Line)
{
// Overwatch ROOT's header begins with "#"
if(m_szCsvPtr == m_szCsvFile && m_szCsvPtr[0] == '#')
m_szCsvPtr++;
// Parse the entire line
while(m_szCsvPtr != NULL && m_szCsvPtr[0] != 0)
{
char * szCsvLine = m_szCsvPtr;
// Get the next line
m_szCsvPtr = PfnNextLine(m_pvUserData, m_szCsvPtr);
// Initialize the line
if (Line.SetLine(this, szCsvLine))
return true;
}
// End-of-file found
return false;
}
bool CASC_CSV::ParseCsvData()
{
// Sanity checks
assert(m_nLines == 0);
// If we have header, then parse it and set the pointer to the next line
if(m_bHasHeader)
{
// Load the current line to the header
if (!LoadNextLine(Header))
return false;
// Initialize the hash table
if(!InitializeHashTable())
return false;
}
// Are we supposed to load all lines?
if(m_bHasAllLines)
{
// Parse each line
for(size_t i = 0; i < m_nLinesMax; i++)
{
if(!LoadNextLine(m_pLines[i]))
break;
m_nLines++;
}
}
return true;
}
const CASC_CSV_COLUMN & CASC_CSV::operator[](const char * szColumnName) const
{
if (m_pLines == NULL || m_nLines == 0)
return NullColumn;
return m_pLines[0][GetColumnIndex(szColumnName)];
}
const CASC_CSV_LINE & CASC_CSV::operator[](size_t nIndex) const
{
if (m_pLines == NULL || nIndex >= m_nLines)
return NullLine;
return m_pLines[nIndex];
}
size_t CASC_CSV::GetHeaderColumns() const
{
return (m_bHasHeader) ? Header.GetColumnCount() : 0;
}
size_t CASC_CSV::GetColumnIndex(const char * szColumnName) const
{
if(m_bHasHeader)
{
// Calculate the start slot and the current slot
size_t nStartIndex = HashToIndex(CalcHashValue(szColumnName));
size_t nHashIndex = nStartIndex;
size_t nIndex;
// Go as long as there is not a free space
while((nIndex = HashTable[nHashIndex]) != 0xFF)
{
// Compare the string
if(!strcmp(Header[nIndex].szValue, szColumnName))
return nIndex;
// Move to the next column
nHashIndex = HashToIndex(nHashIndex + 1);
}
}
return CSV_INVALID_INDEX;
}
<|endoftext|> |
<commit_before>#line 2 "togo/tool_build/types.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief tool_build types.
@ingroup tool_build_types
*/
#pragma once
#include <togo/tool_build/config.hpp>
#include <togo/types.hpp>
#include <togo/memory_types.hpp>
#include <togo/collection_types.hpp>
#include <togo/string_types.hpp>
#include <togo/hash.hpp>
#include <togo/io_types.hpp>
#include <togo/resource_types.hpp>
namespace togo {
namespace tool_build {
// Forward declarations
struct ResourceMetadata;
struct ResourceCompiler;
struct PackageCompiler;
struct CompilerManager;
struct Interface;
/**
@addtogroup tool_build_types
@{
*/
/// Resource metadata.
struct ResourceMetadata {
u32 id;
// Serial
ResourceType type;
u32 format_version;
ResourceNameHash name_hash;
u64 last_compiled;
hash64 tags_collated;
FixedArray<char, 256> path;
};
/** @} */ // end of doc-group tool_build_types
/**
@addtogroup tool_build_resource_compiler
@{
*/
/// Resource compiler.
struct ResourceCompiler {
/// Compile a resource.
using compile_func_type = void (
CompilerManager& /*manager*/,
PackageCompiler& /*package*/,
ResourceMetadata const& /*metadata*/,
IReader& /*in_stream*/,
IWriter& /*out_stream*/
);
ResourceType type;
u32 format_version;
compile_func_type* func_compile;
};
/** @} */ // end of doc-group tool_build_resource_compiler
/**
@addtogroup tool_build_package_compiler
@{
*/
/// Package compiler.
struct PackageCompiler {
// TODO: Dependency tracking
ResourcePackageNameHash _name_hash;
HashMap<ResourceNameHash, u32> _lookup;
Array<ResourceMetadata> _metadata;
FixedArray<char, 48> _name;
FixedArray<char, 256> _path;
PackageCompiler() = delete;
PackageCompiler(PackageCompiler const&) = delete;
PackageCompiler(PackageCompiler&&) = delete;
PackageCompiler& operator=(PackageCompiler const&) = delete;
PackageCompiler& operator=(PackageCompiler&&) = delete;
~PackageCompiler() = default;
PackageCompiler(
StringRef const& path,
Allocator& allocator
);
};
/** @} */ // end of doc-group tool_build_package_compiler
/**
@addtogroup tool_build_compiler_manager
@{
*/
/// Package and resource compiler manager.
struct CompilerManager {
HashMap<ResourceType, ResourceCompiler> _compilers;
Array<PackageCompiler*> _packages;
CompilerManager() = delete;
CompilerManager(CompilerManager const&) = delete;
CompilerManager(CompilerManager&&) = delete;
CompilerManager& operator=(CompilerManager const&) = delete;
CompilerManager& operator=(CompilerManager&&) = delete;
~CompilerManager();
CompilerManager(Allocator& allocator);
};
/** @} */ // end of doc-group tool_build_compiler_manager
/**
@addtogroup tool_build_interface
@{
*/
// Tooling interface.
struct Interface {
CompilerManager _manager;
FixedArray<char, 256> _project_path;
Interface(Interface const&) = delete;
Interface(Interface&&) = delete;
Interface& operator=(Interface const&) = delete;
Interface& operator=(Interface&&) = delete;
~Interface();
Interface();
};
/** @} */ // end of doc-group tool_build_interface
} // namespace tool_build
} // namespace togo
<commit_msg>tool_build/package_compiler: added forgotten LookupNode definition.¹<commit_after>#line 2 "togo/tool_build/types.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief tool_build types.
@ingroup tool_build_types
*/
#pragma once
#include <togo/tool_build/config.hpp>
#include <togo/types.hpp>
#include <togo/memory_types.hpp>
#include <togo/collection_types.hpp>
#include <togo/string_types.hpp>
#include <togo/hash.hpp>
#include <togo/io_types.hpp>
#include <togo/resource_types.hpp>
namespace togo {
namespace tool_build {
// Forward declarations
struct ResourceMetadata;
struct ResourceCompiler;
struct PackageCompiler;
struct CompilerManager;
struct Interface;
/**
@addtogroup tool_build_types
@{
*/
/// Resource metadata.
struct ResourceMetadata {
u32 id;
// Serial
ResourceType type;
u32 format_version;
ResourceNameHash name_hash;
u64 last_compiled;
hash64 tags_collated;
FixedArray<char, 256> path;
};
/** @} */ // end of doc-group tool_build_types
/**
@addtogroup tool_build_resource_compiler
@{
*/
/// Resource compiler.
struct ResourceCompiler {
/// Compile a resource.
using compile_func_type = void (
CompilerManager& /*manager*/,
PackageCompiler& /*package*/,
ResourceMetadata const& /*metadata*/,
IReader& /*in_stream*/,
IWriter& /*out_stream*/
);
ResourceType type;
u32 format_version;
compile_func_type* func_compile;
};
/** @} */ // end of doc-group tool_build_resource_compiler
/**
@addtogroup tool_build_package_compiler
@{
*/
/// Package compiler.
struct PackageCompiler {
using LookupNode = HashMapNode<ResourceNameHash, u32>;
// TODO: Dependency tracking
ResourcePackageNameHash _name_hash;
HashMap<ResourceNameHash, u32> _lookup;
Array<ResourceMetadata> _metadata;
FixedArray<char, 48> _name;
FixedArray<char, 256> _path;
PackageCompiler() = delete;
PackageCompiler(PackageCompiler const&) = delete;
PackageCompiler(PackageCompiler&&) = delete;
PackageCompiler& operator=(PackageCompiler const&) = delete;
PackageCompiler& operator=(PackageCompiler&&) = delete;
~PackageCompiler() = default;
PackageCompiler(
StringRef const& path,
Allocator& allocator
);
};
/** @} */ // end of doc-group tool_build_package_compiler
/**
@addtogroup tool_build_compiler_manager
@{
*/
/// Package and resource compiler manager.
struct CompilerManager {
HashMap<ResourceType, ResourceCompiler> _compilers;
Array<PackageCompiler*> _packages;
CompilerManager() = delete;
CompilerManager(CompilerManager const&) = delete;
CompilerManager(CompilerManager&&) = delete;
CompilerManager& operator=(CompilerManager const&) = delete;
CompilerManager& operator=(CompilerManager&&) = delete;
~CompilerManager();
CompilerManager(Allocator& allocator);
};
/** @} */ // end of doc-group tool_build_compiler_manager
/**
@addtogroup tool_build_interface
@{
*/
// Tooling interface.
struct Interface {
CompilerManager _manager;
FixedArray<char, 256> _project_path;
Interface(Interface const&) = delete;
Interface(Interface&&) = delete;
Interface& operator=(Interface const&) = delete;
Interface& operator=(Interface&&) = delete;
~Interface();
Interface();
};
/** @} */ // end of doc-group tool_build_interface
} // namespace tool_build
} // namespace togo
<|endoftext|> |
<commit_before>// ***************************************************************************
// bamtools_sort.cpp (c) 2010 Derek Barnett, Erik Garrison
// Marth Lab, Department of Biology, Boston College
// All rights reserved.
// ---------------------------------------------------------------------------
// Last modified: 21 June 2010 (DB)
// ---------------------------------------------------------------------------
// Sorts an input BAM file (default by position) and stores in a new BAM file.
// ***************************************************************************
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "bamtools_sort.h"
#include "bamtools_options.h"
#include "BamReader.h"
#include "BamMultiReader.h"
#include "BamWriter.h"
using namespace std;
using namespace BamTools;
namespace BamTools {
// defaults
//
// ** These defaults should be tweaked & 'optimized' per testing ** //
// I say 'optimized' because each system will naturally perform
// differently. We will attempt to determine a sensible
// compromise that should perform well on average.
const unsigned int SORT_DEFAULT_MAX_BUFFER_COUNT = 10000; // max numberOfAlignments for buffer
const unsigned int SORT_DEFAULT_MAX_BUFFER_MEMORY = 1024; // Mb
// -----------------------------------
// comparison objects (for sorting)
struct SortLessThanPosition {
bool operator() (const BamAlignment& lhs, const BamAlignment& rhs) {
if ( lhs.RefID != rhs.RefID )
return lhs.RefID < rhs.RefID;
else
return lhs.Position < rhs.Position;
}
};
struct SortLessThanName {
bool operator() (const BamAlignment& lhs, const BamAlignment& rhs) {
return lhs.Name < rhs.Name;
}
};
} // namespace BamTools
// ---------------------------------------------
// SortToolPrivate declaration
class SortTool::SortToolPrivate {
// ctor & dtor
public:
SortToolPrivate(SortTool::SortSettings* settings);
~SortToolPrivate(void);
// 'public' interface
public:
bool Run(void);
// internal methods
private:
void ClearBuffer(vector<BamAlignment>& buffer);
bool GenerateSortedRuns(void);
bool HandleBufferContents(vector<BamAlignment>& buffer);
bool MergeSortedRuns(void);
bool WriteTempFile(const vector<BamAlignment>& buffer, const string& tempFilename);
void SortBuffer(vector<BamAlignment>& buffer);
// data members
private:
SortTool::SortSettings* m_settings;
string m_tempFilenameStub;
int m_numberOfRuns;
string m_headerText;
RefVector m_references;
vector<string> m_tempFilenames;
};
// ---------------------------------------------
// SortSettings implementation
struct SortTool::SortSettings {
// flags
bool HasInputBamFilename;
bool HasMaxBufferCount;
bool HasMaxBufferMemory;
bool HasOutputBamFilename;
bool IsSortingByName;
// filenames
string InputBamFilename;
string OutputBamFilename;
// parameters
unsigned int MaxBufferCount;
unsigned int MaxBufferMemory;
// constructor
SortSettings(void)
: HasInputBamFilename(false)
, HasMaxBufferCount(false)
, HasMaxBufferMemory(false)
, HasOutputBamFilename(false)
, IsSortingByName(false)
, InputBamFilename(Options::StandardIn())
, OutputBamFilename(Options::StandardOut())
, MaxBufferCount(SORT_DEFAULT_MAX_BUFFER_COUNT)
, MaxBufferMemory(SORT_DEFAULT_MAX_BUFFER_MEMORY)
{ }
};
// ---------------------------------------------
// SortTool implementation
SortTool::SortTool(void)
: AbstractTool()
, m_settings(new SortSettings)
, m_impl(0)
{
// set program details
Options::SetProgramInfo("bamtools sort", "sorts a BAM file", "[-in <filename>] [-out <filename>] [sortOptions]");
// set up options
OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
Options::AddValueOption("-in", "BAM filename", "the input BAM file", "", m_settings->HasInputBamFilename, m_settings->InputBamFilename, IO_Opts, Options::StandardIn());
Options::AddValueOption("-out", "BAM filename", "the output BAM file", "", m_settings->HasOutputBamFilename, m_settings->OutputBamFilename, IO_Opts, Options::StandardOut());
OptionGroup* SortOpts = Options::CreateOptionGroup("Sorting Methods");
Options::AddOption("-byname", "sort by alignment name", m_settings->IsSortingByName, SortOpts);
OptionGroup* MemOpts = Options::CreateOptionGroup("Memory Settings");
Options::AddValueOption("-n", "count", "max number of alignments per tempfile", "", m_settings->HasMaxBufferCount, m_settings->MaxBufferCount, MemOpts, SORT_DEFAULT_MAX_BUFFER_COUNT);
Options::AddValueOption("-mem", "Mb", "max memory to use", "", m_settings->HasMaxBufferMemory, m_settings->MaxBufferMemory, MemOpts, SORT_DEFAULT_MAX_BUFFER_MEMORY);
}
SortTool::~SortTool(void) {
delete m_settings;
m_settings = 0;
delete m_impl;
m_impl = 0;
}
int SortTool::Help(void) {
Options::DisplayHelp();
return 0;
}
int SortTool::Run(int argc, char* argv[]) {
// parse command line arguments
Options::Parse(argc, argv, 1);
// run internal SortTool implementation, return success/fail
m_impl = new SortToolPrivate(m_settings);
if ( m_impl->Run() ) return 0;
else return 1;
}
// ---------------------------------------------
// SortToolPrivate implementation
// constructor
SortTool::SortToolPrivate::SortToolPrivate(SortTool::SortSettings* settings)
: m_settings(settings)
, m_numberOfRuns(0)
{
// set filename stub depending on inputfile path
// that way multiple sort runs don't trip on each other's temp files
if ( m_settings) {
size_t extensionFound = m_settings->InputBamFilename.find(".bam");
if (extensionFound != string::npos )
m_tempFilenameStub = m_settings->InputBamFilename.substr(0,extensionFound);
m_tempFilenameStub.append(".sort.temp.");
}
}
// destructor
SortTool::SortToolPrivate::~SortToolPrivate(void) { }
// generates mutiple sorted temp BAM files from single unsorted BAM file
bool SortTool::SortToolPrivate::GenerateSortedRuns(void) {
// open input BAM file
BamReader inputReader;
if (!inputReader.Open(m_settings->InputBamFilename)) {
cerr << "Could not open " << m_settings->InputBamFilename << " for reading." << endl;
return false;
}
// get basic data that will be shared by all temp/output files
m_headerText = inputReader.GetHeaderText();
m_references = inputReader.GetReferenceData();
// set up alignments buffer
vector<BamAlignment> buffer;
buffer.reserve(m_settings->MaxBufferCount);
// while data available
BamAlignment al;
while ( inputReader.GetNextAlignmentCore(al)) {
// store alignments in buffer
buffer.push_back(al);
// if buffer is full, handle contents (sort & write to temp file)
if ( buffer.size() == m_settings->MaxBufferCount )
HandleBufferContents(buffer);
}
// handle any remaining buffer contents
if ( buffer.size() > 0 )
HandleBufferContents(buffer);
// close reader & return success
inputReader.Close();
return true;
}
bool SortTool::SortToolPrivate::HandleBufferContents(vector<BamAlignment>& buffer ) {
// do sorting
SortBuffer(buffer);
// write sorted contents to temp file, store success/fail
stringstream tempStr;
tempStr << m_tempFilenameStub << m_numberOfRuns;
bool success = WriteTempFile( buffer, tempStr.str() );
// save temp filename for merging later
m_tempFilenames.push_back(tempStr.str());
// clear buffer contents & update run counter
buffer.clear();
++m_numberOfRuns;
// return success/fail of writing to temp file
return success;
}
// merges sorted temp BAM files into single sorted output BAM file
bool SortTool::SortToolPrivate::MergeSortedRuns(void) {
// open up multi reader for all of our temp files
// this might get broken up if we do a multi-pass system later ??
BamMultiReader multiReader;
multiReader.Open(m_tempFilenames, false, true);
// open writer for our completely sorted output BAM file
BamWriter mergedWriter;
mergedWriter.Open(m_settings->OutputBamFilename, m_headerText, m_references);
// while data available in temp files
BamAlignment al;
while ( multiReader.GetNextAlignmentCore(al) )
mergedWriter.SaveAlignment(al);
// close readers
multiReader.Close();
mergedWriter.Close();
// delete all temp files
vector<string>::const_iterator tempIter = m_tempFilenames.begin();
vector<string>::const_iterator tempEnd = m_tempFilenames.end();
for ( ; tempIter != tempEnd; ++tempIter ) {
const string& tempFilename = (*tempIter);
remove(tempFilename.c_str());
}
return true;
}
bool SortTool::SortToolPrivate::Run(void) {
// this does a single pass, chunking up the input file into smaller sorted temp files,
// then write out using BamMultiReader to handle merging
if ( GenerateSortedRuns() )
return MergeSortedRuns();
else
return false;
}
void SortTool::SortToolPrivate::SortBuffer(vector<BamAlignment>& buffer) {
// ** add further custom sort options later ?? **
// sort buffer by desired method
if ( m_settings->IsSortingByName )
sort ( buffer.begin(), buffer.end(), SortLessThanName() );
else
sort ( buffer.begin(), buffer.end(), SortLessThanPosition() );
}
bool SortTool::SortToolPrivate::WriteTempFile(const vector<BamAlignment>& buffer, const string& tempFilename) {
// open temp file for writing
BamWriter tempWriter;
tempWriter.Open(tempFilename, m_headerText, m_references);
// write data
vector<BamAlignment>::const_iterator buffIter = buffer.begin();
vector<BamAlignment>::const_iterator buffEnd = buffer.end();
for ( ; buffIter != buffEnd; ++buffIter ) {
const BamAlignment& al = (*buffIter);
tempWriter.SaveAlignment(al);
}
// close temp file & return success
tempWriter.Close();
return true;
}
<commit_msg>Fixed: Improper sorting -byname<commit_after>// ***************************************************************************
// bamtools_sort.cpp (c) 2010 Derek Barnett, Erik Garrison
// Marth Lab, Department of Biology, Boston College
// All rights reserved.
// ---------------------------------------------------------------------------
// Last modified: 16 December 2010 (DB)
// ---------------------------------------------------------------------------
// Sorts an input BAM file (default by position) and stores in a new BAM file.
// ***************************************************************************
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "bamtools_sort.h"
#include "bamtools_options.h"
#include "BamReader.h"
#include "BamMultiReader.h"
#include "BamWriter.h"
using namespace std;
using namespace BamTools;
namespace BamTools {
// defaults
//
// ** These defaults should be tweaked & 'optimized' per testing ** //
// I say 'optimized' because each system will naturally perform
// differently. We will attempt to determine a sensible
// compromise that should perform well on average.
const unsigned int SORT_DEFAULT_MAX_BUFFER_COUNT = 10000; // max numberOfAlignments for buffer
const unsigned int SORT_DEFAULT_MAX_BUFFER_MEMORY = 1024; // Mb
// -----------------------------------
// comparison objects (for sorting)
struct SortLessThanPosition {
bool operator() (const BamAlignment& lhs, const BamAlignment& rhs) {
if ( lhs.RefID != rhs.RefID )
return lhs.RefID < rhs.RefID;
else
return lhs.Position < rhs.Position;
}
};
struct SortLessThanName {
bool operator() (const BamAlignment& lhs, const BamAlignment& rhs) {
return lhs.Name < rhs.Name;
}
};
} // namespace BamTools
// ---------------------------------------------
// SortToolPrivate declaration
class SortTool::SortToolPrivate {
// ctor & dtor
public:
SortToolPrivate(SortTool::SortSettings* settings);
~SortToolPrivate(void);
// 'public' interface
public:
bool Run(void);
// internal methods
private:
void ClearBuffer(vector<BamAlignment>& buffer);
bool GenerateSortedRuns(void);
bool HandleBufferContents(vector<BamAlignment>& buffer);
bool MergeSortedRuns(void);
bool WriteTempFile(const vector<BamAlignment>& buffer, const string& tempFilename);
void SortBuffer(vector<BamAlignment>& buffer);
// data members
private:
SortTool::SortSettings* m_settings;
string m_tempFilenameStub;
int m_numberOfRuns;
string m_headerText;
RefVector m_references;
vector<string> m_tempFilenames;
};
// ---------------------------------------------
// SortSettings implementation
struct SortTool::SortSettings {
// flags
bool HasInputBamFilename;
bool HasMaxBufferCount;
bool HasMaxBufferMemory;
bool HasOutputBamFilename;
bool IsSortingByName;
// filenames
string InputBamFilename;
string OutputBamFilename;
// parameters
unsigned int MaxBufferCount;
unsigned int MaxBufferMemory;
// constructor
SortSettings(void)
: HasInputBamFilename(false)
, HasMaxBufferCount(false)
, HasMaxBufferMemory(false)
, HasOutputBamFilename(false)
, IsSortingByName(false)
, InputBamFilename(Options::StandardIn())
, OutputBamFilename(Options::StandardOut())
, MaxBufferCount(SORT_DEFAULT_MAX_BUFFER_COUNT)
, MaxBufferMemory(SORT_DEFAULT_MAX_BUFFER_MEMORY)
{ }
};
// ---------------------------------------------
// SortTool implementation
SortTool::SortTool(void)
: AbstractTool()
, m_settings(new SortSettings)
, m_impl(0)
{
// set program details
Options::SetProgramInfo("bamtools sort", "sorts a BAM file", "[-in <filename>] [-out <filename>] [sortOptions]");
// set up options
OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
Options::AddValueOption("-in", "BAM filename", "the input BAM file", "", m_settings->HasInputBamFilename, m_settings->InputBamFilename, IO_Opts, Options::StandardIn());
Options::AddValueOption("-out", "BAM filename", "the output BAM file", "", m_settings->HasOutputBamFilename, m_settings->OutputBamFilename, IO_Opts, Options::StandardOut());
OptionGroup* SortOpts = Options::CreateOptionGroup("Sorting Methods");
Options::AddOption("-byname", "sort by alignment name", m_settings->IsSortingByName, SortOpts);
OptionGroup* MemOpts = Options::CreateOptionGroup("Memory Settings");
Options::AddValueOption("-n", "count", "max number of alignments per tempfile", "", m_settings->HasMaxBufferCount, m_settings->MaxBufferCount, MemOpts, SORT_DEFAULT_MAX_BUFFER_COUNT);
Options::AddValueOption("-mem", "Mb", "max memory to use", "", m_settings->HasMaxBufferMemory, m_settings->MaxBufferMemory, MemOpts, SORT_DEFAULT_MAX_BUFFER_MEMORY);
}
SortTool::~SortTool(void) {
delete m_settings;
m_settings = 0;
delete m_impl;
m_impl = 0;
}
int SortTool::Help(void) {
Options::DisplayHelp();
return 0;
}
int SortTool::Run(int argc, char* argv[]) {
// parse command line arguments
Options::Parse(argc, argv, 1);
// run internal SortTool implementation, return success/fail
m_impl = new SortToolPrivate(m_settings);
if ( m_impl->Run() ) return 0;
else return 1;
}
// ---------------------------------------------
// SortToolPrivate implementation
// constructor
SortTool::SortToolPrivate::SortToolPrivate(SortTool::SortSettings* settings)
: m_settings(settings)
, m_numberOfRuns(0)
{
// set filename stub depending on inputfile path
// that way multiple sort runs don't trip on each other's temp files
if ( m_settings) {
size_t extensionFound = m_settings->InputBamFilename.find(".bam");
if (extensionFound != string::npos )
m_tempFilenameStub = m_settings->InputBamFilename.substr(0,extensionFound);
m_tempFilenameStub.append(".sort.temp.");
}
}
// destructor
SortTool::SortToolPrivate::~SortToolPrivate(void) { }
// generates mutiple sorted temp BAM files from single unsorted BAM file
bool SortTool::SortToolPrivate::GenerateSortedRuns(void) {
// open input BAM file
BamReader inputReader;
if (!inputReader.Open(m_settings->InputBamFilename)) {
cerr << "Could not open " << m_settings->InputBamFilename << " for reading." << endl;
return false;
}
// get basic data that will be shared by all temp/output files
m_headerText = inputReader.GetHeaderText();
m_references = inputReader.GetReferenceData();
// set up alignments buffer
BamAlignment al;
vector<BamAlignment> buffer;
buffer.reserve(m_settings->MaxBufferCount);
// if sorting by name, we need to generate full char data
// so can't use GetNextAlignmentCore()
if ( m_settings->IsSortingByName ) {
// iterate through file
while ( inputReader.GetNextAlignment(al)) {
// store alignments in buffer
buffer.push_back(al);
// if buffer is full, handle contents (sort & write to temp file)
if ( buffer.size() == m_settings->MaxBufferCount )
HandleBufferContents(buffer);
}
}
// sorting by position, can take advantage of GNACore() speedup
else {
// iterate through file
while ( inputReader.GetNextAlignmentCore(al)) {
// store alignments in buffer
buffer.push_back(al);
// if buffer is full, handle contents (sort & write to temp file)
if ( buffer.size() == m_settings->MaxBufferCount )
HandleBufferContents(buffer);
}
}
// handle any remaining buffer contents
if ( buffer.size() > 0 )
HandleBufferContents(buffer);
// close reader & return success
inputReader.Close();
return true;
}
bool SortTool::SortToolPrivate::HandleBufferContents(vector<BamAlignment>& buffer ) {
// do sorting
SortBuffer(buffer);
// write sorted contents to temp file, store success/fail
stringstream tempStr;
tempStr << m_tempFilenameStub << m_numberOfRuns;
bool success = WriteTempFile( buffer, tempStr.str() );
// save temp filename for merging later
m_tempFilenames.push_back(tempStr.str());
// clear buffer contents & update run counter
buffer.clear();
++m_numberOfRuns;
// return success/fail of writing to temp file
return success;
}
// merges sorted temp BAM files into single sorted output BAM file
bool SortTool::SortToolPrivate::MergeSortedRuns(void) {
// open up multi reader for all of our temp files
// this might get broken up if we do a multi-pass system later ??
BamMultiReader multiReader;
multiReader.Open(m_tempFilenames, false, true);
// open writer for our completely sorted output BAM file
BamWriter mergedWriter;
mergedWriter.Open(m_settings->OutputBamFilename, m_headerText, m_references);
// while data available in temp files
BamAlignment al;
while ( multiReader.GetNextAlignmentCore(al) )
mergedWriter.SaveAlignment(al);
// close readers
multiReader.Close();
mergedWriter.Close();
// delete all temp files
vector<string>::const_iterator tempIter = m_tempFilenames.begin();
vector<string>::const_iterator tempEnd = m_tempFilenames.end();
for ( ; tempIter != tempEnd; ++tempIter ) {
const string& tempFilename = (*tempIter);
remove(tempFilename.c_str());
}
return true;
}
bool SortTool::SortToolPrivate::Run(void) {
// this does a single pass, chunking up the input file into smaller sorted temp files,
// then write out using BamMultiReader to handle merging
if ( GenerateSortedRuns() )
return MergeSortedRuns();
else
return false;
}
void SortTool::SortToolPrivate::SortBuffer(vector<BamAlignment>& buffer) {
// ** add further custom sort options later ?? **
// sort buffer by desired method
if ( m_settings->IsSortingByName )
sort ( buffer.begin(), buffer.end(), SortLessThanName() );
else
sort ( buffer.begin(), buffer.end(), SortLessThanPosition() );
}
bool SortTool::SortToolPrivate::WriteTempFile(const vector<BamAlignment>& buffer, const string& tempFilename) {
// open temp file for writing
BamWriter tempWriter;
tempWriter.Open(tempFilename, m_headerText, m_references);
// write data
vector<BamAlignment>::const_iterator buffIter = buffer.begin();
vector<BamAlignment>::const_iterator buffEnd = buffer.end();
for ( ; buffIter != buffEnd; ++buffIter ) {
const BamAlignment& al = (*buffIter);
tempWriter.SaveAlignment(al);
}
// close temp file & return success
tempWriter.Close();
return true;
}
<|endoftext|> |
<commit_before>#include "compression.h"
CompressionType Compression::GetCompressionType(char first_byte) {
switch (first_byte) {
case 0:
return CompressionType::NONE;
case 1:
return CompressionType::BZIP2;
case 2:
return CompressionType::GZIP;
case 3:
return CompressionType::LZMA;
default:
throw std::runtime_error(std::string("invalid compression type ") + boost::lexical_cast<std::string>(first_byte));
}
}
CompressionInfo::CompressionInfo(std::vector<char> &data) {
compression_type = Compression::GetCompressionType(data[0]);
compressed_size = ((data[1] & 0xFF) << 24) | ((data[2] & 0xFF) << 16) | ((data[3] & 0xFF) << 8) | (data[4] & 0xFF);
decompressed_size = ((data[5] & 0xFF) << 24) | ((data[6] & 0xFF) << 16) | ((data[7] & 0xFF) << 8) | (data[8] & 0xFF);
}
int Compression::Decompress(std::vector<char> &original, std::vector<char> &destination) {
CompressionInfo compression_info(original);
auto compression_type = compression_info.GetCompressionType();
destination.resize(compression_info.GetDecompressedSize());
if (compression_type == CompressionType::GZIP) { // Decompress using gzip (or well, skip the gzip header and use plain lzma inflating)
auto strm = new z_stream();
strm->avail_in = original.size();
strm->next_in = reinterpret_cast<Byte*>(original.data() + 19);
strm->avail_out = destination.capacity();
strm->next_out = reinterpret_cast<Byte*>(destination.data());
inflateInit2(strm, -15);
inflate(strm, Z_FINISH);
inflateEnd(strm);
int size = strm->total_out;
delete strm;
return size;
} else if (compression_type == CompressionType::BZIP2) {
// First of all, initialize the stream with just the missing header bytes
bz_stream *strm = new bz_stream();
strm->avail_in = 4;
strm->next_in = const_cast<char*>(BZIP_HEADER);
strm->avail_out = destination.capacity();
strm->next_out = destination.data();
// Let BZ2 decode that header for us..
int init_error = BZ2_bzDecompressInit(strm, 0, 0);
int bzipresult = BZ2_bzDecompress(strm);
// .. And now feed the real data.
strm->avail_in = original.size() - 9;
strm->next_in = original.data() + 9;
bzipresult = BZ2_bzDecompress(strm);
// Free the stream and return the number of read bytes
int read = strm->total_out_lo32;
delete strm;
return read;
} else if (compression_type == CompressionType::LZMA) {
std::vector<char> forged_input(original.size() - 9 + 8); // Properties, dict size and full size
forged_input.resize(original.size() - 9 + 8);
memcpy(forged_input.data(), original.data() + 9, 5); // Copy properties and dict size
auto decompressed_size = compression_info.GetDecompressedSize();
forged_input[5] = (char) (decompressed_size);
forged_input[6] = (char) (decompressed_size >> 8);
forged_input[7] = (char) (decompressed_size >> 16);
forged_input[8] = (char) (decompressed_size >> 24);
memcpy(forged_input.data() + 13, original.data() + 9 + 5, original.size() - 9 - 5);
auto strm = new lzma_stream();
lzma_alone_decoder(strm, UINT64_MAX);
strm->avail_in = forged_input.size();
strm->next_in = (uint8_t *) forged_input.data();
strm->avail_out = destination.capacity();
strm->next_out = (uint8_t *) destination.data();
lzma_code(strm, LZMA_RUN);
lzma_code(strm, LZMA_FINISH);
lzma_end(strm);
return (int) strm->total_out;
} else if (compression_type == CompressionType::NONE) { // If no compression just copy the bytes from O to D
memcpy(destination.data(), original.data() + 9, original.size() - 9);
return (int) (original.size() - 9);
}
return 0;
}
CompressionType CompressionInfo::GetCompressionType() {
return compression_type;
}
int CompressionInfo::GetCompressedSize() {
return compressed_size;
}
int CompressionInfo::GetDecompressedSize() {
return decompressed_size;
}
<commit_msg>Optimize compression deterministics<commit_after>#include "compression.h"
CompressionType Compression::GetCompressionType(char first_byte) {
if (((unsigned char)first_byte) > 3) {
throw std::runtime_error(std::string("invalid compression type ") + boost::lexical_cast<std::string>(first_byte));
}
return (CompressionType) first_byte;
}
CompressionInfo::CompressionInfo(std::vector<char> &data) {
compression_type = Compression::GetCompressionType(data[0]);
compressed_size = ((data[1] & 0xFF) << 24) | ((data[2] & 0xFF) << 16) | ((data[3] & 0xFF) << 8) | (data[4] & 0xFF);
decompressed_size = ((data[5] & 0xFF) << 24) | ((data[6] & 0xFF) << 16) | ((data[7] & 0xFF) << 8) | (data[8] & 0xFF);
}
int Compression::Decompress(std::vector<char> &original, std::vector<char> &destination) {
CompressionInfo compression_info(original);
auto compression_type = compression_info.GetCompressionType();
destination.resize(compression_info.GetDecompressedSize());
if (compression_type == CompressionType::GZIP) { // Decompress using gzip (or well, skip the gzip header and use plain lzma inflating)
auto strm = new z_stream();
strm->avail_in = original.size();
strm->next_in = reinterpret_cast<Byte*>(original.data() + 19);
strm->avail_out = destination.capacity();
strm->next_out = reinterpret_cast<Byte*>(destination.data());
inflateInit2(strm, -15);
inflate(strm, Z_FINISH);
inflateEnd(strm);
int size = strm->total_out;
delete strm;
return size;
} else if (compression_type == CompressionType::BZIP2) {
// First of all, initialize the stream with just the missing header bytes
bz_stream *strm = new bz_stream();
strm->avail_in = 4;
strm->next_in = const_cast<char*>(BZIP_HEADER);
strm->avail_out = destination.capacity();
strm->next_out = destination.data();
// Let BZ2 decode that header for us..
int init_error = BZ2_bzDecompressInit(strm, 0, 0);
int bzipresult = BZ2_bzDecompress(strm);
// .. And now feed the real data.
strm->avail_in = original.size() - 9;
strm->next_in = original.data() + 9;
bzipresult = BZ2_bzDecompress(strm);
// Free the stream and return the number of read bytes
int read = strm->total_out_lo32;
delete strm;
return read;
} else if (compression_type == CompressionType::LZMA) {
std::vector<char> forged_input(original.size() - 9 + 8); // Properties, dict size and full size
forged_input.resize(original.size() - 9 + 8);
memcpy(forged_input.data(), original.data() + 9, 5); // Copy properties and dict size
auto decompressed_size = compression_info.GetDecompressedSize();
forged_input[5] = (char) (decompressed_size);
forged_input[6] = (char) (decompressed_size >> 8);
forged_input[7] = (char) (decompressed_size >> 16);
forged_input[8] = (char) (decompressed_size >> 24);
memcpy(forged_input.data() + 13, original.data() + 9 + 5, original.size() - 9 - 5);
auto strm = new lzma_stream();
lzma_alone_decoder(strm, UINT64_MAX);
strm->avail_in = forged_input.size();
strm->next_in = (uint8_t *) forged_input.data();
strm->avail_out = destination.capacity();
strm->next_out = (uint8_t *) destination.data();
lzma_code(strm, LZMA_RUN);
lzma_code(strm, LZMA_FINISH);
lzma_end(strm);
return (int) strm->total_out;
} else if (compression_type == CompressionType::NONE) { // If no compression just copy the bytes from O to D
memcpy(destination.data(), original.data() + 9, original.size() - 9);
return (int) (original.size() - 9);
}
return 0;
}
CompressionType CompressionInfo::GetCompressionType() {
return compression_type;
}
int CompressionInfo::GetCompressedSize() {
return compressed_size;
}
int CompressionInfo::GetDecompressedSize() {
return decompressed_size;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 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 <compressor.h>
#include <hash.h>
#include <pubkey.h>
#include <script/standard.h>
bool CScriptCompressor::IsToKeyID(CKeyID &hash) const
{
if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160
&& script[2] == 20 && script[23] == OP_EQUALVERIFY
&& script[24] == OP_CHECKSIG) {
memcpy(&hash, &script[3], 20);
return true;
}
return false;
}
bool CScriptCompressor::IsToScriptID(CScriptID &hash) const
{
if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20
&& script[22] == OP_EQUAL) {
memcpy(&hash, &script[2], 20);
return true;
}
return false;
}
bool CScriptCompressor::IsToPubKey(CPubKey &pubkey) const
{
if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG
&& (script[1] == 0x02 || script[1] == 0x03)) {
pubkey.Set(&script[1], &script[34]);
return true;
}
if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG
&& script[1] == 0x04) {
pubkey.Set(&script[1], &script[66]);
return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible
}
return false;
}
bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const
{
CKeyID keyID;
if (IsToKeyID(keyID)) {
out.resize(21);
out[0] = 0x00;
memcpy(&out[1], &keyID, 20);
return true;
}
CScriptID scriptID;
if (IsToScriptID(scriptID)) {
out.resize(21);
out[0] = 0x01;
memcpy(&out[1], &scriptID, 20);
return true;
}
CPubKey pubkey;
if (IsToPubKey(pubkey)) {
out.resize(33);
memcpy(&out[1], &pubkey[1], 32);
if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
out[0] = pubkey[0];
return true;
} else if (pubkey[0] == 0x04) {
out[0] = 0x04 | (pubkey[64] & 0x01);
return true;
}
}
return false;
}
unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
{
if (nSize == 0 || nSize == 1)
return 20;
if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
return 32;
return 0;
}
bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char> &in)
{
switch(nSize) {
case 0x00:
script.resize(25);
script[0] = OP_DUP;
script[1] = OP_HASH160;
script[2] = 20;
memcpy(&script[3], &in[0], 20);
script[23] = OP_EQUALVERIFY;
script[24] = OP_CHECKSIG;
return true;
case 0x01:
script.resize(23);
script[0] = OP_HASH160;
script[1] = 20;
memcpy(&script[2], &in[0], 20);
script[22] = OP_EQUAL;
return true;
case 0x02:
case 0x03:
script.resize(35);
script[0] = 33;
script[1] = nSize;
memcpy(&script[2], &in[0], 32);
script[34] = OP_CHECKSIG;
return true;
case 0x04:
case 0x05:
unsigned char vch[33] = {};
vch[0] = nSize - 2;
memcpy(&vch[1], &in[0], 32);
CPubKey pubkey(&vch[0], &vch[33]);
if (!pubkey.Decompress())
return false;
assert(pubkey.size() == 65);
script.resize(67);
script[0] = 65;
memcpy(&script[1], pubkey.begin(), 65);
script[66] = OP_CHECKSIG;
return true;
}
return false;
}
// Amount compression:
// * If the amount is 0, output 0
// * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
// * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
// * call the result n
// * output 1 + 10*(9*n + d - 1) + e
// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
// (this is decodable, as d is in [1-9] and e is in [0-9])
uint64_t CTxOutCompressor::CompressAmount(uint64_t n)
{
if (n == 0)
return 0;
int e = 0;
while (((n % 10) == 0) && e < 9) {
n /= 10;
e++;
}
if (e < 9) {
int d = (n % 10);
assert(d >= 1 && d <= 9);
n /= 10;
return 1 + (n*9 + d - 1)*10 + e;
} else {
return 1 + (n - 1)*10 + 9;
}
}
uint64_t CTxOutCompressor::DecompressAmount(uint64_t x)
{
// x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
if (x == 0)
return 0;
x--;
// x = 10*(9*n + d - 1) + e
int e = x % 10;
x /= 10;
uint64_t n = 0;
if (e < 9) {
// x = 9*n + d - 1
int d = (x % 9) + 1;
x /= 9;
// x = n
n = x*10 + d;
} else {
n = x+1;
}
while (e) {
n *= 10;
e--;
}
return n;
}
<commit_msg>Fix subscript[0] in compressor.cpp<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 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 <compressor.h>
#include <hash.h>
#include <pubkey.h>
#include <script/standard.h>
bool CScriptCompressor::IsToKeyID(CKeyID &hash) const
{
if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160
&& script[2] == 20 && script[23] == OP_EQUALVERIFY
&& script[24] == OP_CHECKSIG) {
memcpy(&hash, &script[3], 20);
return true;
}
return false;
}
bool CScriptCompressor::IsToScriptID(CScriptID &hash) const
{
if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20
&& script[22] == OP_EQUAL) {
memcpy(&hash, &script[2], 20);
return true;
}
return false;
}
bool CScriptCompressor::IsToPubKey(CPubKey &pubkey) const
{
if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG
&& (script[1] == 0x02 || script[1] == 0x03)) {
pubkey.Set(&script[1], &script[34]);
return true;
}
if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG
&& script[1] == 0x04) {
pubkey.Set(&script[1], &script[66]);
return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible
}
return false;
}
bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const
{
CKeyID keyID;
if (IsToKeyID(keyID)) {
out.resize(21);
out[0] = 0x00;
memcpy(&out[1], &keyID, 20);
return true;
}
CScriptID scriptID;
if (IsToScriptID(scriptID)) {
out.resize(21);
out[0] = 0x01;
memcpy(&out[1], &scriptID, 20);
return true;
}
CPubKey pubkey;
if (IsToPubKey(pubkey)) {
out.resize(33);
memcpy(&out[1], &pubkey[1], 32);
if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
out[0] = pubkey[0];
return true;
} else if (pubkey[0] == 0x04) {
out[0] = 0x04 | (pubkey[64] & 0x01);
return true;
}
}
return false;
}
unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
{
if (nSize == 0 || nSize == 1)
return 20;
if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
return 32;
return 0;
}
bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char> &in)
{
switch(nSize) {
case 0x00:
script.resize(25);
script[0] = OP_DUP;
script[1] = OP_HASH160;
script[2] = 20;
memcpy(&script[3], in.data(), 20);
script[23] = OP_EQUALVERIFY;
script[24] = OP_CHECKSIG;
return true;
case 0x01:
script.resize(23);
script[0] = OP_HASH160;
script[1] = 20;
memcpy(&script[2], in.data(), 20);
script[22] = OP_EQUAL;
return true;
case 0x02:
case 0x03:
script.resize(35);
script[0] = 33;
script[1] = nSize;
memcpy(&script[2], in.data(), 32);
script[34] = OP_CHECKSIG;
return true;
case 0x04:
case 0x05:
unsigned char vch[33] = {};
vch[0] = nSize - 2;
memcpy(&vch[1], in.data(), 32);
CPubKey pubkey(&vch[0], &vch[33]);
if (!pubkey.Decompress())
return false;
assert(pubkey.size() == 65);
script.resize(67);
script[0] = 65;
memcpy(&script[1], pubkey.begin(), 65);
script[66] = OP_CHECKSIG;
return true;
}
return false;
}
// Amount compression:
// * If the amount is 0, output 0
// * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
// * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
// * call the result n
// * output 1 + 10*(9*n + d - 1) + e
// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
// (this is decodable, as d is in [1-9] and e is in [0-9])
uint64_t CTxOutCompressor::CompressAmount(uint64_t n)
{
if (n == 0)
return 0;
int e = 0;
while (((n % 10) == 0) && e < 9) {
n /= 10;
e++;
}
if (e < 9) {
int d = (n % 10);
assert(d >= 1 && d <= 9);
n /= 10;
return 1 + (n*9 + d - 1)*10 + e;
} else {
return 1 + (n - 1)*10 + 9;
}
}
uint64_t CTxOutCompressor::DecompressAmount(uint64_t x)
{
// x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
if (x == 0)
return 0;
x--;
// x = 10*(9*n + d - 1) + e
int e = x % 10;
x /= 10;
uint64_t n = 0;
if (e < 9) {
// x = 9*n + d - 1
int d = (x % 9) + 1;
x /= 9;
// x = n
n = x*10 + d;
} else {
n = x+1;
}
while (e) {
n *= 10;
e--;
}
return n;
}
<|endoftext|> |
<commit_before>// Filename: showBase.cxx
// Created by: shochet (02Feb00)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////
#include "showBase.h"
#include "throw_event.h"
#include "graphicsWindow.h"
#include "chancfg.h"
#include "renderBuffer.h"
#include "get_config_path.h"
#include "camera.h"
#include "graphicsPipeSelection.h"
ConfigureDef(config_showbase);
ConfigureFn(config_showbase) {
}
DSearchPath &
get_particle_path() {
static DSearchPath *particle_path = NULL;
return get_config_path("particle-path", particle_path);
}
// Throw the "NewFrame" event in the C++ world. Some of the lerp code
// depends on receiving this.
void
throw_new_frame() {
throw_event("NewFrame");
}
void
take_snapshot(GraphicsWindow *win, const string &name) {
GraphicsStateGuardian* gsg = win->get_gsg();
const RenderBuffer& rb = gsg->get_render_buffer(RenderBuffer::T_front);
CPT(DisplayRegion) dr = win->get_display_region(0);
nassertv(dr != (DisplayRegion *)NULL);
int width = dr->get_pixel_width();
int height = dr->get_pixel_height();
PixelBuffer p(width, height, 3, 1, PixelBuffer::T_unsigned_byte,
PixelBuffer::F_rgb);
p.copy(gsg, dr, rb);
p.write(name);
}
// Returns the configure object for accessing config variables from a
// scripting language.
ConfigShowbase &
get_config_showbase() {
return config_showbase;
}
// klunky interface since we cant pass array from python->C++ to use verify_window_sizes directly
static int num_fullscreen_testsizes = 0;
#define MAX_FULLSCREEN_TESTS 10
static int fullscreen_testsizes[MAX_FULLSCREEN_TESTS * 2];
void
add_fullscreen_testsize(int xsize, int ysize) {
if ((xsize == 0) && (ysize == 0)) {
num_fullscreen_testsizes = 0;
return;
}
// silently fail if maxtests exceeded
if (num_fullscreen_testsizes < MAX_FULLSCREEN_TESTS) {
fullscreen_testsizes[num_fullscreen_testsizes * 2] = xsize;
fullscreen_testsizes[num_fullscreen_testsizes * 2 + 1] = ysize;
num_fullscreen_testsizes++;
}
}
void
runtest_fullscreen_sizes(GraphicsWindow *win) {
win->verify_window_sizes(num_fullscreen_testsizes, fullscreen_testsizes);
}
bool
query_fullscreen_testresult(int xsize, int ysize) {
// stupid linear search that works ok as long as total tests are small
int i;
for (i=0; i < num_fullscreen_testsizes; i++) {
if((fullscreen_testsizes[i * 2] == xsize) &&
(fullscreen_testsizes[i * 2 + 1] == ysize))
return true;
}
return false;
}
<commit_msg>fix typo<commit_after>// Filename: showBase.cxx
// Created by: shochet (02Feb00)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license. You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://www.panda3d.org/license.txt .
//
// To contact the maintainers of this program write to
// panda3d@yahoogroups.com .
//
////////////////////////////////////////////////////////////////////
#include "showBase.h"
#include "throw_event.h"
#include "graphicsWindow.h"
#include "chancfg.h"
#include "renderBuffer.h"
#include "get_config_path.h"
#include "camera.h"
#include "graphicsPipeSelection.h"
ConfigureDef(config_showbase);
ConfigureFn(config_showbase) {
}
DSearchPath &
get_particle_path() {
static DSearchPath *particle_path = NULL;
return get_config_path("particle-path", particle_path);
}
// Throw the "NewFrame" event in the C++ world. Some of the lerp code
// depends on receiving this.
void
throw_new_frame() {
throw_event("NewFrame");
}
void
take_snapshot(GraphicsWindow *win, const string &name) {
GraphicsStateGuardian* gsg = win->get_gsg();
RenderBuffer rb = gsg->get_render_buffer(RenderBuffer::T_front);
CPT(DisplayRegion) dr = win->get_display_region(0);
nassertv(dr != (DisplayRegion *)NULL);
int width = dr->get_pixel_width();
int height = dr->get_pixel_height();
PixelBuffer p(width, height, 3, 1, PixelBuffer::T_unsigned_byte,
PixelBuffer::F_rgb);
p.copy(gsg, dr, rb);
p.write(name);
}
// Returns the configure object for accessing config variables from a
// scripting language.
ConfigShowbase &
get_config_showbase() {
return config_showbase;
}
// klunky interface since we cant pass array from python->C++ to use verify_window_sizes directly
static int num_fullscreen_testsizes = 0;
#define MAX_FULLSCREEN_TESTS 10
static int fullscreen_testsizes[MAX_FULLSCREEN_TESTS * 2];
void
add_fullscreen_testsize(int xsize, int ysize) {
if ((xsize == 0) && (ysize == 0)) {
num_fullscreen_testsizes = 0;
return;
}
// silently fail if maxtests exceeded
if (num_fullscreen_testsizes < MAX_FULLSCREEN_TESTS) {
fullscreen_testsizes[num_fullscreen_testsizes * 2] = xsize;
fullscreen_testsizes[num_fullscreen_testsizes * 2 + 1] = ysize;
num_fullscreen_testsizes++;
}
}
void
runtest_fullscreen_sizes(GraphicsWindow *win) {
win->verify_window_sizes(num_fullscreen_testsizes, fullscreen_testsizes);
}
bool
query_fullscreen_testresult(int xsize, int ysize) {
// stupid linear search that works ok as long as total tests are small
int i;
for (i=0; i < num_fullscreen_testsizes; i++) {
if((fullscreen_testsizes[i * 2] == xsize) &&
(fullscreen_testsizes[i * 2 + 1] == ysize))
return true;
}
return false;
}
<|endoftext|> |
<commit_before>#include "CudaMatrixKernel.h"
#include "Cublas.h"
#include <iostream>
#include <stdexcept>
#include <tools/Matrix.h>
#include <tools/MismatchedMatricesException.h>
#include <tools/MatrixHelper.h>
using namespace std;
using namespace CudaUtils;
const float ALPHA = 1.0f;
const float BETA = 0.0f;
size_t CudaMatrixKernel::requiredInputs() const
{
return 2;
}
void CudaMatrixKernel::startup(const std::vector<std::string>& arguments)
{
Matrix<float> matrixA = MatrixHelper::readMatrixFrom(arguments[0]);
Matrix<float> matrixB = MatrixHelper::readMatrixFrom(arguments[1]);
matrixARows = matrixA.rows();
matrixACols = matrixA.columns();
matrixBRows = matrixB.rows();
matrixBCols = matrixB.columns();
if (matrixACols != matrixBRows)
throw MismatchedMatricesException(matrixACols, matrixBRows);
size_t matrixASize = matrixARows * matrixACols;
size_t matrixBSize = matrixACols * matrixBCols;
size_t outputSize = matrixARows * matrixBCols;
matrixMemA.reallocate(matrixASize);
matrixMemB.reallocate(matrixBSize);
outputMatrix.reallocate(outputSize);
cublas.reset(new Cublas());
cublas->setMatrix(matrixARows, matrixACols, sizeof(float), matrixA.buffer(), matrixARows, matrixMemA, matrixARows);
cublas->setMatrix(matrixACols, matrixBCols, sizeof(float), matrixB.buffer(), matrixACols, matrixMemB, matrixACols);
}
void CudaMatrixKernel::run()
{
cublas->Sgemm(
CUBLAS_OP_N, CUBLAS_OP_N,
matrixARows, matrixBCols, matrixACols,
&ALPHA,
matrixMemA, matrixARows,
matrixMemB, matrixACols,
&BETA,
outputMatrix, matrixARows
);
}
void CudaMatrixKernel::shutdown(const std::string& outputFilename)
{
size_t rows = matrixARows;
size_t cols = matrixBCols;
vector<float> outputBuffer(rows * cols);
cublas->getMatrix(rows, cols, sizeof(float), outputMatrix, rows, outputBuffer.data(), rows);
Matrix<float> targetMatrix(rows, cols, move(outputBuffer));
MatrixHelper::writeMatrixTo(outputFilename, targetMatrix);
}
std::shared_ptr<BenchmarkKernel> createKernel()
{
BenchmarkKernel* kernel = new CudaMatrixKernel();
return std::shared_ptr<BenchmarkKernel>(kernel);
}
<commit_msg>quick and dirty hack to compute on row-major matrices<commit_after>#include "CudaMatrixKernel.h"
#include "Cublas.h"
#include <iostream>
#include <stdexcept>
#include <tools/Matrix.h>
#include <tools/MismatchedMatricesException.h>
#include <tools/MatrixHelper.h>
using namespace std;
using namespace CudaUtils;
const float ALPHA = 1.0f;
const float BETA = 0.0f;
size_t CudaMatrixKernel::requiredInputs() const
{
return 2;
}
void CudaMatrixKernel::startup(const std::vector<std::string>& arguments)
{
Matrix<float> matrixA = MatrixHelper::readMatrixFrom(arguments[0]);
Matrix<float> matrixB = MatrixHelper::readMatrixFrom(arguments[1]);
matrixARows = matrixA.rows();
matrixACols = matrixA.columns();
matrixBRows = matrixB.rows();
matrixBCols = matrixB.columns();
if (matrixACols != matrixBRows)
throw MismatchedMatricesException(matrixACols, matrixBRows);
size_t matrixASize = matrixARows * matrixACols;
size_t matrixBSize = matrixACols * matrixBCols;
size_t outputSize = matrixARows * matrixBCols;
matrixMemA.reallocate(matrixASize);
matrixMemB.reallocate(matrixBSize);
outputMatrix.reallocate(outputSize);
cublas.reset(new Cublas());
cublas->setMatrix(matrixARows, matrixACols, sizeof(float), matrixA.buffer(), matrixARows, matrixMemA, matrixARows);
cublas->setMatrix(matrixACols, matrixBCols, sizeof(float), matrixB.buffer(), matrixACols, matrixMemB, matrixACols);
}
void CudaMatrixKernel::run()
{
std::swap(matrixARows, matrixACols);
std::swap(matrixBRows, matrixBCols);
cublas->Sgemm(
CUBLAS_OP_N, CUBLAS_OP_N,
matrixBRows, matrixACols, matrixBCols,
&ALPHA,
matrixMemB, matrixBRows,
matrixMemA, matrixARows,
&BETA,
outputMatrix, matrixBRows
);
}
void CudaMatrixKernel::shutdown(const std::string& outputFilename)
{
std::swap(matrixARows, matrixACols);
std::swap(matrixBRows, matrixBCols);
size_t rows = matrixARows;
size_t cols = matrixBCols;
vector<float> outputBuffer(rows * cols);
cublas->getMatrix(rows, cols, sizeof(float), outputMatrix, rows, outputBuffer.data(), rows);
Matrix<float> targetMatrix(rows, cols, move(outputBuffer));
MatrixHelper::writeMatrixTo(outputFilename, targetMatrix);
}
std::shared_ptr<BenchmarkKernel> createKernel()
{
BenchmarkKernel* kernel = new CudaMatrixKernel();
return std::shared_ptr<BenchmarkKernel>(kernel);
}
<|endoftext|> |
<commit_before>#include"Application.hpp"
namespace viewmodel {
void Application::start() {
std::string globalDataDirectories( std::getenv("XDG_DATA_DIRS") );
std::string globalDataDirectory = globalDataDirectories.substr( 0, globalDataDirectories.find_first_of(':') );
std::string localDataDirectories( std::getenv("XDG_DATA_HOME") );
std::string localDataDirectory = localDataDirectories.substr( 0, localDataDirectories.find_first_of(':') );
std::string boardSubdirectory("/boards");
boardLoader = BoardLoaderP( new BoardLoader() );
boardLoader->loadBoards(globalDataDirectory + boardSubdirectory);
boardLoader->loadBoards(localDataDirectory + boardSubdirectory);
std::string armySubdirectory("/armies");
armyLoader = ArmyLoaderP( new ArmyLoader() );
armyLoader->loadArmies(globalDataDirectory + armySubdirectory);
armyLoader->loadArmies(localDataDirectory + armySubdirectory);
mainMenu = MainMenuP( new MainMenu( boardLoader, armyLoader ) );
sigModified(*this);
}
}
<commit_msg>Made the expected data directories more sane.<commit_after>#include"Application.hpp"
namespace viewmodel {
void Application::start() {
std::string programDirectory("/neurohex");
std::string globalDataDirectories( std::getenv("XDG_DATA_DIRS") );
std::string globalDataDirectory = globalDataDirectories.substr( 0, globalDataDirectories.find_first_of(':') ) + programDirectory;
std::string localDataDirectories( std::getenv("XDG_DATA_HOME") );
std::string localDataDirectory = localDataDirectories.substr( 0, localDataDirectories.find_first_of(':') ) + programDirectory;
std::string boardSubdirectory("/boards");
boardLoader = BoardLoaderP( new BoardLoader() );
boardLoader->loadBoards(globalDataDirectory + boardSubdirectory);
boardLoader->loadBoards(localDataDirectory + boardSubdirectory);
std::string armySubdirectory("/armies");
armyLoader = ArmyLoaderP( new ArmyLoader() );
armyLoader->loadArmies(globalDataDirectory + armySubdirectory);
armyLoader->loadArmies(localDataDirectory + armySubdirectory);
mainMenu = MainMenuP( new MainMenu( boardLoader, armyLoader ) );
sigModified(*this);
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2014, Andrew Bell
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include <pdal/pdal_internal.hpp>
#ifdef PDAL_HAVE_ZLIB
#include <zlib.h>
#endif
#include <pdal/drivers/bpf/BpfReader.hpp>
#include <pdal/Options.hpp>
namespace pdal
{
void BpfReader::processOptions(const Options&)
{
if (m_filename.empty())
throw pdal_error("Can't read BPF file without filename.");
}
// When the stage is intialized, the schema needs to be populated with the
// dimensions in order to allow subsequent stages to be aware of or append to
// the dimensions in the PointBuffer.
void BpfReader::initialize()
{
m_stream.open(m_filename);
// In order to know the dimensions we must read the file header.
if (!m_header.read(m_stream))
return;
uint32_t zone(abs(m_header.m_coordId));
std::string code("");
if (m_header.m_coordId > 0)
code = "EPSG:269" + boost::lexical_cast<std::string>(zone);
else
code = "EPSG:327" + boost::lexical_cast<std::string>(zone);
SpatialReference srs(code);
setSpatialReference(srs);
m_dims.insert(m_dims.end(), m_header.m_numDim, BpfDimension());
if (!BpfDimension::read(m_stream, m_dims))
return;
readUlemData();
if (!m_stream)
return;
readUlemFiles();
if (!m_stream)
return;
readPolarData();
// Fast forward file to end of header as reported by base header.
std::streampos pos = m_stream.position();
if (pos > m_header.m_len)
throw "BPF Header length exceeded that reported by file.";
else if (pos < m_header.m_len)
m_stream.seek(m_header.m_len);
}
void BpfReader::addDimensions(PointContextRef ctx)
{
for (size_t i = 0; i < m_dims.size(); ++i)
{
BpfDimension& dim = m_dims[i];
dim.m_id = ctx.registerOrAssignDim(dim.m_label, Dimension::Type::Float);
}
}
bool BpfReader::readUlemData()
{
if (!m_ulemHeader.read(m_stream))
return false;
for (size_t i = 0; i < m_ulemHeader.m_numFrames; i++)
{
BpfUlemFrame frame;
if (!frame.read(m_stream))
return false;
m_ulemFrames.push_back(frame);
}
return (bool)m_stream;
}
bool BpfReader::readUlemFiles()
{
BpfUlemFile file;
while (file.read(m_stream))
m_metadata.addEncoded(file.m_filename,
(const unsigned char *)file.m_buf.data(), file.m_len);
return (bool)m_stream;
}
bool BpfReader::readPolarData()
{
if (!m_polarHeader.read(m_stream))
return false;
for (size_t i = 0; i < m_polarHeader.m_numFrames; ++i)
{
BpfPolarFrame frame;
if (!frame.read(m_stream))
return false;
m_polarFrames.push_back(frame);
}
return (bool)m_stream;
}
void BpfReader::ready(PointContextRef ctx)
{
m_index = 0;
m_start = m_stream.position();
if (m_header.m_compression)
{
#ifdef PDAL_HAVE_ZLIB
m_deflateBuf.resize(numPoints() * m_dims.size() * sizeof(float));
size_t index = 0;
size_t bytesRead = 0;
do
{
bytesRead = readBlock(m_deflateBuf, index);
index += bytesRead;
} while (bytesRead > 0 && index < m_deflateBuf.size());
m_charbuf.initialize(m_deflateBuf.data(), m_deflateBuf.size(), m_start);
m_stream.pushStream(new std::istream(&m_charbuf));
#else
throw "BPF compression required, but ZLIB is unavailable.";
#endif
}
}
void BpfReader::done(PointContextRef)
{
delete m_stream.popStream();
}
point_count_t BpfReader::read(PointBuffer& data, point_count_t count)
{
switch (m_header.m_pointFormat)
{
case BpfFormat::PointMajor:
return readPointMajor(data, count);
case BpfFormat::DimMajor:
return readDimMajor(data, count);
case BpfFormat::ByteMajor:
return readByteMajor(data, count);
default:
break;
}
return 0;
}
size_t BpfReader::readBlock(std::vector<char>& outBuf, size_t index)
{
#ifdef PDAL_HAVE_ZLIB
boost::uint32_t finalBytes;
boost::uint32_t compressBytes;
m_stream >> finalBytes;
m_stream >> compressBytes;
std::vector<char> in(compressBytes);
// Fill the input bytes from the stream.
m_stream.get(in);
int ret = inflate(in.data(), compressBytes,
outBuf.data() + index, finalBytes);
return (ret ? 0 : finalBytes);
#else
throw pdal_error("BPF compression required, but ZLIB is unavailable");
#endif
}
bool BpfReader::eof()
{
return m_index >= numPoints();
}
point_count_t BpfReader::readPointMajor(PointBuffer& data, point_count_t count)
{
PointId nextId = data.size();
PointId idx = m_index;
point_count_t numRead = 0;
seekPointMajor(idx);
while (numRead < count && idx < numPoints())
{
for (size_t d = 0; d < m_dims.size(); ++d)
{
float f;
m_stream >> f;
data.setField(m_dims[d].m_id, nextId, f + m_dims[d].m_offset);
}
idx++;
numRead++;
nextId++;
}
m_index = idx;
return numRead;
}
point_count_t BpfReader::readDimMajor(PointBuffer& data, point_count_t count)
{
PointId idx;
PointId startId = data.size();
point_count_t numRead = 0;
for (size_t d = 0; d < m_dims.size(); ++d)
{
idx = m_index;
PointId nextId = startId;
numRead = 0;
seekDimMajor(d, idx);
for (; numRead < count && idx < numPoints(); idx++, numRead++, nextId++)
{
float f;
m_stream >> f;
data.setField(m_dims[d].m_id, nextId, f + m_dims[d].m_offset);
}
}
m_index = idx;
return numRead;
}
point_count_t BpfReader::readByteMajor(PointBuffer& data, point_count_t count)
{
PointId idx;
PointId startId = data.size();
point_count_t numRead = 0;
// We need a temp buffer for the point data.
union uu
{
float f;
uint32_t u32;
};
std::unique_ptr<union uu> uArr(
new uu[std::min(count, numPoints() - m_index)]);
for (size_t d = 0; d < m_dims.size(); ++d)
{
for (size_t b = 0; b < sizeof(float); ++b)
{
idx = m_index;
numRead = 0;
PointId nextId = startId;
seekByteMajor(d, b, idx);
for (;numRead < count && idx < numPoints();
idx++, numRead++, nextId++)
{
union uu& u = *(uArr.get() + numRead);
if (b == 0)
u.u32 = 0;
uint8_t u8;
m_stream >> u8;
u.u32 |= ((uint32_t)u8 << (b * CHAR_BIT));
if (b == 3)
{
u.f += m_dims[d].m_offset;
data.setField(m_dims[d].m_id, nextId, u.f);
}
}
}
}
m_index = idx;
return numRead;
}
void BpfReader::seekPointMajor(PointId ptIdx)
{
std::streamoff offset = ptIdx * sizeof(float) * m_dims.size();
m_stream.seek(m_start + offset);
}
void BpfReader::seekDimMajor(size_t dimIdx, PointId ptIdx)
{
std::streamoff offset = ((sizeof(float) * dimIdx * numPoints()) +
(sizeof(float) * ptIdx));
m_stream.seek(m_start + offset);
}
void BpfReader::seekByteMajor(size_t dimIdx, size_t byteIdx, PointId ptIdx)
{
std::streamoff offset =
(dimIdx * numPoints() * sizeof(float)) +
(byteIdx * numPoints()) +
ptIdx;
m_stream.seek(m_start + offset);
}
#ifdef PDAL_HAVE_ZLIB
int BpfReader::inflate(char *buf, size_t insize, char *outbuf, size_t outsize)
{
if (insize == 0)
return 0;
int ret;
z_stream strm;
/* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
if (inflateInit(&strm) != Z_OK)
return -2;
strm.avail_in = insize;
strm.next_in = (unsigned char *)buf;
strm.avail_out = outsize;
strm.next_out = (unsigned char *)outbuf;
ret = ::inflate(&strm, Z_NO_FLUSH);
(void)inflateEnd(&strm);
return ret == Z_STREAM_END ? 0 : -1;
}
#endif
} //namespace pdal
<commit_msg>put PDAL_HAVE_GDAL guard around setSpatialReference call in BPF reader<commit_after>/******************************************************************************
* Copyright (c) 2014, Andrew Bell
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include <pdal/pdal_internal.hpp>
#ifdef PDAL_HAVE_ZLIB
#include <zlib.h>
#endif
#include <pdal/drivers/bpf/BpfReader.hpp>
#include <pdal/Options.hpp>
namespace pdal
{
void BpfReader::processOptions(const Options&)
{
if (m_filename.empty())
throw pdal_error("Can't read BPF file without filename.");
}
// When the stage is intialized, the schema needs to be populated with the
// dimensions in order to allow subsequent stages to be aware of or append to
// the dimensions in the PointBuffer.
void BpfReader::initialize()
{
m_stream.open(m_filename);
// In order to know the dimensions we must read the file header.
if (!m_header.read(m_stream))
return;
#ifdef PDAL_HAVE_GDAL
uint32_t zone(abs(m_header.m_coordId));
std::string code("");
if (m_header.m_coordId > 0)
code = "EPSG:269" + boost::lexical_cast<std::string>(zone);
else
code = "EPSG:327" + boost::lexical_cast<std::string>(zone);
SpatialReference srs(code);
setSpatialReference(srs);
#endif
m_dims.insert(m_dims.end(), m_header.m_numDim, BpfDimension());
if (!BpfDimension::read(m_stream, m_dims))
return;
readUlemData();
if (!m_stream)
return;
readUlemFiles();
if (!m_stream)
return;
readPolarData();
// Fast forward file to end of header as reported by base header.
std::streampos pos = m_stream.position();
if (pos > m_header.m_len)
throw "BPF Header length exceeded that reported by file.";
else if (pos < m_header.m_len)
m_stream.seek(m_header.m_len);
}
void BpfReader::addDimensions(PointContextRef ctx)
{
for (size_t i = 0; i < m_dims.size(); ++i)
{
BpfDimension& dim = m_dims[i];
dim.m_id = ctx.registerOrAssignDim(dim.m_label, Dimension::Type::Float);
}
}
bool BpfReader::readUlemData()
{
if (!m_ulemHeader.read(m_stream))
return false;
for (size_t i = 0; i < m_ulemHeader.m_numFrames; i++)
{
BpfUlemFrame frame;
if (!frame.read(m_stream))
return false;
m_ulemFrames.push_back(frame);
}
return (bool)m_stream;
}
bool BpfReader::readUlemFiles()
{
BpfUlemFile file;
while (file.read(m_stream))
m_metadata.addEncoded(file.m_filename,
(const unsigned char *)file.m_buf.data(), file.m_len);
return (bool)m_stream;
}
bool BpfReader::readPolarData()
{
if (!m_polarHeader.read(m_stream))
return false;
for (size_t i = 0; i < m_polarHeader.m_numFrames; ++i)
{
BpfPolarFrame frame;
if (!frame.read(m_stream))
return false;
m_polarFrames.push_back(frame);
}
return (bool)m_stream;
}
void BpfReader::ready(PointContextRef ctx)
{
m_index = 0;
m_start = m_stream.position();
if (m_header.m_compression)
{
#ifdef PDAL_HAVE_ZLIB
m_deflateBuf.resize(numPoints() * m_dims.size() * sizeof(float));
size_t index = 0;
size_t bytesRead = 0;
do
{
bytesRead = readBlock(m_deflateBuf, index);
index += bytesRead;
} while (bytesRead > 0 && index < m_deflateBuf.size());
m_charbuf.initialize(m_deflateBuf.data(), m_deflateBuf.size(), m_start);
m_stream.pushStream(new std::istream(&m_charbuf));
#else
throw "BPF compression required, but ZLIB is unavailable.";
#endif
}
}
void BpfReader::done(PointContextRef)
{
delete m_stream.popStream();
}
point_count_t BpfReader::read(PointBuffer& data, point_count_t count)
{
switch (m_header.m_pointFormat)
{
case BpfFormat::PointMajor:
return readPointMajor(data, count);
case BpfFormat::DimMajor:
return readDimMajor(data, count);
case BpfFormat::ByteMajor:
return readByteMajor(data, count);
default:
break;
}
return 0;
}
size_t BpfReader::readBlock(std::vector<char>& outBuf, size_t index)
{
#ifdef PDAL_HAVE_ZLIB
boost::uint32_t finalBytes;
boost::uint32_t compressBytes;
m_stream >> finalBytes;
m_stream >> compressBytes;
std::vector<char> in(compressBytes);
// Fill the input bytes from the stream.
m_stream.get(in);
int ret = inflate(in.data(), compressBytes,
outBuf.data() + index, finalBytes);
return (ret ? 0 : finalBytes);
#else
throw pdal_error("BPF compression required, but ZLIB is unavailable");
#endif
}
bool BpfReader::eof()
{
return m_index >= numPoints();
}
point_count_t BpfReader::readPointMajor(PointBuffer& data, point_count_t count)
{
PointId nextId = data.size();
PointId idx = m_index;
point_count_t numRead = 0;
seekPointMajor(idx);
while (numRead < count && idx < numPoints())
{
for (size_t d = 0; d < m_dims.size(); ++d)
{
float f;
m_stream >> f;
data.setField(m_dims[d].m_id, nextId, f + m_dims[d].m_offset);
}
idx++;
numRead++;
nextId++;
}
m_index = idx;
return numRead;
}
point_count_t BpfReader::readDimMajor(PointBuffer& data, point_count_t count)
{
PointId idx;
PointId startId = data.size();
point_count_t numRead = 0;
for (size_t d = 0; d < m_dims.size(); ++d)
{
idx = m_index;
PointId nextId = startId;
numRead = 0;
seekDimMajor(d, idx);
for (; numRead < count && idx < numPoints(); idx++, numRead++, nextId++)
{
float f;
m_stream >> f;
data.setField(m_dims[d].m_id, nextId, f + m_dims[d].m_offset);
}
}
m_index = idx;
return numRead;
}
point_count_t BpfReader::readByteMajor(PointBuffer& data, point_count_t count)
{
PointId idx;
PointId startId = data.size();
point_count_t numRead = 0;
// We need a temp buffer for the point data.
union uu
{
float f;
uint32_t u32;
};
std::unique_ptr<union uu> uArr(
new uu[std::min(count, numPoints() - m_index)]);
for (size_t d = 0; d < m_dims.size(); ++d)
{
for (size_t b = 0; b < sizeof(float); ++b)
{
idx = m_index;
numRead = 0;
PointId nextId = startId;
seekByteMajor(d, b, idx);
for (;numRead < count && idx < numPoints();
idx++, numRead++, nextId++)
{
union uu& u = *(uArr.get() + numRead);
if (b == 0)
u.u32 = 0;
uint8_t u8;
m_stream >> u8;
u.u32 |= ((uint32_t)u8 << (b * CHAR_BIT));
if (b == 3)
{
u.f += m_dims[d].m_offset;
data.setField(m_dims[d].m_id, nextId, u.f);
}
}
}
}
m_index = idx;
return numRead;
}
void BpfReader::seekPointMajor(PointId ptIdx)
{
std::streamoff offset = ptIdx * sizeof(float) * m_dims.size();
m_stream.seek(m_start + offset);
}
void BpfReader::seekDimMajor(size_t dimIdx, PointId ptIdx)
{
std::streamoff offset = ((sizeof(float) * dimIdx * numPoints()) +
(sizeof(float) * ptIdx));
m_stream.seek(m_start + offset);
}
void BpfReader::seekByteMajor(size_t dimIdx, size_t byteIdx, PointId ptIdx)
{
std::streamoff offset =
(dimIdx * numPoints() * sizeof(float)) +
(byteIdx * numPoints()) +
ptIdx;
m_stream.seek(m_start + offset);
}
#ifdef PDAL_HAVE_ZLIB
int BpfReader::inflate(char *buf, size_t insize, char *outbuf, size_t outsize)
{
if (insize == 0)
return 0;
int ret;
z_stream strm;
/* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
if (inflateInit(&strm) != Z_OK)
return -2;
strm.avail_in = insize;
strm.next_in = (unsigned char *)buf;
strm.avail_out = outsize;
strm.next_out = (unsigned char *)outbuf;
ret = ::inflate(&strm, Z_NO_FLUSH);
(void)inflateEnd(&strm);
return ret == Z_STREAM_END ? 0 : -1;
}
#endif
} //namespace pdal
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.