text
stringlengths 54
60.6k
|
---|
<commit_before>#include "MainLogic.h"
#include "MotorDriver.h"
#include "DualEncoderDriver.h"
#include "FrontLiftedDetection.h"
#include "ProximitySensors.h"
#include <cmath>
#define STANDARD_SPEED 170
#define SPEED_CHANGE_STEP 1
#define DISTANCE_BETWEEN_MOTORS 85.00
#define HALF_DISTANCE_BETWEEN_MOTORS (DISTANCE_BETWEEN_MOTORS / 2.00)
#define SAMPLE_FREQUENCY 250
enum {
SEARCH_INITIAL,
SEARCH_TURNING,
SEARCH_FORWARD,
FOUND_LEFT,
FOUND_RIGHT,
FOUND_STRAIGHT,
STOP_MOVING
} STATE = SEARCH_INITIAL;
enum {
MOVEMENT_SYSTEM_STATUS_OFF,
MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT,
MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT
} movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
static float distanceExpectedByLeftTire, distanceExpectedByRightTire;
static int16_t leftMotorSpeed, rightMotorSpeed, leftMotorDir, rightMotorDir;
static int8_t directionOfLinearMovement;
static float circleMotorSpeedDifference;
void HandleControlledMovement(float leftTyreSpeed, float rightTyreSpeed)
{
switch(movementSystemStatus)
{
case MOVEMENT_SYSTEM_STATUS_OFF:
// stop the motors, they should not be moving
setMotors(0, 0);
break;
case MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT:
{
// check if the speeds are the same if not correct the speed of the slower motors
if(leftTyreSpeed > rightTyreSpeed)
{
leftMotorSpeed -= SPEED_CHANGE_STEP;
}
else if(leftTyreSpeed < rightTyreSpeed)
{
leftMotorSpeed += SPEED_CHANGE_STEP;
}
// update moved distance
distanceExpectedByLeftTire -= (float)(leftTyreSpeed / SAMPLE_FREQUENCY);
distanceExpectedByRightTire -= (float)(rightTyreSpeed / SAMPLE_FREQUENCY);
if( (distanceExpectedByLeftTire < 0 && directionOfLinearMovement > 0) ||
(distanceExpectedByLeftTire > 0 && directionOfLinearMovement < 0) )
{
leftMotorSpeed = 0;
}
if( (distanceExpectedByRightTire < 0 && directionOfLinearMovement > 0) ||
(distanceExpectedByRightTire > 0 && directionOfLinearMovement < 0) )
{
rightMotorSpeed = 0;
}
if(leftMotorSpeed == 0 && rightMotorSpeed == 0)
{
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
}
setMotors(leftMotorSpeed, rightMotorSpeed);
break;
}
case MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT:
{
// check if the speeds are the same if not correct the speed of the slower motors
if(leftTyreSpeed / rightTyreSpeed > circleMotorSpeedDifference)
{
leftMotorSpeed -= SPEED_CHANGE_STEP;
rightMotorSpeed += SPEED_CHANGE_STEP;
}
else if(leftTyreSpeed / rightTyreSpeed < circleMotorSpeedDifference)
{
leftMotorSpeed += SPEED_CHANGE_STEP;
rightMotorSpeed -= SPEED_CHANGE_STEP;
}
// update moved distance
distanceExpectedByLeftTire -= leftTyreSpeed / SAMPLE_FREQUENCY;
distanceExpectedByRightTire -= rightTyreSpeed / SAMPLE_FREQUENCY;
if( (distanceExpectedByLeftTire < 0 && leftMotorDir > 0) ||
(distanceExpectedByLeftTire > 0 && leftMotorDir < 0) )
{
leftMotorSpeed = 0;
}
if( (distanceExpectedByRightTire < 0 && rightMotorDir > 0) ||
(distanceExpectedByRightTire > 0 && rightMotorDir < 0) )
{
rightMotorSpeed = 0;
}
if(leftMotorSpeed == 0 && rightMotorSpeed == 0)
{
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
}
setMotors(leftMotorSpeed, rightMotorSpeed);
break;
}
}
}
inline bool IsMovementComplete()
{
return movementSystemStatus == MOVEMENT_SYSTEM_STATUS_OFF;
}
void LinearMovement(int32_t distanceInMMWithDirection) // TODO: Fix backwards
{
// evaluate direction and pass to drivers the start state
if(0 < distanceInMMWithDirection)
{
directionOfLinearMovement = 1;
setMotors(STANDARD_SPEED, STANDARD_SPEED);
}
else
{
directionOfLinearMovement = -1;
setMotors(-STANDARD_SPEED, -STANDARD_SPEED);
}
// set setpoints for end of movement, used in handler
distanceExpectedByRightTire = (float)distanceInMMWithDirection;
distanceExpectedByLeftTire = (float)distanceInMMWithDirection;
// set motor speeds, used in handler
rightMotorSpeed = STANDARD_SPEED;
leftMotorSpeed = STANDARD_SPEED;
// set state on state machine
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT;
}
void Turn(int turnRadius, int turnDegrees)
{
if(turnDegrees == 0) return;
distanceExpectedByLeftTire = 2.00 * ((float)turnRadius + HALF_DISTANCE_BETWEEN_MOTORS) * M_PI * (float)turnDegrees / 360;
distanceExpectedByRightTire = 2.00 * ((float)turnRadius - HALF_DISTANCE_BETWEEN_MOTORS) * M_PI * (float)turnDegrees / 360;
if(turnDegrees < 0)
{
auto temp = -distanceExpectedByLeftTire;
distanceExpectedByLeftTire = -distanceExpectedByRightTire;
distanceExpectedByRightTire = temp;
}
circleMotorSpeedDifference = distanceExpectedByLeftTire / distanceExpectedByRightTire;
leftMotorDir = (turnDegrees > 0 || distanceExpectedByLeftTire > 0) ? 1 : -1;
rightMotorDir = (turnDegrees < 0 || distanceExpectedByRightTire > 0) ? 1 : -1;
leftMotorSpeed = STANDARD_SPEED * leftMotorDir;
rightMotorSpeed = STANDARD_SPEED * rightMotorDir;
if(turnDegrees > 0) leftMotorSpeed *= STANDARD_SPEED;
else rightMotorSpeed *= STANDARD_SPEED;
setMotors(leftMotorSpeed, rightMotorSpeed);
// set state on state machine
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT;
}
void MovePattern()
{
switch(STATE)
{
case SEARCH_INITIAL:
if(IsMovementComplete())
{
Turn(0, -90);
STATE = SEARCH_TURNING;
}
break;
case SEARCH_TURNING:
if(IsMovementComplete())
{
LinearMovement(200);
STATE = SEARCH_FORWARD;
}
break;
case SEARCH_FORWARD:
if(IsMovementComplete())
{
Turn(50, 270);
STATE = SEARCH_TURNING;
}
break;
case FOUND_LEFT:
Turn(0, -90);
STATE = FOUND_STRAIGHT;
break;
case FOUND_RIGHT:
Turn(0, 90);
STATE = FOUND_STRAIGHT;
break;
case FOUND_STRAIGHT:
if(IsMovementComplete())
{
LinearMovement(1000);
STATE = FOUND_STRAIGHT;
}
break;
default:
if(IsMovementComplete())
{
setMotors(0, 0);
}
break;
}
}
/*
void RoundPattern()
{
switch(STATE)
{
case INITIAL_STATE:
{
Turn(200,360);
STATE = STATE_TURNING;
}
break;
case STATE_TURNING:
if(IsMovementComplete())
{
// keep turning
Turn(200,360);
}
break;
default:
setMotors(0, 0);
break;
}
// if( digitalRead(LEFT_SENSOR_PIN) ^ 1 == 1 || digitalRead(RIGHT_SENSOR_PIN) ^ 1 == 1)
// {
// STATE = EXIT_STATE_ON_SIDE;
// }
// if(OutOfRing())
// {
// STATE = EXIT_STATE_OUT_OF_RING;
// }
// if(Impact())
// {
// STATE = EXIT_STATE_ON_IMPACT;
// }
}
*/
void MainLogic(float left_speed, float right_speed)
{
uint8_t left, right;
readProximitySensors(left, right);
if(left) STATE = FOUND_LEFT;
else if(right) STATE = FOUND_RIGHT;
MovePattern();
HandleControlledMovement(left_speed, right_speed);
}
<commit_msg>Typo fixes<commit_after>#include "MainLogic.h"
#include "MotorDriver.h"
#include "DualEncoderDriver.h"
#include "FrontLiftedDetection.h"
#include "ProximitySensors.h"
#include <cmath>
#define STANDARD_SPEED 170
#define SPEED_CHANGE_STEP 1
#define DISTANCE_BETWEEN_MOTORS 85.00
#define HALF_DISTANCE_BETWEEN_MOTORS (DISTANCE_BETWEEN_MOTORS / 2.00)
#define SAMPLE_FREQUENCY 250
enum {
SEARCH_INITIAL,
SEARCH_TURNING,
SEARCH_FORWARD,
FOUND_LEFT,
FOUND_RIGHT,
FOUND_STRAIGHT,
STOP_MOVING
} STATE = SEARCH_INITIAL;
enum {
MOVEMENT_SYSTEM_STATUS_OFF,
MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT,
MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT
} movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
static float distanceExpectedByLeftTire, distanceExpectedByRightTire;
static int16_t leftMotorSpeed, rightMotorSpeed, leftMotorDir, rightMotorDir;
static int8_t directionOfLinearMovement;
static float circleMotorSpeedDifference;
void HandleControlledMovement(float leftTireSpeed, float rightTireSpeed)
{
switch(movementSystemStatus)
{
case MOVEMENT_SYSTEM_STATUS_OFF:
// stop the motors, they should not be moving
setMotors(0, 0);
break;
case MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT:
{
// check if the speeds are the same if not correct the speed of the slower motors
if(leftTireSpeed > rightTireSpeed)
{
leftMotorSpeed -= SPEED_CHANGE_STEP;
}
else if(leftTireSpeed < rightTireSpeed)
{
leftMotorSpeed += SPEED_CHANGE_STEP;
}
// update moved distance
distanceExpectedByLeftTire -= (float)(leftTireSpeed / SAMPLE_FREQUENCY);
distanceExpectedByRightTire -= (float)(rightTireSpeed / SAMPLE_FREQUENCY);
if( (distanceExpectedByLeftTire < 0 && directionOfLinearMovement > 0) ||
(distanceExpectedByLeftTire > 0 && directionOfLinearMovement < 0) )
{
leftMotorSpeed = 0;
}
if( (distanceExpectedByRightTire < 0 && directionOfLinearMovement > 0) ||
(distanceExpectedByRightTire > 0 && directionOfLinearMovement < 0) )
{
rightMotorSpeed = 0;
}
if(leftMotorSpeed == 0 && rightMotorSpeed == 0)
{
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
}
setMotors(leftMotorSpeed, rightMotorSpeed);
break;
}
case MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT:
{
// check if the speeds are the same if not correct the speed of the slower motors
if(leftTireSpeed / rightTireSpeed > circleMotorSpeedDifference)
{
leftMotorSpeed -= SPEED_CHANGE_STEP;
rightMotorSpeed += SPEED_CHANGE_STEP;
}
else if(leftTireSpeed / rightTireSpeed < circleMotorSpeedDifference)
{
leftMotorSpeed += SPEED_CHANGE_STEP;
rightMotorSpeed -= SPEED_CHANGE_STEP;
}
// update moved distance
distanceExpectedByLeftTire -= leftTireSpeed / SAMPLE_FREQUENCY;
distanceExpectedByRightTire -= rightTireSpeed / SAMPLE_FREQUENCY;
if( (distanceExpectedByLeftTire < 0 && leftMotorDir > 0) ||
(distanceExpectedByLeftTire > 0 && leftMotorDir < 0) )
{
leftMotorSpeed = 0;
}
if( (distanceExpectedByRightTire < 0 && rightMotorDir > 0) ||
(distanceExpectedByRightTire > 0 && rightMotorDir < 0) )
{
rightMotorSpeed = 0;
}
if(leftMotorSpeed == 0 && rightMotorSpeed == 0)
{
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_OFF;
}
setMotors(leftMotorSpeed, rightMotorSpeed);
break;
}
}
}
inline bool IsMovementComplete()
{
return movementSystemStatus == MOVEMENT_SYSTEM_STATUS_OFF;
}
void LinearMovement(int32_t distanceInMMWithDirection) // TODO: Fix backwards
{
// evaluate direction and pass to drivers the start state
if(0 < distanceInMMWithDirection)
{
directionOfLinearMovement = 1;
setMotors(STANDARD_SPEED, STANDARD_SPEED);
}
else
{
directionOfLinearMovement = -1;
setMotors(-STANDARD_SPEED, -STANDARD_SPEED);
}
// set setpoints for end of movement, used in handler
distanceExpectedByRightTire = (float)distanceInMMWithDirection;
distanceExpectedByLeftTire = (float)distanceInMMWithDirection;
// set motor speeds, used in handler
rightMotorSpeed = STANDARD_SPEED;
leftMotorSpeed = STANDARD_SPEED;
// set state on state machine
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_LINEAR_MOVEMENT;
}
void Turn(int turnRadius, int turnDegrees)
{
if(turnDegrees == 0) return;
distanceExpectedByLeftTire = 2.00 * ((float)turnRadius + HALF_DISTANCE_BETWEEN_MOTORS) * M_PI * (float)turnDegrees / 360;
distanceExpectedByRightTire = 2.00 * ((float)turnRadius - HALF_DISTANCE_BETWEEN_MOTORS) * M_PI * (float)turnDegrees / 360;
if(turnDegrees < 0)
{
auto temp = -distanceExpectedByLeftTire;
distanceExpectedByLeftTire = -distanceExpectedByRightTire;
distanceExpectedByRightTire = temp;
}
circleMotorSpeedDifference = distanceExpectedByLeftTire / distanceExpectedByRightTire;
leftMotorDir = (turnDegrees > 0 || distanceExpectedByLeftTire > 0) ? 1 : -1;
rightMotorDir = (turnDegrees < 0 || distanceExpectedByRightTire > 0) ? 1 : -1;
leftMotorSpeed = STANDARD_SPEED * leftMotorDir;
rightMotorSpeed = STANDARD_SPEED * rightMotorDir;
if(turnDegrees > 0) leftMotorSpeed *= STANDARD_SPEED;
else rightMotorSpeed *= STANDARD_SPEED;
setMotors(leftMotorSpeed, rightMotorSpeed);
// set state on state machine
movementSystemStatus = MOVEMENT_SYSTEM_STATUS_ROUND_MOVEMENT;
}
void MovePattern()
{
switch(STATE)
{
case SEARCH_INITIAL:
if(IsMovementComplete())
{
Turn(0, -90);
STATE = SEARCH_TURNING;
}
break;
case SEARCH_TURNING:
if(IsMovementComplete())
{
LinearMovement(200);
STATE = SEARCH_FORWARD;
}
break;
case SEARCH_FORWARD:
if(IsMovementComplete())
{
Turn(50, 270);
STATE = SEARCH_TURNING;
}
break;
case FOUND_LEFT:
Turn(0, -90);
STATE = FOUND_STRAIGHT;
break;
case FOUND_RIGHT:
Turn(0, 90);
STATE = FOUND_STRAIGHT;
break;
case FOUND_STRAIGHT:
if(IsMovementComplete())
{
LinearMovement(1000);
STATE = FOUND_STRAIGHT;
}
break;
default:
if(IsMovementComplete())
{
setMotors(0, 0);
}
break;
}
}
/*
void RoundPattern()
{
switch(STATE)
{
case INITIAL_STATE:
{
Turn(200,360);
STATE = STATE_TURNING;
}
break;
case STATE_TURNING:
if(IsMovementComplete())
{
// keep turning
Turn(200,360);
}
break;
default:
setMotors(0, 0);
break;
}
// if( digitalRead(LEFT_SENSOR_PIN) ^ 1 == 1 || digitalRead(RIGHT_SENSOR_PIN) ^ 1 == 1)
// {
// STATE = EXIT_STATE_ON_SIDE;
// }
// if(OutOfRing())
// {
// STATE = EXIT_STATE_OUT_OF_RING;
// }
// if(Impact())
// {
// STATE = EXIT_STATE_ON_IMPACT;
// }
}
*/
void MainLogic(float left_speed, float right_speed)
{
uint8_t left, right;
readProximitySensors(left, right);
if(left) STATE = FOUND_LEFT;
else if(right) STATE = FOUND_RIGHT;
MovePattern();
HandleControlledMovement(left_speed, right_speed);
}
<|endoftext|> |
<commit_before>/* This file is part of the Palabos library.
*
* Copyright (C) 2011-2015 FlowKit Sarl
* Route d'Oron 2
* 1010 Lausanne, Switzerland
* E-mail contact: [email protected]
*
* The most recent release of Palabos can be downloaded at
* <http://www.palabos.org/>
*
* The library Palabos is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* The 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Code 1.1 in the Palabos tutorial
*/
#include "palabos2D.h"
#ifndef PLB_PRECOMPILED // Unless precompiled version is used,
#include "palabos2D.hh" // include full template code
#endif
#include <vector>
#include <cmath>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace plb;
using namespace std;
typedef double T;
#define DESCRIPTOR plb::descriptors::D2Q9Descriptor
#define PI 3.14159265
// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics2D.h"
using namespace plb_acoustics;
// ---------------------------------------------
T rho0 = 1.;
T deltaRho = 1.e-4;
T lattice_speed_sound = 1/sqrt(3);
int main(int argc, char* argv[]) {
plbInit(&argc, &argv);
global::directories().setOutputDir("./tmp/");
plint numCores = global::mpi().getSize();
pcout << "Number of MPI threads: " << numCores << std::endl;
const plint maxIter = 10000; // 120000 Iterate during 1000 steps.
const plint nx = 1000; // Choice of lattice dimensions.
const plint ny = 670;
const T omega = 1.98; // Choice of the relaxation parameter
pcout << "Total iteration: " << maxIter << std::endl;
MultiBlockLattice2D<T, DESCRIPTOR> lattice(nx, ny, new CompleteBGKdynamics<T,DESCRIPTOR>(omega));
Array<T,2> u0((T)0,(T)0);
// Initialize constant density everywhere.
initializeAtEquilibrium(lattice, lattice.getBoundingBox(), rho0, u0);
lattice.initialize();
plint size_square = 2;
Box2D square(nx/2 - size_square/2, nx/2 + size_square/2,
ny/2 - size_square/2, ny/2 + size_square/2);
defineDynamics(lattice, square, new BounceBack<T,DESCRIPTOR>(rho0));
// Anechoic Condition
T size_anechoic_buffer = 30;
T rhoBar_target = 0;
Array<T,2> j_target(0.11/std::sqrt(3), 0.0/std::sqrt(3));
//left
plint orientation = 3;
Array<T,2> position_anechoic_wall((T)0,(T)0);
plint length_anechoic_wall = ny + 1;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall, length_anechoic_wall,
rhoBar_target, j_target);
//right
orientation = 1;
Array<T,2> position_anechoic_wall_2((T)nx - 30,(T)0);
length_anechoic_wall = ny + 1;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall_2, length_anechoic_wall,
rhoBar_target, j_target);
//top
orientation = 4;
Array<T,2> position_anechoic_wall_3((T) 0, (T)ny - 30);
length_anechoic_wall = nx + 1;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall_3, length_anechoic_wall,
rhoBar_target, u0);
//bottom
orientation = 2;
Array<T,2> position_anechoic_wall_1((T)0,(T)0);
length_anechoic_wall = nx + 1;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall_1, length_anechoic_wall,
rhoBar_target, u0);
Box2D cima(0, nx, ny - 1, ny);
//defineDynamics(lattice, cima, new BounceBack<T,DESCRIPTOR>(rho0));
Box2D baixo(0, nx, 0, 1);
//defineDynamics(lattice, baixo, new BounceBack<T,DESCRIPTOR>(rho0));
// Main loop over time iterations.
plb_ofstream pressure_file("pressure_50000.dat");
plb_ofstream velocities_file("velocities_50000.dat");
for (plint iT=0; iT<maxIter; ++iT) {
Box2D centralSquare (nx/2, nx/2, ny/2, ny/2);
plb_ofstream pressures_space_file("pressures_space_file.dat");
for (int i = 0; i < ny; i++){
T pressure = lattice_speed_sound*lattice_speed_sound*(lattice.get(nx/2, i).computeDensity() - rho0);
pressures_space_file << setprecision(10) << pressure << endl;
pcout << i << " " << pressure << endl;
}
//T rho_changing = 1. + deltaRho*sin(2*PI*(lattice_speed_sound/200)*iT);
if (iT != 0){
//initializeAtEquilibrium (lattice, centralSquare, rho_changing, u0);
}
if (iT>=60000){
T pressure = lattice_speed_sound*lattice_speed_sound*(lattice.get(680, 460).computeDensity() - rho0);
pressure_file << setprecision(10) << pressure << endl;
Array<T,2> u;
lattice.get(300, ny/2).computeVelocity(u);
velocities_file << setprecision(10) << u[0] << " " << u[1] << endl;
if (iT%1000==0) { // Write an image every 40th time step.
pcout << "iT= " << iT << endl;
ImageWriter<T> imageWriter("leeloo");
imageWriter.writeScaledGif(createFileName("velocity", iT, 6),
*computeVelocityNorm(lattice) );
imageWriter.writeGif(createFileName("density", iT, 6),
*computeDensity(lattice), (T) rho0 - deltaRho/1000, (T) rho0 + deltaRho/1000);
}
}
if (iT%1000==0) { // Write an image every 40th time step.
pcout << "iT= " << iT << endl;
ImageWriter<T> imageWriter("leeloo");
imageWriter.writeScaledGif(createFileName("velocity", iT, 6),
*computeVelocityNorm(lattice) );
imageWriter.writeGif(createFileName("density", iT, 6),
*computeDensity(lattice), (T) rho0 - deltaRho/100, (T) rho0 + deltaRho/100);
/*ImageWriter<T> imageWriter("leeloo");
imageWriter.writeScaledGif(createFileName("u", iT, 6),
*computeVelocityNorm(lattice) );*/
// imageWriter.writeScaledGif(createFileName("u", iT, 6), *computeVorticity(*computeVelocity(lattice)));
//imageWriter.writeScaledGif(createFileName("u", iT, 6), *computeDensity(lattice));
//imageWriter.writeGif(createFileName("u", iT, 6), *computeDensity(lattice), (T) rho0 - deltaRho/1000, (T) rho0 + deltaRho/1000);
pcout << " energy ="
<< setprecision(10) << getStoredAverageEnergy<T>(lattice)
<< " rho ="
<< getStoredAverageDensity<T>(lattice)
<< " max_velocity ="
<< setprecision(10) << getStoredMaxVelocity<T>(lattice)
<< endl;
}
// Execute lattice Boltzmann iteration.
lattice.collideAndStream();
}
}
<commit_msg>Doing directivity<commit_after>/* This file is part of the Palabos library.
*
* Copyright (C) 2011-2015 FlowKit Sarl
* Route d'Oron 2
* 1010 Lausanne, Switzerland
* E-mail contact: [email protected]
*
* The most recent release of Palabos can be downloaded at
* <http://www.palabos.org/>
*
* The library Palabos is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* The 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Code 1.1 in the Palabos tutorial
*/
#include "palabos2D.h"
#ifndef PLB_PRECOMPILED // Unless precompiled version is used,
#include "palabos2D.hh" // include full template code
#endif
#include <vector>
#include <cmath>
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace plb;
using namespace std;
typedef double T;
#define DESCRIPTOR plb::descriptors::D2Q9Descriptor
#define PI 3.14159265
// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics2D.h"
using namespace plb_acoustics;
// ---------------------------------------------
T rho0 = 1.;
T deltaRho = 1.e-4;
T lattice_speed_sound = 1/sqrt(3);
class polar
{
public:
float r,th;
polar(){}
polar(int a,int b)
{
r=a;
th=b;
}
void show()
{
cout<<"In polar form:\nr="<<r<<" and theta="<<th;
}
};
class rectangular
{
public:
float x,y;
rectangular(){}
rectangular(polar p)
{
x=p.r*cos(p.th);
y=p.r*sin(p.th);
}
void show()
{
cout<<"\nIn Rectangular form:\nx="<<x<<"and y="<<y;
}
};
int main(int argc, char* argv[]) {
plbInit(&argc, &argv);
global::directories().setOutputDir("./tmp/");
plint numCores = global::mpi().getSize();
pcout << "Number of MPI threads: " << numCores << std::endl;
const plint maxIter = 40000; // 120000 Iterate during 1000 steps.
const plint nx = 1000; // Choice of lattice dimensions.
const plint ny = 670;
const T omega = 1.98; // Choice of the relaxation parameter
pcout << "Total iteration: " << maxIter << std::endl;
MultiBlockLattice2D<T, DESCRIPTOR> lattice(nx, ny, new CompleteBGKdynamics<T,DESCRIPTOR>(omega));
Array<T,2> u0((T)0,(T)0);
// Initialize constant density everywhere.
initializeAtEquilibrium(lattice, lattice.getBoundingBox(), rho0, u0);
lattice.initialize();
plint size_square = 2;
Box2D square(nx/2 - size_square/2, nx/2 + size_square/2,
ny/2 - size_square/2, ny/2 + size_square/2);
defineDynamics(lattice, square, new BounceBack<T,DESCRIPTOR>(rho0));
// Anechoic Condition
T size_anechoic_buffer = 30;
T rhoBar_target = 0;
Array<T,2> j_target(0.12/std::sqrt(3), 0.0/std::sqrt(3));
//left
plint orientation = 3;
Array<T,2> position_anechoic_wall((T)0,(T)0);
plint length_anechoic_wall = ny + 1;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall, length_anechoic_wall,
rhoBar_target, j_target);
//right
orientation = 1;
Array<T,2> position_anechoic_wall_2((T)nx - 30,(T)0);
length_anechoic_wall = ny + 1;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall_2, length_anechoic_wall,
rhoBar_target, j_target);
//top
orientation = 4;
Array<T,2> position_anechoic_wall_3((T) 0, (T)ny - 30);
length_anechoic_wall = nx + 1;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall_3, length_anechoic_wall,
rhoBar_target, u0);
//bottom
orientation = 2;
Array<T,2> position_anechoic_wall_1((T)0,(T)0);
length_anechoic_wall = nx + 1;
defineAnechoicWall(nx, ny, lattice, size_anechoic_buffer, orientation,
omega, position_anechoic_wall_1, length_anechoic_wall,
rhoBar_target, u0);
Box2D cima(0, nx, ny - 1, ny);
//defineDynamics(lattice, cima, new BounceBack<T,DESCRIPTOR>(rho0));
Box2D baixo(0, nx, 0, 1);
//defineDynamics(lattice, baixo, new BounceBack<T,DESCRIPTOR>(rho0));
// Main loop over time iterations.
plb_ofstream pressures_time_file("pressures_time.dat");
plb_ofstream velocities_file("velocities_50000.dat");
for (plint iT=0; iT<maxIter; ++iT) {
Box2D centralSquare (nx/2, nx/2, ny/2, ny/2);
//T rho_changing = 1. + deltaRho*sin(2*PI*(lattice_speed_sound/200)*iT);
if (iT != 0){
//initializeAtEquilibrium (lattice, centralSquare, rho_changing, u0);
}
if (iT%1000==0) { // Write an image every 40th time step.
pcout << "iT= " << iT << endl;
if (iT>=0){
ImageWriter<T> imageWriter("leeloo");
imageWriter.writeScaledGif(createFileName("velocity", iT, 6),
*computeVelocityNorm(lattice) );
imageWriter.writeGif(createFileName("density", iT, 6),
*computeDensity(lattice), (T) rho0 + -9e-06, (T) rho0 + 4e-05);
// Capturing pressures over time
T pressure = lattice_speed_sound*lattice_speed_sound*(lattice.get(nx/2, ny - 40).computeDensity() - rho0);
pressures_time_file << setprecision(10) << pressure << endl;
// Capturing pressures over space
plb_ofstream pressures_space_file("pressures_space.dat");
for (int i = 0; i < ny; i++){
T pressure = lattice_speed_sound*lattice_speed_sound*(lattice.get(nx/2, i).computeDensity() - rho0);
pressures_space_file << setprecision(10) << pressure << endl;
}
// Calculating directivity
/*plb_ofstream directivity_file("directivity.dat");
T theta;
pcout << "Start to calculate directivity .... " << endl;
for (T i = 0; i < 630; i++){
theta = i/100;
polar polar_obj(ny/2 - 40, theta);
rectangular rectangular_obj;
rectangular_obj = polar_obj;
plint position_x = nx/2 + (plint) rectangular_obj.x;
pcout << position_x << endl;
plint position_y = ny/2 + (plint) rectangular_obj.y;
pcout << position_y << endl;
T pressure = lattice_speed_sound*lattice_speed_sound*
(lattice.get(position_x, position_y).computeDensity() - rho0);
directivity_file << setprecision(10) << pressure << endl;
}
pcout << "Finish calculate directivity .... " << endl;*/
}
/*plb_ofstream matrix_pressure_file("matrix_pressure.dat");
if (iT == 30000){
matrix_pressure_file << setprecision(10) <<
}*/
/*ImageWriter<T> imageWriter("leeloo");
imageWriter.writeScaledGif(createFileName("u", iT, 6),
*computeVelocityNorm(lattice) );*/
// imageWriter.writeScaledGif(createFileName("u", iT, 6), *computeVorticity(*computeVelocity(lattice)));
//imageWriter.writeScaledGif(createFileName("u", iT, 6), *computeDensity(lattice));
//imageWriter.writeGif(createFileName("u", iT, 6), *computeDensity(lattice), (T) rho0 - deltaRho/1000, (T) rho0 + deltaRho/1000);
pcout << " energy ="
<< setprecision(10) << getStoredAverageEnergy<T>(lattice)
<< " rho ="
<< getStoredAverageDensity<T>(lattice)
<< " max_velocity ="
<< setprecision(10) << getStoredMaxVelocity<T>(lattice)
<< endl;
}
// Execute lattice Boltzmann iteration.
lattice.collideAndStream();
}
}
<|endoftext|> |
<commit_before>/* The libMesh Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* 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 */
// <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1>
//
// LibMesh provides interfaces to both Triangle and TetGen for generating
// Delaunay triangulations and tetrahedralizations in two and three dimensions
// (respectively).
// Local header files
#include "libmesh/elem.h"
#include "libmesh/face_tri3.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/mesh_tetgen_interface.h"
#include "libmesh/mesh_triangle_holes.h"
#include "libmesh/mesh_triangle_interface.h"
#include "libmesh/node.h"
#include "libmesh/serial_mesh.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// Major functions called by main
void triangulate_domain(const Parallel::Communicator& comm);
void tetrahedralize_domain(const Parallel::Communicator& comm);
// Helper routine for tetrahedralize_domain(). Adds the points and elements
// of a convex hull generated by TetGen to the input mesh
void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit);
// Begin the main program.
int main (int argc, char** argv)
{
// Initialize libMesh and any dependent libaries, like in example 2.
LibMeshInit init (argc, argv);
libmesh_example_assert(2 <= LIBMESH_DIM, "2D support");
std::cout << "Triangulating an L-shaped domain with holes" << std::endl;
// 1.) 2D triangulation of L-shaped domain with three holes of different shape
triangulate_domain(init.comm);
libmesh_example_assert(3 <= LIBMESH_DIM, "3D support");
std::cout << "Tetrahedralizing a prismatic domain with a hole" << std::endl;
// 2.) 3D tetrahedralization of rectangular domain with hole.
tetrahedralize_domain(init.comm);
return 0;
}
void triangulate_domain(const Parallel::Communicator& comm)
{
#ifdef LIBMESH_HAVE_TRIANGLE
// Use typedefs for slightly less typing.
typedef TriangleInterface::Hole Hole;
typedef TriangleInterface::PolygonHole PolygonHole;
typedef TriangleInterface::ArbitraryHole ArbitraryHole;
// Libmesh mesh that will eventually be created.
Mesh mesh(2, comm);
// The points which make up the L-shape:
mesh.add_point(Point( 0. , 0.));
mesh.add_point(Point( 0. , -1.));
mesh.add_point(Point(-1. , -1.));
mesh.add_point(Point(-1. , 1.));
mesh.add_point(Point( 1. , 1.));
mesh.add_point(Point( 1. , 0.));
// Declare the TriangleInterface object. This is where
// we can set parameters of the triangulation and where the
// actual triangulate function lives.
TriangleInterface t(mesh);
// Customize the variables for the triangulation
t.desired_area() = .01;
// A Planar Straight Line Graph (PSLG) is essentially a list
// of segments which have to exist in the final triangulation.
// For an L-shaped domain, Triangle will compute the convex
// hull of boundary points if we do not specify the PSLG.
// The PSLG algorithm is also required for triangulating domains
// containing holes
t.triangulation_type() = TriangleInterface::PSLG;
// Turn on/off Laplacian mesh smoothing after generation.
// By default this is on.
t.smooth_after_generating() = true;
// Define holes...
// hole_1 is a circle (discretized by 50 points)
PolygonHole hole_1(Point(-0.5, 0.5), // center
0.25, // radius
50); // n. points
// hole_2 is itself a triangle
PolygonHole hole_2(Point(0.5, 0.5), // center
0.1, // radius
3); // n. points
// hole_3 is an ellipse of 100 points which we define here
Point ellipse_center(-0.5, -0.5);
const unsigned int n_ellipse_points=100;
std::vector<Point> ellipse_points(n_ellipse_points);
const Real
dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points),
a = .1,
b = .2;
for (unsigned int i=0; i<n_ellipse_points; ++i)
ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta),
ellipse_center(1)+b*sin(i*dtheta));
ArbitraryHole hole_3(ellipse_center, ellipse_points);
// Create the vector of Hole*'s ...
std::vector<Hole*> holes;
holes.push_back(&hole_1);
holes.push_back(&hole_2);
holes.push_back(&hole_3);
// ... and attach it to the triangulator object
t.attach_hole_list(&holes);
// Triangulate!
t.triangulate();
// Write the result to file
mesh.write("delaunay_l_shaped_hole.e");
#endif // LIBMESH_HAVE_TRIANGLE
}
void tetrahedralize_domain(const Parallel::Communicator& comm)
{
#ifdef LIBMESH_HAVE_TETGEN
// The algorithm is broken up into several steps:
// 1.) A convex hull is constructed for a rectangular hole.
// 2.) A convex hull is constructed for the domain exterior.
// 3.) Neighbor information is updated so TetGen knows there is a convex hull
// 4.) A vector of hole points is created.
// 5.) The domain is tetrahedralized, the mesh is written out, etc.
// The mesh we will eventually generate
SerialMesh mesh(3,comm);
// Lower and Upper bounding box limits for a rectangular hole within the unit cube.
Point hole_lower_limit(0.2, 0.2, 0.4);
Point hole_upper_limit(0.8, 0.8, 0.6);
// 1.) Construct a convex hull for the hole
add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit);
// 2.) Generate elements comprising the outer boundary of the domain.
add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.));
// 3.) Update neighbor information so that TetGen can verify there is a convex hull.
mesh.find_neighbors();
// 4.) Set up vector of hole points
std::vector<Point> hole(1);
hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) );
// 5.) Set parameters and tetrahedralize the domain
// 0 means "use TetGen default value"
Real quality_constraint = 2.0;
// The volume constraint determines the max-allowed tetrahedral
// volume in the Mesh. TetGen will split cells which are larger than
// this size
Real volume_constraint = 0.001;
// Construct the Delaunay tetrahedralization
TetGenMeshInterface t(mesh);
t.triangulate_conformingDelaunayMesh_carvehole(hole,
quality_constraint,
volume_constraint);
// Find neighbors, etc in preparation for writing out the Mesh
mesh.prepare_for_use();
// Finally, write out the result
mesh.write("hole_3D.e");
#endif // LIBMESH_HAVE_TETGEN
}
void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit)
{
#ifdef LIBMESH_HAVE_TETGEN
SerialMesh cube_mesh(3);
unsigned n_elem = 1;
MeshTools::Generation::build_cube(cube_mesh,
n_elem,n_elem,n_elem, // n. elements in each direction
lower_limit(0), upper_limit(0),
lower_limit(1), upper_limit(1),
lower_limit(2), upper_limit(2),
HEX8);
// The pointset_convexhull() algorithm will ignore the Hex8s
// in the Mesh, and just construct the triangulation
// of the convex hull.
TetGenMeshInterface t(cube_mesh);
t.pointset_convexhull();
// Now add all nodes from the boundary of the cube_mesh to the input mesh.
// Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted
// with a dummy value, later to be assigned a value by the input mesh.
std::map<unsigned,unsigned> node_id_map;
typedef std::map<unsigned,unsigned>::iterator iterator;
{
MeshBase::element_iterator it = cube_mesh.elements_begin();
const MeshBase::element_iterator end = cube_mesh.elements_end();
for ( ; it != end; ++it)
{
Elem* elem = *it;
for (unsigned s=0; s<elem->n_sides(); ++s)
if (elem->neighbor(s) == NULL)
{
// Add the node IDs of this side to the set
AutoPtr<Elem> side = elem->side(s);
for (unsigned n=0; n<side->n_nodes(); ++n)
node_id_map.insert( std::make_pair(side->node(n), /*dummy_value=*/0) );
}
}
}
// For each node in the map, insert it into the input mesh and keep
// track of the ID assigned.
for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it)
{
// Id of the node in the cube mesh
unsigned id = (*it).first;
// Pointer to node in the cube mesh
Node* old_node = cube_mesh.node_ptr(id);
// Add geometric point to input mesh
Node* new_node = mesh.add_point ( *old_node );
// Track ID value of new_node in map
(*it).second = new_node->id();
}
// With the points added and the map data structure in place, we are
// ready to add each TRI3 element of the cube_mesh to the input Mesh
// with proper node assignments
{
MeshBase::element_iterator el = cube_mesh.elements_begin();
const MeshBase::element_iterator end_el = cube_mesh.elements_end();
for (; el != end_el; ++el)
{
Elem* old_elem = *el;
if (old_elem->type() == TRI3)
{
Elem* new_elem = mesh.add_elem(new Tri3);
// Assign nodes in new elements. Since this is an example,
// we'll do it in several steps.
for (unsigned i=0; i<old_elem->n_nodes(); ++i)
{
// Locate old node ID in the map
iterator it = node_id_map.find(old_elem->node(i));
// Check for not found
if (it == node_id_map.end())
{
libMesh::err << "Node id " << old_elem->node(i) << " not found in map!" << std::endl;
libmesh_error();
}
// Mapping to node ID in input mesh
unsigned new_node_id = (*it).second;
// Node pointer assigned from input mesh
new_elem->set_node(i) = mesh.node_ptr(new_node_id);
}
}
}
}
#endif // LIBMESH_HAVE_TETGEN
}
<commit_msg>Add communicator for miscellaneous_ex6 SerialMesh<commit_after>/* The libMesh Finite Element Library. */
/* Copyright (C) 2003 Benjamin S. Kirk */
/* 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 */
// <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces</h1>
//
// LibMesh provides interfaces to both Triangle and TetGen for generating
// Delaunay triangulations and tetrahedralizations in two and three dimensions
// (respectively).
// Local header files
#include "libmesh/elem.h"
#include "libmesh/face_tri3.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/mesh_tetgen_interface.h"
#include "libmesh/mesh_triangle_holes.h"
#include "libmesh/mesh_triangle_interface.h"
#include "libmesh/node.h"
#include "libmesh/serial_mesh.h"
// Bring in everything from the libMesh namespace
using namespace libMesh;
// Major functions called by main
void triangulate_domain(const Parallel::Communicator& comm);
void tetrahedralize_domain(const Parallel::Communicator& comm);
// Helper routine for tetrahedralize_domain(). Adds the points and elements
// of a convex hull generated by TetGen to the input mesh
void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit);
// Begin the main program.
int main (int argc, char** argv)
{
// Initialize libMesh and any dependent libaries, like in example 2.
LibMeshInit init (argc, argv);
libmesh_example_assert(2 <= LIBMESH_DIM, "2D support");
std::cout << "Triangulating an L-shaped domain with holes" << std::endl;
// 1.) 2D triangulation of L-shaped domain with three holes of different shape
triangulate_domain(init.comm);
libmesh_example_assert(3 <= LIBMESH_DIM, "3D support");
std::cout << "Tetrahedralizing a prismatic domain with a hole" << std::endl;
// 2.) 3D tetrahedralization of rectangular domain with hole.
tetrahedralize_domain(init.comm);
return 0;
}
void triangulate_domain(const Parallel::Communicator& comm)
{
#ifdef LIBMESH_HAVE_TRIANGLE
// Use typedefs for slightly less typing.
typedef TriangleInterface::Hole Hole;
typedef TriangleInterface::PolygonHole PolygonHole;
typedef TriangleInterface::ArbitraryHole ArbitraryHole;
// Libmesh mesh that will eventually be created.
Mesh mesh(2, comm);
// The points which make up the L-shape:
mesh.add_point(Point( 0. , 0.));
mesh.add_point(Point( 0. , -1.));
mesh.add_point(Point(-1. , -1.));
mesh.add_point(Point(-1. , 1.));
mesh.add_point(Point( 1. , 1.));
mesh.add_point(Point( 1. , 0.));
// Declare the TriangleInterface object. This is where
// we can set parameters of the triangulation and where the
// actual triangulate function lives.
TriangleInterface t(mesh);
// Customize the variables for the triangulation
t.desired_area() = .01;
// A Planar Straight Line Graph (PSLG) is essentially a list
// of segments which have to exist in the final triangulation.
// For an L-shaped domain, Triangle will compute the convex
// hull of boundary points if we do not specify the PSLG.
// The PSLG algorithm is also required for triangulating domains
// containing holes
t.triangulation_type() = TriangleInterface::PSLG;
// Turn on/off Laplacian mesh smoothing after generation.
// By default this is on.
t.smooth_after_generating() = true;
// Define holes...
// hole_1 is a circle (discretized by 50 points)
PolygonHole hole_1(Point(-0.5, 0.5), // center
0.25, // radius
50); // n. points
// hole_2 is itself a triangle
PolygonHole hole_2(Point(0.5, 0.5), // center
0.1, // radius
3); // n. points
// hole_3 is an ellipse of 100 points which we define here
Point ellipse_center(-0.5, -0.5);
const unsigned int n_ellipse_points=100;
std::vector<Point> ellipse_points(n_ellipse_points);
const Real
dtheta = 2*libMesh::pi / static_cast<Real>(n_ellipse_points),
a = .1,
b = .2;
for (unsigned int i=0; i<n_ellipse_points; ++i)
ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta),
ellipse_center(1)+b*sin(i*dtheta));
ArbitraryHole hole_3(ellipse_center, ellipse_points);
// Create the vector of Hole*'s ...
std::vector<Hole*> holes;
holes.push_back(&hole_1);
holes.push_back(&hole_2);
holes.push_back(&hole_3);
// ... and attach it to the triangulator object
t.attach_hole_list(&holes);
// Triangulate!
t.triangulate();
// Write the result to file
mesh.write("delaunay_l_shaped_hole.e");
#endif // LIBMESH_HAVE_TRIANGLE
}
void tetrahedralize_domain(const Parallel::Communicator& comm)
{
#ifdef LIBMESH_HAVE_TETGEN
// The algorithm is broken up into several steps:
// 1.) A convex hull is constructed for a rectangular hole.
// 2.) A convex hull is constructed for the domain exterior.
// 3.) Neighbor information is updated so TetGen knows there is a convex hull
// 4.) A vector of hole points is created.
// 5.) The domain is tetrahedralized, the mesh is written out, etc.
// The mesh we will eventually generate
SerialMesh mesh(3,comm);
// Lower and Upper bounding box limits for a rectangular hole within the unit cube.
Point hole_lower_limit(0.2, 0.2, 0.4);
Point hole_upper_limit(0.8, 0.8, 0.6);
// 1.) Construct a convex hull for the hole
add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit);
// 2.) Generate elements comprising the outer boundary of the domain.
add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.));
// 3.) Update neighbor information so that TetGen can verify there is a convex hull.
mesh.find_neighbors();
// 4.) Set up vector of hole points
std::vector<Point> hole(1);
hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) );
// 5.) Set parameters and tetrahedralize the domain
// 0 means "use TetGen default value"
Real quality_constraint = 2.0;
// The volume constraint determines the max-allowed tetrahedral
// volume in the Mesh. TetGen will split cells which are larger than
// this size
Real volume_constraint = 0.001;
// Construct the Delaunay tetrahedralization
TetGenMeshInterface t(mesh);
t.triangulate_conformingDelaunayMesh_carvehole(hole,
quality_constraint,
volume_constraint);
// Find neighbors, etc in preparation for writing out the Mesh
mesh.prepare_for_use();
// Finally, write out the result
mesh.write("hole_3D.e");
#endif // LIBMESH_HAVE_TETGEN
}
void add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit)
{
#ifdef LIBMESH_HAVE_TETGEN
SerialMesh cube_mesh(3,mesh.communicator());
unsigned n_elem = 1;
MeshTools::Generation::build_cube(cube_mesh,
n_elem,n_elem,n_elem, // n. elements in each direction
lower_limit(0), upper_limit(0),
lower_limit(1), upper_limit(1),
lower_limit(2), upper_limit(2),
HEX8);
// The pointset_convexhull() algorithm will ignore the Hex8s
// in the Mesh, and just construct the triangulation
// of the convex hull.
TetGenMeshInterface t(cube_mesh);
t.pointset_convexhull();
// Now add all nodes from the boundary of the cube_mesh to the input mesh.
// Map from "node id in cube_mesh" -> "node id in mesh". Initially inserted
// with a dummy value, later to be assigned a value by the input mesh.
std::map<unsigned,unsigned> node_id_map;
typedef std::map<unsigned,unsigned>::iterator iterator;
{
MeshBase::element_iterator it = cube_mesh.elements_begin();
const MeshBase::element_iterator end = cube_mesh.elements_end();
for ( ; it != end; ++it)
{
Elem* elem = *it;
for (unsigned s=0; s<elem->n_sides(); ++s)
if (elem->neighbor(s) == NULL)
{
// Add the node IDs of this side to the set
AutoPtr<Elem> side = elem->side(s);
for (unsigned n=0; n<side->n_nodes(); ++n)
node_id_map.insert( std::make_pair(side->node(n), /*dummy_value=*/0) );
}
}
}
// For each node in the map, insert it into the input mesh and keep
// track of the ID assigned.
for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it)
{
// Id of the node in the cube mesh
unsigned id = (*it).first;
// Pointer to node in the cube mesh
Node* old_node = cube_mesh.node_ptr(id);
// Add geometric point to input mesh
Node* new_node = mesh.add_point ( *old_node );
// Track ID value of new_node in map
(*it).second = new_node->id();
}
// With the points added and the map data structure in place, we are
// ready to add each TRI3 element of the cube_mesh to the input Mesh
// with proper node assignments
{
MeshBase::element_iterator el = cube_mesh.elements_begin();
const MeshBase::element_iterator end_el = cube_mesh.elements_end();
for (; el != end_el; ++el)
{
Elem* old_elem = *el;
if (old_elem->type() == TRI3)
{
Elem* new_elem = mesh.add_elem(new Tri3);
// Assign nodes in new elements. Since this is an example,
// we'll do it in several steps.
for (unsigned i=0; i<old_elem->n_nodes(); ++i)
{
// Locate old node ID in the map
iterator it = node_id_map.find(old_elem->node(i));
// Check for not found
if (it == node_id_map.end())
{
libMesh::err << "Node id " << old_elem->node(i) << " not found in map!" << std::endl;
libmesh_error();
}
// Mapping to node ID in input mesh
unsigned new_node_id = (*it).second;
// Node pointer assigned from input mesh
new_elem->set_node(i) = mesh.node_ptr(new_node_id);
}
}
}
}
#endif // LIBMESH_HAVE_TETGEN
}
<|endoftext|> |
<commit_before>#include <dlfcn.h>
#include <string.h>
#include <cstdio>
#include <cstdlib>
#include <sys/ioctl.h>
#include <unistd.h>
typedef ssize_t (*ReadSignature)(int, void*, size_t);
// TODO: per-process memory?
static char __line[1024];
static int __line_index = 0;
#define cursor_forward(x) printf("\033[%dC", (x))
#define cursor_backward(x) printf("\033[%dD", (x))
int open_history_file(FILE **f) {
char history[512], *home_dir = getenv("HOME");
strcpy(history, home_dir);
strcat(history, "/.bash_history");
if ((*f = fopen(history, "r")) == NULL) {
printf("No such file %s\n", history);
return -1;
}
return 0;
}
void complete_from_history(char *pattern, char *result) {
char *buffer = 0;
size_t len = 0;
FILE *f = 0;
open_history_file(&f);
while (getline(&buffer, &len, f) != -1) {
*strchr(buffer, '\n') = 0;
if (!strncmp(buffer, pattern, strlen(pattern))) {
strcpy(result, buffer + strlen(pattern));
break;
}
}
fclose(f);
}
void interactive_completion(unsigned char c) {
char buffer[2048];
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); // TODO:
switch (c) {
case 0xd: // newline
__line_index = 0;
memset(__line, 0, 1024);
memset(buffer, 0, 2048);
break;
case 0x7f: // backspace
if (__line_index > 0)
__line[--__line_index] = 0;
break;
default:
__line[__line_index++] = c;
__line[__line_index] = 0;
complete_from_history(__line, buffer);
if (strlen(buffer) > strlen(__line)) {
cursor_forward(1);
printf("\e[1;30m%s\e[0m", buffer);
cursor_backward((int)strlen(buffer) + 1);
fflush(stdout);
}
break;
}
}
ssize_t read(int fd, void *buf, size_t count) {
static ReadSignature real_read = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, "read"));
ssize_t ret = real_read(fd, buf, count);
if (0 == fd) {
interactive_completion(*(unsigned char *)buf);
}
return ret;
}
<commit_msg>added a little bit of STL<commit_after>#include <dlfcn.h>
#include <string.h>
#include <cstdio>
#include <cstdlib>
#include <sys/ioctl.h>
#include <unistd.h>
#include <array>
typedef ssize_t (*ReadSignature)(int, void*, size_t);
// TODO: per-process memory?
using LineBuffer = std::array<char, 1024>;
static LineBuffer line_buffer;
static auto line_buffer_pos = line_buffer.begin();
#define cursor_forward(x) printf("\033[%dC", (x))
#define cursor_backward(x) printf("\033[%dD", (x))
int open_history_file(FILE **f) {
char history[512], *home_dir = getenv("HOME");
strcpy(history, home_dir);
strcat(history, "/.bash_history");
if ((*f = fopen(history, "r")) == NULL) {
printf("No such file %s\n", history);
return -1;
}
return 0;
}
void complete_from_history(char *pattern, char *result) {
char *buffer = 0;
size_t len = 0;
FILE *f = 0;
open_history_file(&f);
while (getline(&buffer, &len, f) != -1) {
*strchr(buffer, '\n') = 0;
if (!strncmp(buffer, pattern, strlen(pattern))) {
strcpy(result, buffer + strlen(pattern));
break;
}
}
fclose(f);
}
void interactive_completion(unsigned char c) {
char buffer[2048];
struct winsize w;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); // TODO:
switch (c) {
case 0xd: // newline
line_buffer_pos = line_buffer.begin();
std::fill(std::begin(line_buffer), std::end(line_buffer), 0);
memset(buffer, 0, 2048);
break;
case 0x7f: // backspace
if (line_buffer_pos != line_buffer.begin()) {
*(--line_buffer_pos) = 0;
}
break;
default:
*(++line_buffer_pos) = c;
*(line_buffer_pos) = 0;
complete_from_history(line_buffer.data(), buffer);
if (strlen(buffer) > strlen(line_buffer.data())) {
cursor_forward(1);
printf("\e[1;30m%s\e[0m", buffer);
cursor_backward((int)strlen(buffer) + 1);
fflush(stdout);
}
break;
}
}
ssize_t read(int fd, void *buf, size_t count) {
static ReadSignature real_read = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, "read"));
ssize_t ret = real_read(fd, buf, count);
if (0 == fd) {
interactive_completion(*(unsigned char *)buf);
}
return ret;
}
<|endoftext|> |
<commit_before>#include <dlfcn.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <string>
#define cursor_forward(x) printf("\033[%dC", static_cast<int>(x))
#define cursor_backward(x) printf("\033[%dD", static_cast<int>(x))
typedef ssize_t (*ReadSignature)(int, void*, size_t);
thread_local ReadSignature realRead = NULL;
thread_local std::array<char, 1024> lineBuffer;
thread_local auto lineBufferPos = lineBuffer.begin();
thread_local std::vector<std::string> history;
static void readHistory() {
if (history.size()) return;
std::string historyFileName(getenv("HOME"));
historyFileName += "/.bash_history";
std::ifstream historyFile(historyFileName);
std::string line;
while (std::getline(historyFile, line))
history.push_back(line);
}
static void newlineHandler() {
}
static void backspaceHandler() {
if (lineBufferPos != lineBuffer.begin()) {
*(--lineBufferPos) = 0;
}
}
std::string findCompletion(const std::string &pattern) {
for (auto it = history.end() - 1; it > history.begin(); it--) {
if (it->compare(0, pattern.length(), pattern) == 0)
return *it;
}
return pattern;
}
void regularCharHandler(char c) {
*lineBufferPos = c;
lineBufferPos++;
std::string pattern(lineBuffer.data());
auto completion = findCompletion(pattern);
cursor_forward(1);
printf("\e[1;30m%s\e[0m", completion.c_str() + pattern.length());
cursor_backward(completion.length() - pattern.length() + 1);
fflush(stdout);
}
static void yebash(unsigned char c) {
// TODO: uncomment later
//if (!getenv("YEBASH")) {
// return;
//}
readHistory();
switch (c) {
case 0x0d: // newline
newlineHandler();
break;
case 0x7f: // backspace
backspaceHandler();
break;
default: // regular char
regularCharHandler(c);
break;
}
}
ssize_t read(int fd, void *buf, size_t count) {
ssize_t returnValue;
if (!realRead)
realRead = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, "read"));
returnValue = realRead(fd, buf, count);
if (fd == 0)
yebash(*reinterpret_cast<unsigned char *>(buf));
return returnValue;
}
<commit_msg>Add newline handling<commit_after>#include <dlfcn.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <string>
#define cursor_forward(x) printf("\033[%dC", static_cast<int>(x))
#define cursor_backward(x) printf("\033[%dD", static_cast<int>(x))
typedef ssize_t (*ReadSignature)(int, void*, size_t);
thread_local ReadSignature realRead = NULL;
thread_local std::array<char, 1024> lineBuffer;
thread_local auto lineBufferPos = lineBuffer.begin();
thread_local std::vector<std::string> history;
static void readHistory() {
if (history.size()) return;
std::string historyFileName(getenv("HOME"));
historyFileName += "/.bash_history";
std::ifstream historyFile(historyFileName);
std::string line;
while (std::getline(historyFile, line))
history.push_back(line);
}
static void newlineHandler() {
lineBuffer.fill(0);
lineBufferPos = lineBuffer.begin();
}
static void backspaceHandler() {
if (lineBufferPos != lineBuffer.begin()) {
*(--lineBufferPos) = 0;
}
}
std::string findCompletion(const std::string &pattern) {
for (auto it = history.end() - 1; it > history.begin(); it--) {
if (it->compare(0, pattern.length(), pattern) == 0)
return *it;
}
return pattern;
}
void regularCharHandler(char c) {
*lineBufferPos = c;
lineBufferPos++;
std::string pattern(lineBuffer.data());
auto completion = findCompletion(pattern);
cursor_forward(1);
printf("\e[1;30m%s\e[0m", completion.c_str() + pattern.length());
cursor_backward(completion.length() - pattern.length() + 1);
fflush(stdout);
}
static void yebash(unsigned char c) {
// TODO: uncomment later
//if (!getenv("YEBASH")) {
// return;
//}
readHistory();
switch (c) {
case 0x09: // tab
// TODO: seeking through history
break;
case 0x0d: // newline
newlineHandler();
break;
case 0x17: // ctrl+w
newlineHandler(); // TODO: this has to clear lineBuffer
break;
case 0x7f: // backspace
backspaceHandler();
break;
default: // regular char
regularCharHandler(c);
break;
}
}
ssize_t read(int fd, void *buf, size_t count) {
ssize_t returnValue;
if (!realRead)
realRead = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, "read"));
returnValue = realRead(fd, buf, count);
if (fd == 0)
yebash(*reinterpret_cast<unsigned char *>(buf));
return returnValue;
}
<|endoftext|> |
<commit_before>#include "../include/TamuraDistance.h"
using namespace cv;
using namespace std;
double TamuraDistance::calc(const ImageData &dat1, const ImageData &dat2) {
double F_crs1 = calc_granularity(dat1.rgb_img);
double F_crs2 = calc_granularity(dat2.rgb_img);
cout << "F_crs: " << Vec2d(F_crs1, F_crs2) << endl;
// TODO normalisierung
// TODO vermeide mehrfachberechnung fr 1
// TODO performance?
return fabs(F_crs1 - F_crs2);
}
string TamuraDistance::get_class_name() {
return "Tamura-Granularity-Distance";
}
double TamuraDistance::calc_granularity(Mat bgr_img){
//vector<Mat> A_k_list;
//vector<Mat> E_k_list;
Mat gray_img;
cvtColor(bgr_img, gray_img, CV_BGR2GRAY);
Mat S_best_k(bgr_img.size(), CV_32S);
Mat S_best_maxval(bgr_img.size(), CV_64F, Scalar(0));
for (int k = kmin; k <= kmax; k++) {
cout << "k " << k << endl;
Mat A_k(bgr_img.size(), CV_64F);
int k_pow = pow(2, k - 1);
for (int x = 0; x < bgr_img.rows; x++) {
for (int y = 0; y < bgr_img.cols; y++) {
double sum = 0;
for (int i = x - k_pow; i < x + k_pow; i++) {
for (int j = y - k_pow; j < y + k_pow; j++) {
// Out of range pixels are obtained by mirroring at the edge alt: BORDER_WRAP
sum += gray_img.at<uchar>(borderInterpolate(i, gray_img.rows, BORDER_REFLECT_101), borderInterpolate(j, gray_img.cols, BORDER_REFLECT_101));
}
}
A_k.at<double>(x, y) = sum / pow(2, 2 * k);
}
}
//A_k_list.push_back(A_k);
Mat E_k_h(bgr_img.size(), CV_64F), E_k_v(bgr_img.size(), CV_64F);
for (int x = 0; x < bgr_img.rows; x++) {
for (int y = 0; y < bgr_img.cols; y++) {
E_k_h.at<double>(x, y) = fabs(A_k.at<double>(borderInterpolate(x + k_pow, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y, A_k.cols, BORDER_REFLECT_101)) - A_k.at<double>(borderInterpolate(x - k_pow, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y, A_k.cols, BORDER_REFLECT_101)));
E_k_v.at<double>(x, y) = fabs(A_k.at<double>(borderInterpolate(x, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y + k_pow, A_k.cols, BORDER_REFLECT_101)) - A_k.at<double>(borderInterpolate(x, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y - k_pow, A_k.cols, BORDER_REFLECT_101)));
double maxval = max(E_k_h.at<double>(x, y), E_k_v.at<double>(x, y));
if (maxval > S_best_maxval.at<double>(x, y)) {
S_best_maxval.at<double>(x, y) = maxval;
S_best_k.at<int>(x, y) = pow(2, k);
}
}
}
//E_k_list.push_back(E_k_h);
//E_k_list.push_back(E_k_v);
}
//Mat F_crs;
//normalize(S_best_k, F_crs, )
/*
//Mat res;
//boxFilter(A_k_list[3], res, -1, Size(8, 8));
//cout << (res == A_k_list[3]) << endl;
Mat dst;
normalize(A_k_list.at(3), dst, 0, 1, cv::NORM_MINMAX);
imshow("test", dst);
waitKey(0);
//imshow("abc", A_k_list.front());
//waitKey(0);
return 8;
//*/
//cout << "S_best_k" << S_best_k << endl;
//double F_crs = cv::sum(S_best_k)[0] / S_best_k.total();
return mean(S_best_k)[0];
}
<commit_msg>replaced cumulating by boxcar filter<commit_after>#include "../include/TamuraDistance.h"
using namespace cv;
using namespace std;
double TamuraDistance::calc(const ImageData &dat1, const ImageData &dat2) {
double F_crs1 = calc_granularity(dat1.rgb_img);
double F_crs2 = calc_granularity(dat2.rgb_img);
cout << "F_crs: " << Vec2d(F_crs1, F_crs2) << endl;
// TODO normalisierung
// TODO vermeide mehrfachberechnung fr 1
// TODO performance?
return fabs(F_crs1 - F_crs2);
}
string TamuraDistance::get_class_name() {
return "Tamura-Granularity-Distance";
}
double TamuraDistance::calc_granularity(Mat bgr_img){
//vector<Mat> A_k_list;
//vector<Mat> E_k_list;
Mat gray_img;
cvtColor(bgr_img, gray_img, CV_BGR2GRAY);
Mat S_best_k(bgr_img.size(), CV_32S);
Mat S_best_maxval(bgr_img.size(), CV_64F, Scalar(0));
for (int k = kmin; k <= kmax; k++) {
cout << "k " << k << endl;
Mat A_k(bgr_img.size(), CV_64F);
int k_pow = pow(2, k - 1);
/*
for (int x = 0; x < bgr_img.rows; x++) {
for (int y = 0; y < bgr_img.cols; y++) {
double sum = 0;
for (int i = x - k_pow; i < x + k_pow; i++) {
for (int j = y - k_pow; j < y + k_pow; j++) {
// Out of range pixels are obtained by mirroring at the edge alt: BORDER_WRAP
sum += gray_img.at<uchar>(borderInterpolate(i, gray_img.rows, BORDER_REFLECT_101), borderInterpolate(j, gray_img.cols, BORDER_REFLECT_101));
}
}
A_k.at<double>(x, y) = sum / pow(2, 2 * k);
}
}
*/
boxFilter(gray_img, A_k, CV_64F, Size(2*k_pow,2*k_pow), Point(-1,-1), true, BORDER_REFLECT_101);
//A_k /= pow(2, 2 * k);
//A_k_list.push_back(A_k);
Mat E_k_h(bgr_img.size(), CV_64F), E_k_v(bgr_img.size(), CV_64F);
for (int x = 0; x < bgr_img.rows; x++) {
for (int y = 0; y < bgr_img.cols; y++) {
E_k_h.at<double>(x, y) = fabs(A_k.at<double>(borderInterpolate(x + k_pow, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y, A_k.cols, BORDER_REFLECT_101)) - A_k.at<double>(borderInterpolate(x - k_pow, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y, A_k.cols, BORDER_REFLECT_101)));
E_k_v.at<double>(x, y) = fabs(A_k.at<double>(borderInterpolate(x, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y + k_pow, A_k.cols, BORDER_REFLECT_101)) - A_k.at<double>(borderInterpolate(x, A_k.rows, BORDER_REFLECT_101), borderInterpolate(y - k_pow, A_k.cols, BORDER_REFLECT_101)));
double maxval = max(E_k_h.at<double>(x, y), E_k_v.at<double>(x, y));
if (maxval > S_best_maxval.at<double>(x, y)) {
S_best_maxval.at<double>(x, y) = maxval;
S_best_k.at<int>(x, y) = pow(2, k);
}
}
}
//E_k_list.push_back(E_k_h);
//E_k_list.push_back(E_k_v);
}
//Mat F_crs;
//normalize(S_best_k, F_crs, )
/*
//Mat res;
//boxFilter(A_k_list[3], res, -1, Size(8, 8));
//cout << (res == A_k_list[3]) << endl;
Mat dst;
normalize(A_k_list.at(3), dst, 0, 1, cv::NORM_MINMAX);
imshow("test", dst);
waitKey(0);
//imshow("abc", A_k_list.front());
//waitKey(0);
return 8;
//*/
//cout << "S_best_k" << S_best_k << endl;
//double F_crs = cv::sum(S_best_k)[0] / S_best_k.total();
return mean(S_best_k)[0];
}
<|endoftext|> |
<commit_before>#include "rapid_pbd/step_executor.h"
#include <sstream>
#include "boost/shared_ptr.hpp"
#include "moveit_msgs/MoveGroupAction.h"
#include "rapid_pbd_msgs/Action.h"
#include "rapid_pbd_msgs/Step.h"
#include "ros/ros.h"
#include "tf/transform_listener.h"
#include "rapid_pbd/action_executor.h"
#include "rapid_pbd/errors.h"
#include "rapid_pbd/motion_planning.h"
#include "rapid_pbd/visualizer.h"
#include "rapid_pbd/world.h"
using boost::shared_ptr;
using rapid_pbd_msgs::Action;
using rapid_pbd_msgs::Step;
namespace rapid {
namespace pbd {
StepExecutor::StepExecutor(const rapid_pbd_msgs::Step& step,
ActionClients* action_clients,
const RobotConfig& robot_config, World* world,
const RuntimeVisualizer& runtime_viz,
const tf::TransformListener& tf_listener,
const ros::Publisher& planning_scene_pub)
: step_(step),
action_clients_(action_clients),
robot_config_(robot_config),
world_(world),
runtime_viz_(runtime_viz),
motion_planning_(robot_config, world, tf_listener, planning_scene_pub),
executors_() {}
bool StepExecutor::IsValid(const rapid_pbd_msgs::Step& step) {
for (size_t i = 0; i < step.actions.size(); ++i) {
const Action& action = step.actions[i];
if (!ActionExecutor::IsValid(action)) {
ROS_ERROR("Action type %s invalid in action %ld", action.type.c_str(), i);
return false;
}
}
return true;
}
void StepExecutor::Init() {
for (size_t i = 0; i < step_.actions.size(); ++i) {
Action action = step_.actions[i];
shared_ptr<ActionExecutor> ae(
new ActionExecutor(action, action_clients_, &motion_planning_, world_,
robot_config_, runtime_viz_));
executors_.push_back(ae);
}
}
std::string StepExecutor::Start() {
motion_planning_.ClearGoals();
std::string error("");
for (size_t i = 0; i < step_.actions.size(); ++i) {
error = executors_[i]->Start();
if (error != "") {
return error;
}
}
if (motion_planning_.num_goals() > 0) {
moveit_msgs::MoveGroupGoal goal;
motion_planning_.BuildGoal(&goal);
action_clients_->moveit_client.sendGoal(goal);
}
return "";
}
bool StepExecutor::IsDone(std::string* error) const {
for (size_t i = 0; i < executors_.size(); ++i) {
const shared_ptr<ActionExecutor>& executor = executors_[i];
if (!executor->IsDone(error)) {
return false;
}
if (*error != "") {
return true;
}
}
if (motion_planning_.num_goals() > 0) {
if (!action_clients_->moveit_client.getState().isDone()) {
return false;
}
moveit_msgs::MoveGroupResultConstPtr result =
action_clients_->moveit_client.getResult();
if (!result) {
*error = "MoveIt returned null result.";
}
if (result->error_code.val != moveit_msgs::MoveItErrorCodes::SUCCESS) {
std::stringstream ss;
ss << errors::kUnreachablePose
<< " MoveIt error code: " << ErrorCodeToString(result->error_code);
*error = ss.str();
}
// Insert a delay at the end to avoid "start state out of bounds" errors for
// subsequent motion plans.
ros::Duration(1).sleep();
}
return true;
}
void StepExecutor::Cancel() {
for (size_t i = 0; i < executors_.size(); ++i) {
const shared_ptr<ActionExecutor>& executor = executors_[i];
executor->Cancel();
}
if (motion_planning_.num_goals() > 0) {
action_clients_->moveit_client.cancelAllGoals();
motion_planning_.ClearGoals();
}
executors_.clear();
}
} // namespace pbd
} // namespace rapid
<commit_msg>Shorten delay.<commit_after>#include "rapid_pbd/step_executor.h"
#include <sstream>
#include "boost/shared_ptr.hpp"
#include "moveit_msgs/MoveGroupAction.h"
#include "rapid_pbd_msgs/Action.h"
#include "rapid_pbd_msgs/Step.h"
#include "ros/ros.h"
#include "tf/transform_listener.h"
#include "rapid_pbd/action_executor.h"
#include "rapid_pbd/errors.h"
#include "rapid_pbd/motion_planning.h"
#include "rapid_pbd/visualizer.h"
#include "rapid_pbd/world.h"
using boost::shared_ptr;
using rapid_pbd_msgs::Action;
using rapid_pbd_msgs::Step;
namespace rapid {
namespace pbd {
StepExecutor::StepExecutor(const rapid_pbd_msgs::Step& step,
ActionClients* action_clients,
const RobotConfig& robot_config, World* world,
const RuntimeVisualizer& runtime_viz,
const tf::TransformListener& tf_listener,
const ros::Publisher& planning_scene_pub)
: step_(step),
action_clients_(action_clients),
robot_config_(robot_config),
world_(world),
runtime_viz_(runtime_viz),
motion_planning_(robot_config, world, tf_listener, planning_scene_pub),
executors_() {}
bool StepExecutor::IsValid(const rapid_pbd_msgs::Step& step) {
for (size_t i = 0; i < step.actions.size(); ++i) {
const Action& action = step.actions[i];
if (!ActionExecutor::IsValid(action)) {
ROS_ERROR("Action type %s invalid in action %ld", action.type.c_str(), i);
return false;
}
}
return true;
}
void StepExecutor::Init() {
for (size_t i = 0; i < step_.actions.size(); ++i) {
Action action = step_.actions[i];
shared_ptr<ActionExecutor> ae(
new ActionExecutor(action, action_clients_, &motion_planning_, world_,
robot_config_, runtime_viz_));
executors_.push_back(ae);
}
}
std::string StepExecutor::Start() {
motion_planning_.ClearGoals();
std::string error("");
for (size_t i = 0; i < step_.actions.size(); ++i) {
error = executors_[i]->Start();
if (error != "") {
return error;
}
}
if (motion_planning_.num_goals() > 0) {
moveit_msgs::MoveGroupGoal goal;
motion_planning_.BuildGoal(&goal);
action_clients_->moveit_client.sendGoal(goal);
}
return "";
}
bool StepExecutor::IsDone(std::string* error) const {
for (size_t i = 0; i < executors_.size(); ++i) {
const shared_ptr<ActionExecutor>& executor = executors_[i];
if (!executor->IsDone(error)) {
return false;
}
if (*error != "") {
return true;
}
}
if (motion_planning_.num_goals() > 0) {
if (!action_clients_->moveit_client.getState().isDone()) {
return false;
}
moveit_msgs::MoveGroupResultConstPtr result =
action_clients_->moveit_client.getResult();
if (!result) {
*error = "MoveIt returned null result.";
}
if (result->error_code.val != moveit_msgs::MoveItErrorCodes::SUCCESS) {
std::stringstream ss;
ss << errors::kUnreachablePose
<< " MoveIt error code: " << ErrorCodeToString(result->error_code);
*error = ss.str();
}
// Insert a delay at the end to avoid "start state out of bounds" errors for
// subsequent motion plans.
ros::Duration(0.1).sleep();
}
return true;
}
void StepExecutor::Cancel() {
for (size_t i = 0; i < executors_.size(); ++i) {
const shared_ptr<ActionExecutor>& executor = executors_[i];
executor->Cancel();
}
if (motion_planning_.num_goals() > 0) {
action_clients_->moveit_client.cancelAllGoals();
motion_planning_.ClearGoals();
}
executors_.clear();
}
} // namespace pbd
} // namespace rapid
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <seastar/core/seastar.hh>
#include <seastar/core/print.hh>
#include "reader_concurrency_semaphore.hh"
#include "utils/exceptions.hh"
reader_permit::resource_units::resource_units(reader_concurrency_semaphore& semaphore, reader_resources res) noexcept
: _semaphore(&semaphore), _resources(res) {
}
reader_permit::resource_units::resource_units(resource_units&& o) noexcept
: _semaphore(o._semaphore)
, _resources(std::exchange(o._resources, {})) {
}
reader_permit::resource_units::~resource_units() {
reset();
}
reader_permit::resource_units& reader_permit::resource_units::operator=(resource_units&& o) noexcept {
if (&o == this) {
return *this;
}
reset();
_semaphore = o._semaphore;
_resources = std::exchange(o._resources, {});
return *this;
}
void reader_permit::resource_units::add(resource_units&& o) {
assert(_semaphore == o._semaphore);
_resources += std::exchange(o._resources, {});
}
void reader_permit::resource_units::reset(reader_resources res) {
_semaphore->consume(res);
if (_resources) {
_semaphore->signal(_resources);
}
_resources = res;
}
reader_permit::reader_permit(reader_concurrency_semaphore& semaphore)
: _semaphore(&semaphore) {
}
future<reader_permit::resource_units> reader_permit::wait_admission(size_t memory, db::timeout_clock::time_point timeout) {
return _semaphore->do_wait_admission(memory, timeout);
}
reader_permit::resource_units reader_permit::consume_memory(size_t memory) {
return consume_resources(reader_resources{0, ssize_t(memory)});
}
reader_permit::resource_units reader_permit::consume_resources(reader_resources res) {
_semaphore->consume(res);
return resource_units(*_semaphore, res);
}
void reader_concurrency_semaphore::signal(const resources& r) noexcept {
_resources += r;
while (!_wait_list.empty() && has_available_units(_wait_list.front().res)) {
auto& x = _wait_list.front();
_resources -= x.res;
try {
x.pr.set_value(reader_permit::resource_units(*this, x.res));
} catch (...) {
x.pr.set_exception(std::current_exception());
}
_wait_list.pop_front();
}
}
reader_concurrency_semaphore::~reader_concurrency_semaphore() {
broken(std::make_exception_ptr(broken_semaphore{}));
}
reader_concurrency_semaphore::inactive_read_handle reader_concurrency_semaphore::register_inactive_read(std::unique_ptr<inactive_read> ir) {
// Implies _inactive_reads.empty(), we don't queue new readers before
// evicting all inactive reads.
if (_wait_list.empty()) {
const auto [it, _] = _inactive_reads.emplace(_next_id++, std::move(ir));
(void)_;
++_inactive_read_stats.population;
return inactive_read_handle(*this, it->first);
}
// The evicted reader will release its permit, hopefully allowing us to
// admit some readers from the _wait_list.
ir->evict();
++_inactive_read_stats.permit_based_evictions;
return inactive_read_handle();
}
std::unique_ptr<reader_concurrency_semaphore::inactive_read> reader_concurrency_semaphore::unregister_inactive_read(inactive_read_handle irh) {
if (irh && irh._sem != this) {
throw std::runtime_error(fmt::format(
"reader_concurrency_semaphore::unregister_inactive_read(): "
"attempted to unregister an inactive read with a handle belonging to another semaphore: "
"this is {} (0x{:x}) but the handle belongs to {} (0x{:x})",
name(),
reinterpret_cast<uintptr_t>(this),
irh._sem->name(),
reinterpret_cast<uintptr_t>(irh._sem)));
}
if (auto it = _inactive_reads.find(irh._id); it != _inactive_reads.end()) {
auto ir = std::move(it->second);
_inactive_reads.erase(it);
--_inactive_read_stats.population;
return ir;
}
return {};
}
bool reader_concurrency_semaphore::try_evict_one_inactive_read() {
if (_inactive_reads.empty()) {
return false;
}
auto it = _inactive_reads.begin();
it->second->evict();
_inactive_reads.erase(it);
++_inactive_read_stats.permit_based_evictions;
--_inactive_read_stats.population;
return true;
}
future<reader_permit::resource_units> reader_concurrency_semaphore::do_wait_admission(size_t memory, db::timeout_clock::time_point timeout) {
if (_wait_list.size() >= _max_queue_length) {
if (_prethrow_action) {
_prethrow_action();
}
return make_exception_future<reader_permit::resource_units>(
std::make_exception_ptr(std::runtime_error(
format("{}: restricted mutation reader queue overload", _name))));
}
auto r = resources(1, static_cast<ssize_t>(memory));
auto it = _inactive_reads.begin();
while (!may_proceed(r) && it != _inactive_reads.end()) {
auto ir = std::move(it->second);
it = _inactive_reads.erase(it);
ir->evict();
++_inactive_read_stats.permit_based_evictions;
--_inactive_read_stats.population;
}
if (may_proceed(r)) {
_resources -= r;
return make_ready_future<reader_permit::resource_units>(reader_permit::resource_units(*this, r));
}
promise<reader_permit::resource_units> pr;
auto fut = pr.get_future();
_wait_list.push_back(entry(std::move(pr), r), timeout);
return fut;
}
reader_permit reader_concurrency_semaphore::make_permit() {
return reader_permit(*this);
}
void reader_concurrency_semaphore::broken(std::exception_ptr ex) {
while (!_wait_list.empty()) {
_wait_list.front().pr.set_exception(std::make_exception_ptr(broken_semaphore{}));
_wait_list.pop_front();
}
}
// A file that tracks the memory usage of buffers resulting from read
// operations.
class tracking_file_impl : public file_impl {
file _tracked_file;
reader_permit _permit;
public:
tracking_file_impl(file file, reader_permit permit)
: _tracked_file(std::move(file))
, _permit(std::move(permit)) {
_memory_dma_alignment = _tracked_file.memory_dma_alignment();
_disk_read_dma_alignment = _tracked_file.disk_read_dma_alignment();
_disk_write_dma_alignment = _tracked_file.disk_write_dma_alignment();
}
tracking_file_impl(const tracking_file_impl&) = delete;
tracking_file_impl& operator=(const tracking_file_impl&) = delete;
tracking_file_impl(tracking_file_impl&&) = default;
tracking_file_impl& operator=(tracking_file_impl&&) = default;
virtual future<size_t> write_dma(uint64_t pos, const void* buffer, size_t len, const io_priority_class& pc) override {
return get_file_impl(_tracked_file)->write_dma(pos, buffer, len, pc);
}
virtual future<size_t> write_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) override {
return get_file_impl(_tracked_file)->write_dma(pos, std::move(iov), pc);
}
virtual future<size_t> read_dma(uint64_t pos, void* buffer, size_t len, const io_priority_class& pc) override {
return get_file_impl(_tracked_file)->read_dma(pos, buffer, len, pc);
}
virtual future<size_t> read_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) override {
return get_file_impl(_tracked_file)->read_dma(pos, iov, pc);
}
virtual future<> flush(void) override {
return get_file_impl(_tracked_file)->flush();
}
virtual future<struct stat> stat(void) override {
return get_file_impl(_tracked_file)->stat();
}
virtual future<> truncate(uint64_t length) override {
return get_file_impl(_tracked_file)->truncate(length);
}
virtual future<> discard(uint64_t offset, uint64_t length) override {
return get_file_impl(_tracked_file)->discard(offset, length);
}
virtual future<> allocate(uint64_t position, uint64_t length) override {
return get_file_impl(_tracked_file)->allocate(position, length);
}
virtual future<uint64_t> size(void) override {
return get_file_impl(_tracked_file)->size();
}
virtual future<> close() override {
return get_file_impl(_tracked_file)->close();
}
virtual std::unique_ptr<file_handle_impl> dup() override {
return get_file_impl(_tracked_file)->dup();
}
virtual subscription<directory_entry> list_directory(std::function<future<> (directory_entry de)> next) override {
return get_file_impl(_tracked_file)->list_directory(std::move(next));
}
virtual future<temporary_buffer<uint8_t>> dma_read_bulk(uint64_t offset, size_t range_size, const io_priority_class& pc) override {
return get_file_impl(_tracked_file)->dma_read_bulk(offset, range_size, pc).then([this, units = _permit.consume_memory(range_size)] (temporary_buffer<uint8_t> buf) {
return make_ready_future<temporary_buffer<uint8_t>>(make_tracked_temporary_buffer(std::move(buf), _permit));
});
}
};
file make_tracked_file(file f, reader_permit p) {
return file(make_shared<tracking_file_impl>(f, std::move(p)));
}
<commit_msg>reader_permit: reader_resources: make true RAII class<commit_after>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <seastar/core/seastar.hh>
#include <seastar/core/print.hh>
#include "reader_concurrency_semaphore.hh"
#include "utils/exceptions.hh"
reader_permit::resource_units::resource_units(reader_concurrency_semaphore& semaphore, reader_resources res) noexcept
: _semaphore(&semaphore), _resources(res) {
_semaphore->consume(res);
}
reader_permit::resource_units::resource_units(resource_units&& o) noexcept
: _semaphore(o._semaphore)
, _resources(std::exchange(o._resources, {})) {
}
reader_permit::resource_units::~resource_units() {
reset();
}
reader_permit::resource_units& reader_permit::resource_units::operator=(resource_units&& o) noexcept {
if (&o == this) {
return *this;
}
reset();
_semaphore = o._semaphore;
_resources = std::exchange(o._resources, {});
return *this;
}
void reader_permit::resource_units::add(resource_units&& o) {
assert(_semaphore == o._semaphore);
_resources += std::exchange(o._resources, {});
}
void reader_permit::resource_units::reset(reader_resources res) {
_semaphore->consume(res);
if (_resources) {
_semaphore->signal(_resources);
}
_resources = res;
}
reader_permit::reader_permit(reader_concurrency_semaphore& semaphore)
: _semaphore(&semaphore) {
}
future<reader_permit::resource_units> reader_permit::wait_admission(size_t memory, db::timeout_clock::time_point timeout) {
return _semaphore->do_wait_admission(memory, timeout);
}
reader_permit::resource_units reader_permit::consume_memory(size_t memory) {
return consume_resources(reader_resources{0, ssize_t(memory)});
}
reader_permit::resource_units reader_permit::consume_resources(reader_resources res) {
return resource_units(*_semaphore, res);
}
void reader_concurrency_semaphore::signal(const resources& r) noexcept {
_resources += r;
while (!_wait_list.empty() && has_available_units(_wait_list.front().res)) {
auto& x = _wait_list.front();
try {
x.pr.set_value(reader_permit::resource_units(*this, x.res));
} catch (...) {
x.pr.set_exception(std::current_exception());
}
_wait_list.pop_front();
}
}
reader_concurrency_semaphore::~reader_concurrency_semaphore() {
broken(std::make_exception_ptr(broken_semaphore{}));
}
reader_concurrency_semaphore::inactive_read_handle reader_concurrency_semaphore::register_inactive_read(std::unique_ptr<inactive_read> ir) {
// Implies _inactive_reads.empty(), we don't queue new readers before
// evicting all inactive reads.
if (_wait_list.empty()) {
const auto [it, _] = _inactive_reads.emplace(_next_id++, std::move(ir));
(void)_;
++_inactive_read_stats.population;
return inactive_read_handle(*this, it->first);
}
// The evicted reader will release its permit, hopefully allowing us to
// admit some readers from the _wait_list.
ir->evict();
++_inactive_read_stats.permit_based_evictions;
return inactive_read_handle();
}
std::unique_ptr<reader_concurrency_semaphore::inactive_read> reader_concurrency_semaphore::unregister_inactive_read(inactive_read_handle irh) {
if (irh && irh._sem != this) {
throw std::runtime_error(fmt::format(
"reader_concurrency_semaphore::unregister_inactive_read(): "
"attempted to unregister an inactive read with a handle belonging to another semaphore: "
"this is {} (0x{:x}) but the handle belongs to {} (0x{:x})",
name(),
reinterpret_cast<uintptr_t>(this),
irh._sem->name(),
reinterpret_cast<uintptr_t>(irh._sem)));
}
if (auto it = _inactive_reads.find(irh._id); it != _inactive_reads.end()) {
auto ir = std::move(it->second);
_inactive_reads.erase(it);
--_inactive_read_stats.population;
return ir;
}
return {};
}
bool reader_concurrency_semaphore::try_evict_one_inactive_read() {
if (_inactive_reads.empty()) {
return false;
}
auto it = _inactive_reads.begin();
it->second->evict();
_inactive_reads.erase(it);
++_inactive_read_stats.permit_based_evictions;
--_inactive_read_stats.population;
return true;
}
future<reader_permit::resource_units> reader_concurrency_semaphore::do_wait_admission(size_t memory, db::timeout_clock::time_point timeout) {
if (_wait_list.size() >= _max_queue_length) {
if (_prethrow_action) {
_prethrow_action();
}
return make_exception_future<reader_permit::resource_units>(
std::make_exception_ptr(std::runtime_error(
format("{}: restricted mutation reader queue overload", _name))));
}
auto r = resources(1, static_cast<ssize_t>(memory));
auto it = _inactive_reads.begin();
while (!may_proceed(r) && it != _inactive_reads.end()) {
auto ir = std::move(it->second);
it = _inactive_reads.erase(it);
ir->evict();
++_inactive_read_stats.permit_based_evictions;
--_inactive_read_stats.population;
}
if (may_proceed(r)) {
return make_ready_future<reader_permit::resource_units>(reader_permit::resource_units(*this, r));
}
promise<reader_permit::resource_units> pr;
auto fut = pr.get_future();
_wait_list.push_back(entry(std::move(pr), r), timeout);
return fut;
}
reader_permit reader_concurrency_semaphore::make_permit() {
return reader_permit(*this);
}
void reader_concurrency_semaphore::broken(std::exception_ptr ex) {
while (!_wait_list.empty()) {
_wait_list.front().pr.set_exception(std::make_exception_ptr(broken_semaphore{}));
_wait_list.pop_front();
}
}
// A file that tracks the memory usage of buffers resulting from read
// operations.
class tracking_file_impl : public file_impl {
file _tracked_file;
reader_permit _permit;
public:
tracking_file_impl(file file, reader_permit permit)
: _tracked_file(std::move(file))
, _permit(std::move(permit)) {
_memory_dma_alignment = _tracked_file.memory_dma_alignment();
_disk_read_dma_alignment = _tracked_file.disk_read_dma_alignment();
_disk_write_dma_alignment = _tracked_file.disk_write_dma_alignment();
}
tracking_file_impl(const tracking_file_impl&) = delete;
tracking_file_impl& operator=(const tracking_file_impl&) = delete;
tracking_file_impl(tracking_file_impl&&) = default;
tracking_file_impl& operator=(tracking_file_impl&&) = default;
virtual future<size_t> write_dma(uint64_t pos, const void* buffer, size_t len, const io_priority_class& pc) override {
return get_file_impl(_tracked_file)->write_dma(pos, buffer, len, pc);
}
virtual future<size_t> write_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) override {
return get_file_impl(_tracked_file)->write_dma(pos, std::move(iov), pc);
}
virtual future<size_t> read_dma(uint64_t pos, void* buffer, size_t len, const io_priority_class& pc) override {
return get_file_impl(_tracked_file)->read_dma(pos, buffer, len, pc);
}
virtual future<size_t> read_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) override {
return get_file_impl(_tracked_file)->read_dma(pos, iov, pc);
}
virtual future<> flush(void) override {
return get_file_impl(_tracked_file)->flush();
}
virtual future<struct stat> stat(void) override {
return get_file_impl(_tracked_file)->stat();
}
virtual future<> truncate(uint64_t length) override {
return get_file_impl(_tracked_file)->truncate(length);
}
virtual future<> discard(uint64_t offset, uint64_t length) override {
return get_file_impl(_tracked_file)->discard(offset, length);
}
virtual future<> allocate(uint64_t position, uint64_t length) override {
return get_file_impl(_tracked_file)->allocate(position, length);
}
virtual future<uint64_t> size(void) override {
return get_file_impl(_tracked_file)->size();
}
virtual future<> close() override {
return get_file_impl(_tracked_file)->close();
}
virtual std::unique_ptr<file_handle_impl> dup() override {
return get_file_impl(_tracked_file)->dup();
}
virtual subscription<directory_entry> list_directory(std::function<future<> (directory_entry de)> next) override {
return get_file_impl(_tracked_file)->list_directory(std::move(next));
}
virtual future<temporary_buffer<uint8_t>> dma_read_bulk(uint64_t offset, size_t range_size, const io_priority_class& pc) override {
return get_file_impl(_tracked_file)->dma_read_bulk(offset, range_size, pc).then([this, units = _permit.consume_memory(range_size)] (temporary_buffer<uint8_t> buf) {
return make_ready_future<temporary_buffer<uint8_t>>(make_tracked_temporary_buffer(std::move(buf), _permit));
});
}
};
file make_tracked_file(file f, reader_permit p) {
return file(make_shared<tracking_file_impl>(f, std::move(p)));
}
<|endoftext|> |
<commit_before>/*
* TextFileParser.cpp
*
* Created on: 24.01.2015
* Author: sartz
*/
#include "TextFileParser.hpp"
#include <fstream>
#include <sstream>
#include <iostream>
#include "CoinItem.hpp"
#include "TimeItem.hpp"
#include "TriggerItem.hpp"
#include "KeyItem.hpp"
#include "ItemFactory.hpp"
#include "globals.hpp"
#include "TextureManager.hpp"
#include "Tile.hpp"
TextFileParser::TextFileParser() {
// TODO Auto-generated constructor stub
}
TextFileParser::~TextFileParser() {
// TODO Auto-generated destructor stub
}
void TextFileParser::loadTextFile(Scene &scene, std::string fileName)
{
std::ifstream infile(fileName);
// infile.open(fileName.c_str());
std::string line;
// sf::Texture *itemsTexture;
// itemsTexture->loadFromFile(std::string(PATH) + "img/items.png");
sf::Sprite *itemSprite = new sf::Sprite();
itemSprite->setTexture(textureManager.itemsTexture);
ItemFactory tmpFactory = ItemFactory();
while (std::getline(infile, line))
{
std::istringstream iss(line);
std::string first;
iss >> first;
if (first == "Start")
{
int x,y;
iss >> x;
iss >> y;
scene.startPos.x = x*Tile::pixelSizeX*Scene::tileScaleFactor;
scene.startPos.y = y*Tile::pixelSizeY*Scene::tileScaleFactor;
}
if (first == "Portal")
{
int x,y;
iss >> x;
iss >> y;
scene.portalPos.x = x*Tile::pixelSizeX*Scene::tileScaleFactor;
scene.portalPos.y = y*Tile::pixelSizeY*Scene::tileScaleFactor;
Item *tmpItem = tmpFactory.getItem("PortalItem");
tmpItem->setPosition(x, y);
scene.items.push_back(*tmpItem);
}
if (first == "Item")
{
std::string second;
iss >> second;
int x,y;
iss >> x;
iss >> y;
Item *tmpItem = tmpFactory.getItem(second);
tmpItem->setPosition(x*Tile::pixelSizeX*Scene::tileScaleFactor, y*Tile::pixelSizeY*Scene::tileScaleFactor);
scene.items.push_back(*tmpItem);
}
if (first == "TriggerItem")
{
int x1, x2, y1, y2;
iss >> x1;
iss >> y1;
iss >> x2;
iss >> y2;
TriggerItem *tmpItem = (TriggerItem*) tmpFactory.getItem("TriggerItem");
tmpItem->setSwitchPos(x1*Tile::pixelSizeX*Scene::tileScaleFactor, y1*Tile::pixelSizeY*Scene::tileScaleFactor, x2*Tile::pixelSizeX*Scene::tileScaleFactor, y2*Tile::pixelSizeY*Scene::tileScaleFactor);
scene.items.push_back(*tmpItem);
}
}
}
<commit_msg>Fix des letzten fehlerhaften Commits (durch Mergen)<commit_after>/*
* TextFileParser.cpp
*
* Created on: 24.01.2015
* Author: sartz
*/
#include "TextFileParser.hpp"
#include <fstream>
#include <sstream>
#include <iostream>
#include "CoinItem.hpp"
#include "TimeItem.hpp"
#include "TriggerItem.hpp"
#include "KeyItem.hpp"
#include "ItemFactory.hpp"
#include "globals.hpp"
#include "TextureManager.hpp"
#include "Tile.hpp"
TextFileParser::TextFileParser() {
// TODO Auto-generated constructor stub
}
TextFileParser::~TextFileParser() {
// TODO Auto-generated destructor stub
}
void TextFileParser::loadTextFile(Scene &scene, std::string fileName)
{
std::ifstream infile(fileName);
// infile.open(fileName.c_str());
std::string line;
// sf::Texture *itemsTexture;
// itemsTexture->loadFromFile(std::string(PATH) + "img/items.png");
sf::Sprite *itemSprite = new sf::Sprite();
itemSprite->setTexture(textureManager.itemsTexture);
ItemFactory tmpFactory = ItemFactory();
while (std::getline(infile, line))
{
std::istringstream iss(line);
std::string first;
iss >> first;
if (first == "Start")
{
int x,y;
iss >> x;
iss >> y;
scene.startPos.x = x*Tile::pixelSizeX*Scene::tileScaleFactor;
scene.startPos.y = y*Tile::pixelSizeY*Scene::tileScaleFactor;
}
if (first == "Portal")
{
int x,y;
iss >> x;
iss >> y;
scene.portalPos.x = x*Tile::pixelSizeX*Scene::tileScaleFactor;
scene.portalPos.y = y*Tile::pixelSizeY*Scene::tileScaleFactor;
Item *tmpItem = tmpFactory.getItem("PortalItem");
tmpItem->setPosition(x, y);
scene.items.push_back(tmpItem);
}
if (first == "Item")
{
std::string second;
iss >> second;
int x,y;
iss >> x;
iss >> y;
Item *tmpItem = tmpFactory.getItem(second);
tmpItem->setPosition(x*Tile::pixelSizeX*Scene::tileScaleFactor, y*Tile::pixelSizeY*Scene::tileScaleFactor);
scene.items.push_back(tmpItem);
}
if (first == "TriggerItem")
{
int x1, x2, y1, y2;
iss >> x1;
iss >> y1;
iss >> x2;
iss >> y2;
TriggerItem *tmpItem = (TriggerItem*) tmpFactory.getItem("TriggerItem");
tmpItem->setSwitchPos(x1*Tile::pixelSizeX*Scene::tileScaleFactor, y1*Tile::pixelSizeY*Scene::tileScaleFactor, x2*Tile::pixelSizeX*Scene::tileScaleFactor, y2*Tile::pixelSizeY*Scene::tileScaleFactor);
scene.items.push_back(tmpItem);
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2000-2008, François Revol, <[email protected]>. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#include "ThemeAddonItem.h"
#include "ThemeInterfaceView.h"
#include "ThemeManager.h"
#include "UITheme.h"
#include <BeBuild.h>
#ifdef B_ZETA_VERSION
#include <locale/Locale.h>
#else
#define _T(v) v
#define B_LANGUAGE_CHANGED '_BLC'
#define B_PREF_APP_SET_DEFAULTS 'zPAD'
#define B_PREF_APP_REVERT 'zPAR'
#define B_PREF_APP_ADDON_REF 'zPAA'
#endif
#include <Button.h>
#include <CheckBox.h>
#include <Font.h>
#include <Roster.h>
#include <View.h>
#include <stdio.h>
#define CTRL_OFF_X 40
#define CTRL_OFF_Y 25
#define CTRL_SPACING 10
#define HAVE_PREF_BTN
ThemeAddonItem::ThemeAddonItem(BRect bounds, ThemeInterfaceView *iview, int32 id)
: ViewItem(bounds, "addonitem", B_FOLLOW_NONE, B_WILL_DRAW)
{
ThemeManager *tman;
fId = id;
fIView = iview;
tman = iview->GetThemeManager();
fAddonName = tman->AddonName(id);
BString tip(tman->AddonDescription(id));
#ifdef B_BEOS_VERSION_DANO
SetToolTipText(tip.String());
SetViewUIColor(B_UI_PANEL_BACKGROUND_COLOR);
SetLowUIColor(B_UI_PANEL_BACKGROUND_COLOR);
SetHighUIColor(B_UI_PANEL_TEXT_COLOR);
#else
SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
SetLowColor(ui_color(B_PANEL_BACKGROUND_COLOR));
SetHighColor(ui_color(B_PANEL_TEXT_COLOR));
#endif
BMessage *apply = new BMessage(CB_APPLY);
apply->AddInt32("addon", id);
BMessage *save = new BMessage(CB_SAVE);
save->AddInt32("addon", id);
BMessage *prefs = new BMessage(BTN_PREFS);
prefs->AddInt32("addon", id);
fApplyBox = new BCheckBox(BRect(CTRL_OFF_X, CTRL_OFF_Y, CTRL_OFF_X+50, CTRL_OFF_Y+30), "apply", _T("Apply"), apply);
fApplyBox->SetValue((tman->AddonFlags(id) & Z_THEME_ADDON_DO_SET_ALL)?B_CONTROL_ON:B_CONTROL_OFF);
fSaveBox = new BCheckBox(BRect(CTRL_OFF_X+50+CTRL_SPACING, CTRL_OFF_Y, CTRL_OFF_X+100+CTRL_SPACING, CTRL_OFF_Y+30), "save", _T("Save"), save);
fSaveBox->SetValue((tman->AddonFlags(id) & Z_THEME_ADDON_DO_RETRIEVE)?B_CONTROL_ON:B_CONTROL_OFF);
#ifdef B_BEOS_VERSION_DANO
fApplyBox->SetToolTipText(_T("Use this information from themes"));
fSaveBox->SetToolTipText(_T("Save this information to themes"));
#endif
#ifdef HAVE_PREF_BTN
fPrefsBtn = new BButton(BRect(CTRL_OFF_X+100+CTRL_SPACING*2, CTRL_OFF_Y, CTRL_OFF_X+150+CTRL_SPACING*2, CTRL_OFF_Y+30), "prefs", _T("Preferences"), prefs);
#ifdef B_BEOS_VERSION_DANO
fPrefsBtn->SetToolTipText(_T("Run the preferences panel for this topic."));
#endif
#endif
BFont fnt;
GetFont(&fnt);
fnt.SetSize(fnt.Size()+1);
fnt.SetFace(B_ITALIC_FACE);
SetFont(&fnt);
}
ThemeAddonItem::~ThemeAddonItem()
{
delete fApplyBox;
delete fSaveBox;
#ifdef HAVE_PREF_BTN
delete fPrefsBtn;
#endif
}
void
ThemeAddonItem::DrawItem(BView *ownerview, BRect frame, bool complete)
{
ViewItem::DrawItem(ownerview, frame, complete);
}
void
ThemeAddonItem::AttachedToWindow()
{
AddChild(fApplyBox);
fApplyBox->SetTarget(fIView);
AddChild(fSaveBox);
fSaveBox->SetTarget(fIView);
#ifdef HAVE_PREF_BTN
AddChild(fPrefsBtn);
fPrefsBtn->SetTarget(fIView);
#endif
RelayoutButtons();
}
void
ThemeAddonItem::MessageReceived(BMessage *message)
{
switch (message->what) {
case B_LANGUAGE_CHANGED:
break;
}
BView::MessageReceived(message);
}
void
ThemeAddonItem::Draw(BRect)
{
DrawString(fAddonName.String(), BPoint(10, 15/*Bounds().Height()/2*/));
}
void
ThemeAddonItem::RelocalizeStrings()
{
fApplyBox->SetLabel(_T("Apply"));
fSaveBox->SetLabel(_T("Save"));
#ifdef B_BEOS_VERSION_DANO
fApplyBox->SetToolTipText(_T("Use this information from themes"));
fSaveBox->SetToolTipText(_T("Save this information to themes"));
#endif
#ifdef HAVE_PREF_BTN
fPrefsBtn->SetLabel(_T("Preferences"));
#ifdef B_BEOS_VERSION_DANO
fPrefsBtn->SetToolTipText(_T("Run the preferences panel for this topic."));
#endif
#endif
RelayoutButtons();
}
void
ThemeAddonItem::RelayoutButtons()
{
fApplyBox->ResizeToPreferred();
fSaveBox->MoveTo(fApplyBox->Frame().right+CTRL_SPACING, fApplyBox->Frame().top);
fSaveBox->ResizeToPreferred();
#ifdef HAVE_PREF_BTN
fPrefsBtn->MoveTo(fSaveBox->Frame().right+CTRL_SPACING, fSaveBox->Frame().top);
fPrefsBtn->ResizeToPreferred();
#endif
}
int32
ThemeAddonItem::AddonId()
{
return fId;
}
<commit_msg>Add tooltips on Haiku<commit_after>/*
* Copyright 2000-2008, François Revol, <[email protected]>. All rights reserved.
* Distributed under the terms of the MIT License.
*/
#include "ThemeAddonItem.h"
#include "ThemeInterfaceView.h"
#include "ThemeManager.h"
#include "UITheme.h"
#include <BeBuild.h>
#ifdef B_ZETA_VERSION
#include <locale/Locale.h>
#else
#define _T(v) v
#define B_LANGUAGE_CHANGED '_BLC'
#define B_PREF_APP_SET_DEFAULTS 'zPAD'
#define B_PREF_APP_REVERT 'zPAR'
#define B_PREF_APP_ADDON_REF 'zPAA'
#endif
#include <Button.h>
#include <CheckBox.h>
#include <Font.h>
#include <Roster.h>
#include <View.h>
#include <stdio.h>
#define CTRL_OFF_X 40
#define CTRL_OFF_Y 25
#define CTRL_SPACING 10
#define HAVE_PREF_BTN
ThemeAddonItem::ThemeAddonItem(BRect bounds, ThemeInterfaceView *iview, int32 id)
: ViewItem(bounds, "addonitem", B_FOLLOW_NONE, B_WILL_DRAW)
{
ThemeManager *tman;
fId = id;
fIView = iview;
tman = iview->GetThemeManager();
fAddonName = tman->AddonName(id);
BString tip(tman->AddonDescription(id));
#ifdef B_BEOS_VERSION_DANO
SetToolTipText(tip.String());
SetViewUIColor(B_UI_PANEL_BACKGROUND_COLOR);
SetLowUIColor(B_UI_PANEL_BACKGROUND_COLOR);
SetHighUIColor(B_UI_PANEL_TEXT_COLOR);
#else
#ifdef __HAIKU__
SetToolTip(tip.String());
#endif
SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
SetLowColor(ui_color(B_PANEL_BACKGROUND_COLOR));
SetHighColor(ui_color(B_PANEL_TEXT_COLOR));
#endif
BMessage *apply = new BMessage(CB_APPLY);
apply->AddInt32("addon", id);
BMessage *save = new BMessage(CB_SAVE);
save->AddInt32("addon", id);
BMessage *prefs = new BMessage(BTN_PREFS);
prefs->AddInt32("addon", id);
fApplyBox = new BCheckBox(BRect(CTRL_OFF_X, CTRL_OFF_Y, CTRL_OFF_X+50, CTRL_OFF_Y+30), "apply", _T("Apply"), apply);
fApplyBox->SetValue((tman->AddonFlags(id) & Z_THEME_ADDON_DO_SET_ALL)?B_CONTROL_ON:B_CONTROL_OFF);
fSaveBox = new BCheckBox(BRect(CTRL_OFF_X+50+CTRL_SPACING, CTRL_OFF_Y, CTRL_OFF_X+100+CTRL_SPACING, CTRL_OFF_Y+30), "save", _T("Save"), save);
fSaveBox->SetValue((tman->AddonFlags(id) & Z_THEME_ADDON_DO_RETRIEVE)?B_CONTROL_ON:B_CONTROL_OFF);
#ifdef B_BEOS_VERSION_DANO
fApplyBox->SetToolTipText(_T("Use this information from themes"));
fSaveBox->SetToolTipText(_T("Save this information to themes"));
#endif
#ifdef __HAIKU__
fApplyBox->SetToolTip(_T("Use this information from themes"));
fSaveBox->SetToolTip(_T("Save this information to themes"));
#endif
#ifdef HAVE_PREF_BTN
fPrefsBtn = new BButton(BRect(CTRL_OFF_X+100+CTRL_SPACING*2, CTRL_OFF_Y, CTRL_OFF_X+150+CTRL_SPACING*2, CTRL_OFF_Y+30), "prefs", _T("Preferences"), prefs);
#ifdef B_BEOS_VERSION_DANO
fPrefsBtn->SetToolTipText(_T("Run the preferences panel for this topic."));
#endif
#ifdef __HAIKU__
fPrefsBtn->SetToolTip(_T("Run the preferences panel for this topic."));
#endif
#endif
BFont fnt;
GetFont(&fnt);
fnt.SetSize(fnt.Size()+1);
fnt.SetFace(B_ITALIC_FACE);
SetFont(&fnt);
}
ThemeAddonItem::~ThemeAddonItem()
{
delete fApplyBox;
delete fSaveBox;
#ifdef HAVE_PREF_BTN
delete fPrefsBtn;
#endif
}
void
ThemeAddonItem::DrawItem(BView *ownerview, BRect frame, bool complete)
{
ViewItem::DrawItem(ownerview, frame, complete);
}
void
ThemeAddonItem::AttachedToWindow()
{
AddChild(fApplyBox);
fApplyBox->SetTarget(fIView);
AddChild(fSaveBox);
fSaveBox->SetTarget(fIView);
#ifdef HAVE_PREF_BTN
AddChild(fPrefsBtn);
fPrefsBtn->SetTarget(fIView);
#endif
RelayoutButtons();
}
void
ThemeAddonItem::MessageReceived(BMessage *message)
{
switch (message->what) {
case B_LANGUAGE_CHANGED:
break;
}
BView::MessageReceived(message);
}
void
ThemeAddonItem::Draw(BRect)
{
DrawString(fAddonName.String(), BPoint(10, 15/*Bounds().Height()/2*/));
}
void
ThemeAddonItem::RelocalizeStrings()
{
fApplyBox->SetLabel(_T("Apply"));
fSaveBox->SetLabel(_T("Save"));
#ifdef B_BEOS_VERSION_DANO
fApplyBox->SetToolTipText(_T("Use this information from themes"));
fSaveBox->SetToolTipText(_T("Save this information to themes"));
#endif
#ifdef __HAIKU__
fApplyBox->SetToolTip(_T("Use this information from themes"));
fSaveBox->SetToolTip(_T("Save this information to themes"));
#endif
#ifdef HAVE_PREF_BTN
fPrefsBtn->SetLabel(_T("Preferences"));
#ifdef B_BEOS_VERSION_DANO
fPrefsBtn->SetToolTipText(_T("Run the preferences panel for this topic."));
#endif
#ifdef __HAIKU__
fPrefsBtn->SetToolTip(_T("Run the preferences panel for this topic."));
#endif
#endif
RelayoutButtons();
}
void
ThemeAddonItem::RelayoutButtons()
{
fApplyBox->ResizeToPreferred();
fSaveBox->MoveTo(fApplyBox->Frame().right+CTRL_SPACING, fApplyBox->Frame().top);
fSaveBox->ResizeToPreferred();
#ifdef HAVE_PREF_BTN
fPrefsBtn->MoveTo(fSaveBox->Frame().right+CTRL_SPACING, fSaveBox->Frame().top);
fPrefsBtn->ResizeToPreferred();
#endif
}
int32
ThemeAddonItem::AddonId()
{
return fId;
}
<|endoftext|> |
<commit_before>#include "ToolBase.h"
#include "TSVFileStream.h"
#include "Helper.h"
#include "BasicStatistics.h"
#include <QFileInfo>
#include <QBitArray>
class ConcreteTool
: public ToolBase
{
Q_OBJECT
public:
ConcreteTool(int& argc, char *argv[])
: ToolBase(argc, argv)
{
ops << ">" << ">=" << "=" << "<=" << "<" << "is" << "contains";
}
virtual void setup()
{
setDescription("Filters the rows of a TSV file according to the value of a specific column.");
addString("filter", "Filter string with column name, operation and value,e.g. 'depth > 17'.\nValid operations are '" + ops.join("','") + "'.", false);
//optional
addInfile("in", "Input TSV file. If unset, reads from STDIN.", true);
addOutfile("out", "Output TSV file. If unset, writes to STDOUT.", true);
addFlag("numeric", "If set, column name is interpreted as a 1-based column number.");
addFlag("v", "Invert filter.");
}
virtual void main()
{
//init
QString in = getInfile("in");
QString out = getOutfile("out");
if(in!="" && in==out)
{
THROW(ArgumentException, "Input and output files must be different when streaming!");
}
TSVFileStream instream(in);
QSharedPointer<QFile> outstream = Helper::openFileForWriting(out, true);
bool v = getFlag("v");
//split filter
QString filter = getString("filter");
QStringList parts = filter.split(" ");
if (parts.count()<3)
{
THROW(CommandLineParsingException, "Could not split filter '" + filter + "' in three or more parts (by space)!");
}
//re-join string values with spaces
while(parts.count()>3)
{
int count = parts.count();
parts[count-2] += " " +parts[count-1];
parts.removeLast();
}
//check column
QVector<int> cols = instream.checkColumns(parts[0].toLatin1().split(','), getFlag("numeric"));
if (cols.count()!=1)
{
THROW(CommandLineParsingException, "Could not determine column name/index '" + parts[0] + "'!");
}
int col = cols[0];
//check operation
QByteArray op = parts[1].toLatin1();
int op_index = ops.indexOf(op);
if(op_index==-1)
{
THROW(CommandLineParsingException, "Invalid operation '" + op + "'!");
}
//check value
QByteArray value = parts[2].toLatin1();
double value_num = 0;
if (op_index<5)
{
if(!BasicStatistics::isValidFloat(value))
{
THROW(CommandLineParsingException, "Non-numeric filter value '" + value + "' for numeric filter operation '" + op + " given!");
}
value_num = value.toDouble();
}
//write comments
foreach (QByteArray comment, instream.comments())
{
outstream->write(comment);
outstream->write("\n");
}
//write header
const int col_count = instream.header().count();
outstream->write("#");
for(int i=0; i<col_count; ++i)
{
outstream->write(instream.header()[i]);
outstream->write(i==col_count-1 ? "\n" : "\t");
}
qDebug() << parts[0] << " " << op << " " << parts[2];
//write content
while(!instream.atEnd())
{
QList<QByteArray> parts = instream.readLine();
if (parts.count()==0) continue;
QByteArray value2 = parts[col];
double value2_num = 0;
if (op_index<5)
{
bool ok = true;
value2_num = value2.toDouble(&ok);
if (!ok)
{
THROW(CommandLineParsingException, "Non-numeric value '" + value2 + "' for numeric filter operation '" + op + " in line " + QString::number(instream.lineIndex()+1) + "!");
}
}
bool pass_filter = true;
switch(op_index)
{
case 0: //">"
pass_filter = value2_num>value_num;
break;
case 1: //">="
pass_filter = value2_num>=value_num;
break;
case 2: //"="
pass_filter = value2_num==value_num;
break;
case 3: //"<="
pass_filter = value2_num<=value_num;
break;
case 4: //"<"
pass_filter = value2_num<value_num;
break;
case 5: //"is"
pass_filter = value2 == value;
break;
case 6: //"contains"
pass_filter = value2.contains(value);
break;
default:
THROW(ProgrammingException, "Invalid filter operation index " + QString::number(op_index) + "!");
};
if ((!v && !pass_filter) || (v && pass_filter))
{
continue;
}
for(int i=0; i<col_count; ++i)
{
outstream->write(parts[i]);
outstream->write(i==col_count-1 ? "\n" : "\t");
}
}
}
//valid operations list
QStringList ops;
};
#include "main.moc"
int main(int argc, char *argv[])
{
ConcreteTool tool(argc, argv);
return tool.execute();
}
<commit_msg>src/TsvFilter/main.cpp: removed Debug output<commit_after>#include "ToolBase.h"
#include "TSVFileStream.h"
#include "Helper.h"
#include "BasicStatistics.h"
#include <QFileInfo>
#include <QBitArray>
class ConcreteTool
: public ToolBase
{
Q_OBJECT
public:
ConcreteTool(int& argc, char *argv[])
: ToolBase(argc, argv)
{
ops << ">" << ">=" << "=" << "<=" << "<" << "is" << "contains";
}
virtual void setup()
{
setDescription("Filters the rows of a TSV file according to the value of a specific column.");
addString("filter", "Filter string with column name, operation and value,e.g. 'depth > 17'.\nValid operations are '" + ops.join("','") + "'.", false);
//optional
addInfile("in", "Input TSV file. If unset, reads from STDIN.", true);
addOutfile("out", "Output TSV file. If unset, writes to STDOUT.", true);
addFlag("numeric", "If set, column name is interpreted as a 1-based column number.");
addFlag("v", "Invert filter.");
}
virtual void main()
{
//init
QString in = getInfile("in");
QString out = getOutfile("out");
if(in!="" && in==out)
{
THROW(ArgumentException, "Input and output files must be different when streaming!");
}
TSVFileStream instream(in);
QSharedPointer<QFile> outstream = Helper::openFileForWriting(out, true);
bool v = getFlag("v");
//split filter
QString filter = getString("filter");
QStringList parts = filter.split(" ");
if (parts.count()<3)
{
THROW(CommandLineParsingException, "Could not split filter '" + filter + "' in three or more parts (by space)!");
}
//re-join string values with spaces
while(parts.count()>3)
{
int count = parts.count();
parts[count-2] += " " +parts[count-1];
parts.removeLast();
}
//check column
QVector<int> cols = instream.checkColumns(parts[0].toLatin1().split(','), getFlag("numeric"));
if (cols.count()!=1)
{
THROW(CommandLineParsingException, "Could not determine column name/index '" + parts[0] + "'!");
}
int col = cols[0];
//check operation
QByteArray op = parts[1].toLatin1();
int op_index = ops.indexOf(op);
if(op_index==-1)
{
THROW(CommandLineParsingException, "Invalid operation '" + op + "'!");
}
//check value
QByteArray value = parts[2].toLatin1();
double value_num = 0;
if (op_index<5)
{
if(!BasicStatistics::isValidFloat(value))
{
THROW(CommandLineParsingException, "Non-numeric filter value '" + value + "' for numeric filter operation '" + op + " given!");
}
value_num = value.toDouble();
}
//write comments
foreach (QByteArray comment, instream.comments())
{
outstream->write(comment);
outstream->write("\n");
}
//write header
const int col_count = instream.header().count();
outstream->write("#");
for(int i=0; i<col_count; ++i)
{
outstream->write(instream.header()[i]);
outstream->write(i==col_count-1 ? "\n" : "\t");
}
//write content
while(!instream.atEnd())
{
QList<QByteArray> parts = instream.readLine();
if (parts.count()==0) continue;
QByteArray value2 = parts[col];
double value2_num = 0;
if (op_index<5)
{
bool ok = true;
value2_num = value2.toDouble(&ok);
if (!ok)
{
THROW(CommandLineParsingException, "Non-numeric value '" + value2 + "' for numeric filter operation '" + op + " in line " + QString::number(instream.lineIndex()+1) + "!");
}
}
bool pass_filter = true;
switch(op_index)
{
case 0: //">"
pass_filter = value2_num>value_num;
break;
case 1: //">="
pass_filter = value2_num>=value_num;
break;
case 2: //"="
pass_filter = value2_num==value_num;
break;
case 3: //"<="
pass_filter = value2_num<=value_num;
break;
case 4: //"<"
pass_filter = value2_num<value_num;
break;
case 5: //"is"
pass_filter = value2 == value;
break;
case 6: //"contains"
pass_filter = value2.contains(value);
break;
default:
THROW(ProgrammingException, "Invalid filter operation index " + QString::number(op_index) + "!");
};
if ((!v && !pass_filter) || (v && pass_filter))
{
continue;
}
for(int i=0; i<col_count; ++i)
{
outstream->write(parts[i]);
outstream->write(i==col_count-1 ? "\n" : "\t");
}
}
}
//valid operations list
QStringList ops;
};
#include "main.moc"
int main(int argc, char *argv[])
{
ConcreteTool tool(argc, argv);
return tool.execute();
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Alexandru-Eugen Ichim
* Willow Garage, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*/
#ifndef PCL_FEATURES_IMPL_NORMAL_BASED_SIGNATURE_H_
#define PCL_FEATURES_IMPL_NORMAL_BASED_SIGNATURE_H_
#include <pcl/features/normal_based_signature.h>
template <typename PointT, typename PointNT, typename PointFeature> void
pcl::NormalBasedSignatureEstimation<PointT, PointNT, PointFeature>::computeFeature (FeatureCloud &output)
{
// do a few checks before starting the computations
PointFeature test_feature;
if (N_prime_ * M_prime_ != sizeof (test_feature.values) / sizeof (float))
{
PCL_ERROR ("NormalBasedSignatureEstimation: not using the proper signature size: %u vs %u\n", N_prime_ * M_prime_, sizeof (test_feature.values) / sizeof (float));
return;
}
std::vector<int> k_indices;
std::vector<float> k_sqr_distances;
tree_->setInputCloud (input_);
output.points.resize (indices_->size ());
for (size_t index_i = 0; index_i < indices_->size (); ++index_i)
{
size_t point_i = (*indices_)[index_i];
Eigen::MatrixXf s_matrix (N_, M_);
Eigen::Vector4f center_point = input_->points[point_i].getVector4fMap ();
for (size_t k = 0; k < N_; ++k)
{
Eigen::VectorXf s_row (M_);
for (size_t l = 0; l < M_; ++l)
{
Eigen::Vector4f normal = normals_->points[point_i].getNormalVector4fMap ();
Eigen::Vector4f normal_u = Eigen::Vector4f::Zero ();
Eigen::Vector4f normal_v = Eigen::Vector4f::Zero ();
if (fabs (normal.x ()) > 0.0001f)
{
normal_u.x () = - normal.y () / normal.x ();
normal_u.y () = 1.0f;
normal_u.z () = 0.0f;
normal_u.normalize ();
}
else if (fabs (normal.y ()) > 0.0001f)
{
normal_u.x () = 1.0f;
normal_u.y () = - normal.x () / normal.y ();
normal_u.z () = 0.0f;
normal_u.normalize ();
}
else
{
normal_u.x () = 0.0f;
normal_u.y () = 1.0f;
normal_u.z () = - normal.y () / normal.z ();
}
normal_v = normal.cross3 (normal_u);
Eigen::Vector4f zeta_point = 2.0f * static_cast<float> (l + 1) * scale_h_ / static_cast<float> (M_) *
(cosf (2.0f * static_cast<float> (M_PI) * static_cast<float> ((k + 1) / N_)) * normal_u +
sinf (2.0f * static_cast<float> (M_PI) * static_cast<float> ((k + 1) / N_)) * normal_v);
// Compute normal by using the neighbors
Eigen::Vector4f zeta_point_plus_center = zeta_point + center_point;
PointT zeta_point_pcl;
zeta_point_pcl.x = zeta_point_plus_center.x (); zeta_point_pcl.y = zeta_point_plus_center.y (); zeta_point_pcl.z = zeta_point_plus_center.z ();
tree_->radiusSearch (zeta_point_pcl, search_radius_, k_indices, k_sqr_distances);
// Do k nearest search if there are no neighbors nearby
if (k_indices.size () == 0)
{
k_indices.resize (5);
k_sqr_distances.resize (5);
tree_->nearestKSearch (zeta_point_pcl, 5, k_indices, k_sqr_distances);
}
Eigen::Vector4f average_normal = Eigen::Vector4f::Zero ();
float average_normalization_factor = 0.0f;
// Normals weighted by 1/squared_distances
for (size_t nn_i = 0; nn_i < k_indices.size (); ++nn_i)
{
if (k_sqr_distances[nn_i] < 1e-7f)
{
average_normal = normals_->points[k_indices[nn_i]].getNormalVector4fMap ();
average_normalization_factor = 1.0f;
break;
}
average_normal += normals_->points[k_indices[nn_i]].getNormalVector4fMap () / k_sqr_distances[nn_i];
average_normalization_factor += 1.0f / k_sqr_distances[nn_i];
}
average_normal /= average_normalization_factor;
float s = zeta_point.dot (average_normal) / zeta_point.norm ();
s_row[l] = s;
}
// do DCT on the s_matrix row-wise
Eigen::VectorXf dct_row (M_);
for (int m = 0; m < s_row.size (); ++m)
{
float Xk = 0.0f;
for (int n = 0; n < s_row.size (); ++n)
Xk += static_cast<float> (s_row[n] * cos (M_PI / (static_cast<double> (M_ * n) + 0.5) * static_cast<double> (k)));
dct_row[m] = Xk;
}
s_row = dct_row;
s_matrix.row (k).matrix () = dct_row;
}
// do DFT on the s_matrix column-wise
Eigen::MatrixXf dft_matrix (N_, M_);
for (size_t column_i = 0; column_i < M_; ++column_i)
{
Eigen::VectorXf dft_col (N_);
for (size_t k = 0; k < N_; ++k)
{
float Xk_real = 0.0f, Xk_imag = 0.0f;
for (size_t n = 0; n < N_; ++n)
{
Xk_real += static_cast<float> (s_matrix (n, column_i) * cos (2.0f * M_PI / static_cast<double> (N_ * k * n)));
Xk_imag += static_cast<float> (s_matrix (n, column_i) * sin (2.0f * M_PI / static_cast<double> (N_ * k * n)));
}
dft_col[k] = sqrtf (Xk_real*Xk_real + Xk_imag*Xk_imag);
}
dft_matrix.col (column_i).matrix () = dft_col;
}
Eigen::MatrixXf final_matrix = dft_matrix.block (0, 0, N_prime_, M_prime_);
PointFeature feature_point;
for (size_t i = 0; i < N_prime_; ++i)
for (size_t j = 0; j < M_prime_; ++j)
feature_point.values[i*M_prime_ + j] = final_matrix (i, j);
output.points[index_i] = feature_point;
}
}
#define PCL_INSTANTIATE_NormalBasedSignatureEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::NormalBasedSignatureEstimation<T,NT,OutT>;
#endif /* PCL_FEATURES_IMPL_NORMAL_BASED_SIGNATURE_H_ */
<commit_msg>removed a compiler warning on win32<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Alexandru-Eugen Ichim
* Willow Garage, Inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*/
#ifndef PCL_FEATURES_IMPL_NORMAL_BASED_SIGNATURE_H_
#define PCL_FEATURES_IMPL_NORMAL_BASED_SIGNATURE_H_
#include <pcl/features/normal_based_signature.h>
template <typename PointT, typename PointNT, typename PointFeature> void
pcl::NormalBasedSignatureEstimation<PointT, PointNT, PointFeature>::computeFeature (FeatureCloud &output)
{
// do a few checks before starting the computations
PointFeature test_feature;
(void)test_feature;
if (N_prime_ * M_prime_ != sizeof (test_feature.values) / sizeof (float))
{
PCL_ERROR ("NormalBasedSignatureEstimation: not using the proper signature size: %u vs %u\n", N_prime_ * M_prime_, sizeof (test_feature.values) / sizeof (float));
return;
}
std::vector<int> k_indices;
std::vector<float> k_sqr_distances;
tree_->setInputCloud (input_);
output.points.resize (indices_->size ());
for (size_t index_i = 0; index_i < indices_->size (); ++index_i)
{
size_t point_i = (*indices_)[index_i];
Eigen::MatrixXf s_matrix (N_, M_);
Eigen::Vector4f center_point = input_->points[point_i].getVector4fMap ();
for (size_t k = 0; k < N_; ++k)
{
Eigen::VectorXf s_row (M_);
for (size_t l = 0; l < M_; ++l)
{
Eigen::Vector4f normal = normals_->points[point_i].getNormalVector4fMap ();
Eigen::Vector4f normal_u = Eigen::Vector4f::Zero ();
Eigen::Vector4f normal_v = Eigen::Vector4f::Zero ();
if (fabs (normal.x ()) > 0.0001f)
{
normal_u.x () = - normal.y () / normal.x ();
normal_u.y () = 1.0f;
normal_u.z () = 0.0f;
normal_u.normalize ();
}
else if (fabs (normal.y ()) > 0.0001f)
{
normal_u.x () = 1.0f;
normal_u.y () = - normal.x () / normal.y ();
normal_u.z () = 0.0f;
normal_u.normalize ();
}
else
{
normal_u.x () = 0.0f;
normal_u.y () = 1.0f;
normal_u.z () = - normal.y () / normal.z ();
}
normal_v = normal.cross3 (normal_u);
Eigen::Vector4f zeta_point = 2.0f * static_cast<float> (l + 1) * scale_h_ / static_cast<float> (M_) *
(cosf (2.0f * static_cast<float> (M_PI) * static_cast<float> ((k + 1) / N_)) * normal_u +
sinf (2.0f * static_cast<float> (M_PI) * static_cast<float> ((k + 1) / N_)) * normal_v);
// Compute normal by using the neighbors
Eigen::Vector4f zeta_point_plus_center = zeta_point + center_point;
PointT zeta_point_pcl;
zeta_point_pcl.x = zeta_point_plus_center.x (); zeta_point_pcl.y = zeta_point_plus_center.y (); zeta_point_pcl.z = zeta_point_plus_center.z ();
tree_->radiusSearch (zeta_point_pcl, search_radius_, k_indices, k_sqr_distances);
// Do k nearest search if there are no neighbors nearby
if (k_indices.size () == 0)
{
k_indices.resize (5);
k_sqr_distances.resize (5);
tree_->nearestKSearch (zeta_point_pcl, 5, k_indices, k_sqr_distances);
}
Eigen::Vector4f average_normal = Eigen::Vector4f::Zero ();
float average_normalization_factor = 0.0f;
// Normals weighted by 1/squared_distances
for (size_t nn_i = 0; nn_i < k_indices.size (); ++nn_i)
{
if (k_sqr_distances[nn_i] < 1e-7f)
{
average_normal = normals_->points[k_indices[nn_i]].getNormalVector4fMap ();
average_normalization_factor = 1.0f;
break;
}
average_normal += normals_->points[k_indices[nn_i]].getNormalVector4fMap () / k_sqr_distances[nn_i];
average_normalization_factor += 1.0f / k_sqr_distances[nn_i];
}
average_normal /= average_normalization_factor;
float s = zeta_point.dot (average_normal) / zeta_point.norm ();
s_row[l] = s;
}
// do DCT on the s_matrix row-wise
Eigen::VectorXf dct_row (M_);
for (int m = 0; m < s_row.size (); ++m)
{
float Xk = 0.0f;
for (int n = 0; n < s_row.size (); ++n)
Xk += static_cast<float> (s_row[n] * cos (M_PI / (static_cast<double> (M_ * n) + 0.5) * static_cast<double> (k)));
dct_row[m] = Xk;
}
s_row = dct_row;
s_matrix.row (k).matrix () = dct_row;
}
// do DFT on the s_matrix column-wise
Eigen::MatrixXf dft_matrix (N_, M_);
for (size_t column_i = 0; column_i < M_; ++column_i)
{
Eigen::VectorXf dft_col (N_);
for (size_t k = 0; k < N_; ++k)
{
float Xk_real = 0.0f, Xk_imag = 0.0f;
for (size_t n = 0; n < N_; ++n)
{
Xk_real += static_cast<float> (s_matrix (n, column_i) * cos (2.0f * M_PI / static_cast<double> (N_ * k * n)));
Xk_imag += static_cast<float> (s_matrix (n, column_i) * sin (2.0f * M_PI / static_cast<double> (N_ * k * n)));
}
dft_col[k] = sqrtf (Xk_real*Xk_real + Xk_imag*Xk_imag);
}
dft_matrix.col (column_i).matrix () = dft_col;
}
Eigen::MatrixXf final_matrix = dft_matrix.block (0, 0, N_prime_, M_prime_);
PointFeature feature_point;
for (size_t i = 0; i < N_prime_; ++i)
for (size_t j = 0; j < M_prime_; ++j)
feature_point.values[i*M_prime_ + j] = final_matrix (i, j);
output.points[index_i] = feature_point;
}
}
#define PCL_INSTANTIATE_NormalBasedSignatureEstimation(T,NT,OutT) template class PCL_EXPORTS pcl::NormalBasedSignatureEstimation<T,NT,OutT>;
#endif /* PCL_FEATURES_IMPL_NORMAL_BASED_SIGNATURE_H_ */
<|endoftext|> |
<commit_before>#include "addtrainingdlg.h"
#include "ui_addtrainingdlg.h"
#include <QDebug>
#include <QSqlField>
#include <QMessageBox>
/**
* @brief Creates a dialog for adding and editing training.
* @param parent The parent widget.
*/
AddTrainingDlg::AddTrainingDlg(TrainingModel *model, int trainingRow, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddTrainingDlg)
{
ui->setupUi(this);
connect(ui->btnAdd, SIGNAL(clicked()), this, SLOT(addTraining()));
connect(ui->btnAddAndClose, SIGNAL(clicked()), this, SLOT(addTrainingAndClose()));
connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(saveTraining()));
teamModel = new TeamModel;
ui->comboBoxTeam->setModel(teamModel);
ui->comboBoxTeam->setModelColumn(1);
this->trainingModel = model;
QDate currentDate = QDate::currentDate();
int year = currentDate.year();
int month = currentDate.month();
if(month < 9) year--;
startSeason = QDate::fromString("1.9."+QString::number(year), "d.M.yyyy");
endSeason = QDate::fromString("31.8."+QString::number(year+1), "d.M.yyyy");
if(trainingRow == -1) // Add
{
ui->editDate->setDate(currentDate);
ui->btnSave->setVisible(false);
ui->chckBoxCanceled->setVisible(false);
}
else // Edit
{
setWindowTitle(tr("Edit training"));
QSqlRecord record = trainingModel->record(trainingRow);
QDateTime datetime = record.field("datetime").value().toDateTime();
ui->editDate->setDate(datetime.date());
ui->editTime->setTime(datetime.time());
ui->editPlace->setText(record.field("place").value().toString());
ui->checkBoxEveryWeek->setVisible(false);
ui->checkBoxEveryWeek->setChecked(false);
ui->comboBoxDay->setVisible(false);
ui->editDate->setEnabled(true);
ui->btnAdd->setVisible(false);
ui->btnAddAndClose->setVisible(false);
}
m_row = trainingRow;
setWindowState(Qt::WindowMinimized);
}
void AddTrainingDlg::addTraining()
{
if(!insertTrainings()) return;
ui->checkBoxEveryWeek->setChecked(true);
ui->editDate->setEnabled(false);
ui->editTime->setTime(QTime::fromString("12:00", "hh:mm"));
ui->editPlace->setText("");
}
void AddTrainingDlg::addTrainingAndClose()
{
if(!insertTrainings()) return;
close();
}
void AddTrainingDlg::saveTraining()
{
if(!checkForm(tr("Edit training"))) return;
QSqlRecord record = prepareRecords().at(0);
trainingModel->setRecord(m_row, record);
trainingModel->submitAll();
close();
}
bool AddTrainingDlg::insertTrainings()
{
if(!checkForm(tr("Add training"))) return false;
QList<QSqlRecord> records = prepareRecords();
if(records.size() == 0) return false;
QList<QSqlRecord>::iterator r;
for(r = records.begin(); r != records.end(); ++r)
{
if(!trainingModel->insertRecord(-1, *r))
qDebug("err insert record");
}
if(!trainingModel->submitAll())
{
qDebug("err submit");
}
return true;
}
QList<QSqlRecord> AddTrainingDlg::prepareRecords()
{
QList<QSqlRecord> records;
int idx = ui->comboBoxTeam->currentIndex();
int teamId = teamModel->record(idx).field("id").value().toInt();
if(ui->checkBoxEveryWeek->isChecked())
{
QDateTime start = QDateTime::currentDateTime();
start.setTime(ui->editTime->time());
int nowDayOfWeek = start.date().dayOfWeek();
int dayOfWeek = ui->comboBoxDay->currentIndex()+1;
if(dayOfWeek > nowDayOfWeek)
start = start.addDays(dayOfWeek - nowDayOfWeek);
else if(dayOfWeek < nowDayOfWeek)
start = start.addDays(dayOfWeek - nowDayOfWeek + 7);
while(start.date() < endSeason)
{
records.append(createRecord(start, teamId));
start = start.addDays(7);
}
}
else
{
QDateTime datetime = ui->editDate->dateTime();
datetime.setTime(ui->editTime->time());
records.append(createRecord(datetime, teamId));
}
return records;
}
QSqlRecord AddTrainingDlg::createRecord(QDateTime datetime, int teamID)
{
QSqlRecord record;
QSqlField datetimeField("datetime", QVariant::Date);
QSqlField place("place", QVariant::String);
QSqlField canceled("canceled", QVariant::Bool);
QSqlField teamIDField("team_id", QVariant::Int);
datetimeField.setValue(datetime);
place.setValue(ui->editPlace->text().trimmed());
canceled.setValue(ui->chckBoxCanceled->isChecked());
teamIDField.setValue(teamID);
record.append(datetimeField);
record.append(place);
record.append(canceled);
record.append(teamIDField);
return record;
}
bool AddTrainingDlg::checkForm(QString title)
{
if(ui->editPlace->text().trimmed() == "")
{
QMessageBox::information(this, title, tr("You must specified place."));
return false;
}
return true;
}
/**
* @brief Destructs the dialog.
*/
AddTrainingDlg::~AddTrainingDlg()
{
delete ui;
}
<commit_msg>Fixed - Edit training.<commit_after>#include "addtrainingdlg.h"
#include "ui_addtrainingdlg.h"
#include <QDebug>
#include <QSqlField>
#include <QMessageBox>
/**
* @brief Creates a dialog for adding and editing training.
* @param parent The parent widget.
*/
AddTrainingDlg::AddTrainingDlg(TrainingModel *model, int trainingRow, QWidget *parent) :
QDialog(parent),
ui(new Ui::AddTrainingDlg)
{
ui->setupUi(this);
connect(ui->btnAdd, SIGNAL(clicked()), this, SLOT(addTraining()));
connect(ui->btnAddAndClose, SIGNAL(clicked()), this, SLOT(addTrainingAndClose()));
connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(saveTraining()));
teamModel = new TeamModel;
ui->comboBoxTeam->setModel(teamModel);
ui->comboBoxTeam->setModelColumn(1);
this->trainingModel = model;
QDate currentDate = QDate::currentDate();
int year = currentDate.year();
int month = currentDate.month();
if(month < 9) year--;
startSeason = QDate::fromString("1.9."+QString::number(year), "d.M.yyyy");
endSeason = QDate::fromString("31.8."+QString::number(year+1), "d.M.yyyy");
if(trainingRow == -1) // Add
{
ui->editDate->setDate(currentDate);
ui->btnSave->setVisible(false);
ui->chckBoxCanceled->setVisible(false);
}
else // Edit
{
setWindowTitle(tr("Edit training"));
QSqlRecord record = trainingModel->record(trainingRow);
QDateTime datetime = record.field("datetime").value().toDateTime();
ui->editDate->setDate(datetime.date());
ui->editTime->setTime(datetime.time());
ui->editPlace->setText(record.field("place").value().toString());
ui->chckBoxCanceled->setChecked(record.field("canceled").value().toBool());
ui->checkBoxEveryWeek->setVisible(false);
ui->checkBoxEveryWeek->setChecked(false);
ui->comboBoxDay->setVisible(false);
ui->editDate->setEnabled(true);
ui->btnAdd->setVisible(false);
ui->btnAddAndClose->setVisible(false);
}
m_row = trainingRow;
setWindowState(Qt::WindowMinimized);
}
void AddTrainingDlg::addTraining()
{
if(!insertTrainings()) return;
ui->checkBoxEveryWeek->setChecked(true);
ui->editDate->setEnabled(false);
ui->editTime->setTime(QTime::fromString("12:00", "hh:mm"));
ui->editPlace->setText("");
}
void AddTrainingDlg::addTrainingAndClose()
{
if(!insertTrainings()) return;
close();
}
void AddTrainingDlg::saveTraining()
{
if(!checkForm(tr("Edit training"))) return;
QSqlRecord record = prepareRecords().at(0);
trainingModel->setRecord(m_row, record);
trainingModel->submitAll();
close();
}
bool AddTrainingDlg::insertTrainings()
{
if(!checkForm(tr("Add training"))) return false;
QList<QSqlRecord> records = prepareRecords();
if(records.size() == 0) return false;
QList<QSqlRecord>::iterator r;
for(r = records.begin(); r != records.end(); ++r)
{
if(!trainingModel->insertRecord(-1, *r))
qDebug("err insert record");
}
if(!trainingModel->submitAll())
{
qDebug("err submit");
}
return true;
}
QList<QSqlRecord> AddTrainingDlg::prepareRecords()
{
QList<QSqlRecord> records;
int idx = ui->comboBoxTeam->currentIndex();
int teamId = teamModel->record(idx).field("id").value().toInt();
if(ui->checkBoxEveryWeek->isChecked())
{
QDateTime start = QDateTime::currentDateTime();
start.setTime(ui->editTime->time());
int nowDayOfWeek = start.date().dayOfWeek();
int dayOfWeek = ui->comboBoxDay->currentIndex()+1;
if(dayOfWeek > nowDayOfWeek)
start = start.addDays(dayOfWeek - nowDayOfWeek);
else if(dayOfWeek < nowDayOfWeek)
start = start.addDays(dayOfWeek - nowDayOfWeek + 7);
while(start.date() < endSeason)
{
records.append(createRecord(start, teamId));
start = start.addDays(7);
}
}
else
{
QDateTime datetime = ui->editDate->dateTime();
datetime.setTime(ui->editTime->time());
records.append(createRecord(datetime, teamId));
}
return records;
}
QSqlRecord AddTrainingDlg::createRecord(QDateTime datetime, int teamID)
{
QSqlRecord record;
QSqlField datetimeField("datetime", QVariant::Date);
QSqlField place("place", QVariant::String);
QSqlField canceled("canceled", QVariant::Bool);
QSqlField teamIDField("team_id", QVariant::Int);
datetimeField.setValue(datetime);
place.setValue(ui->editPlace->text().trimmed());
canceled.setValue(ui->chckBoxCanceled->isChecked());
teamIDField.setValue(teamID);
record.append(datetimeField);
record.append(place);
record.append(canceled);
record.append(teamIDField);
return record;
}
bool AddTrainingDlg::checkForm(QString title)
{
if(ui->editPlace->text().trimmed() == "")
{
QMessageBox::information(this, title, tr("You must specified place."));
return false;
}
return true;
}
/**
* @brief Destructs the dialog.
*/
AddTrainingDlg::~AddTrainingDlg()
{
delete ui;
}
<|endoftext|> |
<commit_before>#include "engine/blob.h"
#include "engine/command_line_parser.h"
#include "engine/crc32.h"
#include "engine/fs/disk_file_device.h"
#include "engine/fs/file_system.h"
#include "engine/fs/file_system.h"
#include "engine/fs/memory_file_device.h"
#include "engine/fs/pack_file_device.h"
#include "engine/input_system.h"
#include "engine/log.h"
#include "engine/lua_wrapper.h"
#include "engine/mt/thread.h"
#include "engine/path_utils.h"
#include "engine/profiler.h"
#include "engine/resource_manager.h"
#include "engine/resource_manager_base.h"
#include "engine/system.h"
#include "engine/timer.h"
#include "engine/debug/debug.h"
#include "editor/gizmo.h"
#include "editor/world_editor.h"
#include "engine/engine.h"
#include "engine/plugin_manager.h"
#include "renderer/pipeline.h"
#include "renderer/renderer.h"
#include "renderer/texture.h"
#include "engine/universe/universe.h"
#include <cstdio>
#include <X11/Xlib.h>
namespace Lumix
{
struct App
{
App()
{
m_universe = nullptr;
m_exit_code = 0;
m_frame_timer = Timer::create(m_allocator);
ASSERT(!s_instance);
s_instance = this;
m_pipeline = nullptr;
}
~App()
{
Timer::destroy(m_frame_timer);
ASSERT(!m_universe);
s_instance = nullptr;
}
/*
LRESULT onMessage(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
switch (msg)
{
case WM_CLOSE: PostQuitMessage(0); break;
case WM_MOVE:
case WM_SIZE: onResize(); break;
case WM_QUIT: m_finished = true; break;
case WM_INPUT: handleRawInput(lparam); break;
}
return DefWindowProc(hwnd, msg, wparam, lparam);
}
static LRESULT CALLBACK msgProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
if (!s_instance || !s_instance->m_pipeline) return DefWindowProc(hwnd, msg, wparam, lparam);
return s_instance->onMessage(hwnd, msg, wparam, lparam);
}
void onResize()
{
RECT rect;
RECT screen_rect;
GetClientRect(m_hwnd, &rect);
GetWindowRect(m_hwnd, &screen_rect);
int w = rect.right - rect.left;
int h = rect.bottom - rect.top;
if (w > 0)
{
ClipCursor(&screen_rect);
m_pipeline->setViewport(0, 0, w, h);
Renderer* renderer =
static_cast<Renderer*>(m_engine->getPluginManager().getPlugin("renderer"));
renderer->resize(w, h);
}
}
*/
bool createWindow()
{
m_display = XOpenDisplay(nullptr);
if (!m_display) return false;
int s = DefaultScreen(m_display);
m_window = XCreateSimpleWindow(m_display, RootWindow(m_display, s), 10, 10, 100, 100, 1
, BlackPixel(m_display, s), WhitePixel(m_display, s));
XSelectInput(m_display, m_window, ExposureMask | KeyPressMask);
XMapWindow(m_display, m_window);
return true;
}
void init()
{
copyString(m_pipeline_path, "pipelines/app.lua");
copyString(m_startup_script_path, "startup.lua");
char cmd_line[1024];
getCommandLine(cmd_line, lengthOf(cmd_line));
CommandLineParser parser(cmd_line);
while (parser.next())
{
if (parser.currentEquals("-pipeline"))
{
if (!parser.next()) break;
parser.getCurrent(m_pipeline_path, lengthOf(m_pipeline_path));
}
else if(parser.currentEquals("-script"))
{
if (!parser.next()) break;
parser.getCurrent(m_startup_script_path, lengthOf(m_startup_script_path));
}
}
createWindow();
g_log_info.getCallback().bind<outputToConsole>();
g_log_warning.getCallback().bind<outputToConsole>();
g_log_error.getCallback().bind<outputToConsole>();
enableCrashReporting(false);
m_file_system = FS::FileSystem::create(m_allocator);
m_mem_file_device = LUMIX_NEW(m_allocator, FS::MemoryFileDevice)(m_allocator);
m_disk_file_device = LUMIX_NEW(m_allocator, FS::DiskFileDevice)("disk", "", m_allocator);
m_pack_file_device = LUMIX_NEW(m_allocator, FS::PackFileDevice)(m_allocator);
m_file_system->mount(m_mem_file_device);
m_file_system->mount(m_disk_file_device);
m_file_system->mount(m_pack_file_device);
m_pack_file_device->mount("data.pak");
m_file_system->setDefaultDevice("memory:disk:pack");
m_file_system->setSaveGameDevice("memory:disk");
m_engine = Engine::create("", "", m_file_system, m_allocator);
Engine::PlatformData platform_data;
platform_data.window_handle = (void*)(uintptr_t)m_window;
platform_data.display = m_display;
m_engine->setPlatformData(platform_data);
m_engine->getPluginManager().load("renderer");
m_engine->getPluginManager().load("animation");
m_engine->getPluginManager().load("audio");
m_engine->getPluginManager().load("lua_script");
m_engine->getPluginManager().load("physics");
m_engine->getInputSystem().enable(true);
Renderer* renderer = static_cast<Renderer*>(m_engine->getPluginManager().getPlugin("renderer"));
m_pipeline = Pipeline::create(*renderer, Path(m_pipeline_path), "", m_engine->getAllocator());
m_pipeline->load();
while (m_engine->getFileSystem().hasWork())
{
MT::sleep(100);
m_engine->getFileSystem().updateAsyncTransactions();
}
m_universe = &m_engine->createUniverse(true);
m_pipeline->setScene((RenderScene*)m_universe->getScene(crc32("renderer")));
m_pipeline->setViewport(0, 0, 600, 400);
renderer->resize(600, 400);
registerLuaAPI();
//while (ShowCursor(false) >= 0); // TODO
// onResize(); // TODO
}
void startupScriptLoaded(FS::IFile& file, bool success)
{
if (!success)
{
g_log_error.log("App") << "Could not open " << m_startup_script_path;
return;
}
m_engine->runScript((const char*)file.getBuffer(), (int)file.size(), m_startup_script_path);
}
void registerLuaAPI()
{
lua_State* L = m_engine->getState();
#define REGISTER_FUNCTION(F, name) \
do { \
auto* f = &LuaWrapper::wrapMethod<App, decltype(&App::F), &App::F>; \
LuaWrapper::createSystemFunction(L, "App", name, f); \
} while(false) \
REGISTER_FUNCTION(loadUniverse, "loadUniverse");
REGISTER_FUNCTION(frame, "frame");
REGISTER_FUNCTION(exit, "exit");
#undef REGISTER_FUNCTION
LuaWrapper::createSystemVariable(L, "App", "instance", this);
LuaWrapper::createSystemVariable(L, "App", "universe", m_universe);
auto& fs = m_engine->getFileSystem();
FS::ReadCallback cb;
cb.bind<App, &App::startupScriptLoaded>(this);
fs.openAsync(fs.getDefaultDevice(), Path(m_startup_script_path), FS::Mode::OPEN_AND_READ, cb);
}
void universeFileLoaded(FS::IFile& file, bool success)
{
ASSERT(success);
if (!success) return;
ASSERT(file.getBuffer());
InputBlob blob(file.getBuffer(), (int)file.size());
#pragma pack(1)
struct Header
{
u32 magic;
int version;
u32 hash;
u32 engine_hash;
};
#pragma pack()
Header header;
blob.read(header);
if (crc32((const u8*)blob.getData() + sizeof(header), blob.getSize() - sizeof(header)) !=
header.hash)
{
g_log_error.log("App") << "Universe corrupted";
return;
}
bool deserialize_succeeded = m_engine->deserialize(*m_universe, blob);
if (!deserialize_succeeded)
{
g_log_error.log("App") << "Failed to deserialize universe";
}
}
void loadUniverse(const char* path)
{
auto& fs = m_engine->getFileSystem();
FS::ReadCallback file_read_cb;
file_read_cb.bind<App, &App::universeFileLoaded>(this);
fs.openAsync(fs.getDefaultDevice(), Path(path), FS::Mode::OPEN_AND_READ, file_read_cb);
}
void shutdown()
{
m_engine->destroyUniverse(*m_universe);
FS::FileSystem::destroy(m_file_system);
LUMIX_DELETE(m_allocator, m_disk_file_device);
LUMIX_DELETE(m_allocator, m_mem_file_device);
LUMIX_DELETE(m_allocator, m_pack_file_device);
Pipeline::destroy(m_pipeline);
Engine::destroy(m_engine, m_allocator);
m_engine = nullptr;
m_pipeline = nullptr;
m_universe = nullptr;
XCloseDisplay(m_display);
}
int getExitCode() const { return m_exit_code; }
/*
void handleRawInput(LPARAM lParam)
{
UINT dwSize;
char data[sizeof(RAWINPUT) * 10];
GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER));
if (dwSize > sizeof(data)) return;
if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, data, &dwSize, sizeof(RAWINPUTHEADER)) !=
dwSize) return;
RAWINPUT* raw = (RAWINPUT*)data;
if (raw->header.dwType == RIM_TYPEMOUSE &&
raw->data.mouse.usFlags == MOUSE_MOVE_RELATIVE)
{
POINT p;
GetCursorPos(&p);
ScreenToClient(m_hwnd, &p);
auto& input_system = m_engine->getInputSystem();
input_system.injectMouseXMove(float(raw->data.mouse.lLastX));
input_system.injectMouseYMove(float(raw->data.mouse.lLastY));
}
}
*/
void handleEvents()
{
XEvent e;
while (XPending(m_display) > 0)
{
XNextEvent(m_display, &e);
if (e.type == KeyPress) break;
}
}
static void outputToConsole(const char* system, const char* message)
{
printf("%s: %s\n", system, message);
}
void exit(int exit_code)
{
m_finished = true;
m_exit_code = exit_code;
}
void frame()
{
float frame_time = m_frame_timer->tick();
m_engine->update(*m_universe);
m_pipeline->render();
auto* renderer = m_engine->getPluginManager().getPlugin("renderer");
static_cast<Renderer*>(renderer)->frame(false);
m_engine->getFileSystem().updateAsyncTransactions();
if (frame_time < 1 / 60.0f)
{
PROFILE_BLOCK("sleep");
MT::sleep(u32(1000 / 60.0f - frame_time * 1000));
}
handleEvents();
}
void run()
{
m_finished = false;
while (!m_finished)
{
frame();
}
}
private:
DefaultAllocator m_allocator;
Engine* m_engine;
Universe* m_universe;
Pipeline* m_pipeline;
FS::FileSystem* m_file_system;
FS::MemoryFileDevice* m_mem_file_device;
FS::DiskFileDevice* m_disk_file_device;
FS::PackFileDevice* m_pack_file_device;
Timer* m_frame_timer;
bool m_finished;
int m_exit_code;
char m_startup_script_path[MAX_PATH_LENGTH];
char m_pipeline_path[MAX_PATH_LENGTH];
Display* m_display;
Window m_window;
static App* s_instance;
};
App* App::s_instance = nullptr;
}
int main(int argc, char* argv[])
{
Lumix::setCommandLine(argc, argv);
Lumix::App app;
app.init();
app.run();
app.shutdown();
return app.getExitCode();
}
<commit_msg>linux fix<commit_after>#include "engine/blob.h"
#include "engine/command_line_parser.h"
#include "engine/crc32.h"
#include "engine/fs/disk_file_device.h"
#include "engine/fs/file_system.h"
#include "engine/fs/file_system.h"
#include "engine/fs/memory_file_device.h"
#include "engine/fs/pack_file_device.h"
#include "engine/input_system.h"
#include "engine/log.h"
#include "engine/lua_wrapper.h"
#include "engine/mt/thread.h"
#include "engine/path_utils.h"
#include "engine/profiler.h"
#include "engine/resource_manager.h"
#include "engine/resource_manager_base.h"
#include "engine/system.h"
#include "engine/timer.h"
#include "engine/debug/debug.h"
#include "editor/gizmo.h"
#include "editor/world_editor.h"
#include "engine/engine.h"
#include "engine/plugin_manager.h"
#include "renderer/pipeline.h"
#include "renderer/renderer.h"
#include "renderer/texture.h"
#include "engine/universe/universe.h"
#include <cstdio>
#include <X11/Xlib.h>
namespace Lumix
{
struct App
{
App()
{
m_universe = nullptr;
m_exit_code = 0;
m_frame_timer = Timer::create(m_allocator);
ASSERT(!s_instance);
s_instance = this;
m_pipeline = nullptr;
}
~App()
{
Timer::destroy(m_frame_timer);
ASSERT(!m_universe);
s_instance = nullptr;
}
/*
LRESULT onMessage(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
switch (msg)
{
case WM_CLOSE: PostQuitMessage(0); break;
case WM_MOVE:
case WM_SIZE: onResize(); break;
case WM_QUIT: m_finished = true; break;
case WM_INPUT: handleRawInput(lparam); break;
}
return DefWindowProc(hwnd, msg, wparam, lparam);
}
static LRESULT CALLBACK msgProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
if (!s_instance || !s_instance->m_pipeline) return DefWindowProc(hwnd, msg, wparam, lparam);
return s_instance->onMessage(hwnd, msg, wparam, lparam);
}
void onResize()
{
RECT rect;
RECT screen_rect;
GetClientRect(m_hwnd, &rect);
GetWindowRect(m_hwnd, &screen_rect);
int w = rect.right - rect.left;
int h = rect.bottom - rect.top;
if (w > 0)
{
ClipCursor(&screen_rect);
m_pipeline->setViewport(0, 0, w, h);
Renderer* renderer =
static_cast<Renderer*>(m_engine->getPluginManager().getPlugin("renderer"));
renderer->resize(w, h);
}
}
*/
bool createWindow()
{
m_display = XOpenDisplay(nullptr);
if (!m_display) return false;
int s = DefaultScreen(m_display);
m_window = XCreateSimpleWindow(m_display, RootWindow(m_display, s), 10, 10, 100, 100, 1
, BlackPixel(m_display, s), WhitePixel(m_display, s));
XSelectInput(m_display, m_window, ExposureMask | KeyPressMask);
XMapWindow(m_display, m_window);
return true;
}
void init()
{
copyString(m_pipeline_path, "pipelines/app.lua");
copyString(m_startup_script_path, "startup.lua");
char cmd_line[1024];
getCommandLine(cmd_line, lengthOf(cmd_line));
CommandLineParser parser(cmd_line);
while (parser.next())
{
if (parser.currentEquals("-pipeline"))
{
if (!parser.next()) break;
parser.getCurrent(m_pipeline_path, lengthOf(m_pipeline_path));
}
else if(parser.currentEquals("-script"))
{
if (!parser.next()) break;
parser.getCurrent(m_startup_script_path, lengthOf(m_startup_script_path));
}
}
createWindow();
g_log_info.getCallback().bind<outputToConsole>();
g_log_warning.getCallback().bind<outputToConsole>();
g_log_error.getCallback().bind<outputToConsole>();
enableCrashReporting(false);
m_file_system = FS::FileSystem::create(m_allocator);
m_mem_file_device = LUMIX_NEW(m_allocator, FS::MemoryFileDevice)(m_allocator);
m_disk_file_device = LUMIX_NEW(m_allocator, FS::DiskFileDevice)("disk", "", m_allocator);
m_pack_file_device = LUMIX_NEW(m_allocator, FS::PackFileDevice)(m_allocator);
m_file_system->mount(m_mem_file_device);
m_file_system->mount(m_disk_file_device);
m_file_system->mount(m_pack_file_device);
m_pack_file_device->mount("data.pak");
m_file_system->setDefaultDevice("memory:disk:pack");
m_file_system->setSaveGameDevice("memory:disk");
m_engine = Engine::create("", "", m_file_system, m_allocator);
Engine::PlatformData platform_data;
platform_data.window_handle = (void*)(uintptr_t)m_window;
platform_data.display = m_display;
m_engine->setPlatformData(platform_data);
m_engine->getPluginManager().load("renderer");
m_engine->getPluginManager().load("animation");
m_engine->getPluginManager().load("audio");
m_engine->getPluginManager().load("lua_script");
m_engine->getPluginManager().load("physics");
m_engine->getInputSystem().enable(true);
Renderer* renderer = static_cast<Renderer*>(m_engine->getPluginManager().getPlugin("renderer"));
m_pipeline = Pipeline::create(*renderer, Path(m_pipeline_path), "APP", m_engine->getAllocator());
m_pipeline->load();
while (m_engine->getFileSystem().hasWork())
{
MT::sleep(100);
m_engine->getFileSystem().updateAsyncTransactions();
}
m_universe = &m_engine->createUniverse(true);
m_pipeline->setScene((RenderScene*)m_universe->getScene(crc32("renderer")));
m_pipeline->resize(600, 400);
renderer->resize(600, 400);
registerLuaAPI();
//while (ShowCursor(false) >= 0); // TODO
// onResize(); // TODO
}
void startupScriptLoaded(FS::IFile& file, bool success)
{
if (!success)
{
g_log_error.log("App") << "Could not open " << m_startup_script_path;
return;
}
m_engine->runScript((const char*)file.getBuffer(), (int)file.size(), m_startup_script_path);
}
void registerLuaAPI()
{
lua_State* L = m_engine->getState();
#define REGISTER_FUNCTION(F, name) \
do { \
auto* f = &LuaWrapper::wrapMethod<App, decltype(&App::F), &App::F>; \
LuaWrapper::createSystemFunction(L, "App", name, f); \
} while(false) \
REGISTER_FUNCTION(loadUniverse, "loadUniverse");
REGISTER_FUNCTION(frame, "frame");
REGISTER_FUNCTION(exit, "exit");
#undef REGISTER_FUNCTION
LuaWrapper::createSystemVariable(L, "App", "instance", this);
LuaWrapper::createSystemVariable(L, "App", "universe", m_universe);
auto& fs = m_engine->getFileSystem();
FS::ReadCallback cb;
cb.bind<App, &App::startupScriptLoaded>(this);
fs.openAsync(fs.getDefaultDevice(), Path(m_startup_script_path), FS::Mode::OPEN_AND_READ, cb);
}
void universeFileLoaded(FS::IFile& file, bool success)
{
ASSERT(success);
if (!success) return;
ASSERT(file.getBuffer());
InputBlob blob(file.getBuffer(), (int)file.size());
#pragma pack(1)
struct Header
{
u32 magic;
int version;
u32 hash;
u32 engine_hash;
};
#pragma pack()
Header header;
blob.read(header);
if (crc32((const u8*)blob.getData() + sizeof(header), blob.getSize() - sizeof(header)) !=
header.hash)
{
g_log_error.log("App") << "Universe corrupted";
return;
}
bool deserialize_succeeded = m_engine->deserialize(*m_universe, blob);
if (!deserialize_succeeded)
{
g_log_error.log("App") << "Failed to deserialize universe";
}
}
void loadUniverse(const char* path)
{
auto& fs = m_engine->getFileSystem();
FS::ReadCallback file_read_cb;
file_read_cb.bind<App, &App::universeFileLoaded>(this);
fs.openAsync(fs.getDefaultDevice(), Path(path), FS::Mode::OPEN_AND_READ, file_read_cb);
}
void shutdown()
{
m_engine->destroyUniverse(*m_universe);
FS::FileSystem::destroy(m_file_system);
LUMIX_DELETE(m_allocator, m_disk_file_device);
LUMIX_DELETE(m_allocator, m_mem_file_device);
LUMIX_DELETE(m_allocator, m_pack_file_device);
Pipeline::destroy(m_pipeline);
Engine::destroy(m_engine, m_allocator);
m_engine = nullptr;
m_pipeline = nullptr;
m_universe = nullptr;
XCloseDisplay(m_display);
}
int getExitCode() const { return m_exit_code; }
/*
void handleRawInput(LPARAM lParam)
{
UINT dwSize;
char data[sizeof(RAWINPUT) * 10];
GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER));
if (dwSize > sizeof(data)) return;
if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, data, &dwSize, sizeof(RAWINPUTHEADER)) !=
dwSize) return;
RAWINPUT* raw = (RAWINPUT*)data;
if (raw->header.dwType == RIM_TYPEMOUSE &&
raw->data.mouse.usFlags == MOUSE_MOVE_RELATIVE)
{
POINT p;
GetCursorPos(&p);
ScreenToClient(m_hwnd, &p);
auto& input_system = m_engine->getInputSystem();
input_system.injectMouseXMove(float(raw->data.mouse.lLastX));
input_system.injectMouseYMove(float(raw->data.mouse.lLastY));
}
}
*/
void handleEvents()
{
XEvent e;
while (XPending(m_display) > 0)
{
XNextEvent(m_display, &e);
if (e.type == KeyPress) break;
}
}
static void outputToConsole(const char* system, const char* message)
{
printf("%s: %s\n", system, message);
}
void exit(int exit_code)
{
m_finished = true;
m_exit_code = exit_code;
}
void frame()
{
float frame_time = m_frame_timer->tick();
m_engine->update(*m_universe);
m_pipeline->render();
auto* renderer = m_engine->getPluginManager().getPlugin("renderer");
static_cast<Renderer*>(renderer)->frame(false);
m_engine->getFileSystem().updateAsyncTransactions();
if (frame_time < 1 / 60.0f)
{
PROFILE_BLOCK("sleep");
MT::sleep(u32(1000 / 60.0f - frame_time * 1000));
}
handleEvents();
}
void run()
{
m_finished = false;
while (!m_finished)
{
frame();
}
}
private:
DefaultAllocator m_allocator;
Engine* m_engine;
Universe* m_universe;
Pipeline* m_pipeline;
FS::FileSystem* m_file_system;
FS::MemoryFileDevice* m_mem_file_device;
FS::DiskFileDevice* m_disk_file_device;
FS::PackFileDevice* m_pack_file_device;
Timer* m_frame_timer;
bool m_finished;
int m_exit_code;
char m_startup_script_path[MAX_PATH_LENGTH];
char m_pipeline_path[MAX_PATH_LENGTH];
Display* m_display;
Window m_window;
static App* s_instance;
};
App* App::s_instance = nullptr;
}
int main(int argc, char* argv[])
{
Lumix::setCommandLine(argc, argv);
Lumix::App app;
app.init();
app.run();
app.shutdown();
return app.getExitCode();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ignoreIterationMark_ja_JP.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-07 17:28:01 $
*
* 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
*
************************************************************************/
// prevent internal compiler error with MSVC6SP3
#include <utility>
#include <i18nutil/oneToOneMapping.hxx>
#define TRANSLITERATION_IterationMark_ja_JP
#include <transliteration_Ignore.hxx>
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace rtl;
namespace com { namespace sun { namespace star { namespace i18n {
OneToOneMappingTable_t ignoreIterationMark_ja_JP_mappingTable[] = {
MAKE_PAIR( 0x3046, 0x3094 ), // HIRAGANA LETTER U --> HIRAGANA LETTER VU
MAKE_PAIR( 0x304B, 0x304C ), // HIRAGANA LETTER KA --> HIRAGANA LETTER GA
MAKE_PAIR( 0x304D, 0x304E ), // HIRAGANA LETTER KI --> HIRAGANA LETTER GI
MAKE_PAIR( 0x304F, 0x3050 ), // HIRAGANA LETTER KU --> HIRAGANA LETTER GU
MAKE_PAIR( 0x3051, 0x3052 ), // HIRAGANA LETTER KE --> HIRAGANA LETTER GE
MAKE_PAIR( 0x3053, 0x3054 ), // HIRAGANA LETTER KO --> HIRAGANA LETTER GO
MAKE_PAIR( 0x3055, 0x3056 ), // HIRAGANA LETTER SA --> HIRAGANA LETTER ZA
MAKE_PAIR( 0x3057, 0x3058 ), // HIRAGANA LETTER SI --> HIRAGANA LETTER ZI
MAKE_PAIR( 0x3059, 0x305A ), // HIRAGANA LETTER SU --> HIRAGANA LETTER ZU
MAKE_PAIR( 0x305B, 0x305C ), // HIRAGANA LETTER SE --> HIRAGANA LETTER ZE
MAKE_PAIR( 0x305D, 0x305E ), // HIRAGANA LETTER SO --> HIRAGANA LETTER ZO
MAKE_PAIR( 0x305F, 0x3060 ), // HIRAGANA LETTER TA --> HIRAGANA LETTER DA
MAKE_PAIR( 0x3061, 0x3062 ), // HIRAGANA LETTER TI --> HIRAGANA LETTER DI
MAKE_PAIR( 0x3064, 0x3065 ), // HIRAGANA LETTER TU --> HIRAGANA LETTER DU
MAKE_PAIR( 0x3066, 0x3067 ), // HIRAGANA LETTER TE --> HIRAGANA LETTER DE
MAKE_PAIR( 0x3068, 0x3069 ), // HIRAGANA LETTER TO --> HIRAGANA LETTER DO
MAKE_PAIR( 0x306F, 0x3070 ), // HIRAGANA LETTER HA --> HIRAGANA LETTER BA
MAKE_PAIR( 0x3072, 0x3073 ), // HIRAGANA LETTER HI --> HIRAGANA LETTER BI
MAKE_PAIR( 0x3075, 0x3076 ), // HIRAGANA LETTER HU --> HIRAGANA LETTER BU
MAKE_PAIR( 0x3078, 0x3079 ), // HIRAGANA LETTER HE --> HIRAGANA LETTER BE
MAKE_PAIR( 0x307B, 0x307C ), // HIRAGANA LETTER HO --> HIRAGANA LETTER BO
MAKE_PAIR( 0x309D, 0x309E ), // HIRAGANA ITERATION MARK --> HIRAGANA VOICED ITERATION MARK
MAKE_PAIR( 0x30A6, 0x30F4 ), // KATAKANA LETTER U --> KATAKANA LETTER VU
MAKE_PAIR( 0x30AB, 0x30AC ), // KATAKANA LETTER KA --> KATAKANA LETTER GA
MAKE_PAIR( 0x30AD, 0x30AE ), // KATAKANA LETTER KI --> KATAKANA LETTER GI
MAKE_PAIR( 0x30AF, 0x30B0 ), // KATAKANA LETTER KU --> KATAKANA LETTER GU
MAKE_PAIR( 0x30B1, 0x30B2 ), // KATAKANA LETTER KE --> KATAKANA LETTER GE
MAKE_PAIR( 0x30B3, 0x30B4 ), // KATAKANA LETTER KO --> KATAKANA LETTER GO
MAKE_PAIR( 0x30B5, 0x30B6 ), // KATAKANA LETTER SA --> KATAKANA LETTER ZA
MAKE_PAIR( 0x30B7, 0x30B8 ), // KATAKANA LETTER SI --> KATAKANA LETTER ZI
MAKE_PAIR( 0x30B9, 0x30BA ), // KATAKANA LETTER SU --> KATAKANA LETTER ZU
MAKE_PAIR( 0x30BB, 0x30BC ), // KATAKANA LETTER SE --> KATAKANA LETTER ZE
MAKE_PAIR( 0x30BD, 0x30BE ), // KATAKANA LETTER SO --> KATAKANA LETTER ZO
MAKE_PAIR( 0x30BF, 0x30C0 ), // KATAKANA LETTER TA --> KATAKANA LETTER DA
MAKE_PAIR( 0x30C1, 0x30C2 ), // KATAKANA LETTER TI --> KATAKANA LETTER DI
MAKE_PAIR( 0x30C4, 0x30C5 ), // KATAKANA LETTER TU --> KATAKANA LETTER DU
MAKE_PAIR( 0x30C6, 0x30C7 ), // KATAKANA LETTER TE --> KATAKANA LETTER DE
MAKE_PAIR( 0x30C8, 0x30C9 ), // KATAKANA LETTER TO --> KATAKANA LETTER DO
MAKE_PAIR( 0x30CF, 0x30D0 ), // KATAKANA LETTER HA --> KATAKANA LETTER BA
MAKE_PAIR( 0x30D2, 0x30D3 ), // KATAKANA LETTER HI --> KATAKANA LETTER BI
MAKE_PAIR( 0x30D5, 0x30D6 ), // KATAKANA LETTER HU --> KATAKANA LETTER BU
MAKE_PAIR( 0x30D8, 0x30D9 ), // KATAKANA LETTER HE --> KATAKANA LETTER BE
MAKE_PAIR( 0x30DB, 0x30DC ), // KATAKANA LETTER HO --> KATAKANA LETTER BO
MAKE_PAIR( 0x30EF, 0x30F7 ), // KATAKANA LETTER WA --> KATAKANA LETTER VA
MAKE_PAIR( 0x30F0, 0x30F8 ), // KATAKANA LETTER WI --> KATAKANA LETTER VI
MAKE_PAIR( 0x30F1, 0x30F9 ), // KATAKANA LETTER WE --> KATAKANA LETTER VE
MAKE_PAIR( 0x30F2, 0x30FA ), // KATAKANA LETTER WO --> KATAKANA LETTER VO
MAKE_PAIR( 0x30FD, 0x30FE ) // KATAKANA ITERATION MARK --> KATAKANA VOICED ITERATION MARK
};
OUString SAL_CALL
ignoreIterationMark_ja_JP::folding( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset )
throw(RuntimeException)
{
oneToOneMapping table(ignoreIterationMark_ja_JP_mappingTable, sizeof(ignoreIterationMark_ja_JP_mappingTable));
// Create a string buffer which can hold nCount + 1 characters.
// The reference count is 0 now.
rtl_uString * newStr = x_rtl_uString_new_WithLength( nCount ); // defined in x_rtl_ustring.h
sal_Unicode * dst = newStr->buffer;
const sal_Unicode * src = inStr.getStr() + startPos;
sal_Int32 * p = 0;
sal_Int32 position = 0;
if (useOffset) {
// Allocate nCount length to offset argument.
offset.realloc( nCount );
p = offset.getArray();
position = startPos;
}
//
sal_Unicode previousChar = *src ++;
sal_Unicode currentChar;
// Conversion
while (-- nCount > 0) {
currentChar = *src ++;
switch ( currentChar ) {
case 0x30fd: // KATAKANA ITERATION MARK
case 0x309d: // HIRAGANA ITERATION MARK
case 0x3005: // IDEOGRAPHIC ITERATION MARK
currentChar = previousChar;
break;
case 0x30fe: // KATAKANA VOICED ITERATION MARK
case 0x309e: // HIRAGANA VOICED ITERATION MARK
currentChar = table[ previousChar ];
break;
}
if (useOffset)
*p ++ = position ++;
*dst ++ = previousChar;
previousChar = currentChar;
}
if (nCount == 0) {
if (useOffset)
*p = position;
*dst ++ = previousChar;
}
*dst = (sal_Unicode) 0;
newStr->length = sal_Int32(dst - newStr->buffer);
if (useOffset)
offset.realloc(newStr->length);
return OUString( newStr ); // defined in rtl/usrting. The reference count is increased from 0 to 1.
}
} } } }
<commit_msg>INTEGRATION: CWS warnings01 (1.9.14); FILE MERGED 2005/11/09 20:22:03 pl 1.9.14.1: #i53898# removed warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ignoreIterationMark_ja_JP.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2006-06-20 04:49:41 $
*
* 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
*
************************************************************************/
// prevent internal compiler error with MSVC6SP3
#include <utility>
#include <i18nutil/oneToOneMapping.hxx>
#define TRANSLITERATION_IterationMark_ja_JP
#include <transliteration_Ignore.hxx>
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace rtl;
namespace com { namespace sun { namespace star { namespace i18n {
OneToOneMappingTable_t ignoreIterationMark_ja_JP_mappingTable[] = {
MAKE_PAIR( 0x3046, 0x3094 ), // HIRAGANA LETTER U --> HIRAGANA LETTER VU
MAKE_PAIR( 0x304B, 0x304C ), // HIRAGANA LETTER KA --> HIRAGANA LETTER GA
MAKE_PAIR( 0x304D, 0x304E ), // HIRAGANA LETTER KI --> HIRAGANA LETTER GI
MAKE_PAIR( 0x304F, 0x3050 ), // HIRAGANA LETTER KU --> HIRAGANA LETTER GU
MAKE_PAIR( 0x3051, 0x3052 ), // HIRAGANA LETTER KE --> HIRAGANA LETTER GE
MAKE_PAIR( 0x3053, 0x3054 ), // HIRAGANA LETTER KO --> HIRAGANA LETTER GO
MAKE_PAIR( 0x3055, 0x3056 ), // HIRAGANA LETTER SA --> HIRAGANA LETTER ZA
MAKE_PAIR( 0x3057, 0x3058 ), // HIRAGANA LETTER SI --> HIRAGANA LETTER ZI
MAKE_PAIR( 0x3059, 0x305A ), // HIRAGANA LETTER SU --> HIRAGANA LETTER ZU
MAKE_PAIR( 0x305B, 0x305C ), // HIRAGANA LETTER SE --> HIRAGANA LETTER ZE
MAKE_PAIR( 0x305D, 0x305E ), // HIRAGANA LETTER SO --> HIRAGANA LETTER ZO
MAKE_PAIR( 0x305F, 0x3060 ), // HIRAGANA LETTER TA --> HIRAGANA LETTER DA
MAKE_PAIR( 0x3061, 0x3062 ), // HIRAGANA LETTER TI --> HIRAGANA LETTER DI
MAKE_PAIR( 0x3064, 0x3065 ), // HIRAGANA LETTER TU --> HIRAGANA LETTER DU
MAKE_PAIR( 0x3066, 0x3067 ), // HIRAGANA LETTER TE --> HIRAGANA LETTER DE
MAKE_PAIR( 0x3068, 0x3069 ), // HIRAGANA LETTER TO --> HIRAGANA LETTER DO
MAKE_PAIR( 0x306F, 0x3070 ), // HIRAGANA LETTER HA --> HIRAGANA LETTER BA
MAKE_PAIR( 0x3072, 0x3073 ), // HIRAGANA LETTER HI --> HIRAGANA LETTER BI
MAKE_PAIR( 0x3075, 0x3076 ), // HIRAGANA LETTER HU --> HIRAGANA LETTER BU
MAKE_PAIR( 0x3078, 0x3079 ), // HIRAGANA LETTER HE --> HIRAGANA LETTER BE
MAKE_PAIR( 0x307B, 0x307C ), // HIRAGANA LETTER HO --> HIRAGANA LETTER BO
MAKE_PAIR( 0x309D, 0x309E ), // HIRAGANA ITERATION MARK --> HIRAGANA VOICED ITERATION MARK
MAKE_PAIR( 0x30A6, 0x30F4 ), // KATAKANA LETTER U --> KATAKANA LETTER VU
MAKE_PAIR( 0x30AB, 0x30AC ), // KATAKANA LETTER KA --> KATAKANA LETTER GA
MAKE_PAIR( 0x30AD, 0x30AE ), // KATAKANA LETTER KI --> KATAKANA LETTER GI
MAKE_PAIR( 0x30AF, 0x30B0 ), // KATAKANA LETTER KU --> KATAKANA LETTER GU
MAKE_PAIR( 0x30B1, 0x30B2 ), // KATAKANA LETTER KE --> KATAKANA LETTER GE
MAKE_PAIR( 0x30B3, 0x30B4 ), // KATAKANA LETTER KO --> KATAKANA LETTER GO
MAKE_PAIR( 0x30B5, 0x30B6 ), // KATAKANA LETTER SA --> KATAKANA LETTER ZA
MAKE_PAIR( 0x30B7, 0x30B8 ), // KATAKANA LETTER SI --> KATAKANA LETTER ZI
MAKE_PAIR( 0x30B9, 0x30BA ), // KATAKANA LETTER SU --> KATAKANA LETTER ZU
MAKE_PAIR( 0x30BB, 0x30BC ), // KATAKANA LETTER SE --> KATAKANA LETTER ZE
MAKE_PAIR( 0x30BD, 0x30BE ), // KATAKANA LETTER SO --> KATAKANA LETTER ZO
MAKE_PAIR( 0x30BF, 0x30C0 ), // KATAKANA LETTER TA --> KATAKANA LETTER DA
MAKE_PAIR( 0x30C1, 0x30C2 ), // KATAKANA LETTER TI --> KATAKANA LETTER DI
MAKE_PAIR( 0x30C4, 0x30C5 ), // KATAKANA LETTER TU --> KATAKANA LETTER DU
MAKE_PAIR( 0x30C6, 0x30C7 ), // KATAKANA LETTER TE --> KATAKANA LETTER DE
MAKE_PAIR( 0x30C8, 0x30C9 ), // KATAKANA LETTER TO --> KATAKANA LETTER DO
MAKE_PAIR( 0x30CF, 0x30D0 ), // KATAKANA LETTER HA --> KATAKANA LETTER BA
MAKE_PAIR( 0x30D2, 0x30D3 ), // KATAKANA LETTER HI --> KATAKANA LETTER BI
MAKE_PAIR( 0x30D5, 0x30D6 ), // KATAKANA LETTER HU --> KATAKANA LETTER BU
MAKE_PAIR( 0x30D8, 0x30D9 ), // KATAKANA LETTER HE --> KATAKANA LETTER BE
MAKE_PAIR( 0x30DB, 0x30DC ), // KATAKANA LETTER HO --> KATAKANA LETTER BO
MAKE_PAIR( 0x30EF, 0x30F7 ), // KATAKANA LETTER WA --> KATAKANA LETTER VA
MAKE_PAIR( 0x30F0, 0x30F8 ), // KATAKANA LETTER WI --> KATAKANA LETTER VI
MAKE_PAIR( 0x30F1, 0x30F9 ), // KATAKANA LETTER WE --> KATAKANA LETTER VE
MAKE_PAIR( 0x30F2, 0x30FA ), // KATAKANA LETTER WO --> KATAKANA LETTER VO
MAKE_PAIR( 0x30FD, 0x30FE ) // KATAKANA ITERATION MARK --> KATAKANA VOICED ITERATION MARK
};
OUString SAL_CALL
ignoreIterationMark_ja_JP::folding( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, Sequence< sal_Int32 >& offset )
throw(RuntimeException)
{
oneToOneMapping aTable(ignoreIterationMark_ja_JP_mappingTable, sizeof(ignoreIterationMark_ja_JP_mappingTable));
// Create a string buffer which can hold nCount + 1 characters.
// The reference count is 0 now.
rtl_uString * newStr = x_rtl_uString_new_WithLength( nCount ); // defined in x_rtl_ustring.h
sal_Unicode * dst = newStr->buffer;
const sal_Unicode * src = inStr.getStr() + startPos;
sal_Int32 * p = 0;
sal_Int32 position = 0;
if (useOffset) {
// Allocate nCount length to offset argument.
offset.realloc( nCount );
p = offset.getArray();
position = startPos;
}
//
sal_Unicode previousChar = *src ++;
sal_Unicode currentChar;
// Conversion
while (-- nCount > 0) {
currentChar = *src ++;
switch ( currentChar ) {
case 0x30fd: // KATAKANA ITERATION MARK
case 0x309d: // HIRAGANA ITERATION MARK
case 0x3005: // IDEOGRAPHIC ITERATION MARK
currentChar = previousChar;
break;
case 0x30fe: // KATAKANA VOICED ITERATION MARK
case 0x309e: // HIRAGANA VOICED ITERATION MARK
currentChar = aTable[ previousChar ];
break;
}
if (useOffset)
*p ++ = position ++;
*dst ++ = previousChar;
previousChar = currentChar;
}
if (nCount == 0) {
if (useOffset)
*p = position;
*dst ++ = previousChar;
}
*dst = (sal_Unicode) 0;
newStr->length = sal_Int32(dst - newStr->buffer);
if (useOffset)
offset.realloc(newStr->length);
return OUString( newStr ); // defined in rtl/usrting. The reference count is increased from 0 to 1.
}
} } } }
<|endoftext|> |
<commit_before>// Copyright 2015 Open Source Robotics Foundation, 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 IMAGE_PIPELINE__IMAGE_VIEW_NODE_HPP_
#define IMAGE_PIPELINE__IMAGE_VIEW_NODE_HPP_
#include <sstream>
#include <string>
#include "opencv2/highgui/highgui.hpp"
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/image.hpp"
#include "common.hpp"
// Node which receives sensor_msgs/Image messages and renders them using OpenCV.
class ImageViewNode : public rclcpp::Node
{
public:
explicit ImageViewNode(
const std::string & input, const std::string & node_name = "image_view_node",
bool watermark = true)
: Node(node_name, rclcpp::NodeOptions().use_intra_process_comms(true))
{
// Create a subscription on the input topic.
sub_ = this->create_subscription<sensor_msgs::msg::Image>(
input,
rclcpp::SensorDataQoS(),
[node_name, watermark](const sensor_msgs::msg::Image::SharedPtr msg) {
// Create a cv::Mat from the image message (without copying).
cv::Mat cv_mat(
msg->height, msg->width,
encoding2mat_type(msg->encoding),
msg->data.data());
if (watermark) {
// Annotate with the pid and pointer address.
std::stringstream ss;
ss << "pid: " << GETPID() << ", ptr: " << msg.get();
draw_on_image(cv_mat, ss.str(), 60);
}
// Show the image.
cv::Mat c_mat = cv_mat;
cv::imshow(node_name.c_str(), c_mat);
char key = cv::waitKey(1); // Look for key presses.
if (key == 27 /* ESC */ || key == 'q') {
rclcpp::shutdown();
}
if (key == ' ') { // If <space> then pause until another <space>.
key = '\0';
while (key != ' ') {
key = cv::waitKey(1);
}
}
});
}
private:
rclcpp::Subscription<sensor_msgs::msg::Image>::SharedPtr sub_;
cv::VideoCapture cap_;
cv::Mat frame_;
};
#endif // IMAGE_PIPELINE__IMAGE_VIEW_NODE_HPP_
<commit_msg>allow ESC/q/sigint to exit demo (#345)<commit_after>// Copyright 2015 Open Source Robotics Foundation, 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 IMAGE_PIPELINE__IMAGE_VIEW_NODE_HPP_
#define IMAGE_PIPELINE__IMAGE_VIEW_NODE_HPP_
#include <sstream>
#include <string>
#include "opencv2/highgui/highgui.hpp"
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/image.hpp"
#include "common.hpp"
// Node which receives sensor_msgs/Image messages and renders them using OpenCV.
class ImageViewNode : public rclcpp::Node
{
public:
explicit ImageViewNode(
const std::string & input, const std::string & node_name = "image_view_node",
bool watermark = true)
: Node(node_name, rclcpp::NodeOptions().use_intra_process_comms(true))
{
// Create a subscription on the input topic.
sub_ = this->create_subscription<sensor_msgs::msg::Image>(
input,
rclcpp::SensorDataQoS(),
[node_name, watermark](const sensor_msgs::msg::Image::SharedPtr msg) {
// Create a cv::Mat from the image message (without copying).
cv::Mat cv_mat(
msg->height, msg->width,
encoding2mat_type(msg->encoding),
msg->data.data());
if (watermark) {
// Annotate with the pid and pointer address.
std::stringstream ss;
ss << "pid: " << GETPID() << ", ptr: " << msg.get();
draw_on_image(cv_mat, ss.str(), 60);
}
// Show the image.
cv::Mat c_mat = cv_mat;
cv::imshow(node_name.c_str(), c_mat);
char key = cv::waitKey(1); // Look for key presses.
if (key == 27 /* ESC */ || key == 'q') {
rclcpp::shutdown();
}
if (key == ' ') { // If <space> then pause until another <space>.
key = '\0';
while (key != ' ') {
key = cv::waitKey(1);
if (key == 27 /* ESC */ || key == 'q') {
rclcpp::shutdown();
}
if (!rclcpp::ok()) {
break;
}
}
}
});
}
private:
rclcpp::Subscription<sensor_msgs::msg::Image>::SharedPtr sub_;
cv::VideoCapture cap_;
cv::Mat frame_;
};
#endif // IMAGE_PIPELINE__IMAGE_VIEW_NODE_HPP_
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2018 ARM Limited
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright 2015 LabWare
* Copyright 2014 Google, Inc.
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __REMOTE_GDB_HH__
#define __REMOTE_GDB_HH__
#include <sys/signal.h>
#include <exception>
#include <map>
#include <string>
#include "arch/types.hh"
#include "base/intmath.hh"
#include "base/pollevent.hh"
#include "base/socket.hh"
#include "cpu/pc_event.hh"
class System;
class ThreadContext;
class BaseRemoteGDB;
class HardBreakpoint;
/**
* Concrete subclasses of this abstract class represent how the
* register values are transmitted on the wire. Usually each
* architecture should define one subclass, but there can be more
* if there is more than one possible wire format. For example,
* ARM defines both AArch32GdbRegCache and AArch64GdbRegCache.
*/
class BaseGdbRegCache
{
public:
/**
* Return the pointer to the raw bytes buffer containing the
* register values. Each byte of this buffer is literally
* encoded as two hex digits in the g or G RSP packet.
*/
virtual char *data() const = 0;
/**
* Return the size of the raw buffer, in bytes
* (i.e., half of the number of digits in the g/G packet).
*/
virtual size_t size() const = 0;
/**
* Fill the raw buffer from the registers in the ThreadContext.
*/
virtual void getRegs(ThreadContext*) = 0;
/**
* Set the ThreadContext's registers from the values
* in the raw buffer.
*/
virtual void setRegs(ThreadContext*) const = 0;
/**
* Return the name to use in places like DPRINTF.
* Having each concrete superclass redefine this member
* is useful in situations where the class of the regCache
* can change on the fly.
*/
virtual const std::string name() const = 0;
BaseGdbRegCache(BaseRemoteGDB *g) : gdb(g)
{}
virtual ~BaseGdbRegCache()
{}
protected:
BaseRemoteGDB *gdb;
};
class BaseRemoteGDB
{
friend class HardBreakpoint;
public:
/*
* Interface to other parts of the simulator.
*/
BaseRemoteGDB(System *system, ThreadContext *context, int _port);
virtual ~BaseRemoteGDB();
std::string name();
void listen();
void connect();
int port() const;
void attach(int fd);
void detach();
bool isAttached() { return attached; }
void replaceThreadContext(ThreadContext *_tc) { tc = _tc; }
bool trap(int type);
bool breakpoint() { return trap(SIGTRAP); }
private:
/*
* Connection to the external GDB.
*/
void incomingData(int revent);
void connectWrapper(int revent) { connect(); }
template <void (BaseRemoteGDB::*F)(int revent)>
class SocketEvent : public PollEvent
{
protected:
BaseRemoteGDB *gdb;
public:
SocketEvent(BaseRemoteGDB *gdb, int fd, int e) :
PollEvent(fd, e), gdb(gdb)
{}
void process(int revent) { (gdb->*F)(revent); }
};
typedef SocketEvent<&BaseRemoteGDB::connectWrapper> ConnectEvent;
typedef SocketEvent<&BaseRemoteGDB::incomingData> DataEvent;
friend ConnectEvent;
friend DataEvent;
ConnectEvent *connectEvent;
DataEvent *dataEvent;
ListenSocket listener;
int _port;
// The socket commands come in through.
int fd;
// Transfer data to/from GDB.
uint8_t getbyte();
void putbyte(uint8_t b);
void recv(std::vector<char> &bp);
void send(const char *data);
/*
* Simulator side debugger state.
*/
bool active;
bool attached;
System *sys;
ThreadContext *tc;
BaseGdbRegCache *regCachePtr;
class TrapEvent : public Event
{
protected:
int _type;
BaseRemoteGDB *gdb;
public:
TrapEvent(BaseRemoteGDB *g) : gdb(g)
{}
void type(int t) { _type = t; }
void process() { gdb->trap(_type); }
} trapEvent;
/*
* The interface to the simulated system.
*/
// Machine memory.
bool read(Addr addr, size_t size, char *data);
bool write(Addr addr, size_t size, const char *data);
template <class T> T read(Addr addr);
template <class T> void write(Addr addr, T data);
// Single step.
void singleStep();
EventWrapper<BaseRemoteGDB, &BaseRemoteGDB::singleStep> singleStepEvent;
void clearSingleStep();
void setSingleStep();
/// Schedule an event which will be triggered "delta" instructions later.
void scheduleInstCommitEvent(Event *ev, int delta);
/// Deschedule an instruction count based event.
void descheduleInstCommitEvent(Event *ev);
// Breakpoints.
void insertSoftBreak(Addr addr, size_t len);
void removeSoftBreak(Addr addr, size_t len);
void insertHardBreak(Addr addr, size_t len);
void removeHardBreak(Addr addr, size_t len);
void clearTempBreakpoint(Addr &bkpt);
void setTempBreakpoint(Addr bkpt);
/*
* GDB commands.
*/
struct GdbCommand
{
public:
struct Context
{
const GdbCommand *cmd;
char cmd_byte;
int type;
char *data;
int len;
};
typedef bool (BaseRemoteGDB::*Func)(Context &ctx);
const char * const name;
const Func func;
GdbCommand(const char *_name, Func _func) : name(_name), func(_func) {}
};
static std::map<char, GdbCommand> command_map;
bool cmd_unsupported(GdbCommand::Context &ctx);
bool cmd_signal(GdbCommand::Context &ctx);
bool cmd_cont(GdbCommand::Context &ctx);
bool cmd_async_cont(GdbCommand::Context &ctx);
bool cmd_detach(GdbCommand::Context &ctx);
bool cmd_reg_r(GdbCommand::Context &ctx);
bool cmd_reg_w(GdbCommand::Context &ctx);
bool cmd_set_thread(GdbCommand::Context &ctx);
bool cmd_mem_r(GdbCommand::Context &ctx);
bool cmd_mem_w(GdbCommand::Context &ctx);
bool cmd_query_var(GdbCommand::Context &ctx);
bool cmd_step(GdbCommand::Context &ctx);
bool cmd_async_step(GdbCommand::Context &ctx);
bool cmd_clr_hw_bkpt(GdbCommand::Context &ctx);
bool cmd_set_hw_bkpt(GdbCommand::Context &ctx);
protected:
ThreadContext *context() { return tc; }
System *system() { return sys; }
void encodeBinaryData(const std::string &unencoded,
std::string &encoded) const;
void encodeXferResponse(const std::string &unencoded,
std::string &encoded, size_t offset, size_t unencoded_length) const;
// To be implemented by subclasses.
virtual bool checkBpLen(size_t len);
virtual BaseGdbRegCache *gdbRegs() = 0;
virtual bool acc(Addr addr, size_t len) = 0;
virtual std::vector<std::string> availableFeatures() const;
/**
* Get an XML target description.
*
* @param[in] annex the XML filename
* @param[out] output set to the decoded XML
* @return true if the given annex was found
*/
virtual bool getXferFeaturesRead(const std::string &annex,
std::string &output);
};
template <class T>
inline T
BaseRemoteGDB::read(Addr addr)
{
T temp;
read(addr, sizeof(T), (char *)&temp);
return temp;
}
template <class T>
inline void
BaseRemoteGDB::write(Addr addr, T data)
{
write(addr, sizeof(T), (const char *)&data);
}
#endif /* __REMOTE_GDB_H__ */
<commit_msg>base: Tag API methods in remote_gdb.hh<commit_after>/*
* Copyright (c) 2018 ARM Limited
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright 2015 LabWare
* Copyright 2014 Google, Inc.
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __REMOTE_GDB_HH__
#define __REMOTE_GDB_HH__
#include <sys/signal.h>
#include <exception>
#include <map>
#include <string>
#include "arch/types.hh"
#include "base/intmath.hh"
#include "base/pollevent.hh"
#include "base/socket.hh"
#include "cpu/pc_event.hh"
class System;
class ThreadContext;
class BaseRemoteGDB;
class HardBreakpoint;
/**
* Concrete subclasses of this abstract class represent how the
* register values are transmitted on the wire. Usually each
* architecture should define one subclass, but there can be more
* if there is more than one possible wire format. For example,
* ARM defines both AArch32GdbRegCache and AArch64GdbRegCache.
*/
class BaseGdbRegCache
{
public:
/**
* Return the pointer to the raw bytes buffer containing the
* register values. Each byte of this buffer is literally
* encoded as two hex digits in the g or G RSP packet.
*
* @ingroup api_remote_gdb
*/
virtual char *data() const = 0;
/**
* Return the size of the raw buffer, in bytes
* (i.e., half of the number of digits in the g/G packet).
*
* @ingroup api_remote_gdb
*/
virtual size_t size() const = 0;
/**
* Fill the raw buffer from the registers in the ThreadContext.
*
* @ingroup api_remote_gdb
*/
virtual void getRegs(ThreadContext*) = 0;
/**
* Set the ThreadContext's registers from the values
* in the raw buffer.
*
* @ingroup api_remote_gdb
*/
virtual void setRegs(ThreadContext*) const = 0;
/**
* Return the name to use in places like DPRINTF.
* Having each concrete superclass redefine this member
* is useful in situations where the class of the regCache
* can change on the fly.
*
* @ingroup api_remote_gdb
*/
virtual const std::string name() const = 0;
/**
* @ingroup api_remote_gdb
*/
BaseGdbRegCache(BaseRemoteGDB *g) : gdb(g)
{}
virtual ~BaseGdbRegCache()
{}
protected:
BaseRemoteGDB *gdb;
};
class BaseRemoteGDB
{
friend class HardBreakpoint;
public:
/**
* @ingroup api_remote_gdb
* @{
*/
/**
* Interface to other parts of the simulator.
*/
BaseRemoteGDB(System *system, ThreadContext *context, int _port);
virtual ~BaseRemoteGDB();
std::string name();
void listen();
void connect();
int port() const;
void attach(int fd);
void detach();
bool isAttached() { return attached; }
void replaceThreadContext(ThreadContext *_tc) { tc = _tc; }
bool trap(int type);
bool breakpoint() { return trap(SIGTRAP); }
/** @} */ // end of api_remote_gdb
private:
/*
* Connection to the external GDB.
*/
void incomingData(int revent);
void connectWrapper(int revent) { connect(); }
template <void (BaseRemoteGDB::*F)(int revent)>
class SocketEvent : public PollEvent
{
protected:
BaseRemoteGDB *gdb;
public:
SocketEvent(BaseRemoteGDB *gdb, int fd, int e) :
PollEvent(fd, e), gdb(gdb)
{}
void process(int revent) { (gdb->*F)(revent); }
};
typedef SocketEvent<&BaseRemoteGDB::connectWrapper> ConnectEvent;
typedef SocketEvent<&BaseRemoteGDB::incomingData> DataEvent;
friend ConnectEvent;
friend DataEvent;
ConnectEvent *connectEvent;
DataEvent *dataEvent;
ListenSocket listener;
int _port;
// The socket commands come in through.
int fd;
// Transfer data to/from GDB.
uint8_t getbyte();
void putbyte(uint8_t b);
void recv(std::vector<char> &bp);
void send(const char *data);
/*
* Simulator side debugger state.
*/
bool active;
bool attached;
System *sys;
ThreadContext *tc;
BaseGdbRegCache *regCachePtr;
class TrapEvent : public Event
{
protected:
int _type;
BaseRemoteGDB *gdb;
public:
TrapEvent(BaseRemoteGDB *g) : gdb(g)
{}
void type(int t) { _type = t; }
void process() { gdb->trap(_type); }
} trapEvent;
/*
* The interface to the simulated system.
*/
// Machine memory.
bool read(Addr addr, size_t size, char *data);
bool write(Addr addr, size_t size, const char *data);
template <class T> T read(Addr addr);
template <class T> void write(Addr addr, T data);
// Single step.
void singleStep();
EventWrapper<BaseRemoteGDB, &BaseRemoteGDB::singleStep> singleStepEvent;
void clearSingleStep();
void setSingleStep();
/// Schedule an event which will be triggered "delta" instructions later.
void scheduleInstCommitEvent(Event *ev, int delta);
/// Deschedule an instruction count based event.
void descheduleInstCommitEvent(Event *ev);
// Breakpoints.
void insertSoftBreak(Addr addr, size_t len);
void removeSoftBreak(Addr addr, size_t len);
void insertHardBreak(Addr addr, size_t len);
void removeHardBreak(Addr addr, size_t len);
void clearTempBreakpoint(Addr &bkpt);
void setTempBreakpoint(Addr bkpt);
/*
* GDB commands.
*/
struct GdbCommand
{
public:
struct Context
{
const GdbCommand *cmd;
char cmd_byte;
int type;
char *data;
int len;
};
typedef bool (BaseRemoteGDB::*Func)(Context &ctx);
const char * const name;
const Func func;
GdbCommand(const char *_name, Func _func) : name(_name), func(_func) {}
};
static std::map<char, GdbCommand> command_map;
bool cmd_unsupported(GdbCommand::Context &ctx);
bool cmd_signal(GdbCommand::Context &ctx);
bool cmd_cont(GdbCommand::Context &ctx);
bool cmd_async_cont(GdbCommand::Context &ctx);
bool cmd_detach(GdbCommand::Context &ctx);
bool cmd_reg_r(GdbCommand::Context &ctx);
bool cmd_reg_w(GdbCommand::Context &ctx);
bool cmd_set_thread(GdbCommand::Context &ctx);
bool cmd_mem_r(GdbCommand::Context &ctx);
bool cmd_mem_w(GdbCommand::Context &ctx);
bool cmd_query_var(GdbCommand::Context &ctx);
bool cmd_step(GdbCommand::Context &ctx);
bool cmd_async_step(GdbCommand::Context &ctx);
bool cmd_clr_hw_bkpt(GdbCommand::Context &ctx);
bool cmd_set_hw_bkpt(GdbCommand::Context &ctx);
protected:
ThreadContext *context() { return tc; }
System *system() { return sys; }
void encodeBinaryData(const std::string &unencoded,
std::string &encoded) const;
void encodeXferResponse(const std::string &unencoded,
std::string &encoded, size_t offset, size_t unencoded_length) const;
// To be implemented by subclasses.
virtual bool checkBpLen(size_t len);
virtual BaseGdbRegCache *gdbRegs() = 0;
virtual bool acc(Addr addr, size_t len) = 0;
virtual std::vector<std::string> availableFeatures() const;
/**
* Get an XML target description.
*
* @param[in] annex the XML filename
* @param[out] output set to the decoded XML
* @return true if the given annex was found
*/
virtual bool getXferFeaturesRead(const std::string &annex,
std::string &output);
};
template <class T>
inline T
BaseRemoteGDB::read(Addr addr)
{
T temp;
read(addr, sizeof(T), (char *)&temp);
return temp;
}
template <class T>
inline void
BaseRemoteGDB::write(Addr addr, T data)
{
write(addr, sizeof(T), (const char *)&data);
}
#endif /* __REMOTE_GDB_H__ */
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2016 ScyllaDB
*/
#pragma once
#include <seastar/core/file.hh>
#include <seastar/core/shared_ptr.hh>
#include <deque>
#include <atomic>
namespace seastar {
class io_queue;
namespace internal {
// Given a properly aligned vector of iovecs, ensures that it respects the
// IOV_MAX limit, by trimming if necessary. The modified vector still satisfied
// the alignment requirements.
// Returns the final total length of all iovecs.
size_t sanitize_iovecs(std::vector<iovec>& iov, size_t disk_alignment) noexcept;
}
class posix_file_handle_impl : public seastar::file_handle_impl {
int _fd;
std::atomic<unsigned>* _refcount;
dev_t _device_id;
open_flags _open_flags;
uint32_t _memory_dma_alignment;
uint32_t _disk_read_dma_alignment;
uint32_t _disk_write_dma_alignment;
public:
posix_file_handle_impl(int fd, open_flags f, std::atomic<unsigned>* refcount, dev_t device_id,
uint32_t memory_dma_alignment,
uint32_t disk_read_dma_alignment,
uint32_t disk_write_dma_alignment)
: _fd(fd), _refcount(refcount), _device_id(device_id), _open_flags(f)
, _memory_dma_alignment(memory_dma_alignment)
, _disk_read_dma_alignment(disk_read_dma_alignment)
, _disk_write_dma_alignment(disk_write_dma_alignment) {
}
virtual ~posix_file_handle_impl();
posix_file_handle_impl(const posix_file_handle_impl&) = delete;
posix_file_handle_impl(posix_file_handle_impl&&) = delete;
virtual shared_ptr<file_impl> to_file() && override;
virtual std::unique_ptr<seastar::file_handle_impl> clone() const override;
};
class posix_file_impl : public file_impl {
std::atomic<unsigned>* _refcount = nullptr;
dev_t _device_id;
io_queue* _io_queue;
open_flags _open_flags;
public:
int _fd;
posix_file_impl(int fd, open_flags, file_open_options options, dev_t device_id,
uint32_t block_size);
posix_file_impl(int fd, open_flags, std::atomic<unsigned>* refcount, dev_t device_id,
uint32_t memory_dma_alignment,
uint32_t disk_read_dma_alignment,
uint32_t disk_write_dma_alignment);
virtual ~posix_file_impl() override;
future<size_t> write_dma(uint64_t pos, const void* buffer, size_t len, const io_priority_class& pc) noexcept override;
future<size_t> write_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) noexcept override;
future<size_t> read_dma(uint64_t pos, void* buffer, size_t len, const io_priority_class& pc) noexcept override;
future<size_t> read_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) noexcept override;
future<> flush(void) noexcept override;
future<struct stat> stat(void) noexcept override;
future<> truncate(uint64_t length) noexcept override;
future<> discard(uint64_t offset, uint64_t length) noexcept override;
virtual future<> allocate(uint64_t position, uint64_t length) noexcept override;
future<uint64_t> size() noexcept override;
virtual future<> close() noexcept override;
virtual std::unique_ptr<seastar::file_handle_impl> dup() override;
virtual subscription<directory_entry> list_directory(std::function<future<> (directory_entry de)> next) override;
virtual future<temporary_buffer<uint8_t>> dma_read_bulk(uint64_t offset, size_t range_size, const io_priority_class& pc) noexcept override;
open_flags flags() const {
return _open_flags;
}
private:
void query_dma_alignment(uint32_t block_size);
/**
* Try to read from the given position where the previous short read has
* stopped. Check the EOF condition.
*
* The below code assumes the following: short reads due to I/O errors
* always end at address aligned to HW block boundary. Therefore if we issue
* a new read operation from the next position we are promised to get an
* error (different from EINVAL). If we've got a short read because we have
* reached EOF then the above read would either return a zero-length success
* (if the file size is aligned to HW block size) or an EINVAL error (if
* file length is not aligned to HW block size).
*
* @param pos offset to read from
* @param len number of bytes to read
* @param pc the IO priority class under which to queue this operation
*
* @return temporary buffer with read data or zero-sized temporary buffer if
* pos is at or beyond EOF.
* @throw appropriate exception in case of I/O error.
*/
future<temporary_buffer<uint8_t>>
read_maybe_eof(uint64_t pos, size_t len, const io_priority_class& pc);
};
// The Linux XFS implementation is challenged wrt. append: a write that changes
// eof will be blocked by any other concurrent AIO operation to the same file, whether
// it changes file size or not. Furthermore, ftruncate() will also block and be blocked
// by AIO, so attempts to game the system and call ftruncate() have to be done very carefully.
//
// Other Linux filesystems may have different locking rules, so this may need to be
// adjusted for them.
class append_challenged_posix_file_impl : public posix_file_impl, public enable_shared_from_this<append_challenged_posix_file_impl> {
// File size as a result of completed kernel operations (writes and truncates)
uint64_t _committed_size;
// File size as a result of seastar API calls
uint64_t _logical_size;
// Pending operations
enum class opcode {
invalid,
read,
write,
truncate,
flush,
};
struct op {
opcode type;
uint64_t pos;
size_t len;
std::function<future<> ()> run;
};
// Queue of pending operations; processed from front to end to avoid
// starvation, but can issue concurrent operations.
std::deque<op> _q;
unsigned _max_size_changing_ops = 0;
unsigned _current_non_size_changing_ops = 0;
unsigned _current_size_changing_ops = 0;
bool _fsync_is_exclusive = true;
// Set when the user is closing the file
enum class state { open, draining, closing, closed };
state _closing_state = state::open;
bool _sloppy_size = false;
uint64_t _sloppy_size_hint;
// Fulfiled when _done and I/O is complete
promise<> _completed;
private:
void commit_size(uint64_t size) noexcept;
bool must_run_alone(const op& candidate) const noexcept;
bool size_changing(const op& candidate) const noexcept;
bool may_dispatch(const op& candidate) const noexcept;
void dispatch(op& candidate) noexcept;
void optimize_queue() noexcept;
void process_queue() noexcept;
bool may_quit() const noexcept;
void enqueue_op(op&& op);
template <typename... T, typename Func>
future<T...> enqueue(opcode type, uint64_t pos, size_t len, Func&& func) noexcept {
try {
auto pr = make_lw_shared(promise<T...>());
auto fut = pr->get_future();
auto op_func = [func = std::move(func), pr = std::move(pr)] () mutable {
return futurize_invoke(std::move(func)).then_wrapped([pr = std::move(pr)] (future<T...> f) mutable {
f.forward_to(std::move(*pr));
});
};
enqueue_op({type, pos, len, op_func});
return fut;
} catch (...) {
return make_exception_future<T...>(std::current_exception());
}
}
public:
append_challenged_posix_file_impl(int fd, open_flags, file_open_options options, unsigned max_size_changing_ops, bool fsync_is_exclusive, dev_t device_id, size_t block_size);
~append_challenged_posix_file_impl() override;
future<size_t> read_dma(uint64_t pos, void* buffer, size_t len, const io_priority_class& pc) noexcept override;
future<size_t> read_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) noexcept override;
future<size_t> write_dma(uint64_t pos, const void* buffer, size_t len, const io_priority_class& pc) noexcept override;
future<size_t> write_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) noexcept override;
future<> flush() noexcept override;
future<struct stat> stat() noexcept override;
future<> truncate(uint64_t length) noexcept override;
future<uint64_t> size() noexcept override;
future<> close() noexcept override;
};
class blockdev_file_impl : public posix_file_impl {
public:
blockdev_file_impl(int fd, open_flags, file_open_options options, dev_t device_id, size_t block_size);
future<> truncate(uint64_t length) noexcept override;
future<> discard(uint64_t offset, uint64_t length) noexcept override;
future<uint64_t> size() noexcept override;
virtual future<> allocate(uint64_t position, uint64_t length) noexcept override;
};
}
<commit_msg>append-challenged-file: Switch onto noncopyable function<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright 2016 ScyllaDB
*/
#pragma once
#include <seastar/core/file.hh>
#include <seastar/core/shared_ptr.hh>
#include <deque>
#include <atomic>
namespace seastar {
class io_queue;
namespace internal {
// Given a properly aligned vector of iovecs, ensures that it respects the
// IOV_MAX limit, by trimming if necessary. The modified vector still satisfied
// the alignment requirements.
// Returns the final total length of all iovecs.
size_t sanitize_iovecs(std::vector<iovec>& iov, size_t disk_alignment) noexcept;
}
class posix_file_handle_impl : public seastar::file_handle_impl {
int _fd;
std::atomic<unsigned>* _refcount;
dev_t _device_id;
open_flags _open_flags;
uint32_t _memory_dma_alignment;
uint32_t _disk_read_dma_alignment;
uint32_t _disk_write_dma_alignment;
public:
posix_file_handle_impl(int fd, open_flags f, std::atomic<unsigned>* refcount, dev_t device_id,
uint32_t memory_dma_alignment,
uint32_t disk_read_dma_alignment,
uint32_t disk_write_dma_alignment)
: _fd(fd), _refcount(refcount), _device_id(device_id), _open_flags(f)
, _memory_dma_alignment(memory_dma_alignment)
, _disk_read_dma_alignment(disk_read_dma_alignment)
, _disk_write_dma_alignment(disk_write_dma_alignment) {
}
virtual ~posix_file_handle_impl();
posix_file_handle_impl(const posix_file_handle_impl&) = delete;
posix_file_handle_impl(posix_file_handle_impl&&) = delete;
virtual shared_ptr<file_impl> to_file() && override;
virtual std::unique_ptr<seastar::file_handle_impl> clone() const override;
};
class posix_file_impl : public file_impl {
std::atomic<unsigned>* _refcount = nullptr;
dev_t _device_id;
io_queue* _io_queue;
open_flags _open_flags;
public:
int _fd;
posix_file_impl(int fd, open_flags, file_open_options options, dev_t device_id,
uint32_t block_size);
posix_file_impl(int fd, open_flags, std::atomic<unsigned>* refcount, dev_t device_id,
uint32_t memory_dma_alignment,
uint32_t disk_read_dma_alignment,
uint32_t disk_write_dma_alignment);
virtual ~posix_file_impl() override;
future<size_t> write_dma(uint64_t pos, const void* buffer, size_t len, const io_priority_class& pc) noexcept override;
future<size_t> write_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) noexcept override;
future<size_t> read_dma(uint64_t pos, void* buffer, size_t len, const io_priority_class& pc) noexcept override;
future<size_t> read_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) noexcept override;
future<> flush(void) noexcept override;
future<struct stat> stat(void) noexcept override;
future<> truncate(uint64_t length) noexcept override;
future<> discard(uint64_t offset, uint64_t length) noexcept override;
virtual future<> allocate(uint64_t position, uint64_t length) noexcept override;
future<uint64_t> size() noexcept override;
virtual future<> close() noexcept override;
virtual std::unique_ptr<seastar::file_handle_impl> dup() override;
virtual subscription<directory_entry> list_directory(std::function<future<> (directory_entry de)> next) override;
virtual future<temporary_buffer<uint8_t>> dma_read_bulk(uint64_t offset, size_t range_size, const io_priority_class& pc) noexcept override;
open_flags flags() const {
return _open_flags;
}
private:
void query_dma_alignment(uint32_t block_size);
/**
* Try to read from the given position where the previous short read has
* stopped. Check the EOF condition.
*
* The below code assumes the following: short reads due to I/O errors
* always end at address aligned to HW block boundary. Therefore if we issue
* a new read operation from the next position we are promised to get an
* error (different from EINVAL). If we've got a short read because we have
* reached EOF then the above read would either return a zero-length success
* (if the file size is aligned to HW block size) or an EINVAL error (if
* file length is not aligned to HW block size).
*
* @param pos offset to read from
* @param len number of bytes to read
* @param pc the IO priority class under which to queue this operation
*
* @return temporary buffer with read data or zero-sized temporary buffer if
* pos is at or beyond EOF.
* @throw appropriate exception in case of I/O error.
*/
future<temporary_buffer<uint8_t>>
read_maybe_eof(uint64_t pos, size_t len, const io_priority_class& pc);
};
// The Linux XFS implementation is challenged wrt. append: a write that changes
// eof will be blocked by any other concurrent AIO operation to the same file, whether
// it changes file size or not. Furthermore, ftruncate() will also block and be blocked
// by AIO, so attempts to game the system and call ftruncate() have to be done very carefully.
//
// Other Linux filesystems may have different locking rules, so this may need to be
// adjusted for them.
class append_challenged_posix_file_impl : public posix_file_impl, public enable_shared_from_this<append_challenged_posix_file_impl> {
// File size as a result of completed kernel operations (writes and truncates)
uint64_t _committed_size;
// File size as a result of seastar API calls
uint64_t _logical_size;
// Pending operations
enum class opcode {
invalid,
read,
write,
truncate,
flush,
};
struct op {
opcode type;
uint64_t pos;
size_t len;
noncopyable_function<future<> ()> run;
};
// Queue of pending operations; processed from front to end to avoid
// starvation, but can issue concurrent operations.
std::deque<op> _q;
unsigned _max_size_changing_ops = 0;
unsigned _current_non_size_changing_ops = 0;
unsigned _current_size_changing_ops = 0;
bool _fsync_is_exclusive = true;
// Set when the user is closing the file
enum class state { open, draining, closing, closed };
state _closing_state = state::open;
bool _sloppy_size = false;
uint64_t _sloppy_size_hint;
// Fulfiled when _done and I/O is complete
promise<> _completed;
private:
void commit_size(uint64_t size) noexcept;
bool must_run_alone(const op& candidate) const noexcept;
bool size_changing(const op& candidate) const noexcept;
bool may_dispatch(const op& candidate) const noexcept;
void dispatch(op& candidate) noexcept;
void optimize_queue() noexcept;
void process_queue() noexcept;
bool may_quit() const noexcept;
void enqueue_op(op&& op);
template <typename... T, typename Func>
future<T...> enqueue(opcode type, uint64_t pos, size_t len, Func&& func) noexcept {
try {
auto pr = make_lw_shared(promise<T...>());
auto fut = pr->get_future();
auto op_func = [func = std::move(func), pr = std::move(pr)] () mutable {
return futurize_invoke(std::move(func)).then_wrapped([pr = std::move(pr)] (future<T...> f) mutable {
f.forward_to(std::move(*pr));
});
};
enqueue_op({type, pos, len, std::move(op_func)});
return fut;
} catch (...) {
return make_exception_future<T...>(std::current_exception());
}
}
public:
append_challenged_posix_file_impl(int fd, open_flags, file_open_options options, unsigned max_size_changing_ops, bool fsync_is_exclusive, dev_t device_id, size_t block_size);
~append_challenged_posix_file_impl() override;
future<size_t> read_dma(uint64_t pos, void* buffer, size_t len, const io_priority_class& pc) noexcept override;
future<size_t> read_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) noexcept override;
future<size_t> write_dma(uint64_t pos, const void* buffer, size_t len, const io_priority_class& pc) noexcept override;
future<size_t> write_dma(uint64_t pos, std::vector<iovec> iov, const io_priority_class& pc) noexcept override;
future<> flush() noexcept override;
future<struct stat> stat() noexcept override;
future<> truncate(uint64_t length) noexcept override;
future<uint64_t> size() noexcept override;
future<> close() noexcept override;
};
class blockdev_file_impl : public posix_file_impl {
public:
blockdev_file_impl(int fd, open_flags, file_open_options options, dev_t device_id, size_t block_size);
future<> truncate(uint64_t length) noexcept override;
future<> discard(uint64_t offset, uint64_t length) noexcept override;
future<uint64_t> size() noexcept override;
virtual future<> allocate(uint64_t position, uint64_t length) noexcept override;
};
}
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "cf-handler.h"
#include <dirent.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <vespa/defaults.h>
#include <vespa/config/common/configsystem.h>
#include <vespa/config/common/exceptions.h>
#include <vespa/log/log.h>
LOG_SETUP(".cf-handler");
CfHandler::CfHandler() : _subscriber() {}
CfHandler::~CfHandler()
{
}
void
CfHandler::subscribe(const std::string & configId, uint64_t timeoutMS)
{
_handle = _subscriber.subscribe<LogforwarderConfig>(configId, timeoutMS);
}
namespace {
std::string
cfFilePath() {
std::string path = vespa::Defaults::underVespaHome("var/db/vespa/splunk");
DIR *dp = opendir(path.c_str());
if (dp == NULL) {
if (errno != ENOTDIR || mkdir(path.c_str(), 0755) != 0) {
perror(path.c_str());
}
}
if (dp != NULL) closedir(dp);
path += "/deploymentclient.conf";
return path;
}
}
void
CfHandler::doConfigure()
{
std::unique_ptr<LogforwarderConfig> cfg(_handle->getConfig());
const LogforwarderConfig& config(*cfg);
std::string path = cfFilePath();
std::string tmpPath = path + ".new";
FILE *fp = fopen(tmpPath.c_str(), "w");
if (fp == NULL) return;
fprintf(fp, "[deployment-client]\n");
fprintf(fp, "clientName = %s\n", config.clientName.c_str());
fprintf(fp, "\n");
fprintf(fp, "[target-broker:deploymentServer]\n");
fprintf(fp, "targetUri = %s\n", config.deploymentServer.c_str());
fclose(fp);
rename(tmpPath.c_str(), path.c_str());
}
void
CfHandler::check()
{
if (_subscriber.nextConfig(0)) {
doConfigure();
}
}
constexpr uint64_t CONFIG_TIMEOUT_MS = 30 * 1000;
void
CfHandler::start(const char *configId)
{
LOG(debug, "Reading configuration with id '%s'", configId);
try {
subscribe(configId, CONFIG_TIMEOUT_MS);
doConfigure();
} catch (config::ConfigTimeoutException & ex) {
LOG(warning, "Timout getting config, please check your setup. Will exit and restart: %s", ex.getMessage().c_str());
exit(EXIT_FAILURE);
} catch (config::InvalidConfigException& ex) {
LOG(error, "Fatal: Invalid configuration, please check your setup: %s", ex.getMessage().c_str());
exit(EXIT_FAILURE);
} catch (config::ConfigRuntimeException& ex) {
LOG(error, "Fatal: Could not get config, please check your setup: %s", ex.getMessage().c_str());
exit(EXIT_FAILURE);
}
}
<commit_msg>fix logic<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "cf-handler.h"
#include <dirent.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <vespa/defaults.h>
#include <vespa/config/common/configsystem.h>
#include <vespa/config/common/exceptions.h>
#include <vespa/log/log.h>
LOG_SETUP(".cf-handler");
CfHandler::CfHandler() : _subscriber() {}
CfHandler::~CfHandler()
{
}
void
CfHandler::subscribe(const std::string & configId, uint64_t timeoutMS)
{
_handle = _subscriber.subscribe<LogforwarderConfig>(configId, timeoutMS);
}
namespace {
std::string
cfFilePath() {
std::string path = vespa::Defaults::underVespaHome("var/db/vespa/splunk");
DIR *dp = opendir(path.c_str());
if (dp == NULL) {
if (errno != ENOENT || mkdir(path.c_str(), 0755) != 0) {
perror(path.c_str());
}
} else {
closedir(dp);
}
path += "/deploymentclient.conf";
return path;
}
}
void
CfHandler::doConfigure()
{
std::unique_ptr<LogforwarderConfig> cfg(_handle->getConfig());
const LogforwarderConfig& config(*cfg);
std::string path = cfFilePath();
std::string tmpPath = path + ".new";
FILE *fp = fopen(tmpPath.c_str(), "w");
if (fp == NULL) return;
fprintf(fp, "[deployment-client]\n");
fprintf(fp, "clientName = %s\n", config.clientName.c_str());
fprintf(fp, "\n");
fprintf(fp, "[target-broker:deploymentServer]\n");
fprintf(fp, "targetUri = %s\n", config.deploymentServer.c_str());
fclose(fp);
rename(tmpPath.c_str(), path.c_str());
}
void
CfHandler::check()
{
if (_subscriber.nextConfig(0)) {
doConfigure();
}
}
constexpr uint64_t CONFIG_TIMEOUT_MS = 30 * 1000;
void
CfHandler::start(const char *configId)
{
LOG(debug, "Reading configuration with id '%s'", configId);
try {
subscribe(configId, CONFIG_TIMEOUT_MS);
} catch (config::ConfigTimeoutException & ex) {
LOG(warning, "Timout getting config, please check your setup. Will exit and restart: %s", ex.getMessage().c_str());
exit(EXIT_FAILURE);
} catch (config::InvalidConfigException& ex) {
LOG(error, "Fatal: Invalid configuration, please check your setup: %s", ex.getMessage().c_str());
exit(EXIT_FAILURE);
} catch (config::ConfigRuntimeException& ex) {
LOG(error, "Fatal: Could not get config, please check your setup: %s", ex.getMessage().c_str());
exit(EXIT_FAILURE);
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* This file is part of "Patrick's Programming Library", Version 7 (PPL7).
* Web: http://www.pfp.de/ppl/
*
* $Author$
* $Revision$
* $Date$
* $Id$
*
*******************************************************************************
* Copyright (c) 2013, Patrick Fedick <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AND 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 "prolog.h"
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_LIBMHASH
#define PROTOTYPES 1
#undef HAVE__BOOL
#include <mutils/mhash.h>
#endif
#ifdef HAVE_OPENSSL
#include <openssl/evp.h>
#endif
#ifdef HAVE_LIBZ
#include <zlib.h>
#endif
#include "ppl7.h"
#include "ppl7-crypto.h"
namespace ppl7 {
bool __OpenSSLDigestAdded = false;
Mutex __OpenSSLGlobalMutex;
void InitOpenSSLDigest()
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
__OpenSSLGlobalMutex.lock();
::OpenSSL_add_all_digests();
__OpenSSLDigestAdded=true;
__OpenSSLGlobalMutex.unlock();
#endif
}
Digest::Digest()
{
bytecount=0;
m=NULL;
ret=NULL;
ctx=NULL;
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!__OpenSSLDigestAdded) {
InitOpenSSLDigest();
}
#endif
}
Digest::~Digest()
{
#ifdef HAVE_OPENSSL
free(ret);
if (ctx) EVP_MD_CTX_destroy((EVP_MD_CTX*)ctx);
#endif
}
Digest::Digest(const String &name)
{
bytecount=0;
m=NULL;
ret=NULL;
ctx=NULL;
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!__OpenSSLDigestAdded) {
InitOpenSSLDigest();
}
setAlgorithm(name);
#endif
}
Digest::Digest(Algorithm algorithm)
{
bytecount=0;
m=NULL;
ret=NULL;
ctx=NULL;
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!__OpenSSLDigestAdded) {
InitOpenSSLDigest();
}
setAlgorithm(algorithm);
#endif
}
void Digest::setAlgorithm(const String &name)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
m=EVP_get_digestbyname((const char*)name);
if (!m) {
throw InvalidAlgorithmException("%s",(const char*)name);
}
if (!ctx) {
ctx=EVP_MD_CTX_create();
if (!ctx) throw OutOfMemoryException();
} else {
reset();
}
EVP_DigestInit_ex((EVP_MD_CTX*)ctx,(const EVP_MD*)m, NULL);
#endif
}
void Digest::setAlgorithm(Algorithm algorithm)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
switch(algorithm) {
#ifndef OPENSSL_NO_MD4
case Algo_MD4: m=EVP_md4(); break;
#endif
#ifndef OPENSSL_NO_MD5
case Algo_MD5: m=EVP_md5(); break;
#endif
#ifndef OPENSSL_NO_SHA
case Algo_SHA1: m=EVP_sha1(); break;
case Algo_ECDSA: m=EVP_ecdsa(); break;
#endif
#ifndef OPENSSL_NO_SHA256
case Algo_SHA224: m=EVP_sha224(); break;
case Algo_SHA256: m=EVP_sha256(); break;
#endif
#ifndef OPENSSL_NO_SHA512
case Algo_SHA384: m=EVP_sha384(); break;
case Algo_SHA512: m=EVP_sha512(); break;
#endif
#ifndef OPENSSL_NO_WHIRLPOOL
#if OPENSSL_VERSION_NUMBER >= 0x10001000L
case Algo_WHIRLPOOL: m=EVP_whirlpool(); break;
#endif
#endif
#ifndef OPENSSL_NO_RIPEMD
case Algo_RIPEMD160: m=EVP_ripemd160(); break;
#endif
default: throw InvalidAlgorithmException();
}
if (!m) {
throw InvalidAlgorithmException("%i",algorithm);
}
if (!ctx) {
ctx=EVP_MD_CTX_create();
if (!ctx) throw OutOfMemoryException();
} else {
reset();
}
EVP_DigestInit_ex((EVP_MD_CTX*)ctx,(const EVP_MD*)m, NULL);
#endif
}
void Digest::addData(const void *data, size_t size)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!m) throw NoAlgorithmSpecifiedException();
EVP_DigestUpdate((EVP_MD_CTX*)ctx,data,size);
bytecount+=size;
#endif
}
void Digest::addData(const ByteArrayPtr &data)
{
addData(data.ptr(),data.size());
}
void Digest::addData(const String &data)
{
addData(data.getPtr(),data.size());
}
void Digest::addData(const WideString &data)
{
addData(data.getPtr(),data.size());
}
void Digest::addData(FileObject &file)
{
file.seek(0);
size_t bsize=1024*1024*1; // We allocate 1 MB maximum
ppluint64 fsize=file.size();
if (fsize<bsize) bsize=fsize; // or filesize if file is < 1 MB
void *buffer=malloc(bsize);
if (!buffer) {
throw OutOfMemoryException();
}
ppluint64 rest=fsize;
try {
while(rest) {
size_t bytes=rest;
if (bytes>bsize) bytes=bsize;
if (!file.read(buffer,bytes)) {
throw ReadException();
}
addData(buffer,bytes);
rest-=bytes;
}
} catch (...) {
free(buffer);
throw;
}
free(buffer);
}
void Digest::addFile(const String &filename)
{
File ff;
ff.open(filename,File::READ);
addData(ff);
}
ppluint64 Digest::bytesHashed() const
{
return bytecount;
}
void Digest::saveDigest(ByteArray &result)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
result=getDigest();
#endif
}
void Digest::saveDigest(String &result)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
ByteArray ba=getDigest();
result=ba.toHex();
#endif
}
void Digest::saveDigest(WideString &result)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
ByteArray ba=getDigest();
result=ba.toHex();
#endif
}
ByteArray Digest::getDigest()
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
unsigned int len;
if (!ret) {
ret=(unsigned char*)malloc(EVP_MAX_MD_SIZE);
if (!ret) throw OutOfMemoryException();
}
EVP_DigestFinal((EVP_MD_CTX*)ctx,ret,&len);
EVP_MD_CTX_cleanup((EVP_MD_CTX*)ctx);
EVP_DigestInit_ex((EVP_MD_CTX*)ctx,(const EVP_MD*)m, NULL);
bytecount=0;
return ByteArray(ret,len);
#endif
}
void Digest::reset()
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!m) throw NoAlgorithmSpecifiedException();
if (!ctx) throw NoAlgorithmSpecifiedException();
EVP_MD_CTX_cleanup((EVP_MD_CTX*)ctx);
EVP_DigestInit((EVP_MD_CTX*)ctx,(const EVP_MD*)m);
bytecount=0;
#endif
}
ByteArray Digest::hash(const ByteArrayPtr &data, Algorithm algorithm)
{
Digest dig(algorithm);
dig.addData(data);
return dig.getDigest();
}
ByteArray Digest::hash(const ByteArrayPtr &data, const String &algorithmName)
{
Digest dig(algorithmName);
dig.addData(data);
return dig.getDigest();
}
ByteArray Digest::md4(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_MD4);
}
ByteArray Digest::md5(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_MD5);
}
ByteArray Digest::sha1(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA1);
}
ByteArray Digest::sha224(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA224);
}
ByteArray Digest::sha256(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA256);
}
ByteArray Digest::sha384(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA384);
}
ByteArray Digest::sha512(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA512);
}
ByteArray Digest::ecdsa(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_ECDSA);
}
ppluint32 Digest::crc32(const ByteArrayPtr &data)
{
#ifdef HAVE_LIBZ
uLong crc=::crc32(0L,Z_NULL,0);
return ::crc32(crc,(const Bytef*)data.ptr(),(uInt)data.size());
#endif
return Crc32(data.ptr(),data.size());
}
ppluint32 Digest::adler32(const ByteArrayPtr &data)
{
const unsigned char *buffer = (const unsigned char *)data.ptr();
size_t buflength=data.size();
ppluint32 s1 = 1;
ppluint32 s2 = 0;
for (size_t n = 0; n < buflength; n++) {
s1 = (s1 + buffer[n]) % 65521;
s2 = (s2 + s1) % 65521;
}
return (s2 << 16) | s1;
}
}
<commit_msg>take care that InitOpenSSLDigest calls OpenSSL_add_all_digests only once in multithreaded environment<commit_after>/*******************************************************************************
* This file is part of "Patrick's Programming Library", Version 7 (PPL7).
* Web: http://www.pfp.de/ppl/
*
* $Author$
* $Revision$
* $Date$
* $Id$
*
*******************************************************************************
* Copyright (c) 2013, Patrick Fedick <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 AND 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 "prolog.h"
#ifdef HAVE_STDIO_H
#include <stdio.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_LIBMHASH
#define PROTOTYPES 1
#undef HAVE__BOOL
#include <mutils/mhash.h>
#endif
#ifdef HAVE_OPENSSL
#include <openssl/evp.h>
#endif
#ifdef HAVE_LIBZ
#include <zlib.h>
#endif
#include "ppl7.h"
#include "ppl7-crypto.h"
namespace ppl7 {
bool __OpenSSLDigestAdded = false;
Mutex __OpenSSLGlobalMutex;
void InitOpenSSLDigest()
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
__OpenSSLGlobalMutex.lock();
if (!__OpenSSLDigestAdded) {
::OpenSSL_add_all_digests();
__OpenSSLDigestAdded=true;
}
__OpenSSLGlobalMutex.unlock();
#endif
}
Digest::Digest()
{
bytecount=0;
m=NULL;
ret=NULL;
ctx=NULL;
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!__OpenSSLDigestAdded) {
InitOpenSSLDigest();
}
#endif
}
Digest::~Digest()
{
#ifdef HAVE_OPENSSL
free(ret);
if (ctx) EVP_MD_CTX_destroy((EVP_MD_CTX*)ctx);
#endif
}
Digest::Digest(const String &name)
{
bytecount=0;
m=NULL;
ret=NULL;
ctx=NULL;
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!__OpenSSLDigestAdded) {
InitOpenSSLDigest();
}
setAlgorithm(name);
#endif
}
Digest::Digest(Algorithm algorithm)
{
bytecount=0;
m=NULL;
ret=NULL;
ctx=NULL;
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!__OpenSSLDigestAdded) {
InitOpenSSLDigest();
}
setAlgorithm(algorithm);
#endif
}
void Digest::setAlgorithm(const String &name)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
m=EVP_get_digestbyname((const char*)name);
if (!m) {
throw InvalidAlgorithmException("%s",(const char*)name);
}
if (!ctx) {
ctx=EVP_MD_CTX_create();
if (!ctx) throw OutOfMemoryException();
} else {
reset();
}
EVP_DigestInit_ex((EVP_MD_CTX*)ctx,(const EVP_MD*)m, NULL);
#endif
}
void Digest::setAlgorithm(Algorithm algorithm)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
switch(algorithm) {
#ifndef OPENSSL_NO_MD4
case Algo_MD4: m=EVP_md4(); break;
#endif
#ifndef OPENSSL_NO_MD5
case Algo_MD5: m=EVP_md5(); break;
#endif
#ifndef OPENSSL_NO_SHA
case Algo_SHA1: m=EVP_sha1(); break;
case Algo_ECDSA: m=EVP_ecdsa(); break;
#endif
#ifndef OPENSSL_NO_SHA256
case Algo_SHA224: m=EVP_sha224(); break;
case Algo_SHA256: m=EVP_sha256(); break;
#endif
#ifndef OPENSSL_NO_SHA512
case Algo_SHA384: m=EVP_sha384(); break;
case Algo_SHA512: m=EVP_sha512(); break;
#endif
#ifndef OPENSSL_NO_WHIRLPOOL
#if OPENSSL_VERSION_NUMBER >= 0x10001000L
case Algo_WHIRLPOOL: m=EVP_whirlpool(); break;
#endif
#endif
#ifndef OPENSSL_NO_RIPEMD
case Algo_RIPEMD160: m=EVP_ripemd160(); break;
#endif
default: throw InvalidAlgorithmException();
}
if (!m) {
throw InvalidAlgorithmException("%i",algorithm);
}
if (!ctx) {
ctx=EVP_MD_CTX_create();
if (!ctx) throw OutOfMemoryException();
} else {
reset();
}
EVP_DigestInit_ex((EVP_MD_CTX*)ctx,(const EVP_MD*)m, NULL);
#endif
}
void Digest::addData(const void *data, size_t size)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!m) throw NoAlgorithmSpecifiedException();
EVP_DigestUpdate((EVP_MD_CTX*)ctx,data,size);
bytecount+=size;
#endif
}
void Digest::addData(const ByteArrayPtr &data)
{
addData(data.ptr(),data.size());
}
void Digest::addData(const String &data)
{
addData(data.getPtr(),data.size());
}
void Digest::addData(const WideString &data)
{
addData(data.getPtr(),data.size());
}
void Digest::addData(FileObject &file)
{
file.seek(0);
size_t bsize=1024*1024*1; // We allocate 1 MB maximum
ppluint64 fsize=file.size();
if (fsize<bsize) bsize=fsize; // or filesize if file is < 1 MB
void *buffer=malloc(bsize);
if (!buffer) {
throw OutOfMemoryException();
}
ppluint64 rest=fsize;
try {
while(rest) {
size_t bytes=rest;
if (bytes>bsize) bytes=bsize;
if (!file.read(buffer,bytes)) {
throw ReadException();
}
addData(buffer,bytes);
rest-=bytes;
}
} catch (...) {
free(buffer);
throw;
}
free(buffer);
}
void Digest::addFile(const String &filename)
{
File ff;
ff.open(filename,File::READ);
addData(ff);
}
ppluint64 Digest::bytesHashed() const
{
return bytecount;
}
void Digest::saveDigest(ByteArray &result)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
result=getDigest();
#endif
}
void Digest::saveDigest(String &result)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
ByteArray ba=getDigest();
result=ba.toHex();
#endif
}
void Digest::saveDigest(WideString &result)
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
ByteArray ba=getDigest();
result=ba.toHex();
#endif
}
ByteArray Digest::getDigest()
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
unsigned int len;
if (!ret) {
ret=(unsigned char*)malloc(EVP_MAX_MD_SIZE);
if (!ret) throw OutOfMemoryException();
}
EVP_DigestFinal((EVP_MD_CTX*)ctx,ret,&len);
EVP_MD_CTX_cleanup((EVP_MD_CTX*)ctx);
EVP_DigestInit_ex((EVP_MD_CTX*)ctx,(const EVP_MD*)m, NULL);
bytecount=0;
return ByteArray(ret,len);
#endif
}
void Digest::reset()
{
#ifndef HAVE_OPENSSL
throw UnsupportedFeatureException("OpenSSL");
#else
if (!m) throw NoAlgorithmSpecifiedException();
if (!ctx) throw NoAlgorithmSpecifiedException();
EVP_MD_CTX_cleanup((EVP_MD_CTX*)ctx);
EVP_DigestInit((EVP_MD_CTX*)ctx,(const EVP_MD*)m);
bytecount=0;
#endif
}
ByteArray Digest::hash(const ByteArrayPtr &data, Algorithm algorithm)
{
Digest dig(algorithm);
dig.addData(data);
return dig.getDigest();
}
ByteArray Digest::hash(const ByteArrayPtr &data, const String &algorithmName)
{
Digest dig(algorithmName);
dig.addData(data);
return dig.getDigest();
}
ByteArray Digest::md4(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_MD4);
}
ByteArray Digest::md5(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_MD5);
}
ByteArray Digest::sha1(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA1);
}
ByteArray Digest::sha224(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA224);
}
ByteArray Digest::sha256(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA256);
}
ByteArray Digest::sha384(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA384);
}
ByteArray Digest::sha512(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_SHA512);
}
ByteArray Digest::ecdsa(const ByteArrayPtr &data)
{
return Digest::hash(data,Algo_ECDSA);
}
ppluint32 Digest::crc32(const ByteArrayPtr &data)
{
#ifdef HAVE_LIBZ
uLong crc=::crc32(0L,Z_NULL,0);
return ::crc32(crc,(const Bytef*)data.ptr(),(uInt)data.size());
#endif
return Crc32(data.ptr(),data.size());
}
ppluint32 Digest::adler32(const ByteArrayPtr &data)
{
const unsigned char *buffer = (const unsigned char *)data.ptr();
size_t buflength=data.size();
ppluint32 s1 = 1;
ppluint32 s2 = 0;
for (size_t n = 0; n < buflength; n++) {
s1 = (s1 + buffer[n]) % 65521;
s2 = (s2 + s1) % 65521;
}
return (s2 << 16) | s1;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009 Colin Percival, 2011 ArtForz, 2012-2013 pooler
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* This file was originally written by Colin Percival as part of the Tarsnap
* online backup system.
*/
#include "crypto/scrypt.h"
//#include "util.h"
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <openssl/sha.h>
#if defined(USE_SSE2) && !defined(USE_SSE2_ALWAYS)
#ifdef _MSC_VER
// MSVC 64bit is unable to use inline asm
#include <intrin.h>
#else
// GCC Linux or i686-w64-mingw32
#include <cpuid.h>
#endif
#endif
static inline uint32_t be32dec(const void *pp)
{
const uint8_t *p = (uint8_t const *)pp;
return ((uint32_t)(p[3]) + ((uint32_t)(p[2]) << 8) +
((uint32_t)(p[1]) << 16) + ((uint32_t)(p[0]) << 24));
}
static inline void be32enc(void *pp, uint32_t x)
{
uint8_t *p = (uint8_t *)pp;
p[3] = x & 0xff;
p[2] = (x >> 8) & 0xff;
p[1] = (x >> 16) & 0xff;
p[0] = (x >> 24) & 0xff;
}
typedef struct HMAC_SHA256Context {
SHA256_CTX ictx;
SHA256_CTX octx;
} HMAC_SHA256_CTX;
/* Initialize an HMAC-SHA256 operation with the given key. */
static void
HMAC_SHA256_Init(HMAC_SHA256_CTX *ctx, const void *_K, size_t Klen)
{
unsigned char pad[64];
unsigned char khash[32];
const unsigned char *K = (const unsigned char *)_K;
size_t i;
/* If Klen > 64, the key is really SHA256(K). */
if (Klen > 64) {
SHA256_Init(&ctx->ictx);
SHA256_Update(&ctx->ictx, K, Klen);
SHA256_Final(khash, &ctx->ictx);
K = khash;
Klen = 32;
}
/* Inner SHA256 operation is SHA256(K xor [block of 0x36] || data). */
SHA256_Init(&ctx->ictx);
memset(pad, 0x36, 64);
for (i = 0; i < Klen; i++)
pad[i] ^= K[i];
SHA256_Update(&ctx->ictx, pad, 64);
/* Outer SHA256 operation is SHA256(K xor [block of 0x5c] || hash). */
SHA256_Init(&ctx->octx);
memset(pad, 0x5c, 64);
for (i = 0; i < Klen; i++)
pad[i] ^= K[i];
SHA256_Update(&ctx->octx, pad, 64);
/* Clean the stack. */
memset(khash, 0, 32);
}
/* Add bytes to the HMAC-SHA256 operation. */
static void
HMAC_SHA256_Update(HMAC_SHA256_CTX *ctx, const void *in, size_t len)
{
/* Feed data to the inner SHA256 operation. */
SHA256_Update(&ctx->ictx, in, len);
}
/* Finish an HMAC-SHA256 operation. */
static void
HMAC_SHA256_Final(unsigned char digest[32], HMAC_SHA256_CTX *ctx)
{
unsigned char ihash[32];
/* Finish the inner SHA256 operation. */
SHA256_Final(ihash, &ctx->ictx);
/* Feed the inner hash to the outer SHA256 operation. */
SHA256_Update(&ctx->octx, ihash, 32);
/* Finish the outer SHA256 operation. */
SHA256_Final(digest, &ctx->octx);
/* Clean the stack. */
memset(ihash, 0, 32);
}
/**
* PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, c, buf, dkLen):
* Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and
* write the output to buf. The value dkLen must be at most 32 * (2^32 - 1).
*/
void
PBKDF2_SHA256(const uint8_t *passwd, size_t passwdlen, const uint8_t *salt,
size_t saltlen, uint64_t c, uint8_t *buf, size_t dkLen)
{
HMAC_SHA256_CTX PShctx, hctx;
size_t i;
uint8_t ivec[4];
uint8_t U[32];
uint8_t T[32];
uint64_t j;
int k;
size_t clen;
/* Compute HMAC state after processing P and S. */
HMAC_SHA256_Init(&PShctx, passwd, passwdlen);
HMAC_SHA256_Update(&PShctx, salt, saltlen);
/* Iterate through the blocks. */
for (i = 0; i * 32 < dkLen; i++) {
/* Generate INT(i + 1). */
be32enc(ivec, (uint32_t)(i + 1));
/* Compute U_1 = PRF(P, S || INT(i)). */
memcpy(&hctx, &PShctx, sizeof(HMAC_SHA256_CTX));
HMAC_SHA256_Update(&hctx, ivec, 4);
HMAC_SHA256_Final(U, &hctx);
/* T_i = U_1 ... */
memcpy(T, U, 32);
for (j = 2; j <= c; j++) {
/* Compute U_j. */
HMAC_SHA256_Init(&hctx, passwd, passwdlen);
HMAC_SHA256_Update(&hctx, U, 32);
HMAC_SHA256_Final(U, &hctx);
/* ... xor U_j ... */
for (k = 0; k < 32; k++)
T[k] ^= U[k];
}
/* Copy as many bytes as necessary into buf. */
clen = dkLen - i * 32;
if (clen > 32)
clen = 32;
memcpy(&buf[i * 32], T, clen);
}
/* Clean PShctx, since we never called _Final on it. */
memset(&PShctx, 0, sizeof(HMAC_SHA256_CTX));
}
#define ROTL(a, b) (((a) << (b)) | ((a) >> (32 - (b))))
static inline void xor_salsa8(uint32_t B[16], const uint32_t Bx[16])
{
uint32_t x00,x01,x02,x03,x04,x05,x06,x07,x08,x09,x10,x11,x12,x13,x14,x15;
int i;
x00 = (B[ 0] ^= Bx[ 0]);
x01 = (B[ 1] ^= Bx[ 1]);
x02 = (B[ 2] ^= Bx[ 2]);
x03 = (B[ 3] ^= Bx[ 3]);
x04 = (B[ 4] ^= Bx[ 4]);
x05 = (B[ 5] ^= Bx[ 5]);
x06 = (B[ 6] ^= Bx[ 6]);
x07 = (B[ 7] ^= Bx[ 7]);
x08 = (B[ 8] ^= Bx[ 8]);
x09 = (B[ 9] ^= Bx[ 9]);
x10 = (B[10] ^= Bx[10]);
x11 = (B[11] ^= Bx[11]);
x12 = (B[12] ^= Bx[12]);
x13 = (B[13] ^= Bx[13]);
x14 = (B[14] ^= Bx[14]);
x15 = (B[15] ^= Bx[15]);
for (i = 0; i < 8; i += 2) {
/* Operate on columns. */
x04 ^= ROTL(x00 + x12, 7); x09 ^= ROTL(x05 + x01, 7);
x14 ^= ROTL(x10 + x06, 7); x03 ^= ROTL(x15 + x11, 7);
x08 ^= ROTL(x04 + x00, 9); x13 ^= ROTL(x09 + x05, 9);
x02 ^= ROTL(x14 + x10, 9); x07 ^= ROTL(x03 + x15, 9);
x12 ^= ROTL(x08 + x04, 13); x01 ^= ROTL(x13 + x09, 13);
x06 ^= ROTL(x02 + x14, 13); x11 ^= ROTL(x07 + x03, 13);
x00 ^= ROTL(x12 + x08, 18); x05 ^= ROTL(x01 + x13, 18);
x10 ^= ROTL(x06 + x02, 18); x15 ^= ROTL(x11 + x07, 18);
/* Operate on rows. */
x01 ^= ROTL(x00 + x03, 7); x06 ^= ROTL(x05 + x04, 7);
x11 ^= ROTL(x10 + x09, 7); x12 ^= ROTL(x15 + x14, 7);
x02 ^= ROTL(x01 + x00, 9); x07 ^= ROTL(x06 + x05, 9);
x08 ^= ROTL(x11 + x10, 9); x13 ^= ROTL(x12 + x15, 9);
x03 ^= ROTL(x02 + x01, 13); x04 ^= ROTL(x07 + x06, 13);
x09 ^= ROTL(x08 + x11, 13); x14 ^= ROTL(x13 + x12, 13);
x00 ^= ROTL(x03 + x02, 18); x05 ^= ROTL(x04 + x07, 18);
x10 ^= ROTL(x09 + x08, 18); x15 ^= ROTL(x14 + x13, 18);
}
B[ 0] += x00;
B[ 1] += x01;
B[ 2] += x02;
B[ 3] += x03;
B[ 4] += x04;
B[ 5] += x05;
B[ 6] += x06;
B[ 7] += x07;
B[ 8] += x08;
B[ 9] += x09;
B[10] += x10;
B[11] += x11;
B[12] += x12;
B[13] += x13;
B[14] += x14;
B[15] += x15;
}
void scrypt_1024_1_1_256_sp_generic(const char *input, char *output, char *scratchpad)
{
uint8_t B[128];
uint32_t X[32];
uint32_t *V;
uint32_t i, j, k;
V = (uint32_t *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63));
PBKDF2_SHA256((const uint8_t *)input, 80, (const uint8_t *)input, 80, 1, B, 128);
for (k = 0; k < 32; k++)
X[k] = le32dec(&B[4 * k]);
for (i = 0; i < 1024; i++) {
memcpy(&V[i * 32], X, 128);
xor_salsa8(&X[0], &X[16]);
xor_salsa8(&X[16], &X[0]);
}
for (i = 0; i < 1024; i++) {
j = 32 * (X[16] & 1023);
for (k = 0; k < 32; k++)
X[k] ^= V[j + k];
xor_salsa8(&X[0], &X[16]);
xor_salsa8(&X[16], &X[0]);
}
for (k = 0; k < 32; k++)
le32enc(&B[4 * k], X[k]);
PBKDF2_SHA256((const uint8_t *)input, 80, B, 128, 1, (uint8_t *)output, 32);
}
#if defined(USE_SSE2)
// By default, set to generic scrypt function. This will prevent crash in case when scrypt_detect_sse2() wasn't called
void (*scrypt_1024_1_1_256_sp_detected)(const char *input, char *output, char *scratchpad) = &scrypt_1024_1_1_256_sp_generic;
void scrypt_detect_sse2()
{
#if defined(USE_SSE2_ALWAYS)
printf("scrypt: using scrypt-sse2 as built.\n");
#else // USE_SSE2_ALWAYS
// 32bit x86 Linux or Windows, detect cpuid features
unsigned int cpuid_edx=0;
#if defined(_MSC_VER)
// MSVC
int x86cpuid[4];
__cpuid(x86cpuid, 1);
cpuid_edx = (unsigned int)buffer[3];
#else // _MSC_VER
// Linux or i686-w64-mingw32 (gcc-4.6.3)
unsigned int eax, ebx, ecx;
__get_cpuid(1, &eax, &ebx, &ecx, &cpuid_edx);
#endif // _MSC_VER
if (cpuid_edx & 1<<26)
{
scrypt_1024_1_1_256_sp_detected = &scrypt_1024_1_1_256_sp_sse2;
printf("scrypt: using scrypt-sse2 as detected.\n");
}
else
{
scrypt_1024_1_1_256_sp_detected = &scrypt_1024_1_1_256_sp_generic;
printf("scrypt: using scrypt-generic, SSE2 unavailable.\n");
}
#endif // USE_SSE2_ALWAYS
}
#endif
void scrypt_1024_1_1_256(const char *input, char *output)
{
char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
scrypt_1024_1_1_256_sp(input, output, scratchpad);
}
<commit_msg>Delete scrypt.cpp<commit_after><|endoftext|> |
<commit_before>#include <cudaobjdetect.hpp>
extern "C"
struct HOGPtr HOG_ctorCuda(
struct SizeWrapper win_size, struct SizeWrapper block_size,
struct SizeWrapper block_stride, struct SizeWrapper cell_size, int nbins)
{
return rescueObjectFromPtr(cuda::HOG::create(
win_size, block_size, block_stride, cell_size, nbins));
}
extern "C"
void HOG_setWinSigmaCuda(struct HOGPtr ptr, double val)
{
ptr->setWinSigma(val);
}
extern "C"
double HOG_getWinSigmaCuda(struct HOGPtr ptr)
{
return ptr->getWinSigma();
}
extern "C"
void HOG_setL2HysThresholdCuda(struct HOGPtr ptr, double val)
{
ptr->setL2HysThreshold(val);
}
extern "C"
double HOG_getL2HysThresholdCuda(struct HOGPtr ptr)
{
return ptr->getL2HysThreshold();
}
extern "C"
void HOG_setGammaCorrectionCuda(struct HOGPtr ptr, bool val)
{
ptr->setGammaCorrection(val);
}
extern "C"
bool HOG_getGammaCorrectionCuda(struct HOGPtr ptr)
{
return ptr->getGammaCorrection();
}
extern "C"
void HOG_setNumLevelsCuda(struct HOGPtr ptr, int val)
{
ptr->setNumLevels(val);
}
extern "C"
int HOG_getNumLevelsCuda(struct HOGPtr ptr)
{
return ptr->getNumLevels();
}
extern "C"
void HOG_setHitThresholdCuda(struct HOGPtr ptr, double val)
{
ptr->setHitThreshold(val);
}
extern "C"
double HOG_getHitThresholdCuda(struct HOGPtr ptr)
{
return ptr->getHitThreshold();
}
extern "C"
void HOG_setWinStrideCuda(struct HOGPtr ptr, struct SizeWrapper val)
{
ptr->setWinStride(val);
}
extern "C"
struct SizeWrapper HOG_getWinStrideCuda(struct HOGPtr ptr)
{
return ptr->getWinStride();
}
extern "C"
void HOG_setScaleFactorCuda(struct HOGPtr ptr, double val)
{
ptr->setScaleFactor(val);
}
extern "C"
double HOG_getScaleFactorCuda(struct HOGPtr ptr)
{
return ptr->getScaleFactor();
}
extern "C"
void HOG_setGroupThresholdCuda(struct HOGPtr ptr, int val)
{
ptr->setGroupThreshold(val);
}
extern "C"
int HOG_getGroupThresholdCuda(struct HOGPtr ptr)
{
return ptr->getGroupThreshold();
}
extern "C"
void HOG_setDescriptorFormatCuda(struct HOGPtr ptr, int val)
{
ptr->setDescriptorFormat(val);
}
extern "C"
int HOG_getDescriptorFormatCuda(struct HOGPtr ptr)
{
return ptr->getDescriptorFormat();
}
extern "C"
size_t HOG_getDescriptorSizeCuda(struct HOGPtr ptr)
{
return ptr->getDescriptorSize();
}
extern "C"
size_t HOG_getBlockHistogramSizeCuda(struct HOGPtr ptr)
{
return ptr->getBlockHistogramSize();
}
extern "C"
void HOG_setSVMDetectorCuda(struct HOGPtr ptr, struct TensorWrapper val)
{
ptr->setSVMDetector(val.toMat());
}
extern "C"
struct TensorWrapper HOG_getDefaultPeopleDetectorCuda(struct HOGPtr ptr)
{
return TensorWrapper(ptr->getDefaultPeopleDetector());
}
extern "C"
struct TensorPlusPointArray HOG_detectCuda(
struct cutorchInfo info, struct HOGPtr ptr, struct TensorWrapper img)
{
std::vector<cv::Point> found_locations;
std::vector<double> confidences;
cuda::GpuMat imgMat = img.toGpuMat();
cuda::GpuMat imgMatByte;
imgMat.convertTo(imgMatByte, CV_8U, 255.0); // Sorry guys :( #156
ptr->detect(imgMatByte, found_locations, &confidences);
TensorPlusPointArray retval;
new (&retval.points) PointArray(found_locations);
new (&retval.tensor) TensorWrapper(cv::Mat(confidences));
return retval;
}
extern "C"
struct TensorPlusRectArray HOG_detectMultiScaleCuda(
struct cutorchInfo info, struct HOGPtr ptr, struct TensorWrapper img)
{
std::vector<cv::Rect> found_locations;
std::vector<double> confidences;
cuda::GpuMat imgMat = img.toGpuMat();
cuda::GpuMat imgMatByte;
imgMat.convertTo(imgMatByte, CV_8U, 255.0); // Sorry guys :( #156
ptr->detectMultiScale(imgMatByte, found_locations, &confidences);
TensorPlusRectArray retval;
new (&retval.rects) RectArray(found_locations);
new (&retval.tensor) TensorWrapper(cv::Mat(confidences));
return retval;
}
extern "C"
struct TensorWrapper HOG_computeCuda(
struct cutorchInfo info, struct HOGPtr ptr, struct TensorWrapper img,
struct TensorWrapper descriptors)
{
GpuMatT descriptorsMat = descriptors.toGpuMatT();
cuda::GpuMat imgMat = img.toGpuMat();
cuda::GpuMat imgMatByte;
imgMat.convertTo(imgMatByte, CV_8U, 255.0); // Sorry guys :( #156
ptr->compute(imgMatByte, descriptorsMat, prepareStream(info));
return TensorWrapper(descriptorsMat, info.state);
}
extern "C"
struct CascadeClassifierPtr CascadeClassifier_ctor_filenameCuda(const char *filename)
{
return rescueObjectFromPtr(cuda::CascadeClassifier::create(filename));
}
extern "C"
struct CascadeClassifierPtr CascadeClassifier_ctor_fileCuda(struct FileStoragePtr file)
{
return rescueObjectFromPtr(cuda::CascadeClassifier::create(*file));
}
extern "C"
void CascadeClassifier_setMaxObjectSizeCuda(struct CascadeClassifierPtr ptr, struct SizeWrapper val)
{
ptr->setMaxObjectSize(val);
}
extern "C"
struct SizeWrapper CascadeClassifier_getMaxObjectSizeCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getMaxObjectSize();
}
extern "C"
void CascadeClassifier_setMinObjectSizeCuda(struct CascadeClassifierPtr ptr, struct SizeWrapper val)
{
ptr->setMinObjectSize(val);
}
extern "C"
struct SizeWrapper CascadeClassifier_getMinObjectSizeCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getMinObjectSize();
}
extern "C"
void CascadeClassifier_setScaleFactorCuda(struct CascadeClassifierPtr ptr, double val)
{
ptr->setScaleFactor(val);
}
extern "C"
double CascadeClassifier_getScaleFactorCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getScaleFactor();
}
extern "C"
void CascadeClassifier_setMinNeighborsCuda(struct CascadeClassifierPtr ptr, int val)
{
ptr->setMinNeighbors(val);
}
extern "C"
int CascadeClassifier_getMinNeighborsCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getMinNeighbors();
}
extern "C"
void CascadeClassifier_setFindLargestObjectCuda(struct CascadeClassifierPtr ptr, bool val)
{
ptr->setFindLargestObject(val);
}
extern "C"
bool CascadeClassifier_getFindLargestObjectCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getFindLargestObject();
}
extern "C"
void CascadeClassifier_setMaxNumObjectsCuda(struct CascadeClassifierPtr ptr, int val)
{
ptr->setMaxNumObjects(val);
}
extern "C"
int CascadeClassifier_getMaxNumObjectsCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getMaxNumObjects();
}
extern "C"
struct SizeWrapper CascadeClassifier_getClassifierSizeCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getClassifierSize();
}
extern "C"
struct TensorWrapper CascadeClassifier_detectMultiScaleCuda(
struct cutorchInfo info, struct CascadeClassifierPtr ptr,
struct TensorWrapper image, struct TensorWrapper objects)
{
GpuMatT objectsMat = objects.toGpuMatT();
cuda::GpuMat imageMat = image.toGpuMat();
cuda::GpuMat imageByte;
imageMat.convertTo(imageByte, CV_8U, 255.0); // Sorry guys :(
ptr->detectMultiScale(imageByte, objectsMat, prepareStream(info));
return TensorWrapper(objectsMat, info.state);
}
extern "C"
struct RectArray CascadeClassifier_convertCuda(
struct CascadeClassifierPtr ptr, struct TensorWrapper gpu_objects)
{
auto mat = gpu_objects.toGpuMat(CV_32S);
std::vector<cv::Rect> objects;
ptr->convert(mat, objects);
return RectArray(objects);
}
<commit_msg>Error in HOG_detectMultiScaleCuda, #156<commit_after>#include <cudaobjdetect.hpp>
extern "C"
struct HOGPtr HOG_ctorCuda(
struct SizeWrapper win_size, struct SizeWrapper block_size,
struct SizeWrapper block_stride, struct SizeWrapper cell_size, int nbins)
{
return rescueObjectFromPtr(cuda::HOG::create(
win_size, block_size, block_stride, cell_size, nbins));
}
extern "C"
void HOG_setWinSigmaCuda(struct HOGPtr ptr, double val)
{
ptr->setWinSigma(val);
}
extern "C"
double HOG_getWinSigmaCuda(struct HOGPtr ptr)
{
return ptr->getWinSigma();
}
extern "C"
void HOG_setL2HysThresholdCuda(struct HOGPtr ptr, double val)
{
ptr->setL2HysThreshold(val);
}
extern "C"
double HOG_getL2HysThresholdCuda(struct HOGPtr ptr)
{
return ptr->getL2HysThreshold();
}
extern "C"
void HOG_setGammaCorrectionCuda(struct HOGPtr ptr, bool val)
{
ptr->setGammaCorrection(val);
}
extern "C"
bool HOG_getGammaCorrectionCuda(struct HOGPtr ptr)
{
return ptr->getGammaCorrection();
}
extern "C"
void HOG_setNumLevelsCuda(struct HOGPtr ptr, int val)
{
ptr->setNumLevels(val);
}
extern "C"
int HOG_getNumLevelsCuda(struct HOGPtr ptr)
{
return ptr->getNumLevels();
}
extern "C"
void HOG_setHitThresholdCuda(struct HOGPtr ptr, double val)
{
ptr->setHitThreshold(val);
}
extern "C"
double HOG_getHitThresholdCuda(struct HOGPtr ptr)
{
return ptr->getHitThreshold();
}
extern "C"
void HOG_setWinStrideCuda(struct HOGPtr ptr, struct SizeWrapper val)
{
ptr->setWinStride(val);
}
extern "C"
struct SizeWrapper HOG_getWinStrideCuda(struct HOGPtr ptr)
{
return ptr->getWinStride();
}
extern "C"
void HOG_setScaleFactorCuda(struct HOGPtr ptr, double val)
{
ptr->setScaleFactor(val);
}
extern "C"
double HOG_getScaleFactorCuda(struct HOGPtr ptr)
{
return ptr->getScaleFactor();
}
extern "C"
void HOG_setGroupThresholdCuda(struct HOGPtr ptr, int val)
{
ptr->setGroupThreshold(val);
}
extern "C"
int HOG_getGroupThresholdCuda(struct HOGPtr ptr)
{
return ptr->getGroupThreshold();
}
extern "C"
void HOG_setDescriptorFormatCuda(struct HOGPtr ptr, int val)
{
ptr->setDescriptorFormat(val);
}
extern "C"
int HOG_getDescriptorFormatCuda(struct HOGPtr ptr)
{
return ptr->getDescriptorFormat();
}
extern "C"
size_t HOG_getDescriptorSizeCuda(struct HOGPtr ptr)
{
return ptr->getDescriptorSize();
}
extern "C"
size_t HOG_getBlockHistogramSizeCuda(struct HOGPtr ptr)
{
return ptr->getBlockHistogramSize();
}
extern "C"
void HOG_setSVMDetectorCuda(struct HOGPtr ptr, struct TensorWrapper val)
{
ptr->setSVMDetector(val.toMat());
}
extern "C"
struct TensorWrapper HOG_getDefaultPeopleDetectorCuda(struct HOGPtr ptr)
{
return TensorWrapper(ptr->getDefaultPeopleDetector());
}
extern "C"
struct TensorPlusPointArray HOG_detectCuda(
struct cutorchInfo info, struct HOGPtr ptr, struct TensorWrapper img)
{
std::vector<cv::Point> found_locations;
std::vector<double> confidences;
cuda::GpuMat imgMat = img.toGpuMat();
cuda::GpuMat imgMatByte;
imgMat.convertTo(imgMatByte, CV_8U, 255.0); // Sorry guys :( #156
ptr->detect(imgMatByte, found_locations, &confidences);
TensorPlusPointArray retval;
new (&retval.points) PointArray(found_locations);
new (&retval.tensor) TensorWrapper(cv::Mat(confidences));
return retval;
}
extern "C"
struct TensorPlusRectArray HOG_detectMultiScaleCuda(
struct cutorchInfo info, struct HOGPtr ptr, struct TensorWrapper img)
{
std::vector<cv::Rect> found_locations;
std::vector<double> confidences;
cuda::GpuMat imgMat = img.toGpuMat();
cuda::GpuMat imgMatByte;
imgMat.convertTo(imgMatByte, CV_8U, 255.0); // Sorry guys :( #156
if (ptr->getGroupThreshold() == 0) {
ptr->detectMultiScale(imgMatByte, found_locations, &confidences);
} else {
ptr->detectMultiScale(imgMatByte, found_locations, nullptr);
}
TensorPlusRectArray retval;
new (&retval.rects) RectArray(found_locations);
new (&retval.tensor) TensorWrapper(cv::Mat(confidences));
return retval;
}
extern "C"
struct TensorWrapper HOG_computeCuda(
struct cutorchInfo info, struct HOGPtr ptr, struct TensorWrapper img,
struct TensorWrapper descriptors)
{
GpuMatT descriptorsMat = descriptors.toGpuMatT();
cuda::GpuMat imgMat = img.toGpuMat();
cuda::GpuMat imgMatByte;
imgMat.convertTo(imgMatByte, CV_8U, 255.0); // Sorry guys :( #156
ptr->compute(imgMatByte, descriptorsMat, prepareStream(info));
return TensorWrapper(descriptorsMat, info.state);
}
extern "C"
struct CascadeClassifierPtr CascadeClassifier_ctor_filenameCuda(const char *filename)
{
return rescueObjectFromPtr(cuda::CascadeClassifier::create(filename));
}
extern "C"
struct CascadeClassifierPtr CascadeClassifier_ctor_fileCuda(struct FileStoragePtr file)
{
return rescueObjectFromPtr(cuda::CascadeClassifier::create(*file));
}
extern "C"
void CascadeClassifier_setMaxObjectSizeCuda(struct CascadeClassifierPtr ptr, struct SizeWrapper val)
{
ptr->setMaxObjectSize(val);
}
extern "C"
struct SizeWrapper CascadeClassifier_getMaxObjectSizeCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getMaxObjectSize();
}
extern "C"
void CascadeClassifier_setMinObjectSizeCuda(struct CascadeClassifierPtr ptr, struct SizeWrapper val)
{
ptr->setMinObjectSize(val);
}
extern "C"
struct SizeWrapper CascadeClassifier_getMinObjectSizeCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getMinObjectSize();
}
extern "C"
void CascadeClassifier_setScaleFactorCuda(struct CascadeClassifierPtr ptr, double val)
{
ptr->setScaleFactor(val);
}
extern "C"
double CascadeClassifier_getScaleFactorCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getScaleFactor();
}
extern "C"
void CascadeClassifier_setMinNeighborsCuda(struct CascadeClassifierPtr ptr, int val)
{
ptr->setMinNeighbors(val);
}
extern "C"
int CascadeClassifier_getMinNeighborsCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getMinNeighbors();
}
extern "C"
void CascadeClassifier_setFindLargestObjectCuda(struct CascadeClassifierPtr ptr, bool val)
{
ptr->setFindLargestObject(val);
}
extern "C"
bool CascadeClassifier_getFindLargestObjectCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getFindLargestObject();
}
extern "C"
void CascadeClassifier_setMaxNumObjectsCuda(struct CascadeClassifierPtr ptr, int val)
{
ptr->setMaxNumObjects(val);
}
extern "C"
int CascadeClassifier_getMaxNumObjectsCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getMaxNumObjects();
}
extern "C"
struct SizeWrapper CascadeClassifier_getClassifierSizeCuda(struct CascadeClassifierPtr ptr)
{
return ptr->getClassifierSize();
}
extern "C"
struct TensorWrapper CascadeClassifier_detectMultiScaleCuda(
struct cutorchInfo info, struct CascadeClassifierPtr ptr,
struct TensorWrapper image, struct TensorWrapper objects)
{
GpuMatT objectsMat = objects.toGpuMatT();
cuda::GpuMat imageMat = image.toGpuMat();
cuda::GpuMat imageByte;
imageMat.convertTo(imageByte, CV_8U, 255.0); // Sorry guys :(
ptr->detectMultiScale(imageByte, objectsMat, prepareStream(info));
return TensorWrapper(objectsMat, info.state);
}
extern "C"
struct RectArray CascadeClassifier_convertCuda(
struct CascadeClassifierPtr ptr, struct TensorWrapper gpu_objects)
{
auto mat = gpu_objects.toGpuMat(CV_32S);
std::vector<cv::Rect> objects;
ptr->convert(mat, objects);
return RectArray(objects);
}
<|endoftext|> |
<commit_before>/* cclive
* Copyright (C) 2010-2011 Toni Gundogdu <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <ccinternal>
#include <iomanip>
#include <ctime>
#include <boost/foreach.hpp>
#include <boost/random.hpp>
#include <curl/curl.h>
#ifndef foreach
#define foreach BOOST_FOREACH
#endif
#include <ccapplication>
#include <ccquvi>
#include <ccutil>
#include <cclog>
namespace cc
{
static boost::mt19937 _rng;
static void rand_decor()
{
boost::uniform_int<> r(2,5);
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > v(_rng,r);
const int n = v();
for (int i=0; i<n; ++i) cc::log << ".";
}
static void handle_fetch(const quvi_word type, void*)
{
rand_decor();
if (type == QUVISTATUSTYPE_DONE)
cc::log << " ";
}
static void print_done()
{
cc::log << "done.\n";
}
static void handle_verify(const quvi_word type)
{
rand_decor();
if (type == QUVISTATUSTYPE_DONE)
print_done();
}
static void handle_resolve(const quvi_word type)
{
rand_decor();
if (type == QUVISTATUSTYPE_DONE)
cc::log << " ";
}
static int status_callback(long param, void *ptr)
{
const quvi_word status = quvi_loword(param);
const quvi_word type = quvi_hiword(param);
switch (status)
{
case QUVISTATUS_FETCH :
handle_fetch(type,ptr);
break;
case QUVISTATUS_VERIFY:
handle_verify(type);
break;
case QUVISTATUS_RESOLVE:
handle_resolve(type);
break;
}
cc::log << std::flush;
return QUVI_OK;
}
template<class Iterator>
static Iterator make_unique(Iterator first, Iterator last)
{
while (first != last)
{
Iterator next(first);
last = std::remove(++next, last, *first);
first = next;
}
return last;
}
static void print_retrying(const int retry,
const int max_retries,
const int retry_wait)
{
if (retry > 0)
{
cc::log
<< "Retrying "
<< retry
<< " of "
<< max_retries
<< " ... "
<< std::flush;
cc::wait(retry_wait);
}
}
static void print_checking(const int i, const int n)
{
if (n > 1) cc::log << "(" << i << " of " << n << ") ";
cc::log << "Checking ... " << std::flush;
}
static void print_quvi_error(const quvi::error& e)
{
cc::log << "libquvi: error: " << e.what() << std::endl;
}
static void check_quvi_error(const quvi::error& e)
{
const long resp_code = e.response_code();
if (resp_code >= 400 && resp_code <= 500)
throw e;
else
{
switch (e.quvi_code())
{
case QUVI_CURL:
print_quvi_error(e);
break; // Retry.
default:
throw e;
}
}
}
static const char depr_msg[] =
"Warning:\n"
" '--format list' is deprecated and will be removed in the later\n"
" versions. Use --query-formats instead.";
static const char format_usage[] =
"Usage:\n"
" --format arg get format arg of media\n"
" --format list print domains with formats\n"
" --format list arg match arg to supported domain names\n"
"Examples:\n"
" --format list youtube print youtube formats\n"
" --format fmt34_360p get format fmt34_360p of media";
static application::exit_status print_format_help()
{
std::cout << format_usage << "\n" << depr_msg << std::endl;
return application::ok;
}
typedef std::map<std::string,std::string> map_ss;
static void print_host(const map_ss::value_type& t)
{
std::cout
<< t.first
<< ":\n "
<< t.second
<< "\n"
<< std::endl;
}
namespace po = boost::program_options;
static application::exit_status handle_format_list(
const po::variables_map& map,
const quvi::query& query)
{
map_ss m = query.support();
// -f list <pattern>
if (map.count("url"))
{
const std::string arg0 =
map["url"].as< std::vector<std::string> >()[0];
foreach (map_ss::value_type& t, m)
{
if (t.first.find(arg0) != std::string::npos)
print_host(t);
}
}
// -f list
else
{
foreach (map_ss::value_type& t, m)
{
print_host(t);
}
}
std::cout << depr_msg << std::endl;
return application::ok;
}
static application::exit_status query_formats(
const quvi::query& query,
const quvi::options &opts,
const std::vector<std::string>& input)
{
const size_t n = input.size();
size_t i = 0;
foreach (std::string url, input)
{
++i;
try
{
print_checking(i,n);
const std::string formats = query.formats(url, opts);
print_done();
cc::log
<< std::setw(10)
<< formats
<< " : "
<< url
<< std::endl;
}
catch(const quvi::error& e)
{
print_quvi_error(e);
}
}
return application::ok;
}
static char *parse_url_scheme(const std::string& s)
{
char *url = const_cast<char*>(s.c_str());
char *p = strstr(url, ":/");
if (!p)
return NULL;
char *r = NULL;
asprintf(&r, "%.*s", (int)(p - url), url);
return r;
}
#define _free(p) \
do { if (p) free(p); p=NULL; } while (0)
static int is_url(const std::string& s)
{
char *p = parse_url_scheme(s);
if (p)
{
_free(p);
return true;
}
return false;
}
#undef _free
static void read_from(std::istream& is, std::vector<std::string>& dst)
{
std::string s;
char ch = 0;
while (is.get(ch))
s += ch;
std::istringstream iss(s);
std::copy(
std::istream_iterator<std::string >(iss),
std::istream_iterator<std::string >(),
std::back_inserter<std::vector<std::string> >(dst)
);
}
extern char LICENSE[]; // cclive/license.cpp
application::exit_status application::exec(int argc, char **argv)
{
try
{
_opts.exec(argc,argv);
}
catch(const std::exception& e)
{
std::clog << "error: " << e.what() << std::endl;
return invalid_option;
}
const po::variables_map map = _opts.map();
// Dump and terminate options.
if (map.count("help"))
{
std::cout << _opts << std::flush;
return ok;
}
if (map.count("version"))
{
std::cout
<< "cclive version "
#ifdef GIT_DESCRIBE
<< GIT_DESCRIBE
#else
<< PACKAGE_VERSION
#endif
#ifdef BUILD_DATE
<< " built on " << BUILD_DATE
#endif
<< " for " << CANONICAL_TARGET
<< "\nlibquvi version "
<< quvi_version(QUVI_VERSION_LONG)
<< std::endl;
return ok;
}
if (map.count("license"))
{
std::cout << LICENSE << std::endl;
return ok;
}
// --support
quvi::query query; // Throws quvi::error caught in main.cpp
if (map.count("support"))
{
std::cout << quvi::support_to_s(query.support()) << std::flush;
return ok;
}
// --format [<id> | [<help> | <list> [<pattern]]]
const std::string format = map["format"].as<std::string>();
if (format == "help")
return print_format_help();
else if (format == "list")
return handle_format_list(map, query);
// Parse input.
std::vector<std::string> input;
if (map.count("url") == 0)
read_from(std::cin, input);
else
{
std::vector<std::string> args =
map["url"].as< std::vector<std::string> >();
foreach(std::string arg, args)
{
if (!is_url(arg))
{
std::ifstream f(arg.c_str());
if (f.is_open())
read_from(f, input);
else
{
std::clog
<< "error: "
<< arg
<< ": "
<< cc::perror("unable to open")
<< std::endl;
}
}
else
input.push_back(arg);
}
}
if (input.size() == 0)
{
std::clog << "error: no input urls" << std::endl;
return invalid_option;
}
// Remove duplicates.
input.erase(make_unique(input.begin(), input.end()), input.end());
// Turn on libcurl verbose output.
if (map.count("verbose-libcurl"))
curl_easy_setopt(query.curlHandle(), CURLOPT_VERBOSE, 1L);
// Set up quvi.
_tweak_curl_opts(query, map);
quvi::options qopts;
qopts.statusfunc(status_callback);
qopts.format(format);
#ifdef _0
qopts.verify(map.count("no-verify"));
#endif
qopts.resolve(map.count("no-resolve"));
// Seed random generator.
_rng.seed(static_cast<unsigned int>(std::time(0)));
// Omit flag.
bool omit = map.count("quiet");
// Go to background.
#ifdef HAVE_FORK
const bool background_given = map.count("background");
if (background_given)
{
// (Boost) Throws std::runtime_error if fails.
cc::go_background(map["log-file"].as<std::string>(), omit);
}
#endif
// Omit std output. Note that --background flips this above.
cc::log.push(cc::omit_sink(omit));
cc::log.setf(std::ios::fixed);
// Query formats.
if (map.count("query-formats"))
return query_formats(query, qopts, input);
#if defined (HAVE_FORK) && defined (HAVE_GETPID)
if (background_given)
{
cc::log
<< "Running in background (pid: "
<< static_cast<long>(getpid())
<< ")."
<< std::endl;
}
#endif
// For each input URL.
const size_t n = input.size();
size_t i = 0;
const int max_retries = map["max-retries"].as<int>();
const int retry_wait = map["retry-wait"].as<int>();
foreach(std::string url, input)
{
++i;
try
{
int retry = 0;
while (retry <= max_retries)
{
print_retrying(retry, max_retries, retry_wait);
++retry;
print_checking(i, n);
quvi::media m;
try
{
m = query.parse(url, qopts);
}
catch(const quvi::error& e)
{
check_quvi_error(e);
}
cc::get(query, m, map);
break; // Stop retrying.
}
}
catch(const quvi::error& e)
{
print_quvi_error(e);
}
catch(const std::runtime_error& e)
{
cc::log << "error: " << e.what() << std::endl;
}
}
return ok;
}
void application::_tweak_curl_opts(const quvi::query& query,
const po::variables_map& map)
{
CURL *curl = query.curlHandle();
curl_easy_setopt(curl, CURLOPT_USERAGENT,
map["agent"].as<std::string>().c_str());
if (map.count("verbose-curl"))
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
if (map.count("proxy"))
{
curl_easy_setopt(curl, CURLOPT_PROXY,
map["proxy"].as<std::string>().c_str());
}
if (map.count("no-proxy"))
curl_easy_setopt(curl, CURLOPT_PROXY, "");
if (map.count("throttle"))
{
curl_off_t limit = map["throttle"].as<int>()*1024;
curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, limit);
}
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT,
map["connect-timeout"].as<int>());
}
} // namespace cc
// vim: set ts=2 sw=2 tw=72 expandtab:
<commit_msg>Use QUVI_CALLBACK instead of QUVI_CURL<commit_after>/* cclive
* Copyright (C) 2010-2011 Toni Gundogdu <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <ccinternal>
#include <iomanip>
#include <ctime>
#include <boost/foreach.hpp>
#include <boost/random.hpp>
#include <curl/curl.h>
#ifndef foreach
#define foreach BOOST_FOREACH
#endif
#include <ccapplication>
#include <ccquvi>
#include <ccutil>
#include <cclog>
namespace cc
{
static boost::mt19937 _rng;
static void rand_decor()
{
boost::uniform_int<> r(2,5);
boost::variate_generator<boost::mt19937&, boost::uniform_int<> > v(_rng,r);
const int n = v();
for (int i=0; i<n; ++i) cc::log << ".";
}
static void handle_fetch(const quvi_word type, void*)
{
rand_decor();
if (type == QUVISTATUSTYPE_DONE)
cc::log << " ";
}
static void print_done()
{
cc::log << "done.\n";
}
static void handle_verify(const quvi_word type)
{
rand_decor();
if (type == QUVISTATUSTYPE_DONE)
print_done();
}
static void handle_resolve(const quvi_word type)
{
rand_decor();
if (type == QUVISTATUSTYPE_DONE)
cc::log << " ";
}
static int status_callback(long param, void *ptr)
{
const quvi_word status = quvi_loword(param);
const quvi_word type = quvi_hiword(param);
switch (status)
{
case QUVISTATUS_FETCH :
handle_fetch(type,ptr);
break;
case QUVISTATUS_VERIFY:
handle_verify(type);
break;
case QUVISTATUS_RESOLVE:
handle_resolve(type);
break;
}
cc::log << std::flush;
return QUVI_OK;
}
template<class Iterator>
static Iterator make_unique(Iterator first, Iterator last)
{
while (first != last)
{
Iterator next(first);
last = std::remove(++next, last, *first);
first = next;
}
return last;
}
static void print_retrying(const int retry,
const int max_retries,
const int retry_wait)
{
if (retry > 0)
{
cc::log
<< "Retrying "
<< retry
<< " of "
<< max_retries
<< " ... "
<< std::flush;
cc::wait(retry_wait);
}
}
static void print_checking(const int i, const int n)
{
if (n > 1) cc::log << "(" << i << " of " << n << ") ";
cc::log << "Checking ... " << std::flush;
}
static void print_quvi_error(const quvi::error& e)
{
cc::log << "libquvi: error: " << e.what() << std::endl;
}
static void check_quvi_error(const quvi::error& e)
{
const long resp_code = e.response_code();
if (resp_code >= 400 && resp_code <= 500)
throw e;
else
{
switch (e.quvi_code())
{
case QUVI_CALLBACK:
print_quvi_error(e);
break; // Retry.
default:
throw e;
}
}
}
static const char depr_msg[] =
"Warning:\n"
" '--format list' is deprecated and will be removed in the later\n"
" versions. Use --query-formats instead.";
static const char format_usage[] =
"Usage:\n"
" --format arg get format arg of media\n"
" --format list print domains with formats\n"
" --format list arg match arg to supported domain names\n"
"Examples:\n"
" --format list youtube print youtube formats\n"
" --format fmt34_360p get format fmt34_360p of media";
static application::exit_status print_format_help()
{
std::cout << format_usage << "\n" << depr_msg << std::endl;
return application::ok;
}
typedef std::map<std::string,std::string> map_ss;
static void print_host(const map_ss::value_type& t)
{
std::cout
<< t.first
<< ":\n "
<< t.second
<< "\n"
<< std::endl;
}
namespace po = boost::program_options;
static application::exit_status handle_format_list(
const po::variables_map& map,
const quvi::query& query)
{
map_ss m = query.support();
// -f list <pattern>
if (map.count("url"))
{
const std::string arg0 =
map["url"].as< std::vector<std::string> >()[0];
foreach (map_ss::value_type& t, m)
{
if (t.first.find(arg0) != std::string::npos)
print_host(t);
}
}
// -f list
else
{
foreach (map_ss::value_type& t, m)
{
print_host(t);
}
}
std::cout << depr_msg << std::endl;
return application::ok;
}
static application::exit_status query_formats(
const quvi::query& query,
const quvi::options &opts,
const std::vector<std::string>& input)
{
const size_t n = input.size();
size_t i = 0;
foreach (std::string url, input)
{
++i;
try
{
print_checking(i,n);
const std::string formats = query.formats(url, opts);
print_done();
cc::log
<< std::setw(10)
<< formats
<< " : "
<< url
<< std::endl;
}
catch(const quvi::error& e)
{
print_quvi_error(e);
}
}
return application::ok;
}
static char *parse_url_scheme(const std::string& s)
{
char *url = const_cast<char*>(s.c_str());
char *p = strstr(url, ":/");
if (!p)
return NULL;
char *r = NULL;
asprintf(&r, "%.*s", (int)(p - url), url);
return r;
}
#define _free(p) \
do { if (p) free(p); p=NULL; } while (0)
static int is_url(const std::string& s)
{
char *p = parse_url_scheme(s);
if (p)
{
_free(p);
return true;
}
return false;
}
#undef _free
static void read_from(std::istream& is, std::vector<std::string>& dst)
{
std::string s;
char ch = 0;
while (is.get(ch))
s += ch;
std::istringstream iss(s);
std::copy(
std::istream_iterator<std::string >(iss),
std::istream_iterator<std::string >(),
std::back_inserter<std::vector<std::string> >(dst)
);
}
extern char LICENSE[]; // cclive/license.cpp
application::exit_status application::exec(int argc, char **argv)
{
try
{
_opts.exec(argc,argv);
}
catch(const std::exception& e)
{
std::clog << "error: " << e.what() << std::endl;
return invalid_option;
}
const po::variables_map map = _opts.map();
// Dump and terminate options.
if (map.count("help"))
{
std::cout << _opts << std::flush;
return ok;
}
if (map.count("version"))
{
std::cout
<< "cclive version "
#ifdef GIT_DESCRIBE
<< GIT_DESCRIBE
#else
<< PACKAGE_VERSION
#endif
#ifdef BUILD_DATE
<< " built on " << BUILD_DATE
#endif
<< " for " << CANONICAL_TARGET
<< "\nlibquvi version "
<< quvi_version(QUVI_VERSION_LONG)
<< std::endl;
return ok;
}
if (map.count("license"))
{
std::cout << LICENSE << std::endl;
return ok;
}
// --support
quvi::query query; // Throws quvi::error caught in main.cpp
if (map.count("support"))
{
std::cout << quvi::support_to_s(query.support()) << std::flush;
return ok;
}
// --format [<id> | [<help> | <list> [<pattern]]]
const std::string format = map["format"].as<std::string>();
if (format == "help")
return print_format_help();
else if (format == "list")
return handle_format_list(map, query);
// Parse input.
std::vector<std::string> input;
if (map.count("url") == 0)
read_from(std::cin, input);
else
{
std::vector<std::string> args =
map["url"].as< std::vector<std::string> >();
foreach(std::string arg, args)
{
if (!is_url(arg))
{
std::ifstream f(arg.c_str());
if (f.is_open())
read_from(f, input);
else
{
std::clog
<< "error: "
<< arg
<< ": "
<< cc::perror("unable to open")
<< std::endl;
}
}
else
input.push_back(arg);
}
}
if (input.size() == 0)
{
std::clog << "error: no input urls" << std::endl;
return invalid_option;
}
// Remove duplicates.
input.erase(make_unique(input.begin(), input.end()), input.end());
// Turn on libcurl verbose output.
if (map.count("verbose-libcurl"))
curl_easy_setopt(query.curlHandle(), CURLOPT_VERBOSE, 1L);
// Set up quvi.
_tweak_curl_opts(query, map);
quvi::options qopts;
qopts.statusfunc(status_callback);
qopts.format(format);
#ifdef _0
qopts.verify(map.count("no-verify"));
#endif
qopts.resolve(map.count("no-resolve"));
// Seed random generator.
_rng.seed(static_cast<unsigned int>(std::time(0)));
// Omit flag.
bool omit = map.count("quiet");
// Go to background.
#ifdef HAVE_FORK
const bool background_given = map.count("background");
if (background_given)
{
// (Boost) Throws std::runtime_error if fails.
cc::go_background(map["log-file"].as<std::string>(), omit);
}
#endif
// Omit std output. Note that --background flips this above.
cc::log.push(cc::omit_sink(omit));
cc::log.setf(std::ios::fixed);
// Query formats.
if (map.count("query-formats"))
return query_formats(query, qopts, input);
#if defined (HAVE_FORK) && defined (HAVE_GETPID)
if (background_given)
{
cc::log
<< "Running in background (pid: "
<< static_cast<long>(getpid())
<< ")."
<< std::endl;
}
#endif
// For each input URL.
const size_t n = input.size();
size_t i = 0;
const int max_retries = map["max-retries"].as<int>();
const int retry_wait = map["retry-wait"].as<int>();
foreach(std::string url, input)
{
++i;
try
{
int retry = 0;
while (retry <= max_retries)
{
print_retrying(retry, max_retries, retry_wait);
++retry;
print_checking(i, n);
quvi::media m;
try
{
m = query.parse(url, qopts);
}
catch(const quvi::error& e)
{
check_quvi_error(e);
}
cc::get(query, m, map);
break; // Stop retrying.
}
}
catch(const quvi::error& e)
{
print_quvi_error(e);
}
catch(const std::runtime_error& e)
{
cc::log << "error: " << e.what() << std::endl;
}
}
return ok;
}
void application::_tweak_curl_opts(const quvi::query& query,
const po::variables_map& map)
{
CURL *curl = query.curlHandle();
curl_easy_setopt(curl, CURLOPT_USERAGENT,
map["agent"].as<std::string>().c_str());
if (map.count("verbose-curl"))
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
if (map.count("proxy"))
{
curl_easy_setopt(curl, CURLOPT_PROXY,
map["proxy"].as<std::string>().c_str());
}
if (map.count("no-proxy"))
curl_easy_setopt(curl, CURLOPT_PROXY, "");
if (map.count("throttle"))
{
curl_off_t limit = map["throttle"].as<int>()*1024;
curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, limit);
}
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT,
map["connect-timeout"].as<int>());
}
} // namespace cc
// vim: set ts=2 sw=2 tw=72 expandtab:
<|endoftext|> |
<commit_before>#include "cvm.h"
void DabValue::dump(FILE *file) const
{
static const char *types[] = {"INVA", "FIXN", "STRI", "BOOL", "NIL ", "SYMB", "CLAS", "OBJE",
"ARRY", "UIN8", "UI32", "UI64", "IN32", "METH", "PTR*", "BYT*"};
assert((int)data.type >= 0 && (int)data.type < (int)countof(types));
fprintf(file, "%s ", types[data.type]);
print(file, true);
}
int DabValue::class_index() const
{
switch (data.type)
{
case TYPE_FIXNUM:
return CLASS_FIXNUM;
break;
case TYPE_STRING:
return CLASS_STRING;
break;
case TYPE_SYMBOL:
return CLASS_INT_SYMBOL;
break;
case TYPE_BOOLEAN:
return CLASS_BOOLEAN;
break;
case TYPE_NIL:
return CLASS_NILCLASS;
break;
case TYPE_ARRAY:
return CLASS_ARRAY;
break;
case TYPE_CLASS:
return data.fixnum;
break;
case TYPE_OBJECT:
return this->data.object->object->klass;
break;
case TYPE_UINT8:
return CLASS_UINT8;
break;
case TYPE_UINT32:
return CLASS_UINT32;
break;
case TYPE_UINT64:
return CLASS_UINT64;
break;
case TYPE_INT32:
return CLASS_INT32;
break;
case TYPE_METHOD:
return CLASS_METHOD;
break;
case TYPE_INTPTR:
return CLASS_INTPTR;
break;
case TYPE_BYTEBUFFER:
return CLASS_BYTEBUFFER;
break;
default:
fprintf(stderr, "Unknown data.type %d.\n", (int)data.type);
assert(false);
break;
}
}
std::string DabValue::class_name() const
{
return get_class().name;
}
DabClass &DabValue::get_class() const
{
return $VM->get_class(class_index());
}
bool DabValue::is_a(const DabClass &klass) const
{
return get_class().is_subclass_of(klass);
}
void DabValue::print(FILE *out, bool debug) const
{
fprintf(out, "%s", print_value(debug).c_str());
}
std::string DabValue::print_value(bool debug) const
{
char buffer[32] = {0};
std::string ret;
bool use_ret = false;
switch (data.type)
{
case TYPE_FIXNUM:
snprintf(buffer, sizeof(buffer), "%" PRId64, data.fixnum);
break;
case TYPE_UINT8:
snprintf(buffer, sizeof(buffer), "%" PRIu8, data.num_uint8);
break;
case TYPE_UINT32:
snprintf(buffer, sizeof(buffer), "%" PRIu32, data.num_uint32);
break;
case TYPE_UINT64:
snprintf(buffer, sizeof(buffer), "%" PRIu64, data.num_uint64);
break;
case TYPE_INT32:
snprintf(buffer, sizeof(buffer), "%" PRId32, data.num_int32);
break;
case TYPE_STRING:
{
use_ret = true;
ret = data.string;
if (debug)
{
ret = "\"" + ret + "\"";
}
}
break;
case TYPE_SYMBOL:
snprintf(buffer, sizeof(buffer), ":%s", data.string.c_str());
break;
case TYPE_BOOLEAN:
snprintf(buffer, sizeof(buffer), "%s", data.boolean ? "true" : "false");
break;
case TYPE_NIL:
snprintf(buffer, sizeof(buffer), "nil");
break;
case TYPE_CLASS:
snprintf(buffer, sizeof(buffer), "%s", class_name().c_str());
break;
case TYPE_OBJECT:
snprintf(buffer, sizeof(buffer), "#%s", class_name().c_str());
break;
case TYPE_INTPTR:
snprintf(buffer, sizeof(buffer), "%p", data.intptr);
break;
case TYPE_ARRAY:
{
use_ret = true;
ret = "[";
size_t i = 0;
for (auto &item : array())
{
if (i)
ret += ", ";
ret += item.print_value(debug);
i++;
}
ret += "]";
}
break;
default:
snprintf(buffer, sizeof(buffer), "?");
break;
}
if (!use_ret)
{
ret = buffer;
}
if (debug && data.object)
{
char extra[64] = {0};
snprintf(extra, sizeof(extra), " [%d strong]", (int)data.object->count_strong);
ret += extra;
}
return ret;
}
std::vector<DabValue> &DabValue::array() const
{
assert(data.type == TYPE_ARRAY);
auto *obj = (DabArray *)data.object->object;
return obj->array;
}
std::vector<uint8_t> &DabValue::bytebuffer() const
{
assert(data.type == TYPE_BYTEBUFFER);
auto *obj = (DabByteBuffer *)data.object->object;
return obj->bytebuffer;
}
bool DabValue::truthy() const
{
switch (data.type)
{
case TYPE_FIXNUM:
return data.fixnum;
case TYPE_UINT8:
return data.num_uint8;
case TYPE_UINT32:
return data.num_uint32;
case TYPE_UINT64:
return data.num_uint64;
case TYPE_INT32:
return data.num_int32;
case TYPE_STRING:
return data.string.length();
break;
case TYPE_BOOLEAN:
return data.boolean;
case TYPE_INTPTR:
return data.intptr;
case TYPE_NIL:
return false;
case TYPE_ARRAY:
return array().size() > 0;
default:
return true;
}
}
DabValue DabValue::create_instance() const
{
assert(data.type == TYPE_CLASS);
DabBaseObject *object = nullptr;
auto type = TYPE_OBJECT;
if (data.fixnum == CLASS_ARRAY)
{
object = new DabArray;
type = TYPE_ARRAY;
}
else if (data.fixnum == CLASS_BYTEBUFFER)
{
object = new DabByteBuffer;
type = TYPE_BYTEBUFFER;
}
else
{
object = new DabObject;
}
DabObjectProxy *proxy = new DabObjectProxy;
proxy->object = object;
proxy->count_strong = 1;
proxy->object->klass = this->data.fixnum;
DabValue ret;
ret.data.type = type;
ret.data.object = proxy;
if ($VM->verbose)
{
fprintf(stderr, "vm: proxy %p (strong %d): ! created\n", proxy, (int)proxy->count_strong);
}
return ret;
}
DabValue DabValue::_get_instvar(const std::string &name)
{
assert(this->data.type == TYPE_OBJECT);
assert(this->data.object);
if (!this->data.object->object)
{
return DabValue(nullptr);
}
auto object = (DabObject *)this->data.object->object;
auto &instvars = object->instvars;
if (!instvars.count(name))
{
return DabValue(nullptr);
}
return instvars[name];
}
DabValue DabValue::get_instvar(const std::string &name)
{
auto ret = _get_instvar(name);
if ($VM->verbose)
{
fprintf(stderr, "vm: proxy %p (strong %d): Get instvar <%s> -> ", this->data.object,
(int)this->data.object->count_strong, name.c_str());
ret.print(stderr);
fprintf(stderr, "\n");
}
return ret;
}
void DabValue::set_instvar(const std::string &name, const DabValue &value)
{
assert(this->data.type == TYPE_OBJECT);
assert(this->data.object);
if ($VM->verbose)
{
fprintf(stderr, "vm: proxy %p (strong %d): Set instvar <%s> to ", this->data.object,
(int)this->data.object->count_strong, name.c_str());
value.print(stderr);
fprintf(stderr, "\n");
}
if (!this->data.object->object)
{
return;
}
auto object = (DabObject *)this->data.object->object;
auto &instvars = object->instvars;
instvars[name] = value;
}
void DabValue::set_data(const DabValueData &other_data)
{
data = other_data;
if ($VM->autorelease)
{
retain();
}
}
DabValue::DabValue(const DabValue &other)
{
set_data(other.data);
}
DabValue &DabValue::operator=(const DabValue &other)
{
set_data(other.data);
return *this;
}
DabValue::~DabValue()
{
if ($VM->autorelease)
{
release();
}
}
void DabValue::release()
{
if (this->data.type == TYPE_OBJECT || data.type == TYPE_ARRAY)
{
this->data.object->release(this);
this->data.object = nullptr;
}
this->data.type = TYPE_NIL;
}
void DabValue::retain()
{
if (data.type == TYPE_OBJECT || data.type == TYPE_ARRAY)
{
data.object->retain(this);
}
}
//
void DabObjectProxy::retain(DabValue *value)
{
(void)value;
if (this->destroying)
return;
count_strong += 1;
if ($VM->verbose)
{
fprintf(stderr, "vm: proxy %p (strong %d): + retained\n", this, (int)this->count_strong);
}
}
void DabObjectProxy::release(DabValue *value)
{
if (this->destroying)
return;
count_strong -= 1;
if ($VM->verbose)
{
fprintf(stderr, "vm: proxy %p (strong %d): - released\n", this, (int)this->count_strong);
}
if (count_strong == 0)
{
destroy(value);
}
}
void DabObjectProxy::destroy(DabValue *value)
{
(void)value;
this->destroying = true;
fprintf(stderr, "vm: proxy %p (strong %d): X destroy\n", this, (int)this->count_strong);
delete object;
delete this;
}
size_t DabValue::use_count() const
{
if (data.object)
{
return data.object->count_strong;
}
else
{
return 65535;
}
}
<commit_msg>vm: extra debug info for reference counting<commit_after>#include "cvm.h"
void DabValue::dump(FILE *file) const
{
static const char *types[] = {"INVA", "FIXN", "STRI", "BOOL", "NIL ", "SYMB", "CLAS", "OBJE",
"ARRY", "UIN8", "UI32", "UI64", "IN32", "METH", "PTR*", "BYT*"};
assert((int)data.type >= 0 && (int)data.type < (int)countof(types));
fprintf(file, "%s ", types[data.type]);
print(file, true);
}
int DabValue::class_index() const
{
switch (data.type)
{
case TYPE_FIXNUM:
return CLASS_FIXNUM;
break;
case TYPE_STRING:
return CLASS_STRING;
break;
case TYPE_SYMBOL:
return CLASS_INT_SYMBOL;
break;
case TYPE_BOOLEAN:
return CLASS_BOOLEAN;
break;
case TYPE_NIL:
return CLASS_NILCLASS;
break;
case TYPE_ARRAY:
return CLASS_ARRAY;
break;
case TYPE_CLASS:
return data.fixnum;
break;
case TYPE_OBJECT:
return this->data.object->object->klass;
break;
case TYPE_UINT8:
return CLASS_UINT8;
break;
case TYPE_UINT32:
return CLASS_UINT32;
break;
case TYPE_UINT64:
return CLASS_UINT64;
break;
case TYPE_INT32:
return CLASS_INT32;
break;
case TYPE_METHOD:
return CLASS_METHOD;
break;
case TYPE_INTPTR:
return CLASS_INTPTR;
break;
case TYPE_BYTEBUFFER:
return CLASS_BYTEBUFFER;
break;
default:
fprintf(stderr, "Unknown data.type %d.\n", (int)data.type);
assert(false);
break;
}
}
std::string DabValue::class_name() const
{
return get_class().name;
}
DabClass &DabValue::get_class() const
{
return $VM->get_class(class_index());
}
bool DabValue::is_a(const DabClass &klass) const
{
return get_class().is_subclass_of(klass);
}
void DabValue::print(FILE *out, bool debug) const
{
fprintf(out, "%s", print_value(debug).c_str());
}
std::string DabValue::print_value(bool debug) const
{
char buffer[32] = {0};
std::string ret;
bool use_ret = false;
switch (data.type)
{
case TYPE_FIXNUM:
snprintf(buffer, sizeof(buffer), "%" PRId64, data.fixnum);
break;
case TYPE_UINT8:
snprintf(buffer, sizeof(buffer), "%" PRIu8, data.num_uint8);
break;
case TYPE_UINT32:
snprintf(buffer, sizeof(buffer), "%" PRIu32, data.num_uint32);
break;
case TYPE_UINT64:
snprintf(buffer, sizeof(buffer), "%" PRIu64, data.num_uint64);
break;
case TYPE_INT32:
snprintf(buffer, sizeof(buffer), "%" PRId32, data.num_int32);
break;
case TYPE_STRING:
{
use_ret = true;
ret = data.string;
if (debug)
{
ret = "\"" + ret + "\"";
}
}
break;
case TYPE_SYMBOL:
snprintf(buffer, sizeof(buffer), ":%s", data.string.c_str());
break;
case TYPE_BOOLEAN:
snprintf(buffer, sizeof(buffer), "%s", data.boolean ? "true" : "false");
break;
case TYPE_NIL:
snprintf(buffer, sizeof(buffer), "nil");
break;
case TYPE_CLASS:
snprintf(buffer, sizeof(buffer), "%s", class_name().c_str());
break;
case TYPE_OBJECT:
snprintf(buffer, sizeof(buffer), "#%s", class_name().c_str());
break;
case TYPE_INTPTR:
snprintf(buffer, sizeof(buffer), "%p", data.intptr);
break;
case TYPE_ARRAY:
{
use_ret = true;
ret = "[";
size_t i = 0;
for (auto &item : array())
{
if (i)
ret += ", ";
ret += item.print_value(debug);
i++;
}
ret += "]";
}
break;
default:
snprintf(buffer, sizeof(buffer), "?");
break;
}
if (!use_ret)
{
ret = buffer;
}
if (debug && data.object)
{
char extra[64] = {0};
snprintf(extra, sizeof(extra), " [%d strong]", (int)data.object->count_strong);
ret += extra;
}
return ret;
}
std::vector<DabValue> &DabValue::array() const
{
assert(data.type == TYPE_ARRAY);
auto *obj = (DabArray *)data.object->object;
return obj->array;
}
std::vector<uint8_t> &DabValue::bytebuffer() const
{
assert(data.type == TYPE_BYTEBUFFER);
auto *obj = (DabByteBuffer *)data.object->object;
return obj->bytebuffer;
}
bool DabValue::truthy() const
{
switch (data.type)
{
case TYPE_FIXNUM:
return data.fixnum;
case TYPE_UINT8:
return data.num_uint8;
case TYPE_UINT32:
return data.num_uint32;
case TYPE_UINT64:
return data.num_uint64;
case TYPE_INT32:
return data.num_int32;
case TYPE_STRING:
return data.string.length();
break;
case TYPE_BOOLEAN:
return data.boolean;
case TYPE_INTPTR:
return data.intptr;
case TYPE_NIL:
return false;
case TYPE_ARRAY:
return array().size() > 0;
default:
return true;
}
}
DabValue DabValue::create_instance() const
{
assert(data.type == TYPE_CLASS);
DabBaseObject *object = nullptr;
auto type = TYPE_OBJECT;
if (data.fixnum == CLASS_ARRAY)
{
object = new DabArray;
type = TYPE_ARRAY;
}
else if (data.fixnum == CLASS_BYTEBUFFER)
{
object = new DabByteBuffer;
type = TYPE_BYTEBUFFER;
}
else
{
object = new DabObject;
}
DabObjectProxy *proxy = new DabObjectProxy;
proxy->object = object;
proxy->count_strong = 1;
proxy->object->klass = this->data.fixnum;
DabValue ret;
ret.data.type = type;
ret.data.object = proxy;
if ($VM->verbose)
{
fprintf(stderr, "vm: proxy %p (strong %3d): ! created : ", proxy, (int)proxy->count_strong);
ret.dump(stderr);
fprintf(stderr, "\n");
}
return ret;
}
DabValue DabValue::_get_instvar(const std::string &name)
{
assert(this->data.type == TYPE_OBJECT);
assert(this->data.object);
if (!this->data.object->object)
{
return DabValue(nullptr);
}
auto object = (DabObject *)this->data.object->object;
auto &instvars = object->instvars;
if (!instvars.count(name))
{
return DabValue(nullptr);
}
return instvars[name];
}
DabValue DabValue::get_instvar(const std::string &name)
{
auto ret = _get_instvar(name);
if ($VM->verbose)
{
fprintf(stderr, "vm: proxy %p (strong %d): Get instvar <%s> -> ", this->data.object,
(int)this->data.object->count_strong, name.c_str());
ret.print(stderr);
fprintf(stderr, "\n");
}
return ret;
}
void DabValue::set_instvar(const std::string &name, const DabValue &value)
{
assert(this->data.type == TYPE_OBJECT);
assert(this->data.object);
if ($VM->verbose)
{
fprintf(stderr, "vm: proxy %p (strong %d): Set instvar <%s> to ", this->data.object,
(int)this->data.object->count_strong, name.c_str());
value.print(stderr);
fprintf(stderr, "\n");
}
if (!this->data.object->object)
{
return;
}
auto object = (DabObject *)this->data.object->object;
auto &instvars = object->instvars;
instvars[name] = value;
}
void DabValue::set_data(const DabValueData &other_data)
{
data = other_data;
if ($VM->autorelease)
{
retain();
}
}
DabValue::DabValue(const DabValue &other)
{
set_data(other.data);
}
DabValue &DabValue::operator=(const DabValue &other)
{
set_data(other.data);
return *this;
}
DabValue::~DabValue()
{
if ($VM->autorelease)
{
release();
}
}
void DabValue::release()
{
if (this->data.type == TYPE_OBJECT || data.type == TYPE_ARRAY)
{
this->data.object->release(this);
this->data.object = nullptr;
}
this->data.type = TYPE_NIL;
}
void DabValue::retain()
{
if (data.type == TYPE_OBJECT || data.type == TYPE_ARRAY)
{
data.object->retain(this);
}
}
//
void DabObjectProxy::retain(DabValue *value)
{
(void)value;
if (this->destroying)
return;
count_strong += 1;
if ($VM->verbose)
{
fprintf(stderr, "vm: proxy %p (strong %3d): + retained: ", this, (int)this->count_strong);
value->dump(stderr);
fprintf(stderr, "\n");
}
}
void DabObjectProxy::release(DabValue *value)
{
if (this->destroying)
return;
count_strong -= 1;
if ($VM->verbose)
{
fprintf(stderr, "vm: proxy %p (strong %3d): - released: ", this, (int)this->count_strong);
value->dump(stderr);
fprintf(stderr, "\n");
}
if (count_strong == 0)
{
destroy(value);
}
}
void DabObjectProxy::destroy(DabValue *value)
{
(void)value;
this->destroying = true;
fprintf(stderr, "vm: proxy %p (strong %3d): X destroy\n", this, (int)this->count_strong);
delete object;
delete this;
}
size_t DabValue::use_count() const
{
if (data.object)
{
return data.object->count_strong;
}
else
{
return 65535;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/obstacle/onboard/camera_process_subnode.h"
#include <unordered_map>
#include "modules/perception/traffic_light/util/color_space.h"
namespace apollo {
namespace perception {
using apollo::common::adapter::AdapterManager;
bool CameraProcessSubnode::InitInternal() {
// Subnode config in DAG streaming
std::unordered_map<std::string, std::string> fields;
SubnodeHelper::ParseReserveField(reserve_, &fields);
device_id_ = fields["device_id"];
// Shared Data
cam_obj_data_ = static_cast<CameraObjectData *>(
shared_data_manager_->GetSharedData("CameraObjectData"));
cam_shared_data_ = static_cast<CameraSharedData *>(
shared_data_manager_->GetSharedData("CameraSharedData"));
InitCalibration();
InitModules();
AdapterManager::AddImageShortCallback(&CameraProcessSubnode::ImgCallback,
this);
return true;
}
bool CameraProcessSubnode::InitCalibration() {
auto ccm = Singleton<CalibrationConfigManager>::get();
CameraCalibrationPtr calibrator = ccm->get_camera_calibration();
// calibrator->get_image_height_width(&image_height_, &image_width_);
camera_to_car_ = calibrator->get_camera_extrinsics();
intrinsics_ = calibrator->get_camera_intrinsic();
undistortion_handler_ = calibrator->get_camera_undistort_handler();
return true;
}
bool CameraProcessSubnode::InitModules() {
RegisterFactoryYoloCameraDetector();
RegisterFactoryGeometryCameraConverter();
RegisterFactoryCascadedCameraTracker();
RegisterFactoryFlatCameraTransformer();
RegisterFactoryObjectCameraFilter();
detector_.reset(
BaseCameraDetectorRegisterer::GetInstanceByName("YoloCameraDetector"));
detector_->Init();
converter_.reset(BaseCameraConverterRegisterer::GetInstanceByName(
"GeometryCameraConverter"));
converter_->Init();
tracker_.reset(
BaseCameraTrackerRegisterer::GetInstanceByName("CascadedCameraTracker"));
tracker_->Init();
transformer_.reset(BaseCameraTransformerRegisterer::GetInstanceByName(
"FlatCameraTransformer"));
transformer_->Init();
// transformer_->SetExtrinsics(camera_to_car_);
filter_.reset(
BaseCameraFilterRegisterer::GetInstanceByName("ObjectCameraFilter"));
filter_->Init();
return true;
}
void CameraProcessSubnode::ImgCallback(const sensor_msgs::Image &message) {
AdapterManager::Observe();
sensor_msgs::Image msg = AdapterManager::GetImageShort()->GetLatestObserved();
double timestamp = msg.header.stamp.toSec();
AINFO << "CameraProcessSubnode ImgCallback: "
<< " frame: " << ++seq_num_ << " timestamp: ";
AINFO << std::fixed << std::setprecision(64) << timestamp;
cv::Mat img;
if (!FLAGS_image_file_debug) {
MessageToMat(msg, &img);
} else {
img = cv::imread(FLAGS_image_file_path, CV_LOAD_IMAGE_COLOR);
}
std::vector<VisualObjectPtr> objects;
cv::Mat mask = cv::Mat::zeros(img.rows, img.cols, CV_32FC1);
detector_->Multitask(img, CameraDetectorOptions(), &objects, &mask);
converter_->Convert(&objects);
tracker_->Associate(img, timestamp, &objects);
transformer_->Transform(&objects);
filter_->Filter(timestamp, &objects);
std::shared_ptr<SensorObjects> out_objs(new SensorObjects);
out_objs->timestamp = timestamp;
VisualObjToSensorObj(objects, &out_objs);
SharedDataPtr<CameraItem> camera_item_ptr(new CameraItem);
camera_item_ptr->image_src_mat = img.clone();
mask.copyTo(out_objs->camera_frame_supplement->lane_map);
PublishDataAndEvent(timestamp, out_objs, camera_item_ptr);
}
bool CameraProcessSubnode::MessageToMat(const sensor_msgs::Image &msg,
cv::Mat *img) {
cv::Mat cv_img;
if (msg.encoding.compare("yuyv") == 0) {
unsigned char *yuv = (unsigned char *)&(msg.data[0]);
cv_img = cv::Mat(msg.height, msg.width, CV_8UC3);
traffic_light::Yuyv2rgb(yuv, cv_img.data, msg.height * msg.width);
cv::cvtColor(cv_img, cv_img, CV_RGB2BGR);
} else {
cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg,
sensor_msgs::image_encodings::BGR8);
cv_img = cv_ptr->image;
}
if (cv_img.rows != image_height_ || cv_img.cols != image_width_) {
cv::resize(cv_img, cv_img, cv::Size(image_width_, image_height_));
}
*img = cv_img.clone();
return true;
}
void CameraProcessSubnode::VisualObjToSensorObj(
const std::vector<VisualObjectPtr> &objects,
SharedDataPtr<SensorObjects> *sensor_objects) {
(*sensor_objects)->sensor_type = SensorType::CAMERA;
(*sensor_objects)->sensor_id = device_id_;
(*sensor_objects)->seq_num = seq_num_;
(*sensor_objects)->sensor2world_pose = camera_to_car_;
((*sensor_objects)->camera_frame_supplement).reset(new CameraFrameSupplement);
for (size_t i = 0; i < objects.size(); ++i) {
VisualObjectPtr vobj = objects[i];
ObjectPtr obj(new Object());
obj->id = vobj->id;
obj->direction = vobj->direction.cast<double>();
obj->theta = vobj->theta;
obj->center = vobj->center.cast<double>();
obj->length = vobj->length;
obj->width = vobj->width;
obj->height = vobj->height;
obj->type = vobj->type;
obj->track_id = vobj->track_id;
obj->tracking_time = vobj->track_age;
obj->latest_tracked_time = vobj->last_track_timestamp;
obj->velocity = vobj->velocity.cast<double>();
obj->anchor_point = obj->center.cast<double>();
(obj->camera_supplement).reset(new CameraSupplement());
obj->camera_supplement->upper_left = vobj->upper_left.cast<double>();
obj->camera_supplement->lower_right = vobj->lower_right.cast<double>();
obj->camera_supplement->alpha = vobj->alpha;
// obj->type_probs.assign(vobj->type_probs,
// vobj->type_probs + MAX_OBJECT_TYPE);
// obj->camera_supplement->pts8.assign(vobj->pts8,
// vobj->pts8 + 16);
((*sensor_objects)->objects).emplace_back(obj);
}
}
void CameraProcessSubnode::PublishDataAndEvent(
const double ×tamp, const SharedDataPtr<SensorObjects> &sensor_objects,
const SharedDataPtr<CameraItem> &camera_item) {
std::string key = "";
SubnodeHelper::ProduceSharedDataKey(timestamp, device_id_, &key);
cam_obj_data_->Add(key, sensor_objects);
cam_shared_data_->Add(key, camera_item);
for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
const EventMeta &event_meta = pub_meta_events_[idx];
Event event;
event.event_id = event_meta.event_id;
event.timestamp = timestamp;
event.reserve = device_id_;
event_manager_->Publish(event);
}
}
} // namespace perception
} // namespace apollo
<commit_msg>code janitor: clean code for previous commits<commit_after>/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/perception/obstacle/onboard/camera_process_subnode.h"
#include <unordered_map>
#include "modules/perception/traffic_light/util/color_space.h"
namespace apollo {
namespace perception {
using apollo::common::adapter::AdapterManager;
bool CameraProcessSubnode::InitInternal() {
// Subnode config in DAG streaming
std::unordered_map<std::string, std::string> fields;
SubnodeHelper::ParseReserveField(reserve_, &fields);
device_id_ = fields["device_id"];
// Shared Data
cam_obj_data_ = static_cast<CameraObjectData *>(
shared_data_manager_->GetSharedData("CameraObjectData"));
cam_shared_data_ = static_cast<CameraSharedData *>(
shared_data_manager_->GetSharedData("CameraSharedData"));
InitCalibration();
InitModules();
AdapterManager::AddImageShortCallback(&CameraProcessSubnode::ImgCallback,
this);
return true;
}
bool CameraProcessSubnode::InitCalibration() {
auto ccm = Singleton<CalibrationConfigManager>::get();
CameraCalibrationPtr calibrator = ccm->get_camera_calibration();
// calibrator->get_image_height_width(&image_height_, &image_width_);
camera_to_car_ = calibrator->get_camera_extrinsics();
intrinsics_ = calibrator->get_camera_intrinsic();
undistortion_handler_ = calibrator->get_camera_undistort_handler();
return true;
}
bool CameraProcessSubnode::InitModules() {
RegisterFactoryYoloCameraDetector();
RegisterFactoryGeometryCameraConverter();
RegisterFactoryCascadedCameraTracker();
RegisterFactoryFlatCameraTransformer();
RegisterFactoryObjectCameraFilter();
detector_.reset(
BaseCameraDetectorRegisterer::GetInstanceByName("YoloCameraDetector"));
detector_->Init();
converter_.reset(BaseCameraConverterRegisterer::GetInstanceByName(
"GeometryCameraConverter"));
converter_->Init();
tracker_.reset(
BaseCameraTrackerRegisterer::GetInstanceByName("CascadedCameraTracker"));
tracker_->Init();
transformer_.reset(BaseCameraTransformerRegisterer::GetInstanceByName(
"FlatCameraTransformer"));
transformer_->Init();
// transformer_->SetExtrinsics(camera_to_car_);
filter_.reset(
BaseCameraFilterRegisterer::GetInstanceByName("ObjectCameraFilter"));
filter_->Init();
return true;
}
void CameraProcessSubnode::ImgCallback(const sensor_msgs::Image &message) {
AdapterManager::Observe();
sensor_msgs::Image msg = AdapterManager::GetImageShort()->GetLatestObserved();
double timestamp = msg.header.stamp.toSec();
AINFO << "CameraProcessSubnode ImgCallback: "
<< " frame: " << ++seq_num_ << " timestamp: ";
AINFO << std::fixed << std::setprecision(64) << timestamp;
cv::Mat img;
if (!FLAGS_image_file_debug) {
MessageToMat(msg, &img);
} else {
img = cv::imread(FLAGS_image_file_path, CV_LOAD_IMAGE_COLOR);
}
std::vector<VisualObjectPtr> objects;
cv::Mat mask = cv::Mat::zeros(img.rows, img.cols, CV_32FC1);
detector_->Multitask(img, CameraDetectorOptions(), &objects, &mask);
converter_->Convert(&objects);
tracker_->Associate(img, timestamp, &objects);
transformer_->Transform(&objects);
filter_->Filter(timestamp, &objects);
std::shared_ptr<SensorObjects> out_objs(new SensorObjects);
out_objs->timestamp = timestamp;
VisualObjToSensorObj(objects, &out_objs);
SharedDataPtr<CameraItem> camera_item_ptr(new CameraItem);
camera_item_ptr->image_src_mat = img.clone();
mask.copyTo(out_objs->camera_frame_supplement->lane_map);
PublishDataAndEvent(timestamp, out_objs, camera_item_ptr);
}
bool CameraProcessSubnode::MessageToMat(const sensor_msgs::Image &msg,
cv::Mat *img) {
cv::Mat cv_img;
if (msg.encoding.compare("yuyv") == 0) {
unsigned char *yuv = (unsigned char *)&(msg.data[0]);
cv_img = cv::Mat(msg.height, msg.width, CV_8UC3);
traffic_light::Yuyv2rgb(yuv, cv_img.data, msg.height * msg.width);
cv::cvtColor(cv_img, cv_img, CV_RGB2BGR);
} else {
cv_bridge::CvImagePtr cv_ptr =
cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
cv_img = cv_ptr->image;
}
if (cv_img.rows != image_height_ || cv_img.cols != image_width_) {
cv::resize(cv_img, cv_img, cv::Size(image_width_, image_height_));
}
*img = cv_img.clone();
return true;
}
void CameraProcessSubnode::VisualObjToSensorObj(
const std::vector<VisualObjectPtr> &objects,
SharedDataPtr<SensorObjects> *sensor_objects) {
(*sensor_objects)->sensor_type = SensorType::CAMERA;
(*sensor_objects)->sensor_id = device_id_;
(*sensor_objects)->seq_num = seq_num_;
(*sensor_objects)->sensor2world_pose = camera_to_car_;
((*sensor_objects)->camera_frame_supplement).reset(new CameraFrameSupplement);
for (size_t i = 0; i < objects.size(); ++i) {
VisualObjectPtr vobj = objects[i];
ObjectPtr obj(new Object());
obj->id = vobj->id;
obj->direction = vobj->direction.cast<double>();
obj->theta = vobj->theta;
obj->center = vobj->center.cast<double>();
obj->length = vobj->length;
obj->width = vobj->width;
obj->height = vobj->height;
obj->type = vobj->type;
obj->track_id = vobj->track_id;
obj->tracking_time = vobj->track_age;
obj->latest_tracked_time = vobj->last_track_timestamp;
obj->velocity = vobj->velocity.cast<double>();
obj->anchor_point = obj->center.cast<double>();
(obj->camera_supplement).reset(new CameraSupplement());
obj->camera_supplement->upper_left = vobj->upper_left.cast<double>();
obj->camera_supplement->lower_right = vobj->lower_right.cast<double>();
obj->camera_supplement->alpha = vobj->alpha;
// obj->type_probs.assign(vobj->type_probs,
// vobj->type_probs + MAX_OBJECT_TYPE);
// obj->camera_supplement->pts8.assign(vobj->pts8,
// vobj->pts8 + 16);
((*sensor_objects)->objects).emplace_back(obj);
}
}
void CameraProcessSubnode::PublishDataAndEvent(
const double ×tamp, const SharedDataPtr<SensorObjects> &sensor_objects,
const SharedDataPtr<CameraItem> &camera_item) {
std::string key = "";
SubnodeHelper::ProduceSharedDataKey(timestamp, device_id_, &key);
cam_obj_data_->Add(key, sensor_objects);
cam_shared_data_->Add(key, camera_item);
for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {
const EventMeta &event_meta = pub_meta_events_[idx];
Event event;
event.event_id = event_meta.event_id;
event.timestamp = timestamp;
event.reserve = device_id_;
event_manager_->Publish(event);
}
}
} // namespace perception
} // namespace apollo
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2015 The Dash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coinbase-payee.h"
#include "util.h"
#include "addrman.h"
#include "masternode.h"
#include "darksend.h"
#include "masternodeman.h"
#include <boost/filesystem.hpp>
CCoinbasePayee coinbasePayee;
//
// CCoinbasePayeeDB
//
CCoinbasePayeeDB::CCoinbasePayeeDB()
{
pathDB = GetDataDir() / "coinbase-payee.dat";
strMagicMessage = "CoinbasePayeeDB";
}
bool CCoinbasePayeeDB::Write(const CCoinbasePayee& objToSave)
{
int64_t nStart = GetTimeMillis();
// serialize, checksum data up to that point, then append checksum
CDataStream ssObj(SER_DISK, CLIENT_VERSION);
ssObj << strMagicMessage; // coinbase payee cache file specific magic message
ssObj << FLATDATA(Params().MessageStart()); // network specific magic number
ssObj << objToSave;
uint256 hash = Hash(ssObj.begin(), ssObj.end());
ssObj << hash;
// open output file, and associate with CAutoFile
FILE *file = fopen(pathDB.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s : Failed to open file %s", __func__, pathDB.string());
// Write and commit header, data
try {
fileout << ssObj;
}
catch (std::exception &e) {
return error("%s : Serialize or I/O error - %s", __func__, e.what());
}
fileout.fclose();
LogPrintf("Written info to coinbase-payee.dat %dms\n", GetTimeMillis() - nStart);
return true;
}
CCoinbasePayeeDB::ReadResult CCoinbasePayeeDB::Read(CCoinbasePayee& objToLoad)
{
int64_t nStart = GetTimeMillis();
// open input file, and associate with CAutoFile
FILE *file = fopen(pathDB.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
{
error("%s : Failed to open file %s", __func__, pathDB.string());
return FileError;
}
// use file size to size memory buffer
int fileSize = boost::filesystem::file_size(pathDB);
int dataSize = fileSize - sizeof(uint256);
// Don't try to resize to a negative number if file is small
if (dataSize < 0)
dataSize = 0;
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char *)&vchData[0], dataSize);
filein >> hashIn;
}
catch (std::exception &e) {
error("%s : Deserialize or I/O error - %s", __func__, e.what());
return HashReadError;
}
filein.fclose();
CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssObj.begin(), ssObj.end());
if (hashIn != hashTmp)
{
error("%s : Checksum mismatch, data corrupted", __func__);
return IncorrectHash;
}
unsigned char pchMsgTmp[4];
std::string strMagicMessageTmp;
try {
// de-serialize file header (coinbase payee cache file specific magic message) and ..
ssObj >> strMagicMessageTmp;
// ... verify the message matches predefined one
if (strMagicMessage != strMagicMessageTmp)
{
error("%s : Invalid coinbase payee cache magic message", __func__);
return IncorrectMagicMessage;
}
// de-serialize file header (network specific magic number) and ..
ssObj >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
{
error("%s : Invalid network magic number", __func__);
return IncorrectMagicNumber;
}
// de-serialize data into CCoinbasePayee object
ssObj >> objToLoad;
}
catch (std::exception &e) {
objToLoad.Clear();
error("%s : Deserialize or I/O error - %s", __func__, e.what());
return IncorrectFormat;
}
objToLoad.CleanUp(); // clean out expired
LogPrintf("Loaded info from coinbase-payee.dat %dms\n", GetTimeMillis() - nStart);
LogPrintf(" %s\n", objToLoad.ToString());
return Ok;
}
void DumpCoinbasePayees()
{
int64_t nStart = GetTimeMillis();
CCoinbasePayeeDB mndb;
CCoinbasePayee temp;
LogPrintf("Verifying coinbase-payee.dat format...\n");
CCoinbasePayeeDB::ReadResult readResult = mndb.Read(temp);
// there was an error and it was not an error on file openning => do not proceed
if (readResult == CCoinbasePayeeDB::FileError)
LogPrintf("Missing payees cache file - coinbase-payee.dat, will try to recreate\n");
else if (readResult != CCoinbasePayeeDB::Ok)
{
LogPrintf("Error reading coinbase-payee.dat: ");
if(readResult == CCoinbasePayeeDB::IncorrectFormat)
LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
else
{
LogPrintf("file format is unknown or invalid, please fix it manually\n");
return;
}
}
LogPrintf("Writting info to coinbase-payee.dat...\n");
mndb.Write(coinbasePayee);
LogPrintf("Coinbase payee dump finished %dms\n", GetTimeMillis() - nStart);
}
void CCoinbasePayee::BuildIndex(bool bForced)
{
if(mapPaidTime.size() > 0 && !bForced) {
LogPrintf("CCoinbasePayee::BuildIndex - coinbase cache exists, skipping BuildIndex\n");
return;
} else if(bForced) {
if(fDebug) LogPrintf("CCoinbasePayee::BuildIndex - Rebuilding coinbase cache\n");
mapPaidTime.clear();
}
//scan last 30 days worth of blocks, run processBlockCoinbaseTX for each
CBlockIndex* pindexPrev = chainActive.Tip();
int count = 0;
for (unsigned int i = 1; pindexPrev && pindexPrev->nHeight > 0; i++) {
count++;
if(count > 18000) return;
CBlock block;
if (ReadBlockFromDisk(block, pindexPrev)) {
ProcessBlockCoinbaseTX(block.vtx[0], block.nTime);
}
if (pindexPrev->pprev == NULL) { assert(pindexPrev); break; }
pindexPrev = pindexPrev->pprev;
}
return;
}
void CCoinbasePayee::ProcessBlockCoinbaseTX(CTransaction& txCoinbase, int64_t nTime)
{
if (!txCoinbase.IsCoinBase()){
LogPrintf("ERROR: CCoinbasePayee::ProcessBlockCoinbaseTX - tx is not coinbase\n");
return;
}
BOOST_FOREACH(CTxOut out, txCoinbase.vout){
uint256 h = GetScriptHash(out.scriptPubKey);
LogPrintf("CCoinbasePayee::ProcessBlockCoinbaseTX - %s - %d\n", h.ToString(), nTime);
if(mapPaidTime.count(h)){
if(mapPaidTime[h] < nTime) {
mapPaidTime[h] = nTime;
}
} else {
mapPaidTime[h] = nTime;
}
}
}
int64_t CCoinbasePayee::GetLastPaid(CScript& pubkey)
{
uint256 h = GetScriptHash(pubkey);
if(mapPaidTime.count(h)){
return mapPaidTime[h];
}
return 0;
}
void CCoinbasePayee::CleanUp()
{
std::map<uint256, int64_t>::iterator it = mapPaidTime.begin();
while(it != mapPaidTime.end())
{
//keep 30 days of history
if((*it).second < GetAdjustedTime() - (60*60*24*30)) {
mapPaidTime.erase(it++);
} else {
++it;
}
}
}
<commit_msg>Disabled coinpayee cleanup<commit_after>// Copyright (c) 2014-2015 The Dash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coinbase-payee.h"
#include "util.h"
#include "addrman.h"
#include "masternode.h"
#include "darksend.h"
#include "masternodeman.h"
#include <boost/filesystem.hpp>
CCoinbasePayee coinbasePayee;
//
// CCoinbasePayeeDB
//
CCoinbasePayeeDB::CCoinbasePayeeDB()
{
pathDB = GetDataDir() / "coinbase-payee.dat";
strMagicMessage = "CoinbasePayeeDB";
}
bool CCoinbasePayeeDB::Write(const CCoinbasePayee& objToSave)
{
int64_t nStart = GetTimeMillis();
// serialize, checksum data up to that point, then append checksum
CDataStream ssObj(SER_DISK, CLIENT_VERSION);
ssObj << strMagicMessage; // coinbase payee cache file specific magic message
ssObj << FLATDATA(Params().MessageStart()); // network specific magic number
ssObj << objToSave;
uint256 hash = Hash(ssObj.begin(), ssObj.end());
ssObj << hash;
// open output file, and associate with CAutoFile
FILE *file = fopen(pathDB.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s : Failed to open file %s", __func__, pathDB.string());
// Write and commit header, data
try {
fileout << ssObj;
}
catch (std::exception &e) {
return error("%s : Serialize or I/O error - %s", __func__, e.what());
}
fileout.fclose();
LogPrintf("Written info to coinbase-payee.dat %dms\n", GetTimeMillis() - nStart);
return true;
}
CCoinbasePayeeDB::ReadResult CCoinbasePayeeDB::Read(CCoinbasePayee& objToLoad)
{
int64_t nStart = GetTimeMillis();
// open input file, and associate with CAutoFile
FILE *file = fopen(pathDB.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
{
error("%s : Failed to open file %s", __func__, pathDB.string());
return FileError;
}
// use file size to size memory buffer
int fileSize = boost::filesystem::file_size(pathDB);
int dataSize = fileSize - sizeof(uint256);
// Don't try to resize to a negative number if file is small
if (dataSize < 0)
dataSize = 0;
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char *)&vchData[0], dataSize);
filein >> hashIn;
}
catch (std::exception &e) {
error("%s : Deserialize or I/O error - %s", __func__, e.what());
return HashReadError;
}
filein.fclose();
CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssObj.begin(), ssObj.end());
if (hashIn != hashTmp)
{
error("%s : Checksum mismatch, data corrupted", __func__);
return IncorrectHash;
}
unsigned char pchMsgTmp[4];
std::string strMagicMessageTmp;
try {
// de-serialize file header (coinbase payee cache file specific magic message) and ..
ssObj >> strMagicMessageTmp;
// ... verify the message matches predefined one
if (strMagicMessage != strMagicMessageTmp)
{
error("%s : Invalid coinbase payee cache magic message", __func__);
return IncorrectMagicMessage;
}
// de-serialize file header (network specific magic number) and ..
ssObj >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
{
error("%s : Invalid network magic number", __func__);
return IncorrectMagicNumber;
}
// de-serialize data into CCoinbasePayee object
ssObj >> objToLoad;
}
catch (std::exception &e) {
objToLoad.Clear();
error("%s : Deserialize or I/O error - %s", __func__, e.what());
return IncorrectFormat;
}
objToLoad.CleanUp(); // clean out expired
LogPrintf("Loaded info from coinbase-payee.dat %dms\n", GetTimeMillis() - nStart);
LogPrintf(" %s\n", objToLoad.ToString());
return Ok;
}
void DumpCoinbasePayees()
{
int64_t nStart = GetTimeMillis();
CCoinbasePayeeDB mndb;
CCoinbasePayee temp;
LogPrintf("Verifying coinbase-payee.dat format...\n");
CCoinbasePayeeDB::ReadResult readResult = mndb.Read(temp);
// there was an error and it was not an error on file openning => do not proceed
if (readResult == CCoinbasePayeeDB::FileError)
LogPrintf("Missing payees cache file - coinbase-payee.dat, will try to recreate\n");
else if (readResult != CCoinbasePayeeDB::Ok)
{
LogPrintf("Error reading coinbase-payee.dat: ");
if(readResult == CCoinbasePayeeDB::IncorrectFormat)
LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
else
{
LogPrintf("file format is unknown or invalid, please fix it manually\n");
return;
}
}
LogPrintf("Writting info to coinbase-payee.dat...\n");
mndb.Write(coinbasePayee);
LogPrintf("Coinbase payee dump finished %dms\n", GetTimeMillis() - nStart);
}
void CCoinbasePayee::BuildIndex(bool bForced)
{
if(mapPaidTime.size() > 0 && !bForced) {
LogPrintf("CCoinbasePayee::BuildIndex - coinbase cache exists, skipping BuildIndex\n");
return;
} else if(bForced) {
if(fDebug) LogPrintf("CCoinbasePayee::BuildIndex - Rebuilding coinbase cache\n");
mapPaidTime.clear();
}
//scan last 30 days worth of blocks, run processBlockCoinbaseTX for each
CBlockIndex* pindexPrev = chainActive.Tip();
int count = 0;
for (unsigned int i = 1; pindexPrev && pindexPrev->nHeight > 0; i++) {
count++;
if(count > 18000) return;
CBlock block;
if (ReadBlockFromDisk(block, pindexPrev)) {
ProcessBlockCoinbaseTX(block.vtx[0], block.nTime);
}
if (pindexPrev->pprev == NULL) { assert(pindexPrev); break; }
pindexPrev = pindexPrev->pprev;
}
return;
}
void CCoinbasePayee::ProcessBlockCoinbaseTX(CTransaction& txCoinbase, int64_t nTime)
{
if (!txCoinbase.IsCoinBase()){
LogPrintf("ERROR: CCoinbasePayee::ProcessBlockCoinbaseTX - tx is not coinbase\n");
return;
}
BOOST_FOREACH(CTxOut out, txCoinbase.vout){
uint256 h = GetScriptHash(out.scriptPubKey);
LogPrintf("CCoinbasePayee::ProcessBlockCoinbaseTX - %s - %d\n", h.ToString(), nTime);
if(mapPaidTime.count(h)){
if(mapPaidTime[h] < nTime) {
mapPaidTime[h] = nTime;
} else {
LogPrintf("CCoinbasePayee::ProcessBlockCoinbaseTX - not updated -- %s - %d\n", h.ToString(), nTime);
}
} else {
mapPaidTime[h] = nTime;
}
}
}
int64_t CCoinbasePayee::GetLastPaid(CScript& pubkey)
{
uint256 h = GetScriptHash(pubkey);
if(mapPaidTime.count(h)){
return mapPaidTime[h];
}
return 0;
}
void CCoinbasePayee::CleanUp()
{
// std::map<uint256, int64_t>::iterator it = mapPaidTime.begin();
// while(it != mapPaidTime.end())
// {
// //keep 30 days of history
// if((*it).second < GetAdjustedTime() - (60*60*24*30)) {
// mapPaidTime.erase(it++);
// } else {
// ++it;
// }
// }
}
<|endoftext|> |
<commit_before>// Based on:
// Fast Anti-Aliasing Polygon Scan Conversion by Jack Morrison from "Graphics
// Gems", Academic Press, 1990.
// This code renders a polygon, computing subpixel coverage at
// 8 times Y and 16 times X display resolution for anti-aliasing.
#include "df_polygon_aa.h"
#include "df_bitmap.h"
#include "df_common.h"
#include <limits.h>
#include <math.h>
static const int SUBXRES = 16; // subpixel X resolution per pixel
static const int SUBYRES = 8; // subpixel Y resolution per scanline
#define MOD_Y_RES(y) ((y) & 7) // subpixel Y modulo
struct SubpixelRowExtents {
int left, right;
};
// Array to store the start and end X values for each row of subpixels in the
// current scanline.
static SubpixelRowExtents subpixelRowExtents[SUBYRES];
// Min and max X values of subpixels in the current pixel. Can be found by
// searching subpixelRowExtents. Only stored as an optimization.
static int leftMin, rightMax;
// Compute number of subpixels covered by polygon at current pixel.
// x is left subpixel of pixel.
static int ComputePixelCoverage(int x)
{
static const int MAX_AREA = SUBXRES * SUBYRES;
int area = 0;
x *= SUBXRES;
int xr = x + SUBXRES - 1; // Right-most subpixel of pixel.
for (int y = 0; y < SUBYRES; y++) {
// Calc covered area for current subpixel y
int partialArea = IntMin(subpixelRowExtents[y].right, xr) -
IntMax(subpixelRowExtents[y].left, x) + 1;
if (partialArea > 0) {
area += partialArea;
}
}
return 255 * area / MAX_AREA;
}
static void RenderScanline(DfBitmap *bmp, int y, DfColour col)
{
DfColour tmp = col;
int x;
for (x = leftMin / SUBXRES; x <= (rightMax / SUBXRES); x++) {
int coverage = ComputePixelCoverage(x);
if (coverage == 255) {
break;
}
tmp.a = (col.a * coverage) >> 8;
PutPix(bmp, x, y, tmp);
}
int x2;
for (x2 = (rightMax / SUBXRES); x2 > x; x2--) {
int coverage = ComputePixelCoverage(x2);
if (coverage == 255) {
break;
}
tmp.a = (col.a * coverage) >> 8;
PutPix(bmp, x2, y, tmp);
}
if (x2 >= x) {
HLine(bmp, x, y, x2 - x + 1, col);
}
}
static bool IsConvexAndAnticlockwise(DfVertex *verts, int numVerts) {
for (int a = 0; a < numVerts; a++) {
int b = (a + 1) % numVerts;
int c = (a + 2) % numVerts;
int abx = verts[b].x - verts[a].x;
int aby = verts[b].y - verts[a].y;
int bcx = verts[c].x - verts[b].x;
int bcy = verts[c].y - verts[b].y;
int crossProduct = abx * bcy - bcx * aby;
if (crossProduct > 0)
return false;
}
return true;
}
void FillPolygonAa(DfBitmap *bmp, DfVertex *verts, int numVerts, DfColour col)
{
if (!IsConvexAndAnticlockwise(verts, numVerts))
return;
// Convert the verts passed in into the format we use internally,
// find the max vertex y value and the vertex with minimum y.
DfVertex *vertLeft = verts;
int maxY = -1;
for (int i = 0; i < numVerts; i++) {
verts[i].y /= SUBXRES / SUBYRES;
if (verts[i].y < vertLeft->y) {
vertLeft = &verts[i];
}
maxY = IntMax(maxY, verts[i].y);
}
DfVertex *endVert = &verts[numVerts - 1];
// Initialize scanning edges.
DfVertex *nextVertLeft, *vertRight, *nextVertRight;
vertRight = nextVertRight = nextVertLeft = vertLeft;
#define NEXT_LEFT_EDGE() \
vertLeft = nextVertLeft; \
nextVertLeft++; \
if (nextVertLeft > endVert) nextVertLeft = verts; // Wrap.
#define NEXT_RIGHT_EDGE() \
vertRight = nextVertRight; \
nextVertRight--; \
if (nextVertRight < verts) nextVertRight = endVert; // Wrap.
// Skip any initial horizontal edges because they would cause a divide by
// zero in the slope calculation. We know once we've got over the initial
// horizontal edges that there cannot be anymore in a convex poly, other
// than those that would form the bottom of the poly. We'll never
// encounter those either because the main loop will terminate just before
// we get to those (because y will have become equal to maxY).
while (vertLeft->y == nextVertLeft->y) {
NEXT_LEFT_EDGE();
}
while (vertRight->y == nextVertRight->y) {
NEXT_RIGHT_EDGE();
}
// Initialize the extents for each row of subpixels.
for (int i = 0; i < SUBYRES; i++) {
subpixelRowExtents[i].left = -1;
subpixelRowExtents[i].right = -1;
}
leftMin = INT_MAX;
rightMax = -1;
int leftSlope = ((nextVertLeft->x - vertLeft->x) << 16) / (nextVertLeft->y - vertLeft->y);
int rightSlope = ((nextVertRight->x - vertRight->x) << 16) / (nextVertRight->y - vertRight->y);
// Consider each row of subpixels from top to bottom.
for (int y = vertLeft->y; y < maxY; y++) {
// Have we reached the end of the left hand edge we are following?
if (y == nextVertLeft->y) {
NEXT_LEFT_EDGE();
leftSlope = ((nextVertLeft->x - vertLeft->x) << 16) / (nextVertLeft->y - vertLeft->y);
}
// Have we reached the end of the right hand edge we are following?
if (y == nextVertRight->y) {
NEXT_RIGHT_EDGE();
rightSlope = ((nextVertRight->x - vertRight->x) << 16) / (nextVertRight->y - vertRight->y);
}
// Interpolate sub-pixel x endpoints at this y and update extremes.
SubpixelRowExtents *sre = &subpixelRowExtents[MOD_Y_RES(y)];
sre->left = vertLeft->x + (((y - vertLeft->y) * leftSlope) >> 16);
leftMin = IntMin(leftMin, sre->left);
sre->right = vertRight->x + (((y - vertRight->y) * rightSlope) >> 16);
rightMax = IntMax(rightMax, sre->right);
// Is this the last row of subpixels for this scanline?
if (MOD_Y_RES(y) == SUBYRES - 1) {
RenderScanline(bmp, y / SUBYRES, col);
leftMin = INT_MAX;
rightMax = -1;
}
}
// Mark remaining subpixel rows as empty.
for (int yy = MOD_Y_RES(maxY); MOD_Y_RES(yy); yy++) {
subpixelRowExtents[yy].left = subpixelRowExtents[yy].right = -1;
}
RenderScanline(bmp, maxY / SUBYRES, col);
// Convert the verts back into the format the caller uses.
for (int i = 0; i < numVerts; i++) {
verts[i].y *= SUBXRES / SUBYRES;
}
}
<commit_msg>When generating polygons for a fat line, I sometimes was generating degenerate polys where all the vertices had the same y value. This is neither convex nor concave! Turns out the code went wrong with such a poly. A small tweak makes it safely reject them. You could argue that they should be rendered as a horizontal line. However, rejecting them was fine for my current purposes. I might need to reconsider this in the future.<commit_after>// Based on:
// Fast Anti-Aliasing Polygon Scan Conversion by Jack Morrison from "Graphics
// Gems", Academic Press, 1990.
// This code renders a polygon, computing subpixel coverage at
// 8 times Y and 16 times X display resolution for anti-aliasing.
#include "df_polygon_aa.h"
#include "df_bitmap.h"
#include "df_common.h"
#include <limits.h>
#include <math.h>
static const int SUBXRES = 16; // subpixel X resolution per pixel
static const int SUBYRES = 8; // subpixel Y resolution per scanline
#define MOD_Y_RES(y) ((y) & 7) // subpixel Y modulo
struct SubpixelRowExtents {
int left, right;
};
// Array to store the start and end X values for each row of subpixels in the
// current scanline.
static SubpixelRowExtents subpixelRowExtents[SUBYRES];
// Min and max X values of subpixels in the current pixel. Can be found by
// searching subpixelRowExtents. Only stored as an optimization.
static int leftMin, rightMax;
// Compute number of subpixels covered by polygon at current pixel.
// x is left subpixel of pixel.
static int ComputePixelCoverage(int x)
{
static const int MAX_AREA = SUBXRES * SUBYRES;
int area = 0;
x *= SUBXRES;
int xr = x + SUBXRES - 1; // Right-most subpixel of pixel.
for (int y = 0; y < SUBYRES; y++) {
// Calc covered area for current subpixel y
int partialArea = IntMin(subpixelRowExtents[y].right, xr) -
IntMax(subpixelRowExtents[y].left, x) + 1;
if (partialArea > 0) {
area += partialArea;
}
}
return 255 * area / MAX_AREA;
}
static void RenderScanline(DfBitmap *bmp, int y, DfColour col)
{
DfColour tmp = col;
int x;
for (x = leftMin / SUBXRES; x <= (rightMax / SUBXRES); x++) {
int coverage = ComputePixelCoverage(x);
if (coverage == 255) {
break;
}
tmp.a = (col.a * coverage) >> 8;
PutPix(bmp, x, y, tmp);
}
int x2;
for (x2 = (rightMax / SUBXRES); x2 > x; x2--) {
int coverage = ComputePixelCoverage(x2);
if (coverage == 255) {
break;
}
tmp.a = (col.a * coverage) >> 8;
PutPix(bmp, x2, y, tmp);
}
if (x2 >= x) {
HLine(bmp, x, y, x2 - x + 1, col);
}
}
static bool IsConvexAndAnticlockwise(DfVertex *verts, int numVerts) {
for (int a = 0; a < numVerts; a++) {
int b = (a + 1) % numVerts;
int c = (a + 2) % numVerts;
int abx = verts[b].x - verts[a].x;
int aby = verts[b].y - verts[a].y;
int bcx = verts[c].x - verts[b].x;
int bcy = verts[c].y - verts[b].y;
int crossProduct = abx * bcy - bcx * aby;
if (crossProduct > 0)
return false;
}
return true;
}
void FillPolygonAa(DfBitmap *bmp, DfVertex *verts, int numVerts, DfColour col)
{
if (!IsConvexAndAnticlockwise(verts, numVerts))
return;
// Convert the verts passed in into the format we use internally,
// find the max vertex y value and the vertex with minimum y.
DfVertex *vertLeft = verts;
int maxY = -1;
for (int i = 0; i < numVerts; i++) {
verts[i].y /= SUBXRES / SUBYRES;
if (verts[i].y < vertLeft->y) {
vertLeft = &verts[i];
}
maxY = IntMax(maxY, verts[i].y);
}
DfVertex *endVert = &verts[numVerts - 1];
// Initialize scanning edges.
DfVertex *nextVertLeft, *vertRight, *nextVertRight;
vertRight = nextVertRight = nextVertLeft = vertLeft;
#define NEXT_LEFT_EDGE() \
vertLeft = nextVertLeft; \
nextVertLeft++; \
if (nextVertLeft > endVert) nextVertLeft = verts; // Wrap.
#define NEXT_RIGHT_EDGE() \
vertRight = nextVertRight; \
nextVertRight--; \
if (nextVertRight < verts) nextVertRight = endVert; // Wrap.
// Skip any initial horizontal edges because they would cause a divide by
// zero in the slope calculation. We know once we've got over the initial
// horizontal edges that there cannot be anymore in a convex poly, other
// than those that would form the bottom of the poly. We'll never
// encounter those either because the main loop will terminate just before
// we get to those (because y will have become equal to maxY).
for (int i = 0; i < numVerts; i++) {
if (vertLeft->y != nextVertLeft->y)
break;
NEXT_LEFT_EDGE();
}
if (vertLeft->y == nextVertLeft->y)
return; // All verts have the same y value. This is fatal.
while (vertRight->y == nextVertRight->y) {
NEXT_RIGHT_EDGE();
}
// Initialize the extents for each row of subpixels.
for (int i = 0; i < SUBYRES; i++) {
subpixelRowExtents[i].left = -1;
subpixelRowExtents[i].right = -1;
}
leftMin = INT_MAX;
rightMax = -1;
int leftSlope = ((nextVertLeft->x - vertLeft->x) << 16) / (nextVertLeft->y - vertLeft->y);
int rightSlope = ((nextVertRight->x - vertRight->x) << 16) / (nextVertRight->y - vertRight->y);
// Consider each row of subpixels from top to bottom.
for (int y = vertLeft->y; y < maxY; y++) {
// Have we reached the end of the left hand edge we are following?
if (y == nextVertLeft->y) {
NEXT_LEFT_EDGE();
leftSlope = ((nextVertLeft->x - vertLeft->x) << 16) / (nextVertLeft->y - vertLeft->y);
}
// Have we reached the end of the right hand edge we are following?
if (y == nextVertRight->y) {
NEXT_RIGHT_EDGE();
rightSlope = ((nextVertRight->x - vertRight->x) << 16) / (nextVertRight->y - vertRight->y);
}
// Interpolate sub-pixel x endpoints at this y and update extremes.
SubpixelRowExtents *sre = &subpixelRowExtents[MOD_Y_RES(y)];
sre->left = vertLeft->x + (((y - vertLeft->y) * leftSlope) >> 16);
leftMin = IntMin(leftMin, sre->left);
sre->right = vertRight->x + (((y - vertRight->y) * rightSlope) >> 16);
rightMax = IntMax(rightMax, sre->right);
// Is this the last row of subpixels for this scanline?
if (MOD_Y_RES(y) == SUBYRES - 1) {
RenderScanline(bmp, y / SUBYRES, col);
leftMin = INT_MAX;
rightMax = -1;
}
}
// Mark remaining subpixel rows as empty.
for (int yy = MOD_Y_RES(maxY); MOD_Y_RES(yy); yy++) {
subpixelRowExtents[yy].left = subpixelRowExtents[yy].right = -1;
}
RenderScanline(bmp, maxY / SUBYRES, col);
// Convert the verts back into the format the caller uses.
for (int i = 0; i < numVerts; i++) {
verts[i].y *= SUBXRES / SUBYRES;
}
}
<|endoftext|> |
<commit_before>/*
** Copyright 1993 by Miron Livny, and Mike Litzkow
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation, and that the names of the University of
** Wisconsin and the copyright holders not be used in advertising or
** publicity pertaining to distribution of the software without specific,
** written prior permission. The University of Wisconsin and the
** copyright holders make no representations about the suitability of this
** software for any purpose. It is provided "as is" without express
** or implied warranty.
**
** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF
** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT
** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
** OR PERFORMANCE OF THIS SOFTWARE.
**
** Author: Mike Litzkow
**
*/
#if defined(Solaris) && !defined(Solaris251)
#include "condor_fix_timeval.h"
#include </usr/ucbinclude/sys/rusage.h>
#endif
#define _POSIX_SOURCE
#include "condor_common.h"
#include "condor_constants.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "condor_attributes.h"
#include "filter.h"
#include "alloc.h"
static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */
#include "condor_qmgr.h"
char *param();
char *MyName;
int PrioAdjustment;
int NewPriority;
int PrioritySet;
int AdjustmentSet;
int InvokingUid; // user id of person ivoking this program
char *InvokingUserName; // user name of person ivoking this program
const int MIN_PRIO = -20;
const int MAX_PRIO = 20;
// Prototypes of local interest only
void usage();
int compute_adj( char * );
void ProcArg( const char * );
int calc_prio( int old_prio );
void init_user_credentials();
char hostname[512];
// Tell folks how to use this program
void
usage()
{
fprintf( stderr, "Usage: %s [{+|-}priority ] [-p priority] ", MyName );
fprintf( stderr, "[ -a ] [-r host] [user | cluster | cluster.proc] ...\n");
exit( 1 );
}
int
main( int argc, char *argv[] )
{
char *arg;
int prio_adj;
char *args[argc - 1];
int nArgs = 0;
int i;
Qmgr_connection *q;
MyName = argv[0];
config( 0 );
if( argc < 2 ) {
usage();
}
PrioritySet = 0;
AdjustmentSet = 0;
hostname[0] = '\0';
for( argv++; arg = *argv; argv++ ) {
if( (arg[0] == '-' || arg[0] == '+') && isdigit(arg[1]) ) {
PrioAdjustment = compute_adj(arg);
AdjustmentSet = TRUE;
} else if( arg[0] == '-' && arg[1] == 'p' ) {
argv++;
NewPriority = atoi(*argv);
PrioritySet = TRUE;
} else if( arg[0] == '-' && arg[1] == 'r' ) {
// use the given name as the host name to connect to
argv++;
strcpy (hostname, *argv);
} else {
args[nArgs] = arg;
nArgs++;
}
}
if( PrioritySet == FALSE && AdjustmentSet == FALSE ) {
fprintf( stderr,
"You must specify a new priority or priority adjustment.\n");
usage();
exit(1);
}
if( PrioritySet && (NewPriority < MIN_PRIO || NewPriority > MAX_PRIO) ) {
fprintf( stderr,
"Invalid priority specified. Must be between %d and %d.\n",
MIN_PRIO, MAX_PRIO );
exit(1);
}
/* Open job queue */
if (hostname[0] == '\0')
{
// hostname was not set at command line; obtain from system
if(gethostname(hostname, 200) < 0)
{
EXCEPT("gethostname failed, errno = %d", errno);
}
}
if((q = ConnectQ(hostname)) == 0)
{
EXCEPT("Failed to connect to qmgr on host %s", hostname);
}
for(i = 0; i < nArgs; i++)
{
ProcArg(args[i]);
}
DisconnectQ(q);
#if defined(ALLOC_DEBUG)
print_alloc_stats();
#endif
return 0;
}
/*
Given the old priority of a given process, calculate the new
one based on information gotten from the command line arguments.
*/
int
calc_prio( int old_prio )
{
int answer;
if( AdjustmentSet == TRUE && PrioritySet == FALSE ) {
answer = old_prio + PrioAdjustment;
if( answer > MAX_PRIO )
answer = MAX_PRIO;
else if( answer < MIN_PRIO )
answer = MIN_PRIO;
} else {
answer = NewPriority;
}
return answer;
}
/*
Given a command line argument specifing a relative adjustment
of priority of the form "+adj" or "-adj", return the correct
value as a positive or negative integer.
*/
int
compute_adj( char *arg )
{
char *ptr;
int val;
ptr = arg+1;
val = atoi(ptr);
if( *arg == '-' ) {
return( -val );
} else {
return( val );
}
}
extern "C" int SetSyscalls( int foo ) { return foo; }
void UpdateJobAd(int cluster, int proc)
{
int old_prio, new_prio;
if (GetAttributeInt(cluster, proc, ATTR_JOB_PRIO, &old_prio) < 0)
{
fprintf(stderr, "Couldn't retrieve current prio for %d.%d.\n",
cluster, proc);
return;
}
new_prio = calc_prio( old_prio );
SetAttributeInt(cluster, proc, ATTR_JOB_PRIO, new_prio);
}
void ProcArg(const char* arg)
{
int cluster, proc;
char *tmp;
if(isdigit(*arg))
// set prio by cluster/proc #
{
cluster = strtol(arg, &tmp, 10);
if(cluster <= 0)
{
fprintf(stderr, "Invalid cluster # from %s\n", arg);
return;
}
if(*tmp == '\0')
// update prio for all jobs in the cluster
{
ClassAd *ad = new ClassAd;
char constraint[100];
sprintf(constraint, "%s == %d", ATTR_CLUSTER_ID, cluster);
int firstTime = 1;
while(GetNextJobByConstraint(constraint, ad, firstTime) >= 0) {
ad->LookupInteger(ATTR_PROC_ID, proc);
delete ad;
ad = new ClassAd;
UpdateJobAd(cluster, proc);
firstTime = 0;
}
delete ad;
return;
}
if(*tmp == '.')
{
proc = strtol(tmp + 1, &tmp, 10);
if(proc < 0)
{
fprintf(stderr, "Invalid proc # from %s\n", arg);
return;
}
if(*tmp == '\0')
// update prio for proc
{
UpdateJobAd(cluster, proc);
return;
}
fprintf(stderr, "Warning: unrecognized \"%s\" skipped\n", arg);
return;
}
fprintf(stderr, "Warning: unrecognized \"%s\" skipped\n", arg);
}
else if(arg[0] == '-' && arg[1] == 'a')
{
ClassAd *ad = new ClassAd;
int firstTime = 1;
while(GetNextJob(ad, firstTime) >= 0) {
ad->LookupInteger(ATTR_CLUSTER_ID, cluster);
ad->LookupInteger(ATTR_PROC_ID, proc);
delete ad;
ad = new ClassAd;
UpdateJobAd(cluster, proc);
firstTime = 0;
}
delete ad;
}
else if(isalpha(*arg))
// update prio by user name
{
char constraint[100];
ClassAd *ad = new ClassAd;
int firstTime = 1;
sprintf(constraint, "%s == \"%s\"", ATTR_OWNER, arg);
while (GetNextJobByConstraint(constraint, ad, firstTime) >= 0) {
ad->LookupInteger(ATTR_CLUSTER_ID, cluster);
ad->LookupInteger(ATTR_PROC_ID, proc);
delete ad;
ad = new ClassAd;
UpdateJobAd(cluster, proc);
firstTime = 0;
}
delete ad;
}
else
{
fprintf(stderr, "Warning: unrecognized \"%s\" skipped\n", arg);
}
}
<commit_msg>use malloc to allocate args array since array sizes must be constant in VC++<commit_after>/*
** Copyright 1993 by Miron Livny, and Mike Litzkow
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted,
** provided that the above copyright notice appear in all copies and that
** both that copyright notice and this permission notice appear in
** supporting documentation, and that the names of the University of
** Wisconsin and the copyright holders not be used in advertising or
** publicity pertaining to distribution of the software without specific,
** written prior permission. The University of Wisconsin and the
** copyright holders make no representations about the suitability of this
** software for any purpose. It is provided "as is" without express
** or implied warranty.
**
** THE UNIVERSITY OF WISCONSIN AND THE COPYRIGHT HOLDERS DISCLAIM ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF
** WISCONSIN OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT
** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
** OR PERFORMANCE OF THIS SOFTWARE.
**
** Author: Mike Litzkow
**
*/
#if defined(Solaris) && !defined(Solaris251)
#include "condor_fix_timeval.h"
#include </usr/ucbinclude/sys/rusage.h>
#endif
#define _POSIX_SOURCE
#include "condor_common.h"
#include "condor_constants.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "condor_attributes.h"
#include "alloc.h"
static char *_FileName_ = __FILE__; /* Used by EXCEPT (see except.h) */
#include "condor_qmgr.h"
char *param();
char *MyName;
int PrioAdjustment;
int NewPriority;
int PrioritySet;
int AdjustmentSet;
int InvokingUid; // user id of person ivoking this program
char *InvokingUserName; // user name of person ivoking this program
const int MIN_PRIO = -20;
const int MAX_PRIO = 20;
// Prototypes of local interest only
void usage();
int compute_adj( char * );
void ProcArg( const char * );
int calc_prio( int old_prio );
void init_user_credentials();
char hostname[512];
// Tell folks how to use this program
void
usage()
{
fprintf( stderr, "Usage: %s [{+|-}priority ] [-p priority] ", MyName );
fprintf( stderr, "[ -a ] [-r host] [user | cluster | cluster.proc] ...\n");
exit( 1 );
}
int
main( int argc, char *argv[] )
{
char *arg;
char **args = (char **)malloc(sizeof(char *)*(argc - 1));
int nArgs = 0;
int i;
Qmgr_connection *q;
MyName = argv[0];
config( 0 );
if( argc < 2 ) {
usage();
}
PrioritySet = 0;
AdjustmentSet = 0;
hostname[0] = '\0';
for( argv++; arg = *argv; argv++ ) {
if( (arg[0] == '-' || arg[0] == '+') && isdigit(arg[1]) ) {
PrioAdjustment = compute_adj(arg);
AdjustmentSet = TRUE;
} else if( arg[0] == '-' && arg[1] == 'p' ) {
argv++;
NewPriority = atoi(*argv);
PrioritySet = TRUE;
} else if( arg[0] == '-' && arg[1] == 'r' ) {
// use the given name as the host name to connect to
argv++;
strcpy (hostname, *argv);
} else {
args[nArgs] = arg;
nArgs++;
}
}
if( PrioritySet == FALSE && AdjustmentSet == FALSE ) {
fprintf( stderr,
"You must specify a new priority or priority adjustment.\n");
usage();
exit(1);
}
if( PrioritySet && (NewPriority < MIN_PRIO || NewPriority > MAX_PRIO) ) {
fprintf( stderr,
"Invalid priority specified. Must be between %d and %d.\n",
MIN_PRIO, MAX_PRIO );
exit(1);
}
/* Open job queue */
if (hostname[0] == '\0')
{
// hostname was not set at command line; obtain from system
if(gethostname(hostname, 200) < 0)
{
EXCEPT("gethostname failed, errno = %d", errno);
}
}
if((q = ConnectQ(hostname)) == 0)
{
EXCEPT("Failed to connect to qmgr on host %s", hostname);
}
for(i = 0; i < nArgs; i++)
{
ProcArg(args[i]);
}
DisconnectQ(q);
#if defined(ALLOC_DEBUG)
print_alloc_stats();
#endif
return 0;
}
/*
Given the old priority of a given process, calculate the new
one based on information gotten from the command line arguments.
*/
int
calc_prio( int old_prio )
{
int answer;
if( AdjustmentSet == TRUE && PrioritySet == FALSE ) {
answer = old_prio + PrioAdjustment;
if( answer > MAX_PRIO )
answer = MAX_PRIO;
else if( answer < MIN_PRIO )
answer = MIN_PRIO;
} else {
answer = NewPriority;
}
return answer;
}
/*
Given a command line argument specifing a relative adjustment
of priority of the form "+adj" or "-adj", return the correct
value as a positive or negative integer.
*/
int
compute_adj( char *arg )
{
char *ptr;
int val;
ptr = arg+1;
val = atoi(ptr);
if( *arg == '-' ) {
return( -val );
} else {
return( val );
}
}
extern "C" int SetSyscalls( int foo ) { return foo; }
void UpdateJobAd(int cluster, int proc)
{
int old_prio, new_prio;
if (GetAttributeInt(cluster, proc, ATTR_JOB_PRIO, &old_prio) < 0)
{
fprintf(stderr, "Couldn't retrieve current prio for %d.%d.\n",
cluster, proc);
return;
}
new_prio = calc_prio( old_prio );
SetAttributeInt(cluster, proc, ATTR_JOB_PRIO, new_prio);
}
void ProcArg(const char* arg)
{
int cluster, proc;
char *tmp;
if(isdigit(*arg))
// set prio by cluster/proc #
{
cluster = strtol(arg, &tmp, 10);
if(cluster <= 0)
{
fprintf(stderr, "Invalid cluster # from %s\n", arg);
return;
}
if(*tmp == '\0')
// update prio for all jobs in the cluster
{
ClassAd *ad = new ClassAd;
char constraint[100];
sprintf(constraint, "%s == %d", ATTR_CLUSTER_ID, cluster);
int firstTime = 1;
while(GetNextJobByConstraint(constraint, ad, firstTime) >= 0) {
ad->LookupInteger(ATTR_PROC_ID, proc);
delete ad;
ad = new ClassAd;
UpdateJobAd(cluster, proc);
firstTime = 0;
}
delete ad;
return;
}
if(*tmp == '.')
{
proc = strtol(tmp + 1, &tmp, 10);
if(proc < 0)
{
fprintf(stderr, "Invalid proc # from %s\n", arg);
return;
}
if(*tmp == '\0')
// update prio for proc
{
UpdateJobAd(cluster, proc);
return;
}
fprintf(stderr, "Warning: unrecognized \"%s\" skipped\n", arg);
return;
}
fprintf(stderr, "Warning: unrecognized \"%s\" skipped\n", arg);
}
else if(arg[0] == '-' && arg[1] == 'a')
{
ClassAd *ad = new ClassAd;
int firstTime = 1;
while(GetNextJob(ad, firstTime) >= 0) {
ad->LookupInteger(ATTR_CLUSTER_ID, cluster);
ad->LookupInteger(ATTR_PROC_ID, proc);
delete ad;
ad = new ClassAd;
UpdateJobAd(cluster, proc);
firstTime = 0;
}
delete ad;
}
else if(isalpha(*arg))
// update prio by user name
{
char constraint[100];
ClassAd *ad = new ClassAd;
int firstTime = 1;
sprintf(constraint, "%s == \"%s\"", ATTR_OWNER, arg);
while (GetNextJobByConstraint(constraint, ad, firstTime) >= 0) {
ad->LookupInteger(ATTR_CLUSTER_ID, cluster);
ad->LookupInteger(ATTR_PROC_ID, proc);
delete ad;
ad = new ClassAd;
UpdateJobAd(cluster, proc);
firstTime = 0;
}
delete ad;
}
else
{
fprintf(stderr, "Warning: unrecognized \"%s\" skipped\n", arg);
}
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation of Kalman-specific code in beacon-based pose
estimator, to reduce incremental build times.
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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 <iostream>
#include <osvr/Util/EigenCoreGeometry.h>
#if 0
template <typename T>
inline void dumpKalmanDebugOuput(const char name[], const char expr[],
T const &value) {
std::cout << "\n(Kalman Debug Output) " << name << " [" << expr << "]:\n"
<< value << std::endl;
}
#endif
// Internal Includes
#include "BeaconBasedPoseEstimator.h"
#include "VideoJacobian.h"
#include "ImagePointMeasurement.h"
#include "cvToEigen.h"
// Library/third-party includes
#include <osvr/Kalman/FlexibleKalmanFilter.h>
#include <osvr/Kalman/AugmentedProcessModel.h>
#include <osvr/Kalman/AugmentedState.h>
#include <osvr/Kalman/ConstantProcess.h>
#include <osvr/Util/EigenInterop.h>
#include <opencv2/core/eigen.hpp>
// Standard includes
// - none
namespace osvr {
namespace vbtracker {
/// This is the constant maximum distance in image space (pixels) permitted
/// between a projected beacon location and its detected location.
static const auto MAX_RESIDUAL = 75.0;
static const auto MAX_SQUARED_RESIDUAL = MAX_RESIDUAL * MAX_RESIDUAL;
static const auto DEFAULT_MEASUREMENT_VARIANCE = 2.0;
static const auto LOW_BEACON_MEASUREMENT_VARIANCE = 1.0;
static const auto LOW_BEACON_CUTOFF = 5;
static const auto DIM_BEACON_CUTOFF_TO_SKIP_BRIGHTS = 4;
bool
BeaconBasedPoseEstimator::m_kalmanAutocalibEstimator(const LedGroup &leds,
double dt) {
auto const beaconsSize = m_beacons.size();
// Default measurement variance per axis.
auto variance = DEFAULT_MEASUREMENT_VARIANCE;
// Default to using all the measurements we can
auto skipBright = false;
{
auto totalLeds = leds.size();
auto identified = std::size_t{0};
auto inBoundsID = std::size_t{0};
auto inBoundsBright = std::size_t{0};
for (auto const &led : leds) {
if (!led.identified()) {
continue;
}
identified++;
auto id = led.getID();
if (id >= beaconsSize) {
continue;
}
inBoundsID++;
if (led.isBright()) {
inBoundsBright++;
}
}
// Now we decide if we want to cut the variance artificially to
// reduce latency in low-beacon situations
if (inBoundsID < LOW_BEACON_CUTOFF) {
variance = LOW_BEACON_MEASUREMENT_VARIANCE;
}
if (inBoundsID - inBoundsBright >
DIM_BEACON_CUTOFF_TO_SKIP_BRIGHTS) {
skipBright = true;
}
}
CameraModel cam;
cam.focalLength = m_focalLength;
cam.principalPoint = m_principalPoint;
ImagePointMeasurement meas{cam};
meas.setVariance(variance);
kalman::ConstantProcess<kalman::PureVectorState<>> beaconProcess;
Eigen::Vector2d pt;
kalman::predict(m_state, m_model, dt);
auto numBad = std::size_t{0};
auto numGood = std::size_t{0};
for (auto const &led : leds) {
if (!led.identified()) {
continue;
}
auto id = led.getID();
if (id >= beaconsSize) {
continue;
}
if (skipBright && led.isBright()) {
continue;
}
meas.setMeasurement(
Eigen::Vector2d(led.getLocation().x, led.getLocation().y));
auto state = kalman::makeAugmentedState(m_state, *(m_beacons[id]));
meas.updateFromState(state);
auto model =
kalman::makeAugmentedProcessModel(m_model, beaconProcess);
if (meas.getResidual(state).squaredNorm() > MAX_SQUARED_RESIDUAL) {
// probably bad
std::cout << "skipping a measurement with a high residual: id "
<< id << std::endl;
numBad++;
continue;
}
numGood++;
kalman::correct(state, model, meas);
}
bool incrementProbation = false;
if (0 == m_framesInProbation) {
// Let's try to keep a 3:2 ratio of good to bad when not "in
// probation"
incrementProbation = (numBad * 3 > numGood * 2);
} else {
// Already in trouble, add a bit of hysteresis and raising the bar
// so we don't hop out easily.
incrementProbation = numBad * 2 > numGood;
if (!incrementProbation) {
// OK, we're good again
std::cout << "Re-attained our tracking goal." << std::endl;
m_framesInProbation = 0;
}
}
if (incrementProbation) {
std::cout << "Fell below our target for tracking residuals: "
<< numBad << " bad, " << numGood << " good." << std::endl;
m_framesInProbation++;
}
/// Output to the OpenCV state types so we can see the reprojection
/// debug view.
m_rvec = eiQuatToRotVec(m_state.getQuaternion());
cv::eigen2cv(m_state.getPosition().eval(), m_tvec);
return true;
}
OSVR_PoseState
BeaconBasedPoseEstimator::GetPredictedState(double dt) const {
auto state = m_state;
auto model = m_model;
kalman::predict(state, model, dt);
state.postCorrect();
OSVR_PoseState ret;
util::eigen_interop::map(ret).rotation() = state.getQuaternion();
util::eigen_interop::map(ret).translation() =
m_convertInternalPositionRepToExternal(state.getPosition());
return ret;
}
} // namespace vbtracker
} // namespace osvr
<commit_msg>Bump up the max residual again.<commit_after>/** @file
@brief Implementation of Kalman-specific code in beacon-based pose
estimator, to reduce incremental build times.
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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 <iostream>
#include <osvr/Util/EigenCoreGeometry.h>
#if 0
template <typename T>
inline void dumpKalmanDebugOuput(const char name[], const char expr[],
T const &value) {
std::cout << "\n(Kalman Debug Output) " << name << " [" << expr << "]:\n"
<< value << std::endl;
}
#endif
// Internal Includes
#include "BeaconBasedPoseEstimator.h"
#include "VideoJacobian.h"
#include "ImagePointMeasurement.h"
#include "cvToEigen.h"
// Library/third-party includes
#include <osvr/Kalman/FlexibleKalmanFilter.h>
#include <osvr/Kalman/AugmentedProcessModel.h>
#include <osvr/Kalman/AugmentedState.h>
#include <osvr/Kalman/ConstantProcess.h>
#include <osvr/Util/EigenInterop.h>
#include <opencv2/core/eigen.hpp>
// Standard includes
// - none
namespace osvr {
namespace vbtracker {
/// This is the constant maximum distance in image space (pixels) permitted
/// between a projected beacon location and its detected location.
static const auto MAX_RESIDUAL = 100.0;
static const auto MAX_SQUARED_RESIDUAL = MAX_RESIDUAL * MAX_RESIDUAL;
static const auto DEFAULT_MEASUREMENT_VARIANCE = 2.0;
static const auto LOW_BEACON_MEASUREMENT_VARIANCE = 1.0;
static const auto LOW_BEACON_CUTOFF = 5;
static const auto DIM_BEACON_CUTOFF_TO_SKIP_BRIGHTS = 4;
bool
BeaconBasedPoseEstimator::m_kalmanAutocalibEstimator(const LedGroup &leds,
double dt) {
auto const beaconsSize = m_beacons.size();
// Default measurement variance per axis.
auto variance = DEFAULT_MEASUREMENT_VARIANCE;
// Default to using all the measurements we can
auto skipBright = false;
{
auto totalLeds = leds.size();
auto identified = std::size_t{0};
auto inBoundsID = std::size_t{0};
auto inBoundsBright = std::size_t{0};
for (auto const &led : leds) {
if (!led.identified()) {
continue;
}
identified++;
auto id = led.getID();
if (id >= beaconsSize) {
continue;
}
inBoundsID++;
if (led.isBright()) {
inBoundsBright++;
}
}
// Now we decide if we want to cut the variance artificially to
// reduce latency in low-beacon situations
if (inBoundsID < LOW_BEACON_CUTOFF) {
variance = LOW_BEACON_MEASUREMENT_VARIANCE;
}
if (inBoundsID - inBoundsBright >
DIM_BEACON_CUTOFF_TO_SKIP_BRIGHTS) {
skipBright = true;
}
}
CameraModel cam;
cam.focalLength = m_focalLength;
cam.principalPoint = m_principalPoint;
ImagePointMeasurement meas{cam};
meas.setVariance(variance);
kalman::ConstantProcess<kalman::PureVectorState<>> beaconProcess;
Eigen::Vector2d pt;
kalman::predict(m_state, m_model, dt);
auto numBad = std::size_t{0};
auto numGood = std::size_t{0};
for (auto const &led : leds) {
if (!led.identified()) {
continue;
}
auto id = led.getID();
if (id >= beaconsSize) {
continue;
}
if (skipBright && led.isBright()) {
continue;
}
meas.setMeasurement(
Eigen::Vector2d(led.getLocation().x, led.getLocation().y));
auto state = kalman::makeAugmentedState(m_state, *(m_beacons[id]));
meas.updateFromState(state);
auto model =
kalman::makeAugmentedProcessModel(m_model, beaconProcess);
if (meas.getResidual(state).squaredNorm() > MAX_SQUARED_RESIDUAL) {
// probably bad
std::cout << "skipping a measurement with a high residual: id "
<< id << std::endl;
numBad++;
continue;
}
numGood++;
kalman::correct(state, model, meas);
}
bool incrementProbation = false;
if (0 == m_framesInProbation) {
// Let's try to keep a 3:2 ratio of good to bad when not "in
// probation"
incrementProbation = (numBad * 3 > numGood * 2);
} else {
// Already in trouble, add a bit of hysteresis and raising the bar
// so we don't hop out easily.
incrementProbation = numBad * 2 > numGood;
if (!incrementProbation) {
// OK, we're good again
std::cout << "Re-attained our tracking goal." << std::endl;
m_framesInProbation = 0;
}
}
if (incrementProbation) {
std::cout << "Fell below our target for tracking residuals: "
<< numBad << " bad, " << numGood << " good." << std::endl;
m_framesInProbation++;
}
/// Output to the OpenCV state types so we can see the reprojection
/// debug view.
m_rvec = eiQuatToRotVec(m_state.getQuaternion());
cv::eigen2cv(m_state.getPosition().eval(), m_tvec);
return true;
}
OSVR_PoseState
BeaconBasedPoseEstimator::GetPredictedState(double dt) const {
auto state = m_state;
auto model = m_model;
kalman::predict(state, model, dt);
state.postCorrect();
OSVR_PoseState ret;
util::eigen_interop::map(ret).rotation() = state.getQuaternion();
util::eigen_interop::map(ret).translation() =
m_convertInternalPositionRepToExternal(state.getPosition());
return ret;
}
} // namespace vbtracker
} // namespace osvr
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
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 Sony Pictures Imageworks 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 <OpenColorIO/OpenColorIO.h>
#include "FileTransform.h"
#include "OpBuilders.h"
#include "Processor.h"
#include <sstream>
OCIO_NAMESPACE_ENTER
{
Transform::~Transform()
{ }
void BuildOps(OpRcPtrVec & ops,
const Config & config,
const ConstTransformRcPtr & transform,
TransformDirection dir)
{
if(ConstCDLTransformRcPtr cdlTransform = \
DynamicPtrCast<const CDLTransform>(transform))
{
BuildCDLOps(ops, config, *cdlTransform, dir);
}
else if(ConstColorSpaceTransformRcPtr colorSpaceTransform = \
DynamicPtrCast<const ColorSpaceTransform>(transform))
{
BuildColorSpaceOps(ops, config, *colorSpaceTransform, dir);
}
else if(ConstDisplayTransformRcPtr displayTransform = \
DynamicPtrCast<const DisplayTransform>(transform))
{
BuildDisplayOps(ops, config, *displayTransform, dir);
}
else if(ConstFileTransformRcPtr fileTransform = \
DynamicPtrCast<const FileTransform>(transform))
{
BuildFileOps(ops, config, *fileTransform, dir);
}
else if(ConstGroupTransformRcPtr groupTransform = \
DynamicPtrCast<const GroupTransform>(transform))
{
BuildGroupOps(ops, config, *groupTransform, dir);
}
else
{
std::ostringstream os;
os << "Unknown transform type for Op Creation.";
throw Exception(os.str().c_str());
}
}
std::ostream& operator<< (std::ostream & os, const Transform & transform)
{
const Transform* t = &transform;
if(const CDLTransform * cdlTransform = \
dynamic_cast<const CDLTransform*>(t))
{
os << *cdlTransform;
}
else if(const ColorSpaceTransform * colorSpaceTransform = \
dynamic_cast<const ColorSpaceTransform*>(t))
{
os << *colorSpaceTransform;
}
else if(const DisplayTransform * displayTransform = \
dynamic_cast<const DisplayTransform*>(t))
{
os << *displayTransform;
}
else if(const FileTransform * fileTransform = \
dynamic_cast<const FileTransform*>(t))
{
os << *fileTransform;
}
else if(const GroupTransform * groupTransform = \
dynamic_cast<const GroupTransform*>(t))
{
os << *groupTransform;
}
else
{
std::ostringstream error;
os << "Unknown transform type for serialization.";
throw Exception(error.str().c_str());
}
return os;
}
}
OCIO_NAMESPACE_EXIT
<commit_msg>Fixed code registration bug in MatrixTransform<commit_after>/*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
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 Sony Pictures Imageworks 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 <OpenColorIO/OpenColorIO.h>
#include "FileTransform.h"
#include "OpBuilders.h"
#include "Processor.h"
#include <sstream>
OCIO_NAMESPACE_ENTER
{
Transform::~Transform()
{ }
void BuildOps(OpRcPtrVec & ops,
const Config & config,
const ConstTransformRcPtr & transform,
TransformDirection dir)
{
if(ConstCDLTransformRcPtr cdlTransform = \
DynamicPtrCast<const CDLTransform>(transform))
{
BuildCDLOps(ops, config, *cdlTransform, dir);
}
else if(ConstColorSpaceTransformRcPtr colorSpaceTransform = \
DynamicPtrCast<const ColorSpaceTransform>(transform))
{
BuildColorSpaceOps(ops, config, *colorSpaceTransform, dir);
}
else if(ConstDisplayTransformRcPtr displayTransform = \
DynamicPtrCast<const DisplayTransform>(transform))
{
BuildDisplayOps(ops, config, *displayTransform, dir);
}
else if(ConstFileTransformRcPtr fileTransform = \
DynamicPtrCast<const FileTransform>(transform))
{
BuildFileOps(ops, config, *fileTransform, dir);
}
else if(ConstGroupTransformRcPtr groupTransform = \
DynamicPtrCast<const GroupTransform>(transform))
{
BuildGroupOps(ops, config, *groupTransform, dir);
}
else if(ConstMatrixTransformRcPtr matrixTransform = \
DynamicPtrCast<const MatrixTransform>(transform))
{
BuildMatrixOps(ops, config, *matrixTransform, dir);
}
else
{
std::ostringstream os;
os << "Unknown transform type for Op Creation.";
throw Exception(os.str().c_str());
}
}
std::ostream& operator<< (std::ostream & os, const Transform & transform)
{
const Transform* t = &transform;
if(const CDLTransform * cdlTransform = \
dynamic_cast<const CDLTransform*>(t))
{
os << *cdlTransform;
}
else if(const ColorSpaceTransform * colorSpaceTransform = \
dynamic_cast<const ColorSpaceTransform*>(t))
{
os << *colorSpaceTransform;
}
else if(const DisplayTransform * displayTransform = \
dynamic_cast<const DisplayTransform*>(t))
{
os << *displayTransform;
}
else if(const FileTransform * fileTransform = \
dynamic_cast<const FileTransform*>(t))
{
os << *fileTransform;
}
else if(const GroupTransform * groupTransform = \
dynamic_cast<const GroupTransform*>(t))
{
os << *groupTransform;
}
else if(const MatrixTransform * matrixTransform = \
dynamic_cast<const MatrixTransform*>(t))
{
os << *matrixTransform;
}
else
{
std::ostringstream error;
os << "Unknown transform type for serialization.";
throw Exception(error.str().c_str());
}
return os;
}
}
OCIO_NAMESPACE_EXIT
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2014 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "failover-table.h"
#include "atomic.h"
#include "cJSON.h"
FailoverTable::FailoverTable(size_t capacity) : max_entries(capacity) {
}
FailoverTable::FailoverTable() : max_entries(25) {
}
FailoverTable::FailoverTable(const FailoverTable& other) {
max_entries = other.max_entries;
table = other.table;
}
// This should probably be replaced with something better.
uint64_t FailoverTable::generateId() {
return (uint64_t)gethrtime();
}
// Call when taking over as master to update failover table.
// id should be generated to be fairly likely to be unique.
void FailoverTable::createEntry(uint64_t id, uint64_t high_sequence) {
entry_t entry;
entry.first = id;
entry.second = high_sequence;
// Our failover table represents only *our* branch of history.
// We must remove branches we've diverged from.
pruneAbove(high_sequence);
// and *then* add our entry
table.push_front(entry);
// Cap the size of the table
while (table.size() > max_entries) {
table.pop_back();
}
}
// Where should client roll back to?
uint64_t FailoverTable::findRollbackPoint(uint64_t failover_id) {
table_t::iterator it;
for (it = table.begin(); it != table.end(); it++) {
if ((*it).first == failover_id) {
if (it != table.begin()) {
it--;
return (*it).second;
}
// Shouldn't happen, as you should check that the failover id is not
// the most recent
return 0;
}
}
return 0;
}
// Client should be rolled back?
bool FailoverTable::needsRollback(uint64_t since, uint64_t failover_id) {
if (since == 0) {
// Never need to roll back if rolling forward from 0
return false;
}
if (failover_id == table.begin()->first) {
// Client is caught up w.r.t. failovers.
return false;
}
uint64_t rollback_seq = findRollbackPoint(failover_id);
if(since < rollback_seq) {
// Client is behind the branch point, so a rollback would be
// meaningless.
return false;
}
return true;
}
// Prune entries above seq (Should call this any time we roll back!)
void FailoverTable::pruneAbove(uint64_t seq) {
table_t::iterator it;
for (it = table.begin(); it != table.end(); it++) {
if ((*it).second >= seq) {
it = table.erase(it);
}
}
}
std::string FailoverTable::toJSON() {
cJSON* list = cJSON_CreateArray();
table_t::iterator it;
for(it = table.begin(); it != table.end(); it++) {
cJSON* obj = cJSON_CreateObject();
cJSON_AddNumberToObject(obj, "id", (*it).first);
cJSON_AddNumberToObject(obj, "seq", (*it).second);
cJSON_AddItemToArray(list, obj);
}
char* json = cJSON_PrintUnformatted(list);
std::string ret(json);
free(json);
cJSON_Delete(list);
return ret;
}
bool FailoverTable::loadFromJSON(cJSON* parsed) {
table.clear();
bool ok = false;
entry_t e;
if (parsed) {
// Document must be an array
ok = (parsed->type == cJSON_Array);
if (!ok) goto error;
for (cJSON* it = parsed->child; it != NULL; it = it->next) {
// Inner elements must be objects
ok = (it->type == cJSON_Object);
if (!ok) goto error;
// Transform row to entry
ok = JSONtoEntry(it, e);
if (!ok) goto error;
// add to table
table.push_back(e);
}
}
error:
return ok;
}
bool FailoverTable::JSONtoEntry(cJSON* jobj, entry_t& entry) {
cJSON* jid = cJSON_GetObjectItem(jobj, "id");
cJSON* jseq = cJSON_GetObjectItem(jobj, "seq");
if (!(jid && jseq)) return false;
if (jid->type != cJSON_Number) return false;
if (jseq->type != cJSON_Number) return false;
entry.first = (uint64_t) jid->valuedouble;
entry.second = (uint64_t) jseq->valuedouble;
return true;
}
<commit_msg>Don't use goto in the failover log class<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2014 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "failover-table.h"
#include "atomic.h"
#include "cJSON.h"
FailoverTable::FailoverTable(size_t capacity) : max_entries(capacity) {
}
FailoverTable::FailoverTable() : max_entries(25) {
}
FailoverTable::FailoverTable(const FailoverTable& other) {
max_entries = other.max_entries;
table = other.table;
}
// This should probably be replaced with something better.
uint64_t FailoverTable::generateId() {
return (uint64_t)gethrtime();
}
// Call when taking over as master to update failover table.
// id should be generated to be fairly likely to be unique.
void FailoverTable::createEntry(uint64_t id, uint64_t high_sequence) {
entry_t entry;
entry.first = id;
entry.second = high_sequence;
// Our failover table represents only *our* branch of history.
// We must remove branches we've diverged from.
pruneAbove(high_sequence);
// and *then* add our entry
table.push_front(entry);
// Cap the size of the table
while (table.size() > max_entries) {
table.pop_back();
}
}
// Where should client roll back to?
uint64_t FailoverTable::findRollbackPoint(uint64_t failover_id) {
table_t::iterator it;
for (it = table.begin(); it != table.end(); it++) {
if ((*it).first == failover_id) {
if (it != table.begin()) {
it--;
return (*it).second;
}
// Shouldn't happen, as you should check that the failover id is not
// the most recent
return 0;
}
}
return 0;
}
// Client should be rolled back?
bool FailoverTable::needsRollback(uint64_t since, uint64_t failover_id) {
if (since == 0) {
// Never need to roll back if rolling forward from 0
return false;
}
if (failover_id == table.begin()->first) {
// Client is caught up w.r.t. failovers.
return false;
}
uint64_t rollback_seq = findRollbackPoint(failover_id);
if(since < rollback_seq) {
// Client is behind the branch point, so a rollback would be
// meaningless.
return false;
}
return true;
}
// Prune entries above seq (Should call this any time we roll back!)
void FailoverTable::pruneAbove(uint64_t seq) {
table_t::iterator it;
for (it = table.begin(); it != table.end(); it++) {
if ((*it).second >= seq) {
it = table.erase(it);
}
}
}
std::string FailoverTable::toJSON() {
cJSON* list = cJSON_CreateArray();
table_t::iterator it;
for(it = table.begin(); it != table.end(); it++) {
cJSON* obj = cJSON_CreateObject();
cJSON_AddNumberToObject(obj, "id", (*it).first);
cJSON_AddNumberToObject(obj, "seq", (*it).second);
cJSON_AddItemToArray(list, obj);
}
char* json = cJSON_PrintUnformatted(list);
std::string ret(json);
free(json);
cJSON_Delete(list);
return ret;
}
bool FailoverTable::loadFromJSON(cJSON* parsed) {
table.clear();
bool ok = false;
entry_t e;
if (parsed) {
// Document must be an array
ok = (parsed->type == cJSON_Array);
if (!ok) {
return ok;
}
for (cJSON* it = parsed->child; it != NULL; it = it->next) {
// Inner elements must be objects
ok = (it->type == cJSON_Object);
if (!ok) {
return ok;
}
// Transform row to entry
ok = JSONtoEntry(it, e);
if (!ok) {
return ok;
}
// add to table
table.push_back(e);
}
}
return ok;
}
bool FailoverTable::JSONtoEntry(cJSON* jobj, entry_t& entry) {
cJSON* jid = cJSON_GetObjectItem(jobj, "id");
cJSON* jseq = cJSON_GetObjectItem(jobj, "seq");
if (!(jid && jseq)) return false;
if (jid->type != cJSON_Number) return false;
if (jseq->type != cJSON_Number) return false;
entry.first = (uint64_t) jid->valuedouble;
entry.second = (uint64_t) jseq->valuedouble;
return true;
}
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// Local includes
#include "libmesh/side.h"
#include "libmesh/edge_edge2.h"
#include "libmesh/face_quad4.h"
namespace libMesh
{
// ------------------------------------------------------------
// Quad class static member initialization
const unsigned int Quad4::side_nodes_map[4][2] =
{
{0, 1}, // Side 0
{1, 2}, // Side 1
{2, 3}, // Side 2
{3, 0} // Side 3
};
#ifdef LIBMESH_ENABLE_AMR
const float Quad4::_embedding_matrix[4][4][4] =
{
// embedding matrix for child 0
{
// 0 1 2 3
{1.0, 0.0, 0.0, 0.0}, // 0
{0.5, 0.5, 0.0, 0.0}, // 1
{.25, .25, .25, .25}, // 2
{0.5, 0.0, 0.0, 0.5} // 3
},
// embedding matrix for child 1
{
// 0 1 2 3
{0.5, 0.5, 0.0, 0.0}, // 0
{0.0, 1.0, 0.0, 0.0}, // 1
{0.0, 0.5, 0.5, 0.0}, // 2
{.25, .25, .25, .25} // 3
},
// embedding matrix for child 2
{
// 0 1 2 3
{0.5, 0.0, 0.0, 0.5}, // 0
{.25, .25, .25, .25}, // 1
{0.0, 0.0, 0.5, 0.5}, // 2
{0.0, 0.0, 0.0, 1.0} // 3
},
// embedding matrix for child 3
{
// 0 1 2 3
{.25, .25, .25, .25}, // 0
{0.0, 0.5, 0.5, 0.0}, // 1
{0.0, 0.0, 1.0, 0.0}, // 2
{0.0, 0.0, 0.5, 0.5} // 3
}
};
#endif
// ------------------------------------------------------------
// Quad4 class member functions
bool Quad4::is_vertex(const unsigned int) const
{
return true;
}
bool Quad4::is_edge(const unsigned int) const
{
return false;
}
bool Quad4::is_face(const unsigned int) const
{
return false;
}
bool Quad4::is_node_on_side(const unsigned int n,
const unsigned int s) const
{
libmesh_assert_less (s, n_sides());
for (unsigned int i = 0; i != 2; ++i)
if (side_nodes_map[s][i] == n)
return true;
return false;
}
bool Quad4::has_affine_map() const
{
Point v = this->point(3) - this->point(0);
return (v.relative_fuzzy_equals(this->point(2) - this->point(1)));
}
UniquePtr<Elem> Quad4::build_side (const unsigned int i,
bool proxy) const
{
libmesh_assert_less (i, this->n_sides());
if (proxy)
return UniquePtr<Elem>(new Side<Edge2,Quad4>(this,i));
else
{
Elem * edge = new Edge2;
edge->subdomain_id() = this->subdomain_id();
// Set the nodes
for (unsigned n=0; n<edge->n_nodes(); ++n)
edge->set_node(n) = this->get_node(Quad4::side_nodes_map[i][n]);
return UniquePtr<Elem>(edge);
}
libmesh_error_msg("We'll never get here!");
return UniquePtr<Elem>();
}
void Quad4::connectivity(const unsigned int libmesh_dbg_var(sf),
const IOPackage iop,
std::vector<dof_id_type> & conn) const
{
libmesh_assert_less (sf, this->n_sub_elem());
libmesh_assert_not_equal_to (iop, INVALID_IO_PACKAGE);
// Create storage.
conn.resize(4);
switch (iop)
{
case TECPLOT:
{
conn[0] = this->node(0)+1;
conn[1] = this->node(1)+1;
conn[2] = this->node(2)+1;
conn[3] = this->node(3)+1;
return;
}
case VTK:
{
conn[0] = this->node(0);
conn[1] = this->node(1);
conn[2] = this->node(2);
conn[3] = this->node(3);
return;
}
default:
libmesh_error_msg("Unsupported IO package " << iop);
}
}
Real Quad4::volume () const
{
// Make copies of our points. It makes the subsequent calculations a bit
// shorter and avoids dereferencing the same pointer multiple times.
Point
x0 = point(0), x1 = point(1),
x2 = point(2), x3 = point(3);
// Construct constant data vectors.
// \vec{x}_{\xi} = \vec{a1}*eta + \vec{b1}
// \vec{x}_{\eta} = \vec{a2}*xi + \vec{b2}
// This is copy-pasted directly from the output of a Python script.
Point
a1 = x0/4 - x1/4 + x2/4 - x3/4,
b1 = -x0/4 + x1/4 + x2/4 - x3/4,
a2 = a1,
b2 = -x0/4 - x1/4 + x2/4 + x3/4;
// Check for quick return for parallelogram QUAD4.
if (a1.relative_fuzzy_equals(Point(0,0,0)))
return 4. * b1.cross(b2).norm();
// Otherwise, use 2x2 quadrature to approximate the surface area.
// 4-point rule, exact for bi-cubics. The weights for this rule are
// all equal to 1.
const Real q[2] = {-std::sqrt(3.)/3, std::sqrt(3.)/3.};
Real vol=0.;
for (unsigned int i=0; i<2; ++i)
for (unsigned int j=0; j<2; ++j)
vol += (q[j]*a1 + b1).cross(q[i]*a2 + b2).norm();
return vol;
}
} // namespace libMesh
<commit_msg>Add Quad4::volume() implementation based on Taylor-series.<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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
// Local includes
#include "libmesh/side.h"
#include "libmesh/edge_edge2.h"
#include "libmesh/face_quad4.h"
namespace libMesh
{
// ------------------------------------------------------------
// Quad class static member initialization
const unsigned int Quad4::side_nodes_map[4][2] =
{
{0, 1}, // Side 0
{1, 2}, // Side 1
{2, 3}, // Side 2
{3, 0} // Side 3
};
#ifdef LIBMESH_ENABLE_AMR
const float Quad4::_embedding_matrix[4][4][4] =
{
// embedding matrix for child 0
{
// 0 1 2 3
{1.0, 0.0, 0.0, 0.0}, // 0
{0.5, 0.5, 0.0, 0.0}, // 1
{.25, .25, .25, .25}, // 2
{0.5, 0.0, 0.0, 0.5} // 3
},
// embedding matrix for child 1
{
// 0 1 2 3
{0.5, 0.5, 0.0, 0.0}, // 0
{0.0, 1.0, 0.0, 0.0}, // 1
{0.0, 0.5, 0.5, 0.0}, // 2
{.25, .25, .25, .25} // 3
},
// embedding matrix for child 2
{
// 0 1 2 3
{0.5, 0.0, 0.0, 0.5}, // 0
{.25, .25, .25, .25}, // 1
{0.0, 0.0, 0.5, 0.5}, // 2
{0.0, 0.0, 0.0, 1.0} // 3
},
// embedding matrix for child 3
{
// 0 1 2 3
{.25, .25, .25, .25}, // 0
{0.0, 0.5, 0.5, 0.0}, // 1
{0.0, 0.0, 1.0, 0.0}, // 2
{0.0, 0.0, 0.5, 0.5} // 3
}
};
#endif
// ------------------------------------------------------------
// Quad4 class member functions
bool Quad4::is_vertex(const unsigned int) const
{
return true;
}
bool Quad4::is_edge(const unsigned int) const
{
return false;
}
bool Quad4::is_face(const unsigned int) const
{
return false;
}
bool Quad4::is_node_on_side(const unsigned int n,
const unsigned int s) const
{
libmesh_assert_less (s, n_sides());
for (unsigned int i = 0; i != 2; ++i)
if (side_nodes_map[s][i] == n)
return true;
return false;
}
bool Quad4::has_affine_map() const
{
Point v = this->point(3) - this->point(0);
return (v.relative_fuzzy_equals(this->point(2) - this->point(1)));
}
UniquePtr<Elem> Quad4::build_side (const unsigned int i,
bool proxy) const
{
libmesh_assert_less (i, this->n_sides());
if (proxy)
return UniquePtr<Elem>(new Side<Edge2,Quad4>(this,i));
else
{
Elem * edge = new Edge2;
edge->subdomain_id() = this->subdomain_id();
// Set the nodes
for (unsigned n=0; n<edge->n_nodes(); ++n)
edge->set_node(n) = this->get_node(Quad4::side_nodes_map[i][n]);
return UniquePtr<Elem>(edge);
}
libmesh_error_msg("We'll never get here!");
return UniquePtr<Elem>();
}
void Quad4::connectivity(const unsigned int libmesh_dbg_var(sf),
const IOPackage iop,
std::vector<dof_id_type> & conn) const
{
libmesh_assert_less (sf, this->n_sub_elem());
libmesh_assert_not_equal_to (iop, INVALID_IO_PACKAGE);
// Create storage.
conn.resize(4);
switch (iop)
{
case TECPLOT:
{
conn[0] = this->node(0)+1;
conn[1] = this->node(1)+1;
conn[2] = this->node(2)+1;
conn[3] = this->node(3)+1;
return;
}
case VTK:
{
conn[0] = this->node(0);
conn[1] = this->node(1);
conn[2] = this->node(2);
conn[3] = this->node(3);
return;
}
default:
libmesh_error_msg("Unsupported IO package " << iop);
}
}
Real Quad4::volume () const
{
// Make copies of our points. It makes the subsequent calculations a bit
// shorter and avoids dereferencing the same pointer multiple times.
Point
x0 = point(0), x1 = point(1),
x2 = point(2), x3 = point(3);
// This volume formula is derived by replacing the volume integrand,
// which contains a square root, with a Taylor series approximation,
// and integrating it exactly (hence there is no quadrature).
// Construct constant data vectors.
// \vec{x}_{\xi} = \vec{a}*eta + \vec{b}
// \vec{x}_{\eta} = \vec{a}*xi + \vec{c}
Point
a = x0/4 - x1/4 + x2/4 - x3/4,
b = -x0/4 + x1/4 + x2/4 - x3/4,
c = -x0/4 - x1/4 + x2/4 + x3/4;
Point
ba = b.cross(a),
ac = a.cross(c),
bc = b.cross(c);
Real
c00 = bc.norm_sq(),
c10 = 2*(bc*ba),
c01 = 2*(ac*bc),
c20 = ba.norm_sq(),
c02 = ac.norm_sq();
Real sqrt_c00 = std::sqrt(c00);
return 4*sqrt_c00 + 1./(3.*sqrt_c00) * (2.*(c02+c20) - (c10*c10 + c01*c01)/(2.*c00));
}
} // namespace libMesh
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include "shader.h"
#include <istream>
#include <fstream>
#include <string>
#include "glad/glad.h"
#include "../../common/log.h"
#include "driver.h"
#define LOC_BAIL(location) if(location == -1) return
#define USE_THIS_SHADER() driver_->use_shader(*this)
// TODO: Log bad uniform locations.
namespace game { namespace gfx { namespace gl
{
std::string load_stream(std::istream& stream) noexcept
{
std::string ret;
while(!stream.eof() && stream.good())
{
ret.push_back(stream.get());
}
return ret;
}
void compile_shader(GLuint shade, std::string const& data)
{
int len = data.size();
auto data_cstr = data.data();
glShaderSource(shade, 1, &data_cstr, &len);
glCompileShader(shade);
GLint result = 0;
glGetShaderiv(shade, GL_COMPILE_STATUS, &result);
if(result == GL_FALSE)
{
// Compilation failed.
constexpr size_t info_log_length = 2048;
auto info_log = new char[info_log_length];
glGetShaderInfoLog(shade, info_log_length - 1, NULL, info_log);
info_log[info_log_length - 1] = '\0';
log_e("Shader compilation failed (info log):\n%", info_log);
delete[] info_log;
}
}
GL_Shader::GL_Shader(Driver& d) noexcept : driver_(&d)
{
prog_ = glCreateProgram();
}
GL_Shader::~GL_Shader() noexcept
{
if(prog_) glDeleteProgram(prog_);
if(f_shade_) glDeleteShader(f_shade_);
if(v_shade_) glDeleteShader(v_shade_);
}
void GL_Shader::load_vertex_part(std::string const& str) noexcept
{
v_shade_ = glCreateShader(GL_VERTEX_SHADER);
glAttachShader(prog_, v_shade_);
std::ifstream file{str};
compile_shader(v_shade_, load_stream(file));
try_load_();
}
void GL_Shader::load_fragment_part(std::string const& str) noexcept
{
f_shade_ = glCreateShader(GL_FRAGMENT_SHADER);
glAttachShader(prog_, f_shade_);
std::ifstream file{str};
compile_shader(f_shade_, load_stream(file));
try_load_();
}
void GL_Shader::try_load_() noexcept
{
if(!v_shade_ || !f_shade_) return;
glLinkProgram(prog_);
linked_ = true;
}
int GL_Shader::get_location(std::string const& str) noexcept
{
if(!linked_) return -1;
return glGetUniformLocation(prog_, str.data());
}
void GL_Shader::set_matrix(int loc, glm::mat4 const& mat) noexcept
{
LOC_BAIL(loc);
USE_THIS_SHADER();
glUniformMatrix4fv(loc, 1, GL_FALSE, &mat[0][0]);
}
void GL_Shader::set_integer(int loc, int tex_unit) noexcept
{
LOC_BAIL(loc);
USE_THIS_SHADER();
glUniform1i(loc, tex_unit);
}
void GL_Shader::set_vec2(int loc, glm::vec2 const& v) noexcept
{
LOC_BAIL(loc);
USE_THIS_SHADER();
glUniform2fv(loc, 1, &v[0]);
}
void GL_Shader::set_vec3(int loc, glm::vec3 const& v) noexcept
{
LOC_BAIL(loc);
USE_THIS_SHADER();
glUniform3fv(loc, 1, &v[0]);
}
void GL_Shader::set_vec4(int loc, glm::vec4 const& v) noexcept
{
LOC_BAIL(loc);
USE_THIS_SHADER();
glUniform4fv(loc, 1, &v[0]);
}
void GL_Shader::set_float(int loc, float f) noexcept
{
LOC_BAIL(loc);
USE_THIS_SHADER();
glUniform1f(loc, f);
}
void GL_Shader::use() noexcept
{
if(!linked_) return;
glUseProgram(prog_);
}
} } }
#undef LOC_BAIL
<commit_msg>Prevent the eof character from being added to the shader text buffer<commit_after>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include "shader.h"
#include <istream>
#include <fstream>
#include <string>
#include "glad/glad.h"
#include "../../common/log.h"
#include "driver.h"
#define LOC_BAIL(location) if(location == -1) return
#define USE_THIS_SHADER() driver_->use_shader(*this)
// TODO: Log bad uniform locations.
namespace game { namespace gfx { namespace gl
{
std::string load_stream(std::istream& stream) noexcept
{
std::string ret;
while(!stream.eof() && stream.good())
{
auto c = stream.get();
if(std::istream::traits_type::not_eof(c))
{
ret.push_back(c);
}
}
return ret;
}
void compile_shader(GLuint shade, std::string const& data)
{
int len = data.size();
auto data_cstr = data.data();
glShaderSource(shade, 1, &data_cstr, &len);
glCompileShader(shade);
GLint result = 0;
glGetShaderiv(shade, GL_COMPILE_STATUS, &result);
if(result == GL_FALSE)
{
// Compilation failed.
constexpr size_t info_log_length = 2048;
auto info_log = new char[info_log_length];
glGetShaderInfoLog(shade, info_log_length - 1, NULL, info_log);
info_log[info_log_length - 1] = '\0';
log_e("Shader compilation failed (info log):\n%", info_log);
delete[] info_log;
}
}
GL_Shader::GL_Shader(Driver& d) noexcept : driver_(&d)
{
prog_ = glCreateProgram();
}
GL_Shader::~GL_Shader() noexcept
{
if(prog_) glDeleteProgram(prog_);
if(f_shade_) glDeleteShader(f_shade_);
if(v_shade_) glDeleteShader(v_shade_);
}
void GL_Shader::load_vertex_part(std::string const& str) noexcept
{
v_shade_ = glCreateShader(GL_VERTEX_SHADER);
glAttachShader(prog_, v_shade_);
std::ifstream file{str};
compile_shader(v_shade_, load_stream(file));
try_load_();
}
void GL_Shader::load_fragment_part(std::string const& str) noexcept
{
f_shade_ = glCreateShader(GL_FRAGMENT_SHADER);
glAttachShader(prog_, f_shade_);
std::ifstream file{str};
compile_shader(f_shade_, load_stream(file));
try_load_();
}
void GL_Shader::try_load_() noexcept
{
if(!v_shade_ || !f_shade_) return;
glLinkProgram(prog_);
linked_ = true;
}
int GL_Shader::get_location(std::string const& str) noexcept
{
if(!linked_) return -1;
return glGetUniformLocation(prog_, str.data());
}
void GL_Shader::set_matrix(int loc, glm::mat4 const& mat) noexcept
{
LOC_BAIL(loc);
USE_THIS_SHADER();
glUniformMatrix4fv(loc, 1, GL_FALSE, &mat[0][0]);
}
void GL_Shader::set_integer(int loc, int tex_unit) noexcept
{
LOC_BAIL(loc);
USE_THIS_SHADER();
glUniform1i(loc, tex_unit);
}
void GL_Shader::set_vec2(int loc, glm::vec2 const& v) noexcept
{
LOC_BAIL(loc);
USE_THIS_SHADER();
glUniform2fv(loc, 1, &v[0]);
}
void GL_Shader::set_vec3(int loc, glm::vec3 const& v) noexcept
{
LOC_BAIL(loc);
USE_THIS_SHADER();
glUniform3fv(loc, 1, &v[0]);
}
void GL_Shader::set_vec4(int loc, glm::vec4 const& v) noexcept
{
LOC_BAIL(loc);
USE_THIS_SHADER();
glUniform4fv(loc, 1, &v[0]);
}
void GL_Shader::set_float(int loc, float f) noexcept
{
LOC_BAIL(loc);
USE_THIS_SHADER();
glUniform1f(loc, f);
}
void GL_Shader::use() noexcept
{
if(!linked_) return;
glUseProgram(prog_);
}
} } }
#undef LOC_BAIL
<|endoftext|> |
<commit_before>// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: [email protected] (Zhanyong Wan)
// Google Test - The Google C++ Testing Framework
//
// This file implements a universal value printer that can print a
// value of any type T:
//
// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
//
// It uses the << operator when possible, and prints the bytes in the
// object otherwise. A user can override its behavior for a class
// type Foo by defining either operator<<(::std::ostream&, const Foo&)
// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
// defines Foo.
#include "gtest/gtest-printers.h"
#include <ctype.h>
#include <stdio.h>
#include <ostream> // NOLINT
#include <string>
#include "gtest/internal/gtest-port.h"
namespace testing {
namespace {
using ::std::ostream;
#if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s.
# define snprintf _snprintf
#elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf.
# define snprintf _snprintf_s
#elif _MSC_VER
# define snprintf _snprintf
#endif // GTEST_OS_WINDOWS_MOBILE
// Prints a segment of bytes in the given object.
void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
size_t count, ostream* os) {
char text[5] = "";
for (size_t i = 0; i != count; i++) {
const size_t j = start + i;
if (i != 0) {
// Organizes the bytes into groups of 2 for easy parsing by
// human.
if ((j % 2) == 0)
*os << ' ';
else
*os << '-';
}
snprintf(text, sizeof(text), "%02X", obj_bytes[j]);
*os << text;
}
}
// Prints the bytes in the given value to the given ostream.
void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
ostream* os) {
// Tells the user how big the object is.
*os << count << "-byte object <";
const size_t kThreshold = 132;
const size_t kChunkSize = 64;
// If the object size is bigger than kThreshold, we'll have to omit
// some details by printing only the first and the last kChunkSize
// bytes.
// TODO(wan): let the user control the threshold using a flag.
if (count < kThreshold) {
PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
} else {
PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
*os << " ... ";
// Rounds up to 2-byte boundary.
const size_t resume_pos = (count - kChunkSize + 1)/2*2;
PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
}
*os << ">";
}
} // namespace
namespace internal2 {
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
// given object. The delegation simplifies the implementation, which
// uses the << operator and thus is easier done outside of the
// ::testing::internal namespace, which contains a << operator that
// sometimes conflicts with the one in STL.
void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
ostream* os) {
PrintBytesInObjectToImpl(obj_bytes, count, os);
}
} // namespace internal2
namespace internal {
// Depending on the value of a char (or wchar_t), we print it in one
// of three formats:
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
// - as a hexidecimal escape sequence (e.g. '\x7F'), or
// - as a special escape sequence (e.g. '\r', '\n').
enum CharFormat {
kAsIs,
kHexEscape,
kSpecialEscape
};
// Returns true if c is a printable ASCII character. We test the
// value of c directly instead of calling isprint(), which is buggy on
// Windows Mobile.
inline bool IsPrintableAscii(wchar_t c) {
return 0x20 <= c && c <= 0x7E;
}
// Prints a wide or narrow char c as a character literal without the
// quotes, escaping it when necessary; returns how c was formatted.
// The template argument UnsignedChar is the unsigned version of Char,
// which is the type of c.
template <typename UnsignedChar, typename Char>
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
switch (static_cast<wchar_t>(c)) {
case L'\0':
*os << "\\0";
break;
case L'\'':
*os << "\\'";
break;
case L'\\':
*os << "\\\\";
break;
case L'\a':
*os << "\\a";
break;
case L'\b':
*os << "\\b";
break;
case L'\f':
*os << "\\f";
break;
case L'\n':
*os << "\\n";
break;
case L'\r':
*os << "\\r";
break;
case L'\t':
*os << "\\t";
break;
case L'\v':
*os << "\\v";
break;
default:
if (IsPrintableAscii(c)) {
*os << static_cast<char>(c);
return kAsIs;
} else {
*os << String::Format("\\x%X", static_cast<UnsignedChar>(c));
return kHexEscape;
}
}
return kSpecialEscape;
}
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) {
switch (c) {
case L'\'':
*os << "'";
return kAsIs;
case L'"':
*os << "\\\"";
return kSpecialEscape;
default:
return PrintAsCharLiteralTo<wchar_t>(c, os);
}
}
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsNarrowStringLiteralTo(char c, ostream* os) {
return PrintAsWideStringLiteralTo(static_cast<unsigned char>(c), os);
}
// Prints a wide or narrow character c and its code. '\0' is printed
// as "'\\0'", other unprintable characters are also properly escaped
// using the standard C++ escape sequence. The template argument
// UnsignedChar is the unsigned version of Char, which is the type of c.
template <typename UnsignedChar, typename Char>
void PrintCharAndCodeTo(Char c, ostream* os) {
// First, print c as a literal in the most readable form we can find.
*os << ((sizeof(c) > 1) ? "L'" : "'");
const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
*os << "'";
// To aid user debugging, we also print c's code in decimal, unless
// it's 0 (in which case c was printed as '\\0', making the code
// obvious).
if (c == 0)
return;
*os << " (" << String::Format("%d", c).c_str();
// For more convenience, we print c's code again in hexidecimal,
// unless c was already printed in the form '\x##' or the code is in
// [1, 9].
if (format == kHexEscape || (1 <= c && c <= 9)) {
// Do nothing.
} else {
*os << String::Format(", 0x%X",
static_cast<UnsignedChar>(c)).c_str();
}
*os << ")";
}
void PrintTo(unsigned char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
void PrintTo(signed char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
// Prints a wchar_t as a symbol if it is printable or as its internal
// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
void PrintTo(wchar_t wc, ostream* os) {
PrintCharAndCodeTo<wchar_t>(wc, os);
}
// Prints the given array of characters to the ostream.
// The array starts at *begin, the length is len, it may include '\0' characters
// and may not be null-terminated.
static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) {
*os << "\"";
bool is_previous_hex = false;
for (size_t index = 0; index < len; ++index) {
const char cur = begin[index];
if (is_previous_hex && IsXDigit(cur)) {
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
*os << "\" \"";
}
is_previous_hex = PrintAsNarrowStringLiteralTo(cur, os) == kHexEscape;
}
*os << "\"";
}
// Prints a (const) char array of 'len' elements, starting at address 'begin'.
void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
PrintCharsAsStringTo(begin, len, os);
}
// Prints the given array of wide characters to the ostream.
// The array starts at *begin, the length is len, it may include L'\0'
// characters and may not be null-terminated.
static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len,
ostream* os) {
*os << "L\"";
bool is_previous_hex = false;
for (size_t index = 0; index < len; ++index) {
const wchar_t cur = begin[index];
if (is_previous_hex && 0 <= cur && cur < 128 &&
IsXDigit(static_cast<char>(cur))) {
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
*os << "\" L\"";
}
is_previous_hex = PrintAsWideStringLiteralTo(cur, os) == kHexEscape;
}
*os << "\"";
}
// Prints the given C string to the ostream.
void PrintTo(const char* s, ostream* os) {
if (s == NULL) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintCharsAsStringTo(s, strlen(s), os);
}
}
// MSVC compiler can be configured to define whar_t as a typedef
// of unsigned short. Defining an overload for const wchar_t* in that case
// would cause pointers to unsigned shorts be printed as wide strings,
// possibly accessing more memory than intended and causing invalid
// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
// wchar_t is implemented as a native type.
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
// Prints the given wide C string to the ostream.
void PrintTo(const wchar_t* s, ostream* os) {
if (s == NULL) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintWideCharsAsStringTo(s, wcslen(s), os);
}
}
#endif // wchar_t is native
// Prints a ::string object.
#if GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::std::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
// Prints a ::wstring object.
#if GTEST_HAS_GLOBAL_WSTRING
void PrintWideStringTo(const ::wstring& s, ostream* os) {
PrintWideCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_GLOBAL_WSTRING
#if GTEST_HAS_STD_WSTRING
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
PrintWideCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_STD_WSTRING
} // namespace internal
} // namespace testing
<commit_msg>Simplifies ASCII character detection in gtest-printers.h. This also makes it possible to build Google Test on MinGW.<commit_after>// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: [email protected] (Zhanyong Wan)
// Google Test - The Google C++ Testing Framework
//
// This file implements a universal value printer that can print a
// value of any type T:
//
// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
//
// It uses the << operator when possible, and prints the bytes in the
// object otherwise. A user can override its behavior for a class
// type Foo by defining either operator<<(::std::ostream&, const Foo&)
// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
// defines Foo.
#include "gtest/gtest-printers.h"
#include <ctype.h>
#include <stdio.h>
#include <ostream> // NOLINT
#include <string>
#include "gtest/internal/gtest-port.h"
namespace testing {
namespace {
using ::std::ostream;
#if GTEST_OS_WINDOWS_MOBILE // Windows CE does not define _snprintf_s.
# define snprintf _snprintf
#elif _MSC_VER >= 1400 // VC 8.0 and later deprecate snprintf and _snprintf.
# define snprintf _snprintf_s
#elif _MSC_VER
# define snprintf _snprintf
#endif // GTEST_OS_WINDOWS_MOBILE
// Prints a segment of bytes in the given object.
void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
size_t count, ostream* os) {
char text[5] = "";
for (size_t i = 0; i != count; i++) {
const size_t j = start + i;
if (i != 0) {
// Organizes the bytes into groups of 2 for easy parsing by
// human.
if ((j % 2) == 0)
*os << ' ';
else
*os << '-';
}
snprintf(text, sizeof(text), "%02X", obj_bytes[j]);
*os << text;
}
}
// Prints the bytes in the given value to the given ostream.
void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
ostream* os) {
// Tells the user how big the object is.
*os << count << "-byte object <";
const size_t kThreshold = 132;
const size_t kChunkSize = 64;
// If the object size is bigger than kThreshold, we'll have to omit
// some details by printing only the first and the last kChunkSize
// bytes.
// TODO(wan): let the user control the threshold using a flag.
if (count < kThreshold) {
PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
} else {
PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
*os << " ... ";
// Rounds up to 2-byte boundary.
const size_t resume_pos = (count - kChunkSize + 1)/2*2;
PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
}
*os << ">";
}
} // namespace
namespace internal2 {
// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
// given object. The delegation simplifies the implementation, which
// uses the << operator and thus is easier done outside of the
// ::testing::internal namespace, which contains a << operator that
// sometimes conflicts with the one in STL.
void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
ostream* os) {
PrintBytesInObjectToImpl(obj_bytes, count, os);
}
} // namespace internal2
namespace internal {
// Depending on the value of a char (or wchar_t), we print it in one
// of three formats:
// - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
// - as a hexidecimal escape sequence (e.g. '\x7F'), or
// - as a special escape sequence (e.g. '\r', '\n').
enum CharFormat {
kAsIs,
kHexEscape,
kSpecialEscape
};
// Returns true if c is a printable ASCII character. We test the
// value of c directly instead of calling isprint(), which is buggy on
// Windows Mobile.
inline bool IsPrintableAscii(wchar_t c) {
return 0x20 <= c && c <= 0x7E;
}
// Prints a wide or narrow char c as a character literal without the
// quotes, escaping it when necessary; returns how c was formatted.
// The template argument UnsignedChar is the unsigned version of Char,
// which is the type of c.
template <typename UnsignedChar, typename Char>
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
switch (static_cast<wchar_t>(c)) {
case L'\0':
*os << "\\0";
break;
case L'\'':
*os << "\\'";
break;
case L'\\':
*os << "\\\\";
break;
case L'\a':
*os << "\\a";
break;
case L'\b':
*os << "\\b";
break;
case L'\f':
*os << "\\f";
break;
case L'\n':
*os << "\\n";
break;
case L'\r':
*os << "\\r";
break;
case L'\t':
*os << "\\t";
break;
case L'\v':
*os << "\\v";
break;
default:
if (IsPrintableAscii(c)) {
*os << static_cast<char>(c);
return kAsIs;
} else {
*os << String::Format("\\x%X", static_cast<UnsignedChar>(c));
return kHexEscape;
}
}
return kSpecialEscape;
}
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsWideStringLiteralTo(wchar_t c, ostream* os) {
switch (c) {
case L'\'':
*os << "'";
return kAsIs;
case L'"':
*os << "\\\"";
return kSpecialEscape;
default:
return PrintAsCharLiteralTo<wchar_t>(c, os);
}
}
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsNarrowStringLiteralTo(char c, ostream* os) {
return PrintAsWideStringLiteralTo(static_cast<unsigned char>(c), os);
}
// Prints a wide or narrow character c and its code. '\0' is printed
// as "'\\0'", other unprintable characters are also properly escaped
// using the standard C++ escape sequence. The template argument
// UnsignedChar is the unsigned version of Char, which is the type of c.
template <typename UnsignedChar, typename Char>
void PrintCharAndCodeTo(Char c, ostream* os) {
// First, print c as a literal in the most readable form we can find.
*os << ((sizeof(c) > 1) ? "L'" : "'");
const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
*os << "'";
// To aid user debugging, we also print c's code in decimal, unless
// it's 0 (in which case c was printed as '\\0', making the code
// obvious).
if (c == 0)
return;
*os << " (" << String::Format("%d", c).c_str();
// For more convenience, we print c's code again in hexidecimal,
// unless c was already printed in the form '\x##' or the code is in
// [1, 9].
if (format == kHexEscape || (1 <= c && c <= 9)) {
// Do nothing.
} else {
*os << String::Format(", 0x%X",
static_cast<UnsignedChar>(c)).c_str();
}
*os << ")";
}
void PrintTo(unsigned char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
void PrintTo(signed char c, ::std::ostream* os) {
PrintCharAndCodeTo<unsigned char>(c, os);
}
// Prints a wchar_t as a symbol if it is printable or as its internal
// code otherwise and also as its code. L'\0' is printed as "L'\\0'".
void PrintTo(wchar_t wc, ostream* os) {
PrintCharAndCodeTo<wchar_t>(wc, os);
}
// Prints the given array of characters to the ostream.
// The array starts at *begin, the length is len, it may include '\0' characters
// and may not be null-terminated.
static void PrintCharsAsStringTo(const char* begin, size_t len, ostream* os) {
*os << "\"";
bool is_previous_hex = false;
for (size_t index = 0; index < len; ++index) {
const char cur = begin[index];
if (is_previous_hex && IsXDigit(cur)) {
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
*os << "\" \"";
}
is_previous_hex = PrintAsNarrowStringLiteralTo(cur, os) == kHexEscape;
}
*os << "\"";
}
// Prints a (const) char array of 'len' elements, starting at address 'begin'.
void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
PrintCharsAsStringTo(begin, len, os);
}
// Prints the given array of wide characters to the ostream.
// The array starts at *begin, the length is len, it may include L'\0'
// characters and may not be null-terminated.
static void PrintWideCharsAsStringTo(const wchar_t* begin, size_t len,
ostream* os) {
*os << "L\"";
bool is_previous_hex = false;
for (size_t index = 0; index < len; ++index) {
const wchar_t cur = begin[index];
if (is_previous_hex && isascii(cur) && IsXDigit(static_cast<char>(cur))) {
// Previous character is of '\x..' form and this character can be
// interpreted as another hexadecimal digit in its number. Break string to
// disambiguate.
*os << "\" L\"";
}
is_previous_hex = PrintAsWideStringLiteralTo(cur, os) == kHexEscape;
}
*os << "\"";
}
// Prints the given C string to the ostream.
void PrintTo(const char* s, ostream* os) {
if (s == NULL) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintCharsAsStringTo(s, strlen(s), os);
}
}
// MSVC compiler can be configured to define whar_t as a typedef
// of unsigned short. Defining an overload for const wchar_t* in that case
// would cause pointers to unsigned shorts be printed as wide strings,
// possibly accessing more memory than intended and causing invalid
// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
// wchar_t is implemented as a native type.
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
// Prints the given wide C string to the ostream.
void PrintTo(const wchar_t* s, ostream* os) {
if (s == NULL) {
*os << "NULL";
} else {
*os << ImplicitCast_<const void*>(s) << " pointing to ";
PrintWideCharsAsStringTo(s, wcslen(s), os);
}
}
#endif // wchar_t is native
// Prints a ::string object.
#if GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_GLOBAL_STRING
void PrintStringTo(const ::std::string& s, ostream* os) {
PrintCharsAsStringTo(s.data(), s.size(), os);
}
// Prints a ::wstring object.
#if GTEST_HAS_GLOBAL_WSTRING
void PrintWideStringTo(const ::wstring& s, ostream* os) {
PrintWideCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_GLOBAL_WSTRING
#if GTEST_HAS_STD_WSTRING
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
PrintWideCharsAsStringTo(s.data(), s.size(), os);
}
#endif // GTEST_HAS_STD_WSTRING
} // namespace internal
} // namespace testing
<|endoftext|> |
<commit_before>#include "util.h"
#include "h5spikewriter.h"
H5SpikeWriter::H5SpikeWriter()
{
m_nc = 0;
m_nu = 0;
m_nwf = 0;
m_h5groups.clear();
m_h5Dtk.clear();
m_h5Dts.clear();
m_h5Dwf.clear();
m_ns.clear();
m_q = new ReaderWriterQueue<SPIKE *>(H5S_BUF_SIZE);
}
H5SpikeWriter::~H5SpikeWriter()
{
delete m_q;
m_q = NULL;
}
bool H5SpikeWriter::open(const char *fn, size_t nc, size_t nu, size_t nwf);
{
if (isEnabled())
return false;
if (!H5Writer::open(fn)) {
return false;
}
// Create a group
m_h5topgroup = H5Gcreate2(m_h5file, "/Spikes",
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
if (m_h5topgroup < 0) {
close();
return false;
}
// create a group for each channel and for each unit in each channel
for (size_t i=1; i<=nc; i++) { // 1-indexed
char buf[32];
sprintf(buf, "/Spikes/%03i", i);
m_h5topgroup = H5Gcreate2(m_h5file, buf,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
for (size_t j=0; j<=nu; j++) { // 1-indexed, zero is unsorted
sprintf(buf, "/Spikes/%03i/%03i", i, j);
m_h5topgroup = H5Gcreate2(m_h5file, buf,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
}
}
/*
// create analog dataspace
// do not allow numchans to grow
// but allow the number of samples to be unlimited
hsize_t init_dims[2] = {nc, 0};
hsize_t max_dims[2] = {nc, H5S_UNLIMITED};
hid_t ds = H5Screate_simple(2, init_dims, max_dims);
if (ds < 0) {
close();
return false;
}
// Create a dataset creation property list and set it to use chunking
// Online advice is to, "keep chunks above 10KiB or so"
// Realistically it should probably be something that can fit into L1 cache
// so: definitely under 64 KB
// 32*32*2 bytes ~= 2 KB
// 32*128*2 bytes ~= 8 KB
// also, perhaps compression will work better with slightly larger blocks
hid_t prop = H5Pcreate(H5P_DATASET_CREATE);
if (m_shuffle)
shuffleDataset(prop);
if (m_deflate)
deflateDataset(prop);
hsize_t chunk_dims[2] = {nc < 32 ? nc : 32, 128};
H5Pset_chunk(prop, 2, chunk_dims);
// Create the analog dataset
m_h5Dsamples = H5Dcreate(m_h5file, "/Analog/Samples", H5T_STD_I16LE,
ds, H5P_DEFAULT, prop, H5P_DEFAULT);
if (m_h5Dsamples < 0) {
close();
return false;
}
m_h5dataspaces.push_back(ds);
m_h5props.push_back(prop);
// create tick dataspace
// allow the number of samples to be unlimited
init_dims[0] = 0;
max_dims[0] = H5S_UNLIMITED;
ds = H5Screate_simple(1, init_dims, max_dims);
if (ds < 0) {
close();
return false;
}
//Create a dataset creation property list and set it to use chunking
prop = H5Pcreate(H5P_DATASET_CREATE);
if (m_shuffle)
shuffleDataset(prop);
if (m_deflate)
deflateDataset(prop);
chunk_dims[0] = 128;
H5Pset_chunk(prop, 1, chunk_dims);
// Create the tick dataset
m_h5Dtk = H5Dcreate(m_h5file, "/Analog/Ticks", H5T_STD_I64LE,
ds, H5P_DEFAULT, prop, H5P_DEFAULT);
if (m_h5Dtk < 0) {
close();
return false;
}
m_h5dataspaces.push_back(ds);
m_h5props.push_back(prop);
// create timestamp dataspace
// allow the number of samples to be unlimited
init_dims[0] = 0;
max_dims[0] = H5S_UNLIMITED;
ds = H5Screate_simple(1, init_dims, max_dims);
if (ds < 0) {
close();
return false;
}
//Create a dataset creation property list and set it to use chunking
prop = H5Pcreate(H5P_DATASET_CREATE);
if (m_shuffle)
shuffleDataset(prop);
if (m_deflate)
deflateDataset(prop);
chunk_dims[0] = 128;
H5Pset_chunk(prop, 1, chunk_dims);
// Create the tick dataset
m_h5Dts = H5Dcreate(m_h5file, "/Analog/Timestamps", H5T_IEEE_F64LE,
ds, H5P_DEFAULT, prop, H5P_DEFAULT);
if (m_h5Dts < 0) {
close();
return false;
}
m_h5dataspaces.push_back(ds);
m_h5props.push_back(prop);
m_nc = nc;
enable();
*/
return true;
}
/*
bool H5SpikeWriter::close()
{
disable();
m_ns = 0;
m_nc = 0;
if (m_h5Dts > 0) {
H5Dclose(m_h5Dts);
m_h5Dts = 0;
}
if (m_h5Dtk > 0) {
H5Dclose(m_h5Dtk);
m_h5Dtk = 0;
}
if (m_h5Dsamples > 0) {
H5Dclose(m_h5Dsamples);
m_h5Dsamples = 0;
}
return H5Writer::close();
}
bool H5SpikeWriter::add(AD *o) // call from a single producer thread
{
if (!isEnabled()) {
delete[] (o->data);
delete[] (o->tk);
delete[] (o->ts);
delete o;
return false;
}
return m_q->enqueue(o); // todo: what if this (memory alloc) fails
}
bool H5SpikeWriter::write() // call from a single consumer thread
{
if (!isEnabled())
return false;
//Lock so that the file isnt closed out from under us
lock_guard<mutex> lock(m_mtx); // very important!!!
bool dequeued;
do {
AD *o;
dequeued = m_q->try_dequeue(o);
if (dequeued) {
if (o->nc != m_nc) {
warn("well this is embarassing");
}
// extend sample dataset to fit new data
// TODO: CHECK FOR ERROR
hsize_t new_dims[2] = {m_nc, m_ns + o->ns};
H5Dset_extent(m_h5Dsamples, new_dims);
// select hyperslab in extended oprtion of dataset
hid_t filespace = H5Dget_space(m_h5Dsamples);
hsize_t offset[2] = {0, m_ns};
hsize_t packet_dims[2] = {m_nc, o->ns};
H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL,
packet_dims, NULL);
// Define memory space for new data
// TODO CHECK FOR ERROR
hid_t memspace = H5Screate_simple(2, packet_dims, NULL);
// Write the dataset.
// TODO: CHECK FOR ERROR
H5Dwrite(m_h5Dsamples, H5T_NATIVE_INT16, memspace, filespace,
H5P_DEFAULT, o->data);
H5Sclose(memspace);
H5Sclose(filespace);
// extend tick dataset to fit new data
// TODO: CHECK FOR ERROR
new_dims[0] = m_ns + o->ns;
H5Dset_extent(m_h5Dtk, new_dims);
// select hyperslab in extended oprtion of dataset
filespace = H5Dget_space(m_h5Dtk);
offset[0] = m_ns;
packet_dims[0] = o->ns;
H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL,
packet_dims, NULL);
// Define memory space for new data
// TODO CHECK FOR ERROR
memspace = H5Screate_simple(1, packet_dims, NULL);
// Write the dataset.
// TODO: CHECK FOR ERROR
H5Dwrite(m_h5Dtk, H5T_NATIVE_INT64, memspace, filespace,
H5P_DEFAULT, o->tk);
H5Sclose(memspace);
H5Sclose(filespace);
// extend ts dataset to fit new data
// TODO: CHECK FOR ERROR
new_dims[0] = m_ns + o->ns;
H5Dset_extent(m_h5Dts, new_dims);
// select hyperslab in extended oprtion of dataset
filespace = H5Dget_space(m_h5Dts);
offset[0] = m_ns;
packet_dims[0] = o->ns;
H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL,
packet_dims, NULL);
// Define memory space for new data
// TODO CHECK FOR ERROR
memspace = H5Screate_simple(1, packet_dims, NULL);
// Write the dataset.
// TODO: CHECK FOR ERROR
H5Dwrite(m_h5Dts, H5T_NATIVE_DOUBLE, memspace, filespace,
H5P_DEFAULT, o->ts);
H5Sclose(memspace);
H5Sclose(filespace);
m_ns += o->ns; // increment sample pointer
//if (m_os.fail()) { // write lost, should we requeue?
// fprintf(stderr,"ERROR: %s write failed!\n", name());
//}
delete[] (o->data);
delete[] (o->tk);
delete[] (o->ts);
delete o; // free the memory that was pointed to
}
} while (dequeued);
return true;
}
size_t H5SpikeWriter::capacity()
{
return m_q ? m_q->size_approx() : 0;
}
size_t H5SpikeWriter::bytes()
{
return m_ns * m_nc * sizeof(i16);
}
bool H5SpikeWriter::setMetaData(double sr, float *scale, char *name, int slen)
{
hid_t ds, attr, atype;
ds = H5Screate(H5S_SCALAR);
attr = H5Acreate(m_h5group, "Sampling Rate", H5T_IEEE_F64LE, ds,
H5P_DEFAULT, H5P_DEFAULT);
H5Awrite(attr, H5T_NATIVE_DOUBLE, &sr); // TODO: CHECK ERROR
H5Aclose(attr); // TODO: check error
H5Sclose(ds);
hsize_t dims = m_nc;
ds = H5Screate_simple(1, &dims, NULL);
attr = H5Acreate(m_h5group, "Scale Factor", H5T_IEEE_F32LE, ds,
H5P_DEFAULT, H5P_DEFAULT);
H5Awrite(attr, H5T_NATIVE_FLOAT, scale); // TODO: CHECK ERROR
H5Aclose(attr); // TODO: check error
H5Sclose(ds);
ds = H5Screate_simple(1, &dims, NULL);
atype = H5Tcopy(H5T_C_S1);
H5Tset_size(atype, slen);
H5Tset_strpad(atype, H5T_STR_NULLTERM);
attr = H5Acreate(m_h5group, "Channel Name", atype, ds,
H5P_DEFAULT, H5P_DEFAULT);
H5Awrite(attr, atype, name); // TODO: CHECK ERROR
H5Aclose(attr);
H5Sclose(ds);
return true;
}
*/
<commit_msg>now put each spikechan group into a vector<commit_after>#include "util.h"
#include "h5spikewriter.h"
H5SpikeWriter::H5SpikeWriter()
{
m_nc = 0;
m_nu = 0;
m_nwf = 0;
m_h5groups.clear();
m_h5Dtk.clear();
m_h5Dts.clear();
m_h5Dwf.clear();
m_ns.clear();
m_q = new ReaderWriterQueue<SPIKE *>(H5S_BUF_SIZE);
}
H5SpikeWriter::~H5SpikeWriter()
{
delete m_q;
m_q = NULL;
}
bool H5SpikeWriter::open(const char *fn, size_t nc, size_t nu, size_t nwf);
{
if (isEnabled())
return false;
if (!H5Writer::open(fn)) {
return false;
}
// Create a group
m_h5topgroup = H5Gcreate2(m_h5file, "/Spikes",
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
if (m_h5topgroup < 0) {
close();
return false;
}
// create a group for each channel and for each unit in each channel
hid_t group;
for (size_t i=1; i<=nc; i++) { // 1-indexed
char buf[32];
sprintf(buf, "/Spikes/%03i", i);
group = H5Gcreate2(m_h5file, buf,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
if (group < 0) {
close();
return false;
}
m_h5groups.push_back(group);
for (size_t j=0; j<=nu; j++) { // 1-indexed, zero is unsorted
sprintf(buf, "/Spikes/%03i/%03i", i, j);
group = H5Gcreate2(m_h5file, buf,
H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
if (group < 0) {
close();
return false;
}
m_h5groups.push_back(group);
}
}
/*
// create analog dataspace
// do not allow numchans to grow
// but allow the number of samples to be unlimited
hsize_t init_dims[2] = {nc, 0};
hsize_t max_dims[2] = {nc, H5S_UNLIMITED};
hid_t ds = H5Screate_simple(2, init_dims, max_dims);
if (ds < 0) {
close();
return false;
}
// Create a dataset creation property list and set it to use chunking
// Online advice is to, "keep chunks above 10KiB or so"
// Realistically it should probably be something that can fit into L1 cache
// so: definitely under 64 KB
// 32*32*2 bytes ~= 2 KB
// 32*128*2 bytes ~= 8 KB
// also, perhaps compression will work better with slightly larger blocks
hid_t prop = H5Pcreate(H5P_DATASET_CREATE);
if (m_shuffle)
shuffleDataset(prop);
if (m_deflate)
deflateDataset(prop);
hsize_t chunk_dims[2] = {nc < 32 ? nc : 32, 128};
H5Pset_chunk(prop, 2, chunk_dims);
// Create the analog dataset
m_h5Dsamples = H5Dcreate(m_h5file, "/Analog/Samples", H5T_STD_I16LE,
ds, H5P_DEFAULT, prop, H5P_DEFAULT);
if (m_h5Dsamples < 0) {
close();
return false;
}
m_h5dataspaces.push_back(ds);
m_h5props.push_back(prop);
// create tick dataspace
// allow the number of samples to be unlimited
init_dims[0] = 0;
max_dims[0] = H5S_UNLIMITED;
ds = H5Screate_simple(1, init_dims, max_dims);
if (ds < 0) {
close();
return false;
}
//Create a dataset creation property list and set it to use chunking
prop = H5Pcreate(H5P_DATASET_CREATE);
if (m_shuffle)
shuffleDataset(prop);
if (m_deflate)
deflateDataset(prop);
chunk_dims[0] = 128;
H5Pset_chunk(prop, 1, chunk_dims);
// Create the tick dataset
m_h5Dtk = H5Dcreate(m_h5file, "/Analog/Ticks", H5T_STD_I64LE,
ds, H5P_DEFAULT, prop, H5P_DEFAULT);
if (m_h5Dtk < 0) {
close();
return false;
}
m_h5dataspaces.push_back(ds);
m_h5props.push_back(prop);
// create timestamp dataspace
// allow the number of samples to be unlimited
init_dims[0] = 0;
max_dims[0] = H5S_UNLIMITED;
ds = H5Screate_simple(1, init_dims, max_dims);
if (ds < 0) {
close();
return false;
}
//Create a dataset creation property list and set it to use chunking
prop = H5Pcreate(H5P_DATASET_CREATE);
if (m_shuffle)
shuffleDataset(prop);
if (m_deflate)
deflateDataset(prop);
chunk_dims[0] = 128;
H5Pset_chunk(prop, 1, chunk_dims);
// Create the tick dataset
m_h5Dts = H5Dcreate(m_h5file, "/Analog/Timestamps", H5T_IEEE_F64LE,
ds, H5P_DEFAULT, prop, H5P_DEFAULT);
if (m_h5Dts < 0) {
close();
return false;
}
m_h5dataspaces.push_back(ds);
m_h5props.push_back(prop);
m_nc = nc;
enable();
*/
return true;
}
/*
bool H5SpikeWriter::close()
{
disable();
m_ns = 0;
m_nc = 0;
if (m_h5Dts > 0) {
H5Dclose(m_h5Dts);
m_h5Dts = 0;
}
if (m_h5Dtk > 0) {
H5Dclose(m_h5Dtk);
m_h5Dtk = 0;
}
if (m_h5Dsamples > 0) {
H5Dclose(m_h5Dsamples);
m_h5Dsamples = 0;
}
return H5Writer::close();
}
bool H5SpikeWriter::add(AD *o) // call from a single producer thread
{
if (!isEnabled()) {
delete[] (o->data);
delete[] (o->tk);
delete[] (o->ts);
delete o;
return false;
}
return m_q->enqueue(o); // todo: what if this (memory alloc) fails
}
bool H5SpikeWriter::write() // call from a single consumer thread
{
if (!isEnabled())
return false;
//Lock so that the file isnt closed out from under us
lock_guard<mutex> lock(m_mtx); // very important!!!
bool dequeued;
do {
AD *o;
dequeued = m_q->try_dequeue(o);
if (dequeued) {
if (o->nc != m_nc) {
warn("well this is embarassing");
}
// extend sample dataset to fit new data
// TODO: CHECK FOR ERROR
hsize_t new_dims[2] = {m_nc, m_ns + o->ns};
H5Dset_extent(m_h5Dsamples, new_dims);
// select hyperslab in extended oprtion of dataset
hid_t filespace = H5Dget_space(m_h5Dsamples);
hsize_t offset[2] = {0, m_ns};
hsize_t packet_dims[2] = {m_nc, o->ns};
H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL,
packet_dims, NULL);
// Define memory space for new data
// TODO CHECK FOR ERROR
hid_t memspace = H5Screate_simple(2, packet_dims, NULL);
// Write the dataset.
// TODO: CHECK FOR ERROR
H5Dwrite(m_h5Dsamples, H5T_NATIVE_INT16, memspace, filespace,
H5P_DEFAULT, o->data);
H5Sclose(memspace);
H5Sclose(filespace);
// extend tick dataset to fit new data
// TODO: CHECK FOR ERROR
new_dims[0] = m_ns + o->ns;
H5Dset_extent(m_h5Dtk, new_dims);
// select hyperslab in extended oprtion of dataset
filespace = H5Dget_space(m_h5Dtk);
offset[0] = m_ns;
packet_dims[0] = o->ns;
H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL,
packet_dims, NULL);
// Define memory space for new data
// TODO CHECK FOR ERROR
memspace = H5Screate_simple(1, packet_dims, NULL);
// Write the dataset.
// TODO: CHECK FOR ERROR
H5Dwrite(m_h5Dtk, H5T_NATIVE_INT64, memspace, filespace,
H5P_DEFAULT, o->tk);
H5Sclose(memspace);
H5Sclose(filespace);
// extend ts dataset to fit new data
// TODO: CHECK FOR ERROR
new_dims[0] = m_ns + o->ns;
H5Dset_extent(m_h5Dts, new_dims);
// select hyperslab in extended oprtion of dataset
filespace = H5Dget_space(m_h5Dts);
offset[0] = m_ns;
packet_dims[0] = o->ns;
H5Sselect_hyperslab(filespace, H5S_SELECT_SET, offset, NULL,
packet_dims, NULL);
// Define memory space for new data
// TODO CHECK FOR ERROR
memspace = H5Screate_simple(1, packet_dims, NULL);
// Write the dataset.
// TODO: CHECK FOR ERROR
H5Dwrite(m_h5Dts, H5T_NATIVE_DOUBLE, memspace, filespace,
H5P_DEFAULT, o->ts);
H5Sclose(memspace);
H5Sclose(filespace);
m_ns += o->ns; // increment sample pointer
//if (m_os.fail()) { // write lost, should we requeue?
// fprintf(stderr,"ERROR: %s write failed!\n", name());
//}
delete[] (o->data);
delete[] (o->tk);
delete[] (o->ts);
delete o; // free the memory that was pointed to
}
} while (dequeued);
return true;
}
size_t H5SpikeWriter::capacity()
{
return m_q ? m_q->size_approx() : 0;
}
size_t H5SpikeWriter::bytes()
{
return m_ns * m_nc * sizeof(i16);
}
bool H5SpikeWriter::setMetaData(double sr, float *scale, char *name, int slen)
{
hid_t ds, attr, atype;
ds = H5Screate(H5S_SCALAR);
attr = H5Acreate(m_h5group, "Sampling Rate", H5T_IEEE_F64LE, ds,
H5P_DEFAULT, H5P_DEFAULT);
H5Awrite(attr, H5T_NATIVE_DOUBLE, &sr); // TODO: CHECK ERROR
H5Aclose(attr); // TODO: check error
H5Sclose(ds);
hsize_t dims = m_nc;
ds = H5Screate_simple(1, &dims, NULL);
attr = H5Acreate(m_h5group, "Scale Factor", H5T_IEEE_F32LE, ds,
H5P_DEFAULT, H5P_DEFAULT);
H5Awrite(attr, H5T_NATIVE_FLOAT, scale); // TODO: CHECK ERROR
H5Aclose(attr); // TODO: check error
H5Sclose(ds);
ds = H5Screate_simple(1, &dims, NULL);
atype = H5Tcopy(H5T_C_S1);
H5Tset_size(atype, slen);
H5Tset_strpad(atype, H5T_STR_NULLTERM);
attr = H5Acreate(m_h5group, "Channel Name", atype, ds,
H5P_DEFAULT, H5P_DEFAULT);
H5Awrite(attr, atype, name); // TODO: CHECK ERROR
H5Aclose(attr);
H5Sclose(ds);
return true;
}
*/
<|endoftext|> |
<commit_before>#include <vector>
#include <memory>
#include <string>
#include <sstream>
#include <exception>
#include "../third_party/bitmap/bitmap_image.hpp"
#include "../vis/colormap.hpp"
#include "../vis/image.hpp"
#pragma once
namespace io
{
class BmpWriter
{
public:
BmpWriter(std::shared_ptr<vis::Image> image)
: image(image)
{}
/**
* Export to file.
* \param file name
* \param colormap
* \param upscale value
*/
void write(std::string const&, size_t const& = 1) const;
protected:
BmpWriter() = delete;
BmpWriter(BmpWriter const&) = delete;
BmpWriter& operator= (BmpWriter const&) = delete;
private:
std::shared_ptr<vis::Image> image;
};
}
<commit_msg>Added documentation for BmpWriter<commit_after>#include <vector>
#include <memory>
#include <string>
#include <sstream>
#include <exception>
#include "../third_party/bitmap/bitmap_image.hpp"
#include "../vis/colormap.hpp"
#include "../vis/image.hpp"
#pragma once
namespace io
{
/**
* Class to write image data to a Bitmap file.
*/
class BmpWriter
{
public:
/**
* Constructor.
*
* \param image Image object containing pixel values
*/
BmpWriter(std::shared_ptr<vis::Image> image)
: image(image)
{}
/**
* Export to file.
* \param file name
* \param upscale value
*/
void write(std::string const&, size_t const& = 1) const;
protected:
BmpWriter() = delete;
BmpWriter(BmpWriter const&) = delete;
BmpWriter& operator= (BmpWriter const&) = delete;
private:
/**
* Reference to pixel data.
*/
std::shared_ptr<vis::Image> image;
};
}
<|endoftext|> |
<commit_before>// This file is part of Playslave-C++.
// Playslave-C++ is licenced under the MIT license: see LICENSE.txt.
/**
* @file
* Implementation of the non-virtual aspects of the IoReactor class.
* @see io/io_reactor.hpp
* @see io/io_reactor_asio.hpp
* @see io/io_reactor_asio.cpp
* @see io/io_reactor_std.hpp
* @see io/io_reactor_std.cpp
*/
/* This is forced because we require C++11, which has std::chrono, anyway.
Some environments fail Boost's std::chrono detection, and don't set this
flag, which causes compilation failures. */
#ifndef BOOST_ASIO_HAS_STD_CHRONO
#define BOOST_ASIO_HAS_STD_CHRONO
#endif
#include <csignal> // SIG*
#include <string> // std::string
extern "C" {
#include <uv.h>
}
#include "../player/player.hpp" // Player
#include "../cmd.hpp" // CommandHandler
#include "../errors.hpp"
#include "../messages.h" // MSG_*
#include "io_reactor.hpp" // IoReactor
#include "io_response.hpp" // ResponseCode
#include <boost/asio.hpp> // boost::asio::*
#include <boost/asio/high_resolution_timer.hpp> // boost::asio::high_resolution_timer
const std::chrono::nanoseconds IoReactor::PLAYER_UPDATE_PERIOD(1000);
IoReactor::IoReactor(Player &player, CommandHandler &handler,
const std::string &address, const std::string &port)
: player(player),
handler(handler),
io_service(),
acceptor(io_service),
signals(io_service),
manager(),
new_connection(),
loop(uv_loop_new())
{
InitSignals();
InitAcceptor(address, port);
DoAccept();
DoUpdateTimer();
}
void IoReactor::Run()
{
io_service.run();
}
void IoReactor::HandleCommand(const std::string &line)
{
bool valid = this->handler.Handle(line);
if (valid) {
Respond(ResponseCode::OKAY, line);
} else {
Respond(ResponseCode::WHAT, MSG_CMD_INVALID);
}
}
void IoReactor::InitSignals()
{
this->signals.add(SIGINT);
this->signals.add(SIGTERM);
#ifdef SIGQUIT
this->signals.add(SIGQUIT);
#endif // SIGQUIT
this->signals.async_wait([this](boost::system::error_code,
int) { End(); });
}
void IoReactor::DoUpdateTimer()
{
auto tick = std::chrono::duration_cast<
std::chrono::high_resolution_clock::duration>(
PLAYER_UPDATE_PERIOD);
boost::asio::high_resolution_timer t(this->io_service, tick);
t.async_wait([this](boost::system::error_code) {
bool running = this->player.Update();
if (running) {
DoUpdateTimer();
} else {
End();
}
});
}
void IoReactor::InitAcceptor(const std::string &address,
const std::string &port)
{
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::endpoint endpoint =
*resolver.resolve({ address, port });
this->acceptor.open(endpoint.protocol());
this->acceptor.set_option(
boost::asio::ip::tcp::acceptor::reuse_address(true));
this->acceptor.bind(endpoint);
this->acceptor.listen();
}
void IoReactor::DoAccept()
{
auto cmd = [this](const std::string &line) { HandleCommand(line); };
this->new_connection.reset(new TcpConnection(
cmd, this->manager, this->io_service, this->player));
auto on_accept = [this](boost::system::error_code ec) {
if (!ec) {
this->manager.Start(this->new_connection);
}
if (this->acceptor.is_open()) {
DoAccept();
}
};
this->acceptor.async_accept(this->new_connection->Socket(), on_accept);
}
void IoReactor::RespondRaw(const std::string &string)
{
this->manager.Send(string);
}
void IoReactor::End()
{
this->acceptor.close();
this->manager.StopAll();
this->io_service.stop();
}
//
// TcpConnection
//
TcpConnection::TcpConnection(std::function<void(const std::string &)> cmd,
TcpConnectionManager &manager,
boost::asio::io_service &io_service,
const Player &player)
: socket(io_service),
strand(io_service),
outbox(),
cmd(cmd),
manager(manager),
player(player),
closing(false)
{
}
void TcpConnection::Start()
{
this->player.WelcomeClient(*this);
DoRead();
}
void TcpConnection::Stop()
{
this->closing = true;
boost::system::error_code ignored_ec;
this->socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both,
ignored_ec);
this->socket.close();
}
boost::asio::ip::tcp::socket &TcpConnection::Socket()
{
return socket;
}
void TcpConnection::DoRead()
{
// This is needed to keep the TcpConnection alive while it performs the
// read. Otherwise, it'd be destructed as soon as it goes out of the
// connection manager's list and cause illegal memory accesses.
auto self(shared_from_this());
boost::asio::async_read_until(socket, data, "\n",
[this,
self](const boost::system::error_code &
ec,
std::size_t) {
if (!ec) {
std::istream is(&data);
std::string s;
std::getline(is, s);
// If the line ended with CRLF, getline will miss the
// CR, so we need to remove it from the line here.
if (s.back() == '\r') {
s.pop_back();
}
this->cmd(s);
DoRead();
} else if (ec != boost::asio::error::operation_aborted) {
this->manager.Stop(shared_from_this());
}
});
}
void TcpConnection::Send(const std::string &string)
{
if (this->closing) {
return;
}
// This somewhat complex combination of a strand and queue ensure that
// only one process actually writes to a TcpConnection at a given time.
// Otherwise, writes could interrupt each other.
this->strand.post([this, string]() {
this->outbox.push_back(string);
// If this string is the only one in the queue, then the last
// chain
// of DoWrite()s will have ended and we need to start a new one.
if (this->outbox.size() == 1) {
DoWrite();
}
});
}
void TcpConnection::DoWrite()
{
// This is needed to keep the TcpConnection alive while it performs the
// write. Otherwise, it'd be destructed as soon as it goes out of the
// connection manager's list and cause illegal memory accesses.
auto self(shared_from_this());
std::string string = this->outbox[0];
// This is called after the write has finished.
auto write_cb = [this, self](const boost::system::error_code &ec,
std::size_t) {
if (!ec) {
this->outbox.pop_front();
// Keep writing until and unless the outbox is emptied.
// After that, the next Send will start DoWrite()ing
// again.
if (!this->outbox.empty()) {
DoWrite();
}
} else if (ec != boost::asio::error::operation_aborted) {
this->manager.Stop(shared_from_this());
}
};
// Only add the newline character at the final opportunity.
// Makes for easier debug lines.
assert(string.back() != '\n');
string += '\n';
boost::asio::async_write(
this->socket,
boost::asio::buffer(string.c_str(), string.size()),
this->strand.wrap(write_cb));
}
void TcpConnection::RespondRaw(const std::string &string)
{
Send(string);
}
//
// TcpConnectionManager
//
TcpConnectionManager::TcpConnectionManager()
{
}
void TcpConnectionManager::Start(TcpConnection::Pointer c)
{
this->connections.insert(c);
c->Start();
}
void TcpConnectionManager::Stop(TcpConnection::Pointer c)
{
c->Stop();
this->connections.erase(c);
}
void TcpConnectionManager::StopAll()
{
for (auto c : this->connections) {
c->Stop();
}
this->connections.clear();
}
void TcpConnectionManager::Send(const std::string &string)
{
Debug() << "Send to all:" << string << std::endl;
for (auto c : this->connections) {
c->Send(string);
}
}
<commit_msg>Add uv_run call.<commit_after>// This file is part of Playslave-C++.
// Playslave-C++ is licenced under the MIT license: see LICENSE.txt.
/**
* @file
* Implementation of the non-virtual aspects of the IoReactor class.
* @see io/io_reactor.hpp
* @see io/io_reactor_asio.hpp
* @see io/io_reactor_asio.cpp
* @see io/io_reactor_std.hpp
* @see io/io_reactor_std.cpp
*/
/* This is forced because we require C++11, which has std::chrono, anyway.
Some environments fail Boost's std::chrono detection, and don't set this
flag, which causes compilation failures. */
#ifndef BOOST_ASIO_HAS_STD_CHRONO
#define BOOST_ASIO_HAS_STD_CHRONO
#endif
#include <csignal> // SIG*
#include <string> // std::string
extern "C" {
#include <uv.h>
}
#include "../player/player.hpp" // Player
#include "../cmd.hpp" // CommandHandler
#include "../errors.hpp"
#include "../messages.h" // MSG_*
#include "io_reactor.hpp" // IoReactor
#include "io_response.hpp" // ResponseCode
#include <boost/asio.hpp> // boost::asio::*
#include <boost/asio/high_resolution_timer.hpp> // boost::asio::high_resolution_timer
const std::chrono::nanoseconds IoReactor::PLAYER_UPDATE_PERIOD(1000);
IoReactor::IoReactor(Player &player, CommandHandler &handler,
const std::string &address, const std::string &port)
: player(player),
handler(handler),
io_service(),
acceptor(io_service),
signals(io_service),
manager(),
new_connection(),
loop(uv_loop_new())
{
InitSignals();
InitAcceptor(address, port);
DoAccept();
DoUpdateTimer();
}
void IoReactor::Run()
{
uv_run(loop, UV_RUN_DEFAULT);
io_service.run();
}
void IoReactor::HandleCommand(const std::string &line)
{
bool valid = this->handler.Handle(line);
if (valid) {
Respond(ResponseCode::OKAY, line);
} else {
Respond(ResponseCode::WHAT, MSG_CMD_INVALID);
}
}
void IoReactor::InitSignals()
{
this->signals.add(SIGINT);
this->signals.add(SIGTERM);
#ifdef SIGQUIT
this->signals.add(SIGQUIT);
#endif // SIGQUIT
this->signals.async_wait([this](boost::system::error_code,
int) { End(); });
}
void IoReactor::DoUpdateTimer()
{
auto tick = std::chrono::duration_cast<
std::chrono::high_resolution_clock::duration>(
PLAYER_UPDATE_PERIOD);
boost::asio::high_resolution_timer t(this->io_service, tick);
t.async_wait([this](boost::system::error_code) {
bool running = this->player.Update();
if (running) {
DoUpdateTimer();
} else {
End();
}
});
}
void IoReactor::InitAcceptor(const std::string &address,
const std::string &port)
{
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::endpoint endpoint =
*resolver.resolve({ address, port });
this->acceptor.open(endpoint.protocol());
this->acceptor.set_option(
boost::asio::ip::tcp::acceptor::reuse_address(true));
this->acceptor.bind(endpoint);
this->acceptor.listen();
}
void IoReactor::DoAccept()
{
auto cmd = [this](const std::string &line) { HandleCommand(line); };
this->new_connection.reset(new TcpConnection(
cmd, this->manager, this->io_service, this->player));
auto on_accept = [this](boost::system::error_code ec) {
if (!ec) {
this->manager.Start(this->new_connection);
}
if (this->acceptor.is_open()) {
DoAccept();
}
};
this->acceptor.async_accept(this->new_connection->Socket(), on_accept);
}
void IoReactor::RespondRaw(const std::string &string)
{
this->manager.Send(string);
}
void IoReactor::End()
{
this->acceptor.close();
this->manager.StopAll();
this->io_service.stop();
}
//
// TcpConnection
//
TcpConnection::TcpConnection(std::function<void(const std::string &)> cmd,
TcpConnectionManager &manager,
boost::asio::io_service &io_service,
const Player &player)
: socket(io_service),
strand(io_service),
outbox(),
cmd(cmd),
manager(manager),
player(player),
closing(false)
{
}
void TcpConnection::Start()
{
this->player.WelcomeClient(*this);
DoRead();
}
void TcpConnection::Stop()
{
this->closing = true;
boost::system::error_code ignored_ec;
this->socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both,
ignored_ec);
this->socket.close();
}
boost::asio::ip::tcp::socket &TcpConnection::Socket()
{
return socket;
}
void TcpConnection::DoRead()
{
// This is needed to keep the TcpConnection alive while it performs the
// read. Otherwise, it'd be destructed as soon as it goes out of the
// connection manager's list and cause illegal memory accesses.
auto self(shared_from_this());
boost::asio::async_read_until(socket, data, "\n",
[this,
self](const boost::system::error_code &
ec,
std::size_t) {
if (!ec) {
std::istream is(&data);
std::string s;
std::getline(is, s);
// If the line ended with CRLF, getline will miss the
// CR, so we need to remove it from the line here.
if (s.back() == '\r') {
s.pop_back();
}
this->cmd(s);
DoRead();
} else if (ec != boost::asio::error::operation_aborted) {
this->manager.Stop(shared_from_this());
}
});
}
void TcpConnection::Send(const std::string &string)
{
if (this->closing) {
return;
}
// This somewhat complex combination of a strand and queue ensure that
// only one process actually writes to a TcpConnection at a given time.
// Otherwise, writes could interrupt each other.
this->strand.post([this, string]() {
this->outbox.push_back(string);
// If this string is the only one in the queue, then the last
// chain
// of DoWrite()s will have ended and we need to start a new one.
if (this->outbox.size() == 1) {
DoWrite();
}
});
}
void TcpConnection::DoWrite()
{
// This is needed to keep the TcpConnection alive while it performs the
// write. Otherwise, it'd be destructed as soon as it goes out of the
// connection manager's list and cause illegal memory accesses.
auto self(shared_from_this());
std::string string = this->outbox[0];
// This is called after the write has finished.
auto write_cb = [this, self](const boost::system::error_code &ec,
std::size_t) {
if (!ec) {
this->outbox.pop_front();
// Keep writing until and unless the outbox is emptied.
// After that, the next Send will start DoWrite()ing
// again.
if (!this->outbox.empty()) {
DoWrite();
}
} else if (ec != boost::asio::error::operation_aborted) {
this->manager.Stop(shared_from_this());
}
};
// Only add the newline character at the final opportunity.
// Makes for easier debug lines.
assert(string.back() != '\n');
string += '\n';
boost::asio::async_write(
this->socket,
boost::asio::buffer(string.c_str(), string.size()),
this->strand.wrap(write_cb));
}
void TcpConnection::RespondRaw(const std::string &string)
{
Send(string);
}
//
// TcpConnectionManager
//
TcpConnectionManager::TcpConnectionManager()
{
}
void TcpConnectionManager::Start(TcpConnection::Pointer c)
{
this->connections.insert(c);
c->Start();
}
void TcpConnectionManager::Stop(TcpConnection::Pointer c)
{
c->Stop();
this->connections.erase(c);
}
void TcpConnectionManager::StopAll()
{
for (auto c : this->connections) {
c->Stop();
}
this->connections.clear();
}
void TcpConnectionManager::Send(const std::string &string)
{
Debug() << "Send to all:" << string << std::endl;
for (auto c : this->connections) {
c->Send(string);
}
}
<|endoftext|> |
<commit_before>// This file is part of Playslave-C++.
// Playslave-C++ is licenced under the MIT license: see LICENSE.txt.
/**
* @file
* Implementation of the non-virtual aspects of the IoReactor class.
* @see io/io_reactor.hpp
*/
#include <csignal> // SIG*
#include <string> // std::string
extern "C" {
#include <uv.h>
}
#include "../player/player.hpp" // Player
#include "../cmd.hpp" // CommandHandler
#include "../errors.hpp"
#include "../messages.h" // MSG_*
#include "io_reactor.hpp" // IoReactor
#include "io_response.hpp" // ResponseCode
const std::uint16_t IoReactor::PLAYER_UPDATE_PERIOD = 10; // ms
void AllocBuffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf)
{
*buf = uv_buf_init((char *)malloc(suggested_size), suggested_size);
}
void ReadCallback(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf)
{
TcpResponseSink *tcp = static_cast<TcpResponseSink *>(stream->data);
tcp->Read(stream, nread, buf);
}
void OnNewConnection(uv_stream_t *server, int status)
{
if (status == -1) {
return;
}
IoReactor *reactor = static_cast<IoReactor *>(server->data);
reactor->NewConnection(server);
}
void IoReactor::NewConnection(uv_stream_t *server)
{
uv_tcp_t *client = (uv_tcp_t *)malloc(sizeof(uv_tcp_t));
uv_tcp_init(uv_default_loop(), client);
if (uv_accept(server, (uv_stream_t *)client) == 0) {
auto tcp = std::make_shared<TcpResponseSink>(*this, client, this->handler);
this->player.WelcomeClient(*tcp);
this->connections.insert(tcp);
client->data = static_cast<void *>(tcp.get());
uv_read_start((uv_stream_t *)client, AllocBuffer, ReadCallback);
} else {
uv_close((uv_handle_t *)client, nullptr);
}
}
void IoReactor::RemoveConnection(TcpResponseSink &conn)
{
this->connections.erase(std::make_shared<TcpResponseSink>(conn));
}
IoReactor::IoReactor(Player &player, CommandHandler &handler,
const std::string &address, const std::string &port)
: player(player),
handler(handler)
{
InitAcceptor(address, port);
DoUpdateTimer();
}
void IoReactor::Run()
{
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}
void UpdateTimerCallback(uv_timer_t *handle)
{
Player *player = static_cast<Player *>(handle->data);
bool running = player->Update();
if (!running) {
uv_stop(uv_default_loop());
}
}
void CloseCallback(uv_handle_t *handle)
{
TcpResponseSink *tcp = static_cast<TcpResponseSink *>(handle->data);
tcp->Close();
}
void IoReactor::DoUpdateTimer()
{
uv_timer_init(uv_default_loop(), &this->updater);
this->updater.data = static_cast<void *>(&this->player);
uv_timer_start(&this->updater, UpdateTimerCallback, 0, PLAYER_UPDATE_PERIOD);
}
void IoReactor::InitAcceptor(const std::string &address,
const std::string &port)
{
int uport = std::stoi(port);
uv_tcp_init(uv_default_loop(), &this->server);
this->server.data = static_cast<void *>(this);
struct sockaddr_in bind_addr;
uv_ip4_addr(address.c_str(), uport, &bind_addr);
uv_tcp_bind(&this->server, (const sockaddr *)&bind_addr, 0);
int r = uv_listen((uv_stream_t *)&this->server, 128, OnNewConnection);
}
struct WriteReq {
uv_write_t req;
uv_buf_t buf;
};
void RespondCallback(uv_write_t *req, int status)
{
WriteReq *wr = (WriteReq *)req;
delete[] wr->buf.base;
delete wr;
}
void IoReactor::RespondRaw(const std::string &string) const
{
for (const std::shared_ptr<TcpResponseSink> &conn : this->connections) {
conn->RespondRaw(string);
}
}
void IoReactor::End()
{
uv_stop(uv_default_loop());
}
//
// TcpResponseSink
//
TcpResponseSink::TcpResponseSink(IoReactor &parent, uv_tcp_t *tcp, CommandHandler &handler)
: parent(parent),
tcp(tcp),
tokeniser(handler, *this)
{
}
void TcpResponseSink::RespondRaw(const std::string &string) const
{
unsigned int l = string.length();
const char *s = string.c_str();
WriteReq *req = new WriteReq;
req->buf = uv_buf_init(new char[l + 1], l + 1);
memcpy(req->buf.base, s, l);
req->buf.base[l] = '\n';
uv_write((uv_write_t *)req, (uv_stream_t *)tcp, &req->buf, 1, RespondCallback);
}
void TcpResponseSink::Read(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf)
{
if (nread < 0) {
if (nread == UV_EOF) {
uv_close((uv_handle_t *)stream, CloseCallback);
}
return;
}
this->tokeniser.Feed(buf->base, (buf->base) + nread);
}
void TcpResponseSink::Close()
{
Debug() << "Closing client connection" << std::endl;
this->parent.RemoveConnection(*this);
}<commit_msg>Use const auto &.<commit_after>// This file is part of Playslave-C++.
// Playslave-C++ is licenced under the MIT license: see LICENSE.txt.
/**
* @file
* Implementation of the non-virtual aspects of the IoReactor class.
* @see io/io_reactor.hpp
*/
#include <csignal> // SIG*
#include <string> // std::string
extern "C" {
#include <uv.h>
}
#include "../player/player.hpp" // Player
#include "../cmd.hpp" // CommandHandler
#include "../errors.hpp"
#include "../messages.h" // MSG_*
#include "io_reactor.hpp" // IoReactor
#include "io_response.hpp" // ResponseCode
const std::uint16_t IoReactor::PLAYER_UPDATE_PERIOD = 10; // ms
void AllocBuffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf)
{
*buf = uv_buf_init((char *)malloc(suggested_size), suggested_size);
}
void ReadCallback(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf)
{
TcpResponseSink *tcp = static_cast<TcpResponseSink *>(stream->data);
tcp->Read(stream, nread, buf);
}
void OnNewConnection(uv_stream_t *server, int status)
{
if (status == -1) {
return;
}
IoReactor *reactor = static_cast<IoReactor *>(server->data);
reactor->NewConnection(server);
}
void IoReactor::NewConnection(uv_stream_t *server)
{
uv_tcp_t *client = (uv_tcp_t *)malloc(sizeof(uv_tcp_t));
uv_tcp_init(uv_default_loop(), client);
if (uv_accept(server, (uv_stream_t *)client) == 0) {
auto tcp = std::make_shared<TcpResponseSink>(*this, client, this->handler);
this->player.WelcomeClient(*tcp);
this->connections.insert(tcp);
client->data = static_cast<void *>(tcp.get());
uv_read_start((uv_stream_t *)client, AllocBuffer, ReadCallback);
} else {
uv_close((uv_handle_t *)client, nullptr);
}
}
void IoReactor::RemoveConnection(TcpResponseSink &conn)
{
this->connections.erase(std::make_shared<TcpResponseSink>(conn));
}
IoReactor::IoReactor(Player &player, CommandHandler &handler,
const std::string &address, const std::string &port)
: player(player),
handler(handler)
{
InitAcceptor(address, port);
DoUpdateTimer();
}
void IoReactor::Run()
{
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}
void UpdateTimerCallback(uv_timer_t *handle)
{
Player *player = static_cast<Player *>(handle->data);
bool running = player->Update();
if (!running) {
uv_stop(uv_default_loop());
}
}
void CloseCallback(uv_handle_t *handle)
{
TcpResponseSink *tcp = static_cast<TcpResponseSink *>(handle->data);
tcp->Close();
}
void IoReactor::DoUpdateTimer()
{
uv_timer_init(uv_default_loop(), &this->updater);
this->updater.data = static_cast<void *>(&this->player);
uv_timer_start(&this->updater, UpdateTimerCallback, 0, PLAYER_UPDATE_PERIOD);
}
void IoReactor::InitAcceptor(const std::string &address,
const std::string &port)
{
int uport = std::stoi(port);
uv_tcp_init(uv_default_loop(), &this->server);
this->server.data = static_cast<void *>(this);
struct sockaddr_in bind_addr;
uv_ip4_addr(address.c_str(), uport, &bind_addr);
uv_tcp_bind(&this->server, (const sockaddr *)&bind_addr, 0);
int r = uv_listen((uv_stream_t *)&this->server, 128, OnNewConnection);
}
struct WriteReq {
uv_write_t req;
uv_buf_t buf;
};
void RespondCallback(uv_write_t *req, int status)
{
WriteReq *wr = (WriteReq *)req;
delete[] wr->buf.base;
delete wr;
}
void IoReactor::RespondRaw(const std::string &string) const
{
for (const auto &conn : this->connections) {
conn->RespondRaw(string);
}
}
void IoReactor::End()
{
uv_stop(uv_default_loop());
}
//
// TcpResponseSink
//
TcpResponseSink::TcpResponseSink(IoReactor &parent, uv_tcp_t *tcp, CommandHandler &handler)
: parent(parent),
tcp(tcp),
tokeniser(handler, *this)
{
}
void TcpResponseSink::RespondRaw(const std::string &string) const
{
unsigned int l = string.length();
const char *s = string.c_str();
WriteReq *req = new WriteReq;
req->buf = uv_buf_init(new char[l + 1], l + 1);
memcpy(req->buf.base, s, l);
req->buf.base[l] = '\n';
uv_write((uv_write_t *)req, (uv_stream_t *)tcp, &req->buf, 1, RespondCallback);
}
void TcpResponseSink::Read(uv_stream_t *stream, ssize_t nread, const uv_buf_t *buf)
{
if (nread < 0) {
if (nread == UV_EOF) {
uv_close((uv_handle_t *)stream, CloseCallback);
}
return;
}
this->tokeniser.Feed(buf->base, (buf->base) + nread);
}
void TcpResponseSink::Close()
{
Debug() << "Closing client connection" << std::endl;
this->parent.RemoveConnection(*this);
}<|endoftext|> |
<commit_before>#include "rosplan_planning_system/PlannerInterface/FFPlannerInterface.h"
namespace KCL_rosplan {
/*-------------*/
/* constructor */
/*-------------*/
FFPlannerInterface::FFPlannerInterface(ros::NodeHandle& nh)
{
node_handle = &nh;
plan_server = new actionlib::SimpleActionServer<rosplan_dispatch_msgs::PlanAction>((*node_handle), "start_planning", boost::bind(&PlannerInterface::runPlanningServerAction, this, _1), false);
// publishing raw planner output
std::string plannerTopic = "planner_output";
node_handle->getParam("planner_topic", plannerTopic);
plan_publisher = node_handle->advertise<std_msgs::String>(plannerTopic, 1, true);
// start planning action server
plan_server->start();
}
FFPlannerInterface::~FFPlannerInterface()
{
delete plan_server;
}
/**
* Runs external commands
*/
std::string FFPlannerInterface::runCommand(std::string cmd) {
std::string data;
FILE *stream;
char buffer[1000];
stream = popen(cmd.c_str(), "r");
while ( fgets(buffer, 1000, stream) != NULL )
data.append(buffer);
pclose(stream);
return data;
}
/*------------------*/
/* Plan and process */
/*------------------*/
/**
* passes the problem to the Planner; the plan to post-processing.
*/
bool FFPlannerInterface::runPlanner() {
// save problem to file for POPF
if(use_problem_topic && problem_instance_recieved) {
ROS_INFO("KCL: (%s) (%s) Writing problem to file.", ros::this_node::getName().c_str(), problem_name.c_str());
std::ofstream dest;
dest.open((problem_path).c_str());
dest << problem_instance;
dest.close();
}
// prepare the planner command line
std::string str = planner_command;
std::size_t dit = str.find("DOMAIN");
if(dit!=std::string::npos) str.replace(dit,6,domain_path);
std::size_t pit = str.find("PROBLEM");
if(pit!=std::string::npos) str.replace(pit,7,problem_path);
std::string commandString = str + " > " + data_path + "plan.pddl";
// call the planer
ROS_INFO("KCL: (%s) (%s) Running: %s", ros::this_node::getName().c_str(), problem_name.c_str(), commandString.c_str());
std::string plan = runCommand(commandString.c_str());
ROS_INFO("KCL: (%s) (%s) Planning complete", ros::this_node::getName().c_str(), problem_name.c_str());
// check the planner solved the problem
std::ifstream planfile;
planfile.open((data_path + "plan.pddl").c_str());
std::string line;
std::stringstream ss;
bool solved = false;
while (std::getline(planfile, line)) {
// skip lines until there is a plan
if(line.compare("ff: found legal plan as follows") != 0) {
continue;
}
// skip the empty line
while (std::getline(planfile, line)) {
if (line.length()<2) break;
}
// actions look like this:
// step 0: got_place C1
// 1: find_object V1 C1
solved = true;
while (std::getline(planfile, line)) {
if (line.length()<2) break;
unsigned int pos = line.find(' ');
bool action = false;
while(pos != std::string::npos && pos < line.length()) {
if(line.substr(pos,1) != " ") {
action = true;
line = line.substr(pos);
break;
}
pos++;
}
if(action) ss << line << " [0.001]" << std::endl;
}
planner_output = ss.str();
}
planfile.close();
if(!solved) ROS_INFO("KCL: (%s) (%s) Plan was unsolvable.", ros::this_node::getName().c_str(), problem_name.c_str());
else ROS_INFO("KCL: (%s) (%s) Plan was solved.", ros::this_node::getName().c_str(), problem_name.c_str());
return solved;
}
} // close namespace
/*-------------*/
/* Main method */
/*-------------*/
int main(int argc, char **argv) {
srand (static_cast <unsigned> (time(0)));
ros::init(argc,argv,"rosplan_planner_interface");
ros::NodeHandle nh("~");
KCL_rosplan::FFPlannerInterface pi(nh);
// subscribe to problem instance
std::string problemTopic = "problem_instance";
nh.getParam("problem_topic", problemTopic);
ros::Subscriber problem_sub = nh.subscribe(problemTopic, 1, &KCL_rosplan::PlannerInterface::problemCallback, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));
// start the planning services
ros::ServiceServer service1 = nh.advertiseService("planning_server", &KCL_rosplan::PlannerInterface::runPlanningServerDefault, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));
ros::ServiceServer service2 = nh.advertiseService("planning_server_params", &KCL_rosplan::PlannerInterface::runPlanningServerParams, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));
ROS_INFO("KCL: (%s) Ready to receive", ros::this_node::getName().c_str());
ros::spin();
return 0;
}
<commit_msg>Update FFPlannerInterface.cpp<commit_after>#include "rosplan_planning_system/PlannerInterface/FFPlannerInterface.h"
namespace KCL_rosplan {
/*-------------*/
/* constructor */
/*-------------*/
FFPlannerInterface::FFPlannerInterface(ros::NodeHandle& nh)
{
node_handle = &nh;
plan_server = new actionlib::SimpleActionServer<rosplan_dispatch_msgs::PlanAction>((*node_handle), "start_planning", boost::bind(&PlannerInterface::runPlanningServerAction, this, _1), false);
// publishing raw planner output
std::string plannerTopic = "planner_output";
node_handle->getParam("planner_topic", plannerTopic);
plan_publisher = node_handle->advertise<std_msgs::String>(plannerTopic, 1, true);
// start planning action server
plan_server->start();
}
FFPlannerInterface::~FFPlannerInterface()
{
delete plan_server;
}
/**
* Runs external commands
*/
std::string FFPlannerInterface::runCommand(std::string cmd) {
std::string data;
FILE *stream;
char buffer[1000];
stream = popen(cmd.c_str(), "r");
while ( fgets(buffer, 1000, stream) != NULL )
data.append(buffer);
pclose(stream);
return data;
}
/*------------------*/
/* Plan and process */
/*------------------*/
/**
* passes the problem to the Planner; the plan to post-processing.
*/
bool FFPlannerInterface::runPlanner() {
// save problem to file for planner
if(use_problem_topic && problem_instance_recieved) {
ROS_INFO("KCL: (%s) (%s) Writing problem to file.", ros::this_node::getName().c_str(), problem_name.c_str());
std::ofstream dest;
dest.open((problem_path).c_str());
dest << problem_instance;
dest.close();
}
// prepare the planner command line
std::string str = planner_command;
std::size_t dit = str.find("DOMAIN");
if(dit!=std::string::npos) str.replace(dit,6,domain_path);
std::size_t pit = str.find("PROBLEM");
if(pit!=std::string::npos) str.replace(pit,7,problem_path);
std::string commandString = str + " > " + data_path + "plan.pddl";
// call the planer
ROS_INFO("KCL: (%s) (%s) Running: %s", ros::this_node::getName().c_str(), problem_name.c_str(), commandString.c_str());
std::string plan = runCommand(commandString.c_str());
ROS_INFO("KCL: (%s) (%s) Planning complete", ros::this_node::getName().c_str(), problem_name.c_str());
// check the planner solved the problem
std::ifstream planfile;
planfile.open((data_path + "plan.pddl").c_str());
std::string line;
std::stringstream ss;
bool solved = false;
while (std::getline(planfile, line)) {
// skip lines until there is a plan
if(line.compare("ff: found legal plan as follows") != 0) {
continue;
}
// skip the empty line
while (std::getline(planfile, line)) {
if (line.length()<2) break;
}
// actions look like this:
// step 0: got_place C1
// 1: find_object V1 C1
solved = true;
while (std::getline(planfile, line)) {
if (line.length()<2) break;
unsigned int pos = line.find(' ');
bool action = false;
while(pos != std::string::npos && pos < line.length()) {
if(line.substr(pos,1) != " ") {
action = true;
line = line.substr(pos);
break;
}
pos++;
}
if(action) ss << line << " [0.001]" << std::endl;
}
planner_output = ss.str();
}
planfile.close();
if(!solved) ROS_INFO("KCL: (%s) (%s) Plan was unsolvable.", ros::this_node::getName().c_str(), problem_name.c_str());
else ROS_INFO("KCL: (%s) (%s) Plan was solved.", ros::this_node::getName().c_str(), problem_name.c_str());
return solved;
}
} // close namespace
/*-------------*/
/* Main method */
/*-------------*/
int main(int argc, char **argv) {
srand (static_cast <unsigned> (time(0)));
ros::init(argc,argv,"rosplan_planner_interface");
ros::NodeHandle nh("~");
KCL_rosplan::FFPlannerInterface pi(nh);
// subscribe to problem instance
std::string problemTopic = "problem_instance";
nh.getParam("problem_topic", problemTopic);
ros::Subscriber problem_sub = nh.subscribe(problemTopic, 1, &KCL_rosplan::PlannerInterface::problemCallback, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));
// start the planning services
ros::ServiceServer service1 = nh.advertiseService("planning_server", &KCL_rosplan::PlannerInterface::runPlanningServerDefault, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));
ros::ServiceServer service2 = nh.advertiseService("planning_server_params", &KCL_rosplan::PlannerInterface::runPlanningServerParams, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));
ROS_INFO("KCL: (%s) Ready to receive", ros::this_node::getName().c_str());
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>/*
*
* Author: Jeffrey Leung
* Last edited: 2015-12-21
*
* This C++ header file contains the LabyrinthMap class which creates, updates,
* and displays a map of a given Labyrinth.
*
*/
#include <stdexcept>
#include "../include/labyrinth_map.hpp"
// This method returns whether a given Wall coordinate has a wall in the
// given direction.
// An exception is thrown if:
// d is kNone (invalid_argument)
bool LabyrinthMapCoordinateBorder::IsWall( Direction d ) const
{
switch( d )
{
case Direction::kNorth:
return wall_north_;
case Direction::kEast:
return wall_east_;
case Direction::kSouth:
return wall_south_;
case Direction::kWest:
return wall_west_;
default:
throw std::invalid_argument( "Error: IsWall() was given an invalid " \
"direction (kNone)." );
}
}
// This method creates the Wall of a given Wall coordinate.
// May be used to set a Wall which has already been set.
// An exception is thrown if:
// d is kNone (invalid_argument)
void LabyrinthMapCoordinateBorder::RemoveWall( Direction d )
{
switch( d )
{
case Direction::kNorth:
wall_north_ = false;
return;
case Direction::kEast:
wall_east_ = false;
return;
case Direction::kSouth:
wall_south_ = false;
return;
case Direction::kWest:
wall_west_ = false;
return;
default:
throw std::invalid_argument( "Error: SetWall() was given an invalid "\
"direction (kNone)." );
}
return;
}
// This method returns whether a given Wall coordinate has the exit.
bool LabyrinthMapCoordinateBorder::IsExit() const
{
return exit_;
}
// This method sets whether or not a given Wall coordinate has the exit.
// May be used to set an exit where the exit already exists, or to remove
// an exit where none exists.
void LabyrinthMapCoordinateBorder::SetExit( bool b )
{
exit_ = b;
}
// This method returns the inhabitant of the current Room.
Inhabitant LabyrinthMapCoordinateRoom::HasInhabitant() const
{
return i_;
}
// This method sets the current inhabitant of the map's Room.
// May be used to set the inhabitant to the same inhabitant, or to
// no inhabitant.
void LabyrinthMapCoordinateRoom::SetInhabitant( Inhabitant inh )
{
i_ = inh;
}
// This method returns whether the treasure is in a given Room.
bool LabyrinthMapCoordinateRoom::HasTreasure() const
{
return treasure_;
}
// This method sets whether or not the treasure is in the given map's Room.
// May be used to set the treasure when there is already a treasure in
// the Room, or to remove the treasure when there is no treasure already.
void LabyrinthMapCoordinateRoom::SetTreasure( bool b )
{
treasure_ = b;
}
// Parameterized constructor
// An exception is thrown if:
// l is null (invalid_argument)
LabyrinthMap::LabyrinthMap( Labyrinth* l,
unsigned int x_size,
unsigned int y_size )
{
if( l == nullptr )
{
throw std::invalid_argument( "Error: LabyrinthMap() was given an "\
"invalid (null) pointer for the Labyrinth." );
}
l_ = l;
x_size_ = x_size;
y_size_ = y_size;
map_x_size_ = x_size * 2 + 1;
map_y_size_ = y_size * 2 + 1;
// Creation of the map array
map_ = new LabyrinthMapCoordinate**[ map_y_size_ ];
for( unsigned int i = 0; i < map_y_size_; ++i )
{
map_[i] = new LabyrinthMapCoordinate*[ map_x_size_ ];
}
// Creation of the individual map rooms/borders
Coordinate c;
for( unsigned int y = 0; y < map_y_size_; ++y )
{
for( unsigned int x = 0; x < map_x_size_; ++x )
{
c.x = x;
c.y = y;
if( IsRoom(c) )
{
map_[x][y] = new LabyrinthMapCoordinateRoom;
}
else
{
map_[x][y] = new LabyrinthMapCoordinateBorder;
}
}
}
//TODO Remove excess bounds on the exterior of the Labyrinth
//TODO Initialization of the border coordinates
//Update(); //TODO Uncomment when Update() is implemented
}
// This method returns true if the Coordinate is within the bounds
// of the Map, and false otherwise.
bool LabyrinthMap::WithinBoundsOfMap( const Coordinate c ) const
{
return ( -1 < c.x && c.x < map_x_size_ &&
-1 < c.y && c.y < map_y_size_ );
}
// This private method returns true if the coordinate designates a Room in
// the map, and false if it designates a Border.
// An exception is thrown if:
// The coordinate is outside of the Map (domain_error)
bool LabyrinthMap::IsRoom( const Coordinate c ) const
{
if( WithinBoundsOfMap(c) )
{
return c.x % 2 == 1 && c.y % 2 == 1;
}
else
{
throw std::domain_error( "Error: IsRoom() was given a Coordinate "\
"outside of the Map." );
}
}
//TODO Implementation of labyrinth_map.hpp
<commit_msg>Removing lower bounds check for unsigned values.<commit_after>/*
*
* Author: Jeffrey Leung
* Last edited: 2015-12-21
*
* This C++ header file contains the LabyrinthMap class which creates, updates,
* and displays a map of a given Labyrinth.
*
*/
#include <stdexcept>
#include "../include/labyrinth_map.hpp"
// This method returns whether a given Wall coordinate has a wall in the
// given direction.
// An exception is thrown if:
// d is kNone (invalid_argument)
bool LabyrinthMapCoordinateBorder::IsWall( Direction d ) const
{
switch( d )
{
case Direction::kNorth:
return wall_north_;
case Direction::kEast:
return wall_east_;
case Direction::kSouth:
return wall_south_;
case Direction::kWest:
return wall_west_;
default:
throw std::invalid_argument( "Error: IsWall() was given an invalid " \
"direction (kNone)." );
}
}
// This method creates the Wall of a given Wall coordinate.
// May be used to set a Wall which has already been set.
// An exception is thrown if:
// d is kNone (invalid_argument)
void LabyrinthMapCoordinateBorder::RemoveWall( Direction d )
{
switch( d )
{
case Direction::kNorth:
wall_north_ = false;
return;
case Direction::kEast:
wall_east_ = false;
return;
case Direction::kSouth:
wall_south_ = false;
return;
case Direction::kWest:
wall_west_ = false;
return;
default:
throw std::invalid_argument( "Error: SetWall() was given an invalid "\
"direction (kNone)." );
}
return;
}
// This method returns whether a given Wall coordinate has the exit.
bool LabyrinthMapCoordinateBorder::IsExit() const
{
return exit_;
}
// This method sets whether or not a given Wall coordinate has the exit.
// May be used to set an exit where the exit already exists, or to remove
// an exit where none exists.
void LabyrinthMapCoordinateBorder::SetExit( bool b )
{
exit_ = b;
}
// This method returns the inhabitant of the current Room.
Inhabitant LabyrinthMapCoordinateRoom::HasInhabitant() const
{
return i_;
}
// This method sets the current inhabitant of the map's Room.
// May be used to set the inhabitant to the same inhabitant, or to
// no inhabitant.
void LabyrinthMapCoordinateRoom::SetInhabitant( Inhabitant inh )
{
i_ = inh;
}
// This method returns whether the treasure is in a given Room.
bool LabyrinthMapCoordinateRoom::HasTreasure() const
{
return treasure_;
}
// This method sets whether or not the treasure is in the given map's Room.
// May be used to set the treasure when there is already a treasure in
// the Room, or to remove the treasure when there is no treasure already.
void LabyrinthMapCoordinateRoom::SetTreasure( bool b )
{
treasure_ = b;
}
// Parameterized constructor
// An exception is thrown if:
// l is null (invalid_argument)
LabyrinthMap::LabyrinthMap( Labyrinth* l,
unsigned int x_size,
unsigned int y_size )
{
if( l == nullptr )
{
throw std::invalid_argument( "Error: LabyrinthMap() was given an "\
"invalid (null) pointer for the Labyrinth." );
}
l_ = l;
x_size_ = x_size;
y_size_ = y_size;
map_x_size_ = x_size * 2 + 1;
map_y_size_ = y_size * 2 + 1;
// Creation of the map array
map_ = new LabyrinthMapCoordinate**[ map_y_size_ ];
for( unsigned int i = 0; i < map_y_size_; ++i )
{
map_[i] = new LabyrinthMapCoordinate*[ map_x_size_ ];
}
// Creation of the individual map rooms/borders
Coordinate c;
for( unsigned int y = 0; y < map_y_size_; ++y )
{
for( unsigned int x = 0; x < map_x_size_; ++x )
{
c.x = x;
c.y = y;
if( IsRoom(c) )
{
map_[x][y] = new LabyrinthMapCoordinateRoom;
}
else
{
map_[x][y] = new LabyrinthMapCoordinateBorder;
}
}
}
//TODO Remove excess bounds on the exterior of the Labyrinth
//TODO Initialization of the border coordinates
//Update(); //TODO Uncomment when Update() is implemented
}
// This method returns true if the Coordinate is within the bounds
// of the Map, and false otherwise.
bool LabyrinthMap::WithinBoundsOfMap( const Coordinate c ) const
{
return ( c.x < map_x_size_ &&
c.y < map_y_size_ );
}
// This private method returns true if the coordinate designates a Room in
// the map, and false if it designates a Border.
// An exception is thrown if:
// The coordinate is outside of the Map (domain_error)
bool LabyrinthMap::IsRoom( const Coordinate c ) const
{
if( WithinBoundsOfMap(c) )
{
return c.x % 2 == 1 && c.y % 2 == 1;
}
else
{
throw std::domain_error( "Error: IsRoom() was given a Coordinate "\
"outside of the Map." );
}
}
//TODO Implementation of labyrinth_map.hpp
<|endoftext|> |
<commit_before><commit_msg>Marked NotificationTest.TestDOMUIMessageCallback as FAILS after r61174 due to DOM UI bindings being disabled for non-chrome:// URLs.<commit_after><|endoftext|> |
<commit_before>#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include "BasicSort.hpp"
#include "BitonicSort.hpp"
// #include "QuickSort.hpp"
#include "MergeSort.hpp"
#include "CSVTools.hpp"
#define THREAD_START 1
#define SIZE_START 10
#define DEFAULT_ELEMENTS 100
#define DEFAULT_THREADS 4
#define DEFAULT_GAP 10
#define DEFAULT_SAVE_FILE "results.csv"
#define FIELD_WIDTH 10
#define PROG_NAME "Laser Patroll Sorting Benchmark Application"
#define VERSION_STRING "Version: Alpha"
// Potential return values.
const int SUCCESS = 0;
const int ERROR_ON_COMMAND_LINE = 1;
const int ERROR_UNHANDLED_EXCEPTION = 2;
int main(int argc, char * argv[])
{
try {
// Setup and configure the input parser.
namespace po = boost::program_options;
po::variables_map vm;
bool sweep;
bool no_bitonic, no_merge, no_basic;
// Add options here
po::options_description generic("Program Options");
generic.add_options()
("help,h", "Prints out help information.")
("version,v", "Prints out version information.");
po::options_description configuration("Configuration Options");
configuration.add_options()
("size,s", po::value<size_t>()->default_value(DEFAULT_ELEMENTS),
"Number of elements to sort.")
("threads,t", po::value<size_t>()->default_value(DEFAULT_THREADS),
"Number of threads to use for sorting.")
("sweep,z", po::value(&sweep)->zero_tokens(),
"Runs sweep mode. Increment threads by 1 to <threads> and "
"multiple size from 10 by <gap>.")
("file,f", po::value<std::string>(),
"File name to save output data in.");
po::options_description sweep_po("Sweep Options (Used only if <sweep> is set)");
sweep_po.add_options()
("gap,g", po::value<size_t>()->default_value(DEFAULT_GAP),
"Specifies the multiple factor to multiply vector size by"
" in sweep mode.")
("init_size,w",
po::value<size_t>()->default_value(SIZE_START),
"The initial data size to use in sweep mode.");
po::options_description tests_po("Exclude Tests:");
tests_po.add_options()
("basic", po::value(&no_basic)->zero_tokens(),
"Excludes basic sort from tests.")
("bitonic", po::value(&no_bitonic)->zero_tokens(),
"Excludes bitonic sort from tests.")
("merge", po::value(&no_merge)->zero_tokens(),
"Excludes merge sort from tests.");
po::options_description cmd_line_options;
cmd_line_options.add(generic).add(configuration).add(sweep_po).add(tests_po);
// Try to parse the input parameters.
try {
po::store(po::parse_command_line(argc, argv, cmd_line_options),
vm);
// --help option
if( vm.count("help") ) {
std::cout << std::endl << PROG_NAME << std::endl <<
VERSION_STRING << std::endl <<
cmd_line_options << std::endl;
return SUCCESS;
}
// --version options
if( vm.count("version") ) {
std::cout << std::endl << PROG_NAME << std::endl <<
VERSION_STRING << std::endl;
}
po::notify(vm);
}
catch(po::error& e) {
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << cmd_line_options << std::endl;
return ERROR_ON_COMMAND_LINE;
}
// Input parameters were good. Now actually run the program.
// First, get the parameters from the argument parser.
const size_t num_threads = vm["threads"].as<size_t>();
const size_t max_data_size = vm["size"].as<size_t>();
const size_t desired_gap = vm["gap"].as<size_t>();
// Variables used for loops below.
size_t thread_init, size_init;
if(sweep) {
thread_init = THREAD_START;
size_init = vm["init_size"].as<size_t>();
} else {
thread_init = num_threads;
size_init = max_data_size;
}
// Instantiate the sort classes.
//QuickSort quick_sort;
MergeSort * merge_sort = new MergeSort();
BasicSort * basic_sort = new BasicSort();
BitonicSort * bio_sort = new BitonicSort();
CSVTools * csv;
if(vm.count("file"))
csv = new CSVTools(vm["file"].as<std::string>());
// User has requested that data is swept.
for(size_t curr_thread = thread_init; curr_thread <= num_threads; curr_thread++)
{
for(size_t curr_size = size_init; curr_size <= max_data_size; curr_size *= desired_gap)
{
std::cout << "Threads: " <<
std::setw(FIELD_WIDTH) << curr_thread << std::endl;
std::cout << "Data Size: " <<
std::setw(FIELD_WIDTH) << curr_size << std::endl;
SortCommon::DataType const * input_data = new SortCommon::DataType();
input_data = SortCommon::NewData(curr_size);
if(!no_basic)
{
double basic_time = basic_sort->
BenchmarkSort(input_data, curr_thread);
if( vm.count("file") )
{
csv->WriteResult(BasicSort::kTableKey, curr_thread,
curr_size, basic_time);
}
std::cout << "Basic Sort Time: " << std::fixed <<
std::setw(FIELD_WIDTH) << basic_time << std::endl;
}
if(!no_bitonic)
{
double bio_time = bio_sort->
BenchmarkSort(input_data, curr_thread);
if( vm.count("file") )
{
csv->WriteResult(BitonicSort::kTableKey, curr_thread,
curr_size, bio_time);
}
std::cout << "Bitonic Sort Time: " << std::fixed <<
std::setw(FIELD_WIDTH) << bio_time << std::endl;
}
if(!no_merge)
{
double merge_time = merge_sort->
BenchmarkSort(input_data, curr_thread);
if( vm.count("file") )
{
csv->WriteResult(MergeSort::kTableKey, curr_thread,
curr_size, merge_time);
}
std::cout << "MergeSort Sort Time: " << std::fixed <<
std::setw(FIELD_WIDTH) << merge_time << std::endl;
}
std::cout << std::endl;
delete input_data;
}
}
return SUCCESS;
}
catch(std::exception& e) {
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
}
<commit_msg>Fixing issue with sweep not having default value and setting csv to NULL.<commit_after>#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include "BasicSort.hpp"
#include "BitonicSort.hpp"
// #include "QuickSort.hpp"
#include "MergeSort.hpp"
#include "CSVTools.hpp"
#define THREAD_START 1
#define SIZE_START 10
#define DEFAULT_ELEMENTS 100
#define DEFAULT_THREADS 4
#define DEFAULT_GAP 10
#define DEFAULT_SAVE_FILE "results.csv"
#define FIELD_WIDTH 10
#define PROG_NAME "Laser Patroll Sorting Benchmark Application"
#define VERSION_STRING "Version: Alpha"
// Potential return values.
const int SUCCESS = 0;
const int ERROR_ON_COMMAND_LINE = 1;
const int ERROR_UNHANDLED_EXCEPTION = 2;
int main(int argc, char * argv[])
{
try {
// Setup and configure the input parser.
namespace po = boost::program_options;
po::variables_map vm;
bool sweep = false;
bool no_bitonic = false;
bool no_merge = false;
bool no_basic = false;
// Add options here
po::options_description generic("Program Options");
generic.add_options()
("help,h", "Prints out help information.")
("version,v", "Prints out version information.");
po::options_description configuration("Configuration Options");
configuration.add_options()
("size,s", po::value<size_t>()->default_value(DEFAULT_ELEMENTS),
"Number of elements to sort.")
("threads,t", po::value<size_t>()->default_value(DEFAULT_THREADS),
"Number of threads to use for sorting.")
("sweep,z", po::value(&sweep)->zero_tokens(),
"Runs sweep mode. Increment threads by 1 to <threads> and "
"multiple size from 10 by <gap>.")
("file,f", po::value<std::string>(),
"File name to save output data in.");
po::options_description sweep_po("Sweep Options (Used only if <sweep> is set)");
sweep_po.add_options()
("gap,g", po::value<size_t>()->default_value(DEFAULT_GAP),
"Specifies the multiple factor to multiply vector size by"
" in sweep mode.")
("init_size,w",
po::value<size_t>()->default_value(SIZE_START),
"The initial data size to use in sweep mode.");
po::options_description tests_po("Exclude Tests:");
tests_po.add_options()
("basic", po::value(&no_basic)->zero_tokens(),
"Excludes basic sort from tests.")
("bitonic", po::value(&no_bitonic)->zero_tokens(),
"Excludes bitonic sort from tests.")
("merge", po::value(&no_merge)->zero_tokens(),
"Excludes merge sort from tests.");
po::options_description cmd_line_options;
cmd_line_options.add(generic).add(configuration).add(sweep_po).add(tests_po);
// Try to parse the input parameters.
try {
po::store(po::parse_command_line(argc, argv, cmd_line_options),
vm);
// --help option
if( vm.count("help") ) {
std::cout << std::endl << PROG_NAME << std::endl <<
VERSION_STRING << std::endl <<
cmd_line_options << std::endl;
return SUCCESS;
}
// --version options
if( vm.count("version") ) {
std::cout << std::endl << PROG_NAME << std::endl <<
VERSION_STRING << std::endl;
}
po::notify(vm);
}
catch(po::error& e) {
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << cmd_line_options << std::endl;
return ERROR_ON_COMMAND_LINE;
}
// Input parameters were good. Now actually run the program.
// First, get the parameters from the argument parser.
const size_t num_threads = vm["threads"].as<size_t>();
const size_t max_data_size = vm["size"].as<size_t>();
const size_t desired_gap = vm["gap"].as<size_t>();
// Variables used for loops below.
size_t thread_init, size_init;
if(sweep) {
thread_init = THREAD_START;
size_init = vm["init_size"].as<size_t>();
} else {
thread_init = num_threads;
size_init = max_data_size;
}
// Instantiate the sort classes.
//QuickSort quick_sort;
MergeSort * merge_sort = new MergeSort();
BasicSort * basic_sort = new BasicSort();
BitonicSort * bio_sort = new BitonicSort();
CSVTools * csv = NULL;
if(vm.count("file"))
csv = new CSVTools(vm["file"].as<std::string>());
// User has requested that data is swept.
for(size_t curr_thread = thread_init; curr_thread <= num_threads; curr_thread++)
{
for(size_t curr_size = size_init; curr_size <= max_data_size; curr_size *= desired_gap)
{
std::cout << "Threads: " <<
std::setw(FIELD_WIDTH) << curr_thread << std::endl;
std::cout << "Data Size: " <<
std::setw(FIELD_WIDTH) << curr_size << std::endl;
SortCommon::DataType const * input_data = new SortCommon::DataType();
input_data = SortCommon::NewData(curr_size);
if(!no_basic)
{
double basic_time = basic_sort->
BenchmarkSort(input_data, curr_thread);
if( vm.count("file") )
{
csv->WriteResult(BasicSort::kTableKey, curr_thread,
curr_size, basic_time);
}
std::cout << "Basic Sort Time: " << std::fixed <<
std::setw(FIELD_WIDTH) << basic_time << std::endl;
}
if(!no_bitonic)
{
double bio_time = bio_sort->
BenchmarkSort(input_data, curr_thread);
if( vm.count("file") )
{
csv->WriteResult(BitonicSort::kTableKey, curr_thread,
curr_size, bio_time);
}
std::cout << "Bitonic Sort Time: " << std::fixed <<
std::setw(FIELD_WIDTH) << bio_time << std::endl;
}
if(!no_merge)
{
double merge_time = merge_sort->
BenchmarkSort(input_data, curr_thread);
if( vm.count("file") )
{
csv->WriteResult(MergeSort::kTableKey, curr_thread,
curr_size, merge_time);
}
std::cout << "MergeSort Sort Time: " << std::fixed <<
std::setw(FIELD_WIDTH) << merge_time << std::endl;
}
std::cout << std::endl;
delete input_data;
}
}
return SUCCESS;
}
catch(std::exception& e) {
std::cerr << "Unhandled Exception reached the top of main: "
<< e.what() << ", application will now exit" << std::endl;
return ERROR_UNHANDLED_EXCEPTION;
}
}
<|endoftext|> |
<commit_before>#include "../include/level_factory.hpp"
#include "../engine/include/persistence_dat.hpp"
#include "../engine/include/observable.hpp"
#include "../engine/include/log.hpp"
#include <unordered_map>
#include <vector>
using namespace mindscape;
typedef mindscape::GameObjectFactory::Options Opts;
/**
* @brief Updates Game level.
*
* Initiates changing of level, such as changes of scenes.
*
* @param level Level to be changed.
* @param path Path of new level.
* @return void.
*/
void LevelFactory::update_level(engine::Level *level, std::string path) {
DEBUG("Started: update_level()");
std::vector<engine::GameObject *> new_objects = execute_dat(level, path);
for (auto game_object : new_objects) {
level->activate_game_object(game_object);
game_object->load();
}
DEBUG("Ended: update_level()");
}
/**
* @brief Executes Level's data.
*
* Sets all dimension, coordinates, audios and game's objects in the level.
*
* @param level Level to be changed.
* @param path Path of the level.
* @return GameObject Vector of new game objects.
*/
std::vector<engine::GameObject *> LevelFactory::execute_dat(
engine::Level *level, std::string path) {
DEBUG("Started: GameObject execute_dat()");
std::vector<std::string> includes;
std::vector<engine::GameObject *> added_game_objects;
GameObjectFactory mindscape_factory = GameObjectFactory();
engine::PersistenceDat *persistence =
engine::PersistenceDat::get_instance();
engine::PersistenceMap *objects = persistence->load(path);
if (!!objects) {
for (auto it = objects->begin(); it < objects->end(); it++) {
std::unordered_map<std::string, std::string> object = *it;
Opts type = static_cast<Opts>(std::stoi(object["type"]));
if (type == Opts::HITBOX) {
std::pair<int, int> dimensions;
std::pair<int, int> displacement;
dimensions.first = std::stoi(object["size_x"]);
dimensions.second = std::stoi(object["size_y"]);
displacement.first = std::stoi(object["displ_x"]);
displacement.second = std::stoi(object["displ_y"]);
mindscape_factory.fabricate_hitbox(level->get_object_by_name(
object["belongs_to"]), displacement, dimensions);
}
else if (type == Opts::IMAGE) {
int priority = 0;
priority = std::stoi(object["priority"]);
std::pair<int, int> displacement;
std::pair<int, int> dimensions_on_screen;
std::pair<int, int> dimensions_on_texture;
std::pair<int, int> coordinatesOnTexture;
displacement.first = std::stoi(object["displ_x"]);
displacement.second = std::stoi(object["displ_y"]);
dimensions_on_screen.first = std::stoi(object["screen_x"]);
dimensions_on_screen.second = std::stoi(object["screen_y"]);
dimensions_on_texture.first = std::stoi(object["tex_x"]);
dimensions_on_texture.second = std::stoi(object["tex_y"]);
coordinatesOnTexture.first = std::stoi(object["tex_coord_x"]);
coordinatesOnTexture.second = std::stoi(object["tex_coord_y"]);
mindscape_factory.fabricate_image(
level->get_object_by_name(object["belongs_to"]),
object["path"], displacement, priority,
dimensions_on_screen, dimensions_on_texture,
coordinatesOnTexture
);
}
else if (type == Opts::TEXT) {
int priority = 0;
priority = std::stoi(object["priority"]);
std::string text = object["text"];
std::string font_path = object["font_path"];
int font_size = 0;
font_size = std::stoi(object["font_size"]);
std::pair<int, int> displacement;
displacement.first = std::stoi(object["displ_x"]);
displacement.second = std::stoi(object["displ_y"]);
mindscape_factory.fabricate_text(
level->get_object_by_name(object["belongs_to"]),
text, font_path, font_size, displacement, priority
);
}
else if (type == Opts::AUDIO) {
int audio_type = 0;
std::string name = "";
std::string path = "";
audio_type = std::stoi(object["audio_type"]);
name = object["id"];
path = object["path"];
mindscape_factory.fabricate_audio(
level->get_object_by_name(object["belongs_to"]),
name, path, audio_type
);
}
else if (type == Opts::ACTION) {
mindscape_factory.fabricate_action(
level->get_object_by_name(object["belongs_to"]),
std::stoi(object["command"]), object["param"]
);
}
else if (type == Opts::TRANSLATION) {
int key = 0;
std::string event_name = "";
event_name = object["event_name"];
key = std::stoi(object["key"]);
mindscape_factory.fabricate_translation(
level->get_object_by_name(object["belongs_to"]),
key, event_name
);
}
else {
engine::GameObject * constructed_obj =
mindscape_factory.fabricate(
type, object["id"],
std::make_pair(std::stoi(object["x"]),
std::stoi(object["y"])), std::stoi(object["priority"])
);
if (object.count("follows") > 0) { //if follow key is declared
engine::Observable * observable =
level->get_object_by_name(object["follows"]);
observable->attach_observer(constructed_obj);
}
level->add_object(constructed_obj);
added_game_objects.push_back(constructed_obj);
}
}
}
return added_game_objects;
DEBUG("Ended: GameObject execute_dat()");
}
/**
* @brief Fabricates Game Level.
*
* Realizes all the process to build the game level.
*
* @fn execute_dat Decribed above.
* @param path Path of the level datas.
* @return GameObject Vector of new game objects.
*/
engine::Level *LevelFactory::fabricate_level(std::string path) {
INFO("Building Game Level");
engine::Level *level = new engine::Level();
execute_dat(level, path);
return level;
DEBUG("Ended: Building Game level");
}
/**
* @brief Fabricates Menu.
*
* Returns a level null for fabricates the menu.
*
* @return Level null.
*/
engine::Level* LevelFactory::fabricate_menu(){
INFO("Fabricates the menu");
return NULL;
}
/**
* @brief Fabricates Game Over.
*
* Returns a level null for fabricates game over.
*
* @return Level null.
*/
engine::Level* LevelFactory::fabricate_game_over(){
INFO("Fabricates Game Over");
return NULL;
}
<commit_msg>[DEFAULT BEHAVIOR] Applies default behavior in level_factory.cpp<commit_after>#include "../include/level_factory.hpp"
#include "../engine/include/persistence_dat.hpp"
#include "../engine/include/observable.hpp"
#include "../engine/include/log.hpp"
#include <unordered_map>
#include <vector>
using namespace mindscape;
typedef mindscape::GameObjectFactory::Options Opts;
/**
* @brief Updates Game level.
*
* Initiates changing of level, such as changes of scenes.
*
* @param level Level to be changed.
* @param path Path of new level.
* @return void.
*/
void LevelFactory::update_level(engine::Level *level, std::string path) {
DEBUG("Started: update_level()");
std::vector<engine::GameObject *> new_objects = execute_dat(level, path);
for (auto game_object : new_objects) {
level->activate_game_object(game_object);
game_object->load();
}
DEBUG("Ended: update_level()");
}
/**
* @brief Executes Level's data.
*
* Sets all dimension, coordinates, audios and game's objects in the level.
*
* @param level Level to be changed.
* @param path Path of the level.
* @return GameObject Vector of new game objects.
*/
std::vector<engine::GameObject *> LevelFactory::execute_dat(
engine::Level *level, std::string path) {
DEBUG("Started: GameObject execute_dat()");
std::vector<std::string> includes;
std::vector<engine::GameObject *> added_game_objects;
GameObjectFactory mindscape_factory = GameObjectFactory();
engine::PersistenceDat *persistence =
engine::PersistenceDat::get_instance();
engine::PersistenceMap *objects = persistence->load(path);
if (!!objects) {
for (auto it = objects->begin(); it < objects->end(); it++) {
std::unordered_map<std::string, std::string> object = *it;
Opts type = static_cast<Opts>(std::stoi(object["type"]));
if (type == Opts::HITBOX) {
std::pair<int, int> dimensions;
std::pair<int, int> displacement;
dimensions.first = std::stoi(object["size_x"]);
dimensions.second = std::stoi(object["size_y"]);
displacement.first = std::stoi(object["displ_x"]);
displacement.second = std::stoi(object["displ_y"]);
mindscape_factory.fabricate_hitbox(level->get_object_by_name(
object["belongs_to"]), displacement, dimensions);
}
else if (type == Opts::IMAGE) {
int priority = 0;
priority = std::stoi(object["priority"]);
std::pair<int, int> displacement;
displacement.first = std::stoi(object["displ_x"]);
displacement.second = std::stoi(object["displ_y"]);
std::pair<int, int> dimensions_on_screen;
dimensions_on_screen.first = std::stoi(object["screen_x"]);
dimensions_on_screen.second = std::stoi(object["screen_y"]);
std::pair<int, int> dimensions_on_texture;
dimensions_on_texture.first = std::stoi(object["tex_x"]);
dimensions_on_texture.second = std::stoi(object["tex_y"]);
std::pair<int, int> coordinatesOnTexture;
coordinatesOnTexture.first = std::stoi(object["tex_coord_x"]);
coordinatesOnTexture.second = std::stoi(object["tex_coord_y"]);
mindscape_factory.fabricate_image(
level->get_object_by_name(object["belongs_to"]),
object["path"], displacement, priority,
dimensions_on_screen, dimensions_on_texture,
coordinatesOnTexture
);
}
else if (type == Opts::TEXT) {
int priority = 0;
priority = std::stoi(object["priority"]);
std::string text = object["text"];
std::string font_path = object["font_path"];
int font_size = 0;
font_size = std::stoi(object["font_size"]);
std::pair<int, int> displacement;
displacement.first = std::stoi(object["displ_x"]);
displacement.second = std::stoi(object["displ_y"]);
mindscape_factory.fabricate_text(
level->get_object_by_name(object["belongs_to"]),
text, font_path, font_size, displacement, priority
);
}
else if (type == Opts::AUDIO) {
int audio_type = 0;
std::string name = "";
std::string path = "";
audio_type = std::stoi(object["audio_type"]);
name = object["id"];
path = object["path"];
mindscape_factory.fabricate_audio(
level->get_object_by_name(object["belongs_to"]),
name, path, audio_type
);
}
else if (type == Opts::ACTION) {
mindscape_factory.fabricate_action(
level->get_object_by_name(object["belongs_to"]),
std::stoi(object["command"]), object["param"]
);
}
else if (type == Opts::TRANSLATION) {
int key = 0;
std::string event_name = "";
event_name = object["event_name"];
key = std::stoi(object["key"]);
mindscape_factory.fabricate_translation(
level->get_object_by_name(object["belongs_to"]),
key, event_name
);
}
else {
engine::GameObject * constructed_obj =
mindscape_factory.fabricate(
type, object["id"],
std::make_pair(std::stoi(object["x"]),
std::stoi(object["y"])), std::stoi(object["priority"])
);
/* If follow key is declared */
if (object.count("follows") > 0) {
engine::Observable * observable =
level->get_object_by_name(object["follows"]);
observable->attach_observer(constructed_obj);
}
else {
INFO("Follow Key is not declared");
}
level->add_object(constructed_obj);
added_game_objects.push_back(constructed_obj);
}
}
}
else {
/* Do nothing */
}
return added_game_objects;
DEBUG("Ended: GameObject execute_dat()");
}
/**
* @brief Fabricates Game Level.
*
* Realizes all the process to build the game level.
*
* @fn execute_dat Decribed above.
* @param path Path of the level datas.
* @return GameObject Vector of new game objects.
*/
engine::Level *LevelFactory::fabricate_level(std::string path) {
INFO("Building Game Level");
engine::Level *level = new engine::Level();
execute_dat(level, path);
return level;
DEBUG("Ended: Building Game level");
}
/**
* @brief Fabricates Menu.
*
* Returns a level null for fabricates the menu.
*
* @return Level null.
*/
engine::Level* LevelFactory::fabricate_menu(){
INFO("Fabricates the menu");
return NULL;
}
/**
* @brief Fabricates Game Over.
*
* Returns a level null for fabricates game over.
*
* @return Level null.
*/
engine::Level* LevelFactory::fabricate_game_over(){
INFO("Fabricates Game Over");
return NULL;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: filid.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2004-05-10 14:21:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FILID_HXX_
#include "filid.hxx"
#endif
#ifndef _SHELL_HXX_
#include "shell.hxx"
#endif
using namespace fileaccess;
using namespace com::sun::star;
using namespace com::sun::star::ucb;
FileContentIdentifier::FileContentIdentifier(
shell* pMyShell,
const rtl::OUString& aUnqPath,
sal_Bool IsNormalized )
: m_pMyShell( pMyShell ),
m_bNormalized( IsNormalized )
{
if( IsNormalized )
{
m_pMyShell->getUrlFromUnq( aUnqPath,m_aContentId );
m_aNormalizedId = aUnqPath;
m_pMyShell->getScheme( m_aProviderScheme );
}
else
{
m_pMyShell->getUnqFromUrl( aUnqPath,m_aNormalizedId );
m_aContentId = aUnqPath;
m_pMyShell->getScheme( m_aProviderScheme );
}
}
FileContentIdentifier::~FileContentIdentifier()
{
}
void SAL_CALL
FileContentIdentifier::acquire(
void )
throw()
{
OWeakObject::acquire();
}
void SAL_CALL
FileContentIdentifier::release(
void )
throw()
{
OWeakObject::release();
}
uno::Any SAL_CALL
FileContentIdentifier::queryInterface(
const uno::Type& rType )
throw( uno::RuntimeException )
{
uno::Any aRet = cppu::queryInterface( rType,
SAL_STATIC_CAST( lang::XTypeProvider*, this),
SAL_STATIC_CAST( XContentIdentifier*, this) );
return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );
}
uno::Sequence< sal_Int8 > SAL_CALL
FileContentIdentifier::getImplementationId()
throw( uno::RuntimeException )
{
static cppu::OImplementationId* pId = NULL;
if ( !pId )
{
osl::Guard< osl::Mutex > aGuard( osl::Mutex::getGlobalMutex() );
if ( !pId )
{
static cppu::OImplementationId id( sal_False );
pId = &id;
}
}
return (*pId).getImplementationId();
}
uno::Sequence< uno::Type > SAL_CALL
FileContentIdentifier::getTypes(
void )
throw( uno::RuntimeException )
{
static cppu::OTypeCollection* pCollection = NULL;
if ( !pCollection ) {
osl::Guard< osl::Mutex > aGuard( osl::Mutex::getGlobalMutex() );
if ( !pCollection )
{
static cppu::OTypeCollection collection(
getCppuType( static_cast< uno::Reference< lang::XTypeProvider >* >( 0 ) ),
getCppuType( static_cast< uno::Reference< XContentIdentifier >* >( 0 ) ) );
pCollection = &collection;
}
}
return (*pCollection).getTypes();
}
rtl::OUString
SAL_CALL
FileContentIdentifier::getContentIdentifier(
void )
throw( uno::RuntimeException )
{
return m_aContentId;
}
rtl::OUString SAL_CALL
FileContentIdentifier::getContentProviderScheme(
void )
throw( uno::RuntimeException )
{
return m_aProviderScheme;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.94); FILE MERGED 2005/09/05 18:45:00 rt 1.5.94.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: filid.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:23:59 $
*
* 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 _FILID_HXX_
#include "filid.hxx"
#endif
#ifndef _SHELL_HXX_
#include "shell.hxx"
#endif
using namespace fileaccess;
using namespace com::sun::star;
using namespace com::sun::star::ucb;
FileContentIdentifier::FileContentIdentifier(
shell* pMyShell,
const rtl::OUString& aUnqPath,
sal_Bool IsNormalized )
: m_pMyShell( pMyShell ),
m_bNormalized( IsNormalized )
{
if( IsNormalized )
{
m_pMyShell->getUrlFromUnq( aUnqPath,m_aContentId );
m_aNormalizedId = aUnqPath;
m_pMyShell->getScheme( m_aProviderScheme );
}
else
{
m_pMyShell->getUnqFromUrl( aUnqPath,m_aNormalizedId );
m_aContentId = aUnqPath;
m_pMyShell->getScheme( m_aProviderScheme );
}
}
FileContentIdentifier::~FileContentIdentifier()
{
}
void SAL_CALL
FileContentIdentifier::acquire(
void )
throw()
{
OWeakObject::acquire();
}
void SAL_CALL
FileContentIdentifier::release(
void )
throw()
{
OWeakObject::release();
}
uno::Any SAL_CALL
FileContentIdentifier::queryInterface(
const uno::Type& rType )
throw( uno::RuntimeException )
{
uno::Any aRet = cppu::queryInterface( rType,
SAL_STATIC_CAST( lang::XTypeProvider*, this),
SAL_STATIC_CAST( XContentIdentifier*, this) );
return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );
}
uno::Sequence< sal_Int8 > SAL_CALL
FileContentIdentifier::getImplementationId()
throw( uno::RuntimeException )
{
static cppu::OImplementationId* pId = NULL;
if ( !pId )
{
osl::Guard< osl::Mutex > aGuard( osl::Mutex::getGlobalMutex() );
if ( !pId )
{
static cppu::OImplementationId id( sal_False );
pId = &id;
}
}
return (*pId).getImplementationId();
}
uno::Sequence< uno::Type > SAL_CALL
FileContentIdentifier::getTypes(
void )
throw( uno::RuntimeException )
{
static cppu::OTypeCollection* pCollection = NULL;
if ( !pCollection ) {
osl::Guard< osl::Mutex > aGuard( osl::Mutex::getGlobalMutex() );
if ( !pCollection )
{
static cppu::OTypeCollection collection(
getCppuType( static_cast< uno::Reference< lang::XTypeProvider >* >( 0 ) ),
getCppuType( static_cast< uno::Reference< XContentIdentifier >* >( 0 ) ) );
pCollection = &collection;
}
}
return (*pCollection).getTypes();
}
rtl::OUString
SAL_CALL
FileContentIdentifier::getContentIdentifier(
void )
throw( uno::RuntimeException )
{
return m_aContentId;
}
rtl::OUString SAL_CALL
FileContentIdentifier::getContentProviderScheme(
void )
throw( uno::RuntimeException )
{
return m_aProviderScheme;
}
<|endoftext|> |
<commit_before>/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 1998 Graydon Hoare <[email protected]>
* Copyright (C) 1999, 2000 Stefan Seefeld <[email protected]>
* http://www.fresco.org
*
* 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; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include <Fresco/config.hh>
#include <Fresco/DrawingKit.hh>
#include <Fresco/DrawTraversal.hh>
#include <Fresco/Region.hh>
#include <Fresco/IO.hh>
#include "TextChunk.hh"
#include <strstream>
using namespace Fresco;
using namespace Berlin::TextKit;
TextChunk::TextChunk(Unichar u, const Fresco::Graphic::Requisition &r)
: _width(r.x.natural), _height(r.y.natural), _xalign(r.x.align), _yalign(r.y.align), _char(u), _obj_name(0)
{
}
TextChunk::~TextChunk()
{
if (_obj_name) free(const_cast<char*>(_obj_name));
}
void TextChunk::request(Fresco::Graphic::Requisition &r)
{
r.x.defined = true;
r.x.minimum = r.x.natural = r.x.maximum = _width;
r.x.align = _xalign;
r.y.defined = true;
r.y.minimum = r.y.natural = r.y.maximum = _height;
r.y.align = _yalign;
}
const char *TextChunk::object_name()
{
if (_obj_name) return _obj_name;
std::ostringstream buf;
buf << "Char ";
if (_char < 128) buf << (char)_char << std::ends;
else buf << _char << std::ends;
_obj_name = strdup(buf.str().c_str());
return _obj_name;
}
void TextChunk::get_text(Babylon::String &u)
{
u = Babylon::String(_char);
}
unsigned long TextChunk::get_length()
{
return 1;
}
void TextChunk::draw(DrawTraversal_ptr traversal)
{
DrawingKit_var drawing = traversal->drawing();
drawing->draw_char(_char);
}
<commit_msg>s/strstream/sstream/<commit_after>/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 1998 Graydon Hoare <[email protected]>
* Copyright (C) 1999, 2000 Stefan Seefeld <[email protected]>
* http://www.fresco.org
*
* 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; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include <Fresco/config.hh>
#include <Fresco/DrawingKit.hh>
#include <Fresco/DrawTraversal.hh>
#include <Fresco/Region.hh>
#include <Fresco/IO.hh>
#include "TextChunk.hh"
#include <sstream>
using namespace Fresco;
using namespace Berlin::TextKit;
TextChunk::TextChunk(Unichar u, const Fresco::Graphic::Requisition &r)
: _width(r.x.natural), _height(r.y.natural), _xalign(r.x.align), _yalign(r.y.align), _char(u), _obj_name(0)
{
}
TextChunk::~TextChunk()
{
if (_obj_name) free(const_cast<char*>(_obj_name));
}
void TextChunk::request(Fresco::Graphic::Requisition &r)
{
r.x.defined = true;
r.x.minimum = r.x.natural = r.x.maximum = _width;
r.x.align = _xalign;
r.y.defined = true;
r.y.minimum = r.y.natural = r.y.maximum = _height;
r.y.align = _yalign;
}
const char *TextChunk::object_name()
{
if (_obj_name) return _obj_name;
std::ostringstream buf;
buf << "Char ";
if (_char < 128) buf << (char)_char << std::ends;
else buf << _char << std::ends;
_obj_name = strdup(buf.str().c_str());
return _obj_name;
}
void TextChunk::get_text(Babylon::String &u)
{
u = Babylon::String(_char);
}
unsigned long TextChunk::get_length()
{
return 1;
}
void TextChunk::draw(DrawTraversal_ptr traversal)
{
DrawingKit_var drawing = traversal->drawing();
drawing->draw_char(_char);
}
<|endoftext|> |
<commit_before>// Copyright 2016-2019 Jean-Francois Poilpret
//
// 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 <fastarduino/time.h>
#include <fastarduino/i2c_device.h>
#include <fastarduino/devices/mcp23017.h>
constexpr const i2c::I2CMode I2C_MODE = i2c::I2CMode::Fast;
using MCP = devices::MCP23017<I2C_MODE>;
using MCP_PORT = devices::MCP23017Port;
static inline uint8_t shift_pattern(uint8_t pattern, uint8_t shift, bool direction)
{
if (direction) shift = 8 - shift;
uint16_t result = (pattern << shift);
return result | (result >> 8);
}
static inline uint8_t calculate_pattern(uint8_t switches)
{
switch ((~switches) & 0x07)
{
case 0x00:
return 0x01;
case 0x01:
return 0x03;
case 0x02:
return 0x07;
case 0x03:
return 0x0F;
case 0x04:
return 0x55;
case 0x05:
return 0x33;
case 0x06:
return 0x11;
case 0x07:
return 0xDB;
}
}
int main() __attribute__((OS_main));
int main()
{
board::init();
sei();
// Start TWI interface
//====================
i2c::I2CManager<I2C_MODE> manager;
manager.begin();
// Initialize chip
//=================
time::delay_ms(100);
MCP mcp{manager, 0x00};
mcp.configure_gpio<MCP_PORT::PORT_AB>(0x0F00, 0x0F00);
// mcp.configure_gpio<MCP_PORT::PORT_A>(0x00);
// mcp.configure_gpio<MCP_PORT::PORT_B>(0x0F, 0x0F);
mcp.values<MCP_PORT::PORT_AB>(0x0011);
time::delay_ms(1000);
mcp.values<MCP_PORT::PORT_AB>(0x0000);
// Loop of the LED chaser
uint8_t switches = (mcp.values<MCP_PORT::PORT_AB>() >> 8) & 0x0F;
bool direction = (~switches) & 0x08;
uint8_t pattern = calculate_pattern(switches);
while (true)
{
uint8_t new_switches = (mcp.values<MCP_PORT::PORT_AB>() >> 8) & 0x0F;
if (switches != new_switches)
{
switches = new_switches;
direction = (~switches) & 0x08;
pattern = calculate_pattern(switches);
}
for (uint8_t i = 0; i < 8; ++i)
{
mcp.values<MCP_PORT::PORT_AB>(shift_pattern(pattern, i, direction));
time::delay_ms(250);
}
}
// Stop TWI interface
//===================
manager.end();
}
<commit_msg>Remove obsolete comments.<commit_after>// Copyright 2016-2019 Jean-Francois Poilpret
//
// 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 <fastarduino/time.h>
#include <fastarduino/i2c_device.h>
#include <fastarduino/devices/mcp23017.h>
constexpr const i2c::I2CMode I2C_MODE = i2c::I2CMode::Fast;
using MCP = devices::MCP23017<I2C_MODE>;
using MCP_PORT = devices::MCP23017Port;
static inline uint8_t shift_pattern(uint8_t pattern, uint8_t shift, bool direction)
{
if (direction) shift = 8 - shift;
uint16_t result = (pattern << shift);
return result | (result >> 8);
}
static inline uint8_t calculate_pattern(uint8_t switches)
{
switch ((~switches) & 0x07)
{
case 0x00:
return 0x01;
case 0x01:
return 0x03;
case 0x02:
return 0x07;
case 0x03:
return 0x0F;
case 0x04:
return 0x55;
case 0x05:
return 0x33;
case 0x06:
return 0x11;
case 0x07:
return 0xDB;
}
}
int main() __attribute__((OS_main));
int main()
{
board::init();
sei();
// Start TWI interface
//====================
i2c::I2CManager<I2C_MODE> manager;
manager.begin();
// Initialize chip
//=================
time::delay_ms(100);
MCP mcp{manager, 0x00};
mcp.configure_gpio<MCP_PORT::PORT_AB>(0x0F00, 0x0F00);
mcp.values<MCP_PORT::PORT_AB>(0x0011);
time::delay_ms(1000);
mcp.values<MCP_PORT::PORT_AB>(0x0000);
// Loop of the LED chaser
uint8_t switches = (mcp.values<MCP_PORT::PORT_AB>() >> 8) & 0x0F;
bool direction = (~switches) & 0x08;
uint8_t pattern = calculate_pattern(switches);
while (true)
{
uint8_t new_switches = (mcp.values<MCP_PORT::PORT_AB>() >> 8) & 0x0F;
if (switches != new_switches)
{
switches = new_switches;
direction = (~switches) & 0x08;
pattern = calculate_pattern(switches);
}
for (uint8_t i = 0; i < 8; ++i)
{
mcp.values<MCP_PORT::PORT_AB>(shift_pattern(pattern, i, direction));
time::delay_ms(250);
}
}
// Stop TWI interface
//===================
manager.end();
}
<|endoftext|> |
<commit_before>
#include "local_tree.h"
#include "matrices.h"
namespace argweaver {
using namespace std;
//=============================================================================
// Sample recombinations
double recomb_prob_unnormalized(const ArgModel *model, const LocalTree *tree,
const LineageCounts &lineages,
const State &last_state,
const State &state,
const NodePoint &recomb, bool internal)
{
const int k = recomb.time;
const int j = state.time;
int root_time;
int recomb_parent_age;
if (internal) {
int subtree_root = tree->nodes[tree->root].child[0];
int maintree_root = tree->nodes[tree->root].child[1];
root_time = max(tree->nodes[maintree_root].age, last_state.time);
recomb_parent_age = (recomb.node == subtree_root ||
tree->nodes[recomb.node].parent == -1 ||
recomb.node == last_state.node) ?
last_state.time :
tree->nodes[tree->nodes[recomb.node].parent].age;
} else {
root_time = max(tree->nodes[tree->root].age, last_state.time);
recomb_parent_age = (recomb.node == -1 ||
tree->nodes[recomb.node].parent == -1 ||
recomb.node == last_state.node) ?
last_state.time :
tree->nodes[tree->nodes[recomb.node].parent].age;
}
int nbranches_k = lineages.nbranches[k]
+ int(k < last_state.time);
int nrecombs_k = lineages.nrecombs[k]
+ int(k <= last_state.time)
+ int(k == last_state.time)
- int(k == root_time);
// The commented-out section would be correct if we were rounding
// recombs to nearest time point in the same way as coals (keep because
// hope to make this change eventually)
/*double precomb = nbranches_k*model->coal_time_steps[2*k]/nrecombs_k;
if (k > 0) {
int m=k-1;
int nbranches_m = lineages.nbranches[m]
+ int(m < last_state.time)
- int(m < recomb_parent_age);
int nrecombs_m = lineages.nrecombs[m]
+ int(m <= last_state.time)
+ int(m == last_state.time);
precomb += nbranches_m*model->coal_time_steps[2*k-1]/nrecombs_m;
}*/
double precomb = nbranches_k * model->time_steps[k] / nrecombs_k;
// probability of not coalescing before time j-1
double sum = 0.0;
for (int m=k; m<j-1; m++) {
int nbranches_m = lineages.nbranches[m]
+ int(m < last_state.time)
- int(m < recomb_parent_age);
sum += (model->time_steps[m] * nbranches_m
/ (2.0 * model->popsizes[m]));
}
// probability of coalescing at time j
double pcoal = 1.0;
int nbranches_j = lineages.nbranches[j]
+ int(j < last_state.time)
- int(j < recomb_parent_age);
assert(nbranches_j > 0);
if (k == j) {
// in this case coalesce event must happen between time
// j,j+1/2 (coal_time_step[2j])
// NOTE: if k == ntimes - 2, coalescence is probability 1.0
if (j < model->ntimes - 2) {
pcoal = 1.0 - exp(-model->coal_time_steps[2*j] * nbranches_j
/ (2.0 * model->popsizes[j]));
}
} else {
// otherwise it could happen anytime between j-1/2 and j+1/2
int m = j - 1;
int nbranches_m = lineages.nbranches[m]
+ int(m < last_state.time)
- int(m < recomb_parent_age);
// have to not coalesce in the first half interval before j
sum += (model->coal_time_steps[2*m] * nbranches_m
/ (2.0 * model->popsizes[m]));
// NOTE: if k == ntimes - 2, coalescence is probability 1.0
if (j < model->ntimes - 2) {
pcoal = 1.0 - exp(
-model->coal_time_steps[2*j-1] * nbranches_m
/ (2.0 * model->popsizes[m])
- model->coal_time_steps[2*j] * nbranches_j
/ (2.0 * model->popsizes[j]));
}
}
// probability of recoalescing on a choosen branch
int ncoals_j = lineages.ncoals[j]
- int(j <= recomb_parent_age) - int(j == recomb_parent_age);
pcoal /= ncoals_j;
return precomb * exp(- sum) * pcoal;
}
// Returns the possible recombination events that are compatiable with
// the transition (last_state -> state).
void get_possible_recomb(const LocalTree *tree,
const State last_state, const State state,
bool internal, vector<NodePoint> &candidates)
{
// represents the branch above the new node in the tree.
const int new_node = -1;
int end_time = min(state.time, last_state.time);
if (state.node == last_state.node) {
// y = v, k in [0, min(timei, last_timei)]
// y = node, k in Sr(node)
for (int k=tree->nodes[state.node].age; k<=end_time; k++)
candidates.push_back(NodePoint(state.node, k));
}
if (internal) {
const int subtree_root = tree->nodes[tree->root].child[0];
const int subtree_root_age = tree->nodes[subtree_root].age;
for (int k=subtree_root_age; k<=end_time; k++)
candidates.push_back(NodePoint(subtree_root, k));
} else {
for (int k=0; k<=end_time; k++)
candidates.push_back(NodePoint(new_node, k));
}
}
void sample_recombinations(
const LocalTrees *trees, const ArgModel *model,
ArgHmmMatrixIter *matrix_iter,
int *thread_path, vector<int> &recomb_pos, vector<NodePoint> &recombs,
bool internal)
{
States states;
LineageCounts lineages(model->ntimes);
vector <NodePoint> candidates;
vector <double> probs;
// loop through local blocks
for (matrix_iter->begin(); matrix_iter->more(); matrix_iter->next()) {
// get local block information
ArgHmmMatrices &matrices = matrix_iter->ref_matrices();
LocalTree *tree = matrix_iter->get_tree_spr()->tree;
lineages.count(tree, internal);
matrices.states_model.get_coal_states(tree, states);
int next_recomb = -1;
// don't sample recombination if there is no state space
if (internal && states.size() == 0)
continue;
int start = matrix_iter->get_block_start();
int end = matrix_iter->get_block_end();
if (matrices.transmat_switch || start == trees->start_coord) {
// don't allow new recomb at start if we are switching blocks
start++;
}
// loop through positions in block
for (int i=start; i<end; i++) {
if (thread_path[i] == thread_path[i-1]) {
// no change in state, recombination is optional
if (i > next_recomb) {
// sample the next recomb pos
int last_state = thread_path[i-1];
TransMatrix *m = matrices.transmat;
int a = states[last_state].time;
double self_trans = m->get(
tree, states, last_state, last_state);
double rate = 1.0 - (m->norecombs[a] / self_trans);
// NOTE: the min prevents large floats from overflowing
// when cast to int
next_recomb = int(min(double(end), i + expovariate(rate)));
}
if (i < next_recomb)
continue;
}
// sample recombination
next_recomb = -1;
State state = states[thread_path[i]];
State last_state = states[thread_path[i-1]];
// there must be a recombination
// either because state changed or we choose to recombine
// find candidates
candidates.clear();
get_possible_recomb(tree, last_state, state, internal, candidates);
// compute probability of each candidate
probs.clear();
for (vector<NodePoint>::iterator it=candidates.begin();
it != candidates.end(); ++it) {
probs.push_back(recomb_prob_unnormalized(
model, tree, lineages, last_state, state, *it, internal));
}
// sample recombination
recomb_pos.push_back(i);
recombs.push_back(candidates[sample(&probs[0], probs.size())]);
assert(recombs[recombs.size()-1].time <= min(state.time,
last_state.time));
}
}
}
} // namespace argweaver
<commit_msg>remove tabs<commit_after>
#include "local_tree.h"
#include "matrices.h"
namespace argweaver {
using namespace std;
//=============================================================================
// Sample recombinations
double recomb_prob_unnormalized(const ArgModel *model, const LocalTree *tree,
const LineageCounts &lineages,
const State &last_state,
const State &state,
const NodePoint &recomb, bool internal)
{
const int k = recomb.time;
const int j = state.time;
int root_time;
int recomb_parent_age;
if (internal) {
int subtree_root = tree->nodes[tree->root].child[0];
int maintree_root = tree->nodes[tree->root].child[1];
root_time = max(tree->nodes[maintree_root].age, last_state.time);
recomb_parent_age = (recomb.node == subtree_root ||
tree->nodes[recomb.node].parent == -1 ||
recomb.node == last_state.node) ?
last_state.time :
tree->nodes[tree->nodes[recomb.node].parent].age;
} else {
root_time = max(tree->nodes[tree->root].age, last_state.time);
recomb_parent_age = (recomb.node == -1 ||
tree->nodes[recomb.node].parent == -1 ||
recomb.node == last_state.node) ?
last_state.time :
tree->nodes[tree->nodes[recomb.node].parent].age;
}
int nbranches_k = lineages.nbranches[k]
+ int(k < last_state.time);
int nrecombs_k = lineages.nrecombs[k]
+ int(k <= last_state.time)
+ int(k == last_state.time)
- int(k == root_time);
// The commented-out section would be correct if we were rounding
// recombs to nearest time point in the same way as coals (keep because
// hope to make this change eventually)
/*double precomb = nbranches_k*model->coal_time_steps[2*k]/nrecombs_k;
if (k > 0) {
int m=k-1;
int nbranches_m = lineages.nbranches[m]
+ int(m < last_state.time)
- int(m < recomb_parent_age);
int nrecombs_m = lineages.nrecombs[m]
+ int(m <= last_state.time)
+ int(m == last_state.time);
precomb += nbranches_m*model->coal_time_steps[2*k-1]/nrecombs_m;
}*/
double precomb = nbranches_k * model->time_steps[k] / nrecombs_k;
// probability of not coalescing before time j-1
double sum = 0.0;
for (int m=k; m<j-1; m++) {
int nbranches_m = lineages.nbranches[m]
+ int(m < last_state.time)
- int(m < recomb_parent_age);
sum += (model->time_steps[m] * nbranches_m
/ (2.0 * model->popsizes[m]));
}
// probability of coalescing at time j
double pcoal = 1.0;
int nbranches_j = lineages.nbranches[j]
+ int(j < last_state.time)
- int(j < recomb_parent_age);
assert(nbranches_j > 0);
if (k == j) {
// in this case coalesce event must happen between time
// j,j+1/2 (coal_time_step[2j])
// NOTE: if k == ntimes - 2, coalescence is probability 1.0
if (j < model->ntimes - 2) {
pcoal = 1.0 - exp(-model->coal_time_steps[2*j] * nbranches_j
/ (2.0 * model->popsizes[j]));
}
} else {
// otherwise it could happen anytime between j-1/2 and j+1/2
int m = j - 1;
int nbranches_m = lineages.nbranches[m]
+ int(m < last_state.time)
- int(m < recomb_parent_age);
// have to not coalesce in the first half interval before j
sum += (model->coal_time_steps[2*m] * nbranches_m
/ (2.0 * model->popsizes[m]));
// NOTE: if k == ntimes - 2, coalescence is probability 1.0
if (j < model->ntimes - 2) {
pcoal = 1.0 - exp(
-model->coal_time_steps[2*j-1] * nbranches_m
/ (2.0 * model->popsizes[m])
- model->coal_time_steps[2*j] * nbranches_j
/ (2.0 * model->popsizes[j]));
}
}
// probability of recoalescing on a choosen branch
int ncoals_j = lineages.ncoals[j]
- int(j <= recomb_parent_age) - int(j == recomb_parent_age);
pcoal /= ncoals_j;
return precomb * exp(- sum) * pcoal;
}
// Returns the possible recombination events that are compatiable with
// the transition (last_state -> state).
void get_possible_recomb(const LocalTree *tree,
const State last_state, const State state,
bool internal, vector<NodePoint> &candidates)
{
// represents the branch above the new node in the tree.
const int new_node = -1;
int end_time = min(state.time, last_state.time);
if (state.node == last_state.node) {
// y = v, k in [0, min(timei, last_timei)]
// y = node, k in Sr(node)
for (int k=tree->nodes[state.node].age; k<=end_time; k++)
candidates.push_back(NodePoint(state.node, k));
}
if (internal) {
const int subtree_root = tree->nodes[tree->root].child[0];
const int subtree_root_age = tree->nodes[subtree_root].age;
for (int k=subtree_root_age; k<=end_time; k++)
candidates.push_back(NodePoint(subtree_root, k));
} else {
for (int k=0; k<=end_time; k++)
candidates.push_back(NodePoint(new_node, k));
}
}
void sample_recombinations(
const LocalTrees *trees, const ArgModel *model,
ArgHmmMatrixIter *matrix_iter,
int *thread_path, vector<int> &recomb_pos, vector<NodePoint> &recombs,
bool internal)
{
States states;
LineageCounts lineages(model->ntimes);
vector <NodePoint> candidates;
vector <double> probs;
// loop through local blocks
for (matrix_iter->begin(); matrix_iter->more(); matrix_iter->next()) {
// get local block information
ArgHmmMatrices &matrices = matrix_iter->ref_matrices();
LocalTree *tree = matrix_iter->get_tree_spr()->tree;
lineages.count(tree, internal);
matrices.states_model.get_coal_states(tree, states);
int next_recomb = -1;
// don't sample recombination if there is no state space
if (internal && states.size() == 0)
continue;
int start = matrix_iter->get_block_start();
int end = matrix_iter->get_block_end();
if (matrices.transmat_switch || start == trees->start_coord) {
// don't allow new recomb at start if we are switching blocks
start++;
}
// loop through positions in block
for (int i=start; i<end; i++) {
if (thread_path[i] == thread_path[i-1]) {
// no change in state, recombination is optional
if (i > next_recomb) {
// sample the next recomb pos
int last_state = thread_path[i-1];
TransMatrix *m = matrices.transmat;
int a = states[last_state].time;
double self_trans = m->get(
tree, states, last_state, last_state);
double rate = 1.0 - (m->norecombs[a] / self_trans);
// NOTE: the min prevents large floats from overflowing
// when cast to int
next_recomb = int(min(double(end), i + expovariate(rate)));
}
if (i < next_recomb)
continue;
}
// sample recombination
next_recomb = -1;
State state = states[thread_path[i]];
State last_state = states[thread_path[i-1]];
// there must be a recombination
// either because state changed or we choose to recombine
// find candidates
candidates.clear();
get_possible_recomb(tree, last_state, state, internal, candidates);
// compute probability of each candidate
probs.clear();
for (vector<NodePoint>::iterator it=candidates.begin();
it != candidates.end(); ++it) {
probs.push_back(recomb_prob_unnormalized(
model, tree, lineages, last_state, state, *it, internal));
}
// sample recombination
recomb_pos.push_back(i);
recombs.push_back(candidates[sample(&probs[0], probs.size())]);
assert(recombs[recombs.size()-1].time <= min(state.time,
last_state.time));
}
}
}
} // namespace argweaver
<|endoftext|> |
<commit_before>// Time: O(4^n)
// Space: O(n)
class Solution {
public:
vector<string> addOperators(string num, int target) {
vector<string> result;
vector<string> expr;
addOperatorsDFS(num, target, 0, 0, 0, &expr, &result);
return result;
}
void addOperatorsDFS(const string& s, const int& target, const int& pos,
const int& operand1, const int& operand2, vector<string> *expr,
vector<string> *result) {
if (pos == s.length()) {
if (operand1 + operand2 == target) {
result->emplace_back(move(join(*expr)));
}
return;
}
int num = 0;
string num_str;
for (int i = pos; i < s.length(); ++i) {
num_str.push_back(s[i]);
// Check if the value exceeds the max of INT.
if (num_str.length() == to_string(numeric_limits<int>::max()).length() &&
num_str > to_string(numeric_limits<int>::max())) {
break;
}
num = num * 10 + s[i] - '0';
// Case '+':
expr->emplace_back("+"), expr->emplace_back(num_str);
addOperatorsDFS(s, target, i + 1, operand1 + operand2, num, expr, result);
expr->pop_back(), expr->pop_back();
// '-' and '*' could be used only if the expression is not empty.
if (!expr->empty()) {
// Case '-':
expr->emplace_back("-"), expr->emplace_back(num_str);
addOperatorsDFS(s, target, i + 1, operand1 + operand2, -num, expr, result);
expr->pop_back(), expr->pop_back();
// Case '*':
expr->emplace_back("*"), expr->emplace_back(num_str);
addOperatorsDFS(s, target, i + 1, operand1, operand2 * num, expr, result);
expr->pop_back(), expr->pop_back();
}
// Char is '0'.
if (num == 0) {
break;
}
}
}
string join(const vector<string>& expr) {
string e;
for (int i = 0; i < expr.size(); ++i) {
if (i == 0 && expr[i] == "+") { // Skip '+' at the beginning of the string.
continue;
}
e.append(expr[i]);
}
return e;
}
};
<commit_msg>Update expression-add-operators.cpp<commit_after>// Time: O(4^n)
// Space: O(n)
class Solution {
public:
vector<string> addOperators(string num, int target) {
vector<string> result;
vector<string> expr;
addOperatorsDFS(num, target, 0, 0, 0, &expr, &result);
return result;
}
void addOperatorsDFS(const string& s, const int& target, const int& pos,
const int& operand1, const int& operand2, vector<string> *expr,
vector<string> *result) {
if (pos == s.length()) {
if (operand1 + operand2 == target) {
result->emplace_back(move(join(*expr)));
}
return;
}
int num = 0;
string num_str;
for (int i = pos; i < s.length(); ++i) {
num_str.push_back(s[i]);
num = num * 10 + s[i] - '0';
// Avoid overflow and "00...".
if (to_string(num) != num_str) {
break;
}
// Case '+':
expr->emplace_back("+"), expr->emplace_back(num_str);
addOperatorsDFS(s, target, i + 1, operand1 + operand2, num, expr, result);
expr->pop_back(), expr->pop_back();
// '-' and '*' could be used only if the expression is not empty.
if (!expr->empty()) {
// Case '-':
expr->emplace_back("-"), expr->emplace_back(num_str);
addOperatorsDFS(s, target, i + 1, operand1 + operand2, -num, expr, result);
expr->pop_back(), expr->pop_back();
// Case '*':
expr->emplace_back("*"), expr->emplace_back(num_str);
addOperatorsDFS(s, target, i + 1, operand1, operand2 * num, expr, result);
expr->pop_back(), expr->pop_back();
}
}
}
string join(const vector<string>& expr) {
string e;
for (int i = 0; i < expr.size(); ++i) {
if (i == 0 && expr[i] == "+") { // Skip '+' at the beginning of the string.
continue;
}
e.append(expr[i]);
}
return e;
}
};
<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode dummy = ListNode(0);
dummy.next = head;
ListNode *cur = head, *cur_dummy = &dummy;
int len = 0;
while (cur) {
ListNode *next_cur = cur->next;
len = (len + 1) % k;
if (len == 0) {
ListNode *next_dummy = cur_dummy->next;
reverse(&cur_dummy, cur->next);
cur_dummy = next_dummy;
}
cur = next_cur;
}
return dummy.next;
}
void reverse(ListNode **begin, const ListNode *end) {
ListNode *first = (*begin)->next;
ListNode *cur = first->next;
while (cur != end) {
first->next = cur->next;
cur->next = (*begin)->next;
(*begin)->next = cur;
cur = first->next;
}
}
};
<commit_msg>Update reverse-nodes-in-k-group.cpp<commit_after>// Time: O(n)
// Space: O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode dummy{0};
dummy.next = head;
ListNode *cur = head, *cur_dummy = &dummy;
int len = 0;
while (cur) {
ListNode *next_cur = cur->next;
len = (len + 1) % k;
if (len == 0) {
ListNode *next_dummy = cur_dummy->next;
reverse(&cur_dummy, cur->next);
cur_dummy = next_dummy;
}
cur = next_cur;
}
return dummy.next;
}
void reverse(ListNode **begin, const ListNode *end) {
ListNode *first = (*begin)->next;
ListNode *cur = first->next;
while (cur != end) {
first->next = cur->next;
cur->next = (*begin)->next;
(*begin)->next = cur;
cur = first->next;
}
}
};
<|endoftext|> |
<commit_before>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "monkit.h"
#include "dmaManager.h"
#include "MemwriteIndication.h"
#include "MemwriteRequest.h"
#ifdef BOARD_xsim
static int numWords = 0x5000/4;
static int iterCnt = 1;
#elif defined(SIMULATION)
static int numWords = 4096;
static int iterCnt = 1;
#else
static int numWords = 0x1240000/4; // make sure to allocate at least one entry of each size
static int iterCnt = 1; // was 128
#endif
#ifdef PCIE
static int burstLen = 32;
#else
static int burstLen = 16;
#endif
#ifdef NumEngineServers
int numEngineServers = NumEngineServers;
#else
int numEngineServers = 1;
#endif
static sem_t test_sem;
static size_t alloc_sz = numWords*sizeof(unsigned int);
class MemwriteIndication : public MemwriteIndicationWrapper
{
public:
MemwriteIndication(int id, int tile=DEFAULT_TILE) : MemwriteIndicationWrapper(id,tile) {}
void started(uint32_t words) {
fprintf(stderr, "Memwrite::started: words=%x\n", words);
}
void writeDone ( uint32_t srcGen ) {
fprintf(stderr, "Memwrite::writeDone (%08x)\n", srcGen);
sem_post(&test_sem);
}
void reportStateDbg(uint32_t streamWrCnt, uint32_t srcGen) {
fprintf(stderr, "Memwrite::reportStateDbg: streamWrCnt=%08x srcGen=%d\n", streamWrCnt, srcGen);
}
};
int main(int argc, const char **argv)
{
int mismatch = 0;
uint32_t sg = 0;
int max_error = 10;
if (sem_init(&test_sem, 1, 0)) {
fprintf(stderr, "error: failed to init test_sem\n");
exit(1);
}
fprintf(stderr, "testmemwrite: start %s %s\n", __DATE__, __TIME__);
DmaManager *dma = platformInit();
MemwriteRequestProxy *device = new MemwriteRequestProxy(IfcNames_MemwriteRequestS2H);
MemwriteIndication deviceIndication(IfcNames_MemwriteIndicationH2S);
alloc_sz *= numEngineServers;
fprintf(stderr, "main::allocating %lx bytes of memory...\n", (long)alloc_sz);
int dstAlloc = portalAlloc(alloc_sz, 0);
unsigned int *dstBuffer = (unsigned int *)portalMmap(dstAlloc, alloc_sz);
#ifdef FPGA0_CLOCK_FREQ
long req_freq = FPGA0_CLOCK_FREQ, freq = 0;
setClockFrequency(0, req_freq, &freq);
fprintf(stderr, "Requested FCLK[0]=%ld actually %ld\n", req_freq, freq);
#endif
unsigned int ref_dstAlloc = dma->reference(dstAlloc);
for (int i = 0; i < numWords*numEngineServers; i++)
dstBuffer[i] = 0xDEADBEEF;
portalCacheFlush(dstAlloc, dstBuffer, alloc_sz, 1);
fprintf(stderr, "testmemwrite: flush and invalidate complete\n");
fprintf(stderr, "testmemwrite: starting write %08x\n", numWords);
burstLen = 2; // words
while (burstLen <= 2) {
portalTimerStart(0);
device->startWrite(ref_dstAlloc, 0, numWords, burstLen, iterCnt);
sem_wait(&test_sem);
mismatch = 0;
for (int i = 0; i < numWords; i++) {
if (dstBuffer[i] != sg) {
mismatch++;
if (max_error-- > 0)
fprintf(stderr, "testmemwrite: [%d] actual %08x expected %08x\n", i, dstBuffer[i], sg);
}
sg++;
}
platformStatistics();
fprintf(stderr, "testmemwrite: mismatch count %d.\n", mismatch);
burstLen *= 2;
if (mismatch)
exit(mismatch);
// now try with larger burstLen
burstLen *= 2;
}
}
<commit_msg>restore iteration count<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "monkit.h"
#include "dmaManager.h"
#include "MemwriteIndication.h"
#include "MemwriteRequest.h"
#ifdef BOARD_xsim
static int numWords = 0x5000/4;
static int iterCnt = 1;
#elif defined(SIMULATION)
static int numWords = 4096;
static int iterCnt = 8;
#else
static int numWords = 0x1240000/4; // make sure to allocate at least one entry of each size
static int iterCnt = 128;
#endif
#ifdef PCIE
static int burstLen = 32;
#else
static int burstLen = 16;
#endif
#ifdef NumEngineServers
int numEngineServers = NumEngineServers;
#else
int numEngineServers = 1;
#endif
static sem_t test_sem;
static size_t alloc_sz = numWords*sizeof(unsigned int);
class MemwriteIndication : public MemwriteIndicationWrapper
{
public:
MemwriteIndication(int id, int tile=DEFAULT_TILE) : MemwriteIndicationWrapper(id,tile) {}
void started(uint32_t words) {
fprintf(stderr, "Memwrite::started: words=%x\n", words);
}
void writeDone ( uint32_t srcGen ) {
fprintf(stderr, "Memwrite::writeDone (%08x)\n", srcGen);
sem_post(&test_sem);
}
void reportStateDbg(uint32_t streamWrCnt, uint32_t srcGen) {
fprintf(stderr, "Memwrite::reportStateDbg: streamWrCnt=%08x srcGen=%d\n", streamWrCnt, srcGen);
}
};
int main(int argc, const char **argv)
{
int mismatch = 0;
uint32_t sg = 0;
int max_error = 10;
if (sem_init(&test_sem, 1, 0)) {
fprintf(stderr, "error: failed to init test_sem\n");
exit(1);
}
fprintf(stderr, "testmemwrite: start %s %s\n", __DATE__, __TIME__);
DmaManager *dma = platformInit();
MemwriteRequestProxy *device = new MemwriteRequestProxy(IfcNames_MemwriteRequestS2H);
MemwriteIndication deviceIndication(IfcNames_MemwriteIndicationH2S);
alloc_sz *= numEngineServers;
fprintf(stderr, "main::allocating %lx bytes of memory...\n", (long)alloc_sz);
int dstAlloc = portalAlloc(alloc_sz, 0);
unsigned int *dstBuffer = (unsigned int *)portalMmap(dstAlloc, alloc_sz);
#ifdef FPGA0_CLOCK_FREQ
long req_freq = FPGA0_CLOCK_FREQ, freq = 0;
setClockFrequency(0, req_freq, &freq);
fprintf(stderr, "Requested FCLK[0]=%ld actually %ld\n", req_freq, freq);
#endif
unsigned int ref_dstAlloc = dma->reference(dstAlloc);
for (int i = 0; i < numWords*numEngineServers; i++)
dstBuffer[i] = 0xDEADBEEF;
portalCacheFlush(dstAlloc, dstBuffer, alloc_sz, 1);
fprintf(stderr, "testmemwrite: flush and invalidate complete\n");
fprintf(stderr, "testmemwrite: starting write %08x\n", numWords);
burstLen = 2; // words
while (burstLen <= 2) {
portalTimerStart(0);
device->startWrite(ref_dstAlloc, 0, numWords, burstLen, iterCnt);
sem_wait(&test_sem);
mismatch = 0;
for (int i = 0; i < numWords; i++) {
if (dstBuffer[i] != sg) {
mismatch++;
if (max_error-- > 0)
fprintf(stderr, "testmemwrite: [%d] actual %08x expected %08x\n", i, dstBuffer[i], sg);
}
sg++;
}
platformStatistics();
fprintf(stderr, "testmemwrite: mismatch count %d.\n", mismatch);
burstLen *= 2;
if (mismatch)
exit(mismatch);
// now try with larger burstLen
burstLen *= 2;
}
}
<|endoftext|> |
<commit_before>/**
*
* Emerald (kbi/elude @2015)
*
*/
#include "shared.h"
#include "ogl/ogl_context.h"
#include "ogl/ogl_query.h"
#include "ogl/ogl_rendering_handler.h"
#include "system/system_log.h"
/** TODO */
typedef struct _ogl_query_item
{
GLuint gl_id;
bool has_started;
_ogl_query_item()
{
gl_id = 0;
has_started = false;
}
~_ogl_query_item()
{
ASSERT_DEBUG_SYNC(gl_id == 0,
"Sanity check failed.");
}
} _ogl_query_item;
typedef struct _ogl_query
{
/* DO NOT retain/release */
ogl_context context;
unsigned int ring_buffer_size;
_ogl_query_item* qo_items;
GLenum target_gl;
/* Points at the next QO that can be peeked OR result of whose can be retrieved.
* A value of -1 indicates no ogl_query_begin() call was made for this query object.
*
* index_peek must always be < ring_buffer_size.
* index_peek must always be != index_next */
int index_peek;
/* Points at the QO which has been used for the last ogl_query_begin() call.
*
* It is an error if index_next == index_peek, and indicates the ring buffer has run
* out of space. This can only occur if the query object is used for many queries in a row
* without checking the queries' results in-between.
*
* index_next must always be < ring_buffer_size.
*/
int index_current;
/* Cached entry-points */
PFNGLBEGINQUERYPROC pGLBeginQuery;
PFNGLDELETEQUERIESPROC pGLDeleteQueries;
PFNGLENDQUERYPROC pGLEndQuery;
PFNGLGENQUERIESPROC pGLGenQueries;
PFNGLGETQUERYOBJECTUIVPROC pGLGetQueryObjectuiv;
PFNGLGETQUERYOBJECTUI64VPROC pGLGetQueryObjectui64v;
_ogl_query(__in __notnull ogl_context in_context,
__in unsigned int in_ring_buffer_size,
__in GLenum in_target_gl);
~_ogl_query();
} _ogl_query;
/* Forward declarations */
PRIVATE void _ogl_query_deinit_renderer_callback(ogl_context context,
void* user_arg);
PRIVATE void _ogl_query_init_renderer_callback (ogl_context context,
void* user_arg);
/** TODO */
_ogl_query::_ogl_query(__in __notnull ogl_context in_context,
__in unsigned int in_ring_buffer_size,
__in GLenum in_target_gl)
{
ogl_context_type context_type = OGL_CONTEXT_TYPE_UNDEFINED;
ASSERT_DEBUG_SYNC(in_ring_buffer_size > 0,
"Ring buffer size is invalid");
context = in_context;
index_current = -1;
index_peek = -1;
qo_items = new (std::nothrow) _ogl_query_item[in_ring_buffer_size];
ring_buffer_size = in_ring_buffer_size;
target_gl = in_target_gl;
ASSERT_DEBUG_SYNC(qo_items != NULL,
"Out of memory");
/* Cache ES/GL entry-points */
ogl_context_get_property(context,
OGL_CONTEXT_PROPERTY_TYPE,
&context_type);
if (context_type == OGL_CONTEXT_TYPE_GL)
{
const ogl_context_gl_entrypoints* entry_points = NULL;
ogl_context_get_property(context,
OGL_CONTEXT_PROPERTY_ENTRYPOINTS_GL,
&entry_points);
pGLBeginQuery = entry_points->pGLBeginQuery;
pGLDeleteQueries = entry_points->pGLDeleteQueries;
pGLEndQuery = entry_points->pGLEndQuery;
pGLGenQueries = entry_points->pGLGenQueries;
pGLGetQueryObjectuiv = NULL; /* not needed, we're using the 64-bit version instead */
pGLGetQueryObjectui64v = entry_points->pGLGetQueryObjectui64v;
} /* if (context_type == OGL_CONTEXT_TYPE_GL) */
else
{
ASSERT_DEBUG_SYNC(context_type == OGL_CONTEXT_TYPE_ES,
"Unrecognized rendering context type");
const ogl_context_es_entrypoints* entry_points = NULL;
ogl_context_get_property(context,
OGL_CONTEXT_PROPERTY_ENTRYPOINTS_ES,
&entry_points);
pGLBeginQuery = entry_points->pGLBeginQuery;
pGLDeleteQueries = entry_points->pGLDeleteQueries;
pGLEndQuery = entry_points->pGLEndQuery;
pGLGenQueries = entry_points->pGLGenQueries;
pGLGetQueryObjectuiv = entry_points->pGLGetQueryObjectuiv;
pGLGetQueryObjectui64v = NULL;
}
/* Initialize the object */
ogl_context_request_callback_from_context_thread(context,
_ogl_query_init_renderer_callback,
this);
}
/** TODO */
_ogl_query::~_ogl_query()
{
ogl_context_request_callback_from_context_thread(context,
_ogl_query_deinit_renderer_callback,
this);
if (qo_items != NULL)
{
delete [] qo_items;
qo_items = NULL;
} /* if (qo_ids != NULL) */
}
/** TODO */
PRIVATE void _ogl_query_deinit_renderer_callback(ogl_context context,
void* user_arg)
{
_ogl_query* query_ptr = (_ogl_query*) user_arg;
for (unsigned int n_item = 0;
n_item < query_ptr->ring_buffer_size;
++n_item)
{
query_ptr->pGLDeleteQueries(1, /* n */
&query_ptr->qo_items[n_item].gl_id);
query_ptr->qo_items[n_item].gl_id = 0;
} /* for (all items) */
}
/** TODO */
PRIVATE void _ogl_query_init_renderer_callback(__in __notnull ogl_context context,
__in __notnull void* user_arg)
{
_ogl_query* query_ptr = (_ogl_query*) user_arg;
for (unsigned int n_item = 0;
n_item < query_ptr->ring_buffer_size;
++n_item)
{
query_ptr->pGLGenQueries(1, /* n */
&query_ptr->qo_items[n_item].gl_id);
} /* for (all items) */
}
/** Please see header for spec */
PUBLIC RENDERING_CONTEXT_CALL void ogl_query_begin(__in __notnull ogl_query query)
{
_ogl_query* query_ptr = (_ogl_query*) query;
/* Increment the 'current QO' index */
query_ptr->index_current = (query_ptr->index_current + 1) % query_ptr->ring_buffer_size;
ASSERT_DEBUG_SYNC(query_ptr->index_current != query_ptr->index_peek,
"Sanity check failed.");
if (query_ptr->index_current != query_ptr->index_peek)
{
/* Kick off the query */
query_ptr->pGLBeginQuery(query_ptr->target_gl,
query_ptr->qo_items[query_ptr->index_current].gl_id);
query_ptr->qo_items[query_ptr->index_current].has_started = true;
}
else
{
LOG_ERROR("ogl_query_begin(): Ignored, peek index == next index! Fetch query object results first.");
}
}
/** Please see header for spec */
PUBLIC ogl_query ogl_query_create(__in __notnull ogl_context context,
__in unsigned int ring_buffer_size,
__in GLenum gl_query_target)
{
_ogl_query* new_instance = new (std::nothrow) _ogl_query(context,
ring_buffer_size,
gl_query_target);
ASSERT_ALWAYS_SYNC(new_instance != NULL,
"Out of memory");
return (ogl_query) new_instance;
}
/** Please see header for spec */
PUBLIC RENDERING_CONTEXT_CALL void ogl_query_end(__in __notnull ogl_query query)
{
_ogl_query* query_ptr = (_ogl_query*) query;
const unsigned int qo_id = query_ptr->index_current;
if (query_ptr->qo_items[qo_id].has_started)
{
/* Stop the query */
query_ptr->pGLEndQuery(query_ptr->target_gl);
query_ptr->qo_items[qo_id].has_started = false;
}
}
/** Please see header for spec */
PUBLIC RENDERING_CONTEXT_CALL bool ogl_query_peek_result(__in __notnull ogl_query query,
__out_opt GLuint64* out_result)
{
_ogl_query* query_ptr = (_ogl_query*) query;
bool result = false;
/* Sanity checks */
const unsigned int index_peek = (query_ptr->index_peek + 1) % query_ptr->ring_buffer_size;
ASSERT_DEBUG_SYNC(!query_ptr->qo_items[index_peek].has_started,
"The QO that is being peeked has not been ended yet.");
/* Do we have any spare QO to use for the next begin operation? */
bool should_force = ( (query_ptr->index_current + 1) % query_ptr->ring_buffer_size == query_ptr->index_peek);
/* ES offers glGetQueryObjectuiv(), whereas under OpenGL we have glGetQueryObjectui64v() */
if (query_ptr->pGLGetQueryObjectui64v != NULL)
{
/* GL code-path */
GLuint64 temp = -1;
query_ptr->pGLGetQueryObjectui64v(query_ptr->qo_items[index_peek].gl_id,
GL_QUERY_RESULT_NO_WAIT,
&temp);
if (temp == -1 && should_force)
{
/* Got to stall the pipeline .. */
LOG_ERROR("Performance warning: ogl_query_peek_result() about to force an implicit finish.");
query_ptr->pGLGetQueryObjectui64v(query_ptr->qo_items[index_peek].gl_id,
GL_QUERY_RESULT,
&temp);
}
if (temp != -1)
{
/* The result has been returned - yay! */
*out_result = temp;
result = true;
/* Update the index */
query_ptr->index_peek = index_peek;
}
} /* if (query_ptr->pGLGetQueryObjectui64v != NULL) */
else
{
/* ES code-path */
GLuint is_result_available = GL_FALSE;
query_ptr->pGLGetQueryObjectuiv(query_ptr->qo_items[index_peek].gl_id,
GL_QUERY_RESULT_AVAILABLE,
&is_result_available);
if (is_result_available == GL_TRUE ||
should_force)
{
GLuint temp = -1;
query_ptr->pGLGetQueryObjectuiv(query_ptr->qo_items[index_peek].gl_id,
GL_QUERY_RESULT,
&temp);
*out_result = (GLuint64) temp;
result = true;
/* Update the index */
query_ptr->index_peek = index_peek;
} /* if (is_result_available || should_force) */
}
return result;
}
/** Please see header for spec */
PUBLIC void ogl_query_release(__in __notnull __post_invalid ogl_query query)
{
_ogl_query* query_ptr = (_ogl_query*) query;
/* Done */
delete query_ptr;
query_ptr = NULL;
}
<commit_msg>Emerald: IHV-specific fix to avoid thrashing the logging console with ogl_query ring buffer overflow warnings<commit_after>/**
*
* Emerald (kbi/elude @2015)
*
*/
#include "shared.h"
#include "ogl/ogl_context.h"
#include "ogl/ogl_query.h"
#include "ogl/ogl_rendering_handler.h"
#include "system/system_log.h"
/** TODO */
typedef struct _ogl_query_item
{
GLuint gl_id;
bool has_started;
_ogl_query_item()
{
gl_id = 0;
has_started = false;
}
~_ogl_query_item()
{
ASSERT_DEBUG_SYNC(gl_id == 0,
"Sanity check failed.");
}
} _ogl_query_item;
typedef struct _ogl_query
{
/* DO NOT retain/release */
ogl_context context;
unsigned int ring_buffer_size;
_ogl_query_item* qo_items;
GLenum target_gl;
/* Points at the next QO that can be peeked OR result of whose can be retrieved.
* A value of -1 indicates no ogl_query_begin() call was made for this query object.
*
* index_peek must always be < ring_buffer_size.
* index_peek must always be != index_next */
int index_peek;
/* Points at the QO which has been used for the last ogl_query_begin() call.
*
* It is an error if index_next == index_peek, and indicates the ring buffer has run
* out of space. This can only occur if the query object is used for many queries in a row
* without checking the queries' results in-between.
*
* index_next must always be < ring_buffer_size.
*/
int index_current;
/* Cached entry-points */
PFNGLBEGINQUERYPROC pGLBeginQuery;
PFNGLDELETEQUERIESPROC pGLDeleteQueries;
PFNGLENDQUERYPROC pGLEndQuery;
PFNGLGENQUERIESPROC pGLGenQueries;
PFNGLGETQUERYOBJECTUIVPROC pGLGetQueryObjectuiv;
PFNGLGETQUERYOBJECTUI64VPROC pGLGetQueryObjectui64v;
_ogl_query(__in __notnull ogl_context in_context,
__in unsigned int in_ring_buffer_size,
__in GLenum in_target_gl);
~_ogl_query();
} _ogl_query;
/* Forward declarations */
PRIVATE void _ogl_query_deinit_renderer_callback(ogl_context context,
void* user_arg);
PRIVATE void _ogl_query_init_renderer_callback (ogl_context context,
void* user_arg);
/** TODO */
_ogl_query::_ogl_query(__in __notnull ogl_context in_context,
__in unsigned int in_ring_buffer_size,
__in GLenum in_target_gl)
{
ogl_context_type context_type = OGL_CONTEXT_TYPE_UNDEFINED;
ASSERT_DEBUG_SYNC(in_ring_buffer_size > 0,
"Ring buffer size is invalid");
context = in_context;
index_current = -1;
index_peek = -1;
qo_items = new (std::nothrow) _ogl_query_item[in_ring_buffer_size];
ring_buffer_size = in_ring_buffer_size;
target_gl = in_target_gl;
ASSERT_DEBUG_SYNC(qo_items != NULL,
"Out of memory");
/* Cache ES/GL entry-points */
ogl_context_get_property(context,
OGL_CONTEXT_PROPERTY_TYPE,
&context_type);
if (context_type == OGL_CONTEXT_TYPE_GL)
{
const ogl_context_gl_entrypoints* entry_points = NULL;
ogl_context_get_property(context,
OGL_CONTEXT_PROPERTY_ENTRYPOINTS_GL,
&entry_points);
pGLBeginQuery = entry_points->pGLBeginQuery;
pGLDeleteQueries = entry_points->pGLDeleteQueries;
pGLEndQuery = entry_points->pGLEndQuery;
pGLGenQueries = entry_points->pGLGenQueries;
pGLGetQueryObjectuiv = NULL; /* not needed, we're using the 64-bit version instead */
pGLGetQueryObjectui64v = entry_points->pGLGetQueryObjectui64v;
} /* if (context_type == OGL_CONTEXT_TYPE_GL) */
else
{
ASSERT_DEBUG_SYNC(context_type == OGL_CONTEXT_TYPE_ES,
"Unrecognized rendering context type");
const ogl_context_es_entrypoints* entry_points = NULL;
ogl_context_get_property(context,
OGL_CONTEXT_PROPERTY_ENTRYPOINTS_ES,
&entry_points);
pGLBeginQuery = entry_points->pGLBeginQuery;
pGLDeleteQueries = entry_points->pGLDeleteQueries;
pGLEndQuery = entry_points->pGLEndQuery;
pGLGenQueries = entry_points->pGLGenQueries;
pGLGetQueryObjectuiv = entry_points->pGLGetQueryObjectuiv;
pGLGetQueryObjectui64v = NULL;
}
/* Initialize the object */
ogl_context_request_callback_from_context_thread(context,
_ogl_query_init_renderer_callback,
this);
}
/** TODO */
_ogl_query::~_ogl_query()
{
ogl_context_request_callback_from_context_thread(context,
_ogl_query_deinit_renderer_callback,
this);
if (qo_items != NULL)
{
delete [] qo_items;
qo_items = NULL;
} /* if (qo_ids != NULL) */
}
/** TODO */
PRIVATE void _ogl_query_deinit_renderer_callback(ogl_context context,
void* user_arg)
{
_ogl_query* query_ptr = (_ogl_query*) user_arg;
for (unsigned int n_item = 0;
n_item < query_ptr->ring_buffer_size;
++n_item)
{
query_ptr->pGLDeleteQueries(1, /* n */
&query_ptr->qo_items[n_item].gl_id);
query_ptr->qo_items[n_item].gl_id = 0;
} /* for (all items) */
}
/** TODO */
PRIVATE void _ogl_query_init_renderer_callback(__in __notnull ogl_context context,
__in __notnull void* user_arg)
{
_ogl_query* query_ptr = (_ogl_query*) user_arg;
for (unsigned int n_item = 0;
n_item < query_ptr->ring_buffer_size;
++n_item)
{
query_ptr->pGLGenQueries(1, /* n */
&query_ptr->qo_items[n_item].gl_id);
} /* for (all items) */
}
/** Please see header for spec */
PUBLIC RENDERING_CONTEXT_CALL void ogl_query_begin(__in __notnull ogl_query query)
{
_ogl_query* query_ptr = (_ogl_query*) query;
/* Increment the 'current QO' index */
query_ptr->index_current = (query_ptr->index_current + 1) % query_ptr->ring_buffer_size;
ASSERT_DEBUG_SYNC(query_ptr->index_current != query_ptr->index_peek,
"Sanity check failed.");
if (query_ptr->index_current != query_ptr->index_peek)
{
/* Kick off the query */
query_ptr->pGLBeginQuery(query_ptr->target_gl,
query_ptr->qo_items[query_ptr->index_current].gl_id);
query_ptr->qo_items[query_ptr->index_current].has_started = true;
}
else
{
LOG_ERROR("ogl_query_begin(): Ignored, peek index == next index! Fetch query object results first.");
}
}
/** Please see header for spec */
PUBLIC ogl_query ogl_query_create(__in __notnull ogl_context context,
__in unsigned int ring_buffer_size,
__in GLenum gl_query_target)
{
_ogl_query* new_instance = new (std::nothrow) _ogl_query(context,
ring_buffer_size,
gl_query_target);
ASSERT_ALWAYS_SYNC(new_instance != NULL,
"Out of memory");
return (ogl_query) new_instance;
}
/** Please see header for spec */
PUBLIC RENDERING_CONTEXT_CALL void ogl_query_end(__in __notnull ogl_query query)
{
_ogl_query* query_ptr = (_ogl_query*) query;
const unsigned int qo_id = query_ptr->index_current;
if (query_ptr->qo_items[qo_id].has_started)
{
/* Stop the query */
query_ptr->pGLEndQuery(query_ptr->target_gl);
query_ptr->qo_items[qo_id].has_started = false;
}
}
/** Please see header for spec */
PUBLIC RENDERING_CONTEXT_CALL bool ogl_query_peek_result(__in __notnull ogl_query query,
__out_opt GLuint64* out_result)
{
_ogl_query* query_ptr = (_ogl_query*) query;
bool result = false;
/* Sanity checks */
const unsigned int index_peek = (query_ptr->index_peek + 1) % query_ptr->ring_buffer_size;
ASSERT_DEBUG_SYNC(!query_ptr->qo_items[index_peek].has_started,
"The QO that is being peeked has not been ended yet.");
/* Do we have any spare QO to use for the next begin operation? */
bool should_force = ( (query_ptr->index_current + 1) % query_ptr->ring_buffer_size == query_ptr->index_peek);
/* ES offers glGetQueryObjectuiv(), whereas under OpenGL we have glGetQueryObjectui64v() */
if (query_ptr->pGLGetQueryObjectui64v != NULL)
{
/* GL code-path */
GLuint64 temp = -1;
query_ptr->pGLGetQueryObjectui64v(query_ptr->qo_items[index_peek].gl_id,
GL_QUERY_RESULT_NO_WAIT,
&temp);
if (temp == -1 && should_force)
{
/* Got to stall the pipeline .. */
static system_timeline_time last_warning_time = 0;
static system_timeline_time one_sec_time = system_time_get_timeline_time_for_s(1);
static system_timeline_time time_now = system_time_now();
if (time_now - last_warning_time > one_sec_time)
{
LOG_ERROR("Performance warning: ogl_query_peek_result() about to force an implicit finish.");
last_warning_time = time_now;
}
query_ptr->pGLGetQueryObjectui64v(query_ptr->qo_items[index_peek].gl_id,
GL_QUERY_RESULT,
&temp);
}
if (temp != -1)
{
/* The result has been returned - yay! */
*out_result = temp;
result = true;
/* Update the index */
query_ptr->index_peek = index_peek;
}
} /* if (query_ptr->pGLGetQueryObjectui64v != NULL) */
else
{
/* ES code-path */
GLuint is_result_available = GL_FALSE;
query_ptr->pGLGetQueryObjectuiv(query_ptr->qo_items[index_peek].gl_id,
GL_QUERY_RESULT_AVAILABLE,
&is_result_available);
if (is_result_available == GL_TRUE ||
should_force)
{
GLuint temp = -1;
query_ptr->pGLGetQueryObjectuiv(query_ptr->qo_items[index_peek].gl_id,
GL_QUERY_RESULT,
&temp);
*out_result = (GLuint64) temp;
result = true;
/* Update the index */
query_ptr->index_peek = index_peek;
} /* if (is_result_available || should_force) */
}
return result;
}
/** Please see header for spec */
PUBLIC void ogl_query_release(__in __notnull __post_invalid ogl_query query)
{
_ogl_query* query_ptr = (_ogl_query*) query;
/* Done */
delete query_ptr;
query_ptr = NULL;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
*/
#include "arch/utility.hh"
#include "arch/faults.hh"
#include "base/cprintf.hh"
#include "base/inifile.hh"
#include "base/loader/symtab.hh"
#include "base/misc.hh"
#include "base/pollevent.hh"
#include "base/range.hh"
#include "base/stats/events.hh"
#include "base/trace.hh"
#include "cpu/base.hh"
#include "cpu/exetrace.hh"
#include "cpu/profile.hh"
#include "cpu/simple/base.hh"
#include "cpu/simple_thread.hh"
#include "cpu/smt.hh"
#include "cpu/static_inst.hh"
#include "cpu/thread_context.hh"
#include "mem/packet.hh"
#include "sim/builder.hh"
#include "sim/byteswap.hh"
#include "sim/debug.hh"
#include "sim/host.hh"
#include "sim/sim_events.hh"
#include "sim/sim_object.hh"
#include "sim/stats.hh"
#include "sim/system.hh"
#if FULL_SYSTEM
#include "arch/kernel_stats.hh"
#include "arch/stacktrace.hh"
#include "arch/tlb.hh"
#include "arch/vtophys.hh"
#include "base/remote_gdb.hh"
#else // !FULL_SYSTEM
#include "mem/mem_object.hh"
#endif // FULL_SYSTEM
using namespace std;
using namespace TheISA;
BaseSimpleCPU::BaseSimpleCPU(Params *p)
: BaseCPU(p), thread(NULL)
{
#if FULL_SYSTEM
thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb);
#else
thread = new SimpleThread(this, /* thread_num */ 0, p->process,
/* asid */ 0);
#endif // !FULL_SYSTEM
thread->setStatus(ThreadContext::Suspended);
tc = thread->getTC();
numInst = 0;
startNumInst = 0;
numLoad = 0;
startNumLoad = 0;
lastIcacheStall = 0;
lastDcacheStall = 0;
threadContexts.push_back(tc);
}
BaseSimpleCPU::~BaseSimpleCPU()
{
}
void
BaseSimpleCPU::deallocateContext(int thread_num)
{
// for now, these are equivalent
suspendContext(thread_num);
}
void
BaseSimpleCPU::haltContext(int thread_num)
{
// for now, these are equivalent
suspendContext(thread_num);
}
void
BaseSimpleCPU::regStats()
{
using namespace Stats;
BaseCPU::regStats();
numInsts
.name(name() + ".num_insts")
.desc("Number of instructions executed")
;
numMemRefs
.name(name() + ".num_refs")
.desc("Number of memory references")
;
notIdleFraction
.name(name() + ".not_idle_fraction")
.desc("Percentage of non-idle cycles")
;
idleFraction
.name(name() + ".idle_fraction")
.desc("Percentage of idle cycles")
;
icacheStallCycles
.name(name() + ".icache_stall_cycles")
.desc("ICache total stall cycles")
.prereq(icacheStallCycles)
;
dcacheStallCycles
.name(name() + ".dcache_stall_cycles")
.desc("DCache total stall cycles")
.prereq(dcacheStallCycles)
;
icacheRetryCycles
.name(name() + ".icache_retry_cycles")
.desc("ICache total retry cycles")
.prereq(icacheRetryCycles)
;
dcacheRetryCycles
.name(name() + ".dcache_retry_cycles")
.desc("DCache total retry cycles")
.prereq(dcacheRetryCycles)
;
idleFraction = constant(1.0) - notIdleFraction;
}
void
BaseSimpleCPU::resetStats()
{
// startNumInst = numInst;
// notIdleFraction = (_status != Idle);
}
void
BaseSimpleCPU::serialize(ostream &os)
{
BaseCPU::serialize(os);
// SERIALIZE_SCALAR(inst);
nameOut(os, csprintf("%s.xc.0", name()));
thread->serialize(os);
}
void
BaseSimpleCPU::unserialize(Checkpoint *cp, const string §ion)
{
BaseCPU::unserialize(cp, section);
// UNSERIALIZE_SCALAR(inst);
thread->unserialize(cp, csprintf("%s.xc.0", section));
}
void
change_thread_state(int thread_number, int activate, int priority)
{
}
Fault
BaseSimpleCPU::copySrcTranslate(Addr src)
{
#if 0
static bool no_warn = true;
int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;
// Only support block sizes of 64 atm.
assert(blk_size == 64);
int offset = src & (blk_size - 1);
// Make sure block doesn't span page
if (no_warn &&
(src & PageMask) != ((src + blk_size) & PageMask) &&
(src >> 40) != 0xfffffc) {
warn("Copied block source spans pages %x.", src);
no_warn = false;
}
memReq->reset(src & ~(blk_size - 1), blk_size);
// translate to physical address
Fault fault = thread->translateDataReadReq(req);
if (fault == NoFault) {
thread->copySrcAddr = src;
thread->copySrcPhysAddr = memReq->paddr + offset;
} else {
assert(!fault->isAlignmentFault());
thread->copySrcAddr = 0;
thread->copySrcPhysAddr = 0;
}
return fault;
#else
return NoFault;
#endif
}
Fault
BaseSimpleCPU::copy(Addr dest)
{
#if 0
static bool no_warn = true;
int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;
// Only support block sizes of 64 atm.
assert(blk_size == 64);
uint8_t data[blk_size];
//assert(thread->copySrcAddr);
int offset = dest & (blk_size - 1);
// Make sure block doesn't span page
if (no_warn &&
(dest & PageMask) != ((dest + blk_size) & PageMask) &&
(dest >> 40) != 0xfffffc) {
no_warn = false;
warn("Copied block destination spans pages %x. ", dest);
}
memReq->reset(dest & ~(blk_size -1), blk_size);
// translate to physical address
Fault fault = thread->translateDataWriteReq(req);
if (fault == NoFault) {
Addr dest_addr = memReq->paddr + offset;
// Need to read straight from memory since we have more than 8 bytes.
memReq->paddr = thread->copySrcPhysAddr;
thread->mem->read(memReq, data);
memReq->paddr = dest_addr;
thread->mem->write(memReq, data);
if (dcacheInterface) {
memReq->cmd = Copy;
memReq->completionEvent = NULL;
memReq->paddr = thread->copySrcPhysAddr;
memReq->dest = dest_addr;
memReq->size = 64;
memReq->time = curTick;
memReq->flags &= ~INST_READ;
dcacheInterface->access(memReq);
}
}
else
assert(!fault->isAlignmentFault());
return fault;
#else
panic("copy not implemented");
return NoFault;
#endif
}
#if FULL_SYSTEM
Addr
BaseSimpleCPU::dbg_vtophys(Addr addr)
{
return vtophys(tc, addr);
}
#endif // FULL_SYSTEM
#if FULL_SYSTEM
void
BaseSimpleCPU::post_interrupt(int int_num, int index)
{
BaseCPU::post_interrupt(int_num, index);
if (thread->status() == ThreadContext::Suspended) {
DPRINTF(IPI,"Suspended Processor awoke\n");
thread->activate();
}
}
#endif // FULL_SYSTEM
void
BaseSimpleCPU::checkForInterrupts()
{
#if FULL_SYSTEM
if (checkInterrupts && check_interrupts(tc)) {
Fault interrupt = interrupts.getInterrupt(tc);
if (interrupt != NoFault) {
interrupts.updateIntrInfo(tc);
checkInterrupts = false;
interrupt->invoke(tc);
}
}
#endif
}
Fault
BaseSimpleCPU::setupFetchRequest(Request *req)
{
// set up memory request for instruction fetch
#if ISA_HAS_DELAY_SLOT
DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p NNPC:%08p\n",thread->readPC(),
thread->readNextPC(),thread->readNextNPC());
#else
DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p",thread->readPC(),
thread->readNextPC());
#endif
req->setVirt(0, thread->readPC() & ~3, sizeof(MachInst),
(FULL_SYSTEM && (thread->readPC() & 1)) ? PHYSICAL : 0,
thread->readPC());
Fault fault = thread->translateInstReq(req);
return fault;
}
void
BaseSimpleCPU::preExecute()
{
// maintain $r0 semantics
thread->setIntReg(ZeroReg, 0);
#if THE_ISA == ALPHA_ISA
thread->setFloatReg(ZeroReg, 0.0);
#endif // ALPHA_ISA
// keep an instruction count
numInst++;
numInsts++;
thread->funcExeInst++;
// check for instruction-count-based events
comInstEventQueue[0]->serviceEvents(numInst);
// decode the instruction
inst = gtoh(inst);
//If we're not in the middle of a macro instruction
if (!curMacroStaticInst) {
#if THE_ISA == ALPHA_ISA
StaticInstPtr instPtr = StaticInst::decode(makeExtMI(inst, thread->readPC()));
#elif THE_ISA == SPARC_ISA
StaticInstPtr instPtr = StaticInst::decode(makeExtMI(inst, thread->getTC()));
#elif THE_ISA == MIPS_ISA
//Mips doesn't do anything in it's MakeExtMI function right now,
//so it won't be called.
StaticInstPtr instPtr = StaticInst::decode(inst);
#endif
if (instPtr->isMacroOp()) {
curMacroStaticInst = instPtr;
curStaticInst = curMacroStaticInst->
fetchMicroOp(thread->readMicroPC());
} else {
curStaticInst = instPtr;
}
} else {
//Read the next micro op from the macro op
curStaticInst = curMacroStaticInst->
fetchMicroOp(thread->readMicroPC());
}
traceData = Trace::getInstRecord(curTick, tc, curStaticInst,
thread->readPC());
DPRINTF(Decode,"Decode: Decoded %s instruction (opcode: 0x%x): 0x%x\n",
curStaticInst->getName(), curStaticInst->getOpcode(),
curStaticInst->machInst);
#if FULL_SYSTEM
thread->setInst(inst);
#endif // FULL_SYSTEM
}
void
BaseSimpleCPU::postExecute()
{
#if FULL_SYSTEM
if (thread->profile) {
bool usermode = TheISA::inUserMode(tc);
thread->profilePC = usermode ? 1 : thread->readPC();
ProfileNode *node = thread->profile->consume(tc, inst);
if (node)
thread->profileNode = node;
}
#endif
if (curStaticInst->isMemRef()) {
numMemRefs++;
}
if (curStaticInst->isLoad()) {
++numLoad;
comLoadEventQueue[0]->serviceEvents(numLoad);
}
traceFunctions(thread->readPC());
if (traceData) {
traceData->finalize();
}
}
void
BaseSimpleCPU::advancePC(Fault fault)
{
if (fault != NoFault) {
fault->invoke(tc);
} else {
//If we're at the last micro op for this instruction
if (curStaticInst->isLastMicroOp()) {
//We should be working with a macro op
assert(curMacroStaticInst);
//Close out this macro op, and clean up the
//microcode state
curMacroStaticInst = StaticInst::nullStaticInstPtr;
thread->setMicroPC(0);
thread->setNextMicroPC(1);
}
//If we're still in a macro op
if (curMacroStaticInst) {
//Advance the micro pc
thread->setMicroPC(thread->readNextMicroPC());
//Advance the "next" micro pc. Note that there are no delay
//slots, and micro ops are "word" addressed.
thread->setNextMicroPC(thread->readNextMicroPC() + 1);
} else {
// go to the next instruction
thread->setPC(thread->readNextPC());
#if ISA_HAS_DELAY_SLOT
thread->setNextPC(thread->readNextNPC());
thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));
assert(thread->readNextPC() != thread->readNextNPC());
#else
thread->setNextPC(thread->readNextPC() + sizeof(MachInst));
#endif
}
}
#if FULL_SYSTEM
Addr oldpc;
do {
oldpc = thread->readPC();
system->pcEventQueue.service(tc);
} while (oldpc != thread->readPC());
#endif
}
<commit_msg>In the case that we generate a fault (e.g. a tlb miss) on a microcoded instruction set curMacroStaticInst to null This way we'll jump immediately to the handler<commit_after>/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
*/
#include "arch/utility.hh"
#include "arch/faults.hh"
#include "base/cprintf.hh"
#include "base/inifile.hh"
#include "base/loader/symtab.hh"
#include "base/misc.hh"
#include "base/pollevent.hh"
#include "base/range.hh"
#include "base/stats/events.hh"
#include "base/trace.hh"
#include "cpu/base.hh"
#include "cpu/exetrace.hh"
#include "cpu/profile.hh"
#include "cpu/simple/base.hh"
#include "cpu/simple_thread.hh"
#include "cpu/smt.hh"
#include "cpu/static_inst.hh"
#include "cpu/thread_context.hh"
#include "mem/packet.hh"
#include "sim/builder.hh"
#include "sim/byteswap.hh"
#include "sim/debug.hh"
#include "sim/host.hh"
#include "sim/sim_events.hh"
#include "sim/sim_object.hh"
#include "sim/stats.hh"
#include "sim/system.hh"
#if FULL_SYSTEM
#include "arch/kernel_stats.hh"
#include "arch/stacktrace.hh"
#include "arch/tlb.hh"
#include "arch/vtophys.hh"
#include "base/remote_gdb.hh"
#else // !FULL_SYSTEM
#include "mem/mem_object.hh"
#endif // FULL_SYSTEM
using namespace std;
using namespace TheISA;
BaseSimpleCPU::BaseSimpleCPU(Params *p)
: BaseCPU(p), thread(NULL)
{
#if FULL_SYSTEM
thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb);
#else
thread = new SimpleThread(this, /* thread_num */ 0, p->process,
/* asid */ 0);
#endif // !FULL_SYSTEM
thread->setStatus(ThreadContext::Suspended);
tc = thread->getTC();
numInst = 0;
startNumInst = 0;
numLoad = 0;
startNumLoad = 0;
lastIcacheStall = 0;
lastDcacheStall = 0;
threadContexts.push_back(tc);
}
BaseSimpleCPU::~BaseSimpleCPU()
{
}
void
BaseSimpleCPU::deallocateContext(int thread_num)
{
// for now, these are equivalent
suspendContext(thread_num);
}
void
BaseSimpleCPU::haltContext(int thread_num)
{
// for now, these are equivalent
suspendContext(thread_num);
}
void
BaseSimpleCPU::regStats()
{
using namespace Stats;
BaseCPU::regStats();
numInsts
.name(name() + ".num_insts")
.desc("Number of instructions executed")
;
numMemRefs
.name(name() + ".num_refs")
.desc("Number of memory references")
;
notIdleFraction
.name(name() + ".not_idle_fraction")
.desc("Percentage of non-idle cycles")
;
idleFraction
.name(name() + ".idle_fraction")
.desc("Percentage of idle cycles")
;
icacheStallCycles
.name(name() + ".icache_stall_cycles")
.desc("ICache total stall cycles")
.prereq(icacheStallCycles)
;
dcacheStallCycles
.name(name() + ".dcache_stall_cycles")
.desc("DCache total stall cycles")
.prereq(dcacheStallCycles)
;
icacheRetryCycles
.name(name() + ".icache_retry_cycles")
.desc("ICache total retry cycles")
.prereq(icacheRetryCycles)
;
dcacheRetryCycles
.name(name() + ".dcache_retry_cycles")
.desc("DCache total retry cycles")
.prereq(dcacheRetryCycles)
;
idleFraction = constant(1.0) - notIdleFraction;
}
void
BaseSimpleCPU::resetStats()
{
// startNumInst = numInst;
// notIdleFraction = (_status != Idle);
}
void
BaseSimpleCPU::serialize(ostream &os)
{
BaseCPU::serialize(os);
// SERIALIZE_SCALAR(inst);
nameOut(os, csprintf("%s.xc.0", name()));
thread->serialize(os);
}
void
BaseSimpleCPU::unserialize(Checkpoint *cp, const string §ion)
{
BaseCPU::unserialize(cp, section);
// UNSERIALIZE_SCALAR(inst);
thread->unserialize(cp, csprintf("%s.xc.0", section));
}
void
change_thread_state(int thread_number, int activate, int priority)
{
}
Fault
BaseSimpleCPU::copySrcTranslate(Addr src)
{
#if 0
static bool no_warn = true;
int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;
// Only support block sizes of 64 atm.
assert(blk_size == 64);
int offset = src & (blk_size - 1);
// Make sure block doesn't span page
if (no_warn &&
(src & PageMask) != ((src + blk_size) & PageMask) &&
(src >> 40) != 0xfffffc) {
warn("Copied block source spans pages %x.", src);
no_warn = false;
}
memReq->reset(src & ~(blk_size - 1), blk_size);
// translate to physical address
Fault fault = thread->translateDataReadReq(req);
if (fault == NoFault) {
thread->copySrcAddr = src;
thread->copySrcPhysAddr = memReq->paddr + offset;
} else {
assert(!fault->isAlignmentFault());
thread->copySrcAddr = 0;
thread->copySrcPhysAddr = 0;
}
return fault;
#else
return NoFault;
#endif
}
Fault
BaseSimpleCPU::copy(Addr dest)
{
#if 0
static bool no_warn = true;
int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;
// Only support block sizes of 64 atm.
assert(blk_size == 64);
uint8_t data[blk_size];
//assert(thread->copySrcAddr);
int offset = dest & (blk_size - 1);
// Make sure block doesn't span page
if (no_warn &&
(dest & PageMask) != ((dest + blk_size) & PageMask) &&
(dest >> 40) != 0xfffffc) {
no_warn = false;
warn("Copied block destination spans pages %x. ", dest);
}
memReq->reset(dest & ~(blk_size -1), blk_size);
// translate to physical address
Fault fault = thread->translateDataWriteReq(req);
if (fault == NoFault) {
Addr dest_addr = memReq->paddr + offset;
// Need to read straight from memory since we have more than 8 bytes.
memReq->paddr = thread->copySrcPhysAddr;
thread->mem->read(memReq, data);
memReq->paddr = dest_addr;
thread->mem->write(memReq, data);
if (dcacheInterface) {
memReq->cmd = Copy;
memReq->completionEvent = NULL;
memReq->paddr = thread->copySrcPhysAddr;
memReq->dest = dest_addr;
memReq->size = 64;
memReq->time = curTick;
memReq->flags &= ~INST_READ;
dcacheInterface->access(memReq);
}
}
else
assert(!fault->isAlignmentFault());
return fault;
#else
panic("copy not implemented");
return NoFault;
#endif
}
#if FULL_SYSTEM
Addr
BaseSimpleCPU::dbg_vtophys(Addr addr)
{
return vtophys(tc, addr);
}
#endif // FULL_SYSTEM
#if FULL_SYSTEM
void
BaseSimpleCPU::post_interrupt(int int_num, int index)
{
BaseCPU::post_interrupt(int_num, index);
if (thread->status() == ThreadContext::Suspended) {
DPRINTF(IPI,"Suspended Processor awoke\n");
thread->activate();
}
}
#endif // FULL_SYSTEM
void
BaseSimpleCPU::checkForInterrupts()
{
#if FULL_SYSTEM
if (checkInterrupts && check_interrupts(tc)) {
Fault interrupt = interrupts.getInterrupt(tc);
if (interrupt != NoFault) {
interrupts.updateIntrInfo(tc);
checkInterrupts = false;
interrupt->invoke(tc);
}
}
#endif
}
Fault
BaseSimpleCPU::setupFetchRequest(Request *req)
{
// set up memory request for instruction fetch
#if ISA_HAS_DELAY_SLOT
DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p NNPC:%08p\n",thread->readPC(),
thread->readNextPC(),thread->readNextNPC());
#else
DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p",thread->readPC(),
thread->readNextPC());
#endif
req->setVirt(0, thread->readPC() & ~3, sizeof(MachInst),
(FULL_SYSTEM && (thread->readPC() & 1)) ? PHYSICAL : 0,
thread->readPC());
Fault fault = thread->translateInstReq(req);
return fault;
}
void
BaseSimpleCPU::preExecute()
{
// maintain $r0 semantics
thread->setIntReg(ZeroReg, 0);
#if THE_ISA == ALPHA_ISA
thread->setFloatReg(ZeroReg, 0.0);
#endif // ALPHA_ISA
// keep an instruction count
numInst++;
numInsts++;
thread->funcExeInst++;
// check for instruction-count-based events
comInstEventQueue[0]->serviceEvents(numInst);
// decode the instruction
inst = gtoh(inst);
//If we're not in the middle of a macro instruction
if (!curMacroStaticInst) {
#if THE_ISA == ALPHA_ISA
StaticInstPtr instPtr = StaticInst::decode(makeExtMI(inst, thread->readPC()));
#elif THE_ISA == SPARC_ISA
StaticInstPtr instPtr = StaticInst::decode(makeExtMI(inst, thread->getTC()));
#elif THE_ISA == MIPS_ISA
//Mips doesn't do anything in it's MakeExtMI function right now,
//so it won't be called.
StaticInstPtr instPtr = StaticInst::decode(inst);
#endif
if (instPtr->isMacroOp()) {
curMacroStaticInst = instPtr;
curStaticInst = curMacroStaticInst->
fetchMicroOp(thread->readMicroPC());
} else {
curStaticInst = instPtr;
}
} else {
//Read the next micro op from the macro op
curStaticInst = curMacroStaticInst->
fetchMicroOp(thread->readMicroPC());
}
traceData = Trace::getInstRecord(curTick, tc, curStaticInst,
thread->readPC());
DPRINTF(Decode,"Decode: Decoded %s instruction (opcode: 0x%x): 0x%x\n",
curStaticInst->getName(), curStaticInst->getOpcode(),
curStaticInst->machInst);
#if FULL_SYSTEM
thread->setInst(inst);
#endif // FULL_SYSTEM
}
void
BaseSimpleCPU::postExecute()
{
#if FULL_SYSTEM
if (thread->profile) {
bool usermode = TheISA::inUserMode(tc);
thread->profilePC = usermode ? 1 : thread->readPC();
ProfileNode *node = thread->profile->consume(tc, inst);
if (node)
thread->profileNode = node;
}
#endif
if (curStaticInst->isMemRef()) {
numMemRefs++;
}
if (curStaticInst->isLoad()) {
++numLoad;
comLoadEventQueue[0]->serviceEvents(numLoad);
}
traceFunctions(thread->readPC());
if (traceData) {
traceData->finalize();
}
}
void
BaseSimpleCPU::advancePC(Fault fault)
{
if (fault != NoFault) {
curMacroStaticInst = StaticInst::nullStaticInstPtr;
fault->invoke(tc);
} else {
//If we're at the last micro op for this instruction
if (curStaticInst->isLastMicroOp()) {
//We should be working with a macro op
assert(curMacroStaticInst);
//Close out this macro op, and clean up the
//microcode state
curMacroStaticInst = StaticInst::nullStaticInstPtr;
thread->setMicroPC(0);
thread->setNextMicroPC(1);
}
//If we're still in a macro op
if (curMacroStaticInst) {
//Advance the micro pc
thread->setMicroPC(thread->readNextMicroPC());
//Advance the "next" micro pc. Note that there are no delay
//slots, and micro ops are "word" addressed.
thread->setNextMicroPC(thread->readNextMicroPC() + 1);
} else {
// go to the next instruction
thread->setPC(thread->readNextPC());
#if ISA_HAS_DELAY_SLOT
thread->setNextPC(thread->readNextNPC());
thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));
assert(thread->readNextPC() != thread->readNextNPC());
#else
thread->setNextPC(thread->readNextPC() + sizeof(MachInst));
#endif
}
}
#if FULL_SYSTEM
Addr oldpc;
do {
oldpc = thread->readPC();
system->pcEventQueue.service(tc);
} while (oldpc != thread->readPC());
#endif
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
*/
#include "arch/utility.hh"
#include "arch/faults.hh"
#include "base/cprintf.hh"
#include "base/inifile.hh"
#include "base/loader/symtab.hh"
#include "base/misc.hh"
#include "base/pollevent.hh"
#include "base/range.hh"
#include "base/stats/events.hh"
#include "base/trace.hh"
#include "cpu/base.hh"
#include "cpu/exetrace.hh"
#include "cpu/profile.hh"
#include "cpu/simple/base.hh"
#include "cpu/simple_thread.hh"
#include "cpu/smt.hh"
#include "cpu/static_inst.hh"
#include "cpu/thread_context.hh"
#include "mem/packet.hh"
#include "sim/builder.hh"
#include "sim/byteswap.hh"
#include "sim/debug.hh"
#include "sim/host.hh"
#include "sim/sim_events.hh"
#include "sim/sim_object.hh"
#include "sim/stats.hh"
#include "sim/system.hh"
#if FULL_SYSTEM
#include "arch/kernel_stats.hh"
#include "arch/stacktrace.hh"
#include "arch/tlb.hh"
#include "arch/vtophys.hh"
#include "base/remote_gdb.hh"
#else // !FULL_SYSTEM
#include "mem/mem_object.hh"
#endif // FULL_SYSTEM
using namespace std;
using namespace TheISA;
BaseSimpleCPU::BaseSimpleCPU(Params *p)
: BaseCPU(p), thread(NULL), predecoder(NULL)
{
#if FULL_SYSTEM
thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb);
#else
thread = new SimpleThread(this, /* thread_num */ 0, p->process,
/* asid */ 0);
#endif // !FULL_SYSTEM
thread->setStatus(ThreadContext::Suspended);
tc = thread->getTC();
numInst = 0;
startNumInst = 0;
numLoad = 0;
startNumLoad = 0;
lastIcacheStall = 0;
lastDcacheStall = 0;
threadContexts.push_back(tc);
}
BaseSimpleCPU::~BaseSimpleCPU()
{
}
void
BaseSimpleCPU::deallocateContext(int thread_num)
{
// for now, these are equivalent
suspendContext(thread_num);
}
void
BaseSimpleCPU::haltContext(int thread_num)
{
// for now, these are equivalent
suspendContext(thread_num);
}
void
BaseSimpleCPU::regStats()
{
using namespace Stats;
BaseCPU::regStats();
numInsts
.name(name() + ".num_insts")
.desc("Number of instructions executed")
;
numMemRefs
.name(name() + ".num_refs")
.desc("Number of memory references")
;
notIdleFraction
.name(name() + ".not_idle_fraction")
.desc("Percentage of non-idle cycles")
;
idleFraction
.name(name() + ".idle_fraction")
.desc("Percentage of idle cycles")
;
icacheStallCycles
.name(name() + ".icache_stall_cycles")
.desc("ICache total stall cycles")
.prereq(icacheStallCycles)
;
dcacheStallCycles
.name(name() + ".dcache_stall_cycles")
.desc("DCache total stall cycles")
.prereq(dcacheStallCycles)
;
icacheRetryCycles
.name(name() + ".icache_retry_cycles")
.desc("ICache total retry cycles")
.prereq(icacheRetryCycles)
;
dcacheRetryCycles
.name(name() + ".dcache_retry_cycles")
.desc("DCache total retry cycles")
.prereq(dcacheRetryCycles)
;
idleFraction = constant(1.0) - notIdleFraction;
}
void
BaseSimpleCPU::resetStats()
{
// startNumInst = numInst;
// notIdleFraction = (_status != Idle);
}
void
BaseSimpleCPU::serialize(ostream &os)
{
BaseCPU::serialize(os);
// SERIALIZE_SCALAR(inst);
nameOut(os, csprintf("%s.xc.0", name()));
thread->serialize(os);
}
void
BaseSimpleCPU::unserialize(Checkpoint *cp, const string §ion)
{
BaseCPU::unserialize(cp, section);
// UNSERIALIZE_SCALAR(inst);
thread->unserialize(cp, csprintf("%s.xc.0", section));
}
void
change_thread_state(int thread_number, int activate, int priority)
{
}
Fault
BaseSimpleCPU::copySrcTranslate(Addr src)
{
#if 0
static bool no_warn = true;
int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;
// Only support block sizes of 64 atm.
assert(blk_size == 64);
int offset = src & (blk_size - 1);
// Make sure block doesn't span page
if (no_warn &&
(src & PageMask) != ((src + blk_size) & PageMask) &&
(src >> 40) != 0xfffffc) {
warn("Copied block source spans pages %x.", src);
no_warn = false;
}
memReq->reset(src & ~(blk_size - 1), blk_size);
// translate to physical address
Fault fault = thread->translateDataReadReq(req);
if (fault == NoFault) {
thread->copySrcAddr = src;
thread->copySrcPhysAddr = memReq->paddr + offset;
} else {
assert(!fault->isAlignmentFault());
thread->copySrcAddr = 0;
thread->copySrcPhysAddr = 0;
}
return fault;
#else
return NoFault;
#endif
}
Fault
BaseSimpleCPU::copy(Addr dest)
{
#if 0
static bool no_warn = true;
int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;
// Only support block sizes of 64 atm.
assert(blk_size == 64);
uint8_t data[blk_size];
//assert(thread->copySrcAddr);
int offset = dest & (blk_size - 1);
// Make sure block doesn't span page
if (no_warn &&
(dest & PageMask) != ((dest + blk_size) & PageMask) &&
(dest >> 40) != 0xfffffc) {
no_warn = false;
warn("Copied block destination spans pages %x. ", dest);
}
memReq->reset(dest & ~(blk_size -1), blk_size);
// translate to physical address
Fault fault = thread->translateDataWriteReq(req);
if (fault == NoFault) {
Addr dest_addr = memReq->paddr + offset;
// Need to read straight from memory since we have more than 8 bytes.
memReq->paddr = thread->copySrcPhysAddr;
thread->mem->read(memReq, data);
memReq->paddr = dest_addr;
thread->mem->write(memReq, data);
if (dcacheInterface) {
memReq->cmd = Copy;
memReq->completionEvent = NULL;
memReq->paddr = thread->copySrcPhysAddr;
memReq->dest = dest_addr;
memReq->size = 64;
memReq->time = curTick;
memReq->flags &= ~INST_READ;
dcacheInterface->access(memReq);
}
}
else
assert(!fault->isAlignmentFault());
return fault;
#else
panic("copy not implemented");
return NoFault;
#endif
}
#if FULL_SYSTEM
Addr
BaseSimpleCPU::dbg_vtophys(Addr addr)
{
return vtophys(tc, addr);
}
#endif // FULL_SYSTEM
#if FULL_SYSTEM
void
BaseSimpleCPU::post_interrupt(int int_num, int index)
{
BaseCPU::post_interrupt(int_num, index);
if (thread->status() == ThreadContext::Suspended) {
DPRINTF(Quiesce,"Suspended Processor awoke\n");
thread->activate();
}
}
#endif // FULL_SYSTEM
void
BaseSimpleCPU::checkForInterrupts()
{
#if FULL_SYSTEM
if (check_interrupts(tc)) {
Fault interrupt = interrupts.getInterrupt(tc);
if (interrupt != NoFault) {
interrupts.updateIntrInfo(tc);
interrupt->invoke(tc);
}
}
#endif
}
Fault
BaseSimpleCPU::setupFetchRequest(Request *req)
{
// set up memory request for instruction fetch
#if ISA_HAS_DELAY_SLOT
DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p NNPC:%08p\n",thread->readPC(),
thread->readNextPC(),thread->readNextNPC());
#else
DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p",thread->readPC(),
thread->readNextPC());
#endif
req->setVirt(0, thread->readPC() & ~3, sizeof(MachInst),
(FULL_SYSTEM && (thread->readPC() & 1)) ? PHYSICAL : 0,
thread->readPC());
Fault fault = thread->translateInstReq(req);
return fault;
}
void
BaseSimpleCPU::preExecute()
{
// maintain $r0 semantics
thread->setIntReg(ZeroReg, 0);
#if THE_ISA == ALPHA_ISA
thread->setFloatReg(ZeroReg, 0.0);
#endif // ALPHA_ISA
// keep an instruction count
numInst++;
numInsts++;
thread->funcExeInst++;
// check for instruction-count-based events
comInstEventQueue[0]->serviceEvents(numInst);
// decode the instruction
inst = gtoh(inst);
//If we're not in the middle of a macro instruction
if (!curMacroStaticInst) {
StaticInstPtr instPtr = NULL;
//Predecode, ie bundle up an ExtMachInst
//This should go away once the constructor can be set up properly
predecoder.setTC(thread->getTC());
//If more fetch data is needed, pass it in.
if(predecoder.needMoreBytes())
predecoder.moreBytes(thread->readPC(), 0, inst);
else
predecoder.process();
//If an instruction is ready, decode it
if (predecoder.extMachInstReady())
instPtr = StaticInst::decode(predecoder.getExtMachInst());
//If we decoded an instruction and it's microcoded, start pulling
//out micro ops
if (instPtr && instPtr->isMacroOp()) {
curMacroStaticInst = instPtr;
curStaticInst = curMacroStaticInst->
fetchMicroOp(thread->readMicroPC());
} else {
curStaticInst = instPtr;
}
} else {
//Read the next micro op from the macro op
curStaticInst = curMacroStaticInst->
fetchMicroOp(thread->readMicroPC());
}
//If we decoded an instruction this "tick", record information about it.
if(curStaticInst)
{
traceData = Trace::getInstRecord(curTick, tc, curStaticInst,
thread->readPC());
DPRINTF(Decode,"Decode: Decoded %s instruction: 0x%x\n",
curStaticInst->getName(), curStaticInst->machInst);
#if FULL_SYSTEM
thread->setInst(inst);
#endif // FULL_SYSTEM
}
}
void
BaseSimpleCPU::postExecute()
{
#if FULL_SYSTEM
if (thread->profile) {
bool usermode = TheISA::inUserMode(tc);
thread->profilePC = usermode ? 1 : thread->readPC();
ProfileNode *node = thread->profile->consume(tc, inst);
if (node)
thread->profileNode = node;
}
#endif
if (curStaticInst->isMemRef()) {
numMemRefs++;
}
if (curStaticInst->isLoad()) {
++numLoad;
comLoadEventQueue[0]->serviceEvents(numLoad);
}
traceFunctions(thread->readPC());
if (traceData) {
traceData->dump();
delete traceData;
traceData = NULL;
}
}
void
BaseSimpleCPU::advancePC(Fault fault)
{
if (fault != NoFault) {
curMacroStaticInst = StaticInst::nullStaticInstPtr;
fault->invoke(tc);
thread->setMicroPC(0);
thread->setNextMicroPC(1);
} else if (predecoder.needMoreBytes()) {
//If we're at the last micro op for this instruction
if (curStaticInst && curStaticInst->isLastMicroOp()) {
//We should be working with a macro op
assert(curMacroStaticInst);
//Close out this macro op, and clean up the
//microcode state
curMacroStaticInst = StaticInst::nullStaticInstPtr;
thread->setMicroPC(0);
thread->setNextMicroPC(1);
}
//If we're still in a macro op
if (curMacroStaticInst) {
//Advance the micro pc
thread->setMicroPC(thread->readNextMicroPC());
//Advance the "next" micro pc. Note that there are no delay
//slots, and micro ops are "word" addressed.
thread->setNextMicroPC(thread->readNextMicroPC() + 1);
} else {
// go to the next instruction
thread->setPC(thread->readNextPC());
thread->setNextPC(thread->readNextNPC());
thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));
assert(thread->readNextPC() != thread->readNextNPC());
}
}
#if FULL_SYSTEM
Addr oldpc;
do {
oldpc = thread->readPC();
system->pcEventQueue.service(tc);
} while (oldpc != thread->readPC());
#endif
}
<commit_msg>Fix ALPHA_FS compile. The MachInst -> StaticInstPtr constructor is no longer a conversion constructor because it caused ambiguous conversions when setting the pointer to NULL.<commit_after>/*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
*/
#include "arch/utility.hh"
#include "arch/faults.hh"
#include "base/cprintf.hh"
#include "base/inifile.hh"
#include "base/loader/symtab.hh"
#include "base/misc.hh"
#include "base/pollevent.hh"
#include "base/range.hh"
#include "base/stats/events.hh"
#include "base/trace.hh"
#include "cpu/base.hh"
#include "cpu/exetrace.hh"
#include "cpu/profile.hh"
#include "cpu/simple/base.hh"
#include "cpu/simple_thread.hh"
#include "cpu/smt.hh"
#include "cpu/static_inst.hh"
#include "cpu/thread_context.hh"
#include "mem/packet.hh"
#include "sim/builder.hh"
#include "sim/byteswap.hh"
#include "sim/debug.hh"
#include "sim/host.hh"
#include "sim/sim_events.hh"
#include "sim/sim_object.hh"
#include "sim/stats.hh"
#include "sim/system.hh"
#if FULL_SYSTEM
#include "arch/kernel_stats.hh"
#include "arch/stacktrace.hh"
#include "arch/tlb.hh"
#include "arch/vtophys.hh"
#include "base/remote_gdb.hh"
#else // !FULL_SYSTEM
#include "mem/mem_object.hh"
#endif // FULL_SYSTEM
using namespace std;
using namespace TheISA;
BaseSimpleCPU::BaseSimpleCPU(Params *p)
: BaseCPU(p), thread(NULL), predecoder(NULL)
{
#if FULL_SYSTEM
thread = new SimpleThread(this, 0, p->system, p->itb, p->dtb);
#else
thread = new SimpleThread(this, /* thread_num */ 0, p->process,
/* asid */ 0);
#endif // !FULL_SYSTEM
thread->setStatus(ThreadContext::Suspended);
tc = thread->getTC();
numInst = 0;
startNumInst = 0;
numLoad = 0;
startNumLoad = 0;
lastIcacheStall = 0;
lastDcacheStall = 0;
threadContexts.push_back(tc);
}
BaseSimpleCPU::~BaseSimpleCPU()
{
}
void
BaseSimpleCPU::deallocateContext(int thread_num)
{
// for now, these are equivalent
suspendContext(thread_num);
}
void
BaseSimpleCPU::haltContext(int thread_num)
{
// for now, these are equivalent
suspendContext(thread_num);
}
void
BaseSimpleCPU::regStats()
{
using namespace Stats;
BaseCPU::regStats();
numInsts
.name(name() + ".num_insts")
.desc("Number of instructions executed")
;
numMemRefs
.name(name() + ".num_refs")
.desc("Number of memory references")
;
notIdleFraction
.name(name() + ".not_idle_fraction")
.desc("Percentage of non-idle cycles")
;
idleFraction
.name(name() + ".idle_fraction")
.desc("Percentage of idle cycles")
;
icacheStallCycles
.name(name() + ".icache_stall_cycles")
.desc("ICache total stall cycles")
.prereq(icacheStallCycles)
;
dcacheStallCycles
.name(name() + ".dcache_stall_cycles")
.desc("DCache total stall cycles")
.prereq(dcacheStallCycles)
;
icacheRetryCycles
.name(name() + ".icache_retry_cycles")
.desc("ICache total retry cycles")
.prereq(icacheRetryCycles)
;
dcacheRetryCycles
.name(name() + ".dcache_retry_cycles")
.desc("DCache total retry cycles")
.prereq(dcacheRetryCycles)
;
idleFraction = constant(1.0) - notIdleFraction;
}
void
BaseSimpleCPU::resetStats()
{
// startNumInst = numInst;
// notIdleFraction = (_status != Idle);
}
void
BaseSimpleCPU::serialize(ostream &os)
{
BaseCPU::serialize(os);
// SERIALIZE_SCALAR(inst);
nameOut(os, csprintf("%s.xc.0", name()));
thread->serialize(os);
}
void
BaseSimpleCPU::unserialize(Checkpoint *cp, const string §ion)
{
BaseCPU::unserialize(cp, section);
// UNSERIALIZE_SCALAR(inst);
thread->unserialize(cp, csprintf("%s.xc.0", section));
}
void
change_thread_state(int thread_number, int activate, int priority)
{
}
Fault
BaseSimpleCPU::copySrcTranslate(Addr src)
{
#if 0
static bool no_warn = true;
int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;
// Only support block sizes of 64 atm.
assert(blk_size == 64);
int offset = src & (blk_size - 1);
// Make sure block doesn't span page
if (no_warn &&
(src & PageMask) != ((src + blk_size) & PageMask) &&
(src >> 40) != 0xfffffc) {
warn("Copied block source spans pages %x.", src);
no_warn = false;
}
memReq->reset(src & ~(blk_size - 1), blk_size);
// translate to physical address
Fault fault = thread->translateDataReadReq(req);
if (fault == NoFault) {
thread->copySrcAddr = src;
thread->copySrcPhysAddr = memReq->paddr + offset;
} else {
assert(!fault->isAlignmentFault());
thread->copySrcAddr = 0;
thread->copySrcPhysAddr = 0;
}
return fault;
#else
return NoFault;
#endif
}
Fault
BaseSimpleCPU::copy(Addr dest)
{
#if 0
static bool no_warn = true;
int blk_size = (dcacheInterface) ? dcacheInterface->getBlockSize() : 64;
// Only support block sizes of 64 atm.
assert(blk_size == 64);
uint8_t data[blk_size];
//assert(thread->copySrcAddr);
int offset = dest & (blk_size - 1);
// Make sure block doesn't span page
if (no_warn &&
(dest & PageMask) != ((dest + blk_size) & PageMask) &&
(dest >> 40) != 0xfffffc) {
no_warn = false;
warn("Copied block destination spans pages %x. ", dest);
}
memReq->reset(dest & ~(blk_size -1), blk_size);
// translate to physical address
Fault fault = thread->translateDataWriteReq(req);
if (fault == NoFault) {
Addr dest_addr = memReq->paddr + offset;
// Need to read straight from memory since we have more than 8 bytes.
memReq->paddr = thread->copySrcPhysAddr;
thread->mem->read(memReq, data);
memReq->paddr = dest_addr;
thread->mem->write(memReq, data);
if (dcacheInterface) {
memReq->cmd = Copy;
memReq->completionEvent = NULL;
memReq->paddr = thread->copySrcPhysAddr;
memReq->dest = dest_addr;
memReq->size = 64;
memReq->time = curTick;
memReq->flags &= ~INST_READ;
dcacheInterface->access(memReq);
}
}
else
assert(!fault->isAlignmentFault());
return fault;
#else
panic("copy not implemented");
return NoFault;
#endif
}
#if FULL_SYSTEM
Addr
BaseSimpleCPU::dbg_vtophys(Addr addr)
{
return vtophys(tc, addr);
}
#endif // FULL_SYSTEM
#if FULL_SYSTEM
void
BaseSimpleCPU::post_interrupt(int int_num, int index)
{
BaseCPU::post_interrupt(int_num, index);
if (thread->status() == ThreadContext::Suspended) {
DPRINTF(Quiesce,"Suspended Processor awoke\n");
thread->activate();
}
}
#endif // FULL_SYSTEM
void
BaseSimpleCPU::checkForInterrupts()
{
#if FULL_SYSTEM
if (check_interrupts(tc)) {
Fault interrupt = interrupts.getInterrupt(tc);
if (interrupt != NoFault) {
interrupts.updateIntrInfo(tc);
interrupt->invoke(tc);
}
}
#endif
}
Fault
BaseSimpleCPU::setupFetchRequest(Request *req)
{
// set up memory request for instruction fetch
#if ISA_HAS_DELAY_SLOT
DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p NNPC:%08p\n",thread->readPC(),
thread->readNextPC(),thread->readNextNPC());
#else
DPRINTF(Fetch,"Fetch: PC:%08p NPC:%08p",thread->readPC(),
thread->readNextPC());
#endif
req->setVirt(0, thread->readPC() & ~3, sizeof(MachInst),
(FULL_SYSTEM && (thread->readPC() & 1)) ? PHYSICAL : 0,
thread->readPC());
Fault fault = thread->translateInstReq(req);
return fault;
}
void
BaseSimpleCPU::preExecute()
{
// maintain $r0 semantics
thread->setIntReg(ZeroReg, 0);
#if THE_ISA == ALPHA_ISA
thread->setFloatReg(ZeroReg, 0.0);
#endif // ALPHA_ISA
// keep an instruction count
numInst++;
numInsts++;
thread->funcExeInst++;
// check for instruction-count-based events
comInstEventQueue[0]->serviceEvents(numInst);
// decode the instruction
inst = gtoh(inst);
//If we're not in the middle of a macro instruction
if (!curMacroStaticInst) {
StaticInstPtr instPtr = NULL;
//Predecode, ie bundle up an ExtMachInst
//This should go away once the constructor can be set up properly
predecoder.setTC(thread->getTC());
//If more fetch data is needed, pass it in.
if(predecoder.needMoreBytes())
predecoder.moreBytes(thread->readPC(), 0, inst);
else
predecoder.process();
//If an instruction is ready, decode it
if (predecoder.extMachInstReady())
instPtr = StaticInst::decode(predecoder.getExtMachInst());
//If we decoded an instruction and it's microcoded, start pulling
//out micro ops
if (instPtr && instPtr->isMacroOp()) {
curMacroStaticInst = instPtr;
curStaticInst = curMacroStaticInst->
fetchMicroOp(thread->readMicroPC());
} else {
curStaticInst = instPtr;
}
} else {
//Read the next micro op from the macro op
curStaticInst = curMacroStaticInst->
fetchMicroOp(thread->readMicroPC());
}
//If we decoded an instruction this "tick", record information about it.
if(curStaticInst)
{
traceData = Trace::getInstRecord(curTick, tc, curStaticInst,
thread->readPC());
DPRINTF(Decode,"Decode: Decoded %s instruction: 0x%x\n",
curStaticInst->getName(), curStaticInst->machInst);
#if FULL_SYSTEM
thread->setInst(inst);
#endif // FULL_SYSTEM
}
}
void
BaseSimpleCPU::postExecute()
{
#if FULL_SYSTEM
if (thread->profile) {
bool usermode = TheISA::inUserMode(tc);
thread->profilePC = usermode ? 1 : thread->readPC();
StaticInstPtr si(inst);
ProfileNode *node = thread->profile->consume(tc, si);
if (node)
thread->profileNode = node;
}
#endif
if (curStaticInst->isMemRef()) {
numMemRefs++;
}
if (curStaticInst->isLoad()) {
++numLoad;
comLoadEventQueue[0]->serviceEvents(numLoad);
}
traceFunctions(thread->readPC());
if (traceData) {
traceData->dump();
delete traceData;
traceData = NULL;
}
}
void
BaseSimpleCPU::advancePC(Fault fault)
{
if (fault != NoFault) {
curMacroStaticInst = StaticInst::nullStaticInstPtr;
fault->invoke(tc);
thread->setMicroPC(0);
thread->setNextMicroPC(1);
} else if (predecoder.needMoreBytes()) {
//If we're at the last micro op for this instruction
if (curStaticInst && curStaticInst->isLastMicroOp()) {
//We should be working with a macro op
assert(curMacroStaticInst);
//Close out this macro op, and clean up the
//microcode state
curMacroStaticInst = StaticInst::nullStaticInstPtr;
thread->setMicroPC(0);
thread->setNextMicroPC(1);
}
//If we're still in a macro op
if (curMacroStaticInst) {
//Advance the micro pc
thread->setMicroPC(thread->readNextMicroPC());
//Advance the "next" micro pc. Note that there are no delay
//slots, and micro ops are "word" addressed.
thread->setNextMicroPC(thread->readNextMicroPC() + 1);
} else {
// go to the next instruction
thread->setPC(thread->readNextPC());
thread->setNextPC(thread->readNextNPC());
thread->setNextNPC(thread->readNextNPC() + sizeof(MachInst));
assert(thread->readNextPC() != thread->readNextNPC());
}
}
#if FULL_SYSTEM
Addr oldpc;
do {
oldpc = thread->readPC();
system->pcEventQueue.service(tc);
} while (oldpc != thread->readPC());
#endif
}
<|endoftext|> |
<commit_before>/*
* This file is part of Poedit (http://poedit.net)
*
* Copyright (C) 2015 Vaclav Slavik
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#include "customcontrols.h"
#include "concurrency.h"
#include "errors.h"
#include "hidpi.h"
#include <wx/app.h>
#include <wx/clipbrd.h>
#include <wx/menu.h>
#include <wx/settings.h>
#include <wx/sizer.h>
#include <wx/weakref.h>
#include <wx/wupdlock.h>
#if wxCHECK_VERSION(3,1,0)
#include <wx/activityindicator.h>
#else
#include "wx_backports/activityindicator.h"
#endif
#include <unicode/brkiter.h>
#ifdef __WXGTK__
#include <gtk/gtk.h>
#endif
#include "str_helpers.h"
#include <memory>
namespace
{
wxString WrapTextAtWidth(const wxString& text_, int width, wxWindow *wnd)
{
if (text_.empty())
return text_;
auto text = str::to_icu(text_);
static std::unique_ptr<icu::BreakIterator> iter;
if (!iter)
{
UErrorCode err = U_ZERO_ERROR;
iter.reset(icu::BreakIterator::createLineInstance(icu::Locale(), err));
}
iter->setText(text);
wxString out;
out.reserve(text_.length() + 10);
int32_t lineStart = 0;
wxString previousSubstr;
for (int32_t pos = iter->next(); pos != icu::BreakIterator::DONE; pos = iter->next())
{
auto substr = str::to_wx(text.tempSubStringBetween(lineStart, pos));
if (wnd->GetTextExtent(substr).x > width)
{
auto previousPos = iter->previous();
if (previousPos == lineStart || previousPos == icu::BreakIterator::DONE)
{
// line is too large but we can't break it, so have no choice but not to wrap
out += substr;
lineStart = pos;
}
else
{
// need to wrap at previous linebreak position
out += previousSubstr;
lineStart = previousPos;
}
out += '\n';
previousSubstr.clear();
}
else if (pos > 0 && text[pos-1] == '\n') // forced line feed
{
out += substr;
lineStart = pos;
previousSubstr.clear();
}
else
{
previousSubstr = substr;
}
}
if (!previousSubstr.empty())
{
out += previousSubstr;
}
if (out.Last() == '\n')
out.RemoveLast();
return out;
}
} // anonymous namespace
AutoWrappingText::AutoWrappingText(wxWindow *parent, const wxString& label)
: wxStaticText(parent, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, wxST_NO_AUTORESIZE),
m_text(label),
m_wrapWidth(-1)
{
m_text.Replace("\n", " ");
SetInitialSize(wxSize(10,10));
Bind(wxEVT_SIZE, &ExplanationLabel::OnSize, this);
}
void AutoWrappingText::SetAlignment(int align)
{
if (GetWindowStyleFlag() & align)
return;
SetWindowStyleFlag(wxST_NO_AUTORESIZE | align);
}
void AutoWrappingText::SetAndWrapLabel(const wxString& label)
{
wxWindowUpdateLocker lock(this);
m_text = label;
m_wrapWidth = GetSize().x;
SetLabelText(WrapTextAtWidth(label, m_wrapWidth, this));
InvalidateBestSize();
SetMinSize(wxDefaultSize);
SetMinSize(GetBestSize());
}
void AutoWrappingText::OnSize(wxSizeEvent& e)
{
e.Skip();
int w = wxMax(0, e.GetSize().x - PX(4));
if (w == m_wrapWidth)
return;
wxWindowUpdateLocker lock(this);
m_wrapWidth = w;
SetLabel(WrapTextAtWidth(m_text, w, this));
InvalidateBestSize();
SetMinSize(wxDefaultSize);
SetMinSize(GetBestSize());
}
SelectableAutoWrappingText::SelectableAutoWrappingText(wxWindow *parent, const wxString& label)
: AutoWrappingText(parent, label)
{
#if defined(__WXOSX__)
NSTextField *view = (NSTextField*)GetHandle();
[view setSelectable:YES];
#elif defined(__WXGTK__)
GtkLabel *view = GTK_LABEL(GetHandle());
gtk_label_set_selectable(view, TRUE);
#else
// at least allow copying
static wxWindowID idCopy = wxNewId();
Bind(wxEVT_CONTEXT_MENU, [=](wxContextMenuEvent&){
wxMenu *menu = new wxMenu();
menu->Append(idCopy, _("&Copy"));
PopupMenu(menu);
});
Bind(wxEVT_MENU, [=](wxCommandEvent&){
wxClipboardLocker lock;
wxClipboard::Get()->SetData(new wxTextDataObject(m_text));
}, idCopy);
#endif
}
ExplanationLabel::ExplanationLabel(wxWindow *parent, const wxString& label)
: AutoWrappingText(parent, label)
{
#if defined(__WXOSX__) || defined(__WXGTK__)
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
#ifndef __WXGTK__
SetForegroundColour(GetTextColor());
#endif
}
wxColour ExplanationLabel::GetTextColor()
{
#if defined(__WXOSX__)
return wxColour("#777777");
#elif defined(__WXGTK__)
return wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
#else
return wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT);
#endif
}
SecondaryLabel::SecondaryLabel(wxWindow *parent, const wxString& label)
: wxStaticText(parent, wxID_ANY, label)
{
#if defined(__WXOSX__) || defined(__WXGTK__)
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
#ifndef __WXGTK__
SetForegroundColour(GetTextColor());
#endif
}
LearnMoreLink::LearnMoreLink(wxWindow *parent, const wxString& url, wxString label, wxWindowID winid)
{
if (label.empty())
{
#ifdef __WXMSW__
label = _("Learn more");
#else
label = _("Learn More");
#endif
}
wxHyperlinkCtrl::Create(parent, winid, label, url);
SetNormalColour("#2F79BE");
SetVisitedColour("#2F79BE");
SetHoverColour("#3D8DD5");
#ifdef __WXOSX__
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
SetFont(GetFont().Underlined());
#endif
}
wxObject *LearnMoreLinkXmlHandler::DoCreateResource()
{
auto w = new LearnMoreLink(m_parentAsWindow, GetText("url"), GetText("label"), GetID());
w->SetName(GetName());
SetupWindow(w);
return w;
}
bool LearnMoreLinkXmlHandler::CanHandle(wxXmlNode *node)
{
return IsOfClass(node, "LearnMoreLink");
}
ActivityIndicator::ActivityIndicator(wxWindow *parent)
: wxWindow(parent, wxID_ANY), m_running(false)
{
auto sizer = new wxBoxSizer(wxHORIZONTAL);
SetSizer(sizer);
m_spinner = new wxActivityIndicator(this, wxID_ANY);
m_spinner->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
m_label = new wxStaticText(this, wxID_ANY, "");
#ifdef __WXOSX__
m_label->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
sizer->Add(m_spinner, wxSizerFlags().Center().Border(wxRIGHT, PX(4)));
sizer->Add(m_label, wxSizerFlags(1).Center());
HandleError = on_main_thread_for_window<std::exception_ptr>(this, [=](std::exception_ptr e){
StopWithError(DescribeException(e));
});
}
void ActivityIndicator::Start(const wxString& msg)
{
m_running = true;
m_label->SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
m_label->SetLabel(msg);
auto sizer = GetSizer();
sizer->Show(m_spinner);
sizer->Show(m_label, !msg.empty());
Layout();
m_spinner->Start();
}
void ActivityIndicator::Stop()
{
m_running = false;
m_spinner->Stop();
m_label->SetLabel("");
auto sizer = GetSizer();
sizer->Hide(m_spinner);
sizer->Hide(m_label);
Layout();
}
void ActivityIndicator::StopWithError(const wxString& msg)
{
m_running = false;
m_spinner->Stop();
m_label->SetForegroundColour(*wxRED);
m_label->SetLabel(msg);
auto sizer = GetSizer();
sizer->Hide(m_spinner);
sizer->Show(m_label);
Layout();
}
<commit_msg>Use correct explanation text size even with wxGTK 3.0<commit_after>/*
* This file is part of Poedit (http://poedit.net)
*
* Copyright (C) 2015 Vaclav Slavik
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#include "customcontrols.h"
#include "concurrency.h"
#include "errors.h"
#include "hidpi.h"
#include <wx/app.h>
#include <wx/clipbrd.h>
#include <wx/menu.h>
#include <wx/settings.h>
#include <wx/sizer.h>
#include <wx/weakref.h>
#include <wx/wupdlock.h>
#if wxCHECK_VERSION(3,1,0)
#include <wx/activityindicator.h>
#else
#include "wx_backports/activityindicator.h"
#endif
#include <unicode/brkiter.h>
#ifdef __WXGTK__
#include <gtk/gtk.h>
#endif
#include "str_helpers.h"
#include <memory>
namespace
{
wxString WrapTextAtWidth(const wxString& text_, int width, wxWindow *wnd)
{
if (text_.empty())
return text_;
auto text = str::to_icu(text_);
static std::unique_ptr<icu::BreakIterator> iter;
if (!iter)
{
UErrorCode err = U_ZERO_ERROR;
iter.reset(icu::BreakIterator::createLineInstance(icu::Locale(), err));
}
iter->setText(text);
wxString out;
out.reserve(text_.length() + 10);
int32_t lineStart = 0;
wxString previousSubstr;
for (int32_t pos = iter->next(); pos != icu::BreakIterator::DONE; pos = iter->next())
{
auto substr = str::to_wx(text.tempSubStringBetween(lineStart, pos));
if (wnd->GetTextExtent(substr).x > width)
{
auto previousPos = iter->previous();
if (previousPos == lineStart || previousPos == icu::BreakIterator::DONE)
{
// line is too large but we can't break it, so have no choice but not to wrap
out += substr;
lineStart = pos;
}
else
{
// need to wrap at previous linebreak position
out += previousSubstr;
lineStart = previousPos;
}
out += '\n';
previousSubstr.clear();
}
else if (pos > 0 && text[pos-1] == '\n') // forced line feed
{
out += substr;
lineStart = pos;
previousSubstr.clear();
}
else
{
previousSubstr = substr;
}
}
if (!previousSubstr.empty())
{
out += previousSubstr;
}
if (out.Last() == '\n')
out.RemoveLast();
return out;
}
} // anonymous namespace
AutoWrappingText::AutoWrappingText(wxWindow *parent, const wxString& label)
: wxStaticText(parent, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, wxST_NO_AUTORESIZE),
m_text(label),
m_wrapWidth(-1)
{
m_text.Replace("\n", " ");
SetInitialSize(wxSize(10,10));
Bind(wxEVT_SIZE, &ExplanationLabel::OnSize, this);
}
void AutoWrappingText::SetAlignment(int align)
{
if (GetWindowStyleFlag() & align)
return;
SetWindowStyleFlag(wxST_NO_AUTORESIZE | align);
}
void AutoWrappingText::SetAndWrapLabel(const wxString& label)
{
wxWindowUpdateLocker lock(this);
m_text = label;
m_wrapWidth = GetSize().x;
SetLabelText(WrapTextAtWidth(label, m_wrapWidth, this));
InvalidateBestSize();
SetMinSize(wxDefaultSize);
SetMinSize(GetBestSize());
}
void AutoWrappingText::OnSize(wxSizeEvent& e)
{
e.Skip();
int w = wxMax(0, e.GetSize().x - PX(4));
if (w == m_wrapWidth)
return;
wxWindowUpdateLocker lock(this);
m_wrapWidth = w;
SetLabel(WrapTextAtWidth(m_text, w, this));
InvalidateBestSize();
SetMinSize(wxDefaultSize);
SetMinSize(GetBestSize());
}
SelectableAutoWrappingText::SelectableAutoWrappingText(wxWindow *parent, const wxString& label)
: AutoWrappingText(parent, label)
{
#if defined(__WXOSX__)
NSTextField *view = (NSTextField*)GetHandle();
[view setSelectable:YES];
#elif defined(__WXGTK__)
GtkLabel *view = GTK_LABEL(GetHandle());
gtk_label_set_selectable(view, TRUE);
#else
// at least allow copying
static wxWindowID idCopy = wxNewId();
Bind(wxEVT_CONTEXT_MENU, [=](wxContextMenuEvent&){
wxMenu *menu = new wxMenu();
menu->Append(idCopy, _("&Copy"));
PopupMenu(menu);
});
Bind(wxEVT_MENU, [=](wxCommandEvent&){
wxClipboardLocker lock;
wxClipboard::Get()->SetData(new wxTextDataObject(m_text));
}, idCopy);
#endif
}
ExplanationLabel::ExplanationLabel(wxWindow *parent, const wxString& label)
: AutoWrappingText(parent, label)
{
#if defined(__WXOSX__)
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#elif defined(__WXGTK__)
#if wxCHECK_VERSION(3,1,0)
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#else
SetFont(GetFont().Smaller());
#endif
#endif
#ifndef __WXGTK__
SetForegroundColour(GetTextColor());
#endif
}
wxColour ExplanationLabel::GetTextColor()
{
#if defined(__WXOSX__)
return wxColour("#777777");
#elif defined(__WXGTK__)
return wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
#else
return wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT);
#endif
}
SecondaryLabel::SecondaryLabel(wxWindow *parent, const wxString& label)
: wxStaticText(parent, wxID_ANY, label)
{
#if defined(__WXOSX__)
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#elif defined(__WXGTK__)
#if wxCHECK_VERSION(3,1,0)
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#else
SetFont(GetFont().Smaller());
#endif
#endif
#ifndef __WXGTK__
SetForegroundColour(GetTextColor());
#endif
}
LearnMoreLink::LearnMoreLink(wxWindow *parent, const wxString& url, wxString label, wxWindowID winid)
{
if (label.empty())
{
#ifdef __WXMSW__
label = _("Learn more");
#else
label = _("Learn More");
#endif
}
wxHyperlinkCtrl::Create(parent, winid, label, url);
SetNormalColour("#2F79BE");
SetVisitedColour("#2F79BE");
SetHoverColour("#3D8DD5");
#ifdef __WXOSX__
SetWindowVariant(wxWINDOW_VARIANT_SMALL);
SetFont(GetFont().Underlined());
#endif
}
wxObject *LearnMoreLinkXmlHandler::DoCreateResource()
{
auto w = new LearnMoreLink(m_parentAsWindow, GetText("url"), GetText("label"), GetID());
w->SetName(GetName());
SetupWindow(w);
return w;
}
bool LearnMoreLinkXmlHandler::CanHandle(wxXmlNode *node)
{
return IsOfClass(node, "LearnMoreLink");
}
ActivityIndicator::ActivityIndicator(wxWindow *parent)
: wxWindow(parent, wxID_ANY), m_running(false)
{
auto sizer = new wxBoxSizer(wxHORIZONTAL);
SetSizer(sizer);
m_spinner = new wxActivityIndicator(this, wxID_ANY);
m_spinner->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
m_label = new wxStaticText(this, wxID_ANY, "");
#ifdef __WXOSX__
m_label->SetWindowVariant(wxWINDOW_VARIANT_SMALL);
#endif
sizer->Add(m_spinner, wxSizerFlags().Center().Border(wxRIGHT, PX(4)));
sizer->Add(m_label, wxSizerFlags(1).Center());
HandleError = on_main_thread_for_window<std::exception_ptr>(this, [=](std::exception_ptr e){
StopWithError(DescribeException(e));
});
}
void ActivityIndicator::Start(const wxString& msg)
{
m_running = true;
m_label->SetForegroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
m_label->SetLabel(msg);
auto sizer = GetSizer();
sizer->Show(m_spinner);
sizer->Show(m_label, !msg.empty());
Layout();
m_spinner->Start();
}
void ActivityIndicator::Stop()
{
m_running = false;
m_spinner->Stop();
m_label->SetLabel("");
auto sizer = GetSizer();
sizer->Hide(m_spinner);
sizer->Hide(m_label);
Layout();
}
void ActivityIndicator::StopWithError(const wxString& msg)
{
m_running = false;
m_spinner->Stop();
m_label->SetForegroundColour(*wxRED);
m_label->SetLabel(msg);
auto sizer = GetSizer();
sizer->Hide(m_spinner);
sizer->Show(m_label);
Layout();
}
<|endoftext|> |
<commit_before>#include <node.h>
#include <nan.h>
#include <v8.h>
#include <vector>
#include "mouse.h"
#include "deadbeef_rand.h"
#include "keypress.h"
#include "screen.h"
#include "screengrab.h"
#include "MMBitmap.h"
using namespace v8;
/*
__ __
| \/ | ___ _ _ ___ ___
| |\/| |/ _ \| | | / __|/ _ \
| | | | (_) | |_| \__ \ __/
|_| |_|\___/ \__,_|___/\___|
*/
NAN_METHOD(moveMouse)
{
NanScope();
if (args.Length() < 2)
{
return NanThrowError("Invalid number of arguments.");
}
size_t x = args[0]->Int32Value();
size_t y = args[1]->Int32Value();
MMPoint point;
point = MMPointMake(x, y);
moveMouse(point);
NanReturnValue(NanNew("1"));
}
NAN_METHOD(moveMouseSmooth)
{
NanScope();
if (args.Length() < 2)
{
return NanThrowError("Invalid number of arguments.");
}
size_t x = args[0]->Int32Value();
size_t y = args[1]->Int32Value();
MMPoint point;
point = MMPointMake(x, y);
smoothlyMoveMouse(point);
NanReturnValue(NanNew("1"));
}
NAN_METHOD(getMousePos)
{
NanScope();
MMPoint pos = getMousePos();
//Return object with .x and .y.
Local<Object> obj = NanNew<Object>();
obj->Set(NanNew<String>("x"), NanNew<Number>(pos.x));
obj->Set(NanNew<String>("y"), NanNew<Number>(pos.y));
NanReturnValue(obj);
}
NAN_METHOD(mouseClick)
{
NanScope();
MMMouseButton button = LEFT_BUTTON;
if (args.Length() == 1)
{
char *b = (*v8::String::Utf8Value(args[0]->ToString()));
if (strcmp(b, "left") == 0)
{
button = LEFT_BUTTON;
}
else if (strcmp(b, "right") == 0)
{
button = RIGHT_BUTTON;
}
else if (strcmp(b, "middle") == 0)
{
button = CENTER_BUTTON;
}
else
{
return NanThrowError("Invalid mouse button specified.");
}
}
else if (args.Length() > 1)
{
return NanThrowError("Invalid number of arguments.");
}
clickMouse(button);
NanReturnValue(NanNew("1"));
}
NAN_METHOD(mouseToggle)
{
NanScope();
MMMouseButton button = LEFT_BUTTON;
bool down;
if (args.Length() > 0)
{
const char *d = (*v8::String::Utf8Value(args[0]->ToString()));
if (strcmp(d, "down") == 0)
{
down = true;;
}
else if (strcmp(d, "up") == 0)
{
down = false;
}
else
{
return NanThrowError("Invalid mouse button state specified.");
}
}
if (args.Length() == 2)
{
char *b = (*v8::String::Utf8Value(args[1]->ToString()));
if (strcmp(b, "left") == 0)
{
button = LEFT_BUTTON;
}
else if (strcmp(b, "right") == 0)
{
button = RIGHT_BUTTON;
}
else if (strcmp(b, "middle") == 0)
{
button = CENTER_BUTTON;
}
else
{
return NanThrowError("Invalid mouse button specified.");
}
}
else if (args.Length() > 2)
{
return NanThrowError("Invalid number of arguments.");
}
toggleMouse(down, button);
NanReturnValue(NanNew("1"));
}
/*
_ __ _ _
| |/ /___ _ _| |__ ___ __ _ _ __ __| |
| ' // _ \ | | | '_ \ / _ \ / _` | '__/ _` |
| . \ __/ |_| | |_) | (_) | (_| | | | (_| |
|_|\_\___|\__, |_.__/ \___/ \__,_|_| \__,_|
|___/
*/
int CheckKeyCodes(char* k, MMKeyCode *key)
{
if (!key) return -1;
if (strcmp(k, "alt") == 0)
{
*key = K_ALT;
}
else if (strcmp(k, "command") == 0)
{
*key = K_META;
}
else if (strcmp(k, "control") == 0)
{
*key = K_CONTROL;
}
else if (strcmp(k, "shift") == 0)
{
*key = K_SHIFT;
}
else if (strcmp(k, "backspace") == 0)
{
*key = K_BACKSPACE;
}
else if (strcmp(k, "enter") == 0)
{
*key = K_RETURN;
}
else if (strcmp(k, "tab") == 0)
{
*key = K_TAB;
}
else if (strcmp(k, "up") == 0)
{
*key = K_UP;
}
else if (strcmp(k, "down") == 0)
{
*key = K_DOWN;
}
else if (strcmp(k, "left") == 0)
{
*key = K_LEFT;
}
else if (strcmp(k, "right") == 0)
{
*key = K_RIGHT;
}
else if (strcmp(k, "escape") == 0)
{
*key = K_ESCAPE;
}
else if (strcmp(k, "delete") == 0)
{
*key = K_DELETE;
}
else if (strcmp(k, "home") == 0)
{
*key = K_HOME;
}
else if (strcmp(k, "end") == 0)
{
*key = K_END;
}
else if (strcmp(k, "pageup") == 0)
{
*key = K_PAGEUP;
}
else if (strcmp(k, "pagedown") == 0)
{
*key = K_PAGEDOWN;
}
else if (strlen(k) == 1)
{
*key = keyCodeForChar(*k);
}
else
{
return -2;
}
return 0;
}
int CheckKeyFlags(char* f, MMKeyFlags* flags)
{
if (!flags) return -1;
if (strcmp(f, "alt") == 0)
{
*flags = MOD_ALT;
}
else if(strcmp(f, "command") == 0)
{
*flags = MOD_META;
}
else if(strcmp(f, "control") == 0)
{
*flags = MOD_CONTROL;
}
else if(strcmp(f, "shift") == 0)
{
*flags = MOD_SHIFT;
}
else if(strcmp(f, "none") == 0)
{
*flags = MOD_NONE;
}
else
{
return -2;
}
return 0;
}
int mssleep(unsigned long millisecond)
{
struct timespec req;
time_t sec=(int)(millisecond/1000);
millisecond=millisecond-(sec*1000);
req.tv_sec=sec;
req.tv_nsec=millisecond*1000000L;
while(nanosleep(&req,&req)==-1)
continue;
return 1;
}
NAN_METHOD(keyTap)
{
NanScope();
MMKeyFlags flags = MOD_NONE;
MMKeyCode key;
char *k;
char *f;
v8::String::Utf8Value fstr(args[1]->ToString());
v8::String::Utf8Value kstr(args[0]->ToString());
k = *kstr;
f = *fstr;
switch (args.Length())
{
case 2:
break;
case 1:
f = NULL;
break;
default:
return NanThrowError("Invalid number of arguments.");
}
if (f)
{
switch(CheckKeyFlags(f, &flags))
{
case -1:
return NanThrowError("Null pointer in key flag.");
break;
case -2:
return NanThrowError("Invalid key flag specified.");
break;
}
}
switch(CheckKeyCodes(k, &key))
{
case -1:
return NanThrowError("Null pointer in key code.");
break;
case -2:
return NanThrowError("Invalid key code specified.");
break;
default:
tapKeyCode(key, flags);
mssleep(10);
}
NanReturnValue(NanNew("1"));
}
NAN_METHOD(keyToggle)
{
NanScope();
MMKeyFlags flags = MOD_NONE;
MMKeyCode key;
char *k;
bool down;
char *f;
v8::String::Utf8Value kstr(args[0]->ToString());
v8::String::Utf8Value fstr(args[2]->ToString());
down = args[1]->BooleanValue();
k = *kstr;
f = *fstr;
switch (args.Length())
{
case 3:
break;
case 2:
f = NULL;
break;
default:
return NanThrowError("Invalid number of arguments.");
}
if (f)
{
switch(CheckKeyFlags(f, &flags))
{
case -1:
return NanThrowError("Null pointer in key flag.");
break;
case -2:
return NanThrowError("Invalid key flag specified.");
break;
}
}
switch(CheckKeyCodes(k, &key))
{
case -1:
return NanThrowError("Null pointer in key code.");
break;
case -2:
return NanThrowError("Invalid key code specified.");
break;
default:
toggleKeyCode(key, down, flags);
mssleep(10);
}
NanReturnValue(NanNew("1"));
}
NAN_METHOD(typeString)
{
NanScope();
char *str;
NanUtf8String string(args[0]);
str = *string;
typeString(str);
NanReturnValue(NanNew("1"));
}
/*
____
/ ___| ___ _ __ ___ ___ _ __
\___ \ / __| '__/ _ \/ _ \ '_ \
___) | (__| | | __/ __/ | | |
|____/ \___|_| \___|\___|_| |_|
*/
NAN_METHOD(getPixelColor)
{
NanScope();
MMBitmapRef bitmap;
MMRGBHex color;
size_t x = args[0]->Int32Value();
size_t y = args[1]->Int32Value();
bitmap = copyMMBitmapFromDisplayInRect(MMRectMake(x, y, 1, 1));
color = MMRGBHexAtPoint(bitmap, 0, 0);
char hex [6];
//Length needs to be 7 because snprintf includes a terminating null.
//Use %06x to pad hex value with leading 0s.
snprintf(hex, 7, "%06x", color);
destroyMMBitmap(bitmap);
NanReturnValue(NanNew(hex));
}
NAN_METHOD(getScreenSize)
{
NanScope();
//Get display size.
MMSize displaySize = getMainDisplaySize();
//Create our return object.
Local<Object> obj = NanNew<Object>();
obj->Set(NanNew<String>("width"), NanNew<Number>(displaySize.width));
obj->Set(NanNew<String>("height"), NanNew<Number>(displaySize.height));
//Return our object with .width and .height.
NanReturnValue(obj);
}
void init(Handle<Object> target)
{
target->Set(NanNew<String>("moveMouse"),
NanNew<FunctionTemplate>(moveMouse)->GetFunction());
target->Set(NanNew<String>("moveMouseSmooth"),
NanNew<FunctionTemplate>(moveMouseSmooth)->GetFunction());
target->Set(NanNew<String>("getMousePos"),
NanNew<FunctionTemplate>(getMousePos)->GetFunction());
target->Set(NanNew<String>("mouseClick"),
NanNew<FunctionTemplate>(mouseClick)->GetFunction());
target->Set(NanNew<String>("mouseToggle"),
NanNew<FunctionTemplate>(mouseToggle)->GetFunction());
target->Set(NanNew<String>("keyTap"),
NanNew<FunctionTemplate>(keyTap)->GetFunction());
target->Set(NanNew<String>("keyToggle"),
NanNew<FunctionTemplate>(keyToggle)->GetFunction());
target->Set(NanNew<String>("typeString"),
NanNew<FunctionTemplate>(typeString)->GetFunction());
target->Set(NanNew<String>("getPixelColor"),
NanNew<FunctionTemplate>(getPixelColor)->GetFunction());
target->Set(NanNew<String>("getScreenSize"),
NanNew<FunctionTemplate>(getScreenSize)->GetFunction());
}
NODE_MODULE(robotjs, init)
<commit_msg>Spaces to tabs.<commit_after>#include <node.h>
#include <nan.h>
#include <v8.h>
#include <vector>
#include "mouse.h"
#include "deadbeef_rand.h"
#include "keypress.h"
#include "screen.h"
#include "screengrab.h"
#include "MMBitmap.h"
using namespace v8;
/*
__ __
| \/ | ___ _ _ ___ ___
| |\/| |/ _ \| | | / __|/ _ \
| | | | (_) | |_| \__ \ __/
|_| |_|\___/ \__,_|___/\___|
*/
NAN_METHOD(moveMouse)
{
NanScope();
if (args.Length() < 2)
{
return NanThrowError("Invalid number of arguments.");
}
size_t x = args[0]->Int32Value();
size_t y = args[1]->Int32Value();
MMPoint point;
point = MMPointMake(x, y);
moveMouse(point);
NanReturnValue(NanNew("1"));
}
NAN_METHOD(moveMouseSmooth)
{
NanScope();
if (args.Length() < 2)
{
return NanThrowError("Invalid number of arguments.");
}
size_t x = args[0]->Int32Value();
size_t y = args[1]->Int32Value();
MMPoint point;
point = MMPointMake(x, y);
smoothlyMoveMouse(point);
NanReturnValue(NanNew("1"));
}
NAN_METHOD(getMousePos)
{
NanScope();
MMPoint pos = getMousePos();
//Return object with .x and .y.
Local<Object> obj = NanNew<Object>();
obj->Set(NanNew<String>("x"), NanNew<Number>(pos.x));
obj->Set(NanNew<String>("y"), NanNew<Number>(pos.y));
NanReturnValue(obj);
}
NAN_METHOD(mouseClick)
{
NanScope();
MMMouseButton button = LEFT_BUTTON;
if (args.Length() == 1)
{
char *b = (*v8::String::Utf8Value(args[0]->ToString()));
if (strcmp(b, "left") == 0)
{
button = LEFT_BUTTON;
}
else if (strcmp(b, "right") == 0)
{
button = RIGHT_BUTTON;
}
else if (strcmp(b, "middle") == 0)
{
button = CENTER_BUTTON;
}
else
{
return NanThrowError("Invalid mouse button specified.");
}
}
else if (args.Length() > 1)
{
return NanThrowError("Invalid number of arguments.");
}
clickMouse(button);
NanReturnValue(NanNew("1"));
}
NAN_METHOD(mouseToggle)
{
NanScope();
MMMouseButton button = LEFT_BUTTON;
bool down;
if (args.Length() > 0)
{
const char *d = (*v8::String::Utf8Value(args[0]->ToString()));
if (strcmp(d, "down") == 0)
{
down = true;;
}
else if (strcmp(d, "up") == 0)
{
down = false;
}
else
{
return NanThrowError("Invalid mouse button state specified.");
}
}
if (args.Length() == 2)
{
char *b = (*v8::String::Utf8Value(args[1]->ToString()));
if (strcmp(b, "left") == 0)
{
button = LEFT_BUTTON;
}
else if (strcmp(b, "right") == 0)
{
button = RIGHT_BUTTON;
}
else if (strcmp(b, "middle") == 0)
{
button = CENTER_BUTTON;
}
else
{
return NanThrowError("Invalid mouse button specified.");
}
}
else if (args.Length() > 2)
{
return NanThrowError("Invalid number of arguments.");
}
toggleMouse(down, button);
NanReturnValue(NanNew("1"));
}
/*
_ __ _ _
| |/ /___ _ _| |__ ___ __ _ _ __ __| |
| ' // _ \ | | | '_ \ / _ \ / _` | '__/ _` |
| . \ __/ |_| | |_) | (_) | (_| | | | (_| |
|_|\_\___|\__, |_.__/ \___/ \__,_|_| \__,_|
|___/
*/
int CheckKeyCodes(char* k, MMKeyCode *key)
{
if (!key) return -1;
if (strcmp(k, "alt") == 0)
{
*key = K_ALT;
}
else if (strcmp(k, "command") == 0)
{
*key = K_META;
}
else if (strcmp(k, "control") == 0)
{
*key = K_CONTROL;
}
else if (strcmp(k, "shift") == 0)
{
*key = K_SHIFT;
}
else if (strcmp(k, "backspace") == 0)
{
*key = K_BACKSPACE;
}
else if (strcmp(k, "enter") == 0)
{
*key = K_RETURN;
}
else if (strcmp(k, "tab") == 0)
{
*key = K_TAB;
}
else if (strcmp(k, "up") == 0)
{
*key = K_UP;
}
else if (strcmp(k, "down") == 0)
{
*key = K_DOWN;
}
else if (strcmp(k, "left") == 0)
{
*key = K_LEFT;
}
else if (strcmp(k, "right") == 0)
{
*key = K_RIGHT;
}
else if (strcmp(k, "escape") == 0)
{
*key = K_ESCAPE;
}
else if (strcmp(k, "delete") == 0)
{
*key = K_DELETE;
}
else if (strcmp(k, "home") == 0)
{
*key = K_HOME;
}
else if (strcmp(k, "end") == 0)
{
*key = K_END;
}
else if (strcmp(k, "pageup") == 0)
{
*key = K_PAGEUP;
}
else if (strcmp(k, "pagedown") == 0)
{
*key = K_PAGEDOWN;
}
else if (strlen(k) == 1)
{
*key = keyCodeForChar(*k);
}
else
{
return -2;
}
return 0;
}
int CheckKeyFlags(char* f, MMKeyFlags* flags)
{
if (!flags) return -1;
if (strcmp(f, "alt") == 0)
{
*flags = MOD_ALT;
}
else if(strcmp(f, "command") == 0)
{
*flags = MOD_META;
}
else if(strcmp(f, "control") == 0)
{
*flags = MOD_CONTROL;
}
else if(strcmp(f, "shift") == 0)
{
*flags = MOD_SHIFT;
}
else if(strcmp(f, "none") == 0)
{
*flags = MOD_NONE;
}
else
{
return -2;
}
return 0;
}
int mssleep(unsigned long millisecond)
{
struct timespec req;
time_t sec=(int)(millisecond/1000);
millisecond=millisecond-(sec*1000);
req.tv_sec=sec;
req.tv_nsec=millisecond*1000000L;
while(nanosleep(&req,&req)==-1)
continue;
return 1;
}
NAN_METHOD(keyTap)
{
NanScope();
MMKeyFlags flags = MOD_NONE;
MMKeyCode key;
char *k;
char *f;
v8::String::Utf8Value fstr(args[1]->ToString());
v8::String::Utf8Value kstr(args[0]->ToString());
k = *kstr;
f = *fstr;
switch (args.Length())
{
case 2:
break;
case 1:
f = NULL;
break;
default:
return NanThrowError("Invalid number of arguments.");
}
if (f)
{
switch(CheckKeyFlags(f, &flags))
{
case -1:
return NanThrowError("Null pointer in key flag.");
break;
case -2:
return NanThrowError("Invalid key flag specified.");
break;
}
}
switch(CheckKeyCodes(k, &key))
{
case -1:
return NanThrowError("Null pointer in key code.");
break;
case -2:
return NanThrowError("Invalid key code specified.");
break;
default:
tapKeyCode(key, flags);
mssleep(10);
}
NanReturnValue(NanNew("1"));
}
NAN_METHOD(keyToggle)
{
NanScope();
MMKeyFlags flags = MOD_NONE;
MMKeyCode key;
char *k;
bool down;
char *f;
v8::String::Utf8Value kstr(args[0]->ToString());
v8::String::Utf8Value fstr(args[2]->ToString());
down = args[1]->BooleanValue();
k = *kstr;
f = *fstr;
switch (args.Length())
{
case 3:
break;
case 2:
f = NULL;
break;
default:
return NanThrowError("Invalid number of arguments.");
}
if (f)
{
switch(CheckKeyFlags(f, &flags))
{
case -1:
return NanThrowError("Null pointer in key flag.");
break;
case -2:
return NanThrowError("Invalid key flag specified.");
break;
}
}
switch(CheckKeyCodes(k, &key))
{
case -1:
return NanThrowError("Null pointer in key code.");
break;
case -2:
return NanThrowError("Invalid key code specified.");
break;
default:
toggleKeyCode(key, down, flags);
mssleep(10);
}
NanReturnValue(NanNew("1"));
}
NAN_METHOD(typeString)
{
NanScope();
char *str;
NanUtf8String string(args[0]);
str = *string;
typeString(str);
NanReturnValue(NanNew("1"));
}
/*
____
/ ___| ___ _ __ ___ ___ _ __
\___ \ / __| '__/ _ \/ _ \ '_ \
___) | (__| | | __/ __/ | | |
|____/ \___|_| \___|\___|_| |_|
*/
NAN_METHOD(getPixelColor)
{
NanScope();
MMBitmapRef bitmap;
MMRGBHex color;
size_t x = args[0]->Int32Value();
size_t y = args[1]->Int32Value();
bitmap = copyMMBitmapFromDisplayInRect(MMRectMake(x, y, 1, 1));
color = MMRGBHexAtPoint(bitmap, 0, 0);
char hex [6];
//Length needs to be 7 because snprintf includes a terminating null.
//Use %06x to pad hex value with leading 0s.
snprintf(hex, 7, "%06x", color);
destroyMMBitmap(bitmap);
NanReturnValue(NanNew(hex));
}
NAN_METHOD(getScreenSize)
{
NanScope();
//Get display size.
MMSize displaySize = getMainDisplaySize();
//Create our return object.
Local<Object> obj = NanNew<Object>();
obj->Set(NanNew<String>("width"), NanNew<Number>(displaySize.width));
obj->Set(NanNew<String>("height"), NanNew<Number>(displaySize.height));
//Return our object with .width and .height.
NanReturnValue(obj);
}
void init(Handle<Object> target)
{
target->Set(NanNew<String>("moveMouse"),
NanNew<FunctionTemplate>(moveMouse)->GetFunction());
target->Set(NanNew<String>("moveMouseSmooth"),
NanNew<FunctionTemplate>(moveMouseSmooth)->GetFunction());
target->Set(NanNew<String>("getMousePos"),
NanNew<FunctionTemplate>(getMousePos)->GetFunction());
target->Set(NanNew<String>("mouseClick"),
NanNew<FunctionTemplate>(mouseClick)->GetFunction());
target->Set(NanNew<String>("mouseToggle"),
NanNew<FunctionTemplate>(mouseToggle)->GetFunction());
target->Set(NanNew<String>("keyTap"),
NanNew<FunctionTemplate>(keyTap)->GetFunction());
target->Set(NanNew<String>("keyToggle"),
NanNew<FunctionTemplate>(keyToggle)->GetFunction());
target->Set(NanNew<String>("typeString"),
NanNew<FunctionTemplate>(typeString)->GetFunction());
target->Set(NanNew<String>("getPixelColor"),
NanNew<FunctionTemplate>(getPixelColor)->GetFunction());
target->Set(NanNew<String>("getScreenSize"),
NanNew<FunctionTemplate>(getScreenSize)->GetFunction());
}
NODE_MODULE(robotjs, init)
<|endoftext|> |
<commit_before>// Copyright 2017 Esri.
// 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 <QSettings>
#include <QGuiApplication>
#include <QQuickView>
#include <QCommandLineParser>
#include <QDir>
#include <QQmlEngine>
#include <QSurfaceFormat>
#define STRINGIZE(x) #x
#define QUOTE(x) STRINGIZE(x)
int main(int argc, char *argv[])
{
#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
// Linux requires 3.2 OpenGL Context
// in order to instance 3D symbols
QSurfaceFormat fmt = QSurfaceFormat::defaultFormat();
fmt.setVersion(3, 2);
QSurfaceFormat::setDefaultFormat(fmt);
#endif
QGuiApplication app(argc, argv);
#ifdef Q_OS_WIN
// Force usage of OpenGL ES through ANGLE on Windows
QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);
#endif
// Intialize application view
QQuickView view;
view.setResizeMode(QQuickView::SizeRootObjectToView);
QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH);
QString arcGISToolkitImportPath = QUOTE(ARCGIS_TOOLKIT_IMPORT_PATH);
#if defined(LINUX_PLATFORM_REPLACEMENT)
// on some linux platforms the string 'linux' is replaced with 1
// fix the replacement paths which were created
QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT);
arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, "linux", Qt::CaseSensitive);
arcGISToolkitImportPath = arcGISToolkitImportPath.replace(replaceString, "linux", Qt::CaseSensitive);
#endif
// Add the import Path
view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
// Add the Runtime and Extras path
view.engine()->addImportPath(arcGISRuntimeImportPath);
// Add the Toolkit path
view.engine()->addImportPath(arcGISToolkitImportPath);
// Set the source
view.setSource(QUrl("qrc:/Samples/Analysis/FeatureLayerExtrusion/FeatureLayerExtrusion.qml"));
view.show();
return app.exec();
}
<commit_msg>Changed category from Analysis to Scenes<commit_after>// Copyright 2017 Esri.
// 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 <QSettings>
#include <QGuiApplication>
#include <QQuickView>
#include <QCommandLineParser>
#include <QDir>
#include <QQmlEngine>
#include <QSurfaceFormat>
#define STRINGIZE(x) #x
#define QUOTE(x) STRINGIZE(x)
int main(int argc, char *argv[])
{
#if defined(Q_OS_LINUX) && !defined(Q_OS_ANDROID)
// Linux requires 3.2 OpenGL Context
// in order to instance 3D symbols
QSurfaceFormat fmt = QSurfaceFormat::defaultFormat();
fmt.setVersion(3, 2);
QSurfaceFormat::setDefaultFormat(fmt);
#endif
QGuiApplication app(argc, argv);
#ifdef Q_OS_WIN
// Force usage of OpenGL ES through ANGLE on Windows
QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);
#endif
// Intialize application view
QQuickView view;
view.setResizeMode(QQuickView::SizeRootObjectToView);
QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH);
QString arcGISToolkitImportPath = QUOTE(ARCGIS_TOOLKIT_IMPORT_PATH);
#if defined(LINUX_PLATFORM_REPLACEMENT)
// on some linux platforms the string 'linux' is replaced with 1
// fix the replacement paths which were created
QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT);
arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, "linux", Qt::CaseSensitive);
arcGISToolkitImportPath = arcGISToolkitImportPath.replace(replaceString, "linux", Qt::CaseSensitive);
#endif
// Add the import Path
view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
// Add the Runtime and Extras path
view.engine()->addImportPath(arcGISRuntimeImportPath);
// Add the Toolkit path
view.engine()->addImportPath(arcGISToolkitImportPath);
// Set the source
view.setSource(QUrl("qrc:/Samples/Scenes/FeatureLayerExtrusion/FeatureLayerExtrusion.qml"));
view.show();
return app.exec();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <votca/tools/version.h>
#include <iostream>
#include "version.h"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if GMX == 45
#include <gromacs/copyrite.h>
#elif GMX == 40
extern "C"
{
#include <copyrite.h>
}
#endif
#ifdef GMX
// this one is needed because of bool is defined in one of the headers included by gmx
#undef bool
#endif
namespace votca { namespace csg {
#ifdef HGVERSION
static const std::string version_str = VERSION " " HGVERSION " (compiled " __DATE__ ", " __TIME__ ")";
#else
static const std::string version_str = VERSION "(compiled " __DATE__ ", " __TIME__ ")";
#endif
const std::string &CsgVersionStr()
{
return version_str;
}
void HelpTextHeader(const std::string &tool_name)
{
std::cout
<< "==================================================\n"
<< "======== VOTCA (http://www.votca.org) ========\n"
<< "==================================================\n\n"
<< "please submit bugs to " PACKAGE_BUGREPORT "\n\n"
<< tool_name << ", version " << votca::csg::CsgVersionStr()
<< "\nvotca_tools, version " << votca::tools::ToolsVersionStr()
#ifdef GMX
<< "\ngromacs, " << GromacsVersion()
#else
<< "\n"
#endif
<< "\n\n";
}
}}
<commit_msg>libcsg: added precision to GromacsVersion<commit_after>/*
* Copyright 2009 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <votca/tools/version.h>
#include <iostream>
#include "version.h"
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#if GMX == 45
#include <gromacs/copyrite.h>
#elif GMX == 40
extern "C"
{
#include <copyrite.h>
}
#endif
#ifdef GMX
// this one is needed because of bool is defined in one of the headers included by gmx
#undef bool
#endif
namespace votca { namespace csg {
#ifdef HGVERSION
static const std::string version_str = VERSION " " HGVERSION " (compiled " __DATE__ ", " __TIME__ ")";
#else
static const std::string version_str = VERSION "(compiled " __DATE__ ", " __TIME__ ")";
#endif
const std::string &CsgVersionStr()
{
return version_str;
}
void HelpTextHeader(const std::string &tool_name)
{
std::cout
<< "==================================================\n"
<< "======== VOTCA (http://www.votca.org) ========\n"
<< "==================================================\n\n"
<< "please submit bugs to " PACKAGE_BUGREPORT "\n\n"
<< tool_name << ", version " << votca::csg::CsgVersionStr()
<< "\nvotca_tools, version " << votca::tools::ToolsVersionStr()
#ifdef GMX
<< "\ngromacs, " << GromacsVersion()
#ifdef GMX_DOUBLE
<< " (double precision)"
#else
<< " (single precision)"
#endif
#else
<< "\n"
#endif
<< "\n\n";
}
}}
<|endoftext|> |
<commit_before>#include "LdapClient.h"
//------------------------------------------------------------------------------
#ifdef OPENLDAP
#include <cstdlib> // free()
#include <sys/time.h> // struct timeval
#include <sstream> // std::stringstream
/** OpenLDAP client implementation */
class OpenLdapClient : public LdapClient
{
public:
OpenLdapClient() : LdapClient(), ldap(NULL), retval(LDAP_SUCCESS) { }
~OpenLdapClient();
bool bind(const std::string& dn,
const std::string& pass);
int getLastError() { return this->retval; }
std::string getLastErrorMsg() { return std::string(ldap_err2string(this->retval)); }
struct berval** getValuesLen(LDAPMessage* entry,
const char* attr);
int countEntries(LDAPMessage* result);
LDAPMessage* firstEntry(LDAPMessage* result);
bool init(const std::string& host,
int port);
bool msgFree(LDAPMessage* msg);
LDAPMessage* nextEntry(LDAPMessage* entry);
bool search(const std::string& basedn,
int scope,
const std::string& filter,
char* attrs[],
int attrsonly,
LDAPControl** serverctrls,
LDAPControl** clientctrls,
const LdapClient::TimeVal& timeout,
int sizelimit,
LDAPMessage** results);
bool setOption(int option,
void *invalue);
bool valueFreeLen(struct berval** val);
private:
void setTimeval(const LdapClient::TimeVal& src, struct timeval& dest);
private:
LDAP* ldap;
int retval;
};
OpenLdapClient::~OpenLdapClient()
{
ldap_unbind_ext(this->ldap, NULL, NULL);
free(this->ldap);
this->ldap = NULL;
}
bool OpenLdapClient::bind(const std::string& dn,
const std::string& passwd)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
LDAPControl *serverctrls=NULL, *clientctrls=NULL;
struct berval *servercredp=NULL;
struct berval creds;
creds.bv_val = strdup( passwd.c_str() );
creds.bv_len = passwd.length();
this->retval = ldap_sasl_bind_s(ldap,
dn.c_str(),
LDAP_SASL_SIMPLE,
&creds,
&serverctrls,
&clientctrls,
&servercredp);
return this->retval == LDAP_SUCCESS;
}
int OpenLdapClient::countEntries(LDAPMessage* result)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
int num_entries = ldap_count_entries(ldap, result);
this->retval = LDAP_OTHER;
return num_entries;
}
LDAPMessage* OpenLdapClient::firstEntry(LDAPMessage* result)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
LDAPMessage* msg = ldap_first_message(ldap, result);
this->retval = LDAP_OTHER;
return msg;
}
struct berval** OpenLdapClient::getValuesLen(LDAPMessage* entry,
const char* attr)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
return ldap_get_values_len(this->ldap, entry, attr);
}
bool OpenLdapClient::init(const std::string& host, int port)
{
if (this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
std::stringstream uri_buf;
uri_buf << "ldap://" << host << ':' << port;
this->retval = ldap_initialize(&this->ldap, uri_buf.str().c_str());
return this->retval == LDAP_SUCCESS;
}
bool OpenLdapClient::msgFree(LDAPMessage* msg)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
this->retval = ldap_msgfree(msg);
return this->retval == LDAP_SUCCESS;
}
LDAPMessage* OpenLdapClient::nextEntry(LDAPMessage* entry)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
return ldap_next_entry(this->ldap, entry);
}
bool OpenLdapClient::search(const std::string& basedn,
int scope,
const std::string& filter,
char* attrs[],
int attrsonly,
LDAPControl** serverctrls,
LDAPControl** clientctrls,
const LdapClient::TimeVal& timeout,
int sizelimit,
LDAPMessage** results)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
struct timeval openldap_timeout;
this->setTimeval(timeout, openldap_timeout);
ldap_search_ext_s(this->ldap,
basedn.c_str(),
scope,
filter.c_str(),
attrs,
attrsonly,
serverctrls,
clientctrls,
&openldap_timeout,
sizelimit,
results);
return this->retval == LDAP_SUCCESS;
}
bool OpenLdapClient::setOption(int option, void* invalue)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
this->retval = ldap_set_option(this->ldap,
option,
invalue);
return this->retval == LDAP_SUCCESS;
}
void OpenLdapClient::setTimeval(const LdapClient::TimeVal& src, struct timeval& dest)
{
dest.tv_sec = src.tv_sec;
dest.tv_usec = src.tv_usec;
}
bool OpenLdapClient::valueFreeLen(struct berval** val)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
ldap_value_free_len(val);
this->retval = LDAP_SUCCESS;
return this->retval == LDAP_SUCCESS;
}
#endif // OPENLDAP
//------------------------------------------------------------------------------
#ifdef WINLDAP
/** Microsoft Windows LDAP client implementation */
class WinLdapClient : public LdapClient
{
public:
WinLdapClient() : ldap(NULL), retval(LDAP_SUCCESS) { }
~WinLdapClient();
bool bind(const std::string& dn,
const std::string& passwd);
int countEntries(LDAPMessage* result);
LDAPMessage* firstEntry(LDAPMessage* result);
int getLastError() { return this->retval; }
std::string getLastErrorMsg() { return std::string(ldap_err2string(this->retval)); }
struct berval** getValuesLen(LDAPMessage* entry,
const char* attr);
bool init(const std::string& host,
int port);
bool msgFree(LDAPMessage* msg);
LDAPMessage* nextEntry(LDAPMessage* entry);
bool search(const std::string& basedn,
int scope,
const std::string& filter,
char* attrs[],
int attrsonly,
LDAPControl** serverctrls,
LDAPControl** clientctrls,
const LdapClient::TimeVal& timeout,
int sizelimit,
LDAPMessage** results);
bool setOption(int option,
void *invalue);
bool valueFreeLen(struct berval** val);
private:
void setTimeval(const LdapClient::TimeVal& src, struct l_timeval& dest);
private:
LDAP* ldap;
int retval;
};
WinLdapClient::~WinLdapClient()
{
ldap_unbind(this->ldap);
free(this->ldap);
this->ldap = NULL;
}
bool WinLdapClient::bind(const std::string& dn,
const std::string& passwd)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
this->retval = ldap_simple_bind_s(this->ldap,
(char*) dn.c_str(),
(char*) passwd.c_str());
return this->retval == LDAP_SUCCESS;
}
int WinLdapClient::countEntries(LDAPMessage* result)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
int num_entries = ldap_count_entries(ldap, result);
this->retval = LDAP_OTHER;
return num_entries;
}
LDAPMessage* WinLdapClient::firstEntry(LDAPMessage* result)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
LDAPMessage* msg = ldap_first_entry(ldap, result);
this->retval = LDAP_OTHER;
return msg;
}
struct berval** WinLdapClient::getValuesLen(LDAPMessage* entry,
const char* attr)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
return ldap_get_values_len(this->ldap, entry, (char*) attr);
}
bool WinLdapClient::init(const std::string &host, int port)
{
this->ldap = ldap_init((char*) host.c_str(), port);
this->retval = LdapGetLastError();
return this->retval == LDAP_SUCCESS;
}
bool WinLdapClient::msgFree(LDAPMessage* msg)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
this->retval = ldap_msgfree(msg);
return this->retval == LDAP_SUCCESS;
}
LDAPMessage* WinLdapClient::nextEntry(LDAPMessage* entry)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
return ldap_next_entry(this->ldap, entry);
}
bool WinLdapClient::search(const std::string& basedn,
int scope,
const std::string& filter,
char* attrs[],
int attrsonly,
LDAPControl** serverctrls,
LDAPControl** clientctrls,
const LdapClient::TimeVal& timeout,
int sizelimit,
LDAPMessage** results)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
struct l_timeval winldap_timeout;
this->setTimeval(timeout, winldap_timeout);
ldap_search_ext_s(this->ldap,
(char*) basedn.c_str(),
scope,
(char*) filter.c_str(),
attrs,
attrsonly,
serverctrls,
clientctrls,
&winldap_timeout,
sizelimit,
results);
return this->retval == LDAP_SUCCESS;
}
bool WinLdapClient::setOption(int option, void* invalue)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
this->retval = ldap_set_option(this->ldap,
option,
invalue);
return this->retval == LDAP_SUCCESS;
}
void WinLdapClient::setTimeval(const LdapClient::TimeVal& src, struct l_timeval& dest)
{
dest.tv_sec = (long) src.tv_sec;
dest.tv_usec = (long) src.tv_usec;
}
bool WinLdapClient::valueFreeLen(struct berval** val)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
this->retval = ldap_value_free_len(val);
return this->retval == LDAP_SUCCESS;
}
#endif // WINLDAP
//------------------------------------------------------------------------------
LdapClient* LdapClient::createInstance()
{
LdapClient* ldap = NULL;
#ifdef OPENLDAP
ldap = new OpenLdapClient();
#elif WINLDAP
ldap = new WinLdapClient();
#else
#error "You must specify an LDAP define for LdapClient."
#endif
return ldap;
}
//------------------------------------------------------------------------------
<commit_msg>fixed retval handling on ldap search<commit_after>#include "LdapClient.h"
//------------------------------------------------------------------------------
#ifdef OPENLDAP
#include <cstdlib> // free()
#include <sys/time.h> // struct timeval
#include <sstream> // std::stringstream
/** OpenLDAP client implementation */
class OpenLdapClient : public LdapClient
{
public:
OpenLdapClient() : LdapClient(), ldap(NULL), retval(LDAP_SUCCESS) { }
~OpenLdapClient();
bool bind(const std::string& dn,
const std::string& pass);
int getLastError() { return this->retval; }
std::string getLastErrorMsg() { return std::string(ldap_err2string(this->retval)); }
struct berval** getValuesLen(LDAPMessage* entry,
const char* attr);
int countEntries(LDAPMessage* result);
LDAPMessage* firstEntry(LDAPMessage* result);
bool init(const std::string& host,
int port);
bool msgFree(LDAPMessage* msg);
LDAPMessage* nextEntry(LDAPMessage* entry);
bool search(const std::string& basedn,
int scope,
const std::string& filter,
char* attrs[],
int attrsonly,
LDAPControl** serverctrls,
LDAPControl** clientctrls,
const LdapClient::TimeVal& timeout,
int sizelimit,
LDAPMessage** results);
bool setOption(int option,
void *invalue);
bool valueFreeLen(struct berval** val);
private:
void setTimeval(const LdapClient::TimeVal& src, struct timeval& dest);
private:
LDAP* ldap;
int retval;
};
OpenLdapClient::~OpenLdapClient()
{
ldap_unbind_ext(this->ldap, NULL, NULL);
free(this->ldap);
this->ldap = NULL;
}
bool OpenLdapClient::bind(const std::string& dn,
const std::string& passwd)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
LDAPControl *serverctrls=NULL, *clientctrls=NULL;
struct berval *servercredp=NULL;
struct berval creds;
creds.bv_val = strdup( passwd.c_str() );
creds.bv_len = passwd.length();
this->retval = ldap_sasl_bind_s(ldap,
dn.c_str(),
LDAP_SASL_SIMPLE,
&creds,
&serverctrls,
&clientctrls,
&servercredp);
return this->retval == LDAP_SUCCESS;
}
int OpenLdapClient::countEntries(LDAPMessage* result)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
int num_entries = ldap_count_entries(ldap, result);
this->retval = LDAP_OTHER;
return num_entries;
}
LDAPMessage* OpenLdapClient::firstEntry(LDAPMessage* result)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
LDAPMessage* msg = ldap_first_message(ldap, result);
this->retval = LDAP_OTHER;
return msg;
}
struct berval** OpenLdapClient::getValuesLen(LDAPMessage* entry,
const char* attr)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
return ldap_get_values_len(this->ldap, entry, attr);
}
bool OpenLdapClient::init(const std::string& host, int port)
{
if (this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
std::stringstream uri_buf;
uri_buf << "ldap://" << host << ':' << port;
this->retval = ldap_initialize(&this->ldap, uri_buf.str().c_str());
return this->retval == LDAP_SUCCESS;
}
bool OpenLdapClient::msgFree(LDAPMessage* msg)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
this->retval = ldap_msgfree(msg);
return this->retval == LDAP_SUCCESS;
}
LDAPMessage* OpenLdapClient::nextEntry(LDAPMessage* entry)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
return ldap_next_entry(this->ldap, entry);
}
bool OpenLdapClient::search(const std::string& basedn,
int scope,
const std::string& filter,
char* attrs[],
int attrsonly,
LDAPControl** serverctrls,
LDAPControl** clientctrls,
const LdapClient::TimeVal& timeout,
int sizelimit,
LDAPMessage** results)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
struct timeval openldap_timeout;
this->setTimeval(timeout, openldap_timeout);
ldap_search_ext_s(this->ldap,
basedn.c_str(),
scope,
filter.c_str(),
attrs,
attrsonly,
serverctrls,
clientctrls,
&openldap_timeout,
sizelimit,
results);
return this->retval == LDAP_SUCCESS;
}
bool OpenLdapClient::setOption(int option, void* invalue)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
this->retval = ldap_set_option(this->ldap,
option,
invalue);
return this->retval == LDAP_SUCCESS;
}
void OpenLdapClient::setTimeval(const LdapClient::TimeVal& src, struct timeval& dest)
{
dest.tv_sec = src.tv_sec;
dest.tv_usec = src.tv_usec;
}
bool OpenLdapClient::valueFreeLen(struct berval** val)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
ldap_value_free_len(val);
this->retval = LDAP_SUCCESS;
return this->retval == LDAP_SUCCESS;
}
#endif // OPENLDAP
//------------------------------------------------------------------------------
#ifdef WINLDAP
/** Microsoft Windows LDAP client implementation */
class WinLdapClient : public LdapClient
{
public:
WinLdapClient() : ldap(NULL), retval(LDAP_SUCCESS) { }
~WinLdapClient();
bool bind(const std::string& dn,
const std::string& passwd);
int countEntries(LDAPMessage* result);
LDAPMessage* firstEntry(LDAPMessage* result);
int getLastError() { return this->retval; }
std::string getLastErrorMsg() { return std::string(ldap_err2string(this->retval)); }
struct berval** getValuesLen(LDAPMessage* entry,
const char* attr);
bool init(const std::string& host,
int port);
bool msgFree(LDAPMessage* msg);
LDAPMessage* nextEntry(LDAPMessage* entry);
bool search(const std::string& basedn,
int scope,
const std::string& filter,
char* attrs[],
int attrsonly,
LDAPControl** serverctrls,
LDAPControl** clientctrls,
const LdapClient::TimeVal& timeout,
int sizelimit,
LDAPMessage** results);
bool setOption(int option,
void *invalue);
bool valueFreeLen(struct berval** val);
private:
void setTimeval(const LdapClient::TimeVal& src, struct l_timeval& dest);
private:
LDAP* ldap;
int retval;
};
WinLdapClient::~WinLdapClient()
{
ldap_unbind(this->ldap);
free(this->ldap);
this->ldap = NULL;
}
bool WinLdapClient::bind(const std::string& dn,
const std::string& passwd)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
this->retval = ldap_simple_bind_s(this->ldap,
(char*) dn.c_str(),
(char*) passwd.c_str());
return this->retval == LDAP_SUCCESS;
}
int WinLdapClient::countEntries(LDAPMessage* result)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
int num_entries = ldap_count_entries(ldap, result);
this->retval = LDAP_OTHER;
return num_entries;
}
LDAPMessage* WinLdapClient::firstEntry(LDAPMessage* result)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
LDAPMessage* msg = ldap_first_entry(ldap, result);
this->retval = LDAP_OTHER;
return msg;
}
struct berval** WinLdapClient::getValuesLen(LDAPMessage* entry,
const char* attr)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
return ldap_get_values_len(this->ldap, entry, (char*) attr);
}
bool WinLdapClient::init(const std::string &host, int port)
{
this->ldap = ldap_init((char*) host.c_str(), port);
this->retval = LdapGetLastError();
return this->retval == LDAP_SUCCESS;
}
bool WinLdapClient::msgFree(LDAPMessage* msg)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
this->retval = ldap_msgfree(msg);
return this->retval == LDAP_SUCCESS;
}
LDAPMessage* WinLdapClient::nextEntry(LDAPMessage* entry)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
return ldap_next_entry(this->ldap, entry);
}
bool WinLdapClient::search(const std::string& basedn,
int scope,
const std::string& filter,
char* attrs[],
int attrsonly,
LDAPControl** serverctrls,
LDAPControl** clientctrls,
const LdapClient::TimeVal& timeout,
int sizelimit,
LDAPMessage** results)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
struct l_timeval winldap_timeout;
this->setTimeval(timeout, winldap_timeout);
this->retval = ldap_search_ext_s(this->ldap,
(char*) basedn.c_str(),
scope,
(char*) filter.c_str(),
attrs,
attrsonly,
serverctrls,
clientctrls,
&winldap_timeout,
sizelimit,
results);
return this->retval == LDAP_SUCCESS;
}
bool WinLdapClient::setOption(int option, void* invalue)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
this->retval = ldap_set_option(this->ldap,
option,
invalue);
return this->retval == LDAP_SUCCESS;
}
void WinLdapClient::setTimeval(const LdapClient::TimeVal& src, struct l_timeval& dest)
{
dest.tv_sec = (long) src.tv_sec;
dest.tv_usec = (long) src.tv_usec;
}
bool WinLdapClient::valueFreeLen(struct berval** val)
{
if (!this->ldap) {
this->retval = LDAP_CONNECT_ERROR;
return false;
}
this->retval = ldap_value_free_len(val);
return this->retval == LDAP_SUCCESS;
}
#endif // WINLDAP
//------------------------------------------------------------------------------
LdapClient* LdapClient::createInstance()
{
LdapClient* ldap = NULL;
#ifdef OPENLDAP
ldap = new OpenLdapClient();
#elif WINLDAP
ldap = new WinLdapClient();
#else
#error "You must specify an LDAP define for LdapClient."
#endif
return ldap;
}
//------------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*
* Copyright 2009 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <fstream>
#include <vector>
#include <boost/lexical_cast.hpp>
#include "tokenizer.h"
#include "table.h"
#include <stdexcept>
#include <iostream>
#include <boost/algorithm/string/replace.hpp>
using namespace boost;
using namespace std;
void Table::resize(int N, bool preserve)
{
_x.resize(N, preserve);
_y.resize(N, preserve);
_flags.resize(N, preserve);
if (_has_yerr) {
_yerr.resize(N, preserve);
}
}
void Table::Load(string filename)
{
ifstream in;
in.open(filename.c_str());
if(!in)
throw runtime_error(string("error, cannot open file ") + filename);
in >> *this;
in.close();
}
void Table::Save(string filename) const
{
ofstream out;
out.open(filename.c_str());
if(!out)
throw runtime_error(string("error, cannot open file ") + filename);
if (_has_comment) {
string str = "# " + _comment_line;
boost::replace_all(str, "\\n", "\n# ");
out << str <<endl;
}
out << (*this);
out.close();
}
void Table::clear(void)
{
_x.clear();
_y.clear();
_flags.clear();
_yerr.clear();
}
// TODO: this functon is weired, reading occours twice, cleanup!!
// TODO: modify function to work properly, when _has_yerr is true
inline istream &operator>>(istream &in, Table& t)
{
size_t N;
bool bHasN=false;
string line;
t.clear();
// read till the first data line
while(getline(in, line)) {
// remove comments and xmgrace stuff
line = line.substr(0, line.find("#"));
line = line.substr(0, line.find("@"));
// tokenize string and put it to vector
Tokenizer tok(line, " \t");
vector<string> tokens;
tok.ToVector(tokens);
// skip empty lines
if(tokens.size()==0) continue;
// if first line is only 1 token, it's the size
if(tokens.size() == 1) {
N = lexical_cast<int>(tokens[0]);
bHasN = true;
}
// it's the first data line with 2 or 3 entries
else if(tokens.size() == 2) {
t.push_back(lexical_cast<double>(tokens[0]), lexical_cast<double>(tokens[1]), 'i');
}
else if(tokens.size() > 2) {
char flag='i';
if(tokens[2] == "i" || tokens[2] == "o" || tokens[2] == "u")
flag = tokens[2].c_str()[0];
t.push_back(lexical_cast<double>(tokens[0]), lexical_cast<double>(tokens[1]), flag);
}
else throw runtime_error("error, wrong table format");
}
// read the rest
while(getline(in, line)) {
// remove comments and xmgrace stuff
line = line.substr(0, line.find("#"));
line = line.substr(0, line.find("@"));
// tokenize string and put it to vector
Tokenizer tok(line, " \t");
vector<string> tokens;
tok.ToVector(tokens);
// skip empty lines
if(tokens.size()==0) continue;
// it's a data line
if(tokens.size() == 2) {
t.push_back(lexical_cast<double>(tokens[0]), lexical_cast<double>(tokens[1]), 'i');
}
else if(tokens.size() > 2) {
char flag='i';
if(tokens[2] == "i" || tokens[2] == "o" || tokens[2] == "u")
flag = tokens[2].c_str()[0];
t.push_back(lexical_cast<double>(tokens[0]), lexical_cast<double>(tokens[1]), flag);
}
// otherwise error
else throw runtime_error("error, wrong table format");
// was size given and did we read N values?
if(bHasN)
if(--N == 0) break;
}
return in;
}
void Table::GenerateGridSpacing(double min, double max, double spacing)
{
int n = floor((max - min)/spacing + 1.000000001);
resize(n);
int i=0;
for(double x=min; i<n; x+=spacing, ++i)
_x[i] = x;
}
void Table::Smooth(int Nsmooth)
{
while(Nsmooth-- > 0)
for(int i=1; i<size()-1; ++i)
_y[i] =0.25*(_y[i-1] + 2*_y[i] + _y[i+1]);
}
<commit_msg>table, also replace normal \n<commit_after>/*
* Copyright 2009 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <fstream>
#include <vector>
#include <boost/lexical_cast.hpp>
#include "tokenizer.h"
#include "table.h"
#include <stdexcept>
#include <iostream>
#include <boost/algorithm/string/replace.hpp>
using namespace boost;
using namespace std;
void Table::resize(int N, bool preserve)
{
_x.resize(N, preserve);
_y.resize(N, preserve);
_flags.resize(N, preserve);
if (_has_yerr) {
_yerr.resize(N, preserve);
}
}
void Table::Load(string filename)
{
ifstream in;
in.open(filename.c_str());
if(!in)
throw runtime_error(string("error, cannot open file ") + filename);
in >> *this;
in.close();
}
void Table::Save(string filename) const
{
ofstream out;
out.open(filename.c_str());
if(!out)
throw runtime_error(string("error, cannot open file ") + filename);
if (_has_comment) {
string str = "# " + _comment_line;
boost::replace_all(str, "\n", "\n# ");
boost::replace_all(str, "\\n", "\n# ");
out << str <<endl;
}
out << (*this);
out.close();
}
void Table::clear(void)
{
_x.clear();
_y.clear();
_flags.clear();
_yerr.clear();
}
// TODO: this functon is weired, reading occours twice, cleanup!!
// TODO: modify function to work properly, when _has_yerr is true
inline istream &operator>>(istream &in, Table& t)
{
size_t N;
bool bHasN=false;
string line;
t.clear();
// read till the first data line
while(getline(in, line)) {
// remove comments and xmgrace stuff
line = line.substr(0, line.find("#"));
line = line.substr(0, line.find("@"));
// tokenize string and put it to vector
Tokenizer tok(line, " \t");
vector<string> tokens;
tok.ToVector(tokens);
// skip empty lines
if(tokens.size()==0) continue;
// if first line is only 1 token, it's the size
if(tokens.size() == 1) {
N = lexical_cast<int>(tokens[0]);
bHasN = true;
}
// it's the first data line with 2 or 3 entries
else if(tokens.size() == 2) {
t.push_back(lexical_cast<double>(tokens[0]), lexical_cast<double>(tokens[1]), 'i');
}
else if(tokens.size() > 2) {
char flag='i';
if(tokens[2] == "i" || tokens[2] == "o" || tokens[2] == "u")
flag = tokens[2].c_str()[0];
t.push_back(lexical_cast<double>(tokens[0]), lexical_cast<double>(tokens[1]), flag);
}
else throw runtime_error("error, wrong table format");
}
// read the rest
while(getline(in, line)) {
// remove comments and xmgrace stuff
line = line.substr(0, line.find("#"));
line = line.substr(0, line.find("@"));
// tokenize string and put it to vector
Tokenizer tok(line, " \t");
vector<string> tokens;
tok.ToVector(tokens);
// skip empty lines
if(tokens.size()==0) continue;
// it's a data line
if(tokens.size() == 2) {
t.push_back(lexical_cast<double>(tokens[0]), lexical_cast<double>(tokens[1]), 'i');
}
else if(tokens.size() > 2) {
char flag='i';
if(tokens[2] == "i" || tokens[2] == "o" || tokens[2] == "u")
flag = tokens[2].c_str()[0];
t.push_back(lexical_cast<double>(tokens[0]), lexical_cast<double>(tokens[1]), flag);
}
// otherwise error
else throw runtime_error("error, wrong table format");
// was size given and did we read N values?
if(bHasN)
if(--N == 0) break;
}
return in;
}
void Table::GenerateGridSpacing(double min, double max, double spacing)
{
int n = floor((max - min)/spacing + 1.000000001);
resize(n);
int i=0;
for(double x=min; i<n; x+=spacing, ++i)
_x[i] = x;
}
void Table::Smooth(int Nsmooth)
{
while(Nsmooth-- > 0)
for(int i=1; i<size()-1; ++i)
_y[i] =0.25*(_y[i-1] + 2*_y[i] + _y[i+1]);
}
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <sstream>
#include <string>
#include <stdio.h>
#include <string.h>
#include "config.h"
// opaque version number increments on protocol incompatibility
#ifndef BZ_PROTO_VERSION
#define BZ_PROTO_VERSION "0021"
#endif
#ifndef BZ_MAJOR_VERSION
#define BZ_MAJOR_VERSION 1
#endif
#ifndef BZ_MINOR_VERSION
#define BZ_MINOR_VERSION 11
#endif
#ifndef BZ_REV
#define BZ_REV 31
#endif
// DEVEL | STABLE | MAINT
#ifndef BZ_BUILD_TYPE
#define BZ_BUILD_TYPE "DEVEL"
#endif
const char *bzfcopyright = "Copyright (c) 1993 - 2004 Tim Riker";
#ifndef BZ_BUILD_DATE
/* to get the version in the right format YYYYMMDD */
/* yes this is horible but it needs to be done to get it right */
/* windows should pull from a resouce */
/* *nix gets this from the passed from my the Makefile */
char buildDate[] = {__DATE__};
int getBuildDate()
{
int year = 1900, month = 0, day = 0;
char monthStr[512];
sscanf(buildDate, "%s %d %d", monthStr, &day, &year);
// we want it not as a name but a number
if (strcmp(monthStr, "Jan") == 0)
month = 1;
else if (strcmp(monthStr, "Feb") == 0)
month = 2;
else if (strcmp(monthStr, "Mar") == 0)
month = 3;
else if (strcmp(monthStr, "Apr") == 0)
month = 4;
else if (strcmp(monthStr, "May") == 0)
month = 5;
else if (strcmp(monthStr, "Jun") == 0)
month = 6;
else if (strcmp(monthStr, "Jul") == 0)
month = 7;
else if (strcmp(monthStr, "Aug") == 0)
month = 8;
else if (strcmp(monthStr, "Sep") == 0)
month = 9;
else if (strcmp(monthStr, "Oct") == 0)
month = 10;
else if (strcmp(monthStr, "Nov") == 0)
month = 11;
else if (strcmp(monthStr, "Dec") == 0)
month = 12;
return (year*10000) + (month*100)+ day;
}
#endif
// down here so above gets created
#include "version.h"
const char* getProtocolVersion()
{
static std::string protVersion = BZ_PROTO_VERSION;
return protVersion.c_str();
}
const char* getServerVersion()
{
static std::string serverVersion = std::string("BZFS") + getProtocolVersion();
return serverVersion.c_str();
}
const char* getAppVersion()
{
static std::string appVersion = "";
if (!appVersion.size()){
std::ostringstream appVersionStream;
// TODO add current platform, release, cpu, etc
appVersionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION << "." << BZ_REV << "." << BZ_BUILD_DATE
<< "-" << BZ_BUILD_TYPE << "-" << BZ_BUILD_OS;
#ifdef HAVE_SDL
appVersionStream << "-SDL";
#endif
appVersion = appVersionStream.str();
}
return appVersion.c_str();
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>places to touch<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <sstream>
#include <string>
#include <stdio.h>
#include <string.h>
#include "config.h"
// opaque version number increments on protocol incompatibility
#ifndef BZ_PROTO_VERSION
#define BZ_PROTO_VERSION "0021"
#endif
// version numbers - also update:
// ChangeLog
// README
// package/win32/nsis/*.nsi
// package/win32/*.nsi
// src/platform/MacOSX/BZFlag-Info.plist
// tools/TextTool-W32/TextTool.rc
// win32/VC6/installer.dsp
#ifndef BZ_MAJOR_VERSION
#define BZ_MAJOR_VERSION 1
#endif
#ifndef BZ_MINOR_VERSION
#define BZ_MINOR_VERSION 11
#endif
#ifndef BZ_REV
#define BZ_REV 31
#endif
// DEVEL | STABLE | MAINT
#ifndef BZ_BUILD_TYPE
#define BZ_BUILD_TYPE "DEVEL"
#endif
const char *bzfcopyright = "Copyright (c) 1993 - 2004 Tim Riker";
#ifndef BZ_BUILD_DATE
/* to get the version in the right format YYYYMMDD */
/* yes this is horible but it needs to be done to get it right */
/* windows should pull from a resouce */
/* *nix gets this from the passed from my the Makefile */
char buildDate[] = {__DATE__};
int getBuildDate()
{
int year = 1900, month = 0, day = 0;
char monthStr[512];
sscanf(buildDate, "%s %d %d", monthStr, &day, &year);
// we want it not as a name but a number
if (strcmp(monthStr, "Jan") == 0)
month = 1;
else if (strcmp(monthStr, "Feb") == 0)
month = 2;
else if (strcmp(monthStr, "Mar") == 0)
month = 3;
else if (strcmp(monthStr, "Apr") == 0)
month = 4;
else if (strcmp(monthStr, "May") == 0)
month = 5;
else if (strcmp(monthStr, "Jun") == 0)
month = 6;
else if (strcmp(monthStr, "Jul") == 0)
month = 7;
else if (strcmp(monthStr, "Aug") == 0)
month = 8;
else if (strcmp(monthStr, "Sep") == 0)
month = 9;
else if (strcmp(monthStr, "Oct") == 0)
month = 10;
else if (strcmp(monthStr, "Nov") == 0)
month = 11;
else if (strcmp(monthStr, "Dec") == 0)
month = 12;
return (year*10000) + (month*100)+ day;
}
#endif
// down here so above gets created
#include "version.h"
const char* getProtocolVersion()
{
static std::string protVersion = BZ_PROTO_VERSION;
return protVersion.c_str();
}
const char* getServerVersion()
{
static std::string serverVersion = std::string("BZFS") + getProtocolVersion();
return serverVersion.c_str();
}
const char* getAppVersion()
{
static std::string appVersion = "";
if (!appVersion.size()){
std::ostringstream appVersionStream;
// TODO add current platform, release, cpu, etc
appVersionStream << BZ_MAJOR_VERSION << "." << BZ_MINOR_VERSION << "." << BZ_REV << "." << BZ_BUILD_DATE
<< "-" << BZ_BUILD_TYPE << "-" << BZ_BUILD_OS;
#ifdef HAVE_SDL
appVersionStream << "-SDL";
#endif
appVersion = appVersionStream.str();
}
return appVersion.c_str();
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkInformation.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkInformation.h"
#include "vtkInformationExecutivePortKey.h"
#include "vtkInformationExecutivePortVectorKey.h"
#include "vtkInformationKeyVectorKey.h"
//----------------------------------------------------------------------------
void vtkInformation::CopyEntry(vtkInformation* from,
vtkInformationExecutivePortKey* key, int)
{
key->ShallowCopy(from, this);
}
//----------------------------------------------------------------------------
void vtkInformation::Append(vtkInformationKeyVectorKey* key,
vtkInformationExecutivePortKey* value)
{
key->Append(this, value);
}
//----------------------------------------------------------------------------
void vtkInformation::AppendUnique(vtkInformationKeyVectorKey* key,
vtkInformationExecutivePortKey* value)
{
key->AppendUnique(this, value);
}
//----------------------------------------------------------------------------
void vtkInformation::Set(vtkInformationExecutivePortKey* key,
vtkExecutive* executive, int port)
{
key->Set(this, executive, port);
}
//----------------------------------------------------------------------------
void vtkInformation::Remove(vtkInformationExecutivePortKey* key)
{
key->Remove(this);
}
//----------------------------------------------------------------------------
vtkExecutive* vtkInformation::GetExecutive(vtkInformationExecutivePortKey* key)
{
return key->GetExecutive(this);
}
//----------------------------------------------------------------------------
int vtkInformation::GetPort(vtkInformationExecutivePortKey* key)
{
return key->GetPort(this);
}
//----------------------------------------------------------------------------
void vtkInformation::Get(vtkInformationExecutivePortKey* key,
vtkExecutive*& executive, int &port)
{
key->Get(this,executive,port);
}
//----------------------------------------------------------------------------
int vtkInformation::Has(vtkInformationExecutivePortKey* key)
{
return key->Has(this);
}
//----------------------------------------------------------------------------
void vtkInformation::Append(vtkInformationExecutivePortVectorKey* key,
vtkExecutive* executive, int port)
{
key->Append(this, executive, port);
}
//----------------------------------------------------------------------------
void vtkInformation::Remove(vtkInformationExecutivePortVectorKey* key,
vtkExecutive* executive, int port)
{
key->Remove(this, executive, port);
}
//----------------------------------------------------------------------------
void vtkInformation::Set(vtkInformationExecutivePortVectorKey* key,
vtkExecutive** executives, int* ports, int length)
{
key->Set(this, executives, ports, length);
}
//----------------------------------------------------------------------------
vtkExecutive**
vtkInformation::GetExecutives(vtkInformationExecutivePortVectorKey* key)
{
return key->GetExecutives(this);
}
//----------------------------------------------------------------------------
int*
vtkInformation::GetPorts(vtkInformationExecutivePortVectorKey* key)
{
return key->GetPorts(this);
}
//----------------------------------------------------------------------------
void vtkInformation::Get(vtkInformationExecutivePortVectorKey* key,
vtkExecutive** executives, int* ports)
{
key->Get(this, executives, ports);
}
//----------------------------------------------------------------------------
int vtkInformation::Length(vtkInformationExecutivePortVectorKey* key)
{
return key->Length(this);
}
//----------------------------------------------------------------------------
void vtkInformation::Remove(vtkInformationExecutivePortVectorKey* key)
{
key->Remove(this);
}
//----------------------------------------------------------------------------
int vtkInformation::Has(vtkInformationExecutivePortVectorKey* key)
{
return key->Has(this);
}
//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationExecutivePortKey* key)
{
return key;
}
<commit_msg>COMP: Try to eliminate "inconsistent DLL linkage" warnings on Win32/64.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkInformation.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkInformationExecutivePortKey.h"
#include "vtkInformationExecutivePortVectorKey.h"
#include "vtkInformationKeyVectorKey.h"
#include "vtkObject.h"
#ifdef __vtkInformation_h
# error "vtkInformation.h must not be included before this line."
#endif // __vtkInformation_h
#undef VTK_COMMON_EXPORT
#define VTK_COMMON_EXPORT VTK_FILTERING_EXPORT
#include "vtkInformation.h" // Must be last include
//----------------------------------------------------------------------------
void vtkInformation::CopyEntry(vtkInformation* from,
vtkInformationExecutivePortKey* key, int)
{
key->ShallowCopy(from, this);
}
//----------------------------------------------------------------------------
void vtkInformation::Append(vtkInformationKeyVectorKey* key,
vtkInformationExecutivePortKey* value)
{
key->Append(this, value);
}
//----------------------------------------------------------------------------
void vtkInformation::AppendUnique(vtkInformationKeyVectorKey* key,
vtkInformationExecutivePortKey* value)
{
key->AppendUnique(this, value);
}
//----------------------------------------------------------------------------
void vtkInformation::Set(vtkInformationExecutivePortKey* key,
vtkExecutive* executive, int port)
{
key->Set(this, executive, port);
}
//----------------------------------------------------------------------------
void vtkInformation::Remove(vtkInformationExecutivePortKey* key)
{
key->Remove(this);
}
//----------------------------------------------------------------------------
vtkExecutive* vtkInformation::GetExecutive(vtkInformationExecutivePortKey* key)
{
return key->GetExecutive(this);
}
//----------------------------------------------------------------------------
int vtkInformation::GetPort(vtkInformationExecutivePortKey* key)
{
return key->GetPort(this);
}
//----------------------------------------------------------------------------
void vtkInformation::Get(vtkInformationExecutivePortKey* key,
vtkExecutive*& executive, int &port)
{
key->Get(this,executive,port);
}
//----------------------------------------------------------------------------
int vtkInformation::Has(vtkInformationExecutivePortKey* key)
{
return key->Has(this);
}
//----------------------------------------------------------------------------
void vtkInformation::Append(vtkInformationExecutivePortVectorKey* key,
vtkExecutive* executive, int port)
{
key->Append(this, executive, port);
}
//----------------------------------------------------------------------------
void vtkInformation::Remove(vtkInformationExecutivePortVectorKey* key,
vtkExecutive* executive, int port)
{
key->Remove(this, executive, port);
}
//----------------------------------------------------------------------------
void vtkInformation::Set(vtkInformationExecutivePortVectorKey* key,
vtkExecutive** executives, int* ports, int length)
{
key->Set(this, executives, ports, length);
}
//----------------------------------------------------------------------------
vtkExecutive**
vtkInformation::GetExecutives(vtkInformationExecutivePortVectorKey* key)
{
return key->GetExecutives(this);
}
//----------------------------------------------------------------------------
int*
vtkInformation::GetPorts(vtkInformationExecutivePortVectorKey* key)
{
return key->GetPorts(this);
}
//----------------------------------------------------------------------------
void vtkInformation::Get(vtkInformationExecutivePortVectorKey* key,
vtkExecutive** executives, int* ports)
{
key->Get(this, executives, ports);
}
//----------------------------------------------------------------------------
int vtkInformation::Length(vtkInformationExecutivePortVectorKey* key)
{
return key->Length(this);
}
//----------------------------------------------------------------------------
void vtkInformation::Remove(vtkInformationExecutivePortVectorKey* key)
{
key->Remove(this);
}
//----------------------------------------------------------------------------
int vtkInformation::Has(vtkInformationExecutivePortVectorKey* key)
{
return key->Has(this);
}
//----------------------------------------------------------------------------
vtkInformationKey* vtkInformation::GetKey(vtkInformationExecutivePortKey* key)
{
return key;
}
<|endoftext|> |
<commit_before>/// XXX add licence
//
#ifndef HAVE_LLVM
# error "Need LLVM for LLVMDependenceGraph"
#endif
#ifndef ENABLE_CFG
#error "Need CFG enabled for building LLVM Dependence Graph"
#endif
#include <llvm/IR/Instruction.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Value.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/Support/raw_ostream.h>
#include "LLVMNode.h"
#include "LLVMDependenceGraph.h"
using llvm::errs;
namespace dg {
LLVMNode::~LLVMNode()
{
if (owns_key)
delete getKey();
delete memoryobj;
delete[] operands;
}
void LLVMNode::dump() const
{
getKey()->dump();
}
LLVMNode **LLVMNode::findOperands()
{
using namespace llvm;
const Value *val = getKey();
// FIXME use op_begin() and op_end() and do it generic
// for all the instructions (+ maybe some speacial handling
// like CallInst?)
// we have Function nodes stored in globals
if (isa<AllocaInst>(val)) {
operands = new LLVMNode *[1];
operands[0] = dg->getNode(val);
operands_num = 1;
} else if (const StoreInst *Inst = dyn_cast<StoreInst>(val)) {
operands = new LLVMNode *[2];
operands[0] = dg->getNode(Inst->getPointerOperand());
operands[1] = dg->getNode(Inst->getValueOperand());
#ifdef DEBUG_ENABLED
if (!operands[0] && !isa<Constant>(Inst->getPointerOperand()))
errs() << "WARN: Didn't found pointer for " << *Inst << "\n";
if (!operands[1] && !isa<Constant>(Inst->getValueOperand()))
errs() << "WARN: Didn't found value for " << *Inst << "\n";
#endif
operands_num = 2;
} else if (const LoadInst *Inst = dyn_cast<LoadInst>(val)) {
operands = new LLVMNode *[1];
const Value *op = Inst->getPointerOperand();
operands[0] = dg->getNode(op);
#ifdef DEBUG_ENABLED
if (!operands[0])
errs() << "WARN: Didn't found pointer for " << *Inst << "\n";
#endif
operands_num = 1;
} else if (const GetElementPtrInst *Inst = dyn_cast<GetElementPtrInst>(val)) {
operands = new LLVMNode *[1];
operands[0] = dg->getNode(Inst->getPointerOperand());
operands_num = 1;
} else if (const CallInst *Inst = dyn_cast<CallInst>(val)) {
// we store the called function as a first operand
// and all the arguments as the other operands
operands_num = Inst->getNumArgOperands() + 1;
operands = new LLVMNode *[operands_num];
operands[0] = dg->getNode(Inst->getCalledValue());
for (unsigned i = 0; i < operands_num - 1; ++i)
operands[i + 1] = dg->getNode(Inst->getArgOperand(i));
} else if (const ReturnInst *Inst = dyn_cast<ReturnInst>(val)) {
operands = new LLVMNode *[1];
operands[0] = dg->getNode(Inst->getReturnValue());
operands_num = 1;
} else if (const CastInst *Inst = dyn_cast<CastInst>(val)) {
operands = new LLVMNode *[1];
operands[0] = dg->getNode(Inst->stripPointerCasts());
if (!operands[0])
errs() << "WARN: CastInst with unstrippable pointer cast" << *Inst << "\n";
operands_num = 1;
}
if (!operands) {
errs() << "Unhandled instruction: " << *val
<< "Type: " << *val->getType() << "\n";
abort();
}
return operands;
}
void LLVMNode::addActualParameters(LLVMDependenceGraph *funcGraph)
{
using namespace llvm;
const CallInst *CInst = dyn_cast<CallInst>(key);
assert(CInst && "addActualParameters called on non-CallInst");
// do not add redundant nodes
const Function *func = CInst->getCalledFunction();
if (!func || func->arg_size() == 0)
return;
addActualParameters(funcGraph, func);
}
void LLVMNode::addActualParameters(LLVMDependenceGraph *funcGraph,
const llvm::Function *func)
{
using namespace llvm;
const CallInst *CInst = dyn_cast<CallInst>(key);
assert(CInst && "addActualParameters called on non-CallInst");
// do not do nothing if we have parameters.
// This is probably adding subgraph due to function
// pointer in data-flow analysis
if (getParameters())
return;
LLVMDGParameters *formal = funcGraph->getParameters();
LLVMDGParameters *params = new LLVMDGParameters();
LLVMDGParameters *old = addParameters(params);
assert(old == nullptr && "Replaced parameters");
// we need to add edges from actual parameters to formal parameteres
// so if the params exists, just add the edges. If the params
// do not exists, create them and then add the edges
LLVMNode *in, *out;
int idx = 0;
for (auto A = func->arg_begin(), E = func->arg_end();
A != E; ++A, ++idx) {
const Value *opval = CInst->getArgOperand(idx);
LLVMDGParameter *fp = formal->find(&*A);
if (!fp) {
errs() << "ERR: no formal param for value: " << *opval << "\n";
continue;
}
in = new LLVMNode(opval);
out = new LLVMNode(opval);
params->add(opval, in, out, fp);
// add control edges from the call-site node
// to the parameters
addControlDependence(in);
addControlDependence(out);
// from actual in to formal in
in->addDataDependence(fp->in);
// from formal out to actual out
fp->out->addDataDependence(out);
}
}
LLVMNode **LLVMNode::getOperands()
{
if (!operands)
findOperands();
return operands;
}
size_t LLVMNode::getOperandsNum()
{
if (!operands)
findOperands();
return operands_num;
}
LLVMNode *LLVMNode::getOperand(unsigned int idx)
{
if (!operands)
findOperands();
assert(operands_num > idx && "idx is too high");
return operands[idx];
}
LLVMNode *LLVMNode::setOperand(LLVMNode *op, unsigned int idx)
{
assert(operands && "Operands has not been found yet");
assert(operands_num > idx && "idx is too high");
LLVMNode *old = operands[idx];
operands[idx] = op;
return old;
}
} // namespace dg
<commit_msg>llvmnode: make actual params be aware of function pointers<commit_after>/// XXX add licence
//
#ifndef HAVE_LLVM
# error "Need LLVM for LLVMDependenceGraph"
#endif
#ifndef ENABLE_CFG
#error "Need CFG enabled for building LLVM Dependence Graph"
#endif
#include <llvm/IR/Instruction.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Value.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/Support/raw_ostream.h>
#include "LLVMNode.h"
#include "LLVMDependenceGraph.h"
using llvm::errs;
namespace dg {
LLVMNode::~LLVMNode()
{
if (owns_key)
delete getKey();
delete memoryobj;
delete[] operands;
}
void LLVMNode::dump() const
{
getKey()->dump();
}
LLVMNode **LLVMNode::findOperands()
{
using namespace llvm;
const Value *val = getKey();
// FIXME use op_begin() and op_end() and do it generic
// for all the instructions (+ maybe some speacial handling
// like CallInst?)
// we have Function nodes stored in globals
if (isa<AllocaInst>(val)) {
operands = new LLVMNode *[1];
operands[0] = dg->getNode(val);
operands_num = 1;
} else if (const StoreInst *Inst = dyn_cast<StoreInst>(val)) {
operands = new LLVMNode *[2];
operands[0] = dg->getNode(Inst->getPointerOperand());
operands[1] = dg->getNode(Inst->getValueOperand());
#ifdef DEBUG_ENABLED
if (!operands[0] && !isa<Constant>(Inst->getPointerOperand()))
errs() << "WARN: Didn't found pointer for " << *Inst << "\n";
if (!operands[1] && !isa<Constant>(Inst->getValueOperand()))
errs() << "WARN: Didn't found value for " << *Inst << "\n";
#endif
operands_num = 2;
} else if (const LoadInst *Inst = dyn_cast<LoadInst>(val)) {
operands = new LLVMNode *[1];
const Value *op = Inst->getPointerOperand();
operands[0] = dg->getNode(op);
#ifdef DEBUG_ENABLED
if (!operands[0])
errs() << "WARN: Didn't found pointer for " << *Inst << "\n";
#endif
operands_num = 1;
} else if (const GetElementPtrInst *Inst = dyn_cast<GetElementPtrInst>(val)) {
operands = new LLVMNode *[1];
operands[0] = dg->getNode(Inst->getPointerOperand());
operands_num = 1;
} else if (const CallInst *Inst = dyn_cast<CallInst>(val)) {
// we store the called function as a first operand
// and all the arguments as the other operands
operands_num = Inst->getNumArgOperands() + 1;
operands = new LLVMNode *[operands_num];
operands[0] = dg->getNode(Inst->getCalledValue());
for (unsigned i = 0; i < operands_num - 1; ++i)
operands[i + 1] = dg->getNode(Inst->getArgOperand(i));
} else if (const ReturnInst *Inst = dyn_cast<ReturnInst>(val)) {
operands = new LLVMNode *[1];
operands[0] = dg->getNode(Inst->getReturnValue());
operands_num = 1;
} else if (const CastInst *Inst = dyn_cast<CastInst>(val)) {
operands = new LLVMNode *[1];
operands[0] = dg->getNode(Inst->stripPointerCasts());
if (!operands[0])
errs() << "WARN: CastInst with unstrippable pointer cast" << *Inst << "\n";
operands_num = 1;
}
if (!operands) {
errs() << "Unhandled instruction: " << *val
<< "Type: " << *val->getType() << "\n";
abort();
}
return operands;
}
void LLVMNode::addActualParameters(LLVMDependenceGraph *funcGraph)
{
using namespace llvm;
const CallInst *CInst = dyn_cast<CallInst>(key);
assert(CInst && "addActualParameters called on non-CallInst");
// do not add redundant nodes
const Function *func = CInst->getCalledFunction();
if (!func || func->arg_size() == 0)
return;
addActualParameters(funcGraph, func);
}
void LLVMNode::addActualParameters(LLVMDependenceGraph *funcGraph,
const llvm::Function *func)
{
using namespace llvm;
const CallInst *CInst = dyn_cast<CallInst>(key);
assert(CInst && "addActualParameters called on non-CallInst");
// if we have parameters, then use them and just
// add edges to formal parameters (a call-site can
// have more destinations if it is via function pointer)
LLVMDGParameters *params = getParameters();
if (!params) {
params = new LLVMDGParameters();
LLVMDGParameters *old = addParameters(params);
assert(old == nullptr && "Replaced parameters");
}
LLVMDGParameters *formal = funcGraph->getParameters();
LLVMNode *in, *out;
int idx = 0;
for (auto A = func->arg_begin(), E = func->arg_end();
A != E; ++A, ++idx) {
const Value *opval = CInst->getArgOperand(idx);
LLVMDGParameter *fp = formal->find(&*A);
if (!fp) {
errs() << "ERR: no formal param for value: " << *opval << "\n";
continue;
}
LLVMDGParameter *ap = params->find(opval);
if (!ap) {
in = new LLVMNode(opval);
out = new LLVMNode(opval);
params->add(opval, in, out);
} else {
in = ap->in;
out = ap->out;
}
// add control edges from the call-site node
// to the parameters
addControlDependence(in);
addControlDependence(out);
// from actual in to formal in
in->addDataDependence(fp->in);
// from formal out to actual out
fp->out->addDataDependence(out);
}
}
LLVMNode **LLVMNode::getOperands()
{
if (!operands)
findOperands();
return operands;
}
size_t LLVMNode::getOperandsNum()
{
if (!operands)
findOperands();
return operands_num;
}
LLVMNode *LLVMNode::getOperand(unsigned int idx)
{
if (!operands)
findOperands();
assert(operands_num > idx && "idx is too high");
return operands[idx];
}
LLVMNode *LLVMNode::setOperand(LLVMNode *op, unsigned int idx)
{
assert(operands && "Operands has not been found yet");
assert(operands_num > idx && "idx is too high");
LLVMNode *old = operands[idx];
operands[idx] = op;
return old;
}
} // namespace dg
<|endoftext|> |
<commit_before>/*
* Delegate helper pooling.
*
* author: Max Kellermann <[email protected]>
*/
#include "Stock.hxx"
#include "stock/MapStock.hxx"
#include "stock/Class.hxx"
#include "stock/Item.hxx"
#include "async.hxx"
#include "failure.hxx"
#include "system/fd_util.h"
#include "event/Event.hxx"
#include "event/Callback.hxx"
#include "spawn/Spawn.hxx"
#include "spawn/Prepared.hxx"
#include "spawn/ChildOptions.hxx"
#include "gerrno.h"
#include "pool.hxx"
#include <daemon/log.h>
#include <assert.h>
#include <unistd.h>
#include <sys/un.h>
#include <sys/socket.h>
struct DelegateArgs {
const char *executable_path;
const ChildOptions &options;
DelegateArgs(const char *_executable_path,
const ChildOptions &_options)
:executable_path(_executable_path), options(_options) {}
};
struct DelegateProcess final : HeapStockItem {
const pid_t pid;
const int fd;
Event event;
explicit DelegateProcess(CreateStockItem c,
pid_t _pid, int _fd)
:HeapStockItem(c), pid(_pid), fd(_fd) {
event.Set(fd, EV_READ|EV_TIMEOUT,
MakeEventCallback(DelegateProcess, EventCallback), this);
}
~DelegateProcess() override {
if (fd >= 0) {
event.Delete();
close(fd);
}
}
void EventCallback(int fd, short event);
/* virtual methods from class StockItem */
bool Borrow(gcc_unused void *ctx) override {
event.Delete();
return true;
}
bool Release(gcc_unused void *ctx) override {
static constexpr struct timeval tv = {
.tv_sec = 60,
.tv_usec = 0,
};
event.Add(tv);
return true;
}
};
/*
* libevent callback
*
*/
inline void
DelegateProcess::EventCallback(gcc_unused int _fd, short events)
{
assert(_fd == fd);
if ((events & EV_TIMEOUT) == 0) {
assert((events & EV_READ) != 0);
char buffer;
ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
if (nbytes < 0)
daemon_log(2, "error on idle delegate process: %s\n",
strerror(errno));
else if (nbytes > 0)
daemon_log(2, "unexpected data from idle delegate process\n");
}
InvokeIdleDisconnect();
pool_commit();
}
/*
* stock class
*
*/
static void
delegate_stock_create(gcc_unused void *ctx,
gcc_unused struct pool &parent_pool, CreateStockItem c,
gcc_unused const char *uri, void *_info,
gcc_unused struct pool &caller_pool,
gcc_unused struct async_operation_ref &async_ref)
{
auto &info = *(DelegateArgs *)_info;
PreparedChildProcess p;
p.Append(info.executable_path);
GError *error = nullptr;
if (!info.options.CopyTo(p, true, nullptr, &error)) {
c.InvokeCreateError(error);
return;
}
int fds[2];
if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
error = new_error_errno_msg("socketpair() failed: %s");
c.InvokeCreateError(error);
return;
}
p.stdin_fd = fds[1];
pid_t pid = SpawnChildProcess(std::move(p));
if (pid < 0) {
error = new_error_errno_msg2(-pid, "clone() failed");
close(fds[0]);
c.InvokeCreateError(error);
return;
}
auto *process = new DelegateProcess(c, pid, fds[0]);
process->InvokeCreateSuccess();
}
static constexpr StockClass delegate_stock_class = {
.create = delegate_stock_create,
};
/*
* interface
*
*/
StockMap *
delegate_stock_new(struct pool *pool)
{
return hstock_new(*pool, delegate_stock_class, nullptr, 0, 16);
}
StockItem *
delegate_stock_get(StockMap *delegate_stock, struct pool *pool,
const char *helper,
const ChildOptions &options,
GError **error_r)
{
const char *uri = helper;
char options_buffer[4096];
*options.MakeId(options_buffer) = 0;
if (*options_buffer != 0)
uri = p_strcat(pool, helper, "|", options_buffer, nullptr);
DelegateArgs args(helper, options);
return hstock_get_now(*delegate_stock, *pool, uri, &args, error_r);
}
int
delegate_stock_item_get(StockItem &item)
{
auto *process = (DelegateProcess *)&item;
return process->fd;
}
<commit_msg>delegate/Stock: move code to DelegateArgs::GetStockKey()<commit_after>/*
* Delegate helper pooling.
*
* author: Max Kellermann <[email protected]>
*/
#include "Stock.hxx"
#include "stock/MapStock.hxx"
#include "stock/Class.hxx"
#include "stock/Item.hxx"
#include "async.hxx"
#include "failure.hxx"
#include "system/fd_util.h"
#include "event/Event.hxx"
#include "event/Callback.hxx"
#include "spawn/Spawn.hxx"
#include "spawn/Prepared.hxx"
#include "spawn/ChildOptions.hxx"
#include "gerrno.h"
#include "pool.hxx"
#include <daemon/log.h>
#include <assert.h>
#include <unistd.h>
#include <sys/un.h>
#include <sys/socket.h>
struct DelegateArgs {
const char *executable_path;
const ChildOptions &options;
DelegateArgs(const char *_executable_path,
const ChildOptions &_options)
:executable_path(_executable_path), options(_options) {}
const char *GetStockKey(struct pool &pool) const {
const char *key = executable_path;
char options_buffer[4096];
*options.MakeId(options_buffer) = 0;
if (*options_buffer != 0)
key = p_strcat(&pool, key, "|", options_buffer, nullptr);
return key;
}
};
struct DelegateProcess final : HeapStockItem {
const pid_t pid;
const int fd;
Event event;
explicit DelegateProcess(CreateStockItem c,
pid_t _pid, int _fd)
:HeapStockItem(c), pid(_pid), fd(_fd) {
event.Set(fd, EV_READ|EV_TIMEOUT,
MakeEventCallback(DelegateProcess, EventCallback), this);
}
~DelegateProcess() override {
if (fd >= 0) {
event.Delete();
close(fd);
}
}
void EventCallback(int fd, short event);
/* virtual methods from class StockItem */
bool Borrow(gcc_unused void *ctx) override {
event.Delete();
return true;
}
bool Release(gcc_unused void *ctx) override {
static constexpr struct timeval tv = {
.tv_sec = 60,
.tv_usec = 0,
};
event.Add(tv);
return true;
}
};
/*
* libevent callback
*
*/
inline void
DelegateProcess::EventCallback(gcc_unused int _fd, short events)
{
assert(_fd == fd);
if ((events & EV_TIMEOUT) == 0) {
assert((events & EV_READ) != 0);
char buffer;
ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
if (nbytes < 0)
daemon_log(2, "error on idle delegate process: %s\n",
strerror(errno));
else if (nbytes > 0)
daemon_log(2, "unexpected data from idle delegate process\n");
}
InvokeIdleDisconnect();
pool_commit();
}
/*
* stock class
*
*/
static void
delegate_stock_create(gcc_unused void *ctx,
gcc_unused struct pool &parent_pool, CreateStockItem c,
gcc_unused const char *uri, void *_info,
gcc_unused struct pool &caller_pool,
gcc_unused struct async_operation_ref &async_ref)
{
auto &info = *(DelegateArgs *)_info;
PreparedChildProcess p;
p.Append(info.executable_path);
GError *error = nullptr;
if (!info.options.CopyTo(p, true, nullptr, &error)) {
c.InvokeCreateError(error);
return;
}
int fds[2];
if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
error = new_error_errno_msg("socketpair() failed: %s");
c.InvokeCreateError(error);
return;
}
p.stdin_fd = fds[1];
pid_t pid = SpawnChildProcess(std::move(p));
if (pid < 0) {
error = new_error_errno_msg2(-pid, "clone() failed");
close(fds[0]);
c.InvokeCreateError(error);
return;
}
auto *process = new DelegateProcess(c, pid, fds[0]);
process->InvokeCreateSuccess();
}
static constexpr StockClass delegate_stock_class = {
.create = delegate_stock_create,
};
/*
* interface
*
*/
StockMap *
delegate_stock_new(struct pool *pool)
{
return hstock_new(*pool, delegate_stock_class, nullptr, 0, 16);
}
StockItem *
delegate_stock_get(StockMap *delegate_stock, struct pool *pool,
const char *helper,
const ChildOptions &options,
GError **error_r)
{
DelegateArgs args(helper, options);
return hstock_get_now(*delegate_stock, *pool, args.GetStockKey(*pool),
&args, error_r);
}
int
delegate_stock_item_get(StockItem &item)
{
auto *process = (DelegateProcess *)&item;
return process->fd;
}
<|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 "logging/flags.hpp"
mesos::internal::logging::Flags::Flags()
{
add(&Flags::quiet,
"quiet",
"Disable logging to stderr",
false);
add(&Flags::logging_level,
"logging_level",
"Log message at or above this level.\n"
"Possible values: `INFO`, `WARNING`, `ERROR`.\n"
"If `--quiet` is specified, this will only affect the logs\n"
"written to `--log_dir`, if specified.",
"INFO");
add(&Flags::log_dir,
"log_dir",
"Location to put log files. By default, nothing is written to disk.\n"
"Does not affect logging to stderr.\n"
"If specified, the log file will appear in the Mesos WebUI."
"NOTE: 3rd party log messages (e.g. ZooKeeper) are\n"
"only written to stderr!");
add(&Flags::logbufsecs,
"logbufsecs",
"Maximum number of seconds that logs may be buffered for.\n"
"By default, logs are flushed immediately.",
0);
add(&Flags::initialize_driver_logging,
"initialize_driver_logging",
"Whether the master/agent should initialize Google logging for the\n"
"Mesos scheduler and executor drivers, in same way as described here.\n"
"The scheduler/executor drivers have separate logs and do not get\n"
"written to the master/agent logs.\n\n"
"This option has no effect when using the HTTP scheduler/executor APIs.\n"
"By default, this option is true.",
true);
add(&Flags::external_log_file,
"external_log_file",
"Location of the externally managed log file. Mesos does not write to\n"
"this file directly and merely exposes it in the WebUI and HTTP API.\n"
"This is only useful when logging to stderr in combination with an\n"
"external logging mechanism, like syslog or journald.\n\n"
"This option is meaningless when specified along with `--quiet`.\n\n"
"This option takes precedence over `--log_dir` in the WebUI.\n"
"However, logs will still be written to the `--log_dir` if\n"
"that option is specified.");
}
<commit_msg>Fixed newline for `--log_dir` flag usage message.<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 "logging/flags.hpp"
mesos::internal::logging::Flags::Flags()
{
add(&Flags::quiet,
"quiet",
"Disable logging to stderr",
false);
add(&Flags::logging_level,
"logging_level",
"Log message at or above this level.\n"
"Possible values: `INFO`, `WARNING`, `ERROR`.\n"
"If `--quiet` is specified, this will only affect the logs\n"
"written to `--log_dir`, if specified.",
"INFO");
add(&Flags::log_dir,
"log_dir",
"Location to put log files. By default, nothing is written to disk.\n"
"Does not affect logging to stderr.\n"
"If specified, the log file will appear in the Mesos WebUI.\n"
"NOTE: 3rd party log messages (e.g. ZooKeeper) are\n"
"only written to stderr!");
add(&Flags::logbufsecs,
"logbufsecs",
"Maximum number of seconds that logs may be buffered for.\n"
"By default, logs are flushed immediately.",
0);
add(&Flags::initialize_driver_logging,
"initialize_driver_logging",
"Whether the master/agent should initialize Google logging for the\n"
"Mesos scheduler and executor drivers, in same way as described here.\n"
"The scheduler/executor drivers have separate logs and do not get\n"
"written to the master/agent logs.\n\n"
"This option has no effect when using the HTTP scheduler/executor APIs.\n"
"By default, this option is true.",
true);
add(&Flags::external_log_file,
"external_log_file",
"Location of the externally managed log file. Mesos does not write to\n"
"this file directly and merely exposes it in the WebUI and HTTP API.\n"
"This is only useful when logging to stderr in combination with an\n"
"external logging mechanism, like syslog or journald.\n\n"
"This option is meaningless when specified along with `--quiet`.\n\n"
"This option takes precedence over `--log_dir` in the WebUI.\n"
"However, logs will still be written to the `--log_dir` if\n"
"that option is specified.");
}
<|endoftext|> |
<commit_before>#include "Number.h"
#include "BigFix/DataRef.h"
#include "BigFix/Error.h"
namespace BigFix
{
uint64_t ReadLittleEndian( DataRef data )
{
uint64_t number = 0;
for ( size_t i = data.Length(); i != 0; i-- )
{
number *= 256;
number += data.Start()[i - 1];
}
return number;
}
void WriteLittleEndian( uint64_t number, uint8_t* buffer, size_t length )
{
for ( size_t i = 0; i != length; i++ )
{
buffer[i] = number % 256;
number /= 256;
}
}
static bool IsAsciiDigit( uint8_t c )
{
return '0' <= c && c <= '9';
}
template < class T >
T ReadAsciiNumber( DataRef data )
{
T number = 0;
for ( size_t i = 0; i < data.Length(); i++ )
{
uint8_t c = data.Start()[i];
if ( !IsAsciiDigit( c ) )
throw Error( "Invalid ascii number" );
number *= 10;
number += c - '0';
}
return number;
}
template uint8_t ReadAsciiNumber<uint8_t>( DataRef );
template int32_t ReadAsciiNumber<int32_t>( DataRef );
template uint32_t ReadAsciiNumber<uint32_t>( DataRef );
}
<commit_msg>Just use the normal subscript<commit_after>#include "Number.h"
#include "BigFix/DataRef.h"
#include "BigFix/Error.h"
namespace BigFix
{
uint64_t ReadLittleEndian( DataRef data )
{
uint64_t number = 0;
for ( size_t i = data.Length(); i != 0; i-- )
{
number *= 256;
number += data[i - 1];
}
return number;
}
void WriteLittleEndian( uint64_t number, uint8_t* buffer, size_t length )
{
for ( size_t i = 0; i != length; i++ )
{
buffer[i] = number % 256;
number /= 256;
}
}
static bool IsAsciiDigit( uint8_t c )
{
return '0' <= c && c <= '9';
}
template < class T >
T ReadAsciiNumber( DataRef data )
{
T number = 0;
for ( size_t i = 0; i < data.Length(); i++ )
{
uint8_t c = data[i];
if ( !IsAsciiDigit( c ) )
throw Error( "Invalid ascii number" );
number *= 10;
number += c - '0';
}
return number;
}
template uint8_t ReadAsciiNumber<uint8_t>( DataRef );
template int32_t ReadAsciiNumber<int32_t>( DataRef );
template uint32_t ReadAsciiNumber<uint32_t>( DataRef );
}
<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#include "tensorflow/core/platform/stream_executor.h"
#include "tensorflow/core/util/gpu_kernel_helper.h"
#include "tensorflow_addons/custom_ops/image/cc/kernels/adjust_hsv_in_yiq_op.h"
namespace tensorflow {
namespace addons {
namespace {
template <typename T>
inline se::DeviceMemory<T> AsDeviceMemory(const T* cuda_memory, uint64 size) {
se::DeviceMemoryBase wrapped(const_cast<T*>(cuda_memory), size * sizeof(T));
se::DeviceMemory<T> typed(wrapped);
return typed;
}
} // namespace
namespace internal {
__global__ void compute_transformation_matrix_cuda(const float* const delta_h,
const float* const scale_s,
const float* const scale_v,
float* const matrix,
const int matrix_size) {
if (matrix_size == kChannelSize * kChannelSize) {
compute_transformation_matrix<kChannelSize * kChannelSize>(
*delta_h, *scale_s, *scale_v, matrix);
}
}
} // namespace internal
namespace functor {
void AdjustHsvInYiqGPU::operator()(OpKernelContext* ctx, int channel_count,
const Tensor* const input,
const float* const delta_h,
const float* const scale_s,
const float* const scale_v,
Tensor* const output) {
const uint64 m = channel_count;
const uint64 k = kChannelSize;
const uint64 n = kChannelSize;
auto* cu_stream = ctx->eigen_device<GPUDevice>().stream();
OP_REQUIRES(ctx, cu_stream, errors::Internal("No GPU stream available."));
Tensor transformation_matrix;
OP_REQUIRES_OK(ctx, ctx->allocate_temp(
DT_FLOAT, TensorShape({kChannelSize * kChannelSize}),
&transformation_matrix));
// TODO(huangyp): It takes about 3.5 us to compute transformation_matrix
// with one thread. Improve its performance if necessary.
TF_CHECK_OK(CudaLaunchKernel(internal::compute_transformation_matrix_cuda, 1,
1, 0, cu_stream, delta_h, scale_s, scale_v,
transformation_matrix.flat<float>().data(),
transformation_matrix.flat<float>().size()));
// Call cuBlas C = A * B directly.
auto no_transpose = se::blas::Transpose::kNoTranspose;
auto a_ptr =
AsDeviceMemory(input->flat<float>().data(), input->flat<float>().size());
auto b_ptr = AsDeviceMemory(transformation_matrix.flat<float>().data(),
transformation_matrix.flat<float>().size());
auto c_ptr = AsDeviceMemory(output->flat<float>().data(),
output->flat<float>().size());
auto* stream = ctx->op_device_context()->stream();
OP_REQUIRES(ctx, stream, errors::Internal("No GPU stream available."));
// TODO(huangyp): share/use autotune cublas algorithms in Matmul.op.
bool blas_launch_status =
stream
->ThenBlasGemm(no_transpose, no_transpose, n, m, k, 1.0f, b_ptr, n,
a_ptr, k, 0.0f, &c_ptr, n)
.ok();
if (!blas_launch_status) {
ctx->SetStatus(errors::Internal("Blas SGEMM launch failed : m=", m,
", n=", n, ", k=", k));
}
}
} // namespace functor
} // end namespace addons
} // namespace tensorflow
#endif // GOOGLE_CUDA
<commit_msg>use AsDeviceMemory from StreamExecutorUtil (#1851)<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#include "tensorflow/core/util/gpu_kernel_helper.h"
#include "tensorflow/core/util/stream_executor_util.h"
#include "tensorflow_addons/custom_ops/image/cc/kernels/adjust_hsv_in_yiq_op.h"
namespace tensorflow {
namespace addons {
namespace internal {
__global__ void compute_transformation_matrix_cuda(const float* const delta_h,
const float* const scale_s,
const float* const scale_v,
float* const matrix,
const int matrix_size) {
if (matrix_size == kChannelSize * kChannelSize) {
compute_transformation_matrix<kChannelSize * kChannelSize>(
*delta_h, *scale_s, *scale_v, matrix);
}
}
} // namespace internal
namespace functor {
void AdjustHsvInYiqGPU::operator()(OpKernelContext* ctx, int channel_count,
const Tensor* const input,
const float* const delta_h,
const float* const scale_s,
const float* const scale_v,
Tensor* const output) {
const uint64 m = channel_count;
const uint64 k = kChannelSize;
const uint64 n = kChannelSize;
auto* cu_stream = ctx->eigen_device<GPUDevice>().stream();
OP_REQUIRES(ctx, cu_stream, errors::Internal("No GPU stream available."));
Tensor transformation_matrix;
OP_REQUIRES_OK(ctx, ctx->allocate_temp(
DT_FLOAT, TensorShape({kChannelSize * kChannelSize}),
&transformation_matrix));
// TODO(huangyp): It takes about 3.5 us to compute transformation_matrix
// with one thread. Improve its performance if necessary.
TF_CHECK_OK(CudaLaunchKernel(internal::compute_transformation_matrix_cuda, 1,
1, 0, cu_stream, delta_h, scale_s, scale_v,
transformation_matrix.flat<float>().data(),
transformation_matrix.flat<float>().size()));
// Call cuBlas C = A * B directly.
auto no_transpose = se::blas::Transpose::kNoTranspose;
auto a_ptr = StreamExecutorUtil::AsDeviceMemory<float>(*input);
auto b_ptr = StreamExecutorUtil::AsDeviceMemory<float>(transformation_matrix);
auto c_ptr = StreamExecutorUtil::AsDeviceMemory<float>(*output);
auto* stream = ctx->op_device_context()->stream();
OP_REQUIRES(ctx, stream, errors::Internal("No GPU stream available."));
// TODO(huangyp): share/use autotune cublas algorithms in Matmul.op.
bool blas_launch_status =
stream
->ThenBlasGemm(no_transpose, no_transpose, n, m, k, 1.0f, b_ptr, n,
a_ptr, k, 0.0f, &c_ptr, n)
.ok();
if (!blas_launch_status) {
ctx->SetStatus(errors::Internal("Blas SGEMM launch failed : m=", m,
", n=", n, ", k=", k));
}
}
} // namespace functor
} // end namespace addons
} // namespace tensorflow
#endif // GOOGLE_CUDA
<|endoftext|> |
<commit_before>#ifdef ENABLE_MPI
#include <stddef.h>
#include "Tools/Display/bash_tools.h"
#include "Monitor_reduction_mpi.hpp"
struct monitor_vals
{
int n_be;
int n_fe;
unsigned long long n_fra;
};
void MPI_SUM_monitor_vals_func(void *in, void *inout, int *len, MPI_Datatype *datatype)
{
auto in_cvt = static_cast<monitor_vals*>(in );
auto inout_cvt = static_cast<monitor_vals*>(inout);
for (auto i = 0; i < *len; i++)
{
inout_cvt[i].n_be += in_cvt[i].n_be;
inout_cvt[i].n_fe += in_cvt[i].n_fe;
inout_cvt[i].n_fra += in_cvt[i].n_fra;
}
}
template <typename B>
Monitor_reduction_mpi<B>
::Monitor_reduction_mpi(const int& K, const int& N, const int& max_fe,
std::vector<Monitor<B>*>& error_analyzers,
const std::thread::id master_thread_id,
const std::chrono::nanoseconds d_mpi_comm_frequency,
const int& n_frames,
const std::string name)
: Monitor_reduction<B>(K, N, max_fe, error_analyzers, n_frames, name),
master_thread_id(master_thread_id),
is_fe_limit_achieved(false),
t_last_mpi_comm(std::chrono::steady_clock::now()),
d_mpi_comm_frequency(d_mpi_comm_frequency)
{
int blen[3];
MPI_Aint displacements[3];
MPI_Datatype oldtypes[3];
blen[0] = 1; displacements[0] = offsetof(monitor_vals, n_be); oldtypes[0] = MPI_INT;
blen[1] = 1; displacements[1] = offsetof(monitor_vals, n_fe); oldtypes[1] = MPI_INT;
blen[2] = 1; displacements[2] = offsetof(monitor_vals, n_fra); oldtypes[2] = MPI_UNSIGNED_LONG_LONG;
if (auto ret = MPI_Type_create_struct(3, blen, displacements, oldtypes, &MPI_monitor_vals))
{
std::cerr << bold_red("(EE) MPI_Type_create_struct returned \"") << bold_red(std::to_string(ret))
<< bold_red("\", exiting.") << std::endl;
std::exit(-1);
}
if (auto ret = MPI_Type_commit(&MPI_monitor_vals))
{
std::cerr << bold_red("(EE) MPI_Type_commit returned \"") << bold_red(std::to_string(ret))
<< bold_red("\", exiting.") << std::endl;
std::exit(-1);
}
if (auto ret = MPI_Op_create(MPI_SUM_monitor_vals_func, true, &MPI_SUM_monitor_vals))
{
std::cerr << bold_red("(EE) MPI_Op_create returned \"") << bold_red(std::to_string(ret))
<< bold_red("\", exiting.") << std::endl;
std::exit(-1);
}
}
template <typename B>
Monitor_reduction_mpi<B>
::~Monitor_reduction_mpi()
{
}
template <typename B>
bool Monitor_reduction_mpi<B>
::fe_limit_achieved()
{
// only the master thread can do this
if (std::this_thread::get_id() == this->master_thread_id &&
((std::chrono::steady_clock::now() - t_last_mpi_comm) >= d_mpi_comm_frequency))
{
monitor_vals mvals_recv;
monitor_vals mvals_send = { this->get_n_be() - this->n_bit_errors,
this->get_n_fe() - this->n_frame_errors,
this->get_n_analyzed_fra() - this->n_analyzed_frames };
MPI_Allreduce(&mvals_send, &mvals_recv, 1, MPI_monitor_vals, MPI_SUM_monitor_vals, MPI_COMM_WORLD);
this->n_bit_errors = mvals_recv.n_be - mvals_send.n_be;
this->n_frame_errors = mvals_recv.n_fe - mvals_send.n_fe;
this->n_analyzed_frames = mvals_recv.n_fra - mvals_send.n_fra;
t_last_mpi_comm = std::chrono::steady_clock::now();
is_fe_limit_achieved = this->get_n_fe() >= this->get_fe_limit();
}
return is_fe_limit_achieved;
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class Monitor_reduction_mpi<B_8>;
template class Monitor_reduction_mpi<B_16>;
template class Monitor_reduction_mpi<B_32>;
template class Monitor_reduction_mpi<B_64>;
#else
template class Monitor_reduction_mpi<B>;
#endif
// ==================================================================================== explicit template instantiation
#endif
<commit_msg>Fix a possible dead lock.<commit_after>#ifdef ENABLE_MPI
#include <stddef.h>
#include "Tools/Display/bash_tools.h"
#include "Monitor_reduction_mpi.hpp"
struct monitor_vals
{
int n_be;
int n_fe;
unsigned long long n_fra;
};
void MPI_SUM_monitor_vals_func(void *in, void *inout, int *len, MPI_Datatype *datatype)
{
auto in_cvt = static_cast<monitor_vals*>(in );
auto inout_cvt = static_cast<monitor_vals*>(inout);
for (auto i = 0; i < *len; i++)
{
inout_cvt[i].n_be += in_cvt[i].n_be;
inout_cvt[i].n_fe += in_cvt[i].n_fe;
inout_cvt[i].n_fra += in_cvt[i].n_fra;
}
}
template <typename B>
Monitor_reduction_mpi<B>
::Monitor_reduction_mpi(const int& K, const int& N, const int& max_fe,
std::vector<Monitor<B>*>& error_analyzers,
const std::thread::id master_thread_id,
const std::chrono::nanoseconds d_mpi_comm_frequency,
const int& n_frames,
const std::string name)
: Monitor_reduction<B>(K, N, max_fe, error_analyzers, n_frames, name),
master_thread_id(master_thread_id),
is_fe_limit_achieved(false),
t_last_mpi_comm(std::chrono::steady_clock::now()),
d_mpi_comm_frequency(d_mpi_comm_frequency)
{
int blen[3];
MPI_Aint displacements[3];
MPI_Datatype oldtypes[3];
blen[0] = 1; displacements[0] = offsetof(monitor_vals, n_be); oldtypes[0] = MPI_INT;
blen[1] = 1; displacements[1] = offsetof(monitor_vals, n_fe); oldtypes[1] = MPI_INT;
blen[2] = 1; displacements[2] = offsetof(monitor_vals, n_fra); oldtypes[2] = MPI_UNSIGNED_LONG_LONG;
if (auto ret = MPI_Type_create_struct(3, blen, displacements, oldtypes, &MPI_monitor_vals))
{
std::cerr << bold_red("(EE) MPI_Type_create_struct returned \"") << bold_red(std::to_string(ret))
<< bold_red("\", exiting.") << std::endl;
std::exit(-1);
}
if (auto ret = MPI_Type_commit(&MPI_monitor_vals))
{
std::cerr << bold_red("(EE) MPI_Type_commit returned \"") << bold_red(std::to_string(ret))
<< bold_red("\", exiting.") << std::endl;
std::exit(-1);
}
if (auto ret = MPI_Op_create(MPI_SUM_monitor_vals_func, true, &MPI_SUM_monitor_vals))
{
std::cerr << bold_red("(EE) MPI_Op_create returned \"") << bold_red(std::to_string(ret))
<< bold_red("\", exiting.") << std::endl;
std::exit(-1);
}
}
template <typename B>
Monitor_reduction_mpi<B>
::~Monitor_reduction_mpi()
{
}
template <typename B>
bool Monitor_reduction_mpi<B>
::fe_limit_achieved()
{
// only the master thread can do this
if (std::this_thread::get_id() == this->master_thread_id &&
((std::chrono::steady_clock::now() - t_last_mpi_comm) >= d_mpi_comm_frequency))
{
monitor_vals mvals_recv;
monitor_vals mvals_send = { this->get_n_be() - this->n_bit_errors,
this->get_n_fe() - this->n_frame_errors,
this->get_n_analyzed_fra() - this->n_analyzed_frames };
MPI_Allreduce(&mvals_send, &mvals_recv, 1, MPI_monitor_vals, MPI_SUM_monitor_vals, MPI_COMM_WORLD);
this->n_bit_errors = mvals_recv.n_be - mvals_send.n_be;
this->n_frame_errors = mvals_recv.n_fe - mvals_send.n_fe;
this->n_analyzed_frames = mvals_recv.n_fra - mvals_send.n_fra;
t_last_mpi_comm = std::chrono::steady_clock::now();
is_fe_limit_achieved = mvals_recv.n_fe >= this->get_fe_limit();
}
return is_fe_limit_achieved;
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class Monitor_reduction_mpi<B_8>;
template class Monitor_reduction_mpi<B_16>;
template class Monitor_reduction_mpi<B_32>;
template class Monitor_reduction_mpi<B_64>;
#else
template class Monitor_reduction_mpi<B>;
#endif
// ==================================================================================== explicit template instantiation
#endif
<|endoftext|> |
<commit_before>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2013 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
//== INCLUDES =================================================================
#ifdef _MSC_VER
# pragma warning(disable: 4267 4311)
#endif
#include <iostream>
#include <fstream>
#include <qapplication.h>
#include <qdatetime.h>
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Apps/Decimating/DecimaterViewerWidget.hh>
//== IMPLEMENTATION ==========================================================
//-----------------------------------------------------------------------------
void DecimaterViewerWidget::keyPressEvent(QKeyEvent* _event)
{
switch (_event->key())
{
case Key_H:
std::cout << "Press '+' to increase the number of decimating steps\n"
<< "Press '-' to decrease the number of decimating steps\n"
<< "Press 'd' to perform the set number of decimating steps\n"
<< "Press 'S' to save the mesh to 'result.off'\n"
<< "Press 'q' or 'Esc' quit the application" << std::endl;
break;
case Key_D:
{
int rc;
if ( (rc=decimater_->decimate(steps_)) )
{
decimater_->mesh().garbage_collection();
std::cout << rc << " vertices removed!\n";
updateGL();
}
else
std::cout << "Decimation failed\n";
break;
}
case Key_Plus:
++steps_;
steps_ = std::min( steps_ , (size_t)( mesh_.n_vertices() / 10 ) );
updateGL();
std::cout << "# decimating steps increased to " << steps_ << std::endl;
break;
case Key_Minus:
--steps_;
steps_ = std::max( steps_ , size_t(1) );
updateGL();
std::cout << "# decimating steps increased to " << steps_ << std::endl;
break;
case Key_S:
{
OpenMesh::IO::Options opt;
opt += OpenMesh::IO::Options::Binary;
if (OpenMesh::IO::write_mesh( mesh(), "result.off", opt ))
std::cout << "mesh saved in 'result.off'\n";
}
break;
case Key_Q:
case Key_Escape:
qApp->quit();
break;
default:
this->inherited_t::keyPressEvent(_event);
break;
}
}
void DecimaterViewerWidget::animate( void )
{
// updateGL();
// timer_->start(300, true);
}
//=============================================================================
<commit_msg>cppcheck: Missing break<commit_after>/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2013 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision$ *
* $Date$ *
* *
\*===========================================================================*/
//== INCLUDES =================================================================
#ifdef _MSC_VER
# pragma warning(disable: 4267 4311)
#endif
#include <iostream>
#include <fstream>
#include <qapplication.h>
#include <qdatetime.h>
#include <OpenMesh/Core/IO/BinaryHelper.hh>
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Apps/Decimating/DecimaterViewerWidget.hh>
//== IMPLEMENTATION ==========================================================
//-----------------------------------------------------------------------------
void DecimaterViewerWidget::keyPressEvent(QKeyEvent* _event)
{
switch (_event->key())
{
case Key_H:
std::cout << "Press '+' to increase the number of decimating steps\n"
<< "Press '-' to decrease the number of decimating steps\n"
<< "Press 'd' to perform the set number of decimating steps\n"
<< "Press 'S' to save the mesh to 'result.off'\n"
<< "Press 'q' or 'Esc' quit the application" << std::endl;
break;
case Key_D:
{
int rc;
if ( (rc=decimater_->decimate(steps_)) )
{
decimater_->mesh().garbage_collection();
std::cout << rc << " vertices removed!\n";
updateGL();
}
else
std::cout << "Decimation failed\n";
break;
}
case Key_Plus:
++steps_;
steps_ = std::min( steps_ , (size_t)( mesh_.n_vertices() / 10 ) );
updateGL();
std::cout << "# decimating steps increased to " << steps_ << std::endl;
break;
case Key_Minus:
--steps_;
steps_ = std::max( steps_ , size_t(1) );
updateGL();
std::cout << "# decimating steps increased to " << steps_ << std::endl;
break;
case Key_S:
{
OpenMesh::IO::Options opt;
opt += OpenMesh::IO::Options::Binary;
if (OpenMesh::IO::write_mesh( mesh(), "result.off", opt ))
std::cout << "mesh saved in 'result.off'\n";
}
break;
case Key_Q:
qApp->quit();
break;
case Key_Escape:
qApp->quit();
break;
default:
this->inherited_t::keyPressEvent(_event);
break;
}
}
void DecimaterViewerWidget::animate( void )
{
// updateGL();
// timer_->start(300, true);
}
//=============================================================================
<|endoftext|> |
<commit_before>#ifndef ARGUMENT_TYPE_FILE_SYSTEM_HPP_
#define ARGUMENT_TYPE_FILE_SYSTEM_HPP_
#include <string>
#include <iostream>
#include <stdexcept>
#include "Tools/system_functions.h"
#include "Tools/version.h"
#include "../Argument_type_limited.hpp"
namespace aff3ct
{
namespace tools
{
enum class openmode : uint8_t {read, write, read_write};
template <typename Read_F>
std::string modify_path(const std::string& val)
{
std::string binary_path = get_binary_path();
if (!binary_path.empty())
{
std::string basedir, filename;
split_path(binary_path, basedir, filename);
std::string aff3ct_version = aff3ct::version();
if (!aff3ct_version.empty() && aff3ct_version[0] == 'v')
aff3ct_version.erase(0, 1); // rm the 'v'
std::vector<std::string> paths = {
"../../",
"../../../",
"../share/aff3ct-" + aff3ct_version + "/",
"../../share/aff3ct-" + aff3ct_version + "/",
"/usr/share/aff3ct-" + aff3ct_version + "/",
"/usr/share/aff3ct-" + aff3ct_version + "/",
"/usr/local/share/aff3ct-" + aff3ct_version + "/",
"../share/aff3ct/",
"../../share/aff3ct/",
"/usr/share/aff3ct/",
"/usr/local/share/aff3ct/",
};
for (auto &path : paths)
{
std::string full_path = (path[0] != '/') ? basedir + "/" : "";
full_path += path + val;
#if defined(_WIN32) || defined(_WIN64)
if (path[0] == '/')
continue;
std::replace(full_path.begin(), full_path.end(), '/', '\\');
#endif
if (Read_F::check(full_path))
return full_path;
}
}
return "";
}
std::string openmode_to_string(const openmode& mode);
struct Is_file
{
static bool check(const std::string& filename);
};
struct Is_folder
{
static bool check(const std::string& foldername);
};
struct Is_path
{
static bool check(const std::string& path);
};
struct No_check
{
static bool check(const std::string&);
};
template <typename T = std::string, typename Read_F = No_check, typename Write_F = No_check, typename RW_F = No_check, typename... Ranges>
class File_system_type : public Argument_type_limited<T,Ranges...>
{
protected:
const std::string name;
const openmode mode;
public:
template <typename r, typename... R>
explicit File_system_type(const std::string& name, const openmode& mode, const r* range, const R*... ranges)
: Argument_type_limited<T,Ranges...>(generate_title(name, mode), range, ranges...), name(name), mode(mode)
{ }
explicit File_system_type(const std::string& name, const openmode& mode)
: Argument_type_limited<T,Ranges...>(generate_title(name, mode)), name(name), mode(mode)
{ }
virtual ~File_system_type() {};
virtual File_system_type<T, Read_F, Write_F, RW_F, Ranges...>* clone() const
{
auto* clone = new File_system_type<T, Read_F, Write_F, RW_F, Ranges...>(name, mode);
return dynamic_cast<File_system_type<T, Read_F, Write_F, RW_F, Ranges...>*>(this->clone_ranges(clone));
}
template <typename... NewRanges>
File_system_type<T, Read_F, Write_F, RW_F, Ranges..., NewRanges...>* clone(NewRanges*... new_ranges)
{
auto* clone = new File_system_type<T, Read_F, Write_F, RW_F, Ranges..., NewRanges...>(name, mode);
this->clone_ranges(clone);
clone->add_ranges(new_ranges...);
return clone;
}
static std::string generate_title(const std::string& name, const openmode& mode)
{
return name + " [" + openmode_to_string(mode) + "]";
}
virtual T convert(const std::string& val) const
{
return val;
}
virtual void check(const std::string& val) const
{
auto str_val = this->convert(val);
if (str_val.empty())
throw std::runtime_error("shall be a " + name + " name");
switch(mode)
{
case openmode::read :
if(!Read_F::check(str_val))
if (modify_path<Read_F>(str_val).empty())
throw std::runtime_error("does not name an existing " + name);
break;
case openmode::write :
if(!Write_F::check(str_val))
throw std::runtime_error("does not name a " + name);
break;
case openmode::read_write : // nothing to check
if(!RW_F::check(str_val))
throw std::runtime_error("does not name a " + name);
break;
}
this->check_ranges(str_val);
}
};
}
}
#include "File.hpp"
#include "Folder.hpp"
#include "Path.hpp"
#endif /* ARGUMENT_TYPE_FILE_SYSTEM_HPP_ */<commit_msg>Print debug infos.<commit_after>#ifndef ARGUMENT_TYPE_FILE_SYSTEM_HPP_
#define ARGUMENT_TYPE_FILE_SYSTEM_HPP_
#include <string>
#include <iostream>
#include <stdexcept>
#include "Tools/system_functions.h"
#include "Tools/version.h"
#include "../Argument_type_limited.hpp"
namespace aff3ct
{
namespace tools
{
enum class openmode : uint8_t {read, write, read_write};
template <typename Read_F>
std::string modify_path(const std::string& val)
{
std::string binary_path = get_binary_path();
if (!binary_path.empty())
{
std::string basedir, filename;
split_path(binary_path, basedir, filename);
std::cout << "# (DBG) binary_path = '" << binary_path << "'" << std::endl;
std::cout << "# (DBG) basedir = '" << basedir << "'" << std::endl;
std::cout << "# (DBG) filename = '" << filename << "'" << std::endl;
std::string aff3ct_version = aff3ct::version();
if (!aff3ct_version.empty() && aff3ct_version[0] == 'v')
aff3ct_version.erase(0, 1); // rm the 'v'
std::vector<std::string> paths = {
"../../",
"../../../",
"../share/aff3ct-" + aff3ct_version + "/",
"../../share/aff3ct-" + aff3ct_version + "/",
"/usr/share/aff3ct-" + aff3ct_version + "/",
"/usr/share/aff3ct-" + aff3ct_version + "/",
"/usr/local/share/aff3ct-" + aff3ct_version + "/",
"../share/aff3ct/",
"../../share/aff3ct/",
"/usr/share/aff3ct/",
"/usr/local/share/aff3ct/",
};
for (auto &path : paths)
{
std::string full_path = (path[0] != '/') ? basedir + "/" : "";
full_path += path + val;
#if defined(_WIN32) || defined(_WIN64)
if (path[0] == '/')
continue;
std::replace(full_path.begin(), full_path.end(), '/', '\\');
#endif
if (Read_F::check(full_path))
return full_path;
}
}
return "";
}
std::string openmode_to_string(const openmode& mode);
struct Is_file
{
static bool check(const std::string& filename);
};
struct Is_folder
{
static bool check(const std::string& foldername);
};
struct Is_path
{
static bool check(const std::string& path);
};
struct No_check
{
static bool check(const std::string&);
};
template <typename T = std::string, typename Read_F = No_check, typename Write_F = No_check, typename RW_F = No_check, typename... Ranges>
class File_system_type : public Argument_type_limited<T,Ranges...>
{
protected:
const std::string name;
const openmode mode;
public:
template <typename r, typename... R>
explicit File_system_type(const std::string& name, const openmode& mode, const r* range, const R*... ranges)
: Argument_type_limited<T,Ranges...>(generate_title(name, mode), range, ranges...), name(name), mode(mode)
{ }
explicit File_system_type(const std::string& name, const openmode& mode)
: Argument_type_limited<T,Ranges...>(generate_title(name, mode)), name(name), mode(mode)
{ }
virtual ~File_system_type() {};
virtual File_system_type<T, Read_F, Write_F, RW_F, Ranges...>* clone() const
{
auto* clone = new File_system_type<T, Read_F, Write_F, RW_F, Ranges...>(name, mode);
return dynamic_cast<File_system_type<T, Read_F, Write_F, RW_F, Ranges...>*>(this->clone_ranges(clone));
}
template <typename... NewRanges>
File_system_type<T, Read_F, Write_F, RW_F, Ranges..., NewRanges...>* clone(NewRanges*... new_ranges)
{
auto* clone = new File_system_type<T, Read_F, Write_F, RW_F, Ranges..., NewRanges...>(name, mode);
this->clone_ranges(clone);
clone->add_ranges(new_ranges...);
return clone;
}
static std::string generate_title(const std::string& name, const openmode& mode)
{
return name + " [" + openmode_to_string(mode) + "]";
}
virtual T convert(const std::string& val) const
{
return val;
}
virtual void check(const std::string& val) const
{
auto str_val = this->convert(val);
if (str_val.empty())
throw std::runtime_error("shall be a " + name + " name");
switch(mode)
{
case openmode::read :
if(!Read_F::check(str_val))
if (modify_path<Read_F>(str_val).empty())
throw std::runtime_error("does not name an existing " + name);
break;
case openmode::write :
if(!Write_F::check(str_val))
throw std::runtime_error("does not name a " + name);
break;
case openmode::read_write : // nothing to check
if(!RW_F::check(str_val))
throw std::runtime_error("does not name a " + name);
break;
}
this->check_ranges(str_val);
}
};
}
}
#include "File.hpp"
#include "Folder.hpp"
#include "Path.hpp"
#endif /* ARGUMENT_TYPE_FILE_SYSTEM_HPP_ */<|endoftext|> |
<commit_before>#include <readline/readline.h>
#include <readline/history.h>
#include <iostream>
#include <cctype>
#include <sstream>
#include <ctime>
#include "../parser/stmt.h"
#include "../../parser.tab.h"
#include "evaluator.h"
typedef struct yy_buffer_state *YY_BUFFER_STATE;
extern YY_BUFFER_STATE yy_scan_string (const char *yy_str );
extern void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer );
extern void yy_delete_buffer (YY_BUFFER_STATE b );
extern int yyparse ();
using namespace std;
BufferManager BufferManager;
IndexManager IndexManager(&BufferManager);
catalog_manager catm(".");
RecordManager RecordManager;
string base_addr = ".";
void system_init() {
cout << "System Initialized!" << endl;
RecordManager.Init(&BufferManager, &catm, &IndexManager);
}
int main() {
system_init();
int ii = 10;
time_t *start_time = nullptr, *end_time;
while(ii < 1200) {
if ( stmt_queue.empty() ) {
if (start_time != nullptr) {
cout << difftime(*end_time, *start_time) << " seconds used." << endl;
}
time(end_time);
char * line = readline(">>> ");
time(start_time);
add_history(line);
int len = strlen(line);
char *tmp = new char[len + 2];
strcpy(tmp, line);
tmp[len + 1] = 0;
YY_BUFFER_STATE my_string_buffer = yy_scan_string(tmp);
yy_switch_to_buffer( my_string_buffer );
yyparse();
yy_delete_buffer( my_string_buffer );
delete[] tmp;
}
try {
while( !stmt_queue.empty() ) {
switch( stmt_queue.front().first ) {
case stmt_type::_create_table_stmt:
xyzsql_process_create_table();
break;
case stmt_type::_create_index_stmt:
xyzsql_process_create_index();
break;
case stmt_type::_select_stmt:
xyzsql_process_select();
break;
case stmt_type::_insert_stmt:
xyzsql_process_insert();
break;
case stmt_type::_delete_stmt:
xyzsql_process_delete();
break;
case stmt_type::_drop_table_stmt:
xyzsql_process_drop_table();
break;
case stmt_type::_drop_index_stmt:
xyzsql_process_drop_index();
break;
case stmt_type::_transaction_stmt:
xyzsql_process_transaction();
break;
case stmt_type::_commit_stmt:
xyzsql_process_commit();
break;
case stmt_type::_rollback_stmt:
xyzsql_process_rollback();
break;
case stmt_type::_quit_stmt:
xyzsql_exit();
break;
case stmt_type::_exefile_stmt:
xyzsql_batch();
break;
default: xyzsql_unknown_stmt();
}
if ( stmt_queue.front().second != nullptr)
delete stmt_queue.front().second;
stmt_queue.pop();
ii++;
}
} catch( exception &t ) {
cout << t.what() << endl;
stmt_queue.pop();
}
}
xyzsql_finalize();
return 0;
}
<commit_msg>Perfect time measurement module.<commit_after>#include <readline/readline.h>
#include <readline/history.h>
#include <iostream>
#include <cctype>
#include <sstream>
#include <ctime>
#include "../parser/stmt.h"
#include "../../parser.tab.h"
#include "evaluator.h"
typedef struct yy_buffer_state *YY_BUFFER_STATE;
extern YY_BUFFER_STATE yy_scan_string (const char *yy_str );
extern void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer );
extern void yy_delete_buffer (YY_BUFFER_STATE b );
extern int yyparse ();
using namespace std;
BufferManager BufferManager;
IndexManager IndexManager(&BufferManager);
catalog_manager catm(".");
RecordManager RecordManager;
string base_addr = ".";
void system_init() {
cout << "System Initialized!" << endl;
RecordManager.Init(&BufferManager, &catm, &IndexManager);
}
int main() {
system_init();
int ii = 10;
clock_t start_time = 0, end_time;
while(ii < 1200) {
if ( stmt_queue.empty() ) {
end_time = clock();
if (start_time != 0 ) {
cout << (end_time - start_time) * 1000 / CLOCKS_PER_SEC << " ms used. " << end_time - start_time << endl;
}
char * line = readline(">>> ");
add_history(line);
start_time = clock();
int len = strlen(line);
char *tmp = new char[len + 2];
strcpy(tmp, line);
tmp[len + 1] = 0;
YY_BUFFER_STATE my_string_buffer = yy_scan_string(tmp);
yy_switch_to_buffer( my_string_buffer );
yyparse();
yy_delete_buffer( my_string_buffer );
delete[] tmp;
}
try {
while( !stmt_queue.empty() ) {
switch( stmt_queue.front().first ) {
case stmt_type::_create_table_stmt:
xyzsql_process_create_table();
break;
case stmt_type::_create_index_stmt:
xyzsql_process_create_index();
break;
case stmt_type::_select_stmt:
xyzsql_process_select();
break;
case stmt_type::_insert_stmt:
xyzsql_process_insert();
break;
case stmt_type::_delete_stmt:
xyzsql_process_delete();
break;
case stmt_type::_drop_table_stmt:
xyzsql_process_drop_table();
break;
case stmt_type::_drop_index_stmt:
xyzsql_process_drop_index();
break;
case stmt_type::_transaction_stmt:
xyzsql_process_transaction();
break;
case stmt_type::_commit_stmt:
xyzsql_process_commit();
break;
case stmt_type::_rollback_stmt:
xyzsql_process_rollback();
break;
case stmt_type::_quit_stmt:
xyzsql_exit();
break;
case stmt_type::_exefile_stmt:
xyzsql_batch();
break;
default: xyzsql_unknown_stmt();
}
if ( stmt_queue.front().second != nullptr)
delete stmt_queue.front().second;
stmt_queue.pop();
ii++;
}
} catch( exception &t ) {
cout << t.what() << endl;
stmt_queue.pop();
}
}
xyzsql_finalize();
return 0;
}
<|endoftext|> |
<commit_before>/*
* C++ wrappers for the libevent callback.
*
* author: Max Kellermann <[email protected]>
*/
#ifndef EVENT_CALLBACK_HXX
#define EVENT_CALLBACK_HXX
#include <event.h>
template<class T, void (T::*member)()>
struct SimpleEventCallback {
static void Callback(gcc_unused evutil_socket_t fd,
gcc_unused short events,
void *ctx) {
T &t = *(T *)ctx;
(t.*member)();
}
};
/* need C++ N3601 to do this without macros */
#define MakeSimpleEventCallback(T, C) SimpleEventCallback<T, &T::C>::Callback
#endif
<commit_msg>event/Callback: add missing include<commit_after>/*
* C++ wrappers for the libevent callback.
*
* author: Max Kellermann <[email protected]>
*/
#ifndef EVENT_CALLBACK_HXX
#define EVENT_CALLBACK_HXX
#include <inline/compiler.h>
#include <event.h>
template<class T, void (T::*member)()>
struct SimpleEventCallback {
static void Callback(gcc_unused evutil_socket_t fd,
gcc_unused short events,
void *ctx) {
T &t = *(T *)ctx;
(t.*member)();
}
};
/* need C++ N3601 to do this without macros */
#define MakeSimpleEventCallback(T, C) SimpleEventCallback<T, &T::C>::Callback
#endif
<|endoftext|> |
<commit_before>//
// Created by Dawid Drozd aka Gelldur on 6/30/16.
//
#include "Fail.h"
#include <exception>
#include <log.h>
Fail::Fail(const char* fileName, const char* functionName, int lineNumber)
: _lineNumber(lineNumber)
, _fileName(fileName)
, _functionName(functionName)
{
auto srcPosition = _fileName.rfind("/src/");
if (srcPosition != std::string::npos)
{
_fileName.erase(0, srcPosition);
}
_stream << _fileName << " " << _fileName << ":" << _lineNumber << " ";
}
void Fail::report()
{
auto message = _stream.str();
ILOG("Fail: %s", message.c_str());
throw std::runtime_error(message);
}
<commit_msg>Fix GCC 4.9 include<commit_after>//
// Created by Dawid Drozd aka Gelldur on 6/30/16.
//
#include "Fail.h"
#include <stdexcept>
#include <log.h>
Fail::Fail(const char* fileName, const char* functionName, int lineNumber)
: _lineNumber(lineNumber)
, _fileName(fileName)
, _functionName(functionName)
{
auto srcPosition = _fileName.rfind("/src/");
if (srcPosition != std::string::npos)
{
_fileName.erase(0, srcPosition);
}
_stream << _fileName << " " << _fileName << ":" << _lineNumber << " ";
}
void Fail::report()
{
auto message = _stream.str();
ILOG("Fail: %s", message.c_str());
throw std::runtime_error(message);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/file/BaseTagFS.hpp>
#include <nix/NDArray.hpp>
#include <nix/file/DataArrayFS.hpp>
#include <nix/file/BlockFS.hpp>
#include <nix/file/FeatureFS.hpp>
namespace bfs= boost::filesystem;
namespace nix {
namespace file {
BaseTagFS::BaseTagFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,
const std::string &loc)
: EntityWithSourcesFS(file, block, loc)
{
createSubFolders(file);
}
BaseTagFS::BaseTagFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,
const std::string &loc, const std::string &id, const std::string &type, const std::string &name)
: BaseTagFS(file, block, loc, id, type, name, util::getTime())
{
}
BaseTagFS::BaseTagFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,
const std::string &loc, const std::string &id, const std::string &type, const std::string &name, time_t time)
: EntityWithSourcesFS(file, block, loc, id, type, name, time)
{
createSubFolders(file);
}
void BaseTagFS::createSubFolders(const std::shared_ptr<base::IFile> &file) {
bfs::path refs("references");
bfs::path feats("features");
bfs::path p(location());
refs_group = Directory(p / refs, file->fileMode());
feature_group = Directory(p / feats, file->fileMode());
}
//--------------------------------------------------
// Methods concerning references.
//--------------------------------------------------
bool BaseTagFS::hasReference(const std::string &name_or_id) const {
std::string id = name_or_id;
if (!util::looksLikeUUID(name_or_id) && block()->hasDataArray(name_or_id)) {
id = block()->getDataArray(name_or_id)->id();
}
return refs_group.hasObject(id);
}
ndsize_t BaseTagFS::referenceCount() const {
return refs_group.subdirCount();
}
std::shared_ptr<base::IDataArray> BaseTagFS::getReference(const std::string &name_or_id) const {
std::shared_ptr<base::IDataArray> da;
std::string id = name_or_id;
if (!util::looksLikeUUID(name_or_id) && block()->hasDataArray(name_or_id)) {
id = block()->getDataArray(name_or_id)->id();
}
if (hasReference(id)) {
boost::optional<bfs::path> path = refs_group.findByNameOrAttribute("name", name_or_id);
if (path) {
return std::make_shared<DataArrayFS>(file(), block(), path->string());
}
}
return da;
}
std::shared_ptr<base::IDataArray> BaseTagFS::getReference(size_t index) const {
if(index > referenceCount()) {
throw OutOfBounds("No reference at given index", index);
}
bfs::path p = refs_group.sub_dir_by_index(index);
return std::make_shared<DataArrayFS>(file(), block(), p.string());
}
void BaseTagFS::addReference(const std::string &name_or_id) {
if (name_or_id.empty())
throw EmptyString("addReference");
if (!block()->hasDataArray(name_or_id))
throw std::runtime_error("BaseTagFS::addReference: DataArray not found in block!");
auto target = std::dynamic_pointer_cast<DataArrayFS>(block()->getDataArray(name_or_id));
refs_group.createDirectoryLink(target->location(), target->id());
}
bool BaseTagFS::removeReference(const std::string &name_or_id) {
return refs_group.removeObjectByNameOrAttribute("name", name_or_id);
}
void BaseTagFS::references(const std::vector<DataArray> &refs_new) {
// extract vectors of names from vectors of new & old references
std::vector<std::string> names_new(refs_new.size());
transform(refs_new.begin(), refs_new.end(), names_new.begin(), util::toName<DataArray>);
//FIXME: issue 473
std::vector<DataArray> refs_old(static_cast<size_t>(referenceCount()));
for (size_t i = 0; i < refs_old.size(); i++) refs_old[i] = getReference(i);
std::vector<std::string> names_old(refs_old.size());
std::transform(refs_old.begin(), refs_old.end(), names_old.begin(), util::toName<DataArray>);
// sort them
std::sort(names_new.begin(), names_new.end());
std::sort(names_new.begin(), names_new.end());
// get names only in names_new (add), names only in names_old (remove) & ignore rest
std::vector<std::string> names_add;
std::vector<std::string> names_rem;
std::set_difference(names_new.begin(), names_new.end(), names_old.begin(), names_old.end(),
std::inserter(names_add, names_add.begin()));
std::set_difference(names_old.begin(), names_old.end(), names_new.begin(), names_new.end(),
std::inserter(names_rem, names_rem.begin()));
// check if all new references exist & add sources
auto blck = std::dynamic_pointer_cast<BlockFS>(block());
for (auto name : names_add) {
if (!blck->hasDataArray(name))
throw std::runtime_error("One or more data arrays do not exist in this block!");
addReference(blck->getDataArray(name)->id());
}
// remove references
for (auto name : names_rem) {
if (!blck->hasDataArray(name))
removeReference(blck->getDataArray(name)->id());
}
}
//--------------------------------------------------
// Methods concerning features.
//--------------------------------------------------
bool BaseTagFS::hasFeature(const std::string &name_or_id) const {
return !feature_group.findByNameOrAttribute("entity_id", name_or_id)->empty();
}
ndsize_t BaseTagFS::featureCount() const {
return feature_group.subdirCount();
}
std::shared_ptr<base::IFeature> BaseTagFS::getFeature(const std::string &name_or_id) const {
std::shared_ptr<base::IFeature> feature;
boost::optional<bfs::path> p = feature_group.findByNameOrAttribute("name", name_or_id);
if (p) {
return std::make_shared<FeatureFS>(file(), block(), p->string());
}
return feature;
}
std::shared_ptr<base::IFeature> BaseTagFS::getFeature(size_t index) const {
if (index >= featureCount()) {
throw OutOfBounds("Trying to access a feature with an invalid index!");
}
bfs::path id = feature_group.sub_dir_by_index(index);
return getFeature(id.filename().string());
}
std::shared_ptr<base::IFeature> BaseTagFS::createFeature(const std::string &name_or_id, LinkType link_type) {
if(!block()->hasDataArray(name_or_id)) {
throw std::runtime_error("DataArray not found in Block!");
}
std::string rep_id = util::createId();
DataArray a = block()->getDataArray(name_or_id);
return std::make_shared<FeatureFS>(file(), block(), feature_group.location(), rep_id, a, link_type);
}
bool BaseTagFS::deleteFeature(const std::string &name_or_id) {
return feature_group.removeObjectByNameOrAttribute("name", name_or_id);
}
BaseTagFS::~BaseTagFS() {}
} // ns nix::file
} // ns nix<commit_msg>fix issue 473 in BaseTagFS<commit_after>// Copyright (c) 2013 - 2015, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/file/BaseTagFS.hpp>
#include <nix/NDArray.hpp>
#include <nix/file/DataArrayFS.hpp>
#include <nix/file/BlockFS.hpp>
#include <nix/file/FeatureFS.hpp>
namespace bfs= boost::filesystem;
namespace nix {
namespace file {
BaseTagFS::BaseTagFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,
const std::string &loc)
: EntityWithSourcesFS(file, block, loc)
{
createSubFolders(file);
}
BaseTagFS::BaseTagFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,
const std::string &loc, const std::string &id, const std::string &type, const std::string &name)
: BaseTagFS(file, block, loc, id, type, name, util::getTime())
{
}
BaseTagFS::BaseTagFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block,
const std::string &loc, const std::string &id, const std::string &type, const std::string &name, time_t time)
: EntityWithSourcesFS(file, block, loc, id, type, name, time)
{
createSubFolders(file);
}
void BaseTagFS::createSubFolders(const std::shared_ptr<base::IFile> &file) {
bfs::path refs("references");
bfs::path feats("features");
bfs::path p(location());
refs_group = Directory(p / refs, file->fileMode());
feature_group = Directory(p / feats, file->fileMode());
}
//--------------------------------------------------
// Methods concerning references.
//--------------------------------------------------
bool BaseTagFS::hasReference(const std::string &name_or_id) const {
std::string id = name_or_id;
if (!util::looksLikeUUID(name_or_id) && block()->hasDataArray(name_or_id)) {
id = block()->getDataArray(name_or_id)->id();
}
return refs_group.hasObject(id);
}
ndsize_t BaseTagFS::referenceCount() const {
return refs_group.subdirCount();
}
std::shared_ptr<base::IDataArray> BaseTagFS::getReference(const std::string &name_or_id) const {
std::shared_ptr<base::IDataArray> da;
std::string id = name_or_id;
if (!util::looksLikeUUID(name_or_id) && block()->hasDataArray(name_or_id)) {
id = block()->getDataArray(name_or_id)->id();
}
if (hasReference(id)) {
boost::optional<bfs::path> path = refs_group.findByNameOrAttribute("name", name_or_id);
if (path) {
return std::make_shared<DataArrayFS>(file(), block(), path->string());
}
}
return da;
}
std::shared_ptr<base::IDataArray> BaseTagFS::getReference(size_t index) const {
if(index > referenceCount()) {
throw OutOfBounds("No reference at given index", index);
}
bfs::path p = refs_group.sub_dir_by_index(index);
return std::make_shared<DataArrayFS>(file(), block(), p.string());
}
void BaseTagFS::addReference(const std::string &name_or_id) {
if (name_or_id.empty())
throw EmptyString("addReference");
if (!block()->hasDataArray(name_or_id))
throw std::runtime_error("BaseTagFS::addReference: DataArray not found in block!");
auto target = std::dynamic_pointer_cast<DataArrayFS>(block()->getDataArray(name_or_id));
refs_group.createDirectoryLink(target->location(), target->id());
}
bool BaseTagFS::removeReference(const std::string &name_or_id) {
return refs_group.removeObjectByNameOrAttribute("name", name_or_id);
}
void BaseTagFS::references(const std::vector<DataArray> &refs_new) {
// extract vectors of names from vectors of new & old references
std::vector<std::string> names_new(refs_new.size());
transform(refs_new.begin(), refs_new.end(), names_new.begin(), util::toName<DataArray>);
size_t count = nix::check::fits_in_size_t(referenceCount(), "referenceCount() failed! count > than size_t!");
std::vector<DataArray> refs_old(count);
for (size_t i = 0; i < refs_old.size(); i++){
refs_old[i] = getReference(i);
}
std::vector<std::string> names_old(refs_old.size());
std::transform(refs_old.begin(), refs_old.end(), names_old.begin(), util::toName<DataArray>);
// sort them
std::sort(names_new.begin(), names_new.end());
std::sort(names_new.begin(), names_new.end());
// get names only in names_new (add), names only in names_old (remove) & ignore rest
std::vector<std::string> names_add;
std::vector<std::string> names_rem;
std::set_difference(names_new.begin(), names_new.end(), names_old.begin(), names_old.end(),
std::inserter(names_add, names_add.begin()));
std::set_difference(names_old.begin(), names_old.end(), names_new.begin(), names_new.end(),
std::inserter(names_rem, names_rem.begin()));
// check if all new references exist & add sources
auto blck = std::dynamic_pointer_cast<BlockFS>(block());
for (auto name : names_add) {
if (!blck->hasDataArray(name))
throw std::runtime_error("One or more data arrays do not exist in this block!");
addReference(blck->getDataArray(name)->id());
}
// remove references
for (auto name : names_rem) {
if (!blck->hasDataArray(name))
removeReference(blck->getDataArray(name)->id());
}
}
//--------------------------------------------------
// Methods concerning features.
//--------------------------------------------------
bool BaseTagFS::hasFeature(const std::string &name_or_id) const {
return !feature_group.findByNameOrAttribute("entity_id", name_or_id)->empty();
}
ndsize_t BaseTagFS::featureCount() const {
return feature_group.subdirCount();
}
std::shared_ptr<base::IFeature> BaseTagFS::getFeature(const std::string &name_or_id) const {
std::shared_ptr<base::IFeature> feature;
boost::optional<bfs::path> p = feature_group.findByNameOrAttribute("name", name_or_id);
if (p) {
return std::make_shared<FeatureFS>(file(), block(), p->string());
}
return feature;
}
std::shared_ptr<base::IFeature> BaseTagFS::getFeature(size_t index) const {
if (index >= featureCount()) {
throw OutOfBounds("Trying to access a feature with an invalid index!");
}
bfs::path id = feature_group.sub_dir_by_index(index);
return getFeature(id.filename().string());
}
std::shared_ptr<base::IFeature> BaseTagFS::createFeature(const std::string &name_or_id, LinkType link_type) {
if(!block()->hasDataArray(name_or_id)) {
throw std::runtime_error("DataArray not found in Block!");
}
std::string rep_id = util::createId();
DataArray a = block()->getDataArray(name_or_id);
return std::make_shared<FeatureFS>(file(), block(), feature_group.location(), rep_id, a, link_type);
}
bool BaseTagFS::deleteFeature(const std::string &name_or_id) {
return feature_group.removeObjectByNameOrAttribute("name", name_or_id);
}
BaseTagFS::~BaseTagFS() {}
} // ns nix::file
} // ns nix<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2017 Gleb Mishchenko, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// appleseed.foundation headers.
#include "foundation/utility/test.h"
#include "foundation/utility/unzipper.h"
// Boost headers
#include "boost/filesystem.hpp"
// Standard headers
#include <set>
#include <vector>
#include <iostream>
using namespace foundation;
using namespace std;
namespace bf = boost::filesystem;
TEST_SUITE(Foundation_Utility_Unzipper)
{
const string valid_project = "unit tests/inputs/test_packed_project_valid.appleseedz";
const string invalid_project = "unit tests/inputs/test_packed_project_invalid.appleseedz";
set<string> recursive_ls(bf::path dir)
{
set<string> files;
// A default constructed directory_iterator acts as the end iterator
bf::directory_iterator end_iter;
for (bf::directory_iterator dir_itr(dir); dir_itr != end_iter; ++dir_itr)
{
const bf::path current_path = dir_itr->path();
if (bf::is_directory(current_path))
{
const string dirname = current_path.filename().string();
const set<string> files_in_subdir = recursive_ls(current_path);
for (set<string>::iterator it = files_in_subdir.begin(); it != files_in_subdir.end(); ++it)
files.insert(dirname + "/" + *it);
}
else
files.insert(current_path.filename().string());
}
return files;
}
TEST_CASE(UnzipTest)
{
const string unpacked_dir = valid_project + ".unpacked";
try
{
unzip(valid_project, unpacked_dir);
EXPECT_EQ(true, bf::exists(bf::path(unpacked_dir)));
EXPECT_EQ(false, bf::is_empty(bf::path(unpacked_dir)));
const string expected_files[] =
{
"01 - lambertiannrdf - arealight.appleseed",
"geometry/sphere.obj",
"geometry/Box002.binarymesh",
"geometry/GeoSphere001.binarymesh",
"geometry/dirpole reference sphere.obj",
"geometry/Box001.binarymesh",
"geometry/plane.obj",
"geometry/Sphere002.binarymesh",
"geometry/Plane002.binarymesh",
"geometry/cube.obj",
"geometry/Plane001.binarymesh"
};
const set<string> actual_files = recursive_ls(bf::path(unpacked_dir));
for (size_t i = 0; i < 11; ++i)
{
EXPECT_EQ(1, actual_files.count(expected_files[i]));
}
bf::remove_all(bf::path(unpacked_dir));
}
catch (exception e)
{
bf::remove_all(bf::path(unpacked_dir));
throw e;
}
}
TEST_CASE(FilesnamesWithExtensionTest)
{
const string extension = ".appleseed";
const vector<string> appleseed_files_4 = get_filenames_with_extension_from_zip(invalid_project, extension);
const vector<string> appleseed_files_1 = get_filenames_with_extension_from_zip(valid_project, extension);
EXPECT_EQ(4, appleseed_files_4.size());
EXPECT_EQ(1, appleseed_files_1.size());
EXPECT_EQ("01 - lambertiannrdf - arealight.appleseed", appleseed_files_1[0]);
}
}
<commit_msg>Split FilesnamesWithExtensionTest test on two<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2017 Gleb Mishchenko, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// appleseed.foundation headers.
#include "foundation/utility/test.h"
#include "foundation/utility/unzipper.h"
// Boost headers
#include "boost/filesystem.hpp"
// Standard headers
#include <set>
#include <vector>
#include <iostream>
using namespace foundation;
using namespace std;
namespace bf = boost::filesystem;
TEST_SUITE(Foundation_Utility_Unzipper)
{
const string valid_project = "unit tests/inputs/test_packed_project_valid.appleseedz";
const string invalid_project = "unit tests/inputs/test_packed_project_invalid.appleseedz";
set<string> recursive_ls(bf::path dir)
{
set<string> files;
// A default constructed directory_iterator acts as the end iterator
bf::directory_iterator end_iter;
for (bf::directory_iterator dir_itr(dir); dir_itr != end_iter; ++dir_itr)
{
const bf::path current_path = dir_itr->path();
if (bf::is_directory(current_path))
{
const string dirname = current_path.filename().string();
const set<string> files_in_subdir = recursive_ls(current_path);
for (set<string>::iterator it = files_in_subdir.begin(); it != files_in_subdir.end(); ++it)
files.insert(dirname + "/" + *it);
}
else
files.insert(current_path.filename().string());
}
return files;
}
TEST_CASE(UnzipTest)
{
const string unpacked_dir = valid_project + ".unpacked";
try
{
unzip(valid_project, unpacked_dir);
EXPECT_EQ(true, bf::exists(bf::path(unpacked_dir)));
EXPECT_EQ(false, bf::is_empty(bf::path(unpacked_dir)));
const string expected_files[] =
{
"01 - lambertiannrdf - arealight.appleseed",
"geometry/sphere.obj",
"geometry/Box002.binarymesh",
"geometry/GeoSphere001.binarymesh",
"geometry/dirpole reference sphere.obj",
"geometry/Box001.binarymesh",
"geometry/plane.obj",
"geometry/Sphere002.binarymesh",
"geometry/Plane002.binarymesh",
"geometry/cube.obj",
"geometry/Plane001.binarymesh"
};
const set<string> actual_files = recursive_ls(bf::path(unpacked_dir));
for (size_t i = 0; i < 11; ++i)
{
EXPECT_EQ(1, actual_files.count(expected_files[i]));
}
bf::remove_all(bf::path(unpacked_dir));
}
catch (exception e)
{
bf::remove_all(bf::path(unpacked_dir));
throw e;
}
}
TEST_CASE(FilesnamesWithExtensionOneFile)
{
const string extension = ".appleseed";
const vector<string> appleseed_files_1 = get_filenames_with_extension_from_zip(valid_project, extension);
EXPECT_EQ(1, appleseed_files_1.size());
EXPECT_EQ("01 - lambertiannrdf - arealight.appleseed", appleseed_files_1[0]);
}
TEST_CASE(FilesnamesWithExtensionSeveralFiles)
{
const string extension = ".appleseed";
const vector<string> appleseed_files_4 = get_filenames_with_extension_from_zip(invalid_project, extension);
EXPECT_EQ(4, appleseed_files_4.size());
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This translation unit generates microdumps into the console (logcat on
// Android). See crbug.com/410294 for more info and design docs.
#include "client/linux/microdump_writer/microdump_writer.h"
#include <sys/utsname.h>
#include "client/linux/dump_writer_common/seccomp_unwinder.h"
#include "client/linux/dump_writer_common/thread_info.h"
#include "client/linux/dump_writer_common/ucontext_reader.h"
#include "client/linux/handler/exception_handler.h"
#include "client/linux/log/log.h"
#include "client/linux/minidump_writer/linux_ptrace_dumper.h"
#include "common/linux/linux_libc_support.h"
#include "common/scoped_ptr.h"
namespace {
using google_breakpad::ExceptionHandler;
using google_breakpad::LinuxDumper;
using google_breakpad::LinuxPtraceDumper;
using google_breakpad::MappingInfo;
using google_breakpad::MappingList;
using google_breakpad::RawContextCPU;
using google_breakpad::scoped_array;
using google_breakpad::SeccompUnwinder;
using google_breakpad::ThreadInfo;
using google_breakpad::UContextReader;
const size_t kLineBufferSize = 2048;
class MicrodumpWriter {
public:
MicrodumpWriter(const ExceptionHandler::CrashContext* context,
const MappingList& mappings,
LinuxDumper* dumper)
: ucontext_(context ? &context->context : NULL),
#if !defined(__ARM_EABI__) && !defined(__mips__)
float_state_(context ? &context->float_state : NULL),
#endif
dumper_(dumper),
mapping_list_(mappings),
log_line_(new char[kLineBufferSize]) {
log_line_.get()[0] = '\0'; // Clear out the log line buffer.
}
~MicrodumpWriter() { dumper_->ThreadsResume(); }
bool Init() {
if (!dumper_->Init())
return false;
return dumper_->ThreadsSuspend();
}
bool Dump() {
bool success;
LogLine("-----BEGIN BREAKPAD MICRODUMP-----");
success = DumpOSInformation();
if (success)
success = DumpCrashingThread();
if (success)
success = DumpMappings();
LogLine("-----END BREAKPAD MICRODUMP-----");
dumper_->ThreadsResume();
return success;
}
private:
// Writes one line to the system log.
void LogLine(const char* msg) {
logger::write(msg, my_strlen(msg));
#if !defined(__ANDROID__)
logger::write("\n", 1); // Android logger appends the \n. Linux's doesn't.
#endif
}
// Stages the given string in the current line buffer.
void LogAppend(const char* str) {
my_strlcat(log_line_.get(), str, kLineBufferSize);
}
// As above (required to take precedence over template specialization below).
void LogAppend(char* str) {
LogAppend(const_cast<const char*>(str));
}
// Stages the hex repr. of the given int type in the current line buffer.
template<typename T>
void LogAppend(T value) {
// Make enough room to hex encode the largest int type + NUL.
static const char HEX[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'};
char hexstr[sizeof(T) * 2 + 1];
for (int i = sizeof(T) * 2 - 1; i >= 0; --i, value >>= 4)
hexstr[i] = HEX[static_cast<uint8_t>(value) & 0x0F];
hexstr[sizeof(T) * 2] = '\0';
LogAppend(hexstr);
}
// Stages the buffer content hex-encoded in the current line buffer.
void LogAppend(const void* buf, size_t length) {
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(buf);
for (size_t i = 0; i < length; ++i, ++ptr)
LogAppend(*ptr);
}
// Writes out the current line buffer on the system log.
void LogCommitLine() {
LogLine(log_line_.get());
my_strlcpy(log_line_.get(), "", kLineBufferSize);
}
bool DumpOSInformation() {
struct utsname uts;
if (uname(&uts))
return false;
const uint8_t n_cpus = static_cast<uint8_t>(sysconf(_SC_NPROCESSORS_CONF));
#if defined(__ANDROID__)
const char kOSId[] = "A";
#else
const char kOSId[] = "L";
#endif
// We cannot depend on uts.machine. On multiarch devices it always returns the
// primary arch, not the one that match the executable being run.
#if defined(__aarch64__)
const char kArch[] = "arm64";
#elif defined(__ARMEL__)
const char kArch[] = "arm";
#elif defined(__x86_64__)
const char kArch[] = "x86_64";
#elif defined(__i386__)
const char kArch[] = "x86";
#elif defined(__mips__)
const char kArch[] = "mips";
#else
#error "This code has not been ported to your platform yet"
#endif
LogAppend("O ");
LogAppend(kOSId);
LogAppend(" ");
LogAppend(kArch);
LogAppend(" ");
LogAppend(n_cpus);
LogAppend(" ");
LogAppend(uts.machine);
LogAppend(" ");
LogAppend(uts.release);
LogAppend(" ");
LogAppend(uts.version);
LogCommitLine();
return true;
}
bool DumpThreadStack(uint32_t thread_id,
uintptr_t stack_pointer,
int max_stack_len,
uint8_t** stack_copy) {
*stack_copy = NULL;
const void* stack;
size_t stack_len;
if (!dumper_->GetStackInfo(&stack, &stack_len, stack_pointer)) {
// The stack pointer might not be available. In this case we don't hard
// fail, just produce a (almost useless) microdump w/o a stack section.
return true;
}
LogAppend("S 0 ");
LogAppend(stack_pointer);
LogAppend(" ");
LogAppend(reinterpret_cast<uintptr_t>(stack));
LogAppend(" ");
LogAppend(stack_len);
LogCommitLine();
if (max_stack_len >= 0 &&
stack_len > static_cast<unsigned int>(max_stack_len)) {
stack_len = max_stack_len;
}
*stack_copy = reinterpret_cast<uint8_t*>(Alloc(stack_len));
dumper_->CopyFromProcess(*stack_copy, thread_id, stack, stack_len);
// Dump the content of the stack, splicing it into chunks which size is
// compatible with the max logcat line size (see LOGGER_ENTRY_MAX_PAYLOAD).
const size_t STACK_DUMP_CHUNK_SIZE = 384;
for (size_t stack_off = 0; stack_off < stack_len;
stack_off += STACK_DUMP_CHUNK_SIZE) {
LogAppend("S ");
LogAppend(reinterpret_cast<uintptr_t>(stack) + stack_off);
LogAppend(" ");
LogAppend(*stack_copy + stack_off,
std::min(STACK_DUMP_CHUNK_SIZE, stack_len - stack_off));
LogCommitLine();
}
return true;
}
// Write information about the crashing thread.
bool DumpCrashingThread() {
const unsigned num_threads = dumper_->threads().size();
for (unsigned i = 0; i < num_threads; ++i) {
MDRawThread thread;
my_memset(&thread, 0, sizeof(thread));
thread.thread_id = dumper_->threads()[i];
// Dump only the crashing thread.
if (static_cast<pid_t>(thread.thread_id) != dumper_->crash_thread())
continue;
assert(ucontext_);
assert(!dumper_->IsPostMortem());
uint8_t* stack_copy;
const uintptr_t stack_ptr = UContextReader::GetStackPointer(ucontext_);
if (!DumpThreadStack(thread.thread_id, stack_ptr, -1, &stack_copy))
return false;
RawContextCPU cpu;
my_memset(&cpu, 0, sizeof(RawContextCPU));
#if !defined(__ARM_EABI__) && !defined(__mips__)
UContextReader::FillCPUContext(&cpu, ucontext_, float_state_);
#else
UContextReader::FillCPUContext(&cpu, ucontext_);
#endif
if (stack_copy)
SeccompUnwinder::PopSeccompStackFrame(&cpu, thread, stack_copy);
DumpCPUState(&cpu);
}
return true;
}
void DumpCPUState(RawContextCPU* cpu) {
LogAppend("C ");
LogAppend(cpu, sizeof(*cpu));
LogCommitLine();
}
// If there is caller-provided information about this mapping
// in the mapping_list_ list, return true. Otherwise, return false.
bool HaveMappingInfo(const MappingInfo& mapping) {
for (MappingList::const_iterator iter = mapping_list_.begin();
iter != mapping_list_.end();
++iter) {
// Ignore any mappings that are wholly contained within
// mappings in the mapping_info_ list.
if (mapping.start_addr >= iter->first.start_addr &&
(mapping.start_addr + mapping.size) <=
(iter->first.start_addr + iter->first.size)) {
return true;
}
}
return false;
}
// Dump information about the provided |mapping|. If |identifier| is non-NULL,
// use it instead of calculating a file ID from the mapping.
void DumpModule(const MappingInfo& mapping,
bool member,
unsigned int mapping_id,
const uint8_t* identifier) {
MDGUID module_identifier;
if (identifier) {
// GUID was provided by caller.
my_memcpy(&module_identifier, identifier, sizeof(MDGUID));
} else {
dumper_->ElfFileIdentifierForMapping(
mapping,
member,
mapping_id,
reinterpret_cast<uint8_t*>(&module_identifier));
}
char file_name[NAME_MAX];
char file_path[NAME_MAX];
LinuxDumper::GetMappingEffectiveNameAndPath(
mapping, file_path, sizeof(file_path), file_name, sizeof(file_name));
LogAppend("M ");
LogAppend(static_cast<uintptr_t>(mapping.start_addr));
LogAppend(" ");
LogAppend(mapping.offset);
LogAppend(" ");
LogAppend(mapping.size);
LogAppend(" ");
LogAppend(module_identifier.data1);
LogAppend(module_identifier.data2);
LogAppend(module_identifier.data3);
LogAppend(module_identifier.data4[0]);
LogAppend(module_identifier.data4[1]);
LogAppend(module_identifier.data4[2]);
LogAppend(module_identifier.data4[3]);
LogAppend(module_identifier.data4[4]);
LogAppend(module_identifier.data4[5]);
LogAppend(module_identifier.data4[6]);
LogAppend(module_identifier.data4[7]);
LogAppend("0 "); // Age is always 0 on Linux.
LogAppend(file_name);
LogCommitLine();
}
// Write information about the mappings in effect.
bool DumpMappings() {
// First write all the mappings from the dumper
for (unsigned i = 0; i < dumper_->mappings().size(); ++i) {
const MappingInfo& mapping = *dumper_->mappings()[i];
if (mapping.name[0] == 0 || // only want modules with filenames.
!mapping.exec || // only want executable mappings.
mapping.size < 4096 || // too small to get a signature for.
HaveMappingInfo(mapping)) {
continue;
}
DumpModule(mapping, true, i, NULL);
}
// Next write all the mappings provided by the caller
for (MappingList::const_iterator iter = mapping_list_.begin();
iter != mapping_list_.end();
++iter) {
DumpModule(iter->first, false, 0, iter->second);
}
return true;
}
void* Alloc(unsigned bytes) { return dumper_->allocator()->Alloc(bytes); }
const struct ucontext* const ucontext_;
#if !defined(__ARM_EABI__) && !defined(__mips__)
const google_breakpad::fpstate_t* const float_state_;
#endif
LinuxDumper* dumper_;
const MappingList& mapping_list_;
scoped_array<char> log_line_;
};
} // namespace
namespace google_breakpad {
bool WriteMicrodump(pid_t crashing_process,
const void* blob,
size_t blob_size,
const MappingList& mappings) {
LinuxPtraceDumper dumper(crashing_process);
const ExceptionHandler::CrashContext* context = NULL;
if (blob) {
if (blob_size != sizeof(ExceptionHandler::CrashContext))
return false;
context = reinterpret_cast<const ExceptionHandler::CrashContext*>(blob);
dumper.set_crash_address(
reinterpret_cast<uintptr_t>(context->siginfo.si_addr));
dumper.set_crash_signal(context->siginfo.si_signo);
dumper.set_crash_thread(context->tid);
}
MicrodumpWriter writer(context, mappings, &dumper);
if (!writer.Init())
return false;
return writer.Dump();
}
} // namespace google_breakpad
<commit_msg>Microdump writer: stop using new/malloc in compromised context<commit_after>// Copyright (c) 2014, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// This translation unit generates microdumps into the console (logcat on
// Android). See crbug.com/410294 for more info and design docs.
#include "client/linux/microdump_writer/microdump_writer.h"
#include <sys/utsname.h>
#include "client/linux/dump_writer_common/seccomp_unwinder.h"
#include "client/linux/dump_writer_common/thread_info.h"
#include "client/linux/dump_writer_common/ucontext_reader.h"
#include "client/linux/handler/exception_handler.h"
#include "client/linux/log/log.h"
#include "client/linux/minidump_writer/linux_ptrace_dumper.h"
#include "common/linux/linux_libc_support.h"
namespace {
using google_breakpad::ExceptionHandler;
using google_breakpad::LinuxDumper;
using google_breakpad::LinuxPtraceDumper;
using google_breakpad::MappingInfo;
using google_breakpad::MappingList;
using google_breakpad::RawContextCPU;
using google_breakpad::SeccompUnwinder;
using google_breakpad::ThreadInfo;
using google_breakpad::UContextReader;
const size_t kLineBufferSize = 2048;
class MicrodumpWriter {
public:
MicrodumpWriter(const ExceptionHandler::CrashContext* context,
const MappingList& mappings,
LinuxDumper* dumper)
: ucontext_(context ? &context->context : NULL),
#if !defined(__ARM_EABI__) && !defined(__mips__)
float_state_(context ? &context->float_state : NULL),
#endif
dumper_(dumper),
mapping_list_(mappings),
log_line_(NULL) {
log_line_ = reinterpret_cast<char*>(Alloc(kLineBufferSize));
if (log_line_)
log_line_[0] = '\0'; // Clear out the log line buffer.
}
~MicrodumpWriter() { dumper_->ThreadsResume(); }
bool Init() {
// In the exceptional case where the system was out of memory and there
// wasn't even room to allocate the line buffer, bail out. There is nothing
// useful we can possibly achieve without the ability to Log. At least let's
// try to not crash.
if (!dumper_->Init() || !log_line_)
return false;
return dumper_->ThreadsSuspend();
}
bool Dump() {
bool success;
LogLine("-----BEGIN BREAKPAD MICRODUMP-----");
success = DumpOSInformation();
if (success)
success = DumpCrashingThread();
if (success)
success = DumpMappings();
LogLine("-----END BREAKPAD MICRODUMP-----");
dumper_->ThreadsResume();
return success;
}
private:
// Writes one line to the system log.
void LogLine(const char* msg) {
logger::write(msg, my_strlen(msg));
#if !defined(__ANDROID__)
logger::write("\n", 1); // Android logger appends the \n. Linux's doesn't.
#endif
}
// Stages the given string in the current line buffer.
void LogAppend(const char* str) {
my_strlcat(log_line_, str, kLineBufferSize);
}
// As above (required to take precedence over template specialization below).
void LogAppend(char* str) {
LogAppend(const_cast<const char*>(str));
}
// Stages the hex repr. of the given int type in the current line buffer.
template<typename T>
void LogAppend(T value) {
// Make enough room to hex encode the largest int type + NUL.
static const char HEX[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'};
char hexstr[sizeof(T) * 2 + 1];
for (int i = sizeof(T) * 2 - 1; i >= 0; --i, value >>= 4)
hexstr[i] = HEX[static_cast<uint8_t>(value) & 0x0F];
hexstr[sizeof(T) * 2] = '\0';
LogAppend(hexstr);
}
// Stages the buffer content hex-encoded in the current line buffer.
void LogAppend(const void* buf, size_t length) {
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(buf);
for (size_t i = 0; i < length; ++i, ++ptr)
LogAppend(*ptr);
}
// Writes out the current line buffer on the system log.
void LogCommitLine() {
LogLine(log_line_);
my_strlcpy(log_line_, "", kLineBufferSize);
}
bool DumpOSInformation() {
struct utsname uts;
if (uname(&uts))
return false;
const uint8_t n_cpus = static_cast<uint8_t>(sysconf(_SC_NPROCESSORS_CONF));
#if defined(__ANDROID__)
const char kOSId[] = "A";
#else
const char kOSId[] = "L";
#endif
// We cannot depend on uts.machine. On multiarch devices it always returns the
// primary arch, not the one that match the executable being run.
#if defined(__aarch64__)
const char kArch[] = "arm64";
#elif defined(__ARMEL__)
const char kArch[] = "arm";
#elif defined(__x86_64__)
const char kArch[] = "x86_64";
#elif defined(__i386__)
const char kArch[] = "x86";
#elif defined(__mips__)
const char kArch[] = "mips";
#else
#error "This code has not been ported to your platform yet"
#endif
LogAppend("O ");
LogAppend(kOSId);
LogAppend(" ");
LogAppend(kArch);
LogAppend(" ");
LogAppend(n_cpus);
LogAppend(" ");
LogAppend(uts.machine);
LogAppend(" ");
LogAppend(uts.release);
LogAppend(" ");
LogAppend(uts.version);
LogCommitLine();
return true;
}
bool DumpThreadStack(uint32_t thread_id,
uintptr_t stack_pointer,
int max_stack_len,
uint8_t** stack_copy) {
*stack_copy = NULL;
const void* stack;
size_t stack_len;
if (!dumper_->GetStackInfo(&stack, &stack_len, stack_pointer)) {
// The stack pointer might not be available. In this case we don't hard
// fail, just produce a (almost useless) microdump w/o a stack section.
return true;
}
LogAppend("S 0 ");
LogAppend(stack_pointer);
LogAppend(" ");
LogAppend(reinterpret_cast<uintptr_t>(stack));
LogAppend(" ");
LogAppend(stack_len);
LogCommitLine();
if (max_stack_len >= 0 &&
stack_len > static_cast<unsigned int>(max_stack_len)) {
stack_len = max_stack_len;
}
*stack_copy = reinterpret_cast<uint8_t*>(Alloc(stack_len));
dumper_->CopyFromProcess(*stack_copy, thread_id, stack, stack_len);
// Dump the content of the stack, splicing it into chunks which size is
// compatible with the max logcat line size (see LOGGER_ENTRY_MAX_PAYLOAD).
const size_t STACK_DUMP_CHUNK_SIZE = 384;
for (size_t stack_off = 0; stack_off < stack_len;
stack_off += STACK_DUMP_CHUNK_SIZE) {
LogAppend("S ");
LogAppend(reinterpret_cast<uintptr_t>(stack) + stack_off);
LogAppend(" ");
LogAppend(*stack_copy + stack_off,
std::min(STACK_DUMP_CHUNK_SIZE, stack_len - stack_off));
LogCommitLine();
}
return true;
}
// Write information about the crashing thread.
bool DumpCrashingThread() {
const unsigned num_threads = dumper_->threads().size();
for (unsigned i = 0; i < num_threads; ++i) {
MDRawThread thread;
my_memset(&thread, 0, sizeof(thread));
thread.thread_id = dumper_->threads()[i];
// Dump only the crashing thread.
if (static_cast<pid_t>(thread.thread_id) != dumper_->crash_thread())
continue;
assert(ucontext_);
assert(!dumper_->IsPostMortem());
uint8_t* stack_copy;
const uintptr_t stack_ptr = UContextReader::GetStackPointer(ucontext_);
if (!DumpThreadStack(thread.thread_id, stack_ptr, -1, &stack_copy))
return false;
RawContextCPU cpu;
my_memset(&cpu, 0, sizeof(RawContextCPU));
#if !defined(__ARM_EABI__) && !defined(__mips__)
UContextReader::FillCPUContext(&cpu, ucontext_, float_state_);
#else
UContextReader::FillCPUContext(&cpu, ucontext_);
#endif
if (stack_copy)
SeccompUnwinder::PopSeccompStackFrame(&cpu, thread, stack_copy);
DumpCPUState(&cpu);
}
return true;
}
void DumpCPUState(RawContextCPU* cpu) {
LogAppend("C ");
LogAppend(cpu, sizeof(*cpu));
LogCommitLine();
}
// If there is caller-provided information about this mapping
// in the mapping_list_ list, return true. Otherwise, return false.
bool HaveMappingInfo(const MappingInfo& mapping) {
for (MappingList::const_iterator iter = mapping_list_.begin();
iter != mapping_list_.end();
++iter) {
// Ignore any mappings that are wholly contained within
// mappings in the mapping_info_ list.
if (mapping.start_addr >= iter->first.start_addr &&
(mapping.start_addr + mapping.size) <=
(iter->first.start_addr + iter->first.size)) {
return true;
}
}
return false;
}
// Dump information about the provided |mapping|. If |identifier| is non-NULL,
// use it instead of calculating a file ID from the mapping.
void DumpModule(const MappingInfo& mapping,
bool member,
unsigned int mapping_id,
const uint8_t* identifier) {
MDGUID module_identifier;
if (identifier) {
// GUID was provided by caller.
my_memcpy(&module_identifier, identifier, sizeof(MDGUID));
} else {
dumper_->ElfFileIdentifierForMapping(
mapping,
member,
mapping_id,
reinterpret_cast<uint8_t*>(&module_identifier));
}
char file_name[NAME_MAX];
char file_path[NAME_MAX];
LinuxDumper::GetMappingEffectiveNameAndPath(
mapping, file_path, sizeof(file_path), file_name, sizeof(file_name));
LogAppend("M ");
LogAppend(static_cast<uintptr_t>(mapping.start_addr));
LogAppend(" ");
LogAppend(mapping.offset);
LogAppend(" ");
LogAppend(mapping.size);
LogAppend(" ");
LogAppend(module_identifier.data1);
LogAppend(module_identifier.data2);
LogAppend(module_identifier.data3);
LogAppend(module_identifier.data4[0]);
LogAppend(module_identifier.data4[1]);
LogAppend(module_identifier.data4[2]);
LogAppend(module_identifier.data4[3]);
LogAppend(module_identifier.data4[4]);
LogAppend(module_identifier.data4[5]);
LogAppend(module_identifier.data4[6]);
LogAppend(module_identifier.data4[7]);
LogAppend("0 "); // Age is always 0 on Linux.
LogAppend(file_name);
LogCommitLine();
}
// Write information about the mappings in effect.
bool DumpMappings() {
// First write all the mappings from the dumper
for (unsigned i = 0; i < dumper_->mappings().size(); ++i) {
const MappingInfo& mapping = *dumper_->mappings()[i];
if (mapping.name[0] == 0 || // only want modules with filenames.
!mapping.exec || // only want executable mappings.
mapping.size < 4096 || // too small to get a signature for.
HaveMappingInfo(mapping)) {
continue;
}
DumpModule(mapping, true, i, NULL);
}
// Next write all the mappings provided by the caller
for (MappingList::const_iterator iter = mapping_list_.begin();
iter != mapping_list_.end();
++iter) {
DumpModule(iter->first, false, 0, iter->second);
}
return true;
}
void* Alloc(unsigned bytes) { return dumper_->allocator()->Alloc(bytes); }
const struct ucontext* const ucontext_;
#if !defined(__ARM_EABI__) && !defined(__mips__)
const google_breakpad::fpstate_t* const float_state_;
#endif
LinuxDumper* dumper_;
const MappingList& mapping_list_;
char* log_line_;
};
} // namespace
namespace google_breakpad {
bool WriteMicrodump(pid_t crashing_process,
const void* blob,
size_t blob_size,
const MappingList& mappings) {
LinuxPtraceDumper dumper(crashing_process);
const ExceptionHandler::CrashContext* context = NULL;
if (blob) {
if (blob_size != sizeof(ExceptionHandler::CrashContext))
return false;
context = reinterpret_cast<const ExceptionHandler::CrashContext*>(blob);
dumper.set_crash_address(
reinterpret_cast<uintptr_t>(context->siginfo.si_addr));
dumper.set_crash_signal(context->siginfo.si_signo);
dumper.set_crash_thread(context->tid);
}
MicrodumpWriter writer(context, mappings, &dumper);
if (!writer.Init())
return false;
return writer.Dump();
}
} // namespace google_breakpad
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <gtest/gtest.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Matrix.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.h>
#include <Testing/Utils/SCIRunUnitTests.h>
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::TestUtils;
namespace
{
void runTest(int basis, int expectedMatrixRows, int expectedMatrixColumns, const std::string& expectedMatrixString = "")
{
std::cout << "Basis # " << basis << std::endl;
FieldInformation lfi("LatVolMesh", basis, "double");
size_type sizex = 2, sizey = 3, sizez = 4;
Point minb(-1.0, -1.0, -1.0);
Point maxb(1.0, 1.0, 1.0);
MeshHandle mesh = CreateMesh(lfi,sizex, sizey, sizez, minb, maxb);
FieldHandle ofh = CreateField(lfi,mesh);
ofh->vfield()->clear_all_values();
GetFieldBoundaryAlgo algo;
FieldHandle boundary;
MatrixHandle mapping;
algo.run(ofh, boundary, mapping);
ASSERT_TRUE(boundary.get() != nullptr);
/// @todo: need assertions on boundary field
if (basis != -1)
{
ASSERT_TRUE(mapping.get() != nullptr);
EXPECT_EQ(expectedMatrixRows, mapping->nrows());
EXPECT_EQ(expectedMatrixColumns, mapping->ncols());
std::ostringstream ostr;
ostr << *mapping;
//std::cout << "expected\n" << expectedMatrixString << std::endl;
//std::cout << "actual\n" << ostr.str() << std::endl;
EXPECT_EQ(expectedMatrixString, ostr.str());
}
}
const std::string matrixCells =
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n";
const std::string matrixNodes =
"1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 \n";
}
TEST(GetFieldBoundaryTest, LatVolBoundary)
{
runTest(0, 22, 6, matrixCells);
runTest(-1, 0, 0);
runTest(1, 24, 24, matrixNodes);
/*
EXPECT_EQ("GenericField<LatVolMesh<HexTrilinearLgn<Point> > ,NoDataBasis<double> ,FData3d<double,LatVolMesh<HexTrilinearLgn<Point> > > > ", info.type);
EXPECT_EQ(0, info.dataMin);
EXPECT_EQ(0, info.dataMax);
EXPECT_EQ(0, info.numdata_);
EXPECT_EQ(sizex * sizey * sizez, info.numnodes_);
EXPECT_EQ((sizex-1) * (sizey-1) * (sizez-1), info.numelements_);
EXPECT_EQ("None (nodata basis)", info.dataLocation);*/
}
TEST(GetFieldBoundaryTest, CanLogErrorMessage)
{
GetFieldBoundaryAlgo algo;
FieldHandle input, output;
MatrixHandle mapping;
EXPECT_FALSE(algo.run(input, output, mapping));
EXPECT_FALSE(algo.run(input, output));
}<commit_msg>Fix yet another Eigen matrix string debug diff<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <gtest/gtest.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Datatypes/Matrix.h>
#include <Core/Datatypes/MatrixIO.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundaryAlgo.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Testing/Utils/SCIRunUnitTests.h>
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::TestUtils;
namespace
{
void runTest(int basis, int expectedMatrixRows, int expectedMatrixColumns, const std::string& expectedMatrixString = "")
{
std::cout << "Basis # " << basis << std::endl;
FieldInformation lfi("LatVolMesh", basis, "double");
size_type sizex = 2, sizey = 3, sizez = 4;
Point minb(-1.0, -1.0, -1.0);
Point maxb(1.0, 1.0, 1.0);
MeshHandle mesh = CreateMesh(lfi,sizex, sizey, sizez, minb, maxb);
FieldHandle ofh = CreateField(lfi,mesh);
ofh->vfield()->clear_all_values();
GetFieldBoundaryAlgo algo;
FieldHandle boundary;
MatrixHandle mapping;
algo.run(ofh, boundary, mapping);
ASSERT_TRUE(boundary.get() != nullptr);
/// @todo: need assertions on boundary field
if (basis != -1)
{
ASSERT_TRUE(mapping != nullptr);
EXPECT_EQ(expectedMatrixRows, mapping->nrows());
EXPECT_EQ(expectedMatrixColumns, mapping->ncols());
EXPECT_EQ(expectedMatrixString, matrix_to_string(*matrix_convert::to_dense(mapping)));
}
}
const std::string matrixCells =
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"1 0 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 1 0 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 1 0 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 1 0 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 1 0 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n"
"0 0 0 0 0 1 \n";
const std::string matrixNodes =
"1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 \n"
"0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 \n";
}
TEST(GetFieldBoundaryTest, LatVolBoundary)
{
runTest(0, 22, 6, matrixCells);
runTest(-1, 0, 0);
runTest(1, 24, 24, matrixNodes);
/*
EXPECT_EQ("GenericField<LatVolMesh<HexTrilinearLgn<Point> > ,NoDataBasis<double> ,FData3d<double,LatVolMesh<HexTrilinearLgn<Point> > > > ", info.type);
EXPECT_EQ(0, info.dataMin);
EXPECT_EQ(0, info.dataMax);
EXPECT_EQ(0, info.numdata_);
EXPECT_EQ(sizex * sizey * sizez, info.numnodes_);
EXPECT_EQ((sizex-1) * (sizey-1) * (sizez-1), info.numelements_);
EXPECT_EQ("None (nodata basis)", info.dataLocation);*/
}
TEST(GetFieldBoundaryTest, CanLogErrorMessage)
{
GetFieldBoundaryAlgo algo;
FieldHandle input, output;
MatrixHandle mapping;
EXPECT_FALSE(algo.run(input, output, mapping));
EXPECT_FALSE(algo.run(input, output));
}<|endoftext|> |
<commit_before>/*!
* \author ddubois
* \date 03-Sep-18.
*/
#include <future>
#include "nova_renderer.hpp"
#include "platform.hpp"
#include "util/logger.hpp"
#include "glslang/MachineIndependent/Initialize.h"
#include "loading/shaderpack/shaderpack_loading.hpp"
#if _WIN32
#include "render_engine/dx12/dx12_render_engine.hpp"
#endif
#include "render_engine/vulkan/vulkan_render_engine.hpp"
namespace nova {
nova_renderer *nova_renderer::instance;
nova_renderer::nova_renderer(const settings_options &settings) :
render_settings(settings), task_scheduler(16, ttl::empty_queue_behavior::YIELD) {
switch(settings.api) {
case graphics_api::dx12:
#if _WIN32
engine = std::make_unique<dx12_render_engine>(render_settings, &task_scheduler);
break;
#endif
case graphics_api::vulkan:
engine = std::make_unique<vulkan_render_engine>(render_settings, &task_scheduler);
}
NOVA_LOG(DEBUG) << "Opened window";
}
nova_settings &nova_renderer::get_settings() {
return render_settings;
}
void nova_renderer::execute_frame() {
frame_done_future.get();
frame_done_future = task_scheduler.add_task([](ttl::task_scheduler* task_scheduler, render_engine* engine) { engine->render_frame(); }, engine.get());
}
void nova_renderer::load_shaderpack(const std::string &shaderpack_name) {
glslang::InitializeProcess();
std::future<shaderpack_data> shaderpack_data = load_shaderpack_data(fs::path(shaderpack_name), task_scheduler);
shaderpack_data.wait();
engine->set_shaderpack(shaderpack_data.get());
NOVA_LOG(INFO) << "Shaderpack " << shaderpack_name << " loaded successfully";
}
render_engine *nova_renderer::get_engine() const {
return engine.get();
}
nova_renderer *nova_renderer::get_instance() {
return instance;
}
void nova_renderer::deinitialize() {
delete instance;
}
ttl::task_scheduler &nova_renderer::get_task_scheduler() {
return task_scheduler;
}
} // namespace nova
<commit_msg>Commit before removing threading<commit_after>/*!
* \author ddubois
* \date 03-Sep-18.
*/
#include <future>
#include "nova_renderer.hpp"
#include "platform.hpp"
#include "util/logger.hpp"
#include "glslang/MachineIndependent/Initialize.h"
#include "loading/shaderpack/shaderpack_loading.hpp"
#if _WIN32
#include "render_engine/dx12/dx12_render_engine.hpp"
#endif
#include "render_engine/vulkan/vulkan_render_engine.hpp"
namespace nova {
nova_renderer *nova_renderer::instance;
nova_renderer::nova_renderer(const settings_options &settings) :
render_settings(settings), task_scheduler(16, ttl::empty_queue_behavior::YIELD) {
switch(settings.api) {
case graphics_api::dx12:
#if _WIN32
engine = std::make_unique<dx12_render_engine>(render_settings, &task_scheduler);
break;
#endif
case graphics_api::vulkan:
engine = std::make_unique<vulkan_render_engine>(render_settings, &task_scheduler);
}
NOVA_LOG(DEBUG) << "Opened window";
}
nova_settings &nova_renderer::get_settings() {
return render_settings;
}
void nova_renderer::execute_frame() {
frame_done_future.wait();
frame_done_future.get();
try {
frame_done_future = task_scheduler.add_task([](ttl::task_scheduler* task_scheduler, render_engine* engine) { engine->render_frame(); }, engine.get());
} catch(const std::exception& e) {
NOVA_LOG(ERROR) << "Could not execute frame: " << e.what();
}
}
void nova_renderer::load_shaderpack(const std::string &shaderpack_name) {
glslang::InitializeProcess();
std::future<shaderpack_data> shaderpack_data = load_shaderpack_data(fs::path(shaderpack_name), task_scheduler);
shaderpack_data.wait();
engine->set_shaderpack(shaderpack_data.get());
NOVA_LOG(INFO) << "Shaderpack " << shaderpack_name << " loaded successfully";
}
render_engine *nova_renderer::get_engine() const {
return engine.get();
}
nova_renderer *nova_renderer::get_instance() {
return instance;
}
void nova_renderer::deinitialize() {
delete instance;
}
ttl::task_scheduler &nova_renderer::get_task_scheduler() {
return task_scheduler;
}
} // namespace nova
<|endoftext|> |
<commit_before>#include "gaf/gen_pugixml.h"
#include <array>
#include <cassert>
#include "fmt/format.h"
#include "gaf/generator.h"
#include "gaf/args.h"
#include "gaf/array.h"
namespace xml
{
void add_enum_function(const Enum& e, Out* sources)
{
// const auto enum_type = e.name;
// const auto value_prefix = get_value_prefix_opt(e);
// const auto arg = ", const std::string& gaf_path";
const auto signature =
fmt::format("std::string ParseEnumString({}* c, const char* value)", e.name);
sources->header.addf("{};", signature);
sources->source.add(signature);
sources->source.add("{");
for (const auto& v : e.values)
{
sources->source.addf(
"if(strcmp(value, \"{value}\") == 0) {{ *c = {type}::{value}; return \"\"; }}",
fmt::arg("type", e.name), fmt::arg("value", v));
}
// todo(Gustav): add list of valid values with a could_be_fun
sources->source.addf("return fmt::format(\"{{}} is not a valid name for enum {}\", value);",
e.name);
sources->source.add("}");
sources->source.add("");
}
void add_member_failure_to_read(Out* sources, const Member& m)
{
if (m.missing_is_fail || m.is_optional)
{
sources->source.add("else");
sources->source.add("{");
if (m.is_optional)
{
sources->source.addf("c->{}.reset();", m.name);
}
else
{
sources->source.addf("return \"{} is missing\";", m.name);
}
sources->source.add("}");
}
}
bool is_basic_type(const Type& t)
{
switch (t.standard_type)
{
case StandardType::Int8:
case StandardType::Int16:
case StandardType::Int32:
case StandardType::Int64:
case StandardType::Uint8:
case StandardType::Uint16:
case StandardType::Uint32:
case StandardType::Uint64:
case StandardType::Float:
case StandardType::Double:
case StandardType::Byte:
case StandardType::Bool:
case StandardType::String: return true;
default: return false;
}
}
void add_member_variable_array(Out* sources, const Member& m)
{
if (m.type_name.is_enum)
{
sources->source.addf("for(const auto el: value.children(\"{}\"))", m.name);
sources->source.add("{");
sources->addf("auto em = {}{{}};", m.type_name.get_cpp_type());
sources->source.add(
"if(const auto error = ParseEnumString(&em, el.child_value()); error.empty() == "
"false)");
sources->source.add("{");
sources->source.add("return error;");
sources->source.add("}");
sources->source.addf("c->{}.emplace_back(em)", m.name);
sources->source.add("}");
}
else if (is_basic_type(m.type_name))
{
sources->source.addf("for(const auto el: value.children(\"{}\"))", m.name);
sources->source.add("{");
switch (m.type_name.standard_type)
{
case StandardType::Bool:
sources->source.add("bool b = false;");
sources->source.add("if(gaf::parse_bool(&b, el.child_value()) == false)");
sources->source.add("{");
sources->source.addf(
"return fmt::format(\"Invalid bool for {}: {{}}\", el.child_value());", m.name);
sources->source.add("}");
sources->source.addf("c->{}.emplace_back(b);", m.name);
break;
case StandardType::String:
sources->source.addf("c->{}.emplace_back(el.child_value());", m.name);
break;
default:
sources->source.addf("{} v = 0;", m.type_name.get_cpp_type());
sources->source.add("std::istringstream ss(el.child_value());");
sources->source.add("ss >> v;");
sources->source.add("if(ss.good() == false)");
sources->source.add("{");
sources->source.addf(
"return fmt::format(\"Invalid format for {}: {{}}\", el.child_value());", m.name);
sources->source.add("}");
sources->source.addf("c->{}.emplace_back(v);", m.name);
break;
}
sources->source.add("}");
}
else
{
sources->source.addf("for(const auto child: value.children(\"{}\"))", m.name);
sources->source.add("{");
sources->source.addf("auto v = {}{{}};", m.type_name.get_cpp_type());
sources->source.addf(
"if(const auto error = ReadXmlElement(&v, value); error.empty() == false)", m.name);
sources->source.add("{");
sources->source.add("return error;");
sources->source.add("}");
sources->source.addf("c->{}.emplace_back(v);", m.name);
sources->source.add("}");
}
}
void add_member_variable_single(Out* sources, const Member& m)
{
if (m.type_name.is_enum)
{
sources->source.addf("if(const auto el = value.attribute(\"{}\"); el)", m.name);
sources->source.add("{");
sources->source.addf(
"if(const auto error = ParseEnumString(&c->{}, el.value()); error.empty() == false)",
m.name);
sources->source.add("{");
sources->source.add("return error;");
sources->source.add("}");
sources->source.add("}");
add_member_failure_to_read(sources, m);
}
else if (is_basic_type(m.type_name))
{
sources->source.addf("if(const auto el = value.attribute(\"{}\"); el)", m.name);
sources->source.add("{");
switch (m.type_name.standard_type)
{
case StandardType::Bool:
sources->source.addf("if(gaf::parse_bool(&c->{}, el.value()) == false)", m.name);
sources->source.add("{");
sources->source.addf("return fmt::format(\"Invalid bool for {}: {{}}\", el.value());",
m.name);
sources->source.add("}");
break;
case StandardType::String: sources->source.addf("c->{} = el.value();", m.name); break;
default:
sources->source.add("std::istringstream ss(el.value());");
sources->source.addf("ss >> c->{};", m.name);
sources->source.add("if(ss.good() == false)");
sources->source.add("{");
sources->source.addf("return fmt::format(\"Invalid format for {}: {{}}\", el.value());",
m.name);
sources->source.add("}");
break;
}
sources->source.add("}");
add_member_failure_to_read(sources, m);
}
else
{
sources->source.addf("if(const auto child = value.child(\"{}\"); child)", m.name);
sources->source.add("{");
sources->source.addf(
"if(const auto error = ReadXmlElement(&c->{}, value); error.empty() == false)", m.name);
sources->source.add("{");
sources->source.add("return error;");
sources->source.add("}");
sources->source.add("}");
add_member_failure_to_read(sources, m);
}
}
void add_member_variable(Out* sources, const Member& m)
{
if (m.is_dynamic_array)
{
add_member_variable_array(sources, m);
}
else
{
add_member_variable_single(sources, m);
}
}
void add_struct_function(Out* sources, const Struct& s)
{
const auto signature =
fmt::format("std::string ReadXmlElement({}* c, const pugi::xml_node& value)", s.name);
sources->header.addf("{};", signature);
sources->source.add(signature);
sources->source.add("{");
for (const auto& m : s.members) { add_member_variable(sources, m); }
sources->source.add("return \"\";");
sources->source.add("}");
sources->source.add("");
}
Out generate_xml(const File& f, const std::string& name)
{
auto sources = Out{};
sources.header.add("#pragma once");
sources.header.add("");
sources.header.add("#include <string>");
sources.header.add("#include \"pugixml.hpp\"");
sources.header.add("");
sources.header.addf("#include \"gaf_{}.h\"", name);
sources.source.add("#include <cstring>");
sources.source.add("#include <sstream>");
sources.source.add("#include \"fmt/format.h\"");
sources.source.add("#include \"gaf/lib_pugixml.h\"");
sources.add("");
if (f.package_name.empty() == false)
{
sources.addf("namespace {}", f.package_name);
sources.add("{");
}
for (const auto& e : f.enums) { add_enum_function(*e, &sources); }
for (const auto& s : f.structs) { add_struct_function(&sources, *s); }
if (f.package_name.empty() == false)
{
sources.add("}");
sources.add("");
}
return sources;
}
}
std::string PugiXmlPlugin::get_name() { return "pugixml"; }
int PugiXmlPlugin::run_plugin(const File& file, Writer* writer, std::string& output_folder, Args& args,
const std::string& name)
{
if (auto r = no_arguments(args); r != 0)
{
return r;
}
auto out = xml::generate_xml(file, name);
write_cpp(&out, writer, output_folder, name, "gaf_pugixml_");
return 0;
}
<commit_msg>fix: generated xml code compiles now<commit_after>#include "gaf/gen_pugixml.h"
#include <array>
#include <cassert>
#include "fmt/format.h"
#include "gaf/generator.h"
#include "gaf/args.h"
#include "gaf/array.h"
namespace xml
{
void add_enum_function(const Enum& e, Out* sources)
{
// const auto enum_type = e.name;
// const auto value_prefix = get_value_prefix_opt(e);
// const auto arg = ", const std::string& gaf_path";
const auto signature =
fmt::format("std::string ParseEnumString({}* c, const char* value)", e.name);
sources->header.addf("{};", signature);
sources->source.add(signature);
sources->source.add("{");
for (const auto& v : e.values)
{
sources->source.addf(
"if(strcmp(value, \"{value}\") == 0) {{ *c = {type}::{value}; return \"\"; }}",
fmt::arg("type", e.name), fmt::arg("value", v));
}
// todo(Gustav): add list of valid values with a could_be_fun
sources->source.addf("return fmt::format(\"{{}} is not a valid name for enum {}\", value);",
e.name);
sources->source.add("}");
sources->source.add("");
}
void add_member_failure_to_read(Out* sources, const Member& m)
{
if (m.missing_is_fail || m.is_optional)
{
sources->source.add("else");
sources->source.add("{");
if (m.is_optional)
{
sources->source.addf("c->{}.reset();", m.name);
}
else
{
sources->source.addf("return \"{} is missing\";", m.name);
}
sources->source.add("}");
}
}
bool is_basic_type(const Type& t)
{
switch (t.standard_type)
{
case StandardType::Int8:
case StandardType::Int16:
case StandardType::Int32:
case StandardType::Int64:
case StandardType::Uint8:
case StandardType::Uint16:
case StandardType::Uint32:
case StandardType::Uint64:
case StandardType::Float:
case StandardType::Double:
case StandardType::Byte:
case StandardType::Bool:
case StandardType::String: return true;
default: return false;
}
}
void add_member_variable_array(Out* sources, const Member& m)
{
if (m.type_name.is_enum)
{
sources->source.addf("for(const auto el: value.children(\"{}\"))", m.name);
sources->source.add("{");
sources->source.addf("auto em = {}{{}};", m.type_name.get_cpp_type());
sources->source.add(
"if(const auto error = ParseEnumString(&em, el.child_value()); error.empty() == "
"false)");
sources->source.add("{");
sources->source.add("return error;");
sources->source.add("}");
sources->source.addf("c->{}.emplace_back(em);", m.name);
sources->source.add("}");
}
else if (is_basic_type(m.type_name))
{
sources->source.addf("for(const auto el: value.children(\"{}\"))", m.name);
sources->source.add("{");
switch (m.type_name.standard_type)
{
case StandardType::Bool:
sources->source.add("bool b = false;");
sources->source.add("if(gaf::parse_bool(&b, el.child_value()) == false)");
sources->source.add("{");
sources->source.addf(
"return fmt::format(\"Invalid bool for {}: {{}}\", el.child_value());", m.name);
sources->source.add("}");
sources->source.addf("c->{}.emplace_back(b);", m.name);
break;
case StandardType::String:
sources->source.addf("c->{}.emplace_back(el.child_value());", m.name);
break;
default:
sources->source.addf("{} v = 0;", m.type_name.get_cpp_type());
sources->source.add("std::istringstream ss(el.child_value());");
sources->source.add("ss >> v;");
sources->source.add("if(ss.good() == false)");
sources->source.add("{");
sources->source.addf(
"return fmt::format(\"Invalid format for {}: {{}}\", el.child_value());", m.name);
sources->source.add("}");
sources->source.addf("c->{}.emplace_back(v);", m.name);
break;
}
sources->source.add("}");
}
else
{
sources->source.addf("for(const auto el: value.children(\"{}\"))", m.name);
sources->source.add("{");
sources->source.addf("auto v = {}{{}};", m.type_name.get_cpp_type());
sources->source.addf("if(const auto error = ReadXmlElement(&v, el); error.empty() == false)",
m.name);
sources->source.add("{");
sources->source.add("return error;");
sources->source.add("}");
sources->source.addf("c->{}.emplace_back(v);", m.name);
sources->source.add("}");
}
}
void add_member_variable_single(Out* sources, const Member& m)
{
auto ptr = m.is_optional ? fmt::format("c->{}.get()", m.name) : fmt::format("&c->{}", m.name);
auto val = m.is_optional ? fmt::format("*c->{}", m.name) : fmt::format("c->{}", m.name);
auto create_mem = [sources, m]() {
if (m.is_optional)
{
sources->source.addf("c->{} = std::make_shared<{}>();", m.name,
m.type_name.get_cpp_type());
}
};
auto clear_mem = [sources, m]() {
if (m.is_optional)
{
sources->source.addf("c->{}.reset();", m.name);
}
};
if (m.type_name.is_enum)
{
sources->source.addf("if(const auto el = value.attribute(\"{}\"); el)", m.name);
sources->source.add("{");
create_mem();
sources->source.addf(
"if(const auto error = ParseEnumString({}, el.value()); error.empty() == false)", ptr);
sources->source.add("{");
clear_mem();
sources->source.add("return error;");
sources->source.add("}");
sources->source.add("}");
add_member_failure_to_read(sources, m);
}
else if (is_basic_type(m.type_name))
{
sources->source.addf("if(const auto el = value.attribute(\"{}\"); el)", m.name);
sources->source.add("{");
create_mem();
switch (m.type_name.standard_type)
{
case StandardType::Bool:
sources->source.addf("if(gaf::parse_bool({}, el.value()) == false)", ptr);
sources->source.add("{");
clear_mem();
sources->source.addf("return fmt::format(\"Invalid bool for {}: {{}}\", el.value());",
m.name);
sources->source.add("}");
break;
case StandardType::String: sources->source.addf("{} = el.value();", val); break;
default:
sources->source.add("std::istringstream ss(el.value());");
sources->source.addf("ss >> {};", val);
sources->source.add("if(ss.good() == false)");
sources->source.add("{");
clear_mem();
sources->source.addf("return fmt::format(\"Invalid format for {}: {{}}\", el.value());",
m.name);
sources->source.add("}");
break;
}
sources->source.add("}");
add_member_failure_to_read(sources, m);
}
else
{
sources->source.addf("if(const auto child = value.child(\"{}\"); child)", m.name);
sources->source.add("{");
create_mem();
sources->source.addf(
"if(const auto error = ReadXmlElement({}, value); error.empty() == false)", ptr);
sources->source.add("{");
clear_mem();
sources->source.add("return error;");
sources->source.add("}");
sources->source.add("}");
add_member_failure_to_read(sources, m);
}
}
void add_member_variable(Out* sources, const Member& m)
{
if (m.is_dynamic_array)
{
add_member_variable_array(sources, m);
}
else
{
add_member_variable_single(sources, m);
}
}
void add_struct_function(Out* sources, const Struct& s)
{
const auto signature =
fmt::format("std::string ReadXmlElement({}* c, const pugi::xml_node& value)", s.name);
sources->header.addf("{};", signature);
sources->source.add(signature);
sources->source.add("{");
for (const auto& m : s.members) { add_member_variable(sources, m); }
sources->source.add("return \"\";");
sources->source.add("}");
sources->source.add("");
}
Out generate_xml(const File& f, const std::string& name)
{
auto sources = Out{};
sources.header.add("#pragma once");
sources.header.add("");
sources.header.add("#include <string>");
sources.header.add("#include \"pugixml.hpp\"");
sources.header.add("");
sources.header.addf("#include \"gaf_{}.h\"", name);
sources.source.add("#include <cstring>");
sources.source.add("#include <sstream>");
sources.source.add("#include \"fmt/format.h\"");
sources.source.add("#include \"gaf/lib_pugixml.h\"");
sources.add("");
if (f.package_name.empty() == false)
{
sources.addf("namespace {}", f.package_name);
sources.add("{");
}
for (const auto& e : f.enums) { add_enum_function(*e, &sources); }
for (const auto& s : f.structs) { add_struct_function(&sources, *s); }
if (f.package_name.empty() == false)
{
sources.add("}");
sources.add("");
}
return sources;
}
}
std::string PugiXmlPlugin::get_name() { return "pugixml"; }
int PugiXmlPlugin::run_plugin(const File& file, Writer* writer, std::string& output_folder, Args& args,
const std::string& name)
{
if (auto r = no_arguments(args); r != 0)
{
return r;
}
auto out = xml::generate_xml(file, name);
write_cpp(&out, writer, output_folder, name, "gaf_pugixml_");
return 0;
}
<|endoftext|> |
<commit_before>#ifndef CLUSTERING_IMMEDIATE_CONSISTENCY_QUERY_MASTER_HPP_
#define CLUSTERING_IMMEDIATE_CONSISTENCY_QUERY_MASTER_HPP_
#include <map>
#include "clustering/immediate_consistency/branch/broadcaster.hpp"
#include "clustering/immediate_consistency/query/metadata.hpp"
#include "containers/archive/order_token.hpp"
#include "containers/uuid.hpp"
template<class protocol_t>
class master_t {
public:
class ack_checker_t {
public:
virtual bool is_acceptable_ack_set(const std::set<peer_id_t> &acks) = 0;
ack_checker_t() { }
protected:
virtual ~ack_checker_t() { }
private:
DISABLE_COPYING(ack_checker_t);
};
master_t(
mailbox_manager_t *mm,
ack_checker_t *ac,
watchable_variable_t<std::map<master_id_t, master_business_card_t<protocol_t> > > *md,
mutex_assertion_t *mdl,
typename protocol_t::region_t region,
broadcaster_t<protocol_t> *b)
THROWS_ONLY(interrupted_exc_t) :
mailbox_manager(mm),
ack_checker(ac),
broadcaster(b),
read_mailbox(mailbox_manager, boost::bind(&master_t<protocol_t>::on_read,
this, _1, _2, _3, _4, _5, auto_drainer_t::lock_t(&drainer))),
write_mailbox(mailbox_manager, boost::bind(&master_t<protocol_t>::on_write,
this, _1, _2, _3, _4, _5, auto_drainer_t::lock_t(&drainer))),
registrar(mm, this),
master_directory(md), master_directory_lock(mdl),
uuid(generate_uuid()) {
rassert(ack_checker);
master_business_card_t<protocol_t> bcard(
region,
read_mailbox.get_address(), write_mailbox.get_address(),
registrar.get_business_card());
mutex_assertion_t::acq_t master_directory_lock_acq(master_directory_lock);
std::map<master_id_t, master_business_card_t<protocol_t> > master_map = master_directory->get_watchable()->get();
master_map.insert(std::make_pair(uuid, bcard));
master_directory->set_value(master_map);
}
~master_t() {
mutex_assertion_t::acq_t master_directory_lock_acq(master_directory_lock);
std::map<master_id_t, master_business_card_t<protocol_t> > master_map = master_directory->get_watchable()->get();
master_map.erase(uuid);
master_directory->set_value(master_map);
}
private:
struct parser_lifetime_t {
parser_lifetime_t(master_t *m, namespace_interface_business_card_t bc) : m_(m), namespace_interface_id_(bc.namespace_interface_id) {
m->sink_map.insert(std::pair<namespace_interface_id_t, parser_lifetime_t *>(bc.namespace_interface_id, this));
send(m->mailbox_manager, bc.ack_address);
}
~parser_lifetime_t() {
m_->sink_map.erase(namespace_interface_id_);
}
auto_drainer_t *drainer() { return &drainer_; }
fifo_enforcer_sink_t *sink() { return &sink_; }
private:
master_t *m_;
namespace_interface_id_t namespace_interface_id_;
fifo_enforcer_sink_t sink_;
auto_drainer_t drainer_;
DISABLE_COPYING(parser_lifetime_t);
};
void on_read(namespace_interface_id_t parser_id, typename protocol_t::read_t read, order_token_t otok, fifo_enforcer_read_token_t token,
mailbox_addr_t<void(boost::variant<typename protocol_t::read_response_t, std::string>)> response_address,
auto_drainer_t::lock_t keepalive)
THROWS_NOTHING
{
keepalive.assert_is_holding(&drainer);
boost::variant<typename protocol_t::read_response_t, std::string> reply;
try {
typename std::map<namespace_interface_id_t, parser_lifetime_t *>::iterator it = sink_map.find(parser_id);
// TODO: Remove this assertion. Out-of-order operations (which allegedly can happen) could cause it to be wrong?
rassert(it != sink_map.end());
auto_drainer_t::lock_t auto_drainer_lock(it->second->drainer());
fifo_enforcer_sink_t::exit_read_t exiter(it->second->sink(), token);
reply = broadcaster->read(read, &exiter, otok, auto_drainer_lock.get_drain_signal());
} catch (cannot_perform_query_exc_t e) {
reply = e.what();
}
send(mailbox_manager, response_address, reply);
}
void on_write(namespace_interface_id_t parser_id, typename protocol_t::write_t write, order_token_t otok, fifo_enforcer_write_token_t token,
mailbox_addr_t<void(boost::variant<typename protocol_t::write_response_t, std::string>)> response_address,
auto_drainer_t::lock_t keepalive)
THROWS_NOTHING
{
keepalive.assert_is_holding(&drainer);
boost::variant<typename protocol_t::write_response_t, std::string> reply;
try {
typename std::map<namespace_interface_id_t, parser_lifetime_t *>::iterator it = sink_map.find(parser_id);
// TODO: Remove this assertion. Out-of-order operations (which allegedly can hoppen) could cause it to be wrong?
rassert(it != sink_map.end());
class ac_t : public broadcaster_t<protocol_t>::ack_callback_t {
public:
explicit ac_t(master_t *p) : parent(p) { }
bool on_ack(peer_id_t peer) {
ack_set.insert(peer);
return parent->ack_checker->is_acceptable_ack_set(ack_set);
}
master_t *parent;
std::set<peer_id_t> ack_set;
} ack_checker(this);
auto_drainer_t::lock_t auto_drainer_lock(it->second->drainer());
fifo_enforcer_sink_t::exit_write_t exiter(it->second->sink(), token);
reply = broadcaster->write(write, &exiter, &ack_checker, otok, auto_drainer_lock.get_drain_signal());
} catch (cannot_perform_query_exc_t e) {
reply = e.what();
}
send(mailbox_manager, response_address, reply);
}
mailbox_manager_t *mailbox_manager;
ack_checker_t *ack_checker;
broadcaster_t<protocol_t> *broadcaster;
std::map<namespace_interface_id_t, parser_lifetime_t *> sink_map;
auto_drainer_t drainer;
typename master_business_card_t<protocol_t>::read_mailbox_t read_mailbox;
typename master_business_card_t<protocol_t>::write_mailbox_t write_mailbox;
registrar_t<namespace_interface_business_card_t, master_t *, parser_lifetime_t> registrar;
watchable_variable_t<std::map<master_id_t, master_business_card_t<protocol_t> > > *master_directory;
mutex_assertion_t *master_directory_lock;
master_id_t uuid;
};
#endif /* CLUSTERING_IMMEDIATE_CONSISTENCY_QUERY_MASTER_HPP_ */
<commit_msg>Added DISABLE_COPYING to master_t.<commit_after>#ifndef CLUSTERING_IMMEDIATE_CONSISTENCY_QUERY_MASTER_HPP_
#define CLUSTERING_IMMEDIATE_CONSISTENCY_QUERY_MASTER_HPP_
#include <map>
#include "clustering/immediate_consistency/branch/broadcaster.hpp"
#include "clustering/immediate_consistency/query/metadata.hpp"
#include "containers/archive/order_token.hpp"
#include "containers/uuid.hpp"
template<class protocol_t>
class master_t {
public:
class ack_checker_t {
public:
virtual bool is_acceptable_ack_set(const std::set<peer_id_t> &acks) = 0;
ack_checker_t() { }
protected:
virtual ~ack_checker_t() { }
private:
DISABLE_COPYING(ack_checker_t);
};
master_t(
mailbox_manager_t *mm,
ack_checker_t *ac,
watchable_variable_t<std::map<master_id_t, master_business_card_t<protocol_t> > > *md,
mutex_assertion_t *mdl,
typename protocol_t::region_t region,
broadcaster_t<protocol_t> *b)
THROWS_ONLY(interrupted_exc_t) :
mailbox_manager(mm),
ack_checker(ac),
broadcaster(b),
read_mailbox(mailbox_manager, boost::bind(&master_t<protocol_t>::on_read,
this, _1, _2, _3, _4, _5, auto_drainer_t::lock_t(&drainer))),
write_mailbox(mailbox_manager, boost::bind(&master_t<protocol_t>::on_write,
this, _1, _2, _3, _4, _5, auto_drainer_t::lock_t(&drainer))),
registrar(mm, this),
master_directory(md), master_directory_lock(mdl),
uuid(generate_uuid()) {
rassert(ack_checker);
master_business_card_t<protocol_t> bcard(
region,
read_mailbox.get_address(), write_mailbox.get_address(),
registrar.get_business_card());
mutex_assertion_t::acq_t master_directory_lock_acq(master_directory_lock);
std::map<master_id_t, master_business_card_t<protocol_t> > master_map = master_directory->get_watchable()->get();
master_map.insert(std::make_pair(uuid, bcard));
master_directory->set_value(master_map);
}
~master_t() {
mutex_assertion_t::acq_t master_directory_lock_acq(master_directory_lock);
std::map<master_id_t, master_business_card_t<protocol_t> > master_map = master_directory->get_watchable()->get();
master_map.erase(uuid);
master_directory->set_value(master_map);
}
private:
struct parser_lifetime_t {
parser_lifetime_t(master_t *m, namespace_interface_business_card_t bc) : m_(m), namespace_interface_id_(bc.namespace_interface_id) {
m->sink_map.insert(std::pair<namespace_interface_id_t, parser_lifetime_t *>(bc.namespace_interface_id, this));
send(m->mailbox_manager, bc.ack_address);
}
~parser_lifetime_t() {
m_->sink_map.erase(namespace_interface_id_);
}
auto_drainer_t *drainer() { return &drainer_; }
fifo_enforcer_sink_t *sink() { return &sink_; }
private:
master_t *m_;
namespace_interface_id_t namespace_interface_id_;
fifo_enforcer_sink_t sink_;
auto_drainer_t drainer_;
DISABLE_COPYING(parser_lifetime_t);
};
void on_read(namespace_interface_id_t parser_id, typename protocol_t::read_t read, order_token_t otok, fifo_enforcer_read_token_t token,
mailbox_addr_t<void(boost::variant<typename protocol_t::read_response_t, std::string>)> response_address,
auto_drainer_t::lock_t keepalive)
THROWS_NOTHING
{
keepalive.assert_is_holding(&drainer);
boost::variant<typename protocol_t::read_response_t, std::string> reply;
try {
typename std::map<namespace_interface_id_t, parser_lifetime_t *>::iterator it = sink_map.find(parser_id);
// TODO: Remove this assertion. Out-of-order operations (which allegedly can happen) could cause it to be wrong?
rassert(it != sink_map.end());
auto_drainer_t::lock_t auto_drainer_lock(it->second->drainer());
fifo_enforcer_sink_t::exit_read_t exiter(it->second->sink(), token);
reply = broadcaster->read(read, &exiter, otok, auto_drainer_lock.get_drain_signal());
} catch (cannot_perform_query_exc_t e) {
reply = e.what();
}
send(mailbox_manager, response_address, reply);
}
void on_write(namespace_interface_id_t parser_id, typename protocol_t::write_t write, order_token_t otok, fifo_enforcer_write_token_t token,
mailbox_addr_t<void(boost::variant<typename protocol_t::write_response_t, std::string>)> response_address,
auto_drainer_t::lock_t keepalive)
THROWS_NOTHING
{
keepalive.assert_is_holding(&drainer);
boost::variant<typename protocol_t::write_response_t, std::string> reply;
try {
typename std::map<namespace_interface_id_t, parser_lifetime_t *>::iterator it = sink_map.find(parser_id);
// TODO: Remove this assertion. Out-of-order operations (which allegedly can hoppen) could cause it to be wrong?
rassert(it != sink_map.end());
class ac_t : public broadcaster_t<protocol_t>::ack_callback_t {
public:
explicit ac_t(master_t *p) : parent(p) { }
bool on_ack(peer_id_t peer) {
ack_set.insert(peer);
return parent->ack_checker->is_acceptable_ack_set(ack_set);
}
master_t *parent;
std::set<peer_id_t> ack_set;
} ack_checker(this);
auto_drainer_t::lock_t auto_drainer_lock(it->second->drainer());
fifo_enforcer_sink_t::exit_write_t exiter(it->second->sink(), token);
reply = broadcaster->write(write, &exiter, &ack_checker, otok, auto_drainer_lock.get_drain_signal());
} catch (cannot_perform_query_exc_t e) {
reply = e.what();
}
send(mailbox_manager, response_address, reply);
}
mailbox_manager_t *mailbox_manager;
ack_checker_t *ack_checker;
broadcaster_t<protocol_t> *broadcaster;
std::map<namespace_interface_id_t, parser_lifetime_t *> sink_map;
auto_drainer_t drainer;
typename master_business_card_t<protocol_t>::read_mailbox_t read_mailbox;
typename master_business_card_t<protocol_t>::write_mailbox_t write_mailbox;
registrar_t<namespace_interface_business_card_t, master_t *, parser_lifetime_t> registrar;
watchable_variable_t<std::map<master_id_t, master_business_card_t<protocol_t> > > *master_directory;
mutex_assertion_t *master_directory_lock;
master_id_t uuid;
DISABLE_COPYING(master_t);
};
#endif /* CLUSTERING_IMMEDIATE_CONSISTENCY_QUERY_MASTER_HPP_ */
<|endoftext|> |
<commit_before>#include <ghost.h>
#include <ghost_util.h>
#include <ghost_vec.h>
#include <cmath>
#include <cstdio>
#include "ghost_complex.h"
#include <omp.h>
double conjugate(double& c) {
return c;
}
float conjugate(float& c) {
return c;
}
template <typename T>
ghost_complex<T> conjugate(ghost_complex<T>& c) {
return ghost_complex<T>(std::real(c),-std::imag(c));
}
template <typename v_t> void ghost_normalizeVector_tmpl(ghost_vec_t *vec)
{
v_t s;
ghost_vec_dotprod_tmpl<v_t>(vec,vec,&s);
s = (v_t)sqrt(s);
s = (v_t)(((v_t)1.)/s);
vec->scale(vec,&s);
#ifdef GHOST_HAVE_OPENCL
vec->CLupload(vec);
#endif
#ifdef GHOST_HAVE_CUDA
vec->CUupload(vec);
#endif
}
template <typename v_t> void ghost_vec_dotprod_tmpl(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ // the parallelization is done manually because reduction does not work with ghost_complex numbers
if (vec->traits->nrows != vec2->traits->nrows) {
WARNING_LOG("The input vectors of the dot product have different numbers of rows");
}
if (vec->traits->nvecs != vec2->traits->nvecs) {
WARNING_LOG("The input vectors of the dot product have different numbers of columns");
}
ghost_vidx_t i,v;
ghost_vidx_t nr = MIN(vec->traits->nrows,vec2->traits->nrows);
int nthreads;
#pragma omp parallel
nthreads = ghost_ompGetNumThreads();
for (v=0; v<MIN(vec->traits->nvecs,vec2->traits->nvecs); v++) {
v_t sum = 0;
v_t partsums[nthreads];
for (i=0; i<nthreads; i++) partsums[i] = (v_t)0.;
#pragma omp parallel for
for (i=0; i<nr; i++) {
partsums[ghost_ompGetThreadNum()] +=
((v_t *)(vec->val))[i+vec->traits->nrowspadded*v]*
conjugate(((v_t *)(vec2->val))[i+vec->traits->nrowspadded*v]);
}
for (i=0; i<nthreads; i++) sum += partsums[i];
((v_t *)res)[v] = sum;
}
}
template <typename v_t> void ghost_vec_vaxpy_tmpl(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{
ghost_vidx_t i,v;
v_t *s = (v_t *)scale;
ghost_vidx_t nr = MIN(vec->traits->nrows,vec2->traits->nrows);
for (v=0; v<MIN(vec->traits->nvecs,vec2->traits->nvecs); v++) {
#pragma omp parallel for
for (i=0; i<nr; i++) {
((v_t *)(vec->val))[i+vec->traits->nrowspadded*v] += ((v_t *)(vec2->val))[i+vec->traits->nrowspadded*v] * s[v];
}
}
}
template <typename v_t> void ghost_vec_vaxpby_tmpl(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b_)
{
ghost_vidx_t i,v;
v_t *s = (v_t *)scale;
v_t *b = (v_t *)b_;
ghost_vidx_t nr = MIN(vec->traits->nrows,vec2->traits->nrows);
for (v=0; v<MIN(vec->traits->nvecs,vec2->traits->nvecs); v++) {
#pragma omp parallel for
for (i=0; i<nr; i++) {
((v_t *)(vec->val))[i+vec->traits->nrowspadded*v] = ((v_t *)(vec2->val))[i+vec->traits->nrowspadded*v] * s[v] +
((v_t *)(vec->val))[i+vec->traits->nrowspadded*v] * b[v];
}
}
}
template<typename v_t> void ghost_vec_vscale_tmpl(ghost_vec_t *vec, void *scale)
{
ghost_vidx_t i,v;
v_t *s = (v_t *)scale;
for (v=0; v<vec->traits->nvecs; v++) {
#pragma omp parallel for
for (i=0; i<vec->traits->nrows; i++) {
((v_t *)(vec->val))[i+vec->traits->nrowspadded*v] *= s[v];
}
}
}
template <typename v_t> void ghost_vec_fromRand_tmpl(ghost_vec_t *vec)
{
vec_malloc(vec);
DEBUG_LOG(1,"Filling vector with random values");
size_t sizeofdt = ghost_sizeofDataType(vec->traits->datatype);
vec->val = ghost_malloc(vec->traits->nvecs*vec->traits->nrowspadded*sizeofdt);
int i,v;
// TODO fuse loops but preserve randomness
if (vec->traits->nvecs > 1) {
#pragma omp parallel for schedule(runtime) private(i)
for (v=0; v<vec->traits->nvecs; v++) {
for (i=0; i<vec->traits->nrows; i++) {
((v_t *)(vec->val))[v*vec->traits->nrowspadded+i] = (v_t)0;
}
}
} else {
#pragma omp parallel for schedule(runtime)
for (i=0; i<vec->traits->nrows; i++) {
((v_t *)(vec->val))[i] = (v_t)0;
}
}
for (v=0; v<vec->traits->nvecs; v++) {
for (i=0; i<vec->traits->nrows; i++) {
((v_t *)(vec->val))[v*vec->traits->nrowspadded+i] = (v_t)(rand()*1./RAND_MAX); // TODO imag
}
}
vec->upload(vec);
}
extern "C" void d_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< double >(vec); }
extern "C" void s_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< float >(vec); }
extern "C" void z_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< ghost_complex<double> >(vec); }
extern "C" void c_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< ghost_complex<float> >(vec); }
extern "C" void d_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< double >(vec,vec2,res); }
extern "C" void s_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< float >(vec,vec2,res); }
extern "C" void z_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< ghost_complex<double> >(vec,vec2,res); }
extern "C" void c_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< ghost_complex<float> >(vec,vec2,res); }
extern "C" void d_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< double >(vec, scale); }
extern "C" void s_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< float >(vec, scale); }
extern "C" void z_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< ghost_complex<double> >(vec, scale); }
extern "C" void c_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< ghost_complex<float> >(vec, scale); }
extern "C" void d_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< double >(vec, vec2, scale); }
extern "C" void s_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< float >(vec, vec2, scale); }
extern "C" void z_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< ghost_complex<double> >(vec, vec2, scale); }
extern "C" void c_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< ghost_complex<float> >(vec, vec2, scale); }
extern "C" void d_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< double >(vec, vec2, scale, b); }
extern "C" void s_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< float >(vec, vec2, scale, b); }
extern "C" void z_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< ghost_complex<double> >(vec, vec2, scale, b); }
extern "C" void c_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< ghost_complex<float> >(vec, vec2, scale, b); }
extern "C" void d_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< double >(vec); }
extern "C" void s_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< float >(vec); }
extern "C" void z_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< ghost_complex<double> >(vec); }
extern "C" void c_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< ghost_complex<float> >(vec); }
<commit_msg>bugfix: vec->fromRand() was always re-allocating vector data, fixes #5<commit_after>#include <ghost.h>
#include <ghost_util.h>
#include <ghost_vec.h>
#include <cmath>
#include <cstdio>
#include "ghost_complex.h"
#include <omp.h>
double conjugate(double& c) {
return c;
}
float conjugate(float& c) {
return c;
}
template <typename T>
ghost_complex<T> conjugate(ghost_complex<T>& c) {
return ghost_complex<T>(std::real(c),-std::imag(c));
}
template <typename v_t> void ghost_normalizeVector_tmpl(ghost_vec_t *vec)
{
v_t s;
ghost_vec_dotprod_tmpl<v_t>(vec,vec,&s);
s = (v_t)sqrt(s);
s = (v_t)(((v_t)1.)/s);
vec->scale(vec,&s);
#ifdef GHOST_HAVE_OPENCL
vec->CLupload(vec);
#endif
#ifdef GHOST_HAVE_CUDA
vec->CUupload(vec);
#endif
}
template <typename v_t> void ghost_vec_dotprod_tmpl(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ // the parallelization is done manually because reduction does not work with ghost_complex numbers
if (vec->traits->nrows != vec2->traits->nrows) {
WARNING_LOG("The input vectors of the dot product have different numbers of rows");
}
if (vec->traits->nvecs != vec2->traits->nvecs) {
WARNING_LOG("The input vectors of the dot product have different numbers of columns");
}
ghost_vidx_t i,v;
ghost_vidx_t nr = MIN(vec->traits->nrows,vec2->traits->nrows);
int nthreads;
#pragma omp parallel
nthreads = ghost_ompGetNumThreads();
for (v=0; v<MIN(vec->traits->nvecs,vec2->traits->nvecs); v++) {
v_t sum = 0;
v_t partsums[nthreads];
for (i=0; i<nthreads; i++) partsums[i] = (v_t)0.;
#pragma omp parallel for
for (i=0; i<nr; i++) {
partsums[ghost_ompGetThreadNum()] +=
((v_t *)(vec->val))[i+vec->traits->nrowspadded*v]*
conjugate(((v_t *)(vec2->val))[i+vec->traits->nrowspadded*v]);
}
for (i=0; i<nthreads; i++) sum += partsums[i];
((v_t *)res)[v] = sum;
}
}
template <typename v_t> void ghost_vec_vaxpy_tmpl(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{
ghost_vidx_t i,v;
v_t *s = (v_t *)scale;
ghost_vidx_t nr = MIN(vec->traits->nrows,vec2->traits->nrows);
for (v=0; v<MIN(vec->traits->nvecs,vec2->traits->nvecs); v++) {
#pragma omp parallel for
for (i=0; i<nr; i++) {
((v_t *)(vec->val))[i+vec->traits->nrowspadded*v] += ((v_t *)(vec2->val))[i+vec->traits->nrowspadded*v] * s[v];
}
}
}
template <typename v_t> void ghost_vec_vaxpby_tmpl(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b_)
{
ghost_vidx_t i,v;
v_t *s = (v_t *)scale;
v_t *b = (v_t *)b_;
ghost_vidx_t nr = MIN(vec->traits->nrows,vec2->traits->nrows);
for (v=0; v<MIN(vec->traits->nvecs,vec2->traits->nvecs); v++) {
#pragma omp parallel for
for (i=0; i<nr; i++) {
((v_t *)(vec->val))[i+vec->traits->nrowspadded*v] = ((v_t *)(vec2->val))[i+vec->traits->nrowspadded*v] * s[v] +
((v_t *)(vec->val))[i+vec->traits->nrowspadded*v] * b[v];
}
}
}
template<typename v_t> void ghost_vec_vscale_tmpl(ghost_vec_t *vec, void *scale)
{
ghost_vidx_t i,v;
v_t *s = (v_t *)scale;
for (v=0; v<vec->traits->nvecs; v++) {
#pragma omp parallel for
for (i=0; i<vec->traits->nrows; i++) {
((v_t *)(vec->val))[i+vec->traits->nrowspadded*v] *= s[v];
}
}
}
template <typename v_t> void ghost_vec_fromRand_tmpl(ghost_vec_t *vec)
{
vec_malloc(vec);
DEBUG_LOG(1,"Filling vector with random values");
size_t sizeofdt = ghost_sizeofDataType(vec->traits->datatype);
int i,v;
// TODO fuse loops but preserve randomness
if (vec->traits->nvecs > 1) {
#pragma omp parallel for schedule(runtime) private(i)
for (v=0; v<vec->traits->nvecs; v++) {
for (i=0; i<vec->traits->nrows; i++) {
((v_t *)(vec->val))[v*vec->traits->nrowspadded+i] = (v_t)0;
}
}
} else {
#pragma omp parallel for schedule(runtime)
for (i=0; i<vec->traits->nrows; i++) {
((v_t *)(vec->val))[i] = (v_t)0;
}
}
for (v=0; v<vec->traits->nvecs; v++) {
for (i=0; i<vec->traits->nrows; i++) {
((v_t *)(vec->val))[v*vec->traits->nrowspadded+i] = (v_t)(rand()*1./RAND_MAX); // TODO imag
}
}
vec->upload(vec);
}
extern "C" void d_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< double >(vec); }
extern "C" void s_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< float >(vec); }
extern "C" void z_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< ghost_complex<double> >(vec); }
extern "C" void c_ghost_normalizeVector(ghost_vec_t *vec)
{ return ghost_normalizeVector_tmpl< ghost_complex<float> >(vec); }
extern "C" void d_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< double >(vec,vec2,res); }
extern "C" void s_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< float >(vec,vec2,res); }
extern "C" void z_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< ghost_complex<double> >(vec,vec2,res); }
extern "C" void c_ghost_vec_dotprod(ghost_vec_t *vec, ghost_vec_t *vec2, void *res)
{ return ghost_vec_dotprod_tmpl< ghost_complex<float> >(vec,vec2,res); }
extern "C" void d_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< double >(vec, scale); }
extern "C" void s_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< float >(vec, scale); }
extern "C" void z_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< ghost_complex<double> >(vec, scale); }
extern "C" void c_ghost_vec_vscale(ghost_vec_t *vec, void *scale)
{ return ghost_vec_vscale_tmpl< ghost_complex<float> >(vec, scale); }
extern "C" void d_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< double >(vec, vec2, scale); }
extern "C" void s_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< float >(vec, vec2, scale); }
extern "C" void z_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< ghost_complex<double> >(vec, vec2, scale); }
extern "C" void c_ghost_vec_vaxpy(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale)
{ return ghost_vec_vaxpy_tmpl< ghost_complex<float> >(vec, vec2, scale); }
extern "C" void d_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< double >(vec, vec2, scale, b); }
extern "C" void s_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< float >(vec, vec2, scale, b); }
extern "C" void z_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< ghost_complex<double> >(vec, vec2, scale, b); }
extern "C" void c_ghost_vec_vaxpby(ghost_vec_t *vec, ghost_vec_t *vec2, void *scale, void *b)
{ return ghost_vec_vaxpby_tmpl< ghost_complex<float> >(vec, vec2, scale, b); }
extern "C" void d_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< double >(vec); }
extern "C" void s_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< float >(vec); }
extern "C" void z_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< ghost_complex<double> >(vec); }
extern "C" void c_ghost_vec_fromRand(ghost_vec_t *vec)
{ return ghost_vec_fromRand_tmpl< ghost_complex<float> >(vec); }
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2015 Rony Shapiro <[email protected]>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/**
* \file Linux-specific implementation of rand.h
*/
#include "../rand.h"
#include <fstream>
#include <cassert>
#include <cstring>
#include <sys/time.h>
using namespace std;
bool pws_os::InitRandomDataFunction()
{
// For starters, we won't rely on /dev/urandom, only on /dev/random for
// the seed. Returning false indicates this decision.
// Perhaps we can check for a hardware rng in future versions, and change
// the returned value accordingly?
return false;
}
bool pws_os::GetRandomData(void *p, unsigned long len)
{
// Return data from /dev/urandom
// Will not be used by PasswordSafe when InitRandomDataFunction()
// returns false!
ifstream is("/dev/urandom");
if (!is)
return false;
return is.read(static_cast<char *>(p), len);
}
static void get_failsafe_rnd(char * &p, unsigned &slen)
{
// This function will be called
// iff we couldn't get a minimal amount of entropy
// from the kernel's entropy pool.
slen = sizeof(suseconds_t);
p = new char[slen];
struct timeval tv;
gettimeofday(&tv, NULL);
memcpy(p, &tv.tv_usec, slen);
}
void pws_os::GetRandomSeed(void *p, unsigned &slen)
{
/**
* Return a cryptographically strong seed
* from /dev/random, if possible.
*
* When called with p == NULL, return nuber of bytes currently
* in entropy pool.
* To minimize TOCTTOU, we also read the data at this time,
* and deliver it when called with non-NULL p.
*
* This implies a strict calling pattern, but hey, it's
* our application...
*/
const unsigned MAX_ENT_BITS = 256;
static char *data = NULL;
if (p == NULL) {
delete[] data;
data = NULL;
ifstream ent_avail("/proc/sys/kernel/random/entropy_avail");
if (ent_avail) {
unsigned ent_bits;
if (ent_avail >> ent_bits && ent_bits >= 32) {
slen = ent_bits >= MAX_ENT_BITS ? MAX_ENT_BITS/8 : ent_bits/8;
data = new char[slen];
ifstream rnd;
rnd.rdbuf()->pubsetbuf(0, 0);
rnd.open("/dev/random");
if (rnd.read(data, slen))
return;
else { // trouble reading
delete[] data;
data = NULL;
// will get randomness from failsafe.
}
}
}
// here if we had any trouble getting data from /dev/random
get_failsafe_rnd(data, slen);
} else { // called with non-NULL p, just return our hard-earned entropy
assert(data != NULL); // MUST call with p == NULL first!
memcpy(p, data, slen);
delete[] data;
data = NULL;
}
}
<commit_msg>Fix for Fedora 22, applicable to all Linux builds<commit_after>/*
* Copyright (c) 2003-2015 Rony Shapiro <[email protected]>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/**
* \file Linux-specific implementation of rand.h
*/
#include "../rand.h"
#include <fstream>
#include <cassert>
#include <cstring>
#include <sys/time.h>
using namespace std;
bool pws_os::InitRandomDataFunction()
{
// For starters, we won't rely on /dev/urandom, only on /dev/random for
// the seed. Returning false indicates this decision.
// Perhaps we can check for a hardware rng in future versions, and change
// the returned value accordingly?
return false;
}
bool pws_os::GetRandomData(void *p, unsigned long len)
{
// Return data from /dev/urandom
// Will not be used by PasswordSafe when InitRandomDataFunction()
// returns false!
ifstream is("/dev/urandom");
if (!is)
return false;
return is.read(static_cast<char *>(p), len).good();
}
static void get_failsafe_rnd(char * &p, unsigned &slen)
{
// This function will be called
// iff we couldn't get a minimal amount of entropy
// from the kernel's entropy pool.
slen = sizeof(suseconds_t);
p = new char[slen];
struct timeval tv;
gettimeofday(&tv, NULL);
memcpy(p, &tv.tv_usec, slen);
}
void pws_os::GetRandomSeed(void *p, unsigned &slen)
{
/**
* Return a cryptographically strong seed
* from /dev/random, if possible.
*
* When called with p == NULL, return nuber of bytes currently
* in entropy pool.
* To minimize TOCTTOU, we also read the data at this time,
* and deliver it when called with non-NULL p.
*
* This implies a strict calling pattern, but hey, it's
* our application...
*/
const unsigned MAX_ENT_BITS = 256;
static char *data = NULL;
if (p == NULL) {
delete[] data;
data = NULL;
ifstream ent_avail("/proc/sys/kernel/random/entropy_avail");
if (ent_avail) {
unsigned ent_bits;
if (ent_avail >> ent_bits && ent_bits >= 32) {
slen = ent_bits >= MAX_ENT_BITS ? MAX_ENT_BITS/8 : ent_bits/8;
data = new char[slen];
ifstream rnd;
rnd.rdbuf()->pubsetbuf(0, 0);
rnd.open("/dev/random");
if (rnd.read(data, slen))
return;
else { // trouble reading
delete[] data;
data = NULL;
// will get randomness from failsafe.
}
}
}
// here if we had any trouble getting data from /dev/random
get_failsafe_rnd(data, slen);
} else { // called with non-NULL p, just return our hard-earned entropy
assert(data != NULL); // MUST call with p == NULL first!
memcpy(p, data, slen);
delete[] data;
data = NULL;
}
}
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// 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 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
//
// Current versions can be found at www.libavg.de
//
#include "Camera.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../graphics/Filterfliprgb.h"
#if defined(AVG_ENABLE_1394_2)
#include "../imaging/FWCamera.h"
#endif
#ifdef AVG_ENABLE_V4L2
#include "../imaging/V4LCamera.h"
#endif
#ifdef AVG_ENABLE_CMU1394
#include "../imaging/CMUCamera.h"
#endif
#ifdef AVG_ENABLE_DSHOW
#include "../imaging/DSCamera.h"
#endif
#include "../imaging/FakeCamera.h"
#include <cstdlib>
#include <string.h>
#ifdef WIN32
#define strtoll(p, e, b) _strtoi64(p, e, b)
#endif
namespace avg {
using namespace std;
Camera::Camera(PixelFormat camPF, PixelFormat destPF, IntPoint size, float frameRate)
: m_CamPF(camPF),
m_DestPF(destPF),
m_Size(size),
m_FrameRate(frameRate)
{
// cerr << "Camera: " << getPixelFormatString(camPF) << "-->"
// << getPixelFormatString(destPF) << endl;
}
PixelFormat Camera::getCamPF() const
{
return m_CamPF;
}
void Camera::setCamPF(PixelFormat pf)
{
m_CamPF = pf;
}
PixelFormat Camera::getDestPF() const
{
return m_DestPF;
}
static ProfilingZoneID CameraConvertProfilingZone("Camera format conversion", true);
BitmapPtr Camera::convertCamFrameToDestPF(BitmapPtr pCamBmp)
{
ScopeTimer Timer(CameraConvertProfilingZone);
BitmapPtr pDestBmp = BitmapPtr(new Bitmap(pCamBmp->getSize(), m_DestPF));
pDestBmp->copyPixels(*pCamBmp);
if (m_CamPF == R8G8B8 && m_DestPF == B8G8R8X8) {
pDestBmp->setPixelFormat(R8G8B8X8);
FilterFlipRGB().applyInPlace(pDestBmp);
}
return pDestBmp;
}
IntPoint Camera::getImgSize()
{
return m_Size;
}
float Camera::getFrameRate() const
{
return m_FrameRate;
}
PixelFormat Camera::fwBayerStringToPF(unsigned long reg)
{
string sBayerFormat((char*)®, 4);
if (sBayerFormat == "RGGB") {
return BAYER8_RGGB;
} else if (sBayerFormat == "GBRG") {
return BAYER8_GBRG;
} else if (sBayerFormat == "GRBG") {
return BAYER8_GRBG;
} else if (sBayerFormat == "BGGR") {
return BAYER8_BGGR;
} else if (sBayerFormat == "YYYY") {
return I8;
} else {
AVG_ASSERT(false);
return I8;
}
}
void Camera::setImgSize(const IntPoint& size)
{
m_Size = size;
}
string cameraFeatureToString(CameraFeature feature)
{
switch (feature) {
case CAM_FEATURE_BRIGHTNESS:
return "brightness";
case CAM_FEATURE_EXPOSURE:
return "exposure";
case CAM_FEATURE_SHARPNESS:
return "sharpness";
case CAM_FEATURE_WHITE_BALANCE:
return "white balance";
case CAM_FEATURE_HUE:
return "hue";
case CAM_FEATURE_SATURATION:
return "saturation";
case CAM_FEATURE_GAMMA:
return "gamma";
case CAM_FEATURE_SHUTTER:
return "shutter";
case CAM_FEATURE_GAIN:
return "gain";
case CAM_FEATURE_IRIS:
return "iris";
case CAM_FEATURE_FOCUS:
return "focus";
case CAM_FEATURE_TEMPERATURE:
return "temperature";
case CAM_FEATURE_TRIGGER:
return "trigger";
case CAM_FEATURE_TRIGGER_DELAY:
return "trigger delay";
case CAM_FEATURE_WHITE_SHADING:
return "white shading";
case CAM_FEATURE_ZOOM:
return "zoom";
case CAM_FEATURE_PAN:
return "pan";
case CAM_FEATURE_TILT:
return "tilt";
case CAM_FEATURE_OPTICAL_FILTER:
return "optical filter";
case CAM_FEATURE_CAPTURE_SIZE:
return "capture size";
case CAM_FEATURE_CAPTURE_QUALITY:
return "capture quality";
case CAM_FEATURE_CONTRAST:
return "contrast";
case CAM_FEATURE_STROBE_DURATION:
return "strobe duration";
default:
return "unknown";
}
}
CameraPtr createCamera(const string& sDriver, const string& sDevice, int unit,
bool bFW800, const IntPoint& captureSize, PixelFormat camPF, PixelFormat destPF,
float frameRate)
{
CameraPtr pCamera;
try {
if (sDriver == "firewire") {
char * pszErr;
long long guid = strtoll(sDevice.c_str(), &pszErr, 16);
if (strlen(pszErr)) {
throw Exception(AVG_ERR_INVALID_ARGS, "'"+sDevice
+"' is not a valid GUID.");
}
#if defined(AVG_ENABLE_1394_2)
pCamera = CameraPtr(new FWCamera(guid, unit, bFW800, captureSize, camPF,
destPF, frameRate));
#elif defined(AVG_ENABLE_CMU1394)
if (unit != -1) {
throw Exception(AVG_ERR_INVALID_ARGS,
"camera 'unit' attribute is not supported when using the cmu firewire driver.");
}
pCamera = CameraPtr(new CMUCamera(guid, bFW800, captureSize, camPF, destPF,
frameRate));
#else
guid = 0; // Silence compiler warning
AVG_TRACE(Logger::WARNING, "Firewire camera specified, but firewire "
"support not compiled in.");
#endif
} else if (sDriver == "video4linux") {
#if defined(AVG_ENABLE_V4L2)
pCamera = CameraPtr(new V4LCamera(sDevice, unit, captureSize, camPF,
destPF, frameRate));
#else
AVG_TRACE(Logger::WARNING, "Video4Linux camera specified, but "
"Video4Linux support not compiled in.");
#endif
} else if (sDriver == "directshow") {
#if defined(AVG_ENABLE_DSHOW)
if (unit != -1) {
throw Exception(AVG_ERR_INVALID_ARGS,
"camera 'unit' attribute is not supported when using the directshow driver.");
}
pCamera = CameraPtr(new DSCamera(sDevice, captureSize, camPF, destPF,
frameRate));
#else
AVG_TRACE(Logger::WARNING, "DirectShow camera specified, but "
"DirectShow is only available under windows.");
#endif
} else {
throw Exception(AVG_ERR_INVALID_ARGS,
"Unable to set up camera. Camera source '"+sDriver+"' unknown.");
}
} catch (const Exception& e) {
if (e.getCode() == AVG_ERR_CAMERA_NONFATAL) {
AVG_TRACE(Logger::WARNING, e.getStr());
} else {
throw;
}
}
if (!pCamera) {
pCamera = CameraPtr(new FakeCamera(camPF, destPF));
}
return pCamera;
}
std::vector<CameraInfo> getCamerasInfos()
{
std::vector<CameraInfo> camerasInfo;
#ifdef AVG_ENABLE_1394_2
int amountFWCameras = FWCamera::countCameras();
for (int i = 0; i < amountFWCameras; i++) {
CameraInfo* camInfo = FWCamera::getCameraInfos(i);
if (camInfo != NULL) {
camInfo->checkAddBayer8();
camerasInfo.push_back(*camInfo);
}
}
#endif
#ifdef AVG_ENABLE_CMU1394
int amountCMUCameras = CMUCamera::countCameras();
for (int i = 0; i < amountCMUCameras; i++) {
CameraInfo* camInfo = CMUCamera::getCameraInfos(i);
if (camInfo != NULL) {
camInfo->checkAddBayer8();
camerasInfo.push_back(*camInfo);
}
}
#endif
#ifdef AVG_ENABLE_DSHOW
int amountDSCameras = DSCamera::countCameras();
for (int i = 0; i < amountDSCameras; i++) {
CameraInfo* camInfo = DSCamera::getCameraInfos(i);
if (camInfo != NULL) {
camInfo->checkAddBayer8();
camerasInfo.push_back(*camInfo);
}
}
#endif
#ifdef AVG_ENABLE_V4L2
int amountV4LCameras = V4LCamera::countCameras();
for (int i = 0; i < amountV4LCameras; i++) {
CameraInfo* camInfo = V4LCamera::getCameraInfos(i);
if (camInfo != NULL) {
camInfo->checkAddBayer8();
camerasInfo.push_back(*camInfo);
}
}
#endif
return camerasInfo;
}
}
<commit_msg>egl2 branch: Fix compiler warning.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// 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 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
//
// Current versions can be found at www.libavg.de
//
#include "Camera.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../graphics/Filterfliprgb.h"
#if defined(AVG_ENABLE_1394_2)
#include "../imaging/FWCamera.h"
#endif
#ifdef AVG_ENABLE_V4L2
#include "../imaging/V4LCamera.h"
#endif
#ifdef AVG_ENABLE_CMU1394
#include "../imaging/CMUCamera.h"
#endif
#ifdef AVG_ENABLE_DSHOW
#include "../imaging/DSCamera.h"
#endif
#include "../imaging/FakeCamera.h"
#include <cstdlib>
#include <string.h>
#ifdef WIN32
#define strtoll(p, e, b) _strtoi64(p, e, b)
#endif
namespace avg {
using namespace std;
Camera::Camera(PixelFormat camPF, PixelFormat destPF, IntPoint size, float frameRate)
: m_CamPF(camPF),
m_DestPF(destPF),
m_Size(size),
m_FrameRate(frameRate)
{
// cerr << "Camera: " << getPixelFormatString(camPF) << "-->"
// << getPixelFormatString(destPF) << endl;
}
PixelFormat Camera::getCamPF() const
{
return m_CamPF;
}
void Camera::setCamPF(PixelFormat pf)
{
m_CamPF = pf;
}
PixelFormat Camera::getDestPF() const
{
return m_DestPF;
}
static ProfilingZoneID CameraConvertProfilingZone("Camera format conversion", true);
BitmapPtr Camera::convertCamFrameToDestPF(BitmapPtr pCamBmp)
{
ScopeTimer Timer(CameraConvertProfilingZone);
BitmapPtr pDestBmp = BitmapPtr(new Bitmap(pCamBmp->getSize(), m_DestPF));
pDestBmp->copyPixels(*pCamBmp);
if (m_CamPF == R8G8B8 && m_DestPF == B8G8R8X8) {
pDestBmp->setPixelFormat(R8G8B8X8);
FilterFlipRGB().applyInPlace(pDestBmp);
}
return pDestBmp;
}
IntPoint Camera::getImgSize()
{
return m_Size;
}
float Camera::getFrameRate() const
{
return m_FrameRate;
}
PixelFormat Camera::fwBayerStringToPF(unsigned long reg)
{
string sBayerFormat((char*)®, 4);
if (sBayerFormat == "RGGB") {
return BAYER8_RGGB;
} else if (sBayerFormat == "GBRG") {
return BAYER8_GBRG;
} else if (sBayerFormat == "GRBG") {
return BAYER8_GRBG;
} else if (sBayerFormat == "BGGR") {
return BAYER8_BGGR;
} else if (sBayerFormat == "YYYY") {
return I8;
} else {
AVG_ASSERT(false);
return I8;
}
}
void Camera::setImgSize(const IntPoint& size)
{
m_Size = size;
}
string cameraFeatureToString(CameraFeature feature)
{
switch (feature) {
case CAM_FEATURE_BRIGHTNESS:
return "brightness";
case CAM_FEATURE_EXPOSURE:
return "exposure";
case CAM_FEATURE_SHARPNESS:
return "sharpness";
case CAM_FEATURE_WHITE_BALANCE:
return "white balance";
case CAM_FEATURE_HUE:
return "hue";
case CAM_FEATURE_SATURATION:
return "saturation";
case CAM_FEATURE_GAMMA:
return "gamma";
case CAM_FEATURE_SHUTTER:
return "shutter";
case CAM_FEATURE_GAIN:
return "gain";
case CAM_FEATURE_IRIS:
return "iris";
case CAM_FEATURE_FOCUS:
return "focus";
case CAM_FEATURE_TEMPERATURE:
return "temperature";
case CAM_FEATURE_TRIGGER:
return "trigger";
case CAM_FEATURE_TRIGGER_DELAY:
return "trigger delay";
case CAM_FEATURE_WHITE_SHADING:
return "white shading";
case CAM_FEATURE_ZOOM:
return "zoom";
case CAM_FEATURE_PAN:
return "pan";
case CAM_FEATURE_TILT:
return "tilt";
case CAM_FEATURE_OPTICAL_FILTER:
return "optical filter";
case CAM_FEATURE_CAPTURE_SIZE:
return "capture size";
case CAM_FEATURE_CAPTURE_QUALITY:
return "capture quality";
case CAM_FEATURE_CONTRAST:
return "contrast";
case CAM_FEATURE_STROBE_DURATION:
return "strobe duration";
default:
return "unknown";
}
}
CameraPtr createCamera(const string& sDriver, const string& sDevice, int unit,
bool bFW800, const IntPoint& captureSize, PixelFormat camPF, PixelFormat destPF,
float frameRate)
{
CameraPtr pCamera;
try {
if (sDriver == "firewire") {
char * pszErr;
long long guid = strtoll(sDevice.c_str(), &pszErr, 16);
if (strlen(pszErr)) {
throw Exception(AVG_ERR_INVALID_ARGS, "'"+sDevice
+"' is not a valid GUID.");
}
#if defined(AVG_ENABLE_1394_2)
pCamera = CameraPtr(new FWCamera(guid, unit, bFW800, captureSize, camPF,
destPF, frameRate));
#elif defined(AVG_ENABLE_CMU1394)
if (unit != -1) {
throw Exception(AVG_ERR_INVALID_ARGS,
"camera 'unit' attribute is not supported when using the cmu firewire driver.");
}
pCamera = CameraPtr(new CMUCamera(guid, bFW800, captureSize, camPF, destPF,
frameRate));
#else
(void)guid; // Silence compiler warning
AVG_TRACE(Logger::WARNING, "Firewire camera specified, but firewire "
"support not compiled in.");
#endif
} else if (sDriver == "video4linux") {
#if defined(AVG_ENABLE_V4L2)
pCamera = CameraPtr(new V4LCamera(sDevice, unit, captureSize, camPF,
destPF, frameRate));
#else
AVG_TRACE(Logger::WARNING, "Video4Linux camera specified, but "
"Video4Linux support not compiled in.");
#endif
} else if (sDriver == "directshow") {
#if defined(AVG_ENABLE_DSHOW)
if (unit != -1) {
throw Exception(AVG_ERR_INVALID_ARGS,
"camera 'unit' attribute is not supported when using the directshow driver.");
}
pCamera = CameraPtr(new DSCamera(sDevice, captureSize, camPF, destPF,
frameRate));
#else
AVG_TRACE(Logger::WARNING, "DirectShow camera specified, but "
"DirectShow is only available under windows.");
#endif
} else {
throw Exception(AVG_ERR_INVALID_ARGS,
"Unable to set up camera. Camera source '"+sDriver+"' unknown.");
}
} catch (const Exception& e) {
if (e.getCode() == AVG_ERR_CAMERA_NONFATAL) {
AVG_TRACE(Logger::WARNING, e.getStr());
} else {
throw;
}
}
if (!pCamera) {
pCamera = CameraPtr(new FakeCamera(camPF, destPF));
}
return pCamera;
}
std::vector<CameraInfo> getCamerasInfos()
{
std::vector<CameraInfo> camerasInfo;
#ifdef AVG_ENABLE_1394_2
int amountFWCameras = FWCamera::countCameras();
for (int i = 0; i < amountFWCameras; i++) {
CameraInfo* camInfo = FWCamera::getCameraInfos(i);
if (camInfo != NULL) {
camInfo->checkAddBayer8();
camerasInfo.push_back(*camInfo);
}
}
#endif
#ifdef AVG_ENABLE_CMU1394
int amountCMUCameras = CMUCamera::countCameras();
for (int i = 0; i < amountCMUCameras; i++) {
CameraInfo* camInfo = CMUCamera::getCameraInfos(i);
if (camInfo != NULL) {
camInfo->checkAddBayer8();
camerasInfo.push_back(*camInfo);
}
}
#endif
#ifdef AVG_ENABLE_DSHOW
int amountDSCameras = DSCamera::countCameras();
for (int i = 0; i < amountDSCameras; i++) {
CameraInfo* camInfo = DSCamera::getCameraInfos(i);
if (camInfo != NULL) {
camInfo->checkAddBayer8();
camerasInfo.push_back(*camInfo);
}
}
#endif
#ifdef AVG_ENABLE_V4L2
int amountV4LCameras = V4LCamera::countCameras();
for (int i = 0; i < amountV4LCameras; i++) {
CameraInfo* camInfo = V4LCamera::getCameraInfos(i);
if (camInfo != NULL) {
camInfo->checkAddBayer8();
camerasInfo.push_back(*camInfo);
}
}
#endif
return camerasInfo;
}
}
<|endoftext|> |
<commit_before>/*
* ceph_fs.cc - Some Ceph functions that are shared between kernel space and
* user space.
*
*/
/*
* Some non-inline ceph helpers
*/
#include "types.h"
/*
* return true if @layout appears to be valid
*/
int ceph_file_layout_is_valid(const struct ceph_file_layout *layout)
{
__u32 su = le32_to_cpu(layout->fl_stripe_unit);
__u32 sc = le32_to_cpu(layout->fl_stripe_count);
__u32 os = le32_to_cpu(layout->fl_object_size);
/* stripe unit, object size must be non-zero, 64k increment */
if (!su || (su & (CEPH_MIN_STRIPE_UNIT-1)))
return 0;
if (!os || (os & (CEPH_MIN_STRIPE_UNIT-1)))
return 0;
/* object size must be a multiple of stripe unit */
if (os < su || os % su)
return 0;
/* stripe count must be non-zero */
if (!sc)
return 0;
return 1;
}
int ceph_flags_to_mode(int flags)
{
int mode;
#ifdef O_DIRECTORY /* fixme */
if ((flags & O_DIRECTORY) == O_DIRECTORY)
return CEPH_FILE_MODE_PIN;
#endif
if ((flags & O_APPEND) == O_APPEND)
flags |= O_WRONLY;
if ((flags & O_ACCMODE) == O_RDWR)
mode = CEPH_FILE_MODE_RDWR;
else if ((flags & O_ACCMODE) == O_WRONLY)
mode = CEPH_FILE_MODE_WR;
else
mode = CEPH_FILE_MODE_RD;
#ifdef O_LAZY
if (flags & O_LAZY)
mode |= CEPH_FILE_MODE_LAZY;
#endif
return mode;
}
int ceph_caps_for_mode(int mode)
{
int caps = CEPH_CAP_PIN;
if (mode & CEPH_FILE_MODE_RD)
caps |= CEPH_CAP_FILE_SHARED |
CEPH_CAP_FILE_RD | CEPH_CAP_FILE_CACHE;
if (mode & CEPH_FILE_MODE_WR)
caps |= CEPH_CAP_FILE_EXCL |
CEPH_CAP_FILE_WR | CEPH_CAP_FILE_BUFFER |
CEPH_CAP_AUTH_SHARED | CEPH_CAP_AUTH_EXCL |
CEPH_CAP_XATTR_SHARED | CEPH_CAP_XATTR_EXCL;
if (mode & CEPH_FILE_MODE_LAZY)
caps |= CEPH_CAP_FILE_LAZYIO;
return caps;
}
<commit_msg>mds: fix O_APPEND file mode calculation<commit_after>/*
* ceph_fs.cc - Some Ceph functions that are shared between kernel space and
* user space.
*
*/
/*
* Some non-inline ceph helpers
*/
#include "types.h"
/*
* return true if @layout appears to be valid
*/
int ceph_file_layout_is_valid(const struct ceph_file_layout *layout)
{
__u32 su = le32_to_cpu(layout->fl_stripe_unit);
__u32 sc = le32_to_cpu(layout->fl_stripe_count);
__u32 os = le32_to_cpu(layout->fl_object_size);
/* stripe unit, object size must be non-zero, 64k increment */
if (!su || (su & (CEPH_MIN_STRIPE_UNIT-1)))
return 0;
if (!os || (os & (CEPH_MIN_STRIPE_UNIT-1)))
return 0;
/* object size must be a multiple of stripe unit */
if (os < su || os % su)
return 0;
/* stripe count must be non-zero */
if (!sc)
return 0;
return 1;
}
int ceph_flags_to_mode(int flags)
{
int mode;
#ifdef O_DIRECTORY /* fixme */
if ((flags & O_DIRECTORY) == O_DIRECTORY)
return CEPH_FILE_MODE_PIN;
#endif
if ((flags & O_APPEND) &&
(flags & O_ACCMODE) == 0)
flags |= O_WRONLY;
if ((flags & O_ACCMODE) == O_RDWR)
mode = CEPH_FILE_MODE_RDWR;
else if ((flags & O_ACCMODE) == O_WRONLY)
mode = CEPH_FILE_MODE_WR;
else
mode = CEPH_FILE_MODE_RD;
#ifdef O_LAZY
if (flags & O_LAZY)
mode |= CEPH_FILE_MODE_LAZY;
#endif
return mode;
}
int ceph_caps_for_mode(int mode)
{
int caps = CEPH_CAP_PIN;
if (mode & CEPH_FILE_MODE_RD)
caps |= CEPH_CAP_FILE_SHARED |
CEPH_CAP_FILE_RD | CEPH_CAP_FILE_CACHE;
if (mode & CEPH_FILE_MODE_WR)
caps |= CEPH_CAP_FILE_EXCL |
CEPH_CAP_FILE_WR | CEPH_CAP_FILE_BUFFER |
CEPH_CAP_AUTH_SHARED | CEPH_CAP_AUTH_EXCL |
CEPH_CAP_XATTR_SHARED | CEPH_CAP_XATTR_EXCL;
if (mode & CEPH_FILE_MODE_LAZY)
caps |= CEPH_CAP_FILE_LAZYIO;
return caps;
}
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
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 "flusspferd/io/stream_base.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/string_io.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/blob.hpp"
#include <boost/scoped_array.hpp>
#include <cstdlib>
using namespace flusspferd;
using namespace flusspferd::io;
stream_base::stream_base(object const &o, std::streambuf *p)
: native_object_base(o), streambuf(p)
{
register_native_method("readWhole", &stream_base::read_whole);
register_native_method("read", &stream_base::read);
register_native_method("readWholeBlob", &stream_base::read_whole_blob);
register_native_method("readBlob", &stream_base::read_blob);
register_native_method("write", &stream_base::write);
register_native_method("print", &stream_base::print);
register_native_method("flush", &stream_base::flush);
define_property("fieldSeparator", string(" "));
define_property("recordSeparator", string("\n"));
define_property("autoflush", false);
}
stream_base::~stream_base()
{}
void stream_base::set_streambuf(std::streambuf *p) {
streambuf = p;
}
std::streambuf *stream_base::get_streambuf() {
return streambuf;
}
object stream_base::class_info::create_prototype() {
local_root_scope scope;
object proto = create_object();
create_native_method(proto, "readWhole", 0);
create_native_method(proto, "read", 1);
create_native_method(proto, "readWholeBlob", 0);
create_native_method(proto, "readBlob", 1);
create_native_method(proto, "write", 1);
create_native_method(proto, "print", 0);
create_native_method(proto, "flush", 0);
return proto;
}
string stream_base::read_whole() {
std::string data;
char buf[4096];
std::streamsize length;
do {
length = streambuf->sgetn(buf, sizeof(buf));
if (length < 0)
length = 0;
data.append(buf, length);
} while (length > 0);
return string(data);
}
object stream_base::read_whole_blob() {
unsigned const N = 4096;
std::vector<char> data;
std::streamsize length;
do {
data.resize(data.size() + N);
length = streambuf->sgetn(&data[data.size() - N], N);
if (length < 0)
length = 0;
data.resize(data.size() - N + length);
} while (length > 0);
return create_native_object<blob>(
object(), (unsigned char const *)&data[0], data.size());
}
string stream_base::read(unsigned size) {
if (!size)
size = 4096;
boost::scoped_array<char> buf(new char[size + 1]);
std::streamsize length = streambuf->sgetn(buf.get(), size);
if (length < 0)
length = 0;
buf[length] = '\0';
return string(buf.get());
}
object stream_base::read_blob(unsigned size) {
if (!size)
size = 4096;
boost::scoped_array<char> buf(new char[size]);
std::streamsize length = streambuf->sgetn(buf.get(), size);
if (length < 0)
length = 0;
return create_native_object<blob>(
object(),
(unsigned char const *) buf.get(),
length);
}
void stream_base::write(value const &data) {
if (data.is_string()) {
string text = data.get_string();
char const *str = text.c_str();
streambuf->sputn(text.c_str(), std::strlen(str));
} else if (data.is_object()) {
native_object_base *ptr = native_object_base::get_native(data.get_object());
blob &b = dynamic_cast<blob&>(*ptr);
streambuf->sputn((char const*) b.get_data(), b.size());
}
//TODO slow?
if (get_property("autoflush").to_boolean())
flush();
}
void stream_base::print(call_context &x) {
local_root_scope scope;
value delim_v = get_property("fieldSeparator");
string delim;
if (!delim_v.is_void_or_null())
delim = delim_v.to_string();
std::size_t n = x.arg.size();
for (std::size_t i = 0; i < n; ++i) {
write(x.arg[i].to_string());
if (i < n - 1)
write(delim);
}
value record_v = get_property("recordSeparator");
if (!record_v.is_void_or_null())
write(record_v.to_string());
flush();
}
void stream_base::flush() {
streambuf->pubsync();
}
<commit_msg>IO: throw exception in write<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld
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 "flusspferd/io/stream_base.hpp"
#include "flusspferd/local_root_scope.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/string_io.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/blob.hpp"
#include <boost/scoped_array.hpp>
#include <cstdlib>
using namespace flusspferd;
using namespace flusspferd::io;
stream_base::stream_base(object const &o, std::streambuf *p)
: native_object_base(o), streambuf(p)
{
register_native_method("readWhole", &stream_base::read_whole);
register_native_method("read", &stream_base::read);
register_native_method("readWholeBlob", &stream_base::read_whole_blob);
register_native_method("readBlob", &stream_base::read_blob);
register_native_method("write", &stream_base::write);
register_native_method("print", &stream_base::print);
register_native_method("flush", &stream_base::flush);
define_property("fieldSeparator", string(" "));
define_property("recordSeparator", string("\n"));
define_property("autoflush", false);
}
stream_base::~stream_base()
{}
void stream_base::set_streambuf(std::streambuf *p) {
streambuf = p;
}
std::streambuf *stream_base::get_streambuf() {
return streambuf;
}
object stream_base::class_info::create_prototype() {
local_root_scope scope;
object proto = create_object();
create_native_method(proto, "readWhole", 0);
create_native_method(proto, "read", 1);
create_native_method(proto, "readWholeBlob", 0);
create_native_method(proto, "readBlob", 1);
create_native_method(proto, "write", 1);
create_native_method(proto, "print", 0);
create_native_method(proto, "flush", 0);
return proto;
}
string stream_base::read_whole() {
std::string data;
char buf[4096];
std::streamsize length;
do {
length = streambuf->sgetn(buf, sizeof(buf));
if (length < 0)
length = 0;
data.append(buf, length);
} while (length > 0);
return string(data);
}
object stream_base::read_whole_blob() {
unsigned const N = 4096;
std::vector<char> data;
std::streamsize length;
do {
data.resize(data.size() + N);
length = streambuf->sgetn(&data[data.size() - N], N);
if (length < 0)
length = 0;
data.resize(data.size() - N + length);
} while (length > 0);
return create_native_object<blob>(
object(), (unsigned char const *)&data[0], data.size());
}
string stream_base::read(unsigned size) {
if (!size)
size = 4096;
boost::scoped_array<char> buf(new char[size + 1]);
std::streamsize length = streambuf->sgetn(buf.get(), size);
if (length < 0)
length = 0;
buf[length] = '\0';
return string(buf.get());
}
object stream_base::read_blob(unsigned size) {
if (!size)
size = 4096;
boost::scoped_array<char> buf(new char[size]);
std::streamsize length = streambuf->sgetn(buf.get(), size);
if (length < 0)
length = 0;
return create_native_object<blob>(
object(),
(unsigned char const *) buf.get(),
length);
}
void stream_base::write(value const &data) {
if (data.is_string()) {
string text = data.get_string();
char const *str = text.c_str();
streambuf->sputn(text.c_str(), std::strlen(str));
} else if (data.is_object()) {
native_object_base *ptr = native_object_base::get_native(data.get_object());
blob &b = dynamic_cast<blob&>(*ptr);
streambuf->sputn((char const*) b.get_data(), b.size());
} else {
throw exception("Cannot write non-object non-string value to Stream");
}
//TODO slow?
if (get_property("autoflush").to_boolean())
flush();
}
void stream_base::print(call_context &x) {
local_root_scope scope;
value delim_v = get_property("fieldSeparator");
string delim;
if (!delim_v.is_void_or_null())
delim = delim_v.to_string();
std::size_t n = x.arg.size();
for (std::size_t i = 0; i < n; ++i) {
write(x.arg[i].to_string());
if (i < n - 1)
write(delim);
}
value record_v = get_property("recordSeparator");
if (!record_v.is_void_or_null())
write(record_v.to_string());
flush();
}
void stream_base::flush() {
streambuf->pubsync();
}
<|endoftext|> |
<commit_before>#ifndef PARSE_LITERAL_HPP_
#define PARSE_LITERAL_HPP_
#include "symbol.hpp"
#include "parse_error.hpp"
#include <boost/optional.hpp>
namespace parse_literal_detail
{
inline bool is_digit(char c)
{
return '0' <= c && c <= '9';
}
}
template <class State>
boost::optional<symbol> parse_literal(State& state)
{
using namespace parse_literal_detail;
if(state.empty())
return boost::none;
else if(state.front() == '"')
{
source_position begin = state.position();
symbol::literal result; // std::string
state.pop_front();
while(true)
{
if(state.empty() || state.front() == '\n')
throw parse_error("unmatched \"", begin, state.file());
if(state.front() == '"')
break;
else
{
result += state.front();
state.pop_front();
}
}
state.pop_front();
source_position end = state.position();
return symbol{result, source_range{begin, end, state.file()}};
}
else if(is_digit(state.front()))
{
source_position begin = state.position();
symbol::literal result; // std::string
result += state.front();
state.pop_front();
while(!state.empty() && is_digit(state.front()))
{
result += state.front();
state.pop_front();
}
source_position end = state.position();
return symbol{result, source_range{begin, end, state.file()}};
}
else
return boost::none;
}
#endif
<commit_msg>add missing move<commit_after>#ifndef PARSE_LITERAL_HPP_
#define PARSE_LITERAL_HPP_
#include "symbol.hpp"
#include "parse_error.hpp"
#include <boost/optional.hpp>
namespace parse_literal_detail
{
inline bool is_digit(char c)
{
return '0' <= c && c <= '9';
}
}
template <class State>
boost::optional<symbol> parse_literal(State& state)
{
using namespace parse_literal_detail;
if(state.empty())
return boost::none;
else if(state.front() == '"')
{
source_position begin = state.position();
symbol::literal result; // std::string
state.pop_front();
while(true)
{
if(state.empty() || state.front() == '\n')
throw parse_error("unmatched \"", begin, state.file());
if(state.front() == '"')
break;
else
{
result += state.front();
state.pop_front();
}
}
state.pop_front();
source_position end = state.position();
return symbol{std::move(result), source_range{begin, end, state.file()}};
}
else if(is_digit(state.front()))
{
source_position begin = state.position();
symbol::literal result; // std::string
result += state.front();
state.pop_front();
while(!state.empty() && is_digit(state.front()))
{
result += state.front();
state.pop_front();
}
source_position end = state.position();
return symbol{std::move(result), source_range{begin, end, state.file()}};
}
else
return boost::none;
}
#endif
<|endoftext|> |
<commit_before>/*
* Use and distribution licensed under the Apache license version 2.
*
* See the COPYING file in the root project directory for full text.
*/
#include "compare.h"
#include "keyword.h"
#include "token.h"
#include "symbol.h"
namespace sqltoast {
kw_jump_table_t _init_kw_jump_table(char lead_char) {
kw_jump_table_t t;
switch (lead_char) {
case 'a':
t.emplace_back(kw_jump_table_entry_t(KEYWORD_AUTHORIZATION, SYMBOL_AUTHORIZATION, "AUTHORIZATION"));
return t;
case 'c':
t.emplace_back(kw_jump_table_entry_t(KEYWORD_CREATE, SYMBOL_CREATE, "CREATE"));
t.emplace_back(kw_jump_table_entry_t(KEYWORD_CHARACTER, SYMBOL_CHARACTER, "CHARACTER"));
t.emplace_back(kw_jump_table_entry_t(KEYWORD_CASCADE, SYMBOL_CASCADE, "CASCADE"));
return t;
case 'd':
t.emplace_back(kw_jump_table_entry_t(KEYWORD_DEFAULT, SYMBOL_DEFAULT, "DEFAULT"));
t.emplace_back(kw_jump_table_entry_t(KEYWORD_DROP, SYMBOL_DROP, "DROP"));
return t;
case 'r':
t.emplace_back(kw_jump_table_entry_t(KEYWORD_RESTRICT, SYMBOL_RESTRICT, "RESTRICT"));
return t;
case 's':
t.emplace_back(kw_jump_table_entry_t(KEYWORD_SCHEMA, SYMBOL_SCHEMA, "SCHEMA"));
t.emplace_back(kw_jump_table_entry_t(KEYWORD_SET, SYMBOL_SET, "SET"));
return t;
}
return t;
}
kw_jump_table_t kw_jump_tables::a = _init_kw_jump_table('a');
kw_jump_table_t kw_jump_tables::c = _init_kw_jump_table('c');
kw_jump_table_t kw_jump_tables::d = _init_kw_jump_table('d');
kw_jump_table_t kw_jump_tables::r = _init_kw_jump_table('r');
kw_jump_table_t kw_jump_tables::s = _init_kw_jump_table('s');
bool token_keyword(parse_context_t& ctx) {
kw_jump_table_t* jump_tbl;
switch (*ctx.cursor) {
case 'a':
case 'A':
jump_tbl = &kw_jump_tables::a;
break;
case 'c':
case 'C':
jump_tbl = &kw_jump_tables::c;
break;
case 'd':
case 'D':
jump_tbl = &kw_jump_tables::d;
break;
case 'r':
case 'R':
jump_tbl = &kw_jump_tables::r;
break;
case 's':
case 'S':
jump_tbl = &kw_jump_tables::s;
break;
default:
return false;
}
parse_cursor_t start = ctx.cursor;
for (auto entry : *jump_tbl) {
const std::string to_end(parse_position_t(ctx.cursor), ctx.end_pos);
if (ci_find_substr(to_end, entry.kw_str) != -1) {
token_t tok(TOKEN_TYPE_KEYWORD, entry.symbol, start, parse_position_t(ctx.cursor));
ctx.push_token(tok);
ctx.cursor += entry.kw_str.size();
return true;
}
}
return false;
}
} // namespace sqltoast
<commit_msg>ensure keyword token compares lengths of lexeme<commit_after>/*
* Use and distribution licensed under the Apache license version 2.
*
* See the COPYING file in the root project directory for full text.
*/
#include "compare.h"
#include "keyword.h"
#include "token.h"
#include "symbol.h"
namespace sqltoast {
kw_jump_table_t _init_kw_jump_table(char lead_char) {
kw_jump_table_t t;
switch (lead_char) {
case 'a':
t.emplace_back(kw_jump_table_entry_t(KEYWORD_AUTHORIZATION, SYMBOL_AUTHORIZATION, "AUTHORIZATION"));
return t;
case 'c':
t.emplace_back(kw_jump_table_entry_t(KEYWORD_CREATE, SYMBOL_CREATE, "CREATE"));
t.emplace_back(kw_jump_table_entry_t(KEYWORD_CHARACTER, SYMBOL_CHARACTER, "CHARACTER"));
t.emplace_back(kw_jump_table_entry_t(KEYWORD_CASCADE, SYMBOL_CASCADE, "CASCADE"));
return t;
case 'd':
t.emplace_back(kw_jump_table_entry_t(KEYWORD_DEFAULT, SYMBOL_DEFAULT, "DEFAULT"));
t.emplace_back(kw_jump_table_entry_t(KEYWORD_DROP, SYMBOL_DROP, "DROP"));
return t;
case 'r':
t.emplace_back(kw_jump_table_entry_t(KEYWORD_RESTRICT, SYMBOL_RESTRICT, "RESTRICT"));
return t;
case 's':
t.emplace_back(kw_jump_table_entry_t(KEYWORD_SCHEMA, SYMBOL_SCHEMA, "SCHEMA"));
t.emplace_back(kw_jump_table_entry_t(KEYWORD_SET, SYMBOL_SET, "SET"));
return t;
}
return t;
}
kw_jump_table_t kw_jump_tables::a = _init_kw_jump_table('a');
kw_jump_table_t kw_jump_tables::c = _init_kw_jump_table('c');
kw_jump_table_t kw_jump_tables::d = _init_kw_jump_table('d');
kw_jump_table_t kw_jump_tables::r = _init_kw_jump_table('r');
kw_jump_table_t kw_jump_tables::s = _init_kw_jump_table('s');
bool token_keyword(parse_context_t& ctx) {
kw_jump_table_t* jump_tbl;
switch (*ctx.cursor) {
case 'a':
case 'A':
jump_tbl = &kw_jump_tables::a;
break;
case 'c':
case 'C':
jump_tbl = &kw_jump_tables::c;
break;
case 'd':
case 'D':
jump_tbl = &kw_jump_tables::d;
break;
case 'r':
case 'R':
jump_tbl = &kw_jump_tables::r;
break;
case 's':
case 'S':
jump_tbl = &kw_jump_tables::s;
break;
default:
return false;
}
parse_position_t start = ctx.cursor;
parse_cursor_t end = ctx.cursor;
// Find the next space character...
while (end != ctx.end_pos && ! std::isspace(*end))
end++;
const std::string lexeme(start, parse_position_t(end));
size_t lexeme_len = lexeme.size();
for (auto entry : *jump_tbl) {
size_t entry_len = entry.kw_str.size();
if (lexeme_len != entry_len)
continue;
if (ci_find_substr(lexeme, entry.kw_str) == 0) {
token_t tok(TOKEN_TYPE_KEYWORD, entry.symbol, start, end);
ctx.push_token(tok);
ctx.cursor += entry_len;
return true;
}
}
return false;
}
} // namespace sqltoast
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// NOTE: This file is intended to be customised by the end user, and includes
// only local node policy logic
#include <policy/policy.h>
#include <script/interpreter.h>
#include <tinyformat.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <validation.h>
Amount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn) {
/**
* "Dust" is defined in terms of dustRelayFee, which has units
* satoshis-per-kilobyte. If you'd pay more than 1/3 in fees to spend
* something, then we consider it dust. A typical spendable txout is 34
* bytes big, and will need a CTxIn of at least 148 bytes to spend: so dust
* is a spendable txout less than 546*dustRelayFee/1000 (in satoshis).
*/
if (txout.scriptPubKey.IsUnspendable()) {
return Amount::zero();
}
size_t nSize = GetSerializeSize(txout);
// the 148 mentioned above
nSize += (32 + 4 + 1 + 107 + 4);
return 3 * dustRelayFeeIn.GetFee(nSize);
}
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn) {
return (txout.nValue < GetDustThreshold(txout, dustRelayFeeIn));
}
bool IsStandard(const CScript &scriptPubKey, txnouttype &whichType) {
std::vector<std::vector<uint8_t>> vSolutions;
if (!Solver(scriptPubKey, whichType, vSolutions)) {
return false;
}
if (whichType == TX_MULTISIG) {
uint8_t m = vSolutions.front()[0];
uint8_t n = vSolutions.back()[0];
// Support up to x-of-3 multisig txns as standard
if (n < 1 || n > 3) return false;
if (m < 1 || m > n) return false;
} else if (whichType == TX_NULL_DATA) {
if (!fAcceptDatacarrier) {
return false;
}
unsigned nMaxDatacarrierBytes =
gArgs.GetArg("-datacarriersize", MAX_OP_RETURN_RELAY);
if (scriptPubKey.size() > nMaxDatacarrierBytes) {
return false;
}
}
return whichType != TX_NONSTANDARD;
}
bool IsStandardTx(const CTransaction &tx, std::string &reason) {
if (tx.nVersion > CTransaction::MAX_STANDARD_VERSION || tx.nVersion < 1) {
reason = "version";
return false;
}
// Extremely large transactions with lots of inputs can cost the network
// almost as much to process as they cost the sender in fees, because
// computing signature hashes is O(ninputs*txsize). Limiting transactions
// to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
uint32_t sz = tx.GetTotalSize();
if (sz >= MAX_STANDARD_TX_SIZE) {
reason = "tx-size";
return false;
}
for (const CTxIn &txin : tx.vin) {
if (txin.scriptSig.size() > MAX_TX_IN_SCRIPT_SIG_SIZE) {
reason = "scriptsig-size";
return false;
}
if (!txin.scriptSig.IsPushOnly()) {
reason = "scriptsig-not-pushonly";
return false;
}
}
unsigned int nDataOut = 0;
txnouttype whichType;
for (const CTxOut &txout : tx.vout) {
if (!::IsStandard(txout.scriptPubKey, whichType)) {
reason = "scriptpubkey";
return false;
}
if (whichType == TX_NULL_DATA) {
nDataOut++;
} else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
reason = "bare-multisig";
return false;
} else if (IsDust(txout, ::dustRelayFee)) {
reason = "dust";
return false;
}
}
// only one OP_RETURN txout is permitted
if (nDataOut > 1) {
reason = "multi-op-return";
return false;
}
return true;
}
/**
* Check transaction inputs to mitigate two
* potential denial-of-service attacks:
*
* 1. scriptSigs with extra data stuffed into them,
* not consumed by scriptPubKey (or P2SH script)
* 2. P2SH scripts with a crazy number of expensive
* CHECKSIG/CHECKMULTISIG operations
*
* Why bother? To avoid denial-of-service attacks; an attacker
* can submit a standard HASH... OP_EQUAL transaction,
* which will get accepted into blocks. The redemption
* script can be anything; an attacker could use a very
* expensive-to-check-upon-redemption script like:
* DUP CHECKSIG DROP ... repeated 100 times... OP_1
*/
bool AreInputsStandard(const CTransaction &tx,
const CCoinsViewCache &mapInputs) {
if (tx.IsCoinBase()) {
// Coinbases don't use vin normally.
return true;
}
for (const CTxIn &in : tx.vin) {
const CTxOut &prev = mapInputs.GetOutputFor(in);
std::vector<std::vector<uint8_t>> vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript &prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions)) {
return false;
}
if (whichType == TX_SCRIPTHASH) {
std::vector<std::vector<uint8_t>> stack;
// convert the scriptSig into a stack, so we can inspect the
// redeemScript
if (!EvalScript(stack, in.scriptSig, SCRIPT_VERIFY_NONE,
BaseSignatureChecker())) {
return false;
}
if (stack.empty()) {
return false;
}
CScript subscript(stack.back().begin(), stack.back().end());
if (subscript.GetSigOpCount(STANDARD_SCRIPT_VERIFY_FLAGS, true) >
MAX_P2SH_SIGOPS) {
return false;
}
}
}
return true;
}
CFeeRate dustRelayFee = CFeeRate(DUST_RELAY_TX_FEE);
uint32_t nBytesPerSigOp = DEFAULT_BYTES_PER_SIGOP;
int64_t GetVirtualTransactionSize(int64_t nSize, int64_t nSigOpCount,
unsigned int bytes_per_sigop) {
return std::max(nSize, nSigOpCount * bytes_per_sigop);
}
int64_t GetVirtualTransactionSize(const CTransaction &tx, int64_t nSigOpCount,
unsigned int bytes_per_sigop) {
return GetVirtualTransactionSize(::GetSerializeSize(tx, PROTOCOL_VERSION),
nSigOpCount, bytes_per_sigop);
}
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCount,
unsigned int bytes_per_sigop) {
return GetVirtualTransactionSize(::GetSerializeSize(txin, PROTOCOL_VERSION),
nSigOpCount, bytes_per_sigop);
}
<commit_msg>Add some braces to policy/policy.cpp<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// NOTE: This file is intended to be customised by the end user, and includes
// only local node policy logic
#include <policy/policy.h>
#include <script/interpreter.h>
#include <tinyformat.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <validation.h>
Amount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn) {
/**
* "Dust" is defined in terms of dustRelayFee, which has units
* satoshis-per-kilobyte. If you'd pay more than 1/3 in fees to spend
* something, then we consider it dust. A typical spendable txout is 34
* bytes big, and will need a CTxIn of at least 148 bytes to spend: so dust
* is a spendable txout less than 546*dustRelayFee/1000 (in satoshis).
*/
if (txout.scriptPubKey.IsUnspendable()) {
return Amount::zero();
}
size_t nSize = GetSerializeSize(txout);
// the 148 mentioned above
nSize += (32 + 4 + 1 + 107 + 4);
return 3 * dustRelayFeeIn.GetFee(nSize);
}
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn) {
return (txout.nValue < GetDustThreshold(txout, dustRelayFeeIn));
}
bool IsStandard(const CScript &scriptPubKey, txnouttype &whichType) {
std::vector<std::vector<uint8_t>> vSolutions;
if (!Solver(scriptPubKey, whichType, vSolutions)) {
return false;
}
if (whichType == TX_MULTISIG) {
uint8_t m = vSolutions.front()[0];
uint8_t n = vSolutions.back()[0];
// Support up to x-of-3 multisig txns as standard
if (n < 1 || n > 3) {
return false;
}
if (m < 1 || m > n) {
return false;
}
} else if (whichType == TX_NULL_DATA) {
if (!fAcceptDatacarrier) {
return false;
}
unsigned nMaxDatacarrierBytes =
gArgs.GetArg("-datacarriersize", MAX_OP_RETURN_RELAY);
if (scriptPubKey.size() > nMaxDatacarrierBytes) {
return false;
}
}
return whichType != TX_NONSTANDARD;
}
bool IsStandardTx(const CTransaction &tx, std::string &reason) {
if (tx.nVersion > CTransaction::MAX_STANDARD_VERSION || tx.nVersion < 1) {
reason = "version";
return false;
}
// Extremely large transactions with lots of inputs can cost the network
// almost as much to process as they cost the sender in fees, because
// computing signature hashes is O(ninputs*txsize). Limiting transactions
// to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
uint32_t sz = tx.GetTotalSize();
if (sz >= MAX_STANDARD_TX_SIZE) {
reason = "tx-size";
return false;
}
for (const CTxIn &txin : tx.vin) {
if (txin.scriptSig.size() > MAX_TX_IN_SCRIPT_SIG_SIZE) {
reason = "scriptsig-size";
return false;
}
if (!txin.scriptSig.IsPushOnly()) {
reason = "scriptsig-not-pushonly";
return false;
}
}
unsigned int nDataOut = 0;
txnouttype whichType;
for (const CTxOut &txout : tx.vout) {
if (!::IsStandard(txout.scriptPubKey, whichType)) {
reason = "scriptpubkey";
return false;
}
if (whichType == TX_NULL_DATA) {
nDataOut++;
} else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
reason = "bare-multisig";
return false;
} else if (IsDust(txout, ::dustRelayFee)) {
reason = "dust";
return false;
}
}
// only one OP_RETURN txout is permitted
if (nDataOut > 1) {
reason = "multi-op-return";
return false;
}
return true;
}
/**
* Check transaction inputs to mitigate two
* potential denial-of-service attacks:
*
* 1. scriptSigs with extra data stuffed into them,
* not consumed by scriptPubKey (or P2SH script)
* 2. P2SH scripts with a crazy number of expensive
* CHECKSIG/CHECKMULTISIG operations
*
* Why bother? To avoid denial-of-service attacks; an attacker
* can submit a standard HASH... OP_EQUAL transaction,
* which will get accepted into blocks. The redemption
* script can be anything; an attacker could use a very
* expensive-to-check-upon-redemption script like:
* DUP CHECKSIG DROP ... repeated 100 times... OP_1
*/
bool AreInputsStandard(const CTransaction &tx,
const CCoinsViewCache &mapInputs) {
if (tx.IsCoinBase()) {
// Coinbases don't use vin normally.
return true;
}
for (const CTxIn &in : tx.vin) {
const CTxOut &prev = mapInputs.GetOutputFor(in);
std::vector<std::vector<uint8_t>> vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript &prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions)) {
return false;
}
if (whichType == TX_SCRIPTHASH) {
std::vector<std::vector<uint8_t>> stack;
// convert the scriptSig into a stack, so we can inspect the
// redeemScript
if (!EvalScript(stack, in.scriptSig, SCRIPT_VERIFY_NONE,
BaseSignatureChecker())) {
return false;
}
if (stack.empty()) {
return false;
}
CScript subscript(stack.back().begin(), stack.back().end());
if (subscript.GetSigOpCount(STANDARD_SCRIPT_VERIFY_FLAGS, true) >
MAX_P2SH_SIGOPS) {
return false;
}
}
}
return true;
}
CFeeRate dustRelayFee = CFeeRate(DUST_RELAY_TX_FEE);
uint32_t nBytesPerSigOp = DEFAULT_BYTES_PER_SIGOP;
int64_t GetVirtualTransactionSize(int64_t nSize, int64_t nSigOpCount,
unsigned int bytes_per_sigop) {
return std::max(nSize, nSigOpCount * bytes_per_sigop);
}
int64_t GetVirtualTransactionSize(const CTransaction &tx, int64_t nSigOpCount,
unsigned int bytes_per_sigop) {
return GetVirtualTransactionSize(::GetSerializeSize(tx, PROTOCOL_VERSION),
nSigOpCount, bytes_per_sigop);
}
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCount,
unsigned int bytes_per_sigop) {
return GetVirtualTransactionSize(::GetSerializeSize(txin, PROTOCOL_VERSION),
nSigOpCount, bytes_per_sigop);
}
<|endoftext|> |
<commit_before>/*
* File: StateGameStarted.cpp
* Author: maxence
*
* Created on 16 janvier 2015, 23:28
*/
#include "shared/network/MsgData.h"
#include "shared/network/MsgType.h"
#include "shared/network/MsgAction.h"
#include "client/ClientPlayer.h"
#include "client/ClientWorld.h"
#include "client/view/DetailsView.h"
#include "client/view/GlobalView.h"
#include "client/network/ClientNetwork.h"
#include "client/state/game/ClientStateGame.h"
#include "client/state/game/ClientStateGameStarted.h"
#include "client/network/Input.h"
ClientStateGameStarted::ClientStateGameStarted(ClientStateGame& manager, ClientNetwork& network, ClientPlayer& player, ClientWorld& world)
: State()
, m_manager(manager)
, m_network(network)
, m_player(player)
, m_world(world)
, m_followingCamera(true)
, m_zoomValue(1.0f) {
}
ClientStateGameStarted::~ClientStateGameStarted() {
}
void ClientStateGameStarted::initialize(void) {
}
void ClientStateGameStarted::release(void) {
}
void ClientStateGameStarted::activate(void) {
std::cout << "[GameStarted][Activate]" << std::endl;
m_globalView = new GlobalView(m_world.getHeightMap(), m_world.getWindMap(), m_world.getClientShip());
m_detailsView = new DetailsView(m_world);
m_mainGraphic = dynamic_cast<sf::Drawable*> (m_detailsView);
}
void ClientStateGameStarted::deactivate(void) {
std::cout << "[GameStarted][Desactivate]" << std::endl;
m_mainGraphic = nullptr;
delete m_globalView;
delete m_detailsView;
}
void ClientStateGameStarted::update(float dt) {
Input input(m_keys, m_clock.getElapsedTime());
m_world.update(dt);
sf::Uint32 id = m_predictions.add(input);
sendInfo(input, id);
}
void ClientStateGameStarted::render(sf::RenderWindow& window) const {
// Set view position
if (m_followingCamera) {
m_detailsView->setCenter(m_world.getClientShip().getPosition());
}
// Draw view
if (m_mainGraphic)
window.draw(*m_mainGraphic);
// Draw winnner
/*if (m_endGame != nullptr) {
window.setView(window.getDefaultView());
window.draw(TextView(m_winner, 40, TypeAlign::Center));
}*/
}
void ClientStateGameStarted::sendInfo(const Input &input, sf::Uint32 id) {
MsgData msg;
msg << MsgType::Action << static_cast<sf::Uint8> (input.getActions().to_ulong()) << id;
m_network.getUdpManager().send(msg);
}
bool ClientStateGameStarted::switchFollowingCamera() {
m_followingCamera = !m_followingCamera;
return m_followingCamera;
}
bool ClientStateGameStarted::read(sf::Event& event) {
if (event.type == sf::Event::Closed) {
return false;
} else if (event.type == sf::Event::Resized) {
m_detailsView->getView().setSize({event.size.width * m_zoomValue, event.size.height * m_zoomValue});
} else if (event.type == sf::Event::KeyPressed) {
switch (event.key.code) {
case sf::Keyboard::Left:
m_detailsView->getView().move(-5.0f * m_zoomValue, 0.0f);
break;
case sf::Keyboard::Right:
m_detailsView->getView().move(5.0f * m_zoomValue, 0.0f);
break;
case sf::Keyboard::Up:
m_detailsView->getView().move(0.0f, -5.0f * m_zoomValue);
break;
case sf::Keyboard::Down:
m_detailsView->getView().move(0.0f, 5.0f * m_zoomValue);
break;
case sf::Keyboard::L:
case sf::Keyboard::Subtract:
m_zoomValue *= 2.0f;
m_detailsView->getView().zoom(2.0f);
break;
case sf::Keyboard::P:
case sf::Keyboard::Add:
m_zoomValue *= 0.5f;
m_detailsView->getView().zoom(0.5f);
break;
case sf::Keyboard::D:
m_world.getClientShip().setTurningPositive(true);
m_keys.set(TURN_HELM_POSITIVE, true);
break;
case sf::Keyboard::Q:
m_world.getClientShip().setTurningNegative(true);
m_keys.set(TURN_HELM_NEGATIVE, true);
break;
case sf::Keyboard::Z:
m_world.getClientShip().getSail().setTurningPositive(true);
m_keys.set(TURN_SAIL_POSITIVE, true);
break;
case sf::Keyboard::S:
m_world.getClientShip().getSail().setTurningNegative(true);
m_keys.set(TURN_SAIL_NEGATIVE, true);
break;
case sf::Keyboard::A:
m_detailsView->switchSquared();
break;
case sf::Keyboard::W:
m_detailsView->switchEnableWind();
break;
case sf::Keyboard::C:
switchFollowingCamera();
break;
case sf::Keyboard::M:
m_mainGraphic = (m_mainGraphic == dynamic_cast<sf::Drawable*> (m_detailsView)) ? dynamic_cast<sf::Drawable*> (m_globalView) : dynamic_cast<sf::Drawable*> (m_detailsView);
break;
case sf::Keyboard::Escape:
return false;
break;
default:
break;
}
} else if (event.type == sf::Event::KeyReleased) {
switch (event.key.code) {
case sf::Keyboard::D:
m_keys.set(TURN_HELM_POSITIVE, false);
m_world.getClientShip().setTurningPositive(false);
break;
case sf::Keyboard::Q:
m_keys.set(TURN_HELM_NEGATIVE, false);
m_world.getClientShip().setTurningNegative(false);
break;
case sf::Keyboard::Z:
m_keys.set(TURN_SAIL_POSITIVE, false);
m_world.getClientShip().getSail().setTurningPositive(false);
break;
case sf::Keyboard::S:
m_keys.set(TURN_SAIL_NEGATIVE, false);
m_world.getClientShip().getSail().setTurningNegative(false);
break;
default:
break;
}
}
return true;
}
bool ClientStateGameStarted::read(MsgData& msg) {
MsgType msgType;
msg >> msgType;
switch (msgType) {
case MsgType::GameInfo:
return readGameInfo(msg);
case MsgType::Disconnect:
return readDisconnect(msg);
case MsgType::Checkpoint:
return readCheckpoint(msg);
case MsgType::GameEnd:
return readMsgEnd(msg);
default:
return true;
}
}
bool ClientStateGameStarted::readGameInfo(MsgData & msg) {
std::cout << "GameInfo" << std::endl;
sf::Uint32 idReq;
msg >> idReq;
while (!msg.endOfPacket()) {
sf::Uint8 id;
float shipAngle;
float sailAngle;
float positionX;
float positionY;
float speedX;
float speedY;
msg >> id >> shipAngle >> sailAngle >> positionX >> positionY >> speedX >> speedY;
Ship &ship = m_world.getShips()[static_cast<unsigned int> (id)];
ship.setAngle(shipAngle);
ship.getSail().setAngle(sailAngle);
ship.position() = {positionX, positionY};
ship.velocity() = {speedX, speedY};
std::cout << "Recv ship(" << static_cast<unsigned int> (id) << ") pos(" << positionX << "," << positionY << ") speed(" << speedX << "," << speedY << ")" << std::endl;
}
updatePrediction(idReq);
return true;
}
void ClientStateGameStarted::updatePrediction(sf::Uint32 reqId) {
std::vector<Input> predictions = m_predictions.getInputFrom(reqId);
std::cout << "nbPrediction(" << predictions.size() << ")" << std::endl;
Input* prevInput = &predictions[0];
sf::Vector2f oldShipPos = m_world.getClientShip().getPosition();
for (unsigned int i = 1; i < predictions.size(); ++i) {
// Set state of world
Ship& ship = m_world.getClientShip();
ship.setTurningNegative(prevInput->getActions().test(TURN_HELM_NEGATIVE));
ship.setTurningPositive(prevInput->getActions().test(TURN_HELM_POSITIVE));
ship.getSail().setTurningNegative(prevInput->getActions().test(TURN_SAIL_NEGATIVE));
ship.getSail().setTurningPositive(prevInput->getActions().test(TURN_SAIL_POSITIVE));
// Update
sf::Time diffTime = predictions[i].getTime() - prevInput->getTime();
m_world.updateShip(m_world.getClientShip(), diffTime.asSeconds());
// Go to the next predictions
prevInput = &predictions[i];
}
// Set state of world
Ship& ship = m_world.getClientShip();
sf::Vector2f& newShipPos = ship.position();
// Smouth correction
sf::Vector2f diffPos = newShipPos - oldShipPos;
// if(std::abs(diffPos.x) < 1) {
// newShipPos.x = oldShipPos.x + (diffPos.x * 0.2);
// }
// if(std::abs(diffPos.y) < 1) {
// newShipPos.y = oldShipPos.y + (diffPos.y * 0.2);
// }
ship.setTurningNegative(prevInput->getActions().test(TURN_HELM_NEGATIVE));
ship.setTurningPositive(prevInput->getActions().test(TURN_HELM_POSITIVE));
ship.getSail().setTurningNegative(prevInput->getActions().test(TURN_SAIL_NEGATIVE));
ship.getSail().setTurningPositive(prevInput->getActions().test(TURN_SAIL_POSITIVE));
}
bool ClientStateGameStarted::readCheckpoint(MsgData& msg) {
sf::Uint8 idCheckpoint;
msg >> idCheckpoint;
m_world.getCheckPointManager().getCheckPoint(idCheckpoint).activate();
return true;
}
bool ClientStateGameStarted::readDisconnect(MsgData & msg) {
sf::Uint8 id;
msg >> id;
std::cout << m_world.getShips().erase(static_cast<unsigned int> (id)) << std::endl;
m_detailsView->updateShips();
std::cout << "Ship of player " << static_cast<unsigned int> (id) << " remove and view update" << std::endl;
return true;
}
bool ClientStateGameStarted::readMsgEnd(MsgData & msg) {
m_manager.push(EStateGame::End);
return true;
}<commit_msg>add missing add<commit_after>/*
* File: StateGameStarted.cpp
* Author: maxence
*
* Created on 16 janvier 2015, 23:28
*/
#include "shared/network/MsgData.h"
#include "shared/network/MsgType.h"
#include "shared/network/MsgAction.h"
#include "client/ClientPlayer.h"
#include "client/ClientWorld.h"
#include "client/view/DetailsView.h"
#include "client/view/GlobalView.h"
#include "client/network/ClientNetwork.h"
#include "client/state/game/ClientStateGame.h"
#include "client/state/game/ClientStateGameStarted.h"
#include "client/network/Input.h"
ClientStateGameStarted::ClientStateGameStarted(ClientStateGame& manager, ClientNetwork& network, ClientPlayer& player, ClientWorld& world)
: State()
, m_manager(manager)
, m_network(network)
, m_player(player)
, m_world(world)
, m_followingCamera(true)
, m_zoomValue(1.0f) {
}
ClientStateGameStarted::~ClientStateGameStarted() {
}
void ClientStateGameStarted::initialize(void) {
}
void ClientStateGameStarted::release(void) {
}
void ClientStateGameStarted::activate(void) {
std::cout << "[GameStarted][Activate]" << std::endl;
m_globalView = new GlobalView(m_world.getHeightMap(), m_world.getWindMap(), m_world.getClientShip());
m_detailsView = new DetailsView(m_world);
m_mainGraphic = dynamic_cast<sf::Drawable*> (m_detailsView);
}
void ClientStateGameStarted::deactivate(void) {
std::cout << "[GameStarted][Desactivate]" << std::endl;
m_mainGraphic = nullptr;
delete m_globalView;
delete m_detailsView;
}
void ClientStateGameStarted::update(float dt) {
Input input(m_keys, m_clock.getElapsedTime());
m_world.update(dt);
sf::Uint32 id = m_predictions.add(input);
sendInfo(input, id);
}
void ClientStateGameStarted::render(sf::RenderWindow& window) const {
// Set view position
if (m_followingCamera) {
m_detailsView->setCenter(m_world.getClientShip().getPosition());
}
// Draw view
if (m_mainGraphic)
window.draw(*m_mainGraphic);
// Draw winnner
/*if (m_endGame != nullptr) {
window.setView(window.getDefaultView());
window.draw(TextView(m_winner, 40, TypeAlign::Center));
}*/
}
void ClientStateGameStarted::sendInfo(const Input &input, sf::Uint32 id) {
MsgData msg;
msg << MsgType::Action << static_cast<sf::Uint8> (input.getActions().to_ulong()) << id;
m_network.getUdpManager().send(msg);
}
bool ClientStateGameStarted::switchFollowingCamera() {
m_followingCamera = !m_followingCamera;
return m_followingCamera;
}
bool ClientStateGameStarted::read(sf::Event& event) {
if (event.type == sf::Event::Closed) {
return false;
} else if (event.type == sf::Event::Resized) {
m_detailsView->getView().setSize({event.size.width * m_zoomValue, event.size.height * m_zoomValue});
} else if (event.type == sf::Event::KeyPressed) {
switch (event.key.code) {
case sf::Keyboard::Left:
m_detailsView->getView().move(-5.0f * m_zoomValue, 0.0f);
break;
case sf::Keyboard::Right:
m_detailsView->getView().move(5.0f * m_zoomValue, 0.0f);
break;
case sf::Keyboard::Up:
m_detailsView->getView().move(0.0f, -5.0f * m_zoomValue);
break;
case sf::Keyboard::Down:
m_detailsView->getView().move(0.0f, 5.0f * m_zoomValue);
break;
case sf::Keyboard::L:
case sf::Keyboard::Subtract:
m_zoomValue *= 2.0f;
m_detailsView->getView().zoom(2.0f);
break;
case sf::Keyboard::P:
case sf::Keyboard::Add:
m_zoomValue *= 0.5f;
m_detailsView->getView().zoom(0.5f);
break;
case sf::Keyboard::D:
m_world.getClientShip().setTurningPositive(true);
m_keys.set(TURN_HELM_POSITIVE, true);
break;
case sf::Keyboard::Q:
m_world.getClientShip().setTurningNegative(true);
m_keys.set(TURN_HELM_NEGATIVE, true);
break;
case sf::Keyboard::Z:
m_world.getClientShip().getSail().setTurningPositive(true);
m_keys.set(TURN_SAIL_POSITIVE, true);
break;
case sf::Keyboard::S:
m_world.getClientShip().getSail().setTurningNegative(true);
m_keys.set(TURN_SAIL_NEGATIVE, true);
break;
case sf::Keyboard::A:
m_detailsView->switchSquared();
break;
case sf::Keyboard::W:
m_detailsView->switchEnableWind();
break;
case sf::Keyboard::C:
switchFollowingCamera();
break;
case sf::Keyboard::M:
m_mainGraphic = (m_mainGraphic == dynamic_cast<sf::Drawable*> (m_detailsView)) ? dynamic_cast<sf::Drawable*> (m_globalView) : dynamic_cast<sf::Drawable*> (m_detailsView);
break;
case sf::Keyboard::Escape:
return false;
break;
default:
break;
}
} else if (event.type == sf::Event::KeyReleased) {
switch (event.key.code) {
case sf::Keyboard::D:
m_keys.set(TURN_HELM_POSITIVE, false);
m_world.getClientShip().setTurningPositive(false);
break;
case sf::Keyboard::Q:
m_keys.set(TURN_HELM_NEGATIVE, false);
m_world.getClientShip().setTurningNegative(false);
break;
case sf::Keyboard::Z:
m_keys.set(TURN_SAIL_POSITIVE, false);
m_world.getClientShip().getSail().setTurningPositive(false);
break;
case sf::Keyboard::S:
m_keys.set(TURN_SAIL_NEGATIVE, false);
m_world.getClientShip().getSail().setTurningNegative(false);
break;
default:
break;
}
}
return true;
}
bool ClientStateGameStarted::read(MsgData& msg) {
MsgType msgType;
msg >> msgType;
switch (msgType) {
case MsgType::GameInfo:
return readGameInfo(msg);
case MsgType::Disconnect:
return readDisconnect(msg);
case MsgType::Checkpoint:
return readCheckpoint(msg);
case MsgType::GameEnd:
return readMsgEnd(msg);
default:
return true;
}
}
bool ClientStateGameStarted::readGameInfo(MsgData & msg) {
std::cout << "GameInfo" << std::endl;
sf::Uint32 idReq;
msg >> idReq;
while (!msg.endOfPacket()) {
sf::Uint8 id;
float shipAngle;
float sailAngle;
float positionX;
float positionY;
float speedX;
float speedY;
msg >> id >> shipAngle >> sailAngle >> positionX >> positionY >> speedX >> speedY;
Ship &ship = m_world.getShips()[static_cast<unsigned int> (id)];
ship.setAngle(shipAngle);
ship.getSail().setAngle(sailAngle);
ship.position() = {positionX, positionY};
ship.velocity() = {speedX, speedY};
std::cout << "Recv ship(" << static_cast<unsigned int> (id) << ") pos(" << positionX << "," << positionY << ") speed(" << speedX << "," << speedY << ")" << std::endl;
}
updatePrediction(idReq);
return true;
}
void ClientStateGameStarted::updatePrediction(sf::Uint32 reqId) {
std::vector<Input> predictions = m_predictions.getInputFrom(reqId);
std::cout << "nbPrediction(" << predictions.size() << ")" << std::endl;
Input* prevInput = &predictions[0];
sf::Vector2f oldShipPos = m_world.getClientShip().getPosition();
for (unsigned int i = 1; i < predictions.size(); ++i) {
// Set state of world
Ship& ship = m_world.getClientShip();
ship.setTurningNegative(prevInput->getActions().test(TURN_HELM_NEGATIVE));
ship.setTurningPositive(prevInput->getActions().test(TURN_HELM_POSITIVE));
ship.getSail().setTurningNegative(prevInput->getActions().test(TURN_SAIL_NEGATIVE));
ship.getSail().setTurningPositive(prevInput->getActions().test(TURN_SAIL_POSITIVE));
// Update
sf::Time diffTime = predictions[i].getTime() - prevInput->getTime();
m_world.updateShip(m_world.getClientShip(), diffTime.asSeconds());
// Go to the next predictions
prevInput = &predictions[i];
}
// Set state of world
Ship& ship = m_world.getClientShip();
sf::Vector2f& newShipPos = ship.position();
// Smouth correction
sf::Vector2f diffPos = newShipPos - oldShipPos;
if(std::abs(diffPos.x) < 1) {
newShipPos.x = oldShipPos.x + (diffPos.x * 0.2);
}
if(std::abs(diffPos.y) < 1) {
newShipPos.y = oldShipPos.y + (diffPos.y * 0.2);
}
ship.setTurningNegative(prevInput->getActions().test(TURN_HELM_NEGATIVE));
ship.setTurningPositive(prevInput->getActions().test(TURN_HELM_POSITIVE));
ship.getSail().setTurningNegative(prevInput->getActions().test(TURN_SAIL_NEGATIVE));
ship.getSail().setTurningPositive(prevInput->getActions().test(TURN_SAIL_POSITIVE));
}
bool ClientStateGameStarted::readCheckpoint(MsgData& msg) {
sf::Uint8 idCheckpoint;
msg >> idCheckpoint;
m_world.getCheckPointManager().getCheckPoint(idCheckpoint).activate();
return true;
}
bool ClientStateGameStarted::readDisconnect(MsgData & msg) {
sf::Uint8 id;
msg >> id;
std::cout << m_world.getShips().erase(static_cast<unsigned int> (id)) << std::endl;
m_detailsView->updateShips();
std::cout << "Ship of player " << static_cast<unsigned int> (id) << " remove and view update" << std::endl;
return true;
}
bool ClientStateGameStarted::readMsgEnd(MsgData & msg) {
m_manager.push(EStateGame::End);
return true;
}<|endoftext|> |
<commit_before>#include "rpcconsole.h"
#include "ui_rpcconsole.h"
#include "clientmodel.h"
#include "bitcoinrpc.h"
#include "guiutil.h"
#include <QTime>
#include <QTimer>
#include <QThread>
#include <QTextEdit>
#include <QKeyEvent>
#include <QUrl>
#include <QScrollBar>
#include <openssl/crypto.h>
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_SCROLLBACK = 50;
const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);
const struct {
const char *url;
const char *source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}
};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor: public QObject
{
Q_OBJECT
public slots:
void start();
void request(const QString &command);
signals:
void reply(int category, const QString &command);
};
#include "rpcconsole.moc"
void RPCExecutor::start()
{
// Nothing to do
}
/**
* Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
*
* - Arguments are delimited with whitespace
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] args Parsed arguments will be appended to this list
* @param[in] strCommand Command line to split
*/
bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
{
enum CmdParseState
{
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
foreach(char ch, strCommand)
{
switch(state)
{
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch(ch)
{
case '"': state = STATE_DOUBLEQUOTED; break;
case '\'': state = STATE_SINGLEQUOTED; break;
case '\\': state = STATE_ESCAPE_OUTER; break;
case ' ': case '\n': case '\t':
if(state == STATE_ARGUMENT) // Space ends argument
{
args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default: curarg += ch; state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch(ch)
{
case '\'': state = STATE_ARGUMENT; break;
default: curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch(ch)
{
case '"': state = STATE_ARGUMENT; break;
case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
default: curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch; state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch; state = STATE_DOUBLEQUOTED;
break;
}
}
switch(state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
args.push_back(curarg);
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString &command)
{
std::vector<std::string> args;
if(!parseCommandLine(args, command.toStdString()))
{
emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
if(args.empty())
return; // Nothing to do
try
{
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
json_spirit::Value result = tableRPC.execute(
args[0],
RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
// Format result reply
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
}
catch (json_spirit::Object& objError)
{
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
}
catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
}
}
catch (std::exception& e)
{
emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(QWidget *parent) :
QDialog(parent),
ui(new Ui::RPCConsole),
historyPtr(0)
{
ui->setupUi(this);
#ifndef Q_WS_MAC
ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
ui->showCLOptionsButton->setIcon(QIcon(":/icons/options"));
#endif
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// set OpenSSL version label
ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
startExecutor();
clear();
}
RPCConsole::~RPCConsole()
{
emit stopExecutor();
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
{
if(obj == ui->lineEdit)
{
if(event->type() == QEvent::KeyPress)
{
QKeyEvent *key = static_cast<QKeyEvent*>(event);
switch(key->key())
{
case Qt::Key_Up: browseHistory(-1); return true;
case Qt::Key_Down: browseHistory(1); return true;
}
}
}
return QDialog::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel *model)
{
this->clientModel = model;
if(model)
{
// Subscribe to information, replies, messages, errors
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->startupTime->setText(model->formatClientStartupTime());
setNumConnections(model->getNumConnections());
ui->isTestNet->setChecked(model->isTestNet());
setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers());
}
}
static QString categoryClass(int category)
{
switch(category)
{
case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
case RPCConsole::CMD_ERROR: return "cmd-error"; break;
default: return "misc";
}
}
void RPCConsole::clear()
{
ui->messagesWidget->clear();
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for(int i=0; ICON_MAPPING[i].url; ++i)
{
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
ui->messagesWidget->document()->setDefaultStyleSheet(
"table { }"
"td.time { color: #808080; padding-top: 3px; } "
"td.message { font-family: Monospace; font-size: 12px; } "
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
"b { color: #006060; } "
);
message(CMD_REPLY, (tr("Welcome to the Bitcoin RPC console.") + "<br>" +
tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")), true);
}
void RPCConsole::message(int category, const QString &message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if(html)
out += message;
else
out += GUIUtil::HtmlEscape(message, true);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
ui->numberOfConnections->setText(QString::number(count));
}
void RPCConsole::setNumBlocks(int count, int countOfPeers)
{
ui->numberOfBlocks->setText(QString::number(count));
ui->totalBlocks->setText(QString::number(countOfPeers));
if(clientModel)
{
// If there is no current number available display N/A instead of 0, which can't ever be true
ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers()));
ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
}
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if(!cmd.isEmpty())
{
message(CMD_REQUEST, cmd);
emit cmdRequest(cmd);
// Truncate history from current position
history.erase(history.begin() + historyPtr, history.end());
// Append command to history
history.append(cmd);
// Enforce maximum history size
while(history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if(historyPtr < 0)
historyPtr = 0;
if(historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if(historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread* thread = new QThread;
RPCExecutor *executor = new RPCExecutor();
executor->moveToThread(thread);
// Notify executor when thread started (in executor thread)
connect(thread, SIGNAL(started()), executor, SLOT(start()));
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if(ui->tabWidget->widget(index) == ui->tab_console)
{
ui->lineEdit->setFocus();
}
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_showCLOptionsButton_clicked()
{
GUIUtil::HelpMessageBox help;
help.exec();
}
<commit_msg>clear history when using clear button in RPC console<commit_after>#include "rpcconsole.h"
#include "ui_rpcconsole.h"
#include "clientmodel.h"
#include "bitcoinrpc.h"
#include "guiutil.h"
#include <QTime>
#include <QTimer>
#include <QThread>
#include <QTextEdit>
#include <QKeyEvent>
#include <QUrl>
#include <QScrollBar>
#include <openssl/crypto.h>
// TODO: add a scrollback limit, as there is currently none
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);
const struct {
const char *url;
const char *source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}
};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor: public QObject
{
Q_OBJECT
public slots:
void start();
void request(const QString &command);
signals:
void reply(int category, const QString &command);
};
#include "rpcconsole.moc"
void RPCExecutor::start()
{
// Nothing to do
}
/**
* Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
*
* - Arguments are delimited with whitespace
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] args Parsed arguments will be appended to this list
* @param[in] strCommand Command line to split
*/
bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
{
enum CmdParseState
{
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
foreach(char ch, strCommand)
{
switch(state)
{
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch(ch)
{
case '"': state = STATE_DOUBLEQUOTED; break;
case '\'': state = STATE_SINGLEQUOTED; break;
case '\\': state = STATE_ESCAPE_OUTER; break;
case ' ': case '\n': case '\t':
if(state == STATE_ARGUMENT) // Space ends argument
{
args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default: curarg += ch; state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch(ch)
{
case '\'': state = STATE_ARGUMENT; break;
default: curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch(ch)
{
case '"': state = STATE_ARGUMENT; break;
case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
default: curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch; state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch; state = STATE_DOUBLEQUOTED;
break;
}
}
switch(state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
args.push_back(curarg);
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString &command)
{
std::vector<std::string> args;
if(!parseCommandLine(args, command.toStdString()))
{
emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
if(args.empty())
return; // Nothing to do
try
{
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
json_spirit::Value result = tableRPC.execute(
args[0],
RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
// Format result reply
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
}
catch (json_spirit::Object& objError)
{
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
}
catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
}
}
catch (std::exception& e)
{
emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(QWidget *parent) :
QDialog(parent),
ui(new Ui::RPCConsole),
historyPtr(0)
{
ui->setupUi(this);
#ifndef Q_WS_MAC
ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
ui->showCLOptionsButton->setIcon(QIcon(":/icons/options"));
#endif
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// set OpenSSL version label
ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
startExecutor();
clear();
}
RPCConsole::~RPCConsole()
{
emit stopExecutor();
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
{
if(obj == ui->lineEdit)
{
if(event->type() == QEvent::KeyPress)
{
QKeyEvent *key = static_cast<QKeyEvent*>(event);
switch(key->key())
{
case Qt::Key_Up: browseHistory(-1); return true;
case Qt::Key_Down: browseHistory(1); return true;
}
}
}
return QDialog::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel *model)
{
this->clientModel = model;
if(model)
{
// Subscribe to information, replies, messages, errors
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->startupTime->setText(model->formatClientStartupTime());
setNumConnections(model->getNumConnections());
ui->isTestNet->setChecked(model->isTestNet());
setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers());
}
}
static QString categoryClass(int category)
{
switch(category)
{
case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
case RPCConsole::CMD_ERROR: return "cmd-error"; break;
default: return "misc";
}
}
void RPCConsole::clear()
{
ui->messagesWidget->clear();
history.clear();
historyPtr = 0;
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for(int i=0; ICON_MAPPING[i].url; ++i)
{
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
ui->messagesWidget->document()->setDefaultStyleSheet(
"table { }"
"td.time { color: #808080; padding-top: 3px; } "
"td.message { font-family: Monospace; font-size: 12px; } "
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
"b { color: #006060; } "
);
message(CMD_REPLY, (tr("Welcome to the Bitcoin RPC console.") + "<br>" +
tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")), true);
}
void RPCConsole::message(int category, const QString &message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if(html)
out += message;
else
out += GUIUtil::HtmlEscape(message, true);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
ui->numberOfConnections->setText(QString::number(count));
}
void RPCConsole::setNumBlocks(int count, int countOfPeers)
{
ui->numberOfBlocks->setText(QString::number(count));
ui->totalBlocks->setText(QString::number(countOfPeers));
if(clientModel)
{
// If there is no current number available display N/A instead of 0, which can't ever be true
ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers()));
ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
}
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if(!cmd.isEmpty())
{
message(CMD_REQUEST, cmd);
emit cmdRequest(cmd);
// Truncate history from current position
history.erase(history.begin() + historyPtr, history.end());
// Append command to history
history.append(cmd);
// Enforce maximum history size
while(history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if(historyPtr < 0)
historyPtr = 0;
if(historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if(historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread* thread = new QThread;
RPCExecutor *executor = new RPCExecutor();
executor->moveToThread(thread);
// Notify executor when thread started (in executor thread)
connect(thread, SIGNAL(started()), executor, SLOT(start()));
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if(ui->tabWidget->widget(index) == ui->tab_console)
{
ui->lineEdit->setFocus();
}
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_showCLOptionsButton_clicked()
{
GUIUtil::HelpMessageBox help;
help.exec();
}
<|endoftext|> |
<commit_before>#include "recorder_node.h"
#include <cinder/audio/Context.h>
namespace cieq {
namespace audio {
RecorderNode::RecorderNode(size_t numFrames, const Format &format /*= Format()*/)
: inherited(numFrames, format)
, mWindowSize(format.getWindowSize())
, mHopSize(format.getHopSize())
, mLastQueried(0)
{
mMaxPopsPossible = (getNumFrames() - getWindowSize()) / getHopSize();
if ((getNumFrames() - getWindowSize()) % getHopSize() != 0)
mMaxPopsPossible += 1;
}
RecorderNode::RecorderNode(const Format &format /*= Format()*/)
: RecorderNode(0.0f, format)
{}
RecorderNode::RecorderNode(float numSeconds, const Format &format /*= Format()*/)
: RecorderNode(static_cast<size_t>(ci::audio::Context::master()->getSampleRate() * numSeconds), format)
{}
ci::audio::BufferDynamic& RecorderNode::getBufferRaw()
{
return mRecorderBuffer;
}
void RecorderNode::getBufferChunk(size_t start, size_t len, ci::audio::Buffer& other)
{
other.copyOffset(getBufferRaw(), len, 0, start);
}
void RecorderNode::getBufferChunk(size_t start, ci::audio::Buffer& other)
{
getBufferChunk(start, mWindowSize, other);
}
bool RecorderNode::popBufferWindow(ci::audio::Buffer& other)
{
if (!isRecording()) return false;
if (mLastQueried + mWindowSize <= getWritePosition())
{
getBufferChunk(mLastQueried, other);
mLastQueried += mHopSize;
return true;
}
// This is the critical situation that can happen at the end of samples
// where there's not enough number of samples for the last buffer.
else if (getNumFrames() - mLastQueried < mWindowSize)
{
getBufferChunk(mLastQueried, getNumFrames() - mLastQueried, other);
mLastQueried = getNumFrames();
return true;
}
else
{
return false;
}
}
bool RecorderNode::popBufferWindow(size_t& query_pos)
{
if (!isRecording()) return false;
if (mLastQueried + mWindowSize <= getWritePosition())
{
query_pos = mLastQueried;
mLastQueried += mHopSize;
return true;
}
// This is the critical situation that can happen at the end of samples
// where there's not enough number of samples for the last buffer.
else if (getNumFrames() - mLastQueried < mWindowSize)
{
query_pos = mLastQueried;
mLastQueried = getNumFrames();
return true;
}
else
{
return false;
}
}
bool RecorderNode::popBufferWindow(ci::audio::Buffer& other, size_t query_pos)
{
if (query_pos + mWindowSize <= getWritePosition())
{
getBufferChunk(query_pos, other);
query_pos += mHopSize;
return true;
}
// This is the critical situation that can happen at the end of samples
// where there's not enough number of samples for the last buffer.
else if (getNumFrames() - query_pos < mWindowSize)
{
getBufferChunk(query_pos, getNumFrames() - query_pos, other);
query_pos = getNumFrames();
return true;
}
else
{
return false;
}
}
size_t RecorderNode::getWindowSize() const
{
return mWindowSize;
}
size_t RecorderNode::getHopSize() const
{
return mHopSize;
}
bool RecorderNode::isRecording() const
{
return getWritePosition() != getNumFrames();
}
size_t RecorderNode::getMaxPossiblePops() const
{
return mMaxPopsPossible;
}
size_t RecorderNode::getQueryIndexByQueryPos(size_t pos)
{
return pos / mHopSize;
}
void RecorderNode::reset()
{
mLastQueried = 0;
}
}} //!cieq::node<commit_msg>Fixed a math issue for calculating max number of hops possible<commit_after>#include "recorder_node.h"
#include <cinder/audio/Context.h>
namespace cieq {
namespace audio {
RecorderNode::RecorderNode(size_t numFrames, const Format &format /*= Format()*/)
: inherited(numFrames, format)
, mWindowSize(format.getWindowSize())
, mHopSize(format.getHopSize())
, mLastQueried(0)
{
mMaxPopsPossible = getNumFrames() / getHopSize();
if (getNumFrames() % getHopSize() == 0)
mMaxPopsPossible -= 1; //special case where last chunk will be equal to one hop
}
RecorderNode::RecorderNode(const Format &format /*= Format()*/)
: RecorderNode(0.0f, format)
{}
RecorderNode::RecorderNode(float numSeconds, const Format &format /*= Format()*/)
: RecorderNode(static_cast<size_t>(ci::audio::Context::master()->getSampleRate() * numSeconds), format)
{}
ci::audio::BufferDynamic& RecorderNode::getBufferRaw()
{
return mRecorderBuffer;
}
void RecorderNode::getBufferChunk(size_t start, size_t len, ci::audio::Buffer& other)
{
other.copyOffset(getBufferRaw(), len, 0, start);
}
void RecorderNode::getBufferChunk(size_t start, ci::audio::Buffer& other)
{
getBufferChunk(start, mWindowSize, other);
}
bool RecorderNode::popBufferWindow(ci::audio::Buffer& other)
{
if (!isRecording()) return false;
if (mLastQueried + mWindowSize <= getWritePosition())
{
getBufferChunk(mLastQueried, other);
mLastQueried += mHopSize;
return true;
}
// This is the critical situation that can happen at the end of samples
// where there's not enough number of samples for the last buffer.
else if (getNumFrames() - mLastQueried < mWindowSize)
{
getBufferChunk(mLastQueried, getNumFrames() - mLastQueried, other);
mLastQueried = getNumFrames();
return true;
}
else
{
return false;
}
}
bool RecorderNode::popBufferWindow(size_t& query_pos)
{
if (!isRecording()) return false;
if (mLastQueried + mWindowSize <= getWritePosition())
{
query_pos = mLastQueried;
mLastQueried += mHopSize;
return true;
}
// This is the critical situation that can happen at the end of samples
// where there's not enough number of samples for the last buffer.
else if (getNumFrames() - mLastQueried < mWindowSize)
{
query_pos = mLastQueried;
mLastQueried = getNumFrames();
return true;
}
else
{
return false;
}
}
bool RecorderNode::popBufferWindow(ci::audio::Buffer& other, size_t query_pos)
{
if (query_pos + mWindowSize <= getWritePosition())
{
getBufferChunk(query_pos, other);
query_pos += mHopSize;
return true;
}
// This is the critical situation that can happen at the end of samples
// where there's not enough number of samples for the last buffer.
else if (getNumFrames() - query_pos < mWindowSize)
{
getBufferChunk(query_pos, getNumFrames() - query_pos, other);
query_pos = getNumFrames();
return true;
}
else
{
return false;
}
}
size_t RecorderNode::getWindowSize() const
{
return mWindowSize;
}
size_t RecorderNode::getHopSize() const
{
return mHopSize;
}
bool RecorderNode::isRecording() const
{
return getWritePosition() != getNumFrames();
}
size_t RecorderNode::getMaxPossiblePops() const
{
return mMaxPopsPossible;
}
size_t RecorderNode::getQueryIndexByQueryPos(size_t pos)
{
return pos / mHopSize;
}
void RecorderNode::reset()
{
mLastQueried = 0;
}
}} //!cieq::node<|endoftext|> |
<commit_before>/*
* Functions deal with the regex banning.
*
* Copyright (c) eQualit.ie 2013 under GNU AGPL v3.0 or later
*
* Vmon: June 2013, Initial version
*/
#include <vector>
#include <sys/time.h>
#include "regex_manager.h"
using namespace std;
/**
reads all the regular expressions from the database.
and compile them
*/
void RegexManager::load_config()
{
try
{
TSDebug(BANJAX_PLUGIN_NAME, "Setting regex re2 options");
RE2::Options opt;
opt.set_log_errors(false);
opt.set_perl_classes(true);
opt.set_posix_syntax(true);
TSDebug(BANJAX_PLUGIN_NAME, "Loading regex manager conf");
for (const auto& node : cfg) {
string cur_rule = node["rule"].as<std::string>();
TSDebug(BANJAX_PLUGIN_NAME, "initiating rule %s", cur_rule.c_str());
unsigned int observation_interval = node["interval"].as<unsigned int>();
unsigned int threshold = node["hits_per_interval"].as<unsigned int>();
rated_banning_regexes.emplace_back(
new RatedRegex(rated_banning_regexes.size(),
cur_rule,
new RE2(node["regex"].as<std::string>(), opt),
observation_interval * 1000,
threshold /(double)(observation_interval* 1000)));
}
total_no_of_rules = rated_banning_regexes.size();
}
catch(YAML::RepresentationException& e)
{
TSDebug(BANJAX_PLUGIN_NAME, "Error loading regex manager conf [%s].", e.what());
throw;
}
TSDebug(BANJAX_PLUGIN_NAME, "Done loading regex manager conf");
}
/**
applies all regex to an ATS record
@param ats_record: the full request record including time url agent etc
@return: 1 match 0 not match < 0 error.
*/
pair<RegexManager::RegexResult,RegexManager::RatedRegex*>
RegexManager::parse_request(string ip, string ats_record) const
{
boost::optional<IpDb::IpState> ip_state;
for(const auto& rule : rated_banning_regexes) {
if (RE2::FullMatch(ats_record, *(rule->re2_regex))) {
TSDebug(BANJAX_PLUGIN_NAME, "requests matched %s", (rule->re2_regex->pattern()).c_str());
//if it is a simple regex i.e. with rate 0 we bans immidiately without
//wasting time and mem
if (rule->rate == 0) {
TSDebug(BANJAX_PLUGIN_NAME, "simple regex, ban immediately");
return make_pair(REGEX_MATCHED, rule.get());
}
//select appropriate rate, dependent on whether GET or POST request
/* we need to check the rate condition here */
//getting current time in msec
timeval cur_time; gettimeofday(&cur_time, NULL);
long cur_time_msec = cur_time.tv_sec * 1000 + cur_time.tv_usec / 1000.0;
/* first we check if we already have retreived the state for this ip */
if (!ip_state || ip_state->size() == 0) {
ip_state = regex_manager_ip_db->get_ip_state(ip);
if (!ip_state) //we failed to read the database we make no judgement
continue;
}
//if we succeeded in retreiving but the size is zero then it meaens we don't have a record of this ip at all
if (ip_state->size() == 0) {
ip_state->resize(total_no_of_rules);
}
//now we check the begining of the hit for this regex (if the vector is just created everything is 0, in case
//this is the first regex this ip hits)
RegexState state = (*ip_state)[rule->id];
//if it is 0, then we don't have a record for
//the current regex
if (state.begin_msec == 0) {
state.begin_msec = cur_time_msec;
}
//now we have a record, update the rate and ban if necessary.
//we move the interval by the differences of the "begin_in_ms - cur_time_msec - interval*1000"
//if it is less than zero we don't do anything just augument the rate
long time_window_movement = cur_time_msec - state.begin_msec - rule->interval;
if (time_window_movement > 0) { //we need to move
state.begin_msec += time_window_movement;
state.rate = state.rate - (state.rate * time_window_movement - 1)/(double) rule->interval;
state.rate = state.rate < 0 ? 1/(double) rule->interval : state.rate; //if time_window_movement > time_window_movementrule->interval, then we just wipe history and start as a new interval
}
else {
//we are still in the same interval so just increase the hit by 1
state.rate += 1/(double) rule->interval;
}
TSDebug(BANJAX_PLUGIN_NAME, "with rate %f /msec", state.rate);
(*ip_state)[rule->id] = state;
if (state.rate >= rule->rate) {
TSDebug(BANJAX_PLUGIN_NAME, "exceeding excessive rate %f /msec", rule->rate);
//clear the record to avoid multiple reporting to swabber
//we are not clearing the state cause it is not for sure that
//swabber ban the ip due to possible failure of acquiring lock
// ip_state.detail.begin_msec = 0;
// ip_state.detail.rate = 0;
// regex_manager_ip_db->set_ip_state(ip, ip_state.state_allocator);
//before calling swabber we need to delete the memory as swabber will
//delete the ip database entery and the memory will be lost.
//However, if swabber fails to acquire a lock this means
//the ip can escape the banning, this however is a miner
//concern compared to the fact that we might ran out of
//memory.
regex_manager_ip_db->set_ip_state(ip, *ip_state);
return make_pair(REGEX_MATCHED, rule.get());
}
}
}
//if we managed to get/make a valid state we are going to store it
if (ip_state && ip_state->size() > 0)
regex_manager_ip_db->set_ip_state(ip, *ip_state);
//no match
return make_pair(REGEX_MISSED, (RatedRegex*)NULL);
}
FilterResponse RegexManager::on_http_request(const TransactionParts& transaction_parts)
{
const string sep(" ");
TransactionParts ats_record_parts = (TransactionParts) transaction_parts;
string ats_record = ats_record_parts[TransactionMuncher::METHOD] + sep;
ats_record+= ats_record_parts[TransactionMuncher::URL] + sep;
ats_record+= ats_record_parts[TransactionMuncher::HOST] + sep;
ats_record+= ats_record_parts[TransactionMuncher::UA];
TSDebug(BANJAX_PLUGIN_NAME, "Examining '%s' for banned matches", ats_record.c_str());
pair<RegexResult,RatedRegex*> result = parse_request(
ats_record_parts[TransactionMuncher::IP],
ats_record
);
if (result.first == REGEX_MATCHED) {
TSDebug(BANJAX_PLUGIN_NAME, "asking swabber to ban client ip: %s", ats_record_parts[TransactionMuncher::IP].c_str());
//here instead we are calling nosmos's banning client
string ats_rec_comma_sep =
ats_record_parts[TransactionMuncher::METHOD] + ", " +
encapsulate_in_quotes(ats_record_parts[TransactionMuncher::URL]) + ", " +
ats_record_parts[TransactionMuncher::HOST] + ", " +
encapsulate_in_quotes(ats_record_parts[TransactionMuncher::UA]);
string banning_reason = "matched regex rule " + result.second->rule_name + ", " + ats_rec_comma_sep;
swabber->ban(ats_record_parts[TransactionMuncher::IP], banning_reason);
return FilterResponse([&](const TransactionParts& a, const FilterResponse& b) { return this->generate_response(a, b); });
} else if (result.first != REGEX_MISSED) {
TSError("Regex failed with error: %d\n", result.first);
}
return FilterResponse(FilterResponse::GO_AHEAD_NO_COMMENT);
}
std::string RegexManager::generate_response(const TransactionParts& transaction_parts, const FilterResponse& response_info)
{
(void)transaction_parts; (void)response_info;
return forbidden_message;
}
<commit_msg>regex_manager.cpp: consistent padding<commit_after>/*
* Functions deal with the regex banning.
*
* Copyright (c) eQualit.ie 2013 under GNU AGPL v3.0 or later
*
* Vmon: June 2013, Initial version
*/
#include <vector>
#include <sys/time.h>
#include "regex_manager.h"
using namespace std;
/**
reads all the regular expressions from the database.
and compile them
*/
void RegexManager::load_config()
{
try
{
TSDebug(BANJAX_PLUGIN_NAME, "Setting regex re2 options");
RE2::Options opt;
opt.set_log_errors(false);
opt.set_perl_classes(true);
opt.set_posix_syntax(true);
TSDebug(BANJAX_PLUGIN_NAME, "Loading regex manager conf");
for (const auto& node : cfg) {
string cur_rule = node["rule"].as<std::string>();
TSDebug(BANJAX_PLUGIN_NAME, "initiating rule %s", cur_rule.c_str());
unsigned int observation_interval = node["interval"].as<unsigned int>();
unsigned int threshold = node["hits_per_interval"].as<unsigned int>();
rated_banning_regexes.emplace_back(
new RatedRegex(rated_banning_regexes.size(),
cur_rule,
new RE2(node["regex"].as<std::string>(), opt),
observation_interval * 1000,
threshold /(double)(observation_interval* 1000)));
}
total_no_of_rules = rated_banning_regexes.size();
}
catch(YAML::RepresentationException& e)
{
TSDebug(BANJAX_PLUGIN_NAME, "Error loading regex manager conf [%s].", e.what());
throw;
}
TSDebug(BANJAX_PLUGIN_NAME, "Done loading regex manager conf");
}
/**
applies all regex to an ATS record
@param ats_record: the full request record including time url agent etc
@return: 1 match 0 not match < 0 error.
*/
pair<RegexManager::RegexResult,RegexManager::RatedRegex*>
RegexManager::parse_request(string ip, string ats_record) const
{
boost::optional<IpDb::IpState> ip_state;
for(const auto& rule : rated_banning_regexes) {
if (RE2::FullMatch(ats_record, *(rule->re2_regex))) {
TSDebug(BANJAX_PLUGIN_NAME, "requests matched %s", (rule->re2_regex->pattern()).c_str());
//if it is a simple regex i.e. with rate 0 we bans immidiately without
//wasting time and mem
if (rule->rate == 0) {
TSDebug(BANJAX_PLUGIN_NAME, "simple regex, ban immediately");
return make_pair(REGEX_MATCHED, rule.get());
}
//select appropriate rate, dependent on whether GET or POST request
/* we need to check the rate condition here */
//getting current time in msec
timeval cur_time; gettimeofday(&cur_time, NULL);
long cur_time_msec = cur_time.tv_sec * 1000 + cur_time.tv_usec / 1000.0;
/* first we check if we already have retreived the state for this ip */
if (!ip_state || ip_state->size() == 0) {
ip_state = regex_manager_ip_db->get_ip_state(ip);
if (!ip_state) //we failed to read the database we make no judgement
continue;
}
//if we succeeded in retreiving but the size is zero then it meaens we don't have a record of this ip at all
if (ip_state->size() == 0) {
ip_state->resize(total_no_of_rules);
}
//now we check the begining of the hit for this regex (if the vector is just created everything is 0, in case
//this is the first regex this ip hits)
RegexState state = (*ip_state)[rule->id];
//if it is 0, then we don't have a record for
//the current regex
if (state.begin_msec == 0) {
state.begin_msec = cur_time_msec;
}
//now we have a record, update the rate and ban if necessary.
//we move the interval by the differences of the "begin_in_ms - cur_time_msec - interval*1000"
//if it is less than zero we don't do anything just augument the rate
long time_window_movement = cur_time_msec - state.begin_msec - rule->interval;
if (time_window_movement > 0) { //we need to move
state.begin_msec += time_window_movement;
state.rate = state.rate - (state.rate * time_window_movement - 1)/(double) rule->interval;
state.rate = state.rate < 0 ? 1/(double) rule->interval : state.rate; //if time_window_movement > time_window_movementrule->interval, then we just wipe history and start as a new interval
}
else {
//we are still in the same interval so just increase the hit by 1
state.rate += 1/(double) rule->interval;
}
TSDebug(BANJAX_PLUGIN_NAME, "with rate %f /msec", state.rate);
(*ip_state)[rule->id] = state;
if (state.rate >= rule->rate) {
TSDebug(BANJAX_PLUGIN_NAME, "exceeding excessive rate %f /msec", rule->rate);
//clear the record to avoid multiple reporting to swabber
//we are not clearing the state cause it is not for sure that
//swabber ban the ip due to possible failure of acquiring lock
// ip_state.detail.begin_msec = 0;
// ip_state.detail.rate = 0;
// regex_manager_ip_db->set_ip_state(ip, ip_state.state_allocator);
//before calling swabber we need to delete the memory as swabber will
//delete the ip database entery and the memory will be lost.
//However, if swabber fails to acquire a lock this means
//the ip can escape the banning, this however is a miner
//concern compared to the fact that we might ran out of
//memory.
regex_manager_ip_db->set_ip_state(ip, *ip_state);
return make_pair(REGEX_MATCHED, rule.get());
}
}
}
//if we managed to get/make a valid state we are going to store it
if (ip_state && ip_state->size() > 0)
regex_manager_ip_db->set_ip_state(ip, *ip_state);
//no match
return make_pair(REGEX_MISSED, (RatedRegex*)NULL);
}
FilterResponse RegexManager::on_http_request(const TransactionParts& transaction_parts)
{
const string sep(" ");
TransactionParts ats_record_parts = (TransactionParts) transaction_parts;
string ats_record = ats_record_parts[TransactionMuncher::METHOD] + sep;
ats_record+= ats_record_parts[TransactionMuncher::URL] + sep;
ats_record+= ats_record_parts[TransactionMuncher::HOST] + sep;
ats_record+= ats_record_parts[TransactionMuncher::UA];
TSDebug(BANJAX_PLUGIN_NAME, "Examining '%s' for banned matches", ats_record.c_str());
pair<RegexResult,RatedRegex*> result = parse_request(
ats_record_parts[TransactionMuncher::IP],
ats_record
);
if (result.first == REGEX_MATCHED) {
TSDebug(BANJAX_PLUGIN_NAME, "asking swabber to ban client ip: %s", ats_record_parts[TransactionMuncher::IP].c_str());
//here instead we are calling nosmos's banning client
string ats_rec_comma_sep =
ats_record_parts[TransactionMuncher::METHOD] + ", " +
encapsulate_in_quotes(ats_record_parts[TransactionMuncher::URL]) + ", " +
ats_record_parts[TransactionMuncher::HOST] + ", " +
encapsulate_in_quotes(ats_record_parts[TransactionMuncher::UA]);
string banning_reason = "matched regex rule " + result.second->rule_name + ", " + ats_rec_comma_sep;
swabber->ban(ats_record_parts[TransactionMuncher::IP], banning_reason);
return FilterResponse([&](const TransactionParts& a, const FilterResponse& b) { return this->generate_response(a, b); });
} else if (result.first != REGEX_MISSED) {
TSError("Regex failed with error: %d\n", result.first);
}
return FilterResponse(FilterResponse::GO_AHEAD_NO_COMMENT);
}
std::string RegexManager::generate_response(const TransactionParts& transaction_parts, const FilterResponse& response_info)
{
(void)transaction_parts; (void)response_info;
return forbidden_message;
}
<|endoftext|> |
<commit_before>#include "nova_renderer/rhi/rhi_types.hpp"
namespace nova::renderer::rhi {
bool ResourceBindingDescription::operator==(const ResourceBindingDescription& other) {
return set == other.set && binding == other.binding && count == other.count && type == other.type;
}
bool ResourceBindingDescription::operator!=(const ResourceBindingDescription& other) { return !(*this == other); }
ResourceBarrier::ResourceBarrier() {}
DescriptorResourceInfo::DescriptorResourceInfo() {}
uint32_t PipelineInterface::get_num_descriptors_of_type(const DescriptorType type) const {
uint32_t num_descriptors = 0;
for(const auto& [name, description] : bindings) {
if(description.type == type) {
num_descriptors++;
}
}
return num_descriptors;
}
ShaderStage operator|=(const ShaderStage lhs, const ShaderStage rhs) {
return static_cast<ShaderStage>(static_cast<uint32_t>(lhs) | static_cast<uint32_t>(rhs));
}
bool is_depth_format(const PixelFormat format) {
switch(format) {
case PixelFormat::Rgba8:
[[fallthrough]];
case PixelFormat::Rgba16F:
[[fallthrough]];
case PixelFormat::Rgba32F:
return false;
case PixelFormat::Depth32:
[[fallthrough]];
case PixelFormat::Depth24Stencil8:
return true;
default:
return false;
}
}
uint32_t get_byte_size(const VertexFieldFormat format) {
switch(format) {
case VertexFieldFormat::Uint:
return 4;
case VertexFieldFormat::Float2:
return 8;
case VertexFieldFormat::Float3:
return 12;
case VertexFieldFormat::Float4:
return 16;
default:
return 16;
}
}
} // namespace nova::renderer::rhi
<commit_msg>[rhi] Fix iterating over rx::vector<commit_after>#include "nova_renderer/rhi/rhi_types.hpp"
namespace nova::renderer::rhi {
bool ResourceBindingDescription::operator==(const ResourceBindingDescription& other) {
return set == other.set && binding == other.binding && count == other.count && type == other.type;
}
bool ResourceBindingDescription::operator!=(const ResourceBindingDescription& other) { return !(*this == other); }
ResourceBarrier::ResourceBarrier() {}
DescriptorResourceInfo::DescriptorResourceInfo() {}
uint32_t PipelineInterface::get_num_descriptors_of_type(const DescriptorType type) const {
uint32_t num_descriptors = 0;
bindings.each_value([&](const ResourceBindingDescription& description) {
if(description.type == type) {
num_descriptors++;
}
});
return num_descriptors;
}
ShaderStage operator|=(const ShaderStage lhs, const ShaderStage rhs) {
return static_cast<ShaderStage>(static_cast<uint32_t>(lhs) | static_cast<uint32_t>(rhs));
}
bool is_depth_format(const PixelFormat format) {
switch(format) {
case PixelFormat::Rgba8:
[[fallthrough]];
case PixelFormat::Rgba16F:
[[fallthrough]];
case PixelFormat::Rgba32F:
return false;
case PixelFormat::Depth32:
[[fallthrough]];
case PixelFormat::Depth24Stencil8:
return true;
default:
return false;
}
}
uint32_t get_byte_size(const VertexFieldFormat format) {
switch(format) {
case VertexFieldFormat::Uint:
return 4;
case VertexFieldFormat::Float2:
return 8;
case VertexFieldFormat::Float3:
return 12;
case VertexFieldFormat::Float4:
return 16;
default:
return 16;
}
}
} // namespace nova::renderer::rhi
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////
//
// Pixie
//
// Copyright 1999 - 2003, Okan Arikan
//
// Contact: [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
// File : pointCloud.cpp
// Classes : CPointCloud
// Description : Implementation - George
//
////////////////////////////////////////////////////////////////////////
#include <math.h>
#include "pointCloud.h"
#include "object.h"
#include "raytracer.h"
#include "memory.h"
#include "random.h"
#include "error.h"
///////////////////////////////////////////////////////////////////////
// globals
///////////////////////////////////////////////////////////////////////
int CPointCloud::drawDiscs = TRUE;
int CPointCloud::drawChannel = 0;
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : CPointCloud
// Description : Ctor
// Return Value :
// Comments : for a write-mode map, ch and nc must be provided
CPointCloud::CPointCloud(const char *n,const float *from,const float *to,const float *toNDC,const char *channelDefs,int write) : CMap<CPointCloudPoint>(), CTexture3d(n,from,to,toNDC) {
// Create our data areas
flush = write;
maxdP = 0;
osCreateMutex(mutex);
// Assign the channels
defineChannels(channelDefs);
// Make sure we have a root
// (but only if we're looking up, otherwise we'd add duff data)
if (!write) balance();
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : CPointCloud
// Description : Ctor
// Return Value :
// Comments : for a write-mode map via ptcapi, ch and nc must be provided
CPointCloud::CPointCloud(const char *n,const float *from,const float *to,const float *toNDC,int numChannels,char **channelNames,char **channelTypes,int write) : CMap<CPointCloudPoint>(), CTexture3d(n,from,to,toNDC) {
// Create our data areas
flush = write;
maxdP = 0;
osCreateMutex(mutex);
// Assign the channels
defineChannels(numChannels,channelNames,channelTypes);
// Make sure we have a root
// (but only if we're looking up, otherwise we'd add duff data)
if (!write) balance();
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : CPointCloud
// Description : Ctor
// Return Value :
// Comments : for a write-mode map, ch and nc must be provided
CPointCloud::CPointCloud(const char *n,const float *from,const float *to,FILE *in) : CMap<CPointCloudPoint>(), CTexture3d(n,from,to) {
// Create our data areas
flush = FALSE;
maxdP = 0;
osCreateMutex(mutex);
// Try to read the point cloud
// Read the header
readChannels(in);
// Read the points
CMap<CPointCloudPoint>::read(in);
// Reserve the actual space
data.reserve(numItems*dataSize);
// Read the data
fread(data.array,sizeof(float),numItems*dataSize,in);
data.numItems = numItems*dataSize;
// Read the maximum radius
fread(&maxdP,sizeof(float),1,in);
// Close the file
fclose(in);
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : ~CPointCloud
// Description : Dtor
// Return Value :
// Comments :
CPointCloud::~CPointCloud() {
osDeleteMutex(mutex);
if (flush) write();
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : reset
// Description : Reset the photonmap
// Return Value :
// Comments :
void CPointCloud::reset() {
osLock(mutex);
CMap<CPointCloudPoint>::reset();
osUnlock(mutex);
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : write
// Description : Write the photon map into a file
// Return Value :
// Comments :
void CPointCloud::write() {
// Flush the photonmap
FILE *out = ropen(name,"wb",filePointCloud);
if (out != NULL) {
// Balance the map
balance();
// Write out the header and channels
writeChannels(out);
// Write the map
CMap<CPointCloudPoint>::write(out);
// Write the data
fwrite(data.array,sizeof(float),numItems*dataSize,out);
// Read the maximum radius
fwrite(&maxdP,sizeof(float),1,out);
// Close the file
fclose(out);
} else {
error(CODE_BADFILE,"Unable to open %s for writing\n",name);
}
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : lookup
// Description : Locate the nearest points
// Return Value :
// Comments : Nl must be normalized
// Il must be normalized
void CPointCloud::lookup(float *Cl,const float *Pl,const float *Nl,float radius) {
const int maxFound = 16;
const CPointCloudPoint **indices = (const CPointCloudPoint **) alloca((maxFound+1)*sizeof(CPointCloudPoint *));
float *distances = (float *) alloca((maxFound+1)*sizeof(float));
CPointLookup l;
int i,j;
const float scale = 2.5f; // By controlling this, we
distances[0] = maxdP*maxdP*scale*scale;
l.maxFound = maxFound;
l.numFound = 0;
l.ignoreNormal = dotvv(Nl,Nl) == 0;
// Perform lookup in the world coordinate system
mulmp(l.P,to,Pl);
mulmn(l.N,from,Nl);
mulvf(l.N,-1); // Photonmaps have N reversed, we must reverse
// N when looking up it it
normalizevf(l.N);
l.gotHeap = FALSE;
l.indices = indices;
l.distances = distances;
// No need to lock the mutex here, CMap::lookup is thread safe
lookup(&l,1,scale);
for (i=0;i<dataSize;i++) Cl[i] = 0.0f; //GSHTODO: channel fill values
if (l.numFound < 2) return;
int numFound = l.numFound;
float totalWeight = 0;
for (i=1;i<=numFound;i++) {
const CPointCloudPoint *p = indices[i];
assert(distances[i] <= distances[0]);
const float t = sqrtf(distances[i]) / (p->dP*scale);
const float weight = (1-t)*(-dotvv(l.N,p->N));
float *dest = Cl;
const float *src = data.array + p->entryNumber;
for (j=0;j<dataSize;j++) {
*dest++ += (*src++)*weight;
}
totalWeight += weight;
}
if (totalWeight > 0) {
// Divide the contribution
const float weight = 1.0f/totalWeight;
for (i=0;i<dataSize;i++) Cl[i] *= weight;
}
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : balance
// Description : Balance the map
// Return Value :
// Comments :
void CPointCloud::balance() {
// If we have no points in the map, add a dummy one to avoid an if statement during the lookup
if (numItems == 0) {
vector P = {0,0,0};
vector N = {0,0,0};
float *data = (float*) alloca(dataSize*sizeof(float));
for (int i=0;i<dataSize;i++) data[i] = 0;
// Store the fake data
store(data,P,N,0);
}
// Balance the data
CMap<CPointCloudPoint>::balance();
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : store
// Description : Store a photon
// Return Value :
// Comments :
void CPointCloud::store(const float *C,const float *cP,const float *cN,float dP) {
vector P,N;
CPointCloudPoint *point;
// Store in the world coordinate system
mulmp(P,to,cP);
mulmn(N,from,cN);
dP *= dPscale;
osLock(mutex); // FIXME: use rwlock to allow multiple readers
point = CMap<CPointCloudPoint>::store(P,N);
point->entryNumber = data.numItems;
point->dP = dP;
for (int i=0;i<dataSize;i++) data.push(C[i]);
maxdP = max(maxdP,dP);
osUnlock(mutex);
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : getPoint
// Description : Retrieve an indexed point
// Return Value :
// Comments :
void CPointCloud::getPoint(int i,float *C,float *P,float *N,float *dP) {
const CPointCloudPoint *p = items + i;
const float *src = data.array + p->entryNumber;
float *dest = C;
for (int j=0;j<dataSize;j++) {
*dest++ = *src++;
}
movvv(P,p->P);
movvv(N,p->N);
dP[0] = p->dP;
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : draw
// Description : Gui interface
// Return Value :
// Comments :
void CPointCloud::draw() {
float P[chunkSize*3];
float C[chunkSize*3];
float N[chunkSize*3];
float dP[chunkSize];
int i,j;
int sampleStart = channels[drawChannel].sampleStart;
int numSamples = channels[drawChannel].numSamples;
float *cP = P;
float *cC = C;
float *cN = N;
float *cdP = dP;
CPointCloudPoint *cT = items+1;
// Collect and dispatch the photons
for (i=numItems,j=chunkSize;i>0;i--,cT++,cP+=3,cdP++,cN+=3,cC+=3,j--) {
if (j == 0) {
if (drawDiscs) drawDisks(chunkSize,P,dP,N,C);
else drawPoints(chunkSize,P,C);
cP = P;
cC = C;
cN = N;
cdP = dP;
j = chunkSize;
}
movvv(cP,cT->P);
movvv(cN,cT->N);
*cdP = cT->dP; // was /dPscale; but should already be in world
float *DDs = data.array + cT->entryNumber + sampleStart;
if (numSamples == 1) {
initv(cC,DDs[0]);
} else if (numSamples == 2) {
initv(cC,DDs[0],DDs[1],0);
} else {
movvv(cC,DDs);
}
}
if (j != chunkSize) {
if (drawDiscs) drawDisks(chunkSize-j,P,dP,N,C);
else drawPoints(chunkSize-j,P,C);
}
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : keyDown
// Description : handle keypresses
// Return Value : -
// Comments :
int CPointCloud::keyDown(int key) {
if ((key == 'd') || (key == 'D')) {
drawDiscs = TRUE;
return TRUE;
} else if ((key == 'p') || (key == 'P')) {
drawDiscs = FALSE;
return TRUE;
} else if ((key == 'q') || (key == 'Q')) {
drawChannel--;
if (drawChannel < 0) drawChannel = 0;
printf("channel : %s\n",channels[drawChannel].name);
return TRUE;
} else if ((key == 'w') || (key == 'W')) {
drawChannel++;
if (drawChannel >= numChannels) drawChannel = numChannels-1;
printf("channel : %s\n",channels[drawChannel].name);
return TRUE;
}
return FALSE;
}
//////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : draw
// Description : Gui interface
// Return Value :
// Comments :
void CPointCloud::bound(float *bmin,float *bmax) {
movvv(bmin,this->bmin);
movvv(bmax,this->bmax);
}
<commit_msg>fixes for null normal (volume) lookup<commit_after>//////////////////////////////////////////////////////////////////////
//
// Pixie
//
// Copyright 1999 - 2003, Okan Arikan
//
// Contact: [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
// File : pointCloud.cpp
// Classes : CPointCloud
// Description : Implementation - George
//
////////////////////////////////////////////////////////////////////////
#include <math.h>
#include "pointCloud.h"
#include "object.h"
#include "raytracer.h"
#include "memory.h"
#include "random.h"
#include "error.h"
///////////////////////////////////////////////////////////////////////
// globals
///////////////////////////////////////////////////////////////////////
int CPointCloud::drawDiscs = TRUE;
int CPointCloud::drawChannel = 0;
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : CPointCloud
// Description : Ctor
// Return Value :
// Comments : for a write-mode map, ch and nc must be provided
CPointCloud::CPointCloud(const char *n,const float *from,const float *to,const float *toNDC,const char *channelDefs,int write) : CMap<CPointCloudPoint>(), CTexture3d(n,from,to,toNDC) {
// Create our data areas
flush = write;
maxdP = 0;
osCreateMutex(mutex);
// Assign the channels
defineChannels(channelDefs);
// Make sure we have a root
// (but only if we're looking up, otherwise we'd add duff data)
if (!write) balance();
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : CPointCloud
// Description : Ctor
// Return Value :
// Comments : for a write-mode map via ptcapi, ch and nc must be provided
CPointCloud::CPointCloud(const char *n,const float *from,const float *to,const float *toNDC,int numChannels,char **channelNames,char **channelTypes,int write) : CMap<CPointCloudPoint>(), CTexture3d(n,from,to,toNDC) {
// Create our data areas
flush = write;
maxdP = 0;
osCreateMutex(mutex);
// Assign the channels
defineChannels(numChannels,channelNames,channelTypes);
// Make sure we have a root
// (but only if we're looking up, otherwise we'd add duff data)
if (!write) balance();
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : CPointCloud
// Description : Ctor
// Return Value :
// Comments : for a write-mode map, ch and nc must be provided
CPointCloud::CPointCloud(const char *n,const float *from,const float *to,FILE *in) : CMap<CPointCloudPoint>(), CTexture3d(n,from,to) {
// Create our data areas
flush = FALSE;
maxdP = 0;
osCreateMutex(mutex);
// Try to read the point cloud
// Read the header
readChannels(in);
// Read the points
CMap<CPointCloudPoint>::read(in);
// Reserve the actual space
data.reserve(numItems*dataSize);
// Read the data
fread(data.array,sizeof(float),numItems*dataSize,in);
data.numItems = numItems*dataSize;
// Read the maximum radius
fread(&maxdP,sizeof(float),1,in);
// Close the file
fclose(in);
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : ~CPointCloud
// Description : Dtor
// Return Value :
// Comments :
CPointCloud::~CPointCloud() {
osDeleteMutex(mutex);
if (flush) write();
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : reset
// Description : Reset the photonmap
// Return Value :
// Comments :
void CPointCloud::reset() {
osLock(mutex);
CMap<CPointCloudPoint>::reset();
osUnlock(mutex);
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : write
// Description : Write the photon map into a file
// Return Value :
// Comments :
void CPointCloud::write() {
// Flush the photonmap
FILE *out = ropen(name,"wb",filePointCloud);
if (out != NULL) {
// Balance the map
balance();
// Write out the header and channels
writeChannels(out);
// Write the map
CMap<CPointCloudPoint>::write(out);
// Write the data
fwrite(data.array,sizeof(float),numItems*dataSize,out);
// Read the maximum radius
fwrite(&maxdP,sizeof(float),1,out);
// Close the file
fclose(out);
} else {
error(CODE_BADFILE,"Unable to open %s for writing\n",name);
}
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : lookup
// Description : Locate the nearest points
// Return Value :
// Comments : Nl must be normalized
// Il must be normalized
void CPointCloud::lookup(float *Cl,const float *Pl,const float *Nl,float radius) {
const int maxFound = 16;
const CPointCloudPoint **indices = (const CPointCloudPoint **) alloca((maxFound+1)*sizeof(CPointCloudPoint *));
float *distances = (float *) alloca((maxFound+1)*sizeof(float));
CPointLookup l;
int i,j;
const float scale = 2.5f; // By controlling this, we
distances[0] = maxdP*maxdP*scale*scale;
l.maxFound = maxFound;
l.numFound = 0;
l.ignoreNormal = dotvv(Nl,Nl) < C_EPSILON;
// Perform lookup in the world coordinate system
mulmp(l.P,to,Pl);
mulmn(l.N,from,Nl);
mulvf(l.N,-1); // Photonmaps have N reversed, we must reverse
// N when looking up it it
if (dotvv(Nl,Nl) > C_EPSILON) normalizevf(l.N);
l.gotHeap = FALSE;
l.indices = indices;
l.distances = distances;
// No need to lock the mutex here, CMap::lookup is thread safe
lookup(&l,1,scale);
for (i=0;i<dataSize;i++) Cl[i] = 0.0f; //GSHTODO: channel fill values
if (l.numFound < 2) return;
int numFound = l.numFound;
float totalWeight = 0;
for (i=1;i<=numFound;i++) {
const CPointCloudPoint *p = indices[i];
assert(distances[i] <= distances[0]);
const float t = sqrtf(distances[i]) / (p->dP*scale);
const float weight = l.ignoreNormal ? (1-t) : (1-t)*(-dotvv(l.N,p->N));
float *dest = Cl;
const float *src = data.array + p->entryNumber;
for (j=0;j<dataSize;j++) {
*dest++ += (*src++)*weight;
}
totalWeight += weight;
}
if (totalWeight > 0) {
// Divide the contribution
const float weight = 1.0f/totalWeight;
for (i=0;i<dataSize;i++) Cl[i] *= weight;
}
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : balance
// Description : Balance the map
// Return Value :
// Comments :
void CPointCloud::balance() {
// If we have no points in the map, add a dummy one to avoid an if statement during the lookup
if (numItems == 0) {
vector P = {0,0,0};
vector N = {0,0,0};
float *data = (float*) alloca(dataSize*sizeof(float));
for (int i=0;i<dataSize;i++) data[i] = 0;
// Store the fake data
store(data,P,N,0);
}
// Balance the data
CMap<CPointCloudPoint>::balance();
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : store
// Description : Store a photon
// Return Value :
// Comments :
void CPointCloud::store(const float *C,const float *cP,const float *cN,float dP) {
vector P,N;
CPointCloudPoint *point;
// Store in the world coordinate system
mulmp(P,to,cP);
mulmn(N,from,cN);
dP *= dPscale;
osLock(mutex); // FIXME: use rwlock to allow multiple readers
point = CMap<CPointCloudPoint>::store(P,N);
point->entryNumber = data.numItems;
point->dP = dP;
for (int i=0;i<dataSize;i++) data.push(C[i]);
maxdP = max(maxdP,dP);
osUnlock(mutex);
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : getPoint
// Description : Retrieve an indexed point
// Return Value :
// Comments :
void CPointCloud::getPoint(int i,float *C,float *P,float *N,float *dP) {
const CPointCloudPoint *p = items + i;
const float *src = data.array + p->entryNumber;
float *dest = C;
for (int j=0;j<dataSize;j++) {
*dest++ = *src++;
}
movvv(P,p->P);
movvv(N,p->N);
dP[0] = p->dP;
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : draw
// Description : Gui interface
// Return Value :
// Comments :
void CPointCloud::draw() {
float P[chunkSize*3];
float C[chunkSize*3];
float N[chunkSize*3];
float dP[chunkSize];
int i,j;
int sampleStart = channels[drawChannel].sampleStart;
int numSamples = channels[drawChannel].numSamples;
float *cP = P;
float *cC = C;
float *cN = N;
float *cdP = dP;
CPointCloudPoint *cT = items+1;
// Collect and dispatch the photons
for (i=numItems,j=chunkSize;i>0;i--,cT++,cP+=3,cdP++,cN+=3,cC+=3,j--) {
if (j == 0) {
if (drawDiscs) drawDisks(chunkSize,P,dP,N,C);
else drawPoints(chunkSize,P,C);
cP = P;
cC = C;
cN = N;
cdP = dP;
j = chunkSize;
}
movvv(cP,cT->P);
movvv(cN,cT->N);
*cdP = cT->dP; // was /dPscale; but should already be in world
float *DDs = data.array + cT->entryNumber + sampleStart;
if (numSamples == 1) {
initv(cC,DDs[0]);
} else if (numSamples == 2) {
initv(cC,DDs[0],DDs[1],0);
} else {
movvv(cC,DDs);
}
}
if (j != chunkSize) {
if (drawDiscs) drawDisks(chunkSize-j,P,dP,N,C);
else drawPoints(chunkSize-j,P,C);
}
}
///////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : keyDown
// Description : handle keypresses
// Return Value : -
// Comments :
int CPointCloud::keyDown(int key) {
if ((key == 'd') || (key == 'D')) {
drawDiscs = TRUE;
return TRUE;
} else if ((key == 'p') || (key == 'P')) {
drawDiscs = FALSE;
return TRUE;
} else if ((key == 'q') || (key == 'Q')) {
drawChannel--;
if (drawChannel < 0) drawChannel = 0;
printf("channel : %s\n",channels[drawChannel].name);
return TRUE;
} else if ((key == 'w') || (key == 'W')) {
drawChannel++;
if (drawChannel >= numChannels) drawChannel = numChannels-1;
printf("channel : %s\n",channels[drawChannel].name);
return TRUE;
}
return FALSE;
}
//////////////////////////////////////////////////////////////////////
// Class : CPointCloud
// Method : draw
// Description : Gui interface
// Return Value :
// Comments :
void CPointCloud::bound(float *bmin,float *bmax) {
movvv(bmin,this->bmin);
movvv(bmax,this->bmax);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "main.h"
#include "kernel.h"
#include "checkpoints.h"
using namespace json_spirit;
using namespace std;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (pindexBest == NULL)
return 1.0;
else
blockindex = GetLastBlockIndex(pindexBest, false);
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
double GetPoWMHashPS()
{
if (pindexBest->nHeight >= LAST_POW_TIME)
return 0;
int nPoWInterval = 72;
int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;
CBlockIndex* pindex = pindexGenesisBlock;
CBlockIndex* pindexPrevWork = pindexGenesisBlock;
while (pindex)
{
if (pindex->IsProofOfWork())
{
int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
pindexPrevWork = pindex;
}
pindex = pindex->pnext;
}
return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}
double GetPoSKernelPS()
{
int nPoSInterval = 72;
double dStakeKernelsTriedAvg = 0;
int nStakesHandled = 0, nStakesTime = 0;
CBlockIndex* pindex = pindexBest;;
CBlockIndex* pindexPrevStake = NULL;
while (pindex && nStakesHandled < nPoSInterval)
{
if (pindex->IsProofOfStake())
{
if (pindexPrevStake)
{
dStakeKernelsTriedAvg += GetDifficulty(pindexPrevStake) * 4294967296.0;
nStakesTime += pindexPrevStake->nTime - pindex->nTime;
nStakesHandled++;
}
pindexPrevStake = pindex;
}
pindex = pindex->pprev;
}
double result = 0;
if (nStakesTime)
result = dStakeKernelsTriedAvg / nStakesTime;
if (IsProtocolV2(nBestHeight))
result *= STAKE_TIMESTAMP_MASK + 1;
return result;
}
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
Object result;
result.push_back(Pair("hash", block.GetHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (blockindex->IsInMainChain())
confirmations = nBestHeight - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
result.push_back(Pair("time", (int64_t)block.GetBlockTime()));
result.push_back(Pair("nonce", (uint64_t)block.nNonce));
result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
if (blockindex->pnext)
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
result.push_back(Pair("proofhash", blockindex->hashProof.GetHex()));
result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
result.push_back(Pair("modifier", strprintf("%016x", blockindex->nStakeModifier)));
result.push_back(Pair("modifierv2", blockindex->bnStakeModifierV2.GetHex()));
Array txinfo;
BOOST_FOREACH (const CTransaction& tx, block.vtx)
{
if (fPrintTransactionDetail)
{
Object entry;
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
TxToJSON(tx, 0, entry);
txinfo.push_back(entry);
}
else
txinfo.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txinfo));
if (block.IsProofOfStake())
result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));
return result;
}
Value getbestblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbestblockhash\n"
"Returns the hash of the best block in the longest block chain.");
return hashBestChain.GetHex();
}
Value getblockcount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
return nBestHeight;
}
Value getdifficulty(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"Returns the difficulty as a multiple of the minimum difficulty.");
Object obj;
obj.push_back(Pair("proof-of-work", GetDifficulty()));
obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
return obj;
}
Value getrawmempool(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getrawmempool\n"
"Returns all transaction ids in memory pool.");
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
Array a;
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
Value getblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash <index>\n"
"Returns hash of block in best-block-chain at <index>.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
return pblockindex->phashBlock->GetHex();
}
Value getblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock \"blockhash\" ( verbosity ) \n"
"\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
"If verbosity is 1, returns an Object with information about block <hash>.\n"
"If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n"
"\nArguments:\n"
"1. \"blockhash\" (string, required) The block hash\n"
"2. verbosity (numeric, optional, default=1) 0 for hex encoded data, 1 for a json object, and 2 for json object with transaction data\n"
"\nResult (for verbosity = 0):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nResult (for verbosity = 1):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"strippedsize\" : n, (numeric) The block size excluding witness data\n"
" \"weight\" : n (numeric) The block weight as defined in BIP 141\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"tx\" : [ (array of string) The transaction ids\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
" ],\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
"}\n"
"\nResult (for verbosity = 2):\n"
"{\n"
" ..., Same output as verbosity = 1.\n"
" \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
" ,...\n"
" ],\n"
" ,... Same output as verbosity = 1.\n"
"}\n"
"\nExamples:\n"
);
LOCK(cs_main);
std::string strHash = params[0].get_str();
uint256 hash(strHash);
int verbosity = 1;
std::string check_verbosity = params[1].get_str();
if (params.size() > 1) {
//if(params[1].isNum())
if(params[1].get_int())
verbosity = params[1].get_int();
else
verbosity = params[1].get_bool() ? 1 : 0;
}
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (verbosity <= 0)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, pblockindex, verbosity >= 2);
}
Value getblockbynumber(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblockbynumber <number> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-number.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
uint256 hash = *pblockindex->phashBlock;
pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
// ppcoin: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getcheckpoint\n"
"Show info of synchronized checkpoint.\n");
Object result;
const CBlockIndex* pindexCheckpoint = Checkpoints::AutoSelectSyncCheckpoint();
result.push_back(Pair("synccheckpoint", pindexCheckpoint->GetBlockHash().ToString().c_str()));
result.push_back(Pair("height", pindexCheckpoint->nHeight));
result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));
result.push_back(Pair("policy", "rolling"));
return result;
}
<commit_msg>Updated getblock to the latest bitcoin build<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "main.h"
#include "kernel.h"
#include "checkpoints.h"
using namespace json_spirit;
using namespace std;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (pindexBest == NULL)
return 1.0;
else
blockindex = GetLastBlockIndex(pindexBest, false);
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
double GetPoWMHashPS()
{
if (pindexBest->nHeight >= LAST_POW_TIME)
return 0;
int nPoWInterval = 72;
int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30;
CBlockIndex* pindex = pindexGenesisBlock;
CBlockIndex* pindexPrevWork = pindexGenesisBlock;
while (pindex)
{
if (pindex->IsProofOfWork())
{
int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime();
nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1);
nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin);
pindexPrevWork = pindex;
}
pindex = pindex->pnext;
}
return GetDifficulty() * 4294.967296 / nTargetSpacingWork;
}
double GetPoSKernelPS()
{
int nPoSInterval = 72;
double dStakeKernelsTriedAvg = 0;
int nStakesHandled = 0, nStakesTime = 0;
CBlockIndex* pindex = pindexBest;;
CBlockIndex* pindexPrevStake = NULL;
while (pindex && nStakesHandled < nPoSInterval)
{
if (pindex->IsProofOfStake())
{
if (pindexPrevStake)
{
dStakeKernelsTriedAvg += GetDifficulty(pindexPrevStake) * 4294967296.0;
nStakesTime += pindexPrevStake->nTime - pindex->nTime;
nStakesHandled++;
}
pindexPrevStake = pindex;
}
pindex = pindex->pprev;
}
double result = 0;
if (nStakesTime)
result = dStakeKernelsTriedAvg / nStakesTime;
if (IsProtocolV2(nBestHeight))
result *= STAKE_TIMESTAMP_MASK + 1;
return result;
}
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
{
Object result;
result.push_back(Pair("hash", block.GetHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (blockindex->IsInMainChain())
confirmations = nBestHeight - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
result.push_back(Pair("time", (int64_t)block.GetBlockTime()));
result.push_back(Pair("nonce", (uint64_t)block.nNonce));
result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0')));
result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0')));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
if (blockindex->pnext)
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
result.push_back(Pair("proofhash", blockindex->hashProof.GetHex()));
result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
result.push_back(Pair("modifier", strprintf("%016x", blockindex->nStakeModifier)));
result.push_back(Pair("modifierv2", blockindex->bnStakeModifierV2.GetHex()));
Array txinfo;
BOOST_FOREACH (const CTransaction& tx, block.vtx)
{
if (fPrintTransactionDetail)
{
Object entry;
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
TxToJSON(tx, 0, entry);
txinfo.push_back(entry);
}
else
txinfo.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txinfo));
if (block.IsProofOfStake())
result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));
return result;
}
Value getbestblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbestblockhash\n"
"Returns the hash of the best block in the longest block chain.");
return hashBestChain.GetHex();
}
Value getblockcount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"Returns the number of blocks in the longest block chain.");
return nBestHeight;
}
Value getdifficulty(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"Returns the difficulty as a multiple of the minimum difficulty.");
Object obj;
obj.push_back(Pair("proof-of-work", GetDifficulty()));
obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
return obj;
}
Value getrawmempool(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getrawmempool\n"
"Returns all transaction ids in memory pool.");
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
Array a;
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
Value getblockhash(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash <index>\n"
"Returns hash of block in best-block-chain at <index>.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
return pblockindex->phashBlock->GetHex();
}
Value getblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock \"blockhash\" ( verbosity ) \n"
"\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
"If verbosity is 1, returns an Object with information about block <hash>.\n"
"If verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n"
"\nArguments:\n"
"1. \"blockhash\" (string, required) The block hash\n"
"2. verbosity (numeric, optional, default=1) 0 for hex encoded data, 1 for a json object, and 2 for json object with transaction data\n"
"\nResult (for verbosity = 0):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nResult (for verbosity = 1):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"strippedsize\" : n, (numeric) The block size excluding witness data\n"
" \"weight\" : n (numeric) The block weight as defined in BIP 141\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"tx\" : [ (array of string) The transaction ids\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
" ],\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
"}\n"
"\nResult (for verbosity = 2):\n"
"{\n"
" ..., Same output as verbosity = 1.\n"
" \"tx\" : [ (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 \"tx\" result.\n"
" ,...\n"
" ],\n"
" ,... Same output as verbosity = 1.\n"
"}\n"
"\nExamples:\n"
);
LOCK(cs_main);
//std::string strHash = params[0].get_str();
//uint256 hash(strHash);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
int verbosity = 1;
if (params.size() > 1) {
verbosity = params[1].get_bool() ? 1 : 0;
}
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
if(!block.ReadFromDisk(pblockindex, true)){
// Block not found on disk. This could be because we have the block
// header in our index but don't have the block (for example if a
// non-whitelisted node sends us an unrequested long chain of valid
// blocks, we add the headers to our index, but don't accept the
// block).
throw JSONRPCError(RPC_MISC_ERROR, "Block not found on disk");
}
block.ReadFromDisk(pblockindex, true);
if (verbosity <= 0)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
//strHex.insert(0, "testar ");
return strHex;
}
//return blockToJSON(block, pblockindex, verbosity >= 2);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
Value getblock_old(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock <hash> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-hash.");
std::string strHash = params[0].get_str();
uint256 hash(strHash);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
Value getblockbynumber(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblockbynumber <number> [txinfo]\n"
"txinfo optional to print more detailed tx info\n"
"Returns details of a block with given block-number.");
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > nBestHeight)
throw runtime_error("Block number out of range.");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
uint256 hash = *pblockindex->phashBlock;
pblockindex = mapBlockIndex[hash];
block.ReadFromDisk(pblockindex, true);
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
}
// ppcoin: get information of sync-checkpoint
Value getcheckpoint(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getcheckpoint\n"
"Show info of synchronized checkpoint.\n");
Object result;
const CBlockIndex* pindexCheckpoint = Checkpoints::AutoSelectSyncCheckpoint();
result.push_back(Pair("synccheckpoint", pindexCheckpoint->GetBlockHash().ToString().c_str()));
result.push_back(Pair("height", pindexCheckpoint->nHeight));
result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));
result.push_back(Pair("policy", "rolling"));
return result;
}
<|endoftext|> |
<commit_before>/***********************************************************************************
Copyright (C) 2013 by Sajia Akhter, Edwards Lab, San Diego State University
This file is part of Qudaich.
Qudaich 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
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, see <http://www.gnu.org/licenses/>.
**********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h> /* required for MAX_PATH */
void version(char *);
char *execpath(char *);
void inputError(const char *);
void help(char *);
int TOTAL_DB_SEQ = 0, TOTAL_QRY_SEQ = 0, LINE_LEN, SIZE_SEQ = 0, SIZE_SEQ_NAME = 0;
char mypath[PATH_MAX];
void inputError(const char *msg) {
fprintf(stderr, "%s", msg);
exit(-1);
}
/* return the path of the current executable so we can append bin to it
* arg: exec is argv[0]
* returns: a string representing the current path
*
* Uses realpath in stdlib.h and MAX_PATH in limits.h
*/
char *execpath(char *exec) {
char *mp = realpath(exec, mypath); /* this is the complete path */
char *ptr = strrchr(mp, '/'); /* this is from the last / forwards - should be path separator! */
int posn = strlen(mp) - strlen(ptr); /* the position of the last / */
mypath[posn] = '\0';
return mypath;
}
/* print out the version number and then the help menu. Note that we require argv[0] so we can pass it forward */
void version(char *p) {
FILE * fp;
char v[256];
fp = fopen("VERSION", "r");
if (fp != NULL) {
char *check_fgets = fgets(v, 256, fp);
}
printf("\n%s %s\n", p, v);
help(p);
}
/* help() prints the help menu and exits. Please provide argv[0] as an option so we can include that in the help menu */
void help(char * p) {
printf("\n%s -q [query] -d [database] -p [program] or\n%s -query [query file] -db [database file] -prog [program]\n\n", p, p);
printf("-q|-query Name of the query file (Required)\n");
printf("-d|-db Name of database file (Required)\n");
printf("-p|-prog Alignment options (Required): n (nucleotide),\n");
printf(" p (protein),\n");
printf(" trn (translated nucleotide)\n");
printf(" trnx (translated nucleotide vs protein database)\n");
printf("-t|-top Number of alignments per query sequence (default 1)\n");
printf("-f|-freqFile Frequency file Name\n");
printf("-c|-heuristic Heuristic options: 1 (default) or 2 (See the README or paper for more information)\n");
printf("-h|-help Show command line options and exit\n");
printf("-v|-version Print the version and help options and exit\n");
exit(0);
}
int input_size(FILE *f, int flag)
{
int L = 2000, SIZE = 0, t, max = 0, total_seq = 0, temp = 0, maxsize=0 ;
char name[L];
while(fgets(name,L,f)!=NULL)
{
if (name[0] == '>'){
total_seq++;
t = strlen(name);
if(t>max) max = t;
SIZE += temp;
if (temp > maxsize) maxsize = temp;
temp = 0;
continue;
}
else
{
t = strlen(name)-1;
if((name[t]) != '\n')
t++;
temp = temp + t;
}
}
SIZE += temp;
if (temp > maxsize) maxsize = temp;
if (flag == 0){//DB
TOTAL_DB_SEQ = total_seq;
if (SIZE_SEQ<maxsize) SIZE_SEQ = maxsize;
if (SIZE_SEQ_NAME<max) SIZE_SEQ_NAME = max;
}
else//query
{
TOTAL_QRY_SEQ = total_seq;
if (SIZE_SEQ<maxsize) SIZE_SEQ = maxsize;
if (SIZE_SEQ_NAME<max) SIZE_SEQ_NAME = max;
}
return SIZE;
}
int main(int argc, char **argv) {
int i;
char queryFile[1024], refFile[1024], outputfile[1024], program[16];
int top = 1, hypothesis = 1;
FILE *f;
strcpy(outputfile, "freq.txt");
for(i=1;i<argc;i++) {
if(!strcmp(argv[i], "-query") || !strcmp(argv[i], "-q")) {
if(i+1 >= argc) {
inputError("Query File name required\n");
}
strcpy(queryFile, argv[i+1]);
i++;
}
else if(!strcmp(argv[i], "-ref") || !strcmp(argv[i], "-db") || !strcmp(argv[i], "-d")) {
if(i+1 >= argc) {
inputError("Database File name required\n");
}
strcpy(refFile, argv[i+1]);
i++;
}
else if(!strcmp(argv[i], "-prog") || !strcmp(argv[i], "-p")) {
if(i+1 >= argc) {
inputError("Alignment option required\n");
}
strcpy(program, argv[i+1]);
if (strcmp(program,"n")!=0 and strcmp(program,"p")!=0 and strcmp(program,"trn")!=0 and strcmp(program,"trnx")!=0)
inputError("Valid alignment option required\nPlease use -h for details information\n");
i++;
}
else if(!strcmp(argv[i], "-freqFile") || !strcmp(argv[i], "-f")) {
if(i+1 >= argc) {
inputError("Frequency File name required\n");
}
strcpy(outputfile, argv[i+1]);
i++;
}
else if(!strcmp(argv[i], "-hypo") || !strcmp(argv[i], "-heuristic") || !strcmp(argv[i], "-c")) {
if(i+1 >= argc) {
inputError("Argument required\n");
}
sscanf(argv[i+1], "%d", &hypothesis);
if(hypothesis <= 0 || hypothesis >=3) {
inputError("Value of the heuristic must be either 1 (default) or 2\n");
}
i++;
}
else if(!strcmp(argv[i], "-top")) {
if(i+1 >= argc) {
inputError("Argument required\n");
}
sscanf(argv[i+1], "%d", &top);
if(top <= 0) {
inputError("Value of top must be positive\n");
}
i++;
}
else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "-help"))
help(argv[0]);
else if (!strcmp(argv[i], "-version") || !strcmp(argv[i], "-v"))
version(argv[0]);
else {
inputError("Invalid arguments\n");
inputError(argv[i]);
}
}
if(!queryFile[0] || !refFile[0] || !program[0]) {
help(argv[0]);
}
// CHECK whether these are valid files
unsigned int SIZEr = 0, SIZEq = 0, SIZE = 0;
//read file:
f = fopen(refFile,"r");
SIZEr = input_size(f,0);
fclose(f);
f = fopen(queryFile,"r");
SIZEq = input_size(f,1);
fclose(f);
char progBuf[1024],write_buff[1024];
LINE_LEN = 2000;
SIZE_SEQ++;
SIZE_SEQ_NAME++;
sprintf(write_buff,"%d %d %d %d %d", TOTAL_DB_SEQ, TOTAL_QRY_SEQ, LINE_LEN, SIZE_SEQ, SIZE_SEQ_NAME);
char *app_path;
if ((app_path = execpath(argv[0])) == NULL) {
fprintf(stderr, "ERROR: We can not get an application path from %s\n", argv[0]);
exit(-1);
}
if (strcmp(program,"n")==0)
{
SIZE = SIZEr * 2 + SIZEq + 2;
if (SIZE >= 2000000000){
printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u) * 2 + total query bp (%u)]\n",SIZE,SIZEr,SIZEq);
inputError("");
}
if(hypothesis == 1)
{
if(top == 1)
sprintf(progBuf, "%s/bin/search_dna_hypo1 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_dna_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
else
{
if(top == 1)
sprintf(progBuf, "%s/bin/search_dna_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_dna_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
}
else if (strcmp(program,"p")==0)
{
SIZE = SIZEr + SIZEq + 2;
if (SIZE >= 2000000000){
printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u) + total query bp (%u)]\n",SIZE,SIZEr,SIZEq);
inputError("");
}
if(hypothesis == 1)
{
if(top == 1)
sprintf(progBuf, "%s/bin/search_pro_hypo1 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_pro_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
else
{
if(top == 1)
sprintf(progBuf, "%s/bin/search_pro_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_pro_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
}
else if (strcmp(program,"trn")==0)
{
SIZE = SIZEr * 2 + SIZEq + 2;
if (SIZE >= 2000000000) {
printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u) * 2 + total query bp (%u)]\n",SIZE,SIZEr,SIZEq);
inputError("");
}
if(hypothesis == 1)
{
if(top == 1)
sprintf(progBuf, "%s/bin/search_trn_hypo1 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_trn_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
else
{
if(top == 1)
sprintf(progBuf, "%s/bin/search_trn_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_trn_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
}
//////////////////
else if (strcmp(program,"trnx")==0)
{
SIZE = SIZEr + SIZEq*2 + 2;
if (SIZE >= 2000000000) {
printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u) + total query bp (%u) * 2]\n",SIZE,SIZEr,SIZEq);
inputError("");
}
if(hypothesis == 1)
{
sprintf(progBuf, "%s/bin/search_trnx_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
else
{
printf("Current version of Quadich supports only hypothesis I for translated nucleotide vs protein database alignmnet.\n\n");
inputError("");
/*if(top == 1)
sprintf(progBuf, "%s/bin/search_trn_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_trn_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
*/
}
}
else{
inputError("Please specify the correct program option\n");
}
printf("%s\n",progBuf);
int returnval = system(progBuf);
return returnval;
}
<commit_msg>correcting a -t for top<commit_after>/***********************************************************************************
Copyright (C) 2013 by Sajia Akhter, Edwards Lab, San Diego State University
This file is part of Qudaich.
Qudaich 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
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, see <http://www.gnu.org/licenses/>.
**********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h> /* required for MAX_PATH */
void version(char *);
char *execpath(char *);
void inputError(const char *);
void help(char *);
int TOTAL_DB_SEQ = 0, TOTAL_QRY_SEQ = 0, LINE_LEN, SIZE_SEQ = 0, SIZE_SEQ_NAME = 0;
char mypath[PATH_MAX];
void inputError(const char *msg) {
fprintf(stderr, "%s", msg);
exit(-1);
}
/* return the path of the current executable so we can append bin to it
* arg: exec is argv[0]
* returns: a string representing the current path
*
* Uses realpath in stdlib.h and MAX_PATH in limits.h
*/
char *execpath(char *exec) {
char *mp = realpath(exec, mypath); /* this is the complete path */
char *ptr = strrchr(mp, '/'); /* this is from the last / forwards - should be path separator! */
int posn = strlen(mp) - strlen(ptr); /* the position of the last / */
mypath[posn] = '\0';
return mypath;
}
/* print out the version number and then the help menu. Note that we require argv[0] so we can pass it forward */
void version(char *p) {
FILE * fp;
char v[256];
fp = fopen("VERSION", "r");
if (fp != NULL) {
char *check_fgets = fgets(v, 256, fp);
}
printf("\n%s %s\n", p, v);
help(p);
}
/* help() prints the help menu and exits. Please provide argv[0] as an option so we can include that in the help menu */
void help(char * p) {
printf("\n%s -q [query] -d [database] -p [program] or\n%s -query [query file] -db [database file] -prog [program]\n\n", p, p);
printf("-q|-query Name of the query file (Required)\n");
printf("-d|-db Name of database file (Required)\n");
printf("-p|-prog Alignment options (Required): n (nucleotide),\n");
printf(" p (protein),\n");
printf(" trn (translated nucleotide)\n");
printf(" trnx (translated nucleotide vs protein database)\n");
printf("-t|-top Number of alignments per query sequence (default 1)\n");
printf("-f|-freqFile Frequency file Name\n");
printf("-c|-heuristic Heuristic options: 1 (default) or 2 (See the README or paper for more information)\n");
printf("-h|-help Show command line options and exit\n");
printf("-v|-version Print the version and help options and exit\n");
exit(0);
}
int input_size(FILE *f, int flag)
{
int L = 2000, SIZE = 0, t, max = 0, total_seq = 0, temp = 0, maxsize=0 ;
char name[L];
while(fgets(name,L,f)!=NULL)
{
if (name[0] == '>'){
total_seq++;
t = strlen(name);
if(t>max) max = t;
SIZE += temp;
if (temp > maxsize) maxsize = temp;
temp = 0;
continue;
}
else
{
t = strlen(name)-1;
if((name[t]) != '\n')
t++;
temp = temp + t;
}
}
SIZE += temp;
if (temp > maxsize) maxsize = temp;
if (flag == 0){//DB
TOTAL_DB_SEQ = total_seq;
if (SIZE_SEQ<maxsize) SIZE_SEQ = maxsize;
if (SIZE_SEQ_NAME<max) SIZE_SEQ_NAME = max;
}
else//query
{
TOTAL_QRY_SEQ = total_seq;
if (SIZE_SEQ<maxsize) SIZE_SEQ = maxsize;
if (SIZE_SEQ_NAME<max) SIZE_SEQ_NAME = max;
}
return SIZE;
}
int main(int argc, char **argv) {
int i;
char queryFile[1024], refFile[1024], outputfile[1024], program[16];
int top = 1, hypothesis = 1;
FILE *f;
strcpy(outputfile, "freq.txt");
for(i=1;i<argc;i++) {
if(!strcmp(argv[i], "-query") || !strcmp(argv[i], "-q")) {
if(i+1 >= argc) {
inputError("Query File name required\n");
}
strcpy(queryFile, argv[i+1]);
i++;
}
else if(!strcmp(argv[i], "-ref") || !strcmp(argv[i], "-db") || !strcmp(argv[i], "-d")) {
if(i+1 >= argc) {
inputError("Database File name required\n");
}
strcpy(refFile, argv[i+1]);
i++;
}
else if(!strcmp(argv[i], "-prog") || !strcmp(argv[i], "-p")) {
if(i+1 >= argc) {
inputError("Alignment option required\n");
}
strcpy(program, argv[i+1]);
if (strcmp(program,"n")!=0 and strcmp(program,"p")!=0 and strcmp(program,"trn")!=0 and strcmp(program,"trnx")!=0)
inputError("Valid alignment option required\nPlease use -h for details information\n");
i++;
}
else if(!strcmp(argv[i], "-freqFile") || !strcmp(argv[i], "-f")) {
if(i+1 >= argc) {
inputError("Frequency File name required\n");
}
strcpy(outputfile, argv[i+1]);
i++;
}
else if(!strcmp(argv[i], "-hypo") || !strcmp(argv[i], "-heuristic") || !strcmp(argv[i], "-c")) {
if(i+1 >= argc) {
inputError("Argument required\n");
}
sscanf(argv[i+1], "%d", &hypothesis);
if(hypothesis <= 0 || hypothesis >=3) {
inputError("Value of the heuristic must be either 1 (default) or 2\n");
}
i++;
}
else if(!strcmp(argv[i], "-top") || (!strcmp(argv[i], "-t")) {
if(i+1 >= argc) {
inputError("Argument required\n");
}
sscanf(argv[i+1], "%d", &top);
if(top <= 0) {
inputError("Value of top must be positive\n");
}
i++;
}
else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "-help"))
help(argv[0]);
else if (!strcmp(argv[i], "-version") || !strcmp(argv[i], "-v"))
version(argv[0]);
else {
inputError("Invalid arguments\n");
inputError(argv[i]);
}
}
if(!queryFile[0] || !refFile[0] || !program[0]) {
help(argv[0]);
}
// CHECK whether these are valid files
unsigned int SIZEr = 0, SIZEq = 0, SIZE = 0;
//read file:
f = fopen(refFile,"r");
SIZEr = input_size(f,0);
fclose(f);
f = fopen(queryFile,"r");
SIZEq = input_size(f,1);
fclose(f);
char progBuf[1024],write_buff[1024];
LINE_LEN = 2000;
SIZE_SEQ++;
SIZE_SEQ_NAME++;
sprintf(write_buff,"%d %d %d %d %d", TOTAL_DB_SEQ, TOTAL_QRY_SEQ, LINE_LEN, SIZE_SEQ, SIZE_SEQ_NAME);
char *app_path;
if ((app_path = execpath(argv[0])) == NULL) {
fprintf(stderr, "ERROR: We can not get an application path from %s\n", argv[0]);
exit(-1);
}
if (strcmp(program,"n")==0)
{
SIZE = SIZEr * 2 + SIZEq + 2;
if (SIZE >= 2000000000){
printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u) * 2 + total query bp (%u)]\n",SIZE,SIZEr,SIZEq);
inputError("");
}
if(hypothesis == 1)
{
if(top == 1)
sprintf(progBuf, "%s/bin/search_dna_hypo1 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_dna_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
else
{
if(top == 1)
sprintf(progBuf, "%s/bin/search_dna_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_dna_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
}
else if (strcmp(program,"p")==0)
{
SIZE = SIZEr + SIZEq + 2;
if (SIZE >= 2000000000){
printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u) + total query bp (%u)]\n",SIZE,SIZEr,SIZEq);
inputError("");
}
if(hypothesis == 1)
{
if(top == 1)
sprintf(progBuf, "%s/bin/search_pro_hypo1 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_pro_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
else
{
if(top == 1)
sprintf(progBuf, "%s/bin/search_pro_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_pro_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
}
else if (strcmp(program,"trn")==0)
{
SIZE = SIZEr * 2 + SIZEq + 2;
if (SIZE >= 2000000000) {
printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u) * 2 + total query bp (%u)]\n",SIZE,SIZEr,SIZEq);
inputError("");
}
if(hypothesis == 1)
{
if(top == 1)
sprintf(progBuf, "%s/bin/search_trn_hypo1 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_trn_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
else
{
if(top == 1)
sprintf(progBuf, "%s/bin/search_trn_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_trn_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
}
//////////////////
else if (strcmp(program,"trnx")==0)
{
SIZE = SIZEr + SIZEq*2 + 2;
if (SIZE >= 2000000000) {
printf("Current version of Quadich can handle maximum 2 billion bp.\nThe input database and query file contain %u bps [= total database bp (%u) + total query bp (%u) * 2]\n",SIZE,SIZEr,SIZEq);
inputError("");
}
if(hypothesis == 1)
{
sprintf(progBuf, "%s/bin/search_trnx_hypo1_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
}
else
{
printf("Current version of Quadich supports only hypothesis I for translated nucleotide vs protein database alignmnet.\n\n");
inputError("");
/*if(top == 1)
sprintf(progBuf, "%s/bin/search_trn_hypo2 %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
else
sprintf(progBuf, "%s/bin/search_trn_hypo2_top %s %s %s %d %d %s", app_path, refFile, queryFile, outputfile, SIZE, top, write_buff);
*/
}
}
else{
inputError("Please specify the correct program option\n");
}
printf("%s\n",progBuf);
int returnval = system(progBuf);
return returnval;
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2016 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 df_bmp280_wrapper.cpp
* Lightweight driver to access the BMP280 of the DriverFramework.
*
* @author Julian Oes <[email protected]>
*/
#include <px4_config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <px4_getopt.h>
#include <errno.h>
#include <systemlib/perf_counter.h>
#include <systemlib/err.h>
#include <drivers/drv_baro.h>
#include <board_config.h>
//#include <mathlib/math/filter/LowPassFilter2p.hpp>
#include <bmp280/BMP280.hpp>
#include <DevMgr.hpp>
extern "C" { __EXPORT int df_bmp280_wrapper_main(int argc, char *argv[]); }
using namespace DriverFramework;
class DfBmp280Wrapper : public BMP280
{
public:
DfBmp280Wrapper();
~DfBmp280Wrapper();
/**
* Start automatic measurement.
*
* @return 0 on success
*/
int start();
/**
* Stop automatic measurement.
*
* @return 0 on success
*/
int stop();
private:
int _publish(struct baro_sensor_data &data);
orb_advert_t _baro_topic;
int _baro_orb_class_instance;
perf_counter_t _baro_sample_perf;
};
DfBmp280Wrapper::DfBmp280Wrapper() :
BMP280(BARO_DEVICE_PATH),
_baro_topic(nullptr),
_baro_orb_class_instance(-1),
_baro_sample_perf(perf_alloc(PC_ELAPSED, "df_baro_read"))
{
}
DfBmp280Wrapper::~DfBmp280Wrapper()
{
perf_free(_baro_sample_perf);
}
int DfBmp280Wrapper::start()
{
// TODO: don't publish garbage here
baro_report baro_report = {};
_baro_topic = orb_advertise_multi(ORB_ID(sensor_baro), &baro_report,
&_baro_orb_class_instance, ORB_PRIO_DEFAULT);
if (_baro_topic == nullptr) {
PX4_ERR("sensor_baro advert fail");
return -1;
}
/* Init device and start sensor. */
int ret = init();
if (ret != 0) {
PX4_ERR("BMP280 init fail: %d", ret);
return ret;
}
ret = BMP280::start();
if (ret != 0) {
PX4_ERR("BMP280 start fail: %d", ret);
return ret;
}
return 0;
}
int DfBmp280Wrapper::stop()
{
/* Stop sensor. */
int ret = BMP280::stop();
if (ret != 0) {
PX4_ERR("BMP280 stop fail: %d", ret);
return ret;
}
return 0;
}
int DfBmp280Wrapper::_publish(struct baro_sensor_data &data)
{
#if 1
perf_begin(_baro_sample_perf);
baro_report baro_report = {};
baro_report.timestamp = data.last_read_time_usec;
baro_report.pressure = data.pressure_pa;
baro_report.temperature = data.temperature_c;
// TODO: add this
baro_report.altitude = -1.0f;
// TODO: when is this ever blocked?
if (!(m_pub_blocked)) {
if (_baro_topic != nullptr) {
orb_publish(ORB_ID(sensor_baro), _baro_topic, &baro_report);
}
}
/* Notify anyone waiting for data. */
DevMgr::updateNotify(*this);
perf_end(_baro_sample_perf);
#endif
return 0;
};
namespace df_bmp280_wrapper
{
DfBmp280Wrapper *g_dev = nullptr;
int start(/* enum Rotation rotation */);
int stop();
int info();
void usage();
int start(/*enum Rotation rotation*/)
{
g_dev = new DfBmp280Wrapper(/*rotation*/);
if (g_dev == nullptr) {
PX4_ERR("failed instantiating DfBmp280Wrapper object");
return -1;
}
int ret = g_dev->start();
if (ret != 0) {
PX4_ERR("DfBmp280Wrapper start failed");
return ret;
}
// Open the IMU sensor
DevHandle h;
DevMgr::getHandle(BARO_DEVICE_PATH, h);
if (!h.isValid()) {
DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)",
BARO_DEVICE_PATH, h.getError());
return -1;
}
DevMgr::releaseHandle(h);
return 0;
}
int stop()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
int ret = g_dev->stop();
if (ret != 0) {
PX4_ERR("driver could not be stopped");
return ret;
}
delete g_dev;
g_dev = nullptr;
return 0;
}
/**
* Print a little info about the driver.
*/
int
info()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
PX4_DEBUG("state @ %p", g_dev);
return 0;
}
void
usage()
{
PX4_WARN("Usage: df_bmp280_wrapper 'start', 'info', 'stop'");
}
} // namespace df_bmp280_wrapper
int
df_bmp280_wrapper_main(int argc, char *argv[])
{
int ret = 0;
int myoptind = 1;
if (argc <= 1) {
df_bmp280_wrapper::usage();
return 1;
}
const char *verb = argv[myoptind];
if (!strcmp(verb, "start")) {
ret = df_bmp280_wrapper::start();
}
else if (!strcmp(verb, "stop")) {
ret = df_bmp280_wrapper::stop();
}
else if (!strcmp(verb, "info")) {
ret = df_bmp280_wrapper::info();
}
else {
df_bmp280_wrapper::usage();
return 1;
}
return ret;
}
<commit_msg>df_bmp280_wrapper: hack to publish altitude<commit_after>/****************************************************************************
*
* Copyright (c) 2016 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 df_bmp280_wrapper.cpp
* Lightweight driver to access the BMP280 of the DriverFramework.
*
* @author Julian Oes <[email protected]>
*/
#include <px4_config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <px4_getopt.h>
#include <errno.h>
#include <systemlib/perf_counter.h>
#include <systemlib/err.h>
#include <drivers/drv_baro.h>
#include <board_config.h>
//#include <mathlib/math/filter/LowPassFilter2p.hpp>
#include <bmp280/BMP280.hpp>
#include <DevMgr.hpp>
extern "C" { __EXPORT int df_bmp280_wrapper_main(int argc, char *argv[]); }
using namespace DriverFramework;
class DfBmp280Wrapper : public BMP280
{
public:
DfBmp280Wrapper();
~DfBmp280Wrapper();
/**
* Start automatic measurement.
*
* @return 0 on success
*/
int start();
/**
* Stop automatic measurement.
*
* @return 0 on success
*/
int stop();
private:
int _publish(struct baro_sensor_data &data);
orb_advert_t _baro_topic;
int _baro_orb_class_instance;
perf_counter_t _baro_sample_perf;
};
DfBmp280Wrapper::DfBmp280Wrapper() :
BMP280(BARO_DEVICE_PATH),
_baro_topic(nullptr),
_baro_orb_class_instance(-1),
_baro_sample_perf(perf_alloc(PC_ELAPSED, "df_baro_read"))
{
}
DfBmp280Wrapper::~DfBmp280Wrapper()
{
perf_free(_baro_sample_perf);
}
int DfBmp280Wrapper::start()
{
// TODO: don't publish garbage here
baro_report baro_report = {};
_baro_topic = orb_advertise_multi(ORB_ID(sensor_baro), &baro_report,
&_baro_orb_class_instance, ORB_PRIO_DEFAULT);
if (_baro_topic == nullptr) {
PX4_ERR("sensor_baro advert fail");
return -1;
}
/* Init device and start sensor. */
int ret = init();
if (ret != 0) {
PX4_ERR("BMP280 init fail: %d", ret);
return ret;
}
ret = BMP280::start();
if (ret != 0) {
PX4_ERR("BMP280 start fail: %d", ret);
return ret;
}
return 0;
}
int DfBmp280Wrapper::stop()
{
/* Stop sensor. */
int ret = BMP280::stop();
if (ret != 0) {
PX4_ERR("BMP280 stop fail: %d", ret);
return ret;
}
return 0;
}
int DfBmp280Wrapper::_publish(struct baro_sensor_data &data)
{
perf_begin(_baro_sample_perf);
baro_report baro_report = {};
baro_report.timestamp = data.last_read_time_usec;
baro_report.pressure = data.pressure_pa;
baro_report.temperature = data.temperature_c;
// TODO: verify this, it's just copied from the MS5611 driver.
// Constant for now
const float MSL_PRESSURE = 101325.0f;
/* tropospheric properties (0-11km) for standard atmosphere */
const double T1 = 15.0 + 273.15; /* temperature at base height in Kelvin */
const double a = -6.5 / 1000; /* temperature gradient in degrees per metre */
const double g = 9.80665; /* gravity constant in m/s/s */
const double R = 287.05; /* ideal gas constant in J/kg/K */
/* current pressure at MSL in kPa */
double p1 = MSL_PRESSURE / 1000.0;
/* measured pressure in kPa */
double p = data.pressure_pa / 1000.0;
/*
* Solve:
*
* / -(aR / g) \
* | (p / p1) . T1 | - T1
* \ /
* h = ------------------------------- + h1
* a
*/
baro_report.altitude = (((pow((p / p1), (-(a * R) / g))) * T1) - T1) / a;
// TODO: when is this ever blocked?
if (!(m_pub_blocked)) {
if (_baro_topic != nullptr) {
orb_publish(ORB_ID(sensor_baro), _baro_topic, &baro_report);
}
}
/* Notify anyone waiting for data. */
DevMgr::updateNotify(*this);
perf_end(_baro_sample_perf);
return 0;
};
namespace df_bmp280_wrapper
{
DfBmp280Wrapper *g_dev = nullptr;
int start(/* enum Rotation rotation */);
int stop();
int info();
void usage();
int start(/*enum Rotation rotation*/)
{
g_dev = new DfBmp280Wrapper(/*rotation*/);
if (g_dev == nullptr) {
PX4_ERR("failed instantiating DfBmp280Wrapper object");
return -1;
}
int ret = g_dev->start();
if (ret != 0) {
PX4_ERR("DfBmp280Wrapper start failed");
return ret;
}
// Open the IMU sensor
DevHandle h;
DevMgr::getHandle(BARO_DEVICE_PATH, h);
if (!h.isValid()) {
DF_LOG_INFO("Error: unable to obtain a valid handle for the receiver at: %s (%d)",
BARO_DEVICE_PATH, h.getError());
return -1;
}
DevMgr::releaseHandle(h);
return 0;
}
int stop()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
int ret = g_dev->stop();
if (ret != 0) {
PX4_ERR("driver could not be stopped");
return ret;
}
delete g_dev;
g_dev = nullptr;
return 0;
}
/**
* Print a little info about the driver.
*/
int
info()
{
if (g_dev == nullptr) {
PX4_ERR("driver not running");
return 1;
}
PX4_DEBUG("state @ %p", g_dev);
return 0;
}
void
usage()
{
PX4_WARN("Usage: df_bmp280_wrapper 'start', 'info', 'stop'");
}
} // namespace df_bmp280_wrapper
int
df_bmp280_wrapper_main(int argc, char *argv[])
{
int ret = 0;
int myoptind = 1;
if (argc <= 1) {
df_bmp280_wrapper::usage();
return 1;
}
const char *verb = argv[myoptind];
if (!strcmp(verb, "start")) {
ret = df_bmp280_wrapper::start();
}
else if (!strcmp(verb, "stop")) {
ret = df_bmp280_wrapper::stop();
}
else if (!strcmp(verb, "info")) {
ret = df_bmp280_wrapper::info();
}
else {
df_bmp280_wrapper::usage();
return 1;
}
return ret;
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "anchormanipulator.h"
#include "formeditoritem.h"
#include "formeditorscene.h"
#include "formeditorview.h"
#include <model.h>
#include <rewritertransaction.h>
namespace QmlDesigner {
AnchorManipulator::AnchorManipulator(FormEditorView *view)
: m_beginFormEditorItem(0),
m_beginAnchorLine(AnchorLine::Invalid),
m_view(view)
{
}
AnchorManipulator::~AnchorManipulator()
{
clear();
}
void AnchorManipulator::begin(FormEditorItem *beginItem, AnchorLine::Type anchorLine)
{
m_beginFormEditorItem = beginItem;
m_beginAnchorLine = anchorLine;
}
static double offset(const QPointF &topLeft, const QPointF &bottomRight, AnchorLine::Type anchorLine)
{
switch(anchorLine) {
case AnchorLine::Top : return topLeft.y();
case AnchorLine::Left : return topLeft.x();
case AnchorLine::Bottom : return bottomRight.y();
case AnchorLine::Right : return bottomRight.x();
default: break;
}
return 0.0;
}
void AnchorManipulator::setMargin(FormEditorItem *endItem, AnchorLine::Type endAnchorLine)
{
QPointF beginItemTopLeft(m_beginFormEditorItem->mapToParent(m_beginFormEditorItem->qmlItemNode().instanceBoundingRect().topLeft()));
QPointF endItemTopLeft(m_beginFormEditorItem->parentItem()->mapFromItem(endItem, endItem->qmlItemNode().instanceBoundingRect().topLeft()));
QPointF beginItemBottomRight(m_beginFormEditorItem->mapToParent(m_beginFormEditorItem->qmlItemNode().instanceBoundingRect().bottomRight()));
QPointF endItemBottomRight(m_beginFormEditorItem->parentItem()->mapFromItem(endItem, endItem->qmlItemNode().instanceBoundingRect().bottomRight()));
QPointF topLeftAnchorOffset = beginItemTopLeft - endItemTopLeft;
QPointF bottomRightAnchorOffset = endItemBottomRight - beginItemBottomRight;
double anchorOffset = 0.0;
if (m_beginAnchorLine & (AnchorLine::Bottom | AnchorLine::Right)) {
anchorOffset = offset(endItemTopLeft, endItemBottomRight, endAnchorLine) -
offset(beginItemTopLeft, beginItemBottomRight, m_beginAnchorLine);
} else {
anchorOffset = offset(beginItemTopLeft, beginItemBottomRight, m_beginAnchorLine) -
offset(endItemTopLeft, endItemBottomRight, endAnchorLine);
}
m_beginFormEditorItem->qmlItemNode().anchors().setMargin(m_beginAnchorLine, anchorOffset);
}
void AnchorManipulator::addAnchor(FormEditorItem *endItem, AnchorLine::Type endAnchorLine)
{
RewriterTransaction m_rewriterTransaction = m_view->beginRewriterTransaction();
setMargin(endItem, endAnchorLine);
m_beginFormEditorItem->qmlItemNode().anchors().setAnchor(m_beginAnchorLine,
endItem->qmlItemNode(),
endAnchorLine);
}
void AnchorManipulator::removeAnchor()
{
RewriterTransaction transaction = m_view->beginRewriterTransaction();
QmlAnchors anchors(m_beginFormEditorItem->qmlItemNode().anchors());
if (anchors.instanceHasAnchor(m_beginAnchorLine)) {
anchors.removeAnchor(m_beginAnchorLine);
anchors.removeMargin(m_beginAnchorLine);
}
}
void AnchorManipulator::clear()
{
m_beginFormEditorItem = 0;
m_beginAnchorLine = AnchorLine::Invalid;
}
bool AnchorManipulator::isActive() const
{
return m_beginFormEditorItem && m_beginAnchorLine != AnchorLine::Invalid;
}
AnchorLine::Type AnchorManipulator::beginAnchorLine() const
{
return m_beginAnchorLine;
}
bool AnchorManipulator::beginAnchorLineIsHorizontal() const
{
return beginAnchorLine() & AnchorLine::HorizontalMask;
}
bool AnchorManipulator::beginAnchorLineIsVertical() const
{
return beginAnchorLine() & AnchorLine::HorizontalMask;
}
FormEditorItem *AnchorManipulator::beginFormEditorItem() const
{
return m_beginFormEditorItem;
}
} // namespace QmlDesigner
<commit_msg>Remove unused variables.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "anchormanipulator.h"
#include "formeditoritem.h"
#include "formeditorscene.h"
#include "formeditorview.h"
#include <model.h>
#include <rewritertransaction.h>
namespace QmlDesigner {
AnchorManipulator::AnchorManipulator(FormEditorView *view)
: m_beginFormEditorItem(0),
m_beginAnchorLine(AnchorLine::Invalid),
m_view(view)
{
}
AnchorManipulator::~AnchorManipulator()
{
clear();
}
void AnchorManipulator::begin(FormEditorItem *beginItem, AnchorLine::Type anchorLine)
{
m_beginFormEditorItem = beginItem;
m_beginAnchorLine = anchorLine;
}
static double offset(const QPointF &topLeft, const QPointF &bottomRight, AnchorLine::Type anchorLine)
{
switch(anchorLine) {
case AnchorLine::Top : return topLeft.y();
case AnchorLine::Left : return topLeft.x();
case AnchorLine::Bottom : return bottomRight.y();
case AnchorLine::Right : return bottomRight.x();
default: break;
}
return 0.0;
}
void AnchorManipulator::setMargin(FormEditorItem *endItem, AnchorLine::Type endAnchorLine)
{
QPointF beginItemTopLeft(m_beginFormEditorItem->mapToParent(m_beginFormEditorItem->qmlItemNode().instanceBoundingRect().topLeft()));
QPointF endItemTopLeft(m_beginFormEditorItem->parentItem()->mapFromItem(endItem, endItem->qmlItemNode().instanceBoundingRect().topLeft()));
QPointF beginItemBottomRight(m_beginFormEditorItem->mapToParent(m_beginFormEditorItem->qmlItemNode().instanceBoundingRect().bottomRight()));
QPointF endItemBottomRight(m_beginFormEditorItem->parentItem()->mapFromItem(endItem, endItem->qmlItemNode().instanceBoundingRect().bottomRight()));
double anchorOffset = 0.0;
if (m_beginAnchorLine & (AnchorLine::Bottom | AnchorLine::Right)) {
anchorOffset = offset(endItemTopLeft, endItemBottomRight, endAnchorLine) -
offset(beginItemTopLeft, beginItemBottomRight, m_beginAnchorLine);
} else {
anchorOffset = offset(beginItemTopLeft, beginItemBottomRight, m_beginAnchorLine) -
offset(endItemTopLeft, endItemBottomRight, endAnchorLine);
}
m_beginFormEditorItem->qmlItemNode().anchors().setMargin(m_beginAnchorLine, anchorOffset);
}
void AnchorManipulator::addAnchor(FormEditorItem *endItem, AnchorLine::Type endAnchorLine)
{
RewriterTransaction m_rewriterTransaction = m_view->beginRewriterTransaction();
setMargin(endItem, endAnchorLine);
m_beginFormEditorItem->qmlItemNode().anchors().setAnchor(m_beginAnchorLine,
endItem->qmlItemNode(),
endAnchorLine);
}
void AnchorManipulator::removeAnchor()
{
RewriterTransaction transaction = m_view->beginRewriterTransaction();
QmlAnchors anchors(m_beginFormEditorItem->qmlItemNode().anchors());
if (anchors.instanceHasAnchor(m_beginAnchorLine)) {
anchors.removeAnchor(m_beginAnchorLine);
anchors.removeMargin(m_beginAnchorLine);
}
}
void AnchorManipulator::clear()
{
m_beginFormEditorItem = 0;
m_beginAnchorLine = AnchorLine::Invalid;
}
bool AnchorManipulator::isActive() const
{
return m_beginFormEditorItem && m_beginAnchorLine != AnchorLine::Invalid;
}
AnchorLine::Type AnchorManipulator::beginAnchorLine() const
{
return m_beginAnchorLine;
}
bool AnchorManipulator::beginAnchorLineIsHorizontal() const
{
return beginAnchorLine() & AnchorLine::HorizontalMask;
}
bool AnchorManipulator::beginAnchorLineIsVertical() const
{
return beginAnchorLine() & AnchorLine::HorizontalMask;
}
FormEditorItem *AnchorManipulator::beginFormEditorItem() const
{
return m_beginFormEditorItem;
}
} // namespace QmlDesigner
<|endoftext|> |
<commit_before>/* This file is part of Ingen.
* Copyright 2007-2011 David Robillard <http://drobilla.net>
*
* Ingen 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.
*
* Ingen 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 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cassert>
#include <sys/mman.h>
#include <unistd.h>
#include "raul/log.hpp"
#include "raul/Deletable.hpp"
#include "raul/Maid.hpp"
#include "raul/SharedPtr.hpp"
#include "lv2/lv2plug.in/ns/ext/uri-map/uri-map.h"
#include "ingen/EventType.hpp"
#include "events/CreatePatch.hpp"
#include "events/CreatePort.hpp"
#include "shared/World.hpp"
#include "shared/LV2Features.hpp"
#include "shared/LV2URIMap.hpp"
#include "shared/Store.hpp"
#include "BufferFactory.hpp"
#include "ClientBroadcaster.hpp"
#include "ControlBindings.hpp"
#include "Driver.hpp"
#include "Engine.hpp"
#include "EngineStore.hpp"
#include "Event.hpp"
#include "EventSource.hpp"
#include "MessageContext.hpp"
#include "NodeFactory.hpp"
#include "PatchImpl.hpp"
#include "PostProcessor.hpp"
#include "ProcessContext.hpp"
#include "QueuedEngineInterface.hpp"
#include "ThreadManager.hpp"
using namespace std;
using namespace Raul;
namespace Ingen {
namespace Server {
bool ThreadManager::single_threaded = true;
Engine::Engine(Ingen::Shared::World* a_world)
: _world(a_world)
, _broadcaster(new ClientBroadcaster())
, _buffer_factory(new BufferFactory(*this, a_world->uris()))
, _control_bindings(new ControlBindings(*this))
, _maid(new Raul::Maid(event_queue_size()))
, _message_context(new MessageContext(*this))
, _node_factory(new NodeFactory(a_world))
, _post_processor(new PostProcessor(*this, event_queue_size()))
{
if (a_world->store()) {
assert(PtrCast<EngineStore>(a_world->store()));
} else {
a_world->set_store(SharedPtr<Ingen::Shared::Store>(new EngineStore()));
}
}
Engine::~Engine()
{
deactivate();
SharedPtr<EngineStore> store = engine_store();
if (store)
for (EngineStore::iterator i = store->begin(); i != store->end(); ++i)
if ( ! PtrCast<GraphObjectImpl>(i->second)->parent() )
i->second.reset();
delete _maid;
delete _post_processor;
delete _node_factory;
delete _broadcaster;
munlockall();
}
SharedPtr<EngineStore>
Engine::engine_store() const
{
return PtrCast<EngineStore>(_world->store());
}
size_t
Engine::event_queue_size() const
{
return world()->conf()->option("queue-size").get_int32();
}
void
Engine::quit()
{
_quit_flag = true;
}
bool
Engine::main_iteration()
{
_post_processor->process();
_maid->cleanup();
return !_quit_flag;
}
void
Engine::add_event_source(SharedPtr<EventSource> source)
{
_event_sources.insert(source);
}
void
Engine::set_driver(SharedPtr<Driver> driver)
{
_driver = driver;
}
static void
execute_and_delete_event(ProcessContext& context, QueuedEvent* ev)
{
ev->pre_process();
ev->execute(context);
ev->post_process();
delete ev;
}
bool
Engine::activate()
{
assert(_driver);
ThreadManager::single_threaded = true;
_buffer_factory->set_block_length(_driver->block_length());
_message_context->Thread::start();
const Ingen::Shared::LV2URIMap& uris = *world()->uris().get();
// Create root patch
PatchImpl* root_patch = _driver->root_patch();
if (!root_patch) {
root_patch = new PatchImpl(*this, "root", 1, NULL, _driver->sample_rate(), 1);
root_patch->set_property(uris.rdf_type,
Resource::Property(uris.ingen_Patch, Resource::INTERNAL));
root_patch->set_property(uris.ingen_polyphony,
Resource::Property(Raul::Atom(int32_t(1)),
Resource::INTERNAL));
root_patch->activate(*_buffer_factory);
_world->store()->add(root_patch);
root_patch->compiled_patch(root_patch->compile());
_driver->set_root_patch(root_patch);
ProcessContext context(*this);
Resource::Properties control_properties;
control_properties.insert(make_pair(uris.lv2_name, "Control"));
control_properties.insert(make_pair(uris.rdf_type, uris.ev_EventPort));
// Add control input
Resource::Properties in_properties(control_properties);
in_properties.insert(make_pair(uris.rdf_type, uris.lv2_InputPort));
in_properties.insert(make_pair(uris.lv2_index, 0));
in_properties.insert(make_pair(uris.ingenui_canvas_x,
Resource::Property(32.0f, Resource::EXTERNAL)));
in_properties.insert(make_pair(uris.ingenui_canvas_y,
Resource::Property(32.0f, Resource::EXTERNAL)));
execute_and_delete_event(context, new Events::CreatePort(
*this, SharedPtr<Request>(), 0,
"/control_in", uris.ev_EventPort, false, in_properties));
// Add control out
Resource::Properties out_properties(control_properties);
out_properties.insert(make_pair(uris.rdf_type, uris.lv2_OutputPort));
out_properties.insert(make_pair(uris.lv2_index, 1));
out_properties.insert(make_pair(uris.ingenui_canvas_x,
Resource::Property(128.0f, Resource::EXTERNAL)));
out_properties.insert(make_pair(uris.ingenui_canvas_y,
Resource::Property(32.0f, Resource::EXTERNAL)));
execute_and_delete_event(context, new Events::CreatePort(
*this, SharedPtr<Request>(), 0,
"/control_out", uris.ev_EventPort, true, out_properties));
}
_driver->activate();
root_patch->enable();
ThreadManager::single_threaded = false;
return true;
}
void
Engine::deactivate()
{
_driver->deactivate();
_driver->root_patch()->deactivate();
ThreadManager::single_threaded = true;
}
void
Engine::process_events(ProcessContext& context)
{
ThreadManager::assert_thread(THREAD_PROCESS);
for (EventSources::iterator i = _event_sources.begin(); i != _event_sources.end(); ++i)
(*i)->process(*_post_processor, context);
}
} // namespace Server
} // namespace Ingen
<commit_msg>Fix immediate quit due to uninitialised quit flag (fix ticket #677).<commit_after>/* This file is part of Ingen.
* Copyright 2007-2011 David Robillard <http://drobilla.net>
*
* Ingen 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.
*
* Ingen 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 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cassert>
#include <sys/mman.h>
#include <unistd.h>
#include "raul/log.hpp"
#include "raul/Deletable.hpp"
#include "raul/Maid.hpp"
#include "raul/SharedPtr.hpp"
#include "lv2/lv2plug.in/ns/ext/uri-map/uri-map.h"
#include "ingen/EventType.hpp"
#include "events/CreatePatch.hpp"
#include "events/CreatePort.hpp"
#include "shared/World.hpp"
#include "shared/LV2Features.hpp"
#include "shared/LV2URIMap.hpp"
#include "shared/Store.hpp"
#include "BufferFactory.hpp"
#include "ClientBroadcaster.hpp"
#include "ControlBindings.hpp"
#include "Driver.hpp"
#include "Engine.hpp"
#include "EngineStore.hpp"
#include "Event.hpp"
#include "EventSource.hpp"
#include "MessageContext.hpp"
#include "NodeFactory.hpp"
#include "PatchImpl.hpp"
#include "PostProcessor.hpp"
#include "ProcessContext.hpp"
#include "QueuedEngineInterface.hpp"
#include "ThreadManager.hpp"
using namespace std;
using namespace Raul;
namespace Ingen {
namespace Server {
bool ThreadManager::single_threaded = true;
Engine::Engine(Ingen::Shared::World* a_world)
: _world(a_world)
, _broadcaster(new ClientBroadcaster())
, _buffer_factory(new BufferFactory(*this, a_world->uris()))
, _control_bindings(new ControlBindings(*this))
, _maid(new Raul::Maid(event_queue_size()))
, _message_context(new MessageContext(*this))
, _node_factory(new NodeFactory(a_world))
, _post_processor(new PostProcessor(*this, event_queue_size()))
, _quit_flag(false)
{
if (a_world->store()) {
assert(PtrCast<EngineStore>(a_world->store()));
} else {
a_world->set_store(SharedPtr<Ingen::Shared::Store>(new EngineStore()));
}
}
Engine::~Engine()
{
deactivate();
SharedPtr<EngineStore> store = engine_store();
if (store)
for (EngineStore::iterator i = store->begin(); i != store->end(); ++i)
if ( ! PtrCast<GraphObjectImpl>(i->second)->parent() )
i->second.reset();
delete _maid;
delete _post_processor;
delete _node_factory;
delete _broadcaster;
munlockall();
}
SharedPtr<EngineStore>
Engine::engine_store() const
{
return PtrCast<EngineStore>(_world->store());
}
size_t
Engine::event_queue_size() const
{
return world()->conf()->option("queue-size").get_int32();
}
void
Engine::quit()
{
_quit_flag = true;
}
bool
Engine::main_iteration()
{
_post_processor->process();
_maid->cleanup();
return !_quit_flag;
}
void
Engine::add_event_source(SharedPtr<EventSource> source)
{
_event_sources.insert(source);
}
void
Engine::set_driver(SharedPtr<Driver> driver)
{
_driver = driver;
}
static void
execute_and_delete_event(ProcessContext& context, QueuedEvent* ev)
{
ev->pre_process();
ev->execute(context);
ev->post_process();
delete ev;
}
bool
Engine::activate()
{
assert(_driver);
ThreadManager::single_threaded = true;
_buffer_factory->set_block_length(_driver->block_length());
_message_context->Thread::start();
const Ingen::Shared::LV2URIMap& uris = *world()->uris().get();
// Create root patch
PatchImpl* root_patch = _driver->root_patch();
if (!root_patch) {
root_patch = new PatchImpl(*this, "root", 1, NULL, _driver->sample_rate(), 1);
root_patch->set_property(uris.rdf_type,
Resource::Property(uris.ingen_Patch, Resource::INTERNAL));
root_patch->set_property(uris.ingen_polyphony,
Resource::Property(Raul::Atom(int32_t(1)),
Resource::INTERNAL));
root_patch->activate(*_buffer_factory);
_world->store()->add(root_patch);
root_patch->compiled_patch(root_patch->compile());
_driver->set_root_patch(root_patch);
ProcessContext context(*this);
Resource::Properties control_properties;
control_properties.insert(make_pair(uris.lv2_name, "Control"));
control_properties.insert(make_pair(uris.rdf_type, uris.ev_EventPort));
// Add control input
Resource::Properties in_properties(control_properties);
in_properties.insert(make_pair(uris.rdf_type, uris.lv2_InputPort));
in_properties.insert(make_pair(uris.lv2_index, 0));
in_properties.insert(make_pair(uris.ingenui_canvas_x,
Resource::Property(32.0f, Resource::EXTERNAL)));
in_properties.insert(make_pair(uris.ingenui_canvas_y,
Resource::Property(32.0f, Resource::EXTERNAL)));
execute_and_delete_event(context, new Events::CreatePort(
*this, SharedPtr<Request>(), 0,
"/control_in", uris.ev_EventPort, false, in_properties));
// Add control out
Resource::Properties out_properties(control_properties);
out_properties.insert(make_pair(uris.rdf_type, uris.lv2_OutputPort));
out_properties.insert(make_pair(uris.lv2_index, 1));
out_properties.insert(make_pair(uris.ingenui_canvas_x,
Resource::Property(128.0f, Resource::EXTERNAL)));
out_properties.insert(make_pair(uris.ingenui_canvas_y,
Resource::Property(32.0f, Resource::EXTERNAL)));
execute_and_delete_event(context, new Events::CreatePort(
*this, SharedPtr<Request>(), 0,
"/control_out", uris.ev_EventPort, true, out_properties));
}
_driver->activate();
root_patch->enable();
ThreadManager::single_threaded = false;
return true;
}
void
Engine::deactivate()
{
_driver->deactivate();
_driver->root_patch()->deactivate();
ThreadManager::single_threaded = true;
}
void
Engine::process_events(ProcessContext& context)
{
ThreadManager::assert_thread(THREAD_PROCESS);
for (EventSources::iterator i = _event_sources.begin(); i != _event_sources.end(); ++i)
(*i)->process(*_post_processor, context);
}
} // namespace Server
} // namespace Ingen
<|endoftext|> |
<commit_before>#include "server/control.hpp"
#include "arch/spinlock.hpp"
#include "logger.hpp"
#include "errors.hpp"
control_map_t& get_control_map() {
/* Getter function so that we can be sure that control_list is initialized before it is needed,
as advised by the C++ FAQ. Otherwise, a control_t might be initialized before the control list
was initialized. */
static control_map_t control_map;
return control_map;
}
spinlock_t& get_control_lock() {
/* To avoid static initialization fiasco */
static spinlock_t lock;
return lock;
}
std::string control_t::exec(int argc, char **argv) {
if (argc == 0) {
return "You must provide a command name. Type \"rethinkdb help\" for a list of available "
"commands.\r\n";
}
std::string command = argv[0];
control_map_t::iterator it = get_control_map().find(command);
if (it == get_control_map().end()) {
return "There is no command called \"" + command + "\". Type \"rethinkdb help\" for a "
"list of available commands.\r\n";
} else {
return (*it).second->call(argc, argv);
}
}
control_t::control_t(const std::string& _key, const std::string& _help_string, bool _internal)
: key(_key), help_string(_help_string), internal(_internal)
{
rassert(key.size() > 0);
spinlock_acq_t control_acq(&get_control_lock());
rassert(get_control_map().find(key) == get_control_map().end());
get_control_map()[key] = this;
}
control_t::~control_t() {
spinlock_acq_t control_acq(&get_control_lock());
control_map_t &map = get_control_map();
control_map_t::iterator it = map.find(key);
rassert(it != map.end());
map.erase(it);
}
/* Control that displays a list of controls */
struct help_control_t : public control_t
{
help_control_t() : control_t("help", "Display this help message (use \"rethinkdb help internal\" to show internal commands).") { }
std::string call(int argc, char **argv) {
bool show_internal = argc == 2 && argv[1] == std::string("internal");
spinlock_acq_t control_acq(&get_control_lock());
std::string res = "The following \"rethinkdb\" commands are available:\r\n";
for (control_map_t::iterator it = get_control_map().begin(); it != get_control_map().end(); it++) {
if (it->second->internal != show_internal) continue;
res += it->first + ": " + it->second->help_string + "\r\n";
}
return res;
}
} help_control;
/* Example of how to add a control */
struct hi_control_t : public control_t
{
private:
int counter;
public:
hi_control_t() :
control_t("hi", "Say 'hi' to the server, and it will say 'hi' back.", true),
counter(0)
{ }
std::string call(UNUSED int argc, UNUSED char **argv) {
counter++;
if (counter < 3)
return "Salutations, user.\r\n";
else if (counter < 4)
return "Say hi again, I dare you.\r\n";
else
return "Base QPS decreased by 100,000.\r\n";
}
} hi_control;
<commit_msg>Friendlier help message.<commit_after>#include "server/control.hpp"
#include "arch/spinlock.hpp"
#include "utils2.hpp"
#include "logger.hpp"
#include "errors.hpp"
control_map_t& get_control_map() {
/* Getter function so that we can be sure that control_list is initialized before it is needed,
as advised by the C++ FAQ. Otherwise, a control_t might be initialized before the control list
was initialized. */
static control_map_t control_map;
return control_map;
}
spinlock_t& get_control_lock() {
/* To avoid static initialization fiasco */
static spinlock_t lock;
return lock;
}
std::string control_t::exec(int argc, char **argv) {
if (argc == 0) {
return "You must provide a command name. Type \"rethinkdb help\" for a list of available "
"commands.\r\n";
}
std::string command = argv[0];
control_map_t::iterator it = get_control_map().find(command);
if (it == get_control_map().end()) {
return "There is no command called \"" + command + "\". Type \"rethinkdb help\" for a "
"list of available commands.\r\n";
} else {
return (*it).second->call(argc, argv);
}
}
control_t::control_t(const std::string& _key, const std::string& _help_string, bool _internal)
: key(_key), help_string(_help_string), internal(_internal)
{
rassert(key.size() > 0);
spinlock_acq_t control_acq(&get_control_lock());
rassert(get_control_map().find(key) == get_control_map().end());
get_control_map()[key] = this;
}
control_t::~control_t() {
spinlock_acq_t control_acq(&get_control_lock());
control_map_t &map = get_control_map();
control_map_t::iterator it = map.find(key);
rassert(it != map.end());
map.erase(it);
}
/* Control that displays a list of controls */
struct help_control_t : public control_t
{
help_control_t() : control_t("help", "Display this help message (use \"rethinkdb help internal\" to show internal commands).") { }
std::string call(int argc, char **argv) {
bool show_internal = argc == 2 && argv[1] == std::string("internal");
spinlock_acq_t control_acq(&get_control_lock());
std::string res = strprintf("The following %scommands are available:\r\n", show_internal ? "internal " : "");
for (control_map_t::iterator it = get_control_map().begin(); it != get_control_map().end(); it++) {
if (it->second->internal != show_internal) continue;
res += "rethinkdb " + it->first + ": " + it->second->help_string + "\r\n";
}
return res;
}
} help_control;
/* Example of how to add a control */
struct hi_control_t : public control_t
{
private:
int counter;
public:
hi_control_t() :
control_t("hi", "Say 'hi' to the server, and it will say 'hi' back.", true),
counter(0)
{ }
std::string call(UNUSED int argc, UNUSED char **argv) {
counter++;
if (counter < 3)
return "Salutations, user.\r\n";
else if (counter < 4)
return "Say hi again, I dare you.\r\n";
else
return "Base QPS decreased by 100,000.\r\n";
}
} hi_control;
<|endoftext|> |
<commit_before>#include "solver_factory.h"
#include "OsiClpSolverInterface.hpp"
#include "OsiCbcSolverInterface.hpp"
#include "error.h"
namespace cyclus {
// 10800 s = 3 hrs * 60 min/hr * 60 s/min
SolverFactory::SolverFactory() : t_("cbc"), tmax_(10800) { }
SolverFactory::SolverFactory(std::string t) : t_(t), tmax_(10800) { }
SolverFactory::SolverFactory(std::string t, double tmax)
: t_(t),
tmax_(tmax) { }
OsiSolverInterface* SolverFactory::get() {
if (t_ == "clp") {
OsiClpSolverInterface* s = new OsiClpSolverInterface();
s->getModelPtr()->setMaximumSeconds(tmax_);
return s;
} else if (t_ == "cbc") {
OsiCbcSolverInterface* s = new OsiCbcSolverInterface();
s->setMaximumSeconds(tmax_);
return s;
} else {
throw ValueError("invalid SolverFactory type '" + t_ + "'");
}
}
void SolveProg(OsiSolverInterface* si) {
si->initialSolve();
if (HasInt(si)) {
si->branchAndBound();
}
}
bool HasInt(OsiSolverInterface* si) {
int i = 0;
for (i = 0; i != si->getNumCols(); i++) {
if (si->isInteger(i)) {
return true;
}
}
return false;
}
} // namespace cyclus
<commit_msg>now solve fully linear problems with the primal method<commit_after>#include "solver_factory.h"
#include "OsiClpSolverInterface.hpp"
#include "OsiCbcSolverInterface.hpp"
#include "error.h"
namespace cyclus {
// 10800 s = 3 hrs * 60 min/hr * 60 s/min
SolverFactory::SolverFactory() : t_("cbc"), tmax_(10800) { }
SolverFactory::SolverFactory(std::string t) : t_(t), tmax_(10800) { }
SolverFactory::SolverFactory(std::string t, double tmax)
: t_(t),
tmax_(tmax) { }
OsiSolverInterface* SolverFactory::get() {
if (t_ == "clp") {
OsiClpSolverInterface* s = new OsiClpSolverInterface();
s->getModelPtr()->setMaximumSeconds(tmax_);
return s;
} else if (t_ == "cbc") {
OsiCbcSolverInterface* s = new OsiCbcSolverInterface();
s->setMaximumSeconds(tmax_);
return s;
} else {
throw ValueError("invalid SolverFactory type '" + t_ + "'");
}
}
void SolveProg(OsiSolverInterface* si) {
si->initialSolve();
if (HasInt(si)) {
si->branchAndBound();
} else {
OsiClpSolverInterface* cast = dynamic_cast<OsiClpSolverInterface*>(si);
if (cast) {
cast->getModelPtr()->primal(); // solve problem with primal alg
}
}
}
bool HasInt(OsiSolverInterface* si) {
int i = 0;
for (i = 0; i != si->getNumCols(); i++) {
if (si->isInteger(i)) {
return true;
}
}
return false;
}
} // namespace cyclus
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.