text
stringlengths 54
60.6k
|
|---|
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// type_traits
// is_trivially_copyable
// XFAIL: gcc-4.9
#include <type_traits>
#include <cassert>
#include "test_macros.h"
template <class T>
void test_is_trivially_copyable()
{
static_assert( std::is_trivially_copyable<T>::value, "");
static_assert( std::is_trivially_copyable<const T>::value, "");
static_assert( std::is_trivially_copyable<volatile T>::value, "");
static_assert( std::is_trivially_copyable<const volatile T>::value, "");
#if TEST_STD_VER > 14
static_assert( std::is_trivially_copyable_v<T>, "");
static_assert( std::is_trivially_copyable_v<const T>, "");
static_assert( std::is_trivially_copyable_v<volatile T>, "");
static_assert( std::is_trivially_copyable_v<const volatile T>, "");
#endif
}
template <class T>
void test_is_not_trivially_copyable()
{
static_assert(!std::is_trivially_copyable<T>::value, "");
static_assert(!std::is_trivially_copyable<const T>::value, "");
static_assert(!std::is_trivially_copyable<volatile T>::value, "");
static_assert(!std::is_trivially_copyable<const volatile T>::value, "");
#if TEST_STD_VER > 14
static_assert(!std::is_trivially_copyable_v<T>, "");
static_assert(!std::is_trivially_copyable_v<const T>, "");
static_assert(!std::is_trivially_copyable_v<volatile T>, "");
static_assert(!std::is_trivially_copyable_v<const volatile T>, "");
#endif
}
struct A
{
int i_;
};
struct B
{
int i_;
~B() {assert(i_ == 0);}
};
class C
{
public:
C();
};
int main()
{
test_is_trivially_copyable<int> ();
test_is_trivially_copyable<const int> ();
test_is_trivially_copyable<A> ();
test_is_trivially_copyable<const A> ();
test_is_trivially_copyable<C> ();
test_is_not_trivially_copyable<int&> ();
test_is_not_trivially_copyable<const A&> ();
test_is_not_trivially_copyable<B> ();
}
<commit_msg>XFAIL is_trivially_copyable test for compilers that don't implement Core 2094<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// type_traits
// is_trivially_copyable
// These compilers have not implemented Core 2094 which makes volatile
// qualified types trivially copyable.
// XFAIL: clang-3, clang-4, apple-clang, gcc
#include <type_traits>
#include <cassert>
#include "test_macros.h"
template <class T>
void test_is_trivially_copyable()
{
static_assert( std::is_trivially_copyable<T>::value, "");
static_assert( std::is_trivially_copyable<const T>::value, "");
static_assert( std::is_trivially_copyable<volatile T>::value, "");
static_assert( std::is_trivially_copyable<const volatile T>::value, "");
#if TEST_STD_VER > 14
static_assert( std::is_trivially_copyable_v<T>, "");
static_assert( std::is_trivially_copyable_v<const T>, "");
static_assert( std::is_trivially_copyable_v<volatile T>, "");
static_assert( std::is_trivially_copyable_v<const volatile T>, "");
#endif
}
template <class T>
void test_is_not_trivially_copyable()
{
static_assert(!std::is_trivially_copyable<T>::value, "");
static_assert(!std::is_trivially_copyable<const T>::value, "");
static_assert(!std::is_trivially_copyable<volatile T>::value, "");
static_assert(!std::is_trivially_copyable<const volatile T>::value, "");
#if TEST_STD_VER > 14
static_assert(!std::is_trivially_copyable_v<T>, "");
static_assert(!std::is_trivially_copyable_v<const T>, "");
static_assert(!std::is_trivially_copyable_v<volatile T>, "");
static_assert(!std::is_trivially_copyable_v<const volatile T>, "");
#endif
}
struct A
{
int i_;
};
struct B
{
int i_;
~B() {assert(i_ == 0);}
};
class C
{
public:
C();
};
int main()
{
test_is_trivially_copyable<int> ();
test_is_trivially_copyable<const int> ();
test_is_trivially_copyable<A> ();
test_is_trivially_copyable<const A> ();
test_is_trivially_copyable<C> ();
test_is_not_trivially_copyable<int&> ();
test_is_not_trivially_copyable<const A&> ();
test_is_not_trivially_copyable<B> ();
}
<|endoftext|>
|
<commit_before>#include "HCUBE_Defines.h"
#include "Experiments/HCUBE_AtariExperiment.h"
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
using namespace NEAT;
namespace HCUBE
{
AtariExperiment::AtariExperiment(string _experimentName,int _threadID):
Experiment(_experimentName,_threadID), visProc(NULL), rom_file(""),
numActions(0), numObjClasses(0), display_active(false), currentSubstrateIndex(0)
{
}
void AtariExperiment::initializeExperiment(string _rom_file) {
rom_file = _rom_file;
substrate_width = 16;
substrate_height = 21;
// Check that rom exists and is readable
ifstream file(rom_file.c_str());
if (!file.good()) {
cerr << "Unable to find or open rom file: \"" << rom_file << "\"" << endl;
exit(-1);
}
// Initialize Atari Stuff
if (!ale.loadROM(rom_file.c_str(), display_active, true)) {
cerr << "Ale had problem loading rom..." << endl;
exit(-1);
}
numActions = ale.legal_actions.size();
// Load the visual processing framework
visProc = ale.visProc;
numObjClasses = visProc->manual_obj_classes.size();
if (numObjClasses <= 0) {
cerr << "No object classes found. Make sure there is an images directory containg class images." << endl;
exit(-1);
}
// Clear old layerinfo if present
layerInfo.layerNames.clear();
layerInfo.layerSizes.clear();
layerInfo.layerValidSizes.clear();
layerInfo.layerAdjacencyList.clear();
layerInfo.layerIsInput.clear();
layerInfo.layerLocations.clear();
// One input layer for each object class
for (int i=0; i<numObjClasses; ++i) {
layerInfo.layerSizes.push_back(Vector2<int>(substrate_width,substrate_height));
layerInfo.layerIsInput.push_back(true);
layerInfo.layerLocations.push_back(Vector3<float>(4*i,0,0));
layerInfo.layerNames.push_back("Input" + boost::lexical_cast<std::string>(i));
}
// One input layer for the self object
layerInfo.layerSizes.push_back(Vector2<int>(substrate_width,substrate_height));
layerInfo.layerIsInput.push_back(true);
layerInfo.layerLocations.push_back(Vector3<float>(4*numObjClasses,0,0));
layerInfo.layerNames.push_back("InputSelf");
// Processing level -- takes input from all the previous
layerInfo.layerSizes.push_back(Vector2<int>(substrate_width,substrate_height));
layerInfo.layerIsInput.push_back(false);
layerInfo.layerLocations.push_back(Vector3<float>(0,4,0));
layerInfo.layerNames.push_back("Processing");
// Output layer -- used for action selection
layerInfo.layerSizes.push_back(Vector2<int>(numActions,1));
layerInfo.layerIsInput.push_back(false);
layerInfo.layerLocations.push_back(Vector3<float>(0,8,0));
layerInfo.layerNames.push_back("Output");
for (int i=0; i<numObjClasses; ++i) {
layerInfo.layerAdjacencyList.push_back(std::pair<string,string>(
"Input" + boost::lexical_cast<std::string>(i),
"Processing"));
}
layerInfo.layerAdjacencyList.push_back(std::pair<string,string>("InputSelf","Processing"));
layerInfo.layerAdjacencyList.push_back(std::pair<string,string>("Processing","Output"));
layerInfo.normalize = true;
layerInfo.useOldOutputNames = false;
layerInfo.layerValidSizes = layerInfo.layerSizes;
for (int a=0; a<2; a++)
substrates[a].setLayerInfo(layerInfo);
}
NEAT::GeneticPopulation* AtariExperiment::createInitialPopulation(int populationSize) {
GeneticPopulation *population = new GeneticPopulation();
vector<GeneticNodeGene> genes;
// Input Nodes
genes.push_back(GeneticNodeGene("Bias","NetworkSensor",0,false)); // TODO: Check if this helps or not
genes.push_back(GeneticNodeGene("X1","NetworkSensor",0,false));
genes.push_back(GeneticNodeGene("Y1","NetworkSensor",0,false));
genes.push_back(GeneticNodeGene("X2","NetworkSensor",0,false));
genes.push_back(GeneticNodeGene("Y2","NetworkSensor",0,false));
// Output Nodes
for (int i=0; i<numObjClasses; ++i) {
genes.push_back(GeneticNodeGene("Output_Input" + boost::lexical_cast<std::string>(i) +
"_Processing",
"NetworkOutputNode",1,false,
ACTIVATION_FUNCTION_SIGMOID));
}
genes.push_back(GeneticNodeGene("Output_InputSelf_Processing","NetworkOutputNode",1,false,
ACTIVATION_FUNCTION_SIGMOID));
genes.push_back(GeneticNodeGene("Output_Processing_Output","NetworkOutputNode",1,false,
ACTIVATION_FUNCTION_SIGMOID));
for (int a=0; a<populationSize; a++) {
shared_ptr<GeneticIndividual> individual(new GeneticIndividual(genes,true,1.0));
for (int b=0;b<10;b++) {
individual->testMutate();
}
population->addIndividual(individual);
}
cout << "Finished creating population\n";
return population;
}
void AtariExperiment::populateSubstrate(shared_ptr<NEAT::GeneticIndividual> individual,
int substrateNum) {
NEAT::LayeredSubstrate<float>* substrate;
if (substrateNum>=2)
throw CREATE_LOCATEDEXCEPTION_INFO("ERROR: INVALID SUBSTRATE INDEX!");
//Don't bother remaking the same substrate
if (substrateIndividuals[substrateNum]==individual)
return;
substrateIndividuals[substrateNum]=individual;
substrate = &substrates[substrateNum];
substrate->populateSubstrate(individual);
}
void AtariExperiment::processGroup(shared_ptr<NEAT::GeneticGeneration> generation)
{
shared_ptr<NEAT::GeneticIndividual> individual = group.front();
individual->setFitness(0);
// Print the individual. This is rarely useful...
//individual->print();
populateSubstrate(individual);
runAtariEpisode(individual);
}
void AtariExperiment::runAtariEpisode(shared_ptr<NEAT::GeneticIndividual> individual) {
NEAT::LayeredSubstrate<float>* substrate = &substrates[currentSubstrateIndex];
// Reset the game
ale.reset_game();
while (!ale.game_over()) {
// Set value of all nodes to zero
substrate->getNetwork()->reinitialize();
substrate->getNetwork()->dummyActivation();
// Set substrate value for all objects (of a certain size)
setSubstrateObjectValues(*visProc, substrate);
// Set substrate value for self
setSubstrateSelfValue(*visProc, substrate);
// Propagate values through the ANN
substrate->getNetwork()->update();
// Print the Activations of the different layers
//printLayerInfo(substrate);
// Choose which action to take
Action action = selectAction(*visProc, substrate);
ale.act(action);
}
cout << "Game ended in " << ale.frame << " frames with score " << ale.game_score << endl;
// Give the reward to the agent
individual->reward(ale.game_score);
}
void AtariExperiment::setSubstrateObjectValues(VisualProcessor& visProc,
NEAT::LayeredSubstrate<float>* substrate) {
for (int i=0; i<visProc.manual_obj_classes.size(); i++) {
Prototype& proto = visProc.manual_obj_classes[i];
paintSubstrate(visProc, proto, substrate, i);
}
}
void AtariExperiment::paintSubstrate(VisualProcessor& visProc, Prototype& proto,
NEAT::LayeredSubstrate<float>* substrate, int substrateIndx) {
// Assign values to each of the objects
float assigned_value = 1.0;
for (set<long>::iterator it=proto.obj_ids.begin(); it!=proto.obj_ids.end(); it++) {
long obj_id = *it;
assert(visProc.composite_objs.find(obj_id) != visProc.composite_objs.end());
point obj_centroid = visProc.composite_objs[obj_id].get_centroid();
int adj_x = obj_centroid.x * substrate_width / visProc.screen_width;
int adj_y = obj_centroid.y * substrate_height / visProc.screen_height;
// for (int y=0; y<substrate_height; ++y) {
// for (int x=0; x<substrate_width; ++x) {
// double val = gauss2D((double)x,(double)y, assigned_value,
// (double)adj_x,(double)adj_y,1.0,1.0);
// substrate->setValue(Node(x,y,i),substrate->getValue(Node(x,y,i))+val);
// }
// }
substrate->setValue((Node(adj_x,adj_y,substrateIndx)),assigned_value);
}
}
void AtariExperiment::printLayerInfo(NEAT::LayeredSubstrate<float>* substrate) {
for (int i=0; i<layerInfo.layerNames.size(); i++) {
string layerName = layerInfo.layerNames[i];
JGTL::Vector2<int> layerSize = layerInfo.layerSizes[i];
JGTL::Vector2<int> layerValidSize = layerInfo.layerValidSizes[i];
bool isInput = layerInfo.layerIsInput[i];
printf("Layer%d Name:%s Size:<%d,%d> ValidSize:<%d,%d> Input:%d\n",i,layerName.c_str(),
layerSize.x,layerSize.y,layerValidSize.x,layerValidSize.y,isInput);
for (int y=0; y<layerSize.y; ++y) {
for (int x=0; x<layerSize.x; ++x) {
float val = substrate->getValue(Node(x,y,i));
printf("%1.1f ",val);
}
printf("\n");
}
printf("\n");
}
cin.get();
}
void AtariExperiment::setSubstrateSelfValue(VisualProcessor& visProc,
NEAT::LayeredSubstrate<float>* substrate) {
if (!visProc.found_self())
return;
paintSubstrate(visProc, visProc.manual_self, substrate, numObjClasses);
}
Action AtariExperiment::selectAction(VisualProcessor& visProc,
NEAT::LayeredSubstrate<float>* substrate) {
vector<int> max_inds;
float max_val = -1e37;
for (int i=0; i < numActions; i++) {
float output = substrate->getValue(Node(i,0,numObjClasses+2));
if (output == max_val)
max_inds.push_back(i);
else if (output > max_val) {
max_inds.clear();
max_inds.push_back(i);
max_val = output;
}
}
int action_indx = NEAT::Globals::getSingleton()->getRandom().getRandomInt(max_inds.size());
//int action_indx = choice(&max_inds);
return ale.legal_actions[max_inds[action_indx]];
}
double AtariExperiment::gauss2D(double x, double y, double A, double mu_x, double mu_y,
double sigma_x, double sigma_y)
{
return A * exp(-1.0 * ((x-mu_x) * (x-mu_x) / 2.0 * sigma_x * sigma_x + (y-mu_y) * (y-mu_y) / 2.0 * sigma_y * sigma_y));
}
void AtariExperiment::preprocessIndividual(shared_ptr<NEAT::GeneticGeneration> generation,
shared_ptr<NEAT::GeneticIndividual> individual) {
if (individual->getNode("X1") == NULL) {
printf("Got blank individual\n");
}
}
void AtariExperiment::processIndividualPostHoc(shared_ptr<NEAT::GeneticIndividual> individual) {}
Experiment* AtariExperiment::clone()
{
AtariExperiment* experiment = new AtariExperiment(*this);
return experiment;
}
}
<commit_msg>Experimental Setup: HyperNEAT with 8x10 substrate and full legal action set.<commit_after>#include "HCUBE_Defines.h"
#include "Experiments/HCUBE_AtariExperiment.h"
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
using namespace NEAT;
namespace HCUBE
{
AtariExperiment::AtariExperiment(string _experimentName,int _threadID):
Experiment(_experimentName,_threadID), visProc(NULL), rom_file(""),
numActions(0), numObjClasses(0), display_active(false), currentSubstrateIndex(0)
{
}
void AtariExperiment::initializeExperiment(string _rom_file) {
rom_file = _rom_file;
substrate_width = 8;
substrate_height = 10;
// Check that rom exists and is readable
ifstream file(rom_file.c_str());
if (!file.good()) {
cerr << "Unable to find or open rom file: \"" << rom_file << "\"" << endl;
exit(-1);
}
// Initialize Atari Stuff
if (!ale.loadROM(rom_file.c_str(), display_active, true)) {
cerr << "Ale had problem loading rom..." << endl;
exit(-1);
}
numActions = ale.legal_actions.size();
// Load the visual processing framework
visProc = ale.visProc;
numObjClasses = visProc->manual_obj_classes.size();
if (numObjClasses <= 0) {
cerr << "No object classes found. Make sure there is an images directory containg class images." << endl;
exit(-1);
}
// Clear old layerinfo if present
layerInfo.layerNames.clear();
layerInfo.layerSizes.clear();
layerInfo.layerValidSizes.clear();
layerInfo.layerAdjacencyList.clear();
layerInfo.layerIsInput.clear();
layerInfo.layerLocations.clear();
// One input layer for each object class
for (int i=0; i<numObjClasses; ++i) {
layerInfo.layerSizes.push_back(Vector2<int>(substrate_width,substrate_height));
layerInfo.layerIsInput.push_back(true);
layerInfo.layerLocations.push_back(Vector3<float>(4*i,0,0));
layerInfo.layerNames.push_back("Input" + boost::lexical_cast<std::string>(i));
}
// One input layer for the self object
layerInfo.layerSizes.push_back(Vector2<int>(substrate_width,substrate_height));
layerInfo.layerIsInput.push_back(true);
layerInfo.layerLocations.push_back(Vector3<float>(4*numObjClasses,0,0));
layerInfo.layerNames.push_back("InputSelf");
// Processing level -- takes input from all the previous
layerInfo.layerSizes.push_back(Vector2<int>(substrate_width,substrate_height));
layerInfo.layerIsInput.push_back(false);
layerInfo.layerLocations.push_back(Vector3<float>(0,4,0));
layerInfo.layerNames.push_back("Processing");
// Output layer -- used for action selection
layerInfo.layerSizes.push_back(Vector2<int>(numActions,1));
layerInfo.layerIsInput.push_back(false);
layerInfo.layerLocations.push_back(Vector3<float>(0,8,0));
layerInfo.layerNames.push_back("Output");
for (int i=0; i<numObjClasses; ++i) {
layerInfo.layerAdjacencyList.push_back(std::pair<string,string>(
"Input" + boost::lexical_cast<std::string>(i),
"Processing"));
}
layerInfo.layerAdjacencyList.push_back(std::pair<string,string>("InputSelf","Processing"));
layerInfo.layerAdjacencyList.push_back(std::pair<string,string>("Processing","Output"));
layerInfo.normalize = true;
layerInfo.useOldOutputNames = false;
layerInfo.layerValidSizes = layerInfo.layerSizes;
for (int a=0; a<2; a++)
substrates[a].setLayerInfo(layerInfo);
}
NEAT::GeneticPopulation* AtariExperiment::createInitialPopulation(int populationSize) {
GeneticPopulation *population = new GeneticPopulation();
vector<GeneticNodeGene> genes;
// Input Nodes
genes.push_back(GeneticNodeGene("Bias","NetworkSensor",0,false)); // TODO: Check if this helps or not
genes.push_back(GeneticNodeGene("X1","NetworkSensor",0,false));
genes.push_back(GeneticNodeGene("Y1","NetworkSensor",0,false));
genes.push_back(GeneticNodeGene("X2","NetworkSensor",0,false));
genes.push_back(GeneticNodeGene("Y2","NetworkSensor",0,false));
// Output Nodes
for (int i=0; i<numObjClasses; ++i) {
genes.push_back(GeneticNodeGene("Output_Input" + boost::lexical_cast<std::string>(i) +
"_Processing",
"NetworkOutputNode",1,false,
ACTIVATION_FUNCTION_SIGMOID));
}
genes.push_back(GeneticNodeGene("Output_InputSelf_Processing","NetworkOutputNode",1,false,
ACTIVATION_FUNCTION_SIGMOID));
genes.push_back(GeneticNodeGene("Output_Processing_Output","NetworkOutputNode",1,false,
ACTIVATION_FUNCTION_SIGMOID));
for (int a=0; a<populationSize; a++) {
shared_ptr<GeneticIndividual> individual(new GeneticIndividual(genes,true,1.0));
for (int b=0;b<10;b++) {
individual->testMutate();
}
population->addIndividual(individual);
}
cout << "Finished creating population\n";
return population;
}
void AtariExperiment::populateSubstrate(shared_ptr<NEAT::GeneticIndividual> individual,
int substrateNum) {
NEAT::LayeredSubstrate<float>* substrate;
if (substrateNum>=2)
throw CREATE_LOCATEDEXCEPTION_INFO("ERROR: INVALID SUBSTRATE INDEX!");
//Don't bother remaking the same substrate
if (substrateIndividuals[substrateNum]==individual)
return;
substrateIndividuals[substrateNum]=individual;
substrate = &substrates[substrateNum];
substrate->populateSubstrate(individual);
}
void AtariExperiment::processGroup(shared_ptr<NEAT::GeneticGeneration> generation)
{
shared_ptr<NEAT::GeneticIndividual> individual = group.front();
individual->setFitness(0);
// Print the individual. This is rarely useful...
//individual->print();
populateSubstrate(individual);
runAtariEpisode(individual);
}
void AtariExperiment::runAtariEpisode(shared_ptr<NEAT::GeneticIndividual> individual) {
NEAT::LayeredSubstrate<float>* substrate = &substrates[currentSubstrateIndex];
// Reset the game
ale.reset_game();
while (!ale.game_over()) {
// Set value of all nodes to zero
substrate->getNetwork()->reinitialize();
substrate->getNetwork()->dummyActivation();
// Set substrate value for all objects (of a certain size)
setSubstrateObjectValues(*visProc, substrate);
// Set substrate value for self
setSubstrateSelfValue(*visProc, substrate);
// Propagate values through the ANN
substrate->getNetwork()->update();
// Print the Activations of the different layers
//printLayerInfo(substrate);
// Choose which action to take
Action action = selectAction(*visProc, substrate);
ale.act(action);
}
cout << "Game ended in " << ale.frame << " frames with score " << ale.game_score << endl;
// Give the reward to the agent
individual->reward(ale.game_score);
}
void AtariExperiment::setSubstrateObjectValues(VisualProcessor& visProc,
NEAT::LayeredSubstrate<float>* substrate) {
for (int i=0; i<visProc.manual_obj_classes.size(); i++) {
Prototype& proto = visProc.manual_obj_classes[i];
paintSubstrate(visProc, proto, substrate, i);
}
}
void AtariExperiment::paintSubstrate(VisualProcessor& visProc, Prototype& proto,
NEAT::LayeredSubstrate<float>* substrate, int substrateIndx) {
// Assign values to each of the objects
float assigned_value = 1.0;
for (set<long>::iterator it=proto.obj_ids.begin(); it!=proto.obj_ids.end(); it++) {
long obj_id = *it;
assert(visProc.composite_objs.find(obj_id) != visProc.composite_objs.end());
point obj_centroid = visProc.composite_objs[obj_id].get_centroid();
int adj_x = obj_centroid.x * substrate_width / visProc.screen_width;
int adj_y = obj_centroid.y * substrate_height / visProc.screen_height;
// for (int y=0; y<substrate_height; ++y) {
// for (int x=0; x<substrate_width; ++x) {
// double val = gauss2D((double)x,(double)y, assigned_value,
// (double)adj_x,(double)adj_y,1.0,1.0);
// substrate->setValue(Node(x,y,i),substrate->getValue(Node(x,y,i))+val);
// }
// }
substrate->setValue((Node(adj_x,adj_y,substrateIndx)),assigned_value);
}
}
void AtariExperiment::printLayerInfo(NEAT::LayeredSubstrate<float>* substrate) {
for (int i=0; i<layerInfo.layerNames.size(); i++) {
string layerName = layerInfo.layerNames[i];
JGTL::Vector2<int> layerSize = layerInfo.layerSizes[i];
JGTL::Vector2<int> layerValidSize = layerInfo.layerValidSizes[i];
bool isInput = layerInfo.layerIsInput[i];
printf("Layer%d Name:%s Size:<%d,%d> ValidSize:<%d,%d> Input:%d\n",i,layerName.c_str(),
layerSize.x,layerSize.y,layerValidSize.x,layerValidSize.y,isInput);
for (int y=0; y<layerSize.y; ++y) {
for (int x=0; x<layerSize.x; ++x) {
float val = substrate->getValue(Node(x,y,i));
printf("%1.1f ",val);
}
printf("\n");
}
printf("\n");
}
cin.get();
}
void AtariExperiment::setSubstrateSelfValue(VisualProcessor& visProc,
NEAT::LayeredSubstrate<float>* substrate) {
if (!visProc.found_self())
return;
paintSubstrate(visProc, visProc.manual_self, substrate, numObjClasses);
}
Action AtariExperiment::selectAction(VisualProcessor& visProc,
NEAT::LayeredSubstrate<float>* substrate) {
vector<int> max_inds;
float max_val = -1e37;
for (int i=0; i < numActions; i++) {
float output = substrate->getValue(Node(i,0,numObjClasses+2));
if (output == max_val)
max_inds.push_back(i);
else if (output > max_val) {
max_inds.clear();
max_inds.push_back(i);
max_val = output;
}
}
int action_indx = NEAT::Globals::getSingleton()->getRandom().getRandomInt(max_inds.size());
//int action_indx = choice(&max_inds);
return ale.legal_actions[max_inds[action_indx]];
}
double AtariExperiment::gauss2D(double x, double y, double A, double mu_x, double mu_y,
double sigma_x, double sigma_y)
{
return A * exp(-1.0 * ((x-mu_x) * (x-mu_x) / 2.0 * sigma_x * sigma_x + (y-mu_y) * (y-mu_y) / 2.0 * sigma_y * sigma_y));
}
void AtariExperiment::preprocessIndividual(shared_ptr<NEAT::GeneticGeneration> generation,
shared_ptr<NEAT::GeneticIndividual> individual) {
if (individual->getNode("X1") == NULL) {
printf("Got blank individual\n");
}
}
void AtariExperiment::processIndividualPostHoc(shared_ptr<NEAT::GeneticIndividual> individual) {}
Experiment* AtariExperiment::clone()
{
AtariExperiment* experiment = new AtariExperiment(*this);
return experiment;
}
}
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
//Mitk
#include <mitkDataNode.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
#include <mitkIRenderingManager.h>
// Qmitk
#include "UltrasoundSupport.h"
#include <QTimer>
// Qt
#include <QMessageBox>
// Ultrasound
#include "mitkUSDevice.h"
#include "QmitkUSAbstractCustomWidget.h"
#include <usModuleContext.h>
#include <usGetModuleContext.h>
#include "usServiceReference.h"
#include "internal/org_mitk_gui_qt_ultrasound_Activator.h"
const std::string UltrasoundSupport::VIEW_ID = "org.mitk.views.ultrasoundsupport";
void UltrasoundSupport::SetFocus()
{
}
void UltrasoundSupport::CreateQtPartControl( QWidget *parent )
{
m_Timer = new QTimer(this);
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi( parent );
connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this, SLOT(OnClickedAddNewDevice()) ); // Change Widget Visibilities
connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this->m_Controls.m_NewVideoDeviceWidget, SLOT(CreateNewDevice()) ); // Init NewDeviceWidget
connect( m_Controls.m_NewVideoDeviceWidget, SIGNAL(Finished()), this, SLOT(OnNewDeviceWidgetDone()) ); // After NewDeviceWidget finished editing
connect( m_Controls.m_BtnView, SIGNAL(clicked()), this, SLOT(OnClickedViewDevice()) );
connect( m_Controls.m_FrameRate, SIGNAL(valueChanged(int)), this, SLOT(OnChangedFramerateLimit(int)) );
connect( m_Controls.m_FreezeButton, SIGNAL(clicked()), this, SLOT(OnClickedFreezeButton()) );
connect( m_Timer, SIGNAL(timeout()), this, SLOT(DisplayImage()));
// Initializations
m_Controls.m_NewVideoDeviceWidget->setVisible(false);
std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "="
+ "org.mitk.services.UltrasoundDevice)("
+ mitk::USDevice::GetPropertyKeys().US_PROPKEY_ISACTIVE + "=true))";
m_Controls.m_ActiveVideoDevices->Initialize<mitk::USDevice>(
mitk::USDevice::GetPropertyKeys().US_PROPKEY_LABEL ,filter);
m_Node = this->GetDataStorage()->GetNamedNode("US Image Stream");
if (m_Node.IsNull())
{
// Create Node for US Stream
m_Node = mitk::DataNode::New();
m_Node->SetName("US Image Stream");
this->GetDataStorage()->Add(m_Node);
}
m_Controls.tabWidget->setTabEnabled(1, false);
}
void UltrasoundSupport::OnClickedAddNewDevice()
{
m_Controls.m_NewVideoDeviceWidget->setVisible(true);
m_Controls.m_DeviceManagerWidget->setVisible(false);
m_Controls.m_Headline->setText("Add New Video Device:");
m_Controls.m_WidgetActiveDevices->setVisible(false);
}
void UltrasoundSupport::DisplayImage()
{
m_Device->Modified();
m_Device->Update();
mitk::Image::Pointer curOutput = m_Device->GetOutput();
if (! m_ImageAlreadySetToNode && curOutput.IsNotNull() && curOutput->IsInitialized())
{
m_Node->SetData(curOutput);
m_ImageAlreadySetToNode = true;
}
if ( curOutput.GetPointer() != m_Node->GetData() )
{
MITK_INFO << "Data Node of the ultrasound image stream was changed by another plugin. Stop viewing.";
this->StopViewing();
return;
}
this->RequestRenderWindowUpdate();
if ( curOutput->GetDimension() > 1
&& (curOutput->GetDimension(0) != m_CurrentImageWidth
|| curOutput->GetDimension(1) != m_CurrentImageHeight) )
{
// make a reinit on the ultrasound image
mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart();
if ( renderWindow != NULL && curOutput->GetTimeGeometry()->IsValid() )
{
renderWindow->GetRenderingManager()->InitializeViews(
curOutput->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true );
renderWindow->GetRenderingManager()->RequestUpdateAll();
}
m_CurrentImageWidth = curOutput->GetDimension(0);
m_CurrentImageHeight = curOutput->GetDimension(1);
}
m_FrameCounter ++;
if (m_FrameCounter == 10)
{
int nMilliseconds = m_Clock.restart();
int fps = 10000.0f / (nMilliseconds );
m_Controls.m_FramerateLabel->setText("Current Framerate: "+ QString::number(fps) +" FPS");
m_FrameCounter = 0;
}
}
void UltrasoundSupport::OnClickedViewDevice()
{
m_FrameCounter = 0;
// We use the activity state of the timer to determine whether we are currently viewing images
if ( ! m_Timer->isActive() ) // Activate Imaging
{
this->StartViewing();
}
else //deactivate imaging
{
this->StopViewing();
}
}
void UltrasoundSupport::OnChangedFramerateLimit(int value)
{
m_Timer->setInterval(1000 / value);
}
void UltrasoundSupport::OnClickedFreezeButton()
{
if ( m_Device->GetIsFreezed() )
{
m_Device->SetIsFreezed(false);
m_Controls.m_FreezeButton->setText("Freeze");
}
else
{
m_Device->SetIsFreezed(true);
m_Controls.m_FreezeButton->setText("Start Viewing Again");
}
}
void UltrasoundSupport::OnNewDeviceWidgetDone()
{
m_Controls.m_NewVideoDeviceWidget->setVisible(false);
m_Controls.m_DeviceManagerWidget->setVisible(true);
m_Controls.m_Headline->setText("Ultrasound Devices:");
m_Controls.m_WidgetActiveDevices->setVisible(true);
}
void UltrasoundSupport::StartViewing()
{
m_ImageAlreadySetToNode = false;
m_Controls.tabWidget->setTabEnabled(1, true);
m_Controls.tabWidget->setCurrentIndex(1);
//get device & set data node
m_Device = m_Controls.m_ActiveVideoDevices->GetSelectedService<mitk::USDevice>();
if (m_Device.IsNull())
{
m_Timer->stop();
return;
}
//start timer
int interval = (1000 / m_Controls.m_FrameRate->value());
m_Timer->setInterval(interval);
m_Timer->start();
//change UI elements
m_Controls.m_BtnView->setText("Stop Viewing");
this->CreateControlWidgets();
}
void UltrasoundSupport::StopViewing()
{
m_Controls.tabWidget->setTabEnabled(1, false);
this->RemoveControlWidgets();
//stop timer & release data
m_Timer->stop();
m_Node->ReleaseData();
this->RequestRenderWindowUpdate();
//change UI elements
m_Controls.m_BtnView->setText("Start Viewing");
}
void UltrasoundSupport::CreateControlWidgets()
{
m_ControlProbesWidget = new QmitkUSControlsProbesWidget(m_Device->GetControlInterfaceProbes(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.probesWidgetContainer->addWidget(m_ControlProbesWidget);
// create b mode widget for current device
m_ControlBModeWidget = new QmitkUSControlsBModeWidget(m_Device->GetControlInterfaceBMode(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlBModeWidget, "B Mode Controls");
if ( ! m_Device->GetControlInterfaceBMode() )
{
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
// create doppler widget for current device
m_ControlDopplerWidget = new QmitkUSControlsDopplerWidget(m_Device->GetControlInterfaceDoppler(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlDopplerWidget, "Doppler Controls");
if ( ! m_Device->GetControlInterfaceDoppler() )
{
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
if ( pluginContext )
{
std::string filter = "(ork.mitk.services.UltrasoundCustomWidget.deviceClass=" + m_Device->GetDeviceClass() + ")";
QString interfaceName ( us_service_interface_iid<QmitkUSAbstractCustomWidget>() );
m_CustomWidgetServiceReference = pluginContext->getServiceReferences(interfaceName, QString::fromStdString(filter));
if (m_CustomWidgetServiceReference.size() > 0)
{
m_ControlCustomWidget = pluginContext->getService<QmitkUSAbstractCustomWidget>
(m_CustomWidgetServiceReference.at(0))->CloneForQt(m_Controls.tab2);
m_ControlCustomWidget->SetDevice(m_Device);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlCustomWidget, "Custom Controls");
}
else
{
m_Controls.m_ToolBoxControlWidgets->addItem(new QWidget(m_Controls.m_ToolBoxControlWidgets), "Custom Controls");
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
}
// select first enabled control widget
for ( int n = 0; n < m_Controls.m_ToolBoxControlWidgets->count(); ++n)
{
if ( m_Controls.m_ToolBoxControlWidgets->isItemEnabled(n) )
{
m_Controls.m_ToolBoxControlWidgets->setCurrentIndex(n);
break;
}
}
}
void UltrasoundSupport::RemoveControlWidgets()
{
// remove all control widgets from the tool box widget
while (m_Controls.m_ToolBoxControlWidgets->count() > 0)
{
m_Controls.m_ToolBoxControlWidgets->removeItem(0);
}
// remove probes widget (which is not part of the tool box widget)
m_Controls.probesWidgetContainer->removeWidget(m_ControlProbesWidget);
delete m_ControlProbesWidget;
m_ControlProbesWidget = 0;
delete m_ControlBModeWidget;
m_ControlBModeWidget = 0;
delete m_ControlDopplerWidget;
m_ControlDopplerWidget = 0;
// delete custom widget if it is present
if ( m_ControlCustomWidget )
{
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
delete m_ControlCustomWidget; m_ControlCustomWidget = 0;
if ( m_CustomWidgetServiceReference.size() > 0 )
{
pluginContext->ungetService(m_CustomWidgetServiceReference.at(0));
}
}
}
void UltrasoundSupport::OnDeciveServiceEvent(const ctkServiceEvent event)
{
if ( m_Device.IsNull() || event.getType() != us::ServiceEvent::MODIFIED ) { return; }
ctkServiceReference service = event.getServiceReference();
if ( m_Device->GetDeviceManufacturer() != service.getProperty(mitk::USImageMetadata::PROP_DEV_MANUFACTURER).toString().toStdString()
&& m_Device->GetDeviceModel() != service.getProperty(mitk::USImageMetadata::PROP_DEV_MODEL).toString().toStdString() )
{
return;
}
if ( ! m_Device->GetIsActive() && m_Timer->isActive() )
{
this->StopViewing();
}
}
UltrasoundSupport::UltrasoundSupport()
: m_ControlCustomWidget(0), m_ControlBModeWidget(0),
m_ControlProbesWidget(0), m_ImageAlreadySetToNode(false),
m_CurrentImageWidth(0), m_CurrentImageHeight(0)
{
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
if ( pluginContext )
{
// to be notified about service event of an USDevice
pluginContext->connectServiceListener(this, "OnDeciveServiceEvent",
QString::fromStdString("(" + us::ServiceConstants::OBJECTCLASS() + "=" + us_service_interface_iid<mitk::USDevice>() + ")"));
}
}
UltrasoundSupport::~UltrasoundSupport()
{
}
<commit_msg>Commented out some code which is not working as intended and is only used by an internal navigation application.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
//Mitk
#include <mitkDataNode.h>
#include <mitkNodePredicateNot.h>
#include <mitkNodePredicateProperty.h>
#include <mitkIRenderingManager.h>
// Qmitk
#include "UltrasoundSupport.h"
#include <QTimer>
// Qt
#include <QMessageBox>
// Ultrasound
#include "mitkUSDevice.h"
#include "QmitkUSAbstractCustomWidget.h"
#include <usModuleContext.h>
#include <usGetModuleContext.h>
#include "usServiceReference.h"
#include "internal/org_mitk_gui_qt_ultrasound_Activator.h"
const std::string UltrasoundSupport::VIEW_ID = "org.mitk.views.ultrasoundsupport";
void UltrasoundSupport::SetFocus()
{
}
void UltrasoundSupport::CreateQtPartControl( QWidget *parent )
{
m_Timer = new QTimer(this);
// create GUI widgets from the Qt Designer's .ui file
m_Controls.setupUi( parent );
connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this, SLOT(OnClickedAddNewDevice()) ); // Change Widget Visibilities
connect( m_Controls.m_DeviceManagerWidget, SIGNAL(NewDeviceButtonClicked()), this->m_Controls.m_NewVideoDeviceWidget, SLOT(CreateNewDevice()) ); // Init NewDeviceWidget
connect( m_Controls.m_NewVideoDeviceWidget, SIGNAL(Finished()), this, SLOT(OnNewDeviceWidgetDone()) ); // After NewDeviceWidget finished editing
connect( m_Controls.m_BtnView, SIGNAL(clicked()), this, SLOT(OnClickedViewDevice()) );
connect( m_Controls.m_FrameRate, SIGNAL(valueChanged(int)), this, SLOT(OnChangedFramerateLimit(int)) );
connect( m_Controls.m_FreezeButton, SIGNAL(clicked()), this, SLOT(OnClickedFreezeButton()) );
connect( m_Timer, SIGNAL(timeout()), this, SLOT(DisplayImage()));
// Initializations
m_Controls.m_NewVideoDeviceWidget->setVisible(false);
std::string filter = "(&(" + us::ServiceConstants::OBJECTCLASS() + "="
+ "org.mitk.services.UltrasoundDevice)("
+ mitk::USDevice::GetPropertyKeys().US_PROPKEY_ISACTIVE + "=true))";
m_Controls.m_ActiveVideoDevices->Initialize<mitk::USDevice>(
mitk::USDevice::GetPropertyKeys().US_PROPKEY_LABEL ,filter);
m_Node = this->GetDataStorage()->GetNamedNode("US Image Stream");
if (m_Node.IsNull())
{
// Create Node for US Stream
m_Node = mitk::DataNode::New();
m_Node->SetName("US Image Stream");
this->GetDataStorage()->Add(m_Node);
}
m_Controls.tabWidget->setTabEnabled(1, false);
}
void UltrasoundSupport::OnClickedAddNewDevice()
{
m_Controls.m_NewVideoDeviceWidget->setVisible(true);
m_Controls.m_DeviceManagerWidget->setVisible(false);
m_Controls.m_Headline->setText("Add New Video Device:");
m_Controls.m_WidgetActiveDevices->setVisible(false);
}
void UltrasoundSupport::DisplayImage()
{
m_Device->Modified();
m_Device->Update();
mitk::Image::Pointer curOutput = m_Device->GetOutput();
if (! m_ImageAlreadySetToNode && curOutput.IsNotNull() && curOutput->IsInitialized())
{
m_Node->SetData(curOutput);
m_ImageAlreadySetToNode = true;
}
/*if ( curOutput.GetPointer() != m_Node->GetData() )
{
MITK_INFO << "Data Node of the ultrasound image stream was changed by another plugin. Stop viewing.";
this->StopViewing();
return;
}*/
this->RequestRenderWindowUpdate();
if ( curOutput->GetDimension() > 1
&& (curOutput->GetDimension(0) != m_CurrentImageWidth
|| curOutput->GetDimension(1) != m_CurrentImageHeight) )
{
// make a reinit on the ultrasound image
mitk::IRenderWindowPart* renderWindow = this->GetRenderWindowPart();
if ( renderWindow != NULL && curOutput->GetTimeGeometry()->IsValid() )
{
renderWindow->GetRenderingManager()->InitializeViews(
curOutput->GetTimeGeometry(), mitk::RenderingManager::REQUEST_UPDATE_ALL, true );
renderWindow->GetRenderingManager()->RequestUpdateAll();
}
m_CurrentImageWidth = curOutput->GetDimension(0);
m_CurrentImageHeight = curOutput->GetDimension(1);
}
m_FrameCounter ++;
if (m_FrameCounter == 10)
{
int nMilliseconds = m_Clock.restart();
int fps = 10000.0f / (nMilliseconds );
m_Controls.m_FramerateLabel->setText("Current Framerate: "+ QString::number(fps) +" FPS");
m_FrameCounter = 0;
}
}
void UltrasoundSupport::OnClickedViewDevice()
{
m_FrameCounter = 0;
// We use the activity state of the timer to determine whether we are currently viewing images
if ( ! m_Timer->isActive() ) // Activate Imaging
{
this->StartViewing();
}
else //deactivate imaging
{
this->StopViewing();
}
}
void UltrasoundSupport::OnChangedFramerateLimit(int value)
{
m_Timer->setInterval(1000 / value);
}
void UltrasoundSupport::OnClickedFreezeButton()
{
if ( m_Device->GetIsFreezed() )
{
m_Device->SetIsFreezed(false);
m_Controls.m_FreezeButton->setText("Freeze");
}
else
{
m_Device->SetIsFreezed(true);
m_Controls.m_FreezeButton->setText("Start Viewing Again");
}
}
void UltrasoundSupport::OnNewDeviceWidgetDone()
{
m_Controls.m_NewVideoDeviceWidget->setVisible(false);
m_Controls.m_DeviceManagerWidget->setVisible(true);
m_Controls.m_Headline->setText("Ultrasound Devices:");
m_Controls.m_WidgetActiveDevices->setVisible(true);
}
void UltrasoundSupport::StartViewing()
{
m_ImageAlreadySetToNode = false;
m_Controls.tabWidget->setTabEnabled(1, true);
m_Controls.tabWidget->setCurrentIndex(1);
//get device & set data node
m_Device = m_Controls.m_ActiveVideoDevices->GetSelectedService<mitk::USDevice>();
if (m_Device.IsNull())
{
m_Timer->stop();
return;
}
//start timer
int interval = (1000 / m_Controls.m_FrameRate->value());
m_Timer->setInterval(interval);
m_Timer->start();
//change UI elements
m_Controls.m_BtnView->setText("Stop Viewing");
this->CreateControlWidgets();
}
void UltrasoundSupport::StopViewing()
{
m_Controls.tabWidget->setTabEnabled(1, false);
this->RemoveControlWidgets();
//stop timer & release data
m_Timer->stop();
m_Node->ReleaseData();
this->RequestRenderWindowUpdate();
//change UI elements
m_Controls.m_BtnView->setText("Start Viewing");
}
void UltrasoundSupport::CreateControlWidgets()
{
m_ControlProbesWidget = new QmitkUSControlsProbesWidget(m_Device->GetControlInterfaceProbes(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.probesWidgetContainer->addWidget(m_ControlProbesWidget);
// create b mode widget for current device
m_ControlBModeWidget = new QmitkUSControlsBModeWidget(m_Device->GetControlInterfaceBMode(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlBModeWidget, "B Mode Controls");
if ( ! m_Device->GetControlInterfaceBMode() )
{
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
// create doppler widget for current device
m_ControlDopplerWidget = new QmitkUSControlsDopplerWidget(m_Device->GetControlInterfaceDoppler(), m_Controls.m_ToolBoxControlWidgets);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlDopplerWidget, "Doppler Controls");
if ( ! m_Device->GetControlInterfaceDoppler() )
{
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
if ( pluginContext )
{
std::string filter = "(ork.mitk.services.UltrasoundCustomWidget.deviceClass=" + m_Device->GetDeviceClass() + ")";
QString interfaceName ( us_service_interface_iid<QmitkUSAbstractCustomWidget>() );
m_CustomWidgetServiceReference = pluginContext->getServiceReferences(interfaceName, QString::fromStdString(filter));
if (m_CustomWidgetServiceReference.size() > 0)
{
m_ControlCustomWidget = pluginContext->getService<QmitkUSAbstractCustomWidget>
(m_CustomWidgetServiceReference.at(0))->CloneForQt(m_Controls.tab2);
m_ControlCustomWidget->SetDevice(m_Device);
m_Controls.m_ToolBoxControlWidgets->addItem(m_ControlCustomWidget, "Custom Controls");
}
else
{
m_Controls.m_ToolBoxControlWidgets->addItem(new QWidget(m_Controls.m_ToolBoxControlWidgets), "Custom Controls");
m_Controls.m_ToolBoxControlWidgets->setItemEnabled(m_Controls.m_ToolBoxControlWidgets->count()-1, false);
}
}
// select first enabled control widget
for ( int n = 0; n < m_Controls.m_ToolBoxControlWidgets->count(); ++n)
{
if ( m_Controls.m_ToolBoxControlWidgets->isItemEnabled(n) )
{
m_Controls.m_ToolBoxControlWidgets->setCurrentIndex(n);
break;
}
}
}
void UltrasoundSupport::RemoveControlWidgets()
{
// remove all control widgets from the tool box widget
while (m_Controls.m_ToolBoxControlWidgets->count() > 0)
{
m_Controls.m_ToolBoxControlWidgets->removeItem(0);
}
// remove probes widget (which is not part of the tool box widget)
m_Controls.probesWidgetContainer->removeWidget(m_ControlProbesWidget);
delete m_ControlProbesWidget;
m_ControlProbesWidget = 0;
delete m_ControlBModeWidget;
m_ControlBModeWidget = 0;
delete m_ControlDopplerWidget;
m_ControlDopplerWidget = 0;
// delete custom widget if it is present
if ( m_ControlCustomWidget )
{
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
delete m_ControlCustomWidget; m_ControlCustomWidget = 0;
if ( m_CustomWidgetServiceReference.size() > 0 )
{
pluginContext->ungetService(m_CustomWidgetServiceReference.at(0));
}
}
}
void UltrasoundSupport::OnDeciveServiceEvent(const ctkServiceEvent event)
{
if ( m_Device.IsNull() || event.getType() != us::ServiceEvent::MODIFIED ) { return; }
ctkServiceReference service = event.getServiceReference();
if ( m_Device->GetDeviceManufacturer() != service.getProperty(mitk::USImageMetadata::PROP_DEV_MANUFACTURER).toString().toStdString()
&& m_Device->GetDeviceModel() != service.getProperty(mitk::USImageMetadata::PROP_DEV_MODEL).toString().toStdString() )
{
return;
}
if ( ! m_Device->GetIsActive() && m_Timer->isActive() )
{
this->StopViewing();
}
}
UltrasoundSupport::UltrasoundSupport()
: m_ControlCustomWidget(0), m_ControlBModeWidget(0),
m_ControlProbesWidget(0), m_ImageAlreadySetToNode(false),
m_CurrentImageWidth(0), m_CurrentImageHeight(0)
{
ctkPluginContext* pluginContext = mitk::PluginActivator::GetContext();
if ( pluginContext )
{
// to be notified about service event of an USDevice
pluginContext->connectServiceListener(this, "OnDeciveServiceEvent",
QString::fromStdString("(" + us::ServiceConstants::OBJECTCLASS() + "=" + us_service_interface_iid<mitk::USDevice>() + ")"));
}
}
UltrasoundSupport::~UltrasoundSupport()
{
}
<|endoftext|>
|
<commit_before>
/*
* Stream.cpp
* sfeMovie project
*
* Copyright (C) 2010-2014 Lucas Soltic
* lucas.soltic@orange.fr
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
extern "C"
{
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
#include <stdint.h>
}
#include "Demuxer.hpp"
#include "VideoStream.hpp"
#include "AudioStream.hpp"
#include "SubtitleStream.hpp"
#include "Log.hpp"
#include "Utilities.hpp"
#include <iostream>
#include <stdexcept>
namespace sfe
{
std::list<Demuxer::DemuxerInfo> Demuxer::g_availableDemuxers;
std::list<Demuxer::DecoderInfo> Demuxer::g_availableDecoders;
static void loadFFmpeg()
{
ONCE(av_register_all());
ONCE(avcodec_register_all());
ONCE(Log::initialize());
}
static MediaType AVMediaTypeToMediaType(AVMediaType type)
{
switch (type)
{
case AVMEDIA_TYPE_AUDIO: return Audio;
case AVMEDIA_TYPE_SUBTITLE: return Subtitle;
case AVMEDIA_TYPE_VIDEO: return Video;
default: return Unknown;
}
}
const std::list<Demuxer::DemuxerInfo>& Demuxer::getAvailableDemuxers()
{
AVInputFormat* demuxer = NULL;
loadFFmpeg();
if (g_availableDemuxers.empty())
{
while (NULL != (demuxer = av_iformat_next(demuxer)))
{
DemuxerInfo info =
{
std::string(demuxer->name),
std::string(demuxer->long_name)
};
g_availableDemuxers.push_back(info);
}
}
return g_availableDemuxers;
}
const std::list<Demuxer::DecoderInfo>& Demuxer::getAvailableDecoders()
{
AVCodec* codec = NULL;
loadFFmpeg();
if (g_availableDecoders.empty())
{
while (NULL != (codec = av_codec_next(codec)))
{
DecoderInfo info =
{
avcodec_get_name(codec->id),
codec->long_name,
AVMediaTypeToMediaType(codec->type)
};
g_availableDecoders.push_back(info);
}
}
return g_availableDecoders;
}
Demuxer::Demuxer(const std::string& sourceFile, Timer& timer, VideoStream::Delegate& videoDelegate, SubtitleStream::Delegate& subtitleDelegate) :
m_formatCtx(NULL),
m_eofReached(false),
m_streams(),
m_ignoredStreams(),
m_synchronized(),
m_timer(timer),
m_connectedAudioStream(NULL),
m_connectedVideoStream(NULL),
m_duration(sf::Time::Zero)
{
CHECK(sourceFile.size(), "Demuxer::Demuxer() - invalid argument: sourceFile");
int err = 0;
// Load all the decoders
loadFFmpeg();
// Open the movie file
err = avformat_open_input(&m_formatCtx, sourceFile.c_str(), NULL, NULL);
CHECK0(err, "Demuxer::Demuxer() - error while opening media: " + sourceFile);
CHECK(m_formatCtx, "Demuxer() - inconsistency: media context cannot be null");
// Read the general movie informations
err = avformat_find_stream_info(m_formatCtx, NULL);
CHECK0(err, "Demuxer::Demuxer() - error while retreiving media information");
// Get the media duration if possible (otherwise rely on the streams)
if (m_formatCtx->duration != AV_NOPTS_VALUE)
{
long secs, us;
secs = m_formatCtx->duration / AV_TIME_BASE;
us = m_formatCtx->duration % AV_TIME_BASE;
m_duration = sf::seconds(secs + (float)us / AV_TIME_BASE);
}
// Find all interesting streams
for (unsigned int i = 0; i < m_formatCtx->nb_streams; i++)
{
AVStream* ffstream = m_formatCtx->streams[i];
try
{
switch (ffstream->codec->codec_type)
{
case AVMEDIA_TYPE_VIDEO:
m_streams[ffstream->index] = new VideoStream(m_formatCtx, ffstream, *this, timer, videoDelegate);
if (m_duration == sf::Time::Zero)
{
extractDurationFromStream(ffstream);
}
sfeLogDebug("Loaded " + avcodec_get_name(ffstream->codec->codec_id) + " video stream");
break;
case AVMEDIA_TYPE_AUDIO:
m_streams[ffstream->index] = new AudioStream(m_formatCtx, ffstream, *this, timer);
if (m_duration == sf::Time::Zero)
{
extractDurationFromStream(ffstream);
}
sfeLogDebug("Loaded " + avcodec_get_name(ffstream->codec->codec_id) + " audio stream");
break;
case AVMEDIA_TYPE_SUBTITLE:
m_streams[ffstream->index] = new SubtitleStream(m_formatCtx, ffstream, *this, timer, subtitleDelegate);
if (m_duration == sf::Time::Zero)
{
extractDurationFromStream(ffstream);
}
sfeLogDebug("Loaded " + avcodec_get_name(ffstream->codec->codec_id) + " subtitle stream");
break;
default:
m_ignoredStreams[ffstream->index] = std::string("'" + std::string(av_get_media_type_string(ffstream->codec->codec_type)) + "/" + avcodec_get_name(ffstream->codec->codec_id));
sfeLogDebug(m_ignoredStreams[ffstream->index] + "' stream ignored");
break;
}
} catch (std::runtime_error& e)
{
std::cerr << "Demuxer::Demuxer() - " << e.what() << std::endl;
}
}
if (m_duration == sf::Time::Zero)
{
sfeLogWarning("The media duration could not be retreived");
}
m_timer.addObserver(*this);
}
Demuxer::~Demuxer()
{
if (m_timer.getStatus() != Stopped)
m_timer.stop();
m_timer.removeObserver(*this);
while (m_streams.size())
{
delete m_streams.begin()->second;
m_streams.erase(m_streams.begin());
}
if (m_formatCtx)
{
avformat_close_input(&m_formatCtx);
}
}
const std::map<int, Stream*>& Demuxer::getStreams() const
{
return m_streams;
}
std::set<Stream*> Demuxer::getStreamsOfType(MediaType type) const
{
std::set<Stream*> streamSet;
std::map<int, Stream*>::const_iterator it;
for (it = m_streams.begin(); it != m_streams.end(); it++)
{
if (it->second->getStreamKind() == type)
streamSet.insert(it->second);
}
return streamSet;
}
Streams Demuxer::computeStreamDescriptors(MediaType type) const
{
Streams entries;
std::set<Stream*> streamSet;
std::map<int, Stream*>::const_iterator it;
for (it = m_streams.begin(); it != m_streams.end(); it++)
{
if (it->second->getStreamKind() == type)
{
StreamDescriptor entry;
entry.type = type;
entry.identifier = it->first;
entry.language = it->second->getLanguage();
entries.push_back(entry);
}
}
return entries;
}
void Demuxer::selectAudioStream(AudioStream* stream)
{
Status oldStatus = m_timer.getStatus();
CHECK(oldStatus == Stopped, "Changing the selected stream after starting "
"the movie playback isn't supported yet");
if (oldStatus == Playing)
m_timer.pause();
if (stream != m_connectedAudioStream)
{
if (m_connectedAudioStream)
{
m_connectedAudioStream->disconnect();
}
if (stream)
stream->connect();
m_connectedAudioStream = stream;
}
if (oldStatus == Playing)
m_timer.play();
}
void Demuxer::selectFirstAudioStream()
{
std::set<Stream*> audioStreams = getStreamsOfType(Audio);
if (audioStreams.size())
selectAudioStream(dynamic_cast<AudioStream*>(*audioStreams.begin()));
}
AudioStream* Demuxer::getSelectedAudioStream() const
{
return dynamic_cast<AudioStream*>(m_connectedAudioStream);
}
void Demuxer::selectVideoStream(VideoStream* stream)
{
Status oldStatus = m_timer.getStatus();
CHECK(oldStatus == Stopped, "Changing the selected stream after starting "
"the movie playback isn't supported yet");
if (oldStatus == Playing)
m_timer.pause();
if (stream != m_connectedVideoStream)
{
if (m_connectedVideoStream)
{
m_connectedVideoStream->disconnect();
}
if (stream)
stream->connect();
m_connectedVideoStream = stream;
}
if (oldStatus == Playing)
m_timer.play();
}
void Demuxer::selectFirstVideoStream()
{
std::set<Stream*> videoStreams = getStreamsOfType(Video);
if (videoStreams.size())
selectVideoStream(dynamic_cast<VideoStream*>(*videoStreams.begin()));
}
VideoStream* Demuxer::getSelectedVideoStream() const
{
return dynamic_cast<VideoStream*>(m_connectedVideoStream);
}
void Demuxer::selectSubtitleStream(SubtitleStream* stream)
{
Status oldStatus = m_timer.getStatus();
if (oldStatus == Playing)
m_timer.pause();
if (stream != m_connectedSubtitleStream)
{
if (m_connectedSubtitleStream)
m_connectedSubtitleStream->disconnect();
if (stream)
stream->connect();
m_connectedSubtitleStream = stream;
}
if (oldStatus == Playing)
m_timer.play();
}
void Demuxer::selectFirstSubtitleStream()
{
std::set<Stream*> subtitleStreams = getStreamsOfType(Subtitle);
if (subtitleStreams.size())
selectSubtitleStream(dynamic_cast<SubtitleStream*>(*subtitleStreams.begin()));
}
SubtitleStream* Demuxer::getSelectedSubtitleStream() const
{
return dynamic_cast<SubtitleStream*>(m_connectedSubtitleStream);
}
void Demuxer::feedStream(Stream& stream)
{
sf::Lock l(m_synchronized);
sfeLogDebug("Feed " + mediaTypeToString(stream.getStreamKind()) + " stream");
while (!didReachEndOfFile() && stream.needsMoreData())
{
AVPacket* pkt = readPacket();
if (!pkt)
{
m_eofReached = true;
}
else
{
if (!distributePacket(pkt))
{
sfeLogWarning(m_ignoredStreams[pkt->stream_index] + " packet not handled and dropped");
av_free_packet(pkt);
av_free(pkt);
}
}
}
}
void Demuxer::update()
{
std::map<int, Stream*> streams = getStreams();
std::map<int, Stream*>::iterator it;
for (it = streams.begin();it != streams.end(); it++)
{
it->second->update();
}
}
bool Demuxer::didReachEndOfFile() const
{
return m_eofReached;
}
sf::Time Demuxer::getDuration() const
{
return m_duration;
}
AVPacket* Demuxer::readPacket()
{
sf::Lock l(m_synchronized);
AVPacket *pkt = NULL;
int err = 0;
pkt = (AVPacket *)av_malloc(sizeof(*pkt));
CHECK(pkt, "Demuxer::readPacket() - out of memory");
av_init_packet(pkt);
err = av_read_frame(m_formatCtx, pkt);
if (err < 0)
{
av_free_packet(pkt);
av_free(pkt);
pkt = NULL;
}
return pkt;
}
bool Demuxer::distributePacket(AVPacket* packet)
{
sf::Lock l(m_synchronized);
CHECK(packet, "Demuxer::distributePacket() - invalid argument");
bool result = false;
std::map<int, Stream*>::iterator it = m_streams.find(packet->stream_index);
if (it != m_streams.end())
{
it->second->pushEncodedData(packet);
result = true;
}
return result;
}
void Demuxer::extractDurationFromStream(AVStream* stream)
{
if (m_duration != sf::Time::Zero)
return;
if (stream->duration != AV_NOPTS_VALUE)
{
long secs, us;
secs = stream->duration / AV_TIME_BASE;
us = stream->duration % AV_TIME_BASE;
m_duration = sf::seconds(secs + (float)us / AV_TIME_BASE);
}
}
void Demuxer::requestMoreData(Stream& starvingStream)
{
sf::Lock l(m_synchronized);
feedStream(starvingStream);
}
void Demuxer::resetEndOfFileStatus()
{
m_eofReached = false;
}
void Demuxer::willSeek(const Timer &timer, sf::Time position)
{
resetEndOfFileStatus();
if (m_formatCtx->iformat->flags & AVFMT_SEEK_TO_PTS)
{
int64_t timestamp = 0;
if (m_formatCtx->start_time != AV_NOPTS_VALUE)
timestamp += m_formatCtx->start_time;
int err = avformat_seek_file(m_formatCtx, -1, INT64_MIN, timestamp, INT64_MAX, AVSEEK_FLAG_BACKWARD);
sfeLogDebug("Seek by PTS at timestamp=" + s(timestamp) + " returned " + s(err));
}
else
{
int err = avformat_seek_file(m_formatCtx, -1, INT64_MIN, 0, INT64_MAX, AVSEEK_FLAG_BACKWARD);
// sfeLogDebug("Seek by PTS at timestamp=" + s(timestamp) + " returned " + s(err));
// int err = av_seek_frame(m_formatCtx, m_streamID, -999999, AVSEEK_FLAG_BACKWARD);
sfeLogDebug("Seek by DTS at timestamp " + s(-9999) + " returned " + s(err));
}
}
}
<commit_msg>#7 Fixed a bug that would cause sfeMovie to crash (subtitleStream didn't get initialized, so getSelectedSubtitleStream() would crash)<commit_after>
/*
* Stream.cpp
* sfeMovie project
*
* Copyright (C) 2010-2014 Lucas Soltic
* lucas.soltic@orange.fr
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
extern "C"
{
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
#include <stdint.h>
}
#include "Demuxer.hpp"
#include "VideoStream.hpp"
#include "AudioStream.hpp"
#include "SubtitleStream.hpp"
#include "Log.hpp"
#include "Utilities.hpp"
#include <iostream>
#include <stdexcept>
namespace sfe
{
std::list<Demuxer::DemuxerInfo> Demuxer::g_availableDemuxers;
std::list<Demuxer::DecoderInfo> Demuxer::g_availableDecoders;
static void loadFFmpeg()
{
ONCE(av_register_all());
ONCE(avcodec_register_all());
ONCE(Log::initialize());
}
static MediaType AVMediaTypeToMediaType(AVMediaType type)
{
switch (type)
{
case AVMEDIA_TYPE_AUDIO: return Audio;
case AVMEDIA_TYPE_SUBTITLE: return Subtitle;
case AVMEDIA_TYPE_VIDEO: return Video;
default: return Unknown;
}
}
const std::list<Demuxer::DemuxerInfo>& Demuxer::getAvailableDemuxers()
{
AVInputFormat* demuxer = NULL;
loadFFmpeg();
if (g_availableDemuxers.empty())
{
while (NULL != (demuxer = av_iformat_next(demuxer)))
{
DemuxerInfo info =
{
std::string(demuxer->name),
std::string(demuxer->long_name)
};
g_availableDemuxers.push_back(info);
}
}
return g_availableDemuxers;
}
const std::list<Demuxer::DecoderInfo>& Demuxer::getAvailableDecoders()
{
AVCodec* codec = NULL;
loadFFmpeg();
if (g_availableDecoders.empty())
{
while (NULL != (codec = av_codec_next(codec)))
{
DecoderInfo info =
{
avcodec_get_name(codec->id),
codec->long_name,
AVMediaTypeToMediaType(codec->type)
};
g_availableDecoders.push_back(info);
}
}
return g_availableDecoders;
}
Demuxer::Demuxer(const std::string& sourceFile, Timer& timer, VideoStream::Delegate& videoDelegate, SubtitleStream::Delegate& subtitleDelegate) :
m_formatCtx(NULL),
m_eofReached(false),
m_streams(),
m_ignoredStreams(),
m_synchronized(),
m_timer(timer),
m_connectedAudioStream(NULL),
m_connectedVideoStream(NULL),
m_connectedSubtitleStream(NULL),
m_duration(sf::Time::Zero)
{
CHECK(sourceFile.size(), "Demuxer::Demuxer() - invalid argument: sourceFile");
int err = 0;
// Load all the decoders
loadFFmpeg();
// Open the movie file
err = avformat_open_input(&m_formatCtx, sourceFile.c_str(), NULL, NULL);
CHECK0(err, "Demuxer::Demuxer() - error while opening media: " + sourceFile);
CHECK(m_formatCtx, "Demuxer() - inconsistency: media context cannot be null");
// Read the general movie informations
err = avformat_find_stream_info(m_formatCtx, NULL);
CHECK0(err, "Demuxer::Demuxer() - error while retreiving media information");
// Get the media duration if possible (otherwise rely on the streams)
if (m_formatCtx->duration != AV_NOPTS_VALUE)
{
long secs, us;
secs = m_formatCtx->duration / AV_TIME_BASE;
us = m_formatCtx->duration % AV_TIME_BASE;
m_duration = sf::seconds(secs + (float)us / AV_TIME_BASE);
}
// Find all interesting streams
for (unsigned int i = 0; i < m_formatCtx->nb_streams; i++)
{
AVStream* ffstream = m_formatCtx->streams[i];
try
{
switch (ffstream->codec->codec_type)
{
case AVMEDIA_TYPE_VIDEO:
m_streams[ffstream->index] = new VideoStream(m_formatCtx, ffstream, *this, timer, videoDelegate);
if (m_duration == sf::Time::Zero)
{
extractDurationFromStream(ffstream);
}
sfeLogDebug("Loaded " + avcodec_get_name(ffstream->codec->codec_id) + " video stream");
break;
case AVMEDIA_TYPE_AUDIO:
m_streams[ffstream->index] = new AudioStream(m_formatCtx, ffstream, *this, timer);
if (m_duration == sf::Time::Zero)
{
extractDurationFromStream(ffstream);
}
sfeLogDebug("Loaded " + avcodec_get_name(ffstream->codec->codec_id) + " audio stream");
break;
case AVMEDIA_TYPE_SUBTITLE:
m_streams[ffstream->index] = new SubtitleStream(m_formatCtx, ffstream, *this, timer, subtitleDelegate);
if (m_duration == sf::Time::Zero)
{
extractDurationFromStream(ffstream);
}
sfeLogDebug("Loaded " + avcodec_get_name(ffstream->codec->codec_id) + " subtitle stream");
break;
default:
m_ignoredStreams[ffstream->index] = std::string("'" + std::string(av_get_media_type_string(ffstream->codec->codec_type)) + "/" + avcodec_get_name(ffstream->codec->codec_id));
sfeLogDebug(m_ignoredStreams[ffstream->index] + "' stream ignored");
break;
}
} catch (std::runtime_error& e)
{
std::cerr << "Demuxer::Demuxer() - " << e.what() << std::endl;
}
}
if (m_duration == sf::Time::Zero)
{
sfeLogWarning("The media duration could not be retreived");
}
m_timer.addObserver(*this);
}
Demuxer::~Demuxer()
{
if (m_timer.getStatus() != Stopped)
m_timer.stop();
m_timer.removeObserver(*this);
while (m_streams.size())
{
delete m_streams.begin()->second;
m_streams.erase(m_streams.begin());
}
if (m_formatCtx)
{
avformat_close_input(&m_formatCtx);
}
}
const std::map<int, Stream*>& Demuxer::getStreams() const
{
return m_streams;
}
std::set<Stream*> Demuxer::getStreamsOfType(MediaType type) const
{
std::set<Stream*> streamSet;
std::map<int, Stream*>::const_iterator it;
for (it = m_streams.begin(); it != m_streams.end(); it++)
{
if (it->second->getStreamKind() == type)
streamSet.insert(it->second);
}
return streamSet;
}
Streams Demuxer::computeStreamDescriptors(MediaType type) const
{
Streams entries;
std::set<Stream*> streamSet;
std::map<int, Stream*>::const_iterator it;
for (it = m_streams.begin(); it != m_streams.end(); it++)
{
if (it->second->getStreamKind() == type)
{
StreamDescriptor entry;
entry.type = type;
entry.identifier = it->first;
entry.language = it->second->getLanguage();
entries.push_back(entry);
}
}
return entries;
}
void Demuxer::selectAudioStream(AudioStream* stream)
{
Status oldStatus = m_timer.getStatus();
CHECK(oldStatus == Stopped, "Changing the selected stream after starting "
"the movie playback isn't supported yet");
if (oldStatus == Playing)
m_timer.pause();
if (stream != m_connectedAudioStream)
{
if (m_connectedAudioStream)
{
m_connectedAudioStream->disconnect();
}
if (stream)
stream->connect();
m_connectedAudioStream = stream;
}
if (oldStatus == Playing)
m_timer.play();
}
void Demuxer::selectFirstAudioStream()
{
std::set<Stream*> audioStreams = getStreamsOfType(Audio);
if (audioStreams.size())
selectAudioStream(dynamic_cast<AudioStream*>(*audioStreams.begin()));
}
AudioStream* Demuxer::getSelectedAudioStream() const
{
return dynamic_cast<AudioStream*>(m_connectedAudioStream);
}
void Demuxer::selectVideoStream(VideoStream* stream)
{
Status oldStatus = m_timer.getStatus();
CHECK(oldStatus == Stopped, "Changing the selected stream after starting "
"the movie playback isn't supported yet");
if (oldStatus == Playing)
m_timer.pause();
if (stream != m_connectedVideoStream)
{
if (m_connectedVideoStream)
{
m_connectedVideoStream->disconnect();
}
if (stream)
stream->connect();
m_connectedVideoStream = stream;
}
if (oldStatus == Playing)
m_timer.play();
}
void Demuxer::selectFirstVideoStream()
{
std::set<Stream*> videoStreams = getStreamsOfType(Video);
if (videoStreams.size())
selectVideoStream(dynamic_cast<VideoStream*>(*videoStreams.begin()));
}
VideoStream* Demuxer::getSelectedVideoStream() const
{
return dynamic_cast<VideoStream*>(m_connectedVideoStream);
}
void Demuxer::selectSubtitleStream(SubtitleStream* stream)
{
Status oldStatus = m_timer.getStatus();
if (oldStatus == Playing)
m_timer.pause();
if (stream != m_connectedSubtitleStream)
{
if (m_connectedSubtitleStream)
m_connectedSubtitleStream->disconnect();
if (stream)
stream->connect();
m_connectedSubtitleStream = stream;
}
if (oldStatus == Playing)
m_timer.play();
}
void Demuxer::selectFirstSubtitleStream()
{
std::set<Stream*> subtitleStreams = getStreamsOfType(Subtitle);
if (subtitleStreams.size())
selectSubtitleStream(dynamic_cast<SubtitleStream*>(*subtitleStreams.begin()));
}
SubtitleStream* Demuxer::getSelectedSubtitleStream() const
{
return dynamic_cast<SubtitleStream*>(m_connectedSubtitleStream);
}
void Demuxer::feedStream(Stream& stream)
{
sf::Lock l(m_synchronized);
sfeLogDebug("Feed " + mediaTypeToString(stream.getStreamKind()) + " stream");
while (!didReachEndOfFile() && stream.needsMoreData())
{
AVPacket* pkt = readPacket();
if (!pkt)
{
m_eofReached = true;
}
else
{
if (!distributePacket(pkt))
{
sfeLogWarning(m_ignoredStreams[pkt->stream_index] + " packet not handled and dropped");
av_free_packet(pkt);
av_free(pkt);
}
}
}
}
void Demuxer::update()
{
std::map<int, Stream*> streams = getStreams();
std::map<int, Stream*>::iterator it;
for (it = streams.begin();it != streams.end(); it++)
{
it->second->update();
}
}
bool Demuxer::didReachEndOfFile() const
{
return m_eofReached;
}
sf::Time Demuxer::getDuration() const
{
return m_duration;
}
AVPacket* Demuxer::readPacket()
{
sf::Lock l(m_synchronized);
AVPacket *pkt = NULL;
int err = 0;
pkt = (AVPacket *)av_malloc(sizeof(*pkt));
CHECK(pkt, "Demuxer::readPacket() - out of memory");
av_init_packet(pkt);
err = av_read_frame(m_formatCtx, pkt);
if (err < 0)
{
av_free_packet(pkt);
av_free(pkt);
pkt = NULL;
}
return pkt;
}
bool Demuxer::distributePacket(AVPacket* packet)
{
sf::Lock l(m_synchronized);
CHECK(packet, "Demuxer::distributePacket() - invalid argument");
bool result = false;
std::map<int, Stream*>::iterator it = m_streams.find(packet->stream_index);
if (it != m_streams.end())
{
it->second->pushEncodedData(packet);
result = true;
}
return result;
}
void Demuxer::extractDurationFromStream(AVStream* stream)
{
if (m_duration != sf::Time::Zero)
return;
if (stream->duration != AV_NOPTS_VALUE)
{
long secs, us;
secs = stream->duration / AV_TIME_BASE;
us = stream->duration % AV_TIME_BASE;
m_duration = sf::seconds(secs + (float)us / AV_TIME_BASE);
}
}
void Demuxer::requestMoreData(Stream& starvingStream)
{
sf::Lock l(m_synchronized);
feedStream(starvingStream);
}
void Demuxer::resetEndOfFileStatus()
{
m_eofReached = false;
}
void Demuxer::willSeek(const Timer &timer, sf::Time position)
{
resetEndOfFileStatus();
if (m_formatCtx->iformat->flags & AVFMT_SEEK_TO_PTS)
{
int64_t timestamp = 0;
if (m_formatCtx->start_time != AV_NOPTS_VALUE)
timestamp += m_formatCtx->start_time;
int err = avformat_seek_file(m_formatCtx, -1, INT64_MIN, timestamp, INT64_MAX, AVSEEK_FLAG_BACKWARD);
sfeLogDebug("Seek by PTS at timestamp=" + s(timestamp) + " returned " + s(err));
}
else
{
int err = avformat_seek_file(m_formatCtx, -1, INT64_MIN, 0, INT64_MAX, AVSEEK_FLAG_BACKWARD);
// sfeLogDebug("Seek by PTS at timestamp=" + s(timestamp) + " returned " + s(err));
// int err = av_seek_frame(m_formatCtx, m_streamID, -999999, AVSEEK_FLAG_BACKWARD);
sfeLogDebug("Seek by DTS at timestamp " + s(-9999) + " returned " + s(err));
}
}
}
<|endoftext|>
|
<commit_before>#include "GraphML.h"
#include "DirectedGraph.h"
#include "UndirectedGraph.h"
#include <tinyxml2.h>
#include <Table.h>
#include <cassert>
#include <map>
#include <iostream>
using namespace std;
using namespace tinyxml2;
GraphML::GraphML() : FileTypeHandler("GraphML", true) {
addExtension("graphml");
}
std::shared_ptr<Graph>
GraphML::openGraph(const char * filename, const std::shared_ptr<NodeArray> & initial_nodes) {
RenderMode mode = RENDERMODE_3D;
XMLDocument doc;
doc.LoadFile(filename);
XMLElement * graphml_element = doc.FirstChildElement("graphml");
assert(graphml_element);
XMLElement * graph_element = graphml_element->FirstChildElement("graph");
assert(graph_element);
map<string, int> nodes_by_id;
const char * edgedefault = graph_element->Attribute("edgedefault");
bool directed = true;
if (edgedefault && strcmp(edgedefault, "undirected") == 0) {
directed = false;
}
std::shared_ptr<Graph> graph;
if (directed) {
graph = std::make_shared<DirectedGraph>();
graph->setNodeArray(initial_nodes);
graph->getNodeArray().setNodeSizeMethod(SizeMethod(SizeMethod::SIZE_FROM_INDEGREE));
} else {
graph = std::make_shared<UndirectedGraph>();
graph->setNodeArray(initial_nodes);
graph->getNodeArray().setNodeSizeMethod(SizeMethod(SizeMethod::SIZE_FROM_DEGREE));
}
graph->getNodeArray().setFlattenHierarchy(true);
auto & node_table = graph->getNodeArray().getTable();
auto & edge_table = graph->getFaceData();
XMLElement * key_element = graphml_element->FirstChildElement("key");
for ( ; key_element ; key_element = key_element->NextSiblingElement("key") ) {
const char * key_type = key_element->Attribute("attr.type");
const char * key_id = key_element->Attribute("id");
const char * for_type = key_element->Attribute("for");
const char * name = key_element->Attribute("attr.name");
assert(key_type && key_id && for_type);
std::shared_ptr<table::Column> column;
if (strcmp(key_type, "string") == 0) {
column = std::make_shared<table::ColumnText>(key_id ? key_id : "");
} else if (strcmp(key_type, "double") == 0 || strcmp(key_type, "float") == 0) {
column = std::make_shared<table::ColumnDouble>(key_id ? key_id : "");
} else if (strcmp(key_type, "int") == 0) {
column = std::make_shared<table::ColumnInt>(key_id ? key_id : "");
} else {
assert(0);
}
if (strcmp(for_type, "node") == 0) {
node_table.addColumn(column);
} else if (strcmp(for_type, "edge") == 0) {
edge_table.addColumn(column);
} else {
assert(0);
}
}
createGraphFromElement(*graph, *graphml_element, *graph_element, nodes_by_id, directed);
graph->updateAppearance();
graph->randomizeGeometry();
// graph->setComplexGraph(is_complex);
// graph->setHasSubGraphs(is_complex);
return graph;
}
void
GraphML::createGraphFromElement(Graph & graph, XMLElement & graphml_element, XMLElement & graph_element, map<string, int> & nodes_by_id, bool is_directed, int parent_node_id) const {
auto & node_table = graph.getNodeArray().getTable();
auto & edge_table = graph.getFaceData();
auto & node_id_column = node_table.addTextColumn("id");
auto & edge_id_column = edge_table.addTextColumn("id");
XMLElement * node_element = graph_element.FirstChildElement("node");
for ( ; node_element ; node_element = node_element->NextSiblingElement("node") ) {
const char * node_id_text = node_element->Attribute("id");
assert(node_id_text);
int node_id = graph.addNode();
node_id_column.setValue(node_id, node_id_text);
nodes_by_id[node_id_text] = node_id + 1;
if (parent_node_id != -1) graph.addChild(parent_node_id, node_id);
XMLElement * data_element = node_element->FirstChildElement("data");
for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) {
const char * key = data_element->Attribute("key");
assert(key);
const char * text = data_element->GetText();
if (text) {
node_table[key].setValue(node_id, text);
}
}
XMLElement * nested_graph_element = node_element->FirstChildElement("graph");
if (nested_graph_element) {
createGraphFromElement(graph, graphml_element, *nested_graph_element, nodes_by_id, is_directed, node_id);
}
}
XMLElement * edge_element = graph_element.FirstChildElement("edge");
for ( ; edge_element ; edge_element = edge_element->NextSiblingElement("edge") ) {
const char * edge_id_text = edge_element->Attribute("id");
const char * source = edge_element->Attribute("source");
const char * target = edge_element->Attribute("target");
assert(source && target);
if (strcmp(source, target) == 0) {
cerr << "GraphML: skipping self link for " << source << endl;
continue;
}
int source_node = nodes_by_id[source];
int target_node = nodes_by_id[target];
if (source_node && target_node) {
int face_id = graph.addFace(-1);
int edge_id1 = graph.addEdge(source_node - 1, target_node - 1, face_id);
if (!is_directed) {
int edge_id2 = graph.addEdge(target_node - 1, source_node - 1, face_id);
graph.connectEdgePair(edge_id1, edge_id2);
}
if (edge_id_text && strlen(edge_id_text) != 0) {
edge_id_column.setValue(face_id, edge_id_text);
}
XMLElement * data_element = edge_element->FirstChildElement("data");
for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) {
const char * key = data_element->Attribute("key");
assert(key);
const char * text = data_element->GetText();
if (text) {
edge_table[key].setValue(face_id, text);
}
}
} else {
if (!source_node) {
// cerr << "cannot find node " << source << endl;
}
if (!target_node) {
// cerr << "cannot find node " << target << endl;
}
}
}
}
bool
GraphML::saveGraph(const Graph & graph, const std::string & filename) {
XMLDocument doc;
doc.LinkEndChild(doc.NewDeclaration());
XMLElement * graphml_element = doc.NewElement("graphml");
graphml_element->SetAttribute("xmlns", "http://graphml.graphdrawing.org/xmlns");
bool directed = graph.isDirected();
auto & node_table = graph.getNodeArray().getTable();
auto & edge_table = graph.getFaceData();
for (auto & col : node_table.getColumns()) {
XMLElement * key_element = doc.NewElement("key");
key_element->SetAttribute("attr.name", col.first.c_str());
key_element->SetAttribute("id", col.first.c_str());
key_element->SetAttribute("attr.type", col.second->getTypeText());
key_element->SetAttribute("for", "node");
graphml_element->LinkEndChild(key_element);
}
for (auto & col : edge_table.getColumns()) {
XMLElement * key_element = doc.NewElement("key");
key_element->SetAttribute("attr.name", col.first.c_str());
key_element->SetAttribute("id", col.first.c_str());
key_element->SetAttribute("attr.type", col.second->getTypeText());
key_element->SetAttribute("for", "edge");
graphml_element->LinkEndChild(key_element);
}
XMLElement * graph_element = doc.NewElement("graph");
graphml_element->LinkEndChild(graph_element);
if (!directed) {
graph_element->SetAttribute("edgedefault", "undirected");
}
for (unsigned int i = 0; i < graph.getNodeArray().size(); i++) {
XMLElement * node_element = doc.NewElement("node");
string node_id = "n" + to_string(i);
node_element->SetAttribute("id", node_id.c_str());
for (auto & col : node_table.getColumns()) {
XMLElement * data_element = doc.NewElement("data");
data_element->SetAttribute("key", col.first.c_str());
data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str()));
node_element->LinkEndChild(data_element);
}
graph_element->LinkEndChild(node_element);
}
for (unsigned int i = 0; i < graph.getFaceCount(); i++) {
XMLElement * edge_element = doc.NewElement("edge");
#if 0
auto edge = graph.getEdgeAttributes(i);
string node_id1 = "n" + to_string(edge.tail);
string node_id2 = "n" + to_string(edge.head);
// timestamp, sentiment
edge_element->SetAttribute("source", node_id1.c_str());
edge_element->SetAttribute("target", node_id2.c_str());
#endif
for (auto & col : edge_table.getColumns()) {
XMLElement * data_element = doc.NewElement("data");
data_element->SetAttribute("key", col.first.c_str());
data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str()));
edge_element->LinkEndChild(data_element);
}
graph_element->LinkEndChild(edge_element);
}
doc.LinkEndChild(graphml_element);
doc.SaveFile(filename.c_str());
return true;
}
<commit_msg>rename method call<commit_after>#include "GraphML.h"
#include "DirectedGraph.h"
#include "UndirectedGraph.h"
#include <tinyxml2.h>
#include <Table.h>
#include <cassert>
#include <map>
#include <iostream>
using namespace std;
using namespace tinyxml2;
GraphML::GraphML() : FileTypeHandler("GraphML", true) {
addExtension("graphml");
}
std::shared_ptr<Graph>
GraphML::openGraph(const char * filename, const std::shared_ptr<NodeArray> & initial_nodes) {
RenderMode mode = RENDERMODE_3D;
XMLDocument doc;
doc.LoadFile(filename);
XMLElement * graphml_element = doc.FirstChildElement("graphml");
assert(graphml_element);
XMLElement * graph_element = graphml_element->FirstChildElement("graph");
assert(graph_element);
map<string, int> nodes_by_id;
const char * edgedefault = graph_element->Attribute("edgedefault");
bool directed = true;
if (edgedefault && strcmp(edgedefault, "undirected") == 0) {
directed = false;
}
std::shared_ptr<Graph> graph;
if (directed) {
graph = std::make_shared<DirectedGraph>();
graph->setNodeArray(initial_nodes);
graph->getNodeArray().setNodeSizeMethod(SizeMethod(SizeMethod::SIZE_FROM_INDEGREE));
} else {
graph = std::make_shared<UndirectedGraph>();
graph->setNodeArray(initial_nodes);
graph->getNodeArray().setNodeSizeMethod(SizeMethod(SizeMethod::SIZE_FROM_DEGREE));
}
graph->getNodeArray().setFlattenHierarchy(true);
auto & node_table = graph->getNodeArray().getTable();
auto & edge_table = graph->getFaceData();
XMLElement * key_element = graphml_element->FirstChildElement("key");
for ( ; key_element ; key_element = key_element->NextSiblingElement("key") ) {
const char * key_type = key_element->Attribute("attr.type");
const char * key_id = key_element->Attribute("id");
const char * for_type = key_element->Attribute("for");
const char * name = key_element->Attribute("attr.name");
assert(key_type && key_id && for_type);
std::shared_ptr<table::Column> column;
if (strcmp(key_type, "string") == 0) {
column = std::make_shared<table::ColumnText>(key_id ? key_id : "");
} else if (strcmp(key_type, "double") == 0 || strcmp(key_type, "float") == 0) {
column = std::make_shared<table::ColumnDouble>(key_id ? key_id : "");
} else if (strcmp(key_type, "int") == 0) {
column = std::make_shared<table::ColumnInt>(key_id ? key_id : "");
} else {
assert(0);
}
if (strcmp(for_type, "node") == 0) {
node_table.addColumn(column);
} else if (strcmp(for_type, "edge") == 0) {
edge_table.addColumn(column);
} else {
assert(0);
}
}
createGraphFromElement(*graph, *graphml_element, *graph_element, nodes_by_id, directed);
graph->updateFaceAppearance();
graph->randomizeGeometry();
// graph->setComplexGraph(is_complex);
// graph->setHasSubGraphs(is_complex);
return graph;
}
void
GraphML::createGraphFromElement(Graph & graph, XMLElement & graphml_element, XMLElement & graph_element, map<string, int> & nodes_by_id, bool is_directed, int parent_node_id) const {
auto & node_table = graph.getNodeArray().getTable();
auto & edge_table = graph.getFaceData();
auto & node_id_column = node_table.addTextColumn("id");
auto & edge_id_column = edge_table.addTextColumn("id");
XMLElement * node_element = graph_element.FirstChildElement("node");
for ( ; node_element ; node_element = node_element->NextSiblingElement("node") ) {
const char * node_id_text = node_element->Attribute("id");
assert(node_id_text);
int node_id = graph.addNode();
node_id_column.setValue(node_id, node_id_text);
nodes_by_id[node_id_text] = node_id + 1;
if (parent_node_id != -1) graph.addChild(parent_node_id, node_id);
XMLElement * data_element = node_element->FirstChildElement("data");
for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) {
const char * key = data_element->Attribute("key");
assert(key);
const char * text = data_element->GetText();
if (text) {
node_table[key].setValue(node_id, text);
}
}
XMLElement * nested_graph_element = node_element->FirstChildElement("graph");
if (nested_graph_element) {
createGraphFromElement(graph, graphml_element, *nested_graph_element, nodes_by_id, is_directed, node_id);
}
}
XMLElement * edge_element = graph_element.FirstChildElement("edge");
for ( ; edge_element ; edge_element = edge_element->NextSiblingElement("edge") ) {
const char * edge_id_text = edge_element->Attribute("id");
const char * source = edge_element->Attribute("source");
const char * target = edge_element->Attribute("target");
assert(source && target);
if (strcmp(source, target) == 0) {
cerr << "GraphML: skipping self link for " << source << endl;
continue;
}
int source_node = nodes_by_id[source];
int target_node = nodes_by_id[target];
if (source_node && target_node) {
int face_id = graph.addFace(-1);
int edge_id1 = graph.addEdge(source_node - 1, target_node - 1, face_id);
if (!is_directed) {
int edge_id2 = graph.addEdge(target_node - 1, source_node - 1, face_id);
graph.connectEdgePair(edge_id1, edge_id2);
}
if (edge_id_text && strlen(edge_id_text) != 0) {
edge_id_column.setValue(face_id, edge_id_text);
}
XMLElement * data_element = edge_element->FirstChildElement("data");
for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) {
const char * key = data_element->Attribute("key");
assert(key);
const char * text = data_element->GetText();
if (text) {
edge_table[key].setValue(face_id, text);
}
}
} else {
if (!source_node) {
// cerr << "cannot find node " << source << endl;
}
if (!target_node) {
// cerr << "cannot find node " << target << endl;
}
}
}
}
bool
GraphML::saveGraph(const Graph & graph, const std::string & filename) {
XMLDocument doc;
doc.LinkEndChild(doc.NewDeclaration());
XMLElement * graphml_element = doc.NewElement("graphml");
graphml_element->SetAttribute("xmlns", "http://graphml.graphdrawing.org/xmlns");
bool directed = graph.isDirected();
auto & node_table = graph.getNodeArray().getTable();
auto & edge_table = graph.getFaceData();
for (auto & col : node_table.getColumns()) {
XMLElement * key_element = doc.NewElement("key");
key_element->SetAttribute("attr.name", col.first.c_str());
key_element->SetAttribute("id", col.first.c_str());
key_element->SetAttribute("attr.type", col.second->getTypeText());
key_element->SetAttribute("for", "node");
graphml_element->LinkEndChild(key_element);
}
for (auto & col : edge_table.getColumns()) {
XMLElement * key_element = doc.NewElement("key");
key_element->SetAttribute("attr.name", col.first.c_str());
key_element->SetAttribute("id", col.first.c_str());
key_element->SetAttribute("attr.type", col.second->getTypeText());
key_element->SetAttribute("for", "edge");
graphml_element->LinkEndChild(key_element);
}
XMLElement * graph_element = doc.NewElement("graph");
graphml_element->LinkEndChild(graph_element);
if (!directed) {
graph_element->SetAttribute("edgedefault", "undirected");
}
for (unsigned int i = 0; i < graph.getNodeArray().size(); i++) {
XMLElement * node_element = doc.NewElement("node");
string node_id = "n" + to_string(i);
node_element->SetAttribute("id", node_id.c_str());
for (auto & col : node_table.getColumns()) {
XMLElement * data_element = doc.NewElement("data");
data_element->SetAttribute("key", col.first.c_str());
data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str()));
node_element->LinkEndChild(data_element);
}
graph_element->LinkEndChild(node_element);
}
for (unsigned int i = 0; i < graph.getFaceCount(); i++) {
XMLElement * edge_element = doc.NewElement("edge");
#if 0
auto edge = graph.getEdgeAttributes(i);
string node_id1 = "n" + to_string(edge.tail);
string node_id2 = "n" + to_string(edge.head);
// timestamp, sentiment
edge_element->SetAttribute("source", node_id1.c_str());
edge_element->SetAttribute("target", node_id2.c_str());
#endif
for (auto & col : edge_table.getColumns()) {
XMLElement * data_element = doc.NewElement("data");
data_element->SetAttribute("key", col.first.c_str());
data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str()));
edge_element->LinkEndChild(data_element);
}
graph_element->LinkEndChild(edge_element);
}
doc.LinkEndChild(graphml_element);
doc.SaveFile(filename.c_str());
return true;
}
<|endoftext|>
|
<commit_before>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sstream>
#include "liblogger.h"
namespace liblogger
{
LogFile::LogFile(const std::string fname) :
m_fname(fname)
{
m_fp = fopen(m_fname.c_str(), "a");
if (m_fp == NULL)
{
std::stringstream ss;
ss << "Cannot open file: '" << m_fname << "' error: " << strerror(errno);
throw(LogException(ss.str()));
}
}
LogFile::~LogFile()
{
if (m_fp != NULL)
{
if (fclose(m_fp) < 0)
{
std::stringstream ss;
ss << "Cannot close file: '" << m_fname << "' error: " << strerror(errno);
throw(LogException(ss.str()));
}
}
}
void LogFile::GetName(std::string *str)
{
*str = "File";
}
void LogFile::GetDesc(std::string *str)
{
*str = "Logs to a File";
}
void LogFile::Log(const LogType Type, const std::string &str)
{
if (m_fp == NULL)
return;
time_t current = time(NULL);
struct tm timeinfo;
char buf[128];
localtime_r(¤t, &timeinfo);
strftime(buf, sizeof(buf), "%F %T", &timeinfo);
if (fprintf(m_fp, "%s - %s [PID: %d] - %s\n", buf, LogTypeToStr(Type).c_str(), getpid(), str.c_str()) < 0)
{
std::stringstream ss;
ss << "failed to write to file '" << m_fname.c_str() << "' error:" << strerror(errno);
throw(LogException(ss.str()));
}
if (fflush(m_fp) < 0)
{
std::stringstream ss;
ss << "failed to fflush to file '" << m_fname.c_str() << "' error:" << strerror(errno);
throw(LogException(ss.str()));
}
}
void LogFile::Rotate()
{
if (m_fp != NULL)
{
if (fclose(m_fp) < 0)
{
std::stringstream ss;
ss << "failed to close to file '" << m_fname.c_str() << "' error:" << strerror(errno);
throw(LogException(ss.str()));
}
}
m_fp = fopen(m_fname.c_str(), "a");
if (m_fp == NULL)
{
std::stringstream ss;
ss << "Cannot open file: '" << m_fname << "'";
throw(LogException(ss.str()));
}
}
};
<commit_msg>Added missing error check to strftime<commit_after>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sstream>
#include "liblogger.h"
namespace liblogger
{
LogFile::LogFile(const std::string fname) :
m_fname(fname)
{
m_fp = fopen(m_fname.c_str(), "a");
if (m_fp == NULL)
{
std::stringstream ss;
ss << "Cannot open file: '" << m_fname << "' error: " << strerror(errno);
throw(LogException(ss.str()));
}
}
LogFile::~LogFile()
{
if (m_fp != NULL)
{
if (fclose(m_fp) < 0)
{
std::stringstream ss;
ss << "Cannot close file: '" << m_fname << "' error: " << strerror(errno);
throw(LogException(ss.str()));
}
}
}
void LogFile::GetName(std::string *str)
{
*str = "File";
}
void LogFile::GetDesc(std::string *str)
{
*str = "Logs to a File";
}
void LogFile::Log(const LogType Type, const std::string &str)
{
if (m_fp == NULL)
return;
time_t current = time(NULL);
struct tm timeinfo;
char buf[128];
localtime_r(¤t, &timeinfo);
if (strftime(buf, sizeof(buf), "%F %T", &timeinfo) == 0)
{
std::stringstream ss;
ss << "strftime failed: '" << "' error: " << strerror(errno);
throw(LogException(ss.str()));
}
if (fprintf(m_fp, "%s - %s [PID: %d] - %s\n", buf, LogTypeToStr(Type).c_str(), getpid(), str.c_str()) < 0)
{
std::stringstream ss;
ss << "failed to write to file '" << m_fname.c_str() << "' error:" << strerror(errno);
throw(LogException(ss.str()));
}
if (fflush(m_fp) < 0)
{
std::stringstream ss;
ss << "failed to fflush to file '" << m_fname.c_str() << "' error:" << strerror(errno);
throw(LogException(ss.str()));
}
}
void LogFile::Rotate()
{
if (m_fp != NULL)
{
if (fclose(m_fp) < 0)
{
std::stringstream ss;
ss << "failed to close to file '" << m_fname.c_str() << "' error:" << strerror(errno);
throw(LogException(ss.str()));
}
}
m_fp = fopen(m_fname.c_str(), "a");
if (m_fp == NULL)
{
std::stringstream ss;
ss << "Cannot open file: '" << m_fname << "'";
throw(LogException(ss.str()));
}
}
};
<|endoftext|>
|
<commit_before>#include "Louvain.h"
#include <Graph.h>
#include <iostream>
#include <cassert>
#include <unordered_set>
using namespace std;
Louvain::Louvain(Graph * _g, int _max_num_passes, double _min_modularity,
bool _create_node_clusters, bool _create_edge_clusters)
: g(_g),
max_num_passes(_max_num_passes),
min_modularity(_min_modularity),
create_node_clusters(_create_node_clusters),
create_edge_clusters(_create_edge_clusters)
{
}
int
Louvain::getNodeCommunity(int node) const {
while ( 1 ) {
auto & td = getGraph().getNodeTertiaryData(node);
if (td.parent_node == -1) break;
node = td.parent_node;
}
return node;
}
unordered_map<int, float>
Louvain::neighboringCommunities(int node) const {
unordered_map<int, float> comms;
comms[getNodeCommunity(node)] = 0.0f;
auto nd = g->getAllNeighbors(node);
for (auto n : nd) {
unsigned int neigh = n.first;
unsigned int neigh_comm = getNodeCommunity(neigh);
float neigh_w = n.second;
if (neigh != node) {
auto it = comms.find(neigh_comm);
if (it == comms.end()) {
comms[neigh_comm] = neigh_w;
} else {
it->second += neigh_w;
}
}
}
return comms;
}
bool
Louvain::oneLevel() {
std::vector<int> nodes, edges;
if (create_node_clusters) {
auto end = g->end_visible_nodes();
for (auto it = g->begin_visible_nodes(); it != end; ++it) {
// if (getNodeCommunity(*it) == -1) {
if (getGraph().getNodeTertiaryData(*it).parent_node == -1) {
nodes.push_back(*it);
}
}
for (auto & n : nodes) {
int community_id = g->getNodeArray().createCommunity(n);
// g->getNodeArray().setPosition(community_id, g->getNodePosition(n));
g->addChild(community_id, n, 0);
// g->getNodeArray().setPosition(n, glm::vec3());
}
} else {
assert(0);
}
#if 0
if (create_edge_clusters) {
auto end = g->end_edges();
for (auto it = g->begin_edges(); it != end; ++it) {
if (getEdgeCommunity(*it) == -1) {
edges.push_back(*it);
int community_id = g->getNodeArray().createCommunity(*it);
g->addEdgeChild(community_id, *it, 0);
}
}
}
#endif
bool is_improved = false;
double initial_modularity = getGraph().modularity();
double modularity = initial_modularity;
#if 0
// shuffle nodes
for (int i = 0; i < nodes.size()-1; i++) {
int rand_pos = rand() % (nodes.size()-i)+i;
int tmp = nodes[i];
nodes[i] = nodes[rand_pos];
nodes[rand_pos] = tmp;
}
#endif
// cerr << "max_num_passes = " << max_num_passes << endl;
// repeat until there is no improvement in modularity, or the improvement is smaller than epsilon, or maximum number of passes have been done
for (int num_passes = 0; max_num_passes == -1 || num_passes < max_num_passes; num_passes++) {
int num_moves = 0;
// for each node: remove the node from its community and insert it in the best community
for (int node : nodes) {
int node_comm = getNodeCommunity(node);
float weighted_degree = g->weightedDegree(node);
// get the neighboring communities of the node
auto neighboring_comms = neighboringCommunities(node);
// remove the node from its community
g->removeChild(node, neighboring_comms[node_comm]);
// find the best community for node
int best_comm = node_comm;
double best_num_edges = 0.0, best_increase = 0.0;
for (auto & ncd : neighboring_comms) {
double increase = getGraph().modularityGain(node, ncd.first, ncd.second, weighted_degree);
if (increase > best_increase) {
best_comm = ncd.first;
best_num_edges = ncd.second;
best_increase = increase;
}
}
// insert node in the best community
g->addChild(best_comm, node, best_num_edges);
if (best_comm != node_comm) {
num_moves++;
}
}
double prev_modularity = modularity;
modularity = getGraph().modularity();
if (num_moves > 0) {
is_improved = true;
}
if (!num_moves) {
cerr << "Louvain: stopping due to no moves\n";
break;
} if (modularity - prev_modularity < min_modularity) {
cerr << "Louvain: modularity diff too small, min = " << min_modularity << "\n";
break;
}
}
cerr << "level done, modularity increase: " << initial_modularity << " to " << modularity << endl;
std::unordered_set<int> clusters;
if (is_improved) {
for (int node : nodes) {
clusters.insert(getNodeCommunity(node));
}
current_clusters.clear();
current_clusters.reserve(clusters.size());
for (auto id : clusters) {
current_clusters.push_back(id);
}
} else {
for (int node : nodes) {
getGraph().removeChild(node);
}
}
return is_improved;
}
<commit_msg>add safety check<commit_after>#include "Louvain.h"
#include <Graph.h>
#include <iostream>
#include <cassert>
#include <unordered_set>
using namespace std;
Louvain::Louvain(Graph * _g, int _max_num_passes, double _min_modularity,
bool _create_node_clusters, bool _create_edge_clusters)
: g(_g),
max_num_passes(_max_num_passes),
min_modularity(_min_modularity),
create_node_clusters(_create_node_clusters),
create_edge_clusters(_create_edge_clusters)
{
}
int
Louvain::getNodeCommunity(int node) const {
while ( 1 ) {
auto & td = getGraph().getNodeTertiaryData(node);
if (td.parent_node == -1) break;
node = td.parent_node;
}
return node;
}
unordered_map<int, float>
Louvain::neighboringCommunities(int node) const {
unordered_map<int, float> comms;
comms[getNodeCommunity(node)] = 0.0f;
auto nd = g->getAllNeighbors(node);
for (auto n : nd) {
unsigned int neigh = n.first;
unsigned int neigh_comm = getNodeCommunity(neigh);
float neigh_w = n.second;
if (neigh != node) {
auto it = comms.find(neigh_comm);
if (it == comms.end()) {
comms[neigh_comm] = neigh_w;
} else {
it->second += neigh_w;
}
}
}
return comms;
}
bool
Louvain::oneLevel() {
std::vector<int> nodes, edges;
if (create_node_clusters) {
auto end = g->end_visible_nodes();
for (auto it = g->begin_visible_nodes(); it != end; ++it) {
// if (getNodeCommunity(*it) == -1) {
if (getGraph().getNodeTertiaryData(*it).parent_node == -1) {
nodes.push_back(*it);
}
}
for (auto & n : nodes) {
int community_id = g->getNodeArray().createCommunity(n);
assert(getGraph().getNodeTertiaryData(community_id).parent_node == -1);
// g->getNodeArray().setPosition(community_id, g->getNodePosition(n));
g->addChild(community_id, n, 0);
// g->getNodeArray().setPosition(n, glm::vec3());
}
} else {
assert(0);
}
#if 0
if (create_edge_clusters) {
auto end = g->end_edges();
for (auto it = g->begin_edges(); it != end; ++it) {
if (getEdgeCommunity(*it) == -1) {
edges.push_back(*it);
int community_id = g->getNodeArray().createCommunity(*it);
g->addEdgeChild(community_id, *it, 0);
}
}
}
#endif
bool is_improved = false;
double initial_modularity = getGraph().modularity();
double modularity = initial_modularity;
#if 0
// shuffle nodes
for (int i = 0; i < nodes.size()-1; i++) {
int rand_pos = rand() % (nodes.size()-i)+i;
int tmp = nodes[i];
nodes[i] = nodes[rand_pos];
nodes[rand_pos] = tmp;
}
#endif
// cerr << "max_num_passes = " << max_num_passes << endl;
// repeat until there is no improvement in modularity, or the improvement is smaller than epsilon, or maximum number of passes have been done
for (int num_passes = 0; max_num_passes == -1 || num_passes < max_num_passes; num_passes++) {
int num_moves = 0;
// for each node: remove the node from its community and insert it in the best community
for (int node : nodes) {
int node_comm = getNodeCommunity(node);
float weighted_degree = g->weightedDegree(node);
// get the neighboring communities of the node
auto neighboring_comms = neighboringCommunities(node);
// remove the node from its community
g->removeChild(node, neighboring_comms[node_comm]);
// find the best community for node
int best_comm = node_comm;
double best_num_edges = 0.0, best_increase = 0.0;
for (auto & ncd : neighboring_comms) {
double increase = getGraph().modularityGain(node, ncd.first, ncd.second, weighted_degree);
if (increase > best_increase) {
best_comm = ncd.first;
best_num_edges = ncd.second;
best_increase = increase;
}
}
// insert node in the best community
g->addChild(best_comm, node, best_num_edges);
if (best_comm != node_comm) {
num_moves++;
}
}
double prev_modularity = modularity;
modularity = getGraph().modularity();
if (num_moves > 0) {
is_improved = true;
}
if (!num_moves) {
cerr << "Louvain: stopping due to no moves\n";
break;
} if (modularity - prev_modularity < min_modularity) {
cerr << "Louvain: modularity diff too small, min = " << min_modularity << "\n";
break;
}
}
cerr << "level done, modularity increase: " << initial_modularity << " to " << modularity << endl;
std::unordered_set<int> clusters;
if (is_improved) {
for (int node : nodes) {
clusters.insert(getNodeCommunity(node));
}
current_clusters.clear();
current_clusters.reserve(clusters.size());
for (auto id : clusters) {
current_clusters.push_back(id);
}
} else {
for (int node : nodes) {
getGraph().removeChild(node);
}
}
return is_improved;
}
<|endoftext|>
|
<commit_before>// Copyright (c) M5Stack. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "M5Stack.h"
M5Stack::M5Stack() : isInited(0) {
}
void M5Stack::begin(bool LCDEnable, bool SDEnable, bool SerialEnable, bool I2CEnable) {
// Correct init once
if (isInited == true) {
return;
} else {
isInited = true;
}
// UART
if (SerialEnable == true) {
Serial.begin(115200);
Serial.flush();
delay(50);
Serial.print("M5Stack initializing...");
}
// TF Card
if (SDEnable == true) {
SD.begin(TFCARD_CS_PIN, SPI, 40000000);
}
// LCD INIT
if (LCDEnable == true) {
Lcd.begin();
}
// TONE
// Speaker.begin();
// Set wakeup button
Power.setWakeupButton(BUTTON_A_PIN);
// I2C init
if (I2CEnable == true) {
Wire.begin(21, 22);
}
if (SerialEnable == true) {
Serial.println("OK");
}
// if use M5GO button, need set gpio15 OD or PP mode to avoid affecting the wifi signal
pinMode(15, OUTPUT_OPEN_DRAIN);
}
void M5Stack::update() {
//Button update
BtnA.read();
BtnB.read();
BtnC.read();
//Speaker update
Speaker.update();
}
/**
* Function has been move to Power class.(for compatibility)
* This name will be removed in a future release.
*/
void M5Stack::setPowerBoostKeepOn(bool en) {
M5.Power.setPowerBoostKeepOn(en);
}
/**
* Function has been move to Power class.(for compatibility)
* This name will be removed in a future release.
*/
void M5Stack::setWakeupButton(uint8_t button) {
M5.Power.setWakeupButton(button);
}
/**
* Function has been move to Power class.(for compatibility)
* This name will be removed in a future release.
*/
void M5Stack::powerOFF() {
M5.Power.deepSleep();
}
M5Stack M5;
<commit_msg>Print init text on own line, neatens Serial output<commit_after>// Copyright (c) M5Stack. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "M5Stack.h"
M5Stack::M5Stack() : isInited(0) {
}
void M5Stack::begin(bool LCDEnable, bool SDEnable, bool SerialEnable, bool I2CEnable) {
// Correct init once
if (isInited == true) {
return;
} else {
isInited = true;
}
// UART
if (SerialEnable == true) {
Serial.begin(115200);
Serial.flush();
delay(50);
Serial.println("M5Stack initializing...");
}
// TF Card
if (SDEnable == true) {
SD.begin(TFCARD_CS_PIN, SPI, 40000000);
}
// LCD INIT
if (LCDEnable == true) {
Lcd.begin();
}
// TONE
// Speaker.begin();
// Set wakeup button
Power.setWakeupButton(BUTTON_A_PIN);
// I2C init
if (I2CEnable == true) {
Wire.begin(21, 22);
}
if (SerialEnable == true) {
Serial.println("OK");
}
// if use M5GO button, need set gpio15 OD or PP mode to avoid affecting the wifi signal
pinMode(15, OUTPUT_OPEN_DRAIN);
}
void M5Stack::update() {
//Button update
BtnA.read();
BtnB.read();
BtnC.read();
//Speaker update
Speaker.update();
}
/**
* Function has been move to Power class.(for compatibility)
* This name will be removed in a future release.
*/
void M5Stack::setPowerBoostKeepOn(bool en) {
M5.Power.setPowerBoostKeepOn(en);
}
/**
* Function has been move to Power class.(for compatibility)
* This name will be removed in a future release.
*/
void M5Stack::setWakeupButton(uint8_t button) {
M5.Power.setWakeupButton(button);
}
/**
* Function has been move to Power class.(for compatibility)
* This name will be removed in a future release.
*/
void M5Stack::powerOFF() {
M5.Power.deepSleep();
}
M5Stack M5;
<|endoftext|>
|
<commit_before>#include "MyServo.h"
#include <Arduino.h>
MyServo::MyServo(int pin): pin(pin), servo() {}
void MyServo::setUp() {
this->servo.attach(this->pin);
}
void MyServo::updateFromAnalog(AnalogInput& input) {
int rawVal = input.read(-100, 100);
int finalVal = rawVal / 10;
this->servo.write(this->servo.read() + finalVal);
}
<commit_msg>Small change in MyServo<commit_after>#include "MyServo.h"
MyServo::MyServo(int pin): pin(pin), servo() {}
void MyServo::setUp() {
this->servo.attach(this->pin);
}
void MyServo::updateFromAnalog(AnalogInput& input) {
int rawVal = input.read(-100, 100);
int finalVal = rawVal / 10;
this->servo.write(this->servo.read() + finalVal);
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <string>
#include <iostream>
#include "Options.hpp"
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
using namespace eddic;
bool eddic::OptimizeStrings;
bool eddic::OptimizeUnused;
bool eddic::WarningUnused;
po::variables_map eddic::options;
po::options_description desc("Usage : eddic [options] source.eddi");
std::pair<std::string, std::string> numeric_parser(const std::string& s){
if (s.find("-32") == 0) {
return make_pair("32", std::string("true"));
} else if (s.find("-64") == 0) {
return make_pair("64", std::string("true"));
} else {
return make_pair(std::string(), std::string());
}
}
bool eddic::parseOptions(int argc, const char* argv[]) {
try {
desc.add_options()
("help,h", "Generate this help message")
("assembly,S", "Generate only the assembly")
("keep,k", "Keep the assembly file")
("version", "Print the version of eddic")
("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable")
("ast", "Print the Abstract Syntax Tree representation of the source")
("tac", "Print the Three Address Code representation of the source")
("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)")
("tac-only", "Only print the Three Address Code representation of the source (do not continue compilation after printing)")
("optimize-all", "Enable all optimizations")
("optimize-strings", po::bool_switch(&OptimizeStrings), "Enable the optimizations on strings")
("optimize-unused", po::bool_switch(&OptimizeUnused), "Enable the removal of unused variables and functions")
("debug,g", "Add debugging symbols")
("warning-all", "Enable all the warnings")
("warning-unused", po::bool_switch(&WarningUnused), "Enable warnings for unused variables, parameters and functions")
("32", po::value<std::string>(), "Force the compilation for 32 bits platform")
("64", po::value<std::string>(), "Force the compilation for 64 bits platform")
("input", po::value<std::string>(), "Input file");
po::positional_options_description p;
p.add("input", -1);
po::store(po::command_line_parser(argc, argv).options(desc).extra_parser(numeric_parser).positional(p).run(), options);
po::notify(options);
if(options.count("optimize-all")){
OptimizeStrings = OptimizeUnused = true;
}
if(options.count("warning-all")){
WarningUnused = true;
}
if(options.count("64") && options.count("32")){
std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl;
return false;
}
} catch (const po::ambiguous_option& e) {
std::cout << "Invalid command line options : " << e.what() << std::endl;
return false;
} catch (const po::unknown_option& e) {
std::cout << "Invalid command line options : " << e.what() << std::endl;
return false;
} catch (const po::multiple_occurrences& e) {
std::cout << "Only one file can be compiled" << std::endl;
return false;
}
return true;
}
void eddic::printHelp(){
std::cout << desc << std::endl;
}
void eddic::printVersion(){
std::cout << "eddic version 0.8.1" << std::endl;
}
<commit_msg>Fix the description of command line swithches<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <string>
#include <iostream>
#include "Options.hpp"
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
using namespace eddic;
bool eddic::OptimizeStrings;
bool eddic::OptimizeUnused;
bool eddic::WarningUnused;
po::variables_map eddic::options;
po::options_description desc("Usage : eddic [options] source.eddi");
std::pair<std::string, std::string> numeric_parser(const std::string& s){
if (s.find("-32") == 0) {
return make_pair("32", std::string("true"));
} else if (s.find("-64") == 0) {
return make_pair("64", std::string("true"));
} else {
return make_pair(std::string(), std::string());
}
}
bool eddic::parseOptions(int argc, const char* argv[]) {
try {
desc.add_options()
("help,h", "Generate this help message")
("assembly,S", "Generate only the assembly")
("keep,k", "Keep the assembly file")
("version", "Print the version of eddic")
("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable")
("ast", "Print the Abstract Syntax Tree representation of the source")
("tac", "Print the Three Address Code representation of the source")
("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)")
("tac-only", "Only print the Three Address Code representation of the source (do not continue compilation after printing)")
("optimize-all", "Enable all optimizations")
("optimize-strings", po::bool_switch(&OptimizeStrings), "Enable the optimizations on strings")
("optimize-unused", po::bool_switch(&OptimizeUnused), "Enable the removal of unused variables and functions")
("debug,g", "Add debugging symbols")
("warning-all", "Enable all the warnings")
("warning-unused", po::bool_switch(&WarningUnused), "Enable warnings for unused variables, parameters and functions")
("32", "Force the compilation for 32 bits platform")
("64", "Force the compilation for 64 bits platform")
("input", po::value<std::string>(), "Input file");
po::positional_options_description p;
p.add("input", -1);
po::store(po::command_line_parser(argc, argv).options(desc).extra_parser(numeric_parser).positional(p).run(), options);
po::notify(options);
if(options.count("optimize-all")){
OptimizeStrings = OptimizeUnused = true;
}
if(options.count("warning-all")){
WarningUnused = true;
}
if(options.count("64") && options.count("32")){
std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl;
return false;
}
} catch (const po::ambiguous_option& e) {
std::cout << "Invalid command line options : " << e.what() << std::endl;
return false;
} catch (const po::unknown_option& e) {
std::cout << "Invalid command line options : " << e.what() << std::endl;
return false;
} catch (const po::multiple_occurrences& e) {
std::cout << "Only one file can be compiled" << std::endl;
return false;
}
return true;
}
void eddic::printHelp(){
std::cout << desc << std::endl;
}
void eddic::printVersion(){
std::cout << "eddic version 0.8.1" << std::endl;
}
<|endoftext|>
|
<commit_before>#ifndef RADIAL_PAIRED_COORDINATES_VISUALIZATION_METHOD_HPP
#define RADIAL_PAIRED_COORDINATES_VISUALIZATION_METHOD_HPP
#include "LotsOfLines/IVisualizationMethod.hpp"
namespace LotsOfLines
{
class RadialPairedCoordinatesVisualizationMethod : public IVisualizationMethod
{
public:
VISUALIZATION_METHOD("Radial Paired Coordinates", EVT_RADIAL_PAIRED_COORDINATES)
const char* DRAW_SEQUENTIALLY = "Draw lines sequentially";
void getNavigationOptions(NavigationOptions& optionsOut)
{
optionsOut = NavigationOptions();
}
void getDefaultOptions(VisualizationOptions& options)
{
options.setBool(DRAW_SEQUENTIALLY, true);
}
bool generateVBO(const std::shared_ptr<const DataSet> dataSet, std::vector<Vertex>& verticesOut, std::vector<unsigned int>& indicesOut, const VisualizationOptions& options);
};
}
#endif<commit_msg>Change radial paired name<commit_after>#ifndef RADIAL_PAIRED_COORDINATES_VISUALIZATION_METHOD_HPP
#define RADIAL_PAIRED_COORDINATES_VISUALIZATION_METHOD_HPP
#include "LotsOfLines/IVisualizationMethod.hpp"
namespace LotsOfLines
{
class RadialPairedCoordinatesVisualizationMethod : public IVisualizationMethod
{
public:
VISUALIZATION_METHOD("Radial (Anchored) Paired Coordinates", EVT_RADIAL_PAIRED_COORDINATES)
const char* DRAW_SEQUENTIALLY = "Draw lines sequentially";
void getNavigationOptions(NavigationOptions& optionsOut)
{
optionsOut = NavigationOptions();
}
void getDefaultOptions(VisualizationOptions& options)
{
options.setBool(DRAW_SEQUENTIALLY, true);
}
bool generateVBO(const std::shared_ptr<const DataSet> dataSet, std::vector<Vertex>& verticesOut, std::vector<unsigned int>& indicesOut, const VisualizationOptions& options);
};
}
#endif<|endoftext|>
|
<commit_before>// Program.cpp
#include "stdafx.h"
#include "Program.h"
#include "PythonStuff.h"
#include "tinyxml/tinyxml.h"
#include "ProgramCanvas.h"
#include "NCCode.h"
#include "interface/MarkedObject.h"
#include "interface/PropertyString.h"
#include "interface/PropertyChoice.h"
#include "interface/Tool.h"
#include "Profile.h"
#include "Pocket.h"
#include "ZigZag.h"
#include "Adaptive.h"
#include "Op.h"
#include "CNCConfig.h"
bool COperations::CanAdd(HeeksObj* object)
{
return object->GetType() == ProfileType || object->GetType() == PocketType || object->GetType() == ZigZagType || object->GetType() == AdaptiveType;
}
void COperations::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "Operations" );
root->LinkEndChild( element );
WriteBaseXML(element);
}
//static
HeeksObj* COperations::ReadFromXMLElement(TiXmlElement* pElem)
{
COperations* new_object = new COperations;
new_object->ReadBaseXML(pElem);
return new_object;
}
static COperations* object_for_tools = NULL;
class SetAllActive: public Tool{
// Tool's virtual functions
const wxChar* GetTitle(){return _("Set All Operations Active");}
void Run()
{
for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
{
if(COp::IsAnOperation(object->GetType()))
{
((COp*)object)->m_active = true;
heeksCAD->WasModified(object);
}
}
}
wxString BitmapPath(){ return _T("setactive");}
};
static SetAllActive set_all_active;
class SetAllInactive: public Tool{
// Tool's virtual functions
const wxChar* GetTitle(){return _("Set All Operations Inactive");}
void Run()
{
for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
{
if(COp::IsAnOperation(object->GetType()))
{
((COp*)object)->m_active = false;
heeksCAD->WasModified(object);
}
}
}
wxString BitmapPath(){ return _T("setinactive");}
};
static SetAllInactive set_all_inactive;
void COperations::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
object_for_tools = this;
t_list->push_back(&set_all_active);
t_list->push_back(&set_all_inactive);
ObjList::GetTools(t_list, p);
}
CProgram::CProgram():m_nc_code(NULL), m_operations(NULL), m_script_edited(false)
{
CNCConfig config;
config.Read(_T("ProgramMachine"), &m_machine, _T("nc.iso"));
config.Read(_T("ProgramOutputFile"), &m_output_file, _T("/tmp/test.tap"));
config.Read(_T("ProgramUnits"), &m_units, 1.0);
}
HeeksObj *CProgram::MakeACopy(void)const
{
return new CProgram(*this);
}
void CProgram::CopyFrom(const HeeksObj* object)
{
operator=(*((CProgram*)object));
}
static void on_set_machine(const wxChar* value, HeeksObj* object)
{
((CProgram*)object)->m_machine = value;
CNCConfig config;
config.Write(_T("ProgramMachine"), ((CProgram*)object)->m_machine);
}
static void on_set_output_file(const wxChar* value, HeeksObj* object)
{
((CProgram*)object)->m_output_file = value;
CNCConfig config;
config.Write(_T("ProgramOutputFile"), ((CProgram*)object)->m_output_file);
}
static void on_set_units(int value, HeeksObj* object)
{
((CProgram*)object)->m_units = (value == 0) ? 1.0:25.4;
CNCConfig config;
config.Write(_T("ProgramUnits"), ((CProgram*)object)->m_units);
// also change HeeksCAD's view units automatically
heeksCAD->SetViewUnits(((CProgram*)object)->m_units, true);
}
void CProgram::GetProperties(std::list<Property *> *list)
{
list->push_back(new PropertyString(_("machine"), m_machine, this, on_set_machine));
list->push_back(new PropertyString(_("output file"), m_output_file, this, on_set_output_file));
{
std::list< wxString > choices;
choices.push_back ( wxString ( _("mm") ) );
choices.push_back ( wxString ( _("inch") ) );
int choice = 0;
if(m_units > 25.0)choice = 1;
list->push_back ( new PropertyChoice ( _("units"), choices, choice, this, on_set_units ) );
}
HeeksObj::GetProperties(list);
}
bool CProgram::CanAdd(HeeksObj* object)
{
return object->GetType() == NCCodeType || object->GetType() == OperationsType;
}
bool CProgram::CanAddTo(HeeksObj* owner)
{
return owner->GetType() == DocumentType;
}
void CProgram::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction)
{
if(marked_object->m_map.size() > 0)
{
MarkedObject* sub_marked_object = marked_object->m_map.begin()->second;
if(sub_marked_object)
{
HeeksObj* object = sub_marked_object->m_map.begin()->first;
if(object && object->GetType() == NCCodeType)
{
((CNCCode*)object)->SetClickMarkPoint(sub_marked_object, ray_start, ray_direction);
}
}
}
}
void CProgram::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "Program" );
root->LinkEndChild( element );
element->SetAttribute("machine", Ttc(m_machine.c_str()));
element->SetAttribute("output_file", Ttc(m_output_file.c_str()));
element->SetAttribute("program", Ttc(theApp.m_program_canvas->m_textCtrl->GetValue()));
element->SetDoubleAttribute("units", m_units);
WriteBaseXML(element);
}
bool CProgram::Add(HeeksObj* object, HeeksObj* prev_object)
{
if(object->GetType() == NCCodeType)m_nc_code = (CNCCode*)object;
if(object->GetType() == OperationsType)m_operations = (COperations*)object;
return ObjList::Add(object, prev_object);
}
void CProgram::Remove(HeeksObj* object)
{
// these shouldn't happen, though
if(object == m_nc_code)m_nc_code = NULL;
else if(object == m_operations)m_operations = NULL;
ObjList::Remove(object);
}
// static member function
HeeksObj* CProgram::ReadFromXMLElement(TiXmlElement* pElem)
{
CProgram* new_object = new CProgram;
// get the attributes
for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "machine"){new_object->m_machine.assign(Ctt(a->Value()));}
else if(name == "output_file"){new_object->m_output_file.assign(Ctt(a->Value()));}
else if(name == "program"){theApp.m_program_canvas->m_textCtrl->SetValue(Ctt(a->Value()));}
else if(name == "units"){new_object->m_units = a->DoubleValue();}
}
new_object->ReadBaseXML(pElem);
theApp.m_program = new_object;
return new_object;
}
void CProgram::RewritePythonProgram()
{
theApp.m_program_canvas->m_textCtrl->Clear();
CZigZag::number_for_stl_file = 1;
CAdaptive::number_for_stl_file = 1;
bool profile_op_exists = false;
bool pocket_op_exists = false;
bool zigzag_op_exists = false;
bool adaptive_op_exists = false;
for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
{
if(object->GetType() == ProfileType)
{
if(((CProfile*)object)->m_active)profile_op_exists = true;
}
else if(object->GetType() == PocketType)
{
if(((CPocket*)object)->m_active)pocket_op_exists = true;
}
else if(object->GetType() == ZigZagType)
{
if(((CZigZag*)object)->m_active)zigzag_op_exists = true;
}
else if(object->GetType() == AdaptiveType)
{
if(((CAdaptive*)object)->m_active)adaptive_op_exists = true;
}
}
// add standard stuff at the top
//hackhack, make it work on unix with FHS
#ifndef WIN32
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'/usr/lib/heekscnc/')\n"));
#endif
// kurve related things
if(profile_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve_funcs\n"));
}
// area related things
if(pocket_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area_funcs\n"));
}
// pycam stuff
if(zigzag_op_exists)
{
#ifdef WIN32
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
#endif
theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'PyCam/trunk')\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Geometry import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.SphericalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.CylindricalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.ToroidalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Importers.STLImporter import ImportModel\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.PathGenerators.DropCutter import DropCutter\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from PyCamToHeeks import HeeksCNCExporter\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
}
// actp
if(adaptive_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp_funcs\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
}
// machine general stuff
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from nc.nc import *\n"));
// specific machine
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import ") + m_machine + _T("\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
// output file
theApp.m_program_canvas->m_textCtrl->AppendText(_T("output('") + m_output_file + _T("')\n"));
// begin program
theApp.m_program_canvas->m_textCtrl->AppendText(_T("program_begin(123, 'Test program')\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("absolute()\n"));
if(m_units > 25.0)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("imperial()\n"));
}
else
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("metric()\n"));
}
theApp.m_program_canvas->m_textCtrl->AppendText(_T("set_plane(0)\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
// write the operations
for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
{
switch(object->GetType())
{
case ProfileType:
if(((CProfile*)object)->m_active)((CProfile*)object)->AppendTextToProgram();
break;
case PocketType:
if(((CPocket*)object)->m_active)((CPocket*)object)->AppendTextToProgram();
break;
case ZigZagType:
if(((CZigZag*)object)->m_active)((CZigZag*)object)->AppendTextToProgram();
break;
case AdaptiveType:
if(((CAdaptive*)object)->m_active)((CAdaptive*)object)->AppendTextToProgram();
break;
}
}
}
ProgramUserType CProgram::GetUserType()
{
if(m_nc_code->m_user_edited)return ProgramUserTypeNC;
if(m_script_edited)return ProgramUserTypeScript;
if(m_operations->GetFirstChild())return ProgramUserTypeTree;
return ProgramUserTypeUnkown;
}
void CProgram::UpdateFromUserType()
{
#if 0
switch(GetUserType())
{
case ProgramUserTypeUnkown:
case tree:
Enable "Operations" icon in tree
editing the tree, recreates the python script
Read only "Program" window
pressing "Post-process" creates the NC code ( and backplots it )
Read only "Output" window
Disable all buttons on "Output" window
}
#endif
}
<commit_msg>added '/usr/local/lib' to make things coincide with PREFIX changes that were made earlier<commit_after>// Program.cpp
#include "stdafx.h"
#include "Program.h"
#include "PythonStuff.h"
#include "tinyxml/tinyxml.h"
#include "ProgramCanvas.h"
#include "NCCode.h"
#include "interface/MarkedObject.h"
#include "interface/PropertyString.h"
#include "interface/PropertyChoice.h"
#include "interface/Tool.h"
#include "Profile.h"
#include "Pocket.h"
#include "ZigZag.h"
#include "Adaptive.h"
#include "Op.h"
#include "CNCConfig.h"
bool COperations::CanAdd(HeeksObj* object)
{
return object->GetType() == ProfileType || object->GetType() == PocketType || object->GetType() == ZigZagType || object->GetType() == AdaptiveType;
}
void COperations::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "Operations" );
root->LinkEndChild( element );
WriteBaseXML(element);
}
//static
HeeksObj* COperations::ReadFromXMLElement(TiXmlElement* pElem)
{
COperations* new_object = new COperations;
new_object->ReadBaseXML(pElem);
return new_object;
}
static COperations* object_for_tools = NULL;
class SetAllActive: public Tool{
// Tool's virtual functions
const wxChar* GetTitle(){return _("Set All Operations Active");}
void Run()
{
for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
{
if(COp::IsAnOperation(object->GetType()))
{
((COp*)object)->m_active = true;
heeksCAD->WasModified(object);
}
}
}
wxString BitmapPath(){ return _T("setactive");}
};
static SetAllActive set_all_active;
class SetAllInactive: public Tool{
// Tool's virtual functions
const wxChar* GetTitle(){return _("Set All Operations Inactive");}
void Run()
{
for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
{
if(COp::IsAnOperation(object->GetType()))
{
((COp*)object)->m_active = false;
heeksCAD->WasModified(object);
}
}
}
wxString BitmapPath(){ return _T("setinactive");}
};
static SetAllInactive set_all_inactive;
void COperations::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
object_for_tools = this;
t_list->push_back(&set_all_active);
t_list->push_back(&set_all_inactive);
ObjList::GetTools(t_list, p);
}
CProgram::CProgram():m_nc_code(NULL), m_operations(NULL), m_script_edited(false)
{
CNCConfig config;
config.Read(_T("ProgramMachine"), &m_machine, _T("nc.iso"));
config.Read(_T("ProgramOutputFile"), &m_output_file, _T("/tmp/test.tap"));
config.Read(_T("ProgramUnits"), &m_units, 1.0);
}
HeeksObj *CProgram::MakeACopy(void)const
{
return new CProgram(*this);
}
void CProgram::CopyFrom(const HeeksObj* object)
{
operator=(*((CProgram*)object));
}
static void on_set_machine(const wxChar* value, HeeksObj* object)
{
((CProgram*)object)->m_machine = value;
CNCConfig config;
config.Write(_T("ProgramMachine"), ((CProgram*)object)->m_machine);
}
static void on_set_output_file(const wxChar* value, HeeksObj* object)
{
((CProgram*)object)->m_output_file = value;
CNCConfig config;
config.Write(_T("ProgramOutputFile"), ((CProgram*)object)->m_output_file);
}
static void on_set_units(int value, HeeksObj* object)
{
((CProgram*)object)->m_units = (value == 0) ? 1.0:25.4;
CNCConfig config;
config.Write(_T("ProgramUnits"), ((CProgram*)object)->m_units);
// also change HeeksCAD's view units automatically
heeksCAD->SetViewUnits(((CProgram*)object)->m_units, true);
}
void CProgram::GetProperties(std::list<Property *> *list)
{
list->push_back(new PropertyString(_("machine"), m_machine, this, on_set_machine));
list->push_back(new PropertyString(_("output file"), m_output_file, this, on_set_output_file));
{
std::list< wxString > choices;
choices.push_back ( wxString ( _("mm") ) );
choices.push_back ( wxString ( _("inch") ) );
int choice = 0;
if(m_units > 25.0)choice = 1;
list->push_back ( new PropertyChoice ( _("units"), choices, choice, this, on_set_units ) );
}
HeeksObj::GetProperties(list);
}
bool CProgram::CanAdd(HeeksObj* object)
{
return object->GetType() == NCCodeType || object->GetType() == OperationsType;
}
bool CProgram::CanAddTo(HeeksObj* owner)
{
return owner->GetType() == DocumentType;
}
void CProgram::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction)
{
if(marked_object->m_map.size() > 0)
{
MarkedObject* sub_marked_object = marked_object->m_map.begin()->second;
if(sub_marked_object)
{
HeeksObj* object = sub_marked_object->m_map.begin()->first;
if(object && object->GetType() == NCCodeType)
{
((CNCCode*)object)->SetClickMarkPoint(sub_marked_object, ray_start, ray_direction);
}
}
}
}
void CProgram::WriteXML(TiXmlNode *root)
{
TiXmlElement * element;
element = new TiXmlElement( "Program" );
root->LinkEndChild( element );
element->SetAttribute("machine", Ttc(m_machine.c_str()));
element->SetAttribute("output_file", Ttc(m_output_file.c_str()));
element->SetAttribute("program", Ttc(theApp.m_program_canvas->m_textCtrl->GetValue()));
element->SetDoubleAttribute("units", m_units);
WriteBaseXML(element);
}
bool CProgram::Add(HeeksObj* object, HeeksObj* prev_object)
{
if(object->GetType() == NCCodeType)m_nc_code = (CNCCode*)object;
if(object->GetType() == OperationsType)m_operations = (COperations*)object;
return ObjList::Add(object, prev_object);
}
void CProgram::Remove(HeeksObj* object)
{
// these shouldn't happen, though
if(object == m_nc_code)m_nc_code = NULL;
else if(object == m_operations)m_operations = NULL;
ObjList::Remove(object);
}
// static member function
HeeksObj* CProgram::ReadFromXMLElement(TiXmlElement* pElem)
{
CProgram* new_object = new CProgram;
// get the attributes
for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "machine"){new_object->m_machine.assign(Ctt(a->Value()));}
else if(name == "output_file"){new_object->m_output_file.assign(Ctt(a->Value()));}
else if(name == "program"){theApp.m_program_canvas->m_textCtrl->SetValue(Ctt(a->Value()));}
else if(name == "units"){new_object->m_units = a->DoubleValue();}
}
new_object->ReadBaseXML(pElem);
theApp.m_program = new_object;
return new_object;
}
void CProgram::RewritePythonProgram()
{
theApp.m_program_canvas->m_textCtrl->Clear();
CZigZag::number_for_stl_file = 1;
CAdaptive::number_for_stl_file = 1;
bool profile_op_exists = false;
bool pocket_op_exists = false;
bool zigzag_op_exists = false;
bool adaptive_op_exists = false;
for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
{
if(object->GetType() == ProfileType)
{
if(((CProfile*)object)->m_active)profile_op_exists = true;
}
else if(object->GetType() == PocketType)
{
if(((CPocket*)object)->m_active)pocket_op_exists = true;
}
else if(object->GetType() == ZigZagType)
{
if(((CZigZag*)object)->m_active)zigzag_op_exists = true;
}
else if(object->GetType() == AdaptiveType)
{
if(((CAdaptive*)object)->m_active)adaptive_op_exists = true;
}
}
// add standard stuff at the top
//hackhack, make it work on unix with FHS
#ifndef WIN32
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'/usr/local/lib/heekscnc/')\n"));
#endif
// kurve related things
if(profile_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve_funcs\n"));
}
// area related things
if(pocket_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area_funcs\n"));
}
// pycam stuff
if(zigzag_op_exists)
{
#ifdef WIN32
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
#endif
theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'PyCam/trunk')\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Geometry import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.SphericalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.CylindricalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.ToroidalCutter import *\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Importers.STLImporter import ImportModel\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.PathGenerators.DropCutter import DropCutter\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from PyCamToHeeks import HeeksCNCExporter\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
}
// actp
if(adaptive_op_exists)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp_funcs\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
}
// machine general stuff
theApp.m_program_canvas->m_textCtrl->AppendText(_T("from nc.nc import *\n"));
// specific machine
theApp.m_program_canvas->m_textCtrl->AppendText(_T("import ") + m_machine + _T("\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
// output file
theApp.m_program_canvas->m_textCtrl->AppendText(_T("output('") + m_output_file + _T("')\n"));
// begin program
theApp.m_program_canvas->m_textCtrl->AppendText(_T("program_begin(123, 'Test program')\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("absolute()\n"));
if(m_units > 25.0)
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("imperial()\n"));
}
else
{
theApp.m_program_canvas->m_textCtrl->AppendText(_T("metric()\n"));
}
theApp.m_program_canvas->m_textCtrl->AppendText(_T("set_plane(0)\n"));
theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
// write the operations
for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
{
switch(object->GetType())
{
case ProfileType:
if(((CProfile*)object)->m_active)((CProfile*)object)->AppendTextToProgram();
break;
case PocketType:
if(((CPocket*)object)->m_active)((CPocket*)object)->AppendTextToProgram();
break;
case ZigZagType:
if(((CZigZag*)object)->m_active)((CZigZag*)object)->AppendTextToProgram();
break;
case AdaptiveType:
if(((CAdaptive*)object)->m_active)((CAdaptive*)object)->AppendTextToProgram();
break;
}
}
}
ProgramUserType CProgram::GetUserType()
{
if(m_nc_code->m_user_edited)return ProgramUserTypeNC;
if(m_script_edited)return ProgramUserTypeScript;
if(m_operations->GetFirstChild())return ProgramUserTypeTree;
return ProgramUserTypeUnkown;
}
void CProgram::UpdateFromUserType()
{
#if 0
switch(GetUserType())
{
case ProgramUserTypeUnkown:
case tree:
Enable "Operations" icon in tree
editing the tree, recreates the python script
Read only "Program" window
pressing "Post-process" creates the NC code ( and backplots it )
Read only "Output" window
Disable all buttons on "Output" window
}
#endif
}
<|endoftext|>
|
<commit_before>#include "RThread.h"
#include "REventLoop.h"
#include "RForwardList.h"
#include "RSpinLocker.h"
class RThreadPrivate
{
public:
static void
run(void *arg);
};
// FIXME: Thread list not guarded by mutex now !
static RForwardList<RThread *> sThreads;
void
RThreadPrivate::run(void *arg)
{
RThread *thread = static_cast<RThread *>(arg);
if(thread)
{
thread->started.emit();
thread->run();
thread->finished.emit();
}
}
RThread::RThread(TaskHandle_t handle)
// So that RObject won't create another RThread lead infinite looping
: RObject(this)
, mStackSize(128)
, mHandle(handle)
, mIsOwnded(false)
{
}
RThread::RThread()
: RObject(this)
, mStackSize(128)
, mHandle(NULL)
, mIsOwnded(false)
{
R_MAKE_SPINLOCKER();
sThreads.pushFront(this);
}
RThread::~RThread()
{
terminate();
R_MAKE_SPINLOCKER();
// Clear this thread pointer in thread list
sThreads.remove(this);
}
void
RThread::exit(int returnCode)
{
REventLoop::instance(this)->exit(returnCode);
}
bool
RThread::isFinished() const
{
if(!mHandle)
{
return true;
}
return (eDeleted == eTaskGetState(mHandle));
}
bool
RThread::isRunning() const
{
if(!mHandle)
{
return false;
}
return (eDeleted != eTaskGetState(mHandle));
}
RThread::Priority
RThread::priority() const
{
if(!mHandle)
{
return IdlePriority;
}
return static_cast<RThread::Priority>(uxTaskPriorityGet(mHandle));
}
void
RThread::setPriority(RThread::Priority priority)
{
if(!mHandle)
{
return;
}
vTaskPrioritySet(mHandle, static_cast<UBaseType_t>(priority));
}
void
RThread::setStackSize(size_t stackSize)
{
mStackSize = stackSize;
}
size_t
RThread::stackSize() const
{
return mStackSize;
}
bool
RThread::wait(unsigned long time)
{
/// FIXME: Ugly way to wait for thread finished.
/* Block for 100ms each time */
const TickType_t ticksPerBlock = 100 / portTICK_PERIOD_MS;
if(currentThreadId() == mHandle)
{
// You can't wait yourself in the samethread!
return false;
}
while(true)
{
if(isFinished())
{
return true;
}
if(time < std::numeric_limits<unsigned long>::max())
{
if(time <= 100)
{
// Timeout!
return false;
}
else
{
time -= 100;
}
}
vTaskDelay(ticksPerBlock);
}
}
void
RThread::quit()
{
this->exit(0);
}
void
RThread::start(RThread::Priority priority)
{
/* Create the task, storing the handle. */
TaskHandle_t handle = NULL;
if(isRunning())
{
return;
}
terminate();
UBaseType_t targetPriority = IdlePriority;
if(InheritPriority == priority)
{
targetPriority = uxTaskPriorityGet(currentThreadId());
}
auto ret = xTaskCreate(
RThreadPrivate::run, /* Function that implements the task. */
"", /* Text name for the task. */
(stackSize() + 1) % sizeof(uint16_t), /* Stack size in words, not bytes. */
static_cast<void *>(this), /* Parameter passed into the task. */
targetPriority, /* Priority at which the task is created. */
&handle); /* Used to pass out the created task's handle. */
if(ret == pdPASS)
{
mIsOwnded = true;
mHandle = handle;
}
}
void
RThread::terminate()
{
if(mIsOwnded && mHandle)
{
// Ensure no tasks and interrupts will be trigger during thread event loop
// destruction.
{
R_MAKE_SPINLOCKER();
REventLoop::_destroy(this);
vTaskDelete(mHandle);
}
terminated.emit();
}
mHandle = NULL;
}
RThread *
RThread::currentThread()
{
TaskHandle_t handle = currentThreadId();
for(auto it = sThreads.begin(); it != sThreads.end(); ++it)
{
if(handle == (*it)->mHandle)
{
return *it;
}
}
// FIXME: Here generated an orphan RThread object!
return new RThread(handle);
}
TaskHandle_t
RThread::currentThreadId()
{
return xTaskGetCurrentTaskHandle();
}
void
RThread::yieldCurrentThread()
{
taskYIELD();
}
int
RThread::exec()
{
REventLoop *loop = REventLoop::instance(this);
return loop->exec();
}
void
RThread::run()
{
exec();
}
void
RThread::msleep(unsigned long msecs)
{
unsigned long blockTime = std::numeric_limits<unsigned long>::max() / 1000;
while(msecs > 0)
{
if(msecs <= std::numeric_limits<unsigned long>::max())
{
usleep(msecs);
return;
}
usleep(std::numeric_limits<unsigned long>::max());
msecs -= blockTime;
}
}
void
RThread::sleep(unsigned long secs)
{
unsigned long blockTime = std::numeric_limits<unsigned long>::max() /
1000000l;
while(secs > 0)
{
if(secs <= std::numeric_limits<unsigned long>::max())
{
usleep(secs);
return;
}
usleep(std::numeric_limits<unsigned long>::max());
secs -= blockTime;
}
}
void
RThread::usleep(unsigned long usecs)
{
unsigned long ticks = usecs / (1000 * portTICK_PERIOD_MS);
while(ticks > 0)
{
if(ticks <= static_cast<decltype(usecs)>(portMAX_DELAY))
{
vTaskDelay(static_cast<decltype(portMAX_DELAY)>(ticks));
return;
}
vTaskDelay(portMAX_DELAY);
ticks -= static_cast<decltype(usecs)>(portMAX_DELAY);
}
}
<commit_msg>Fixed task not running<commit_after>#include "RThread.h"
#include "REventLoop.h"
#include "RForwardList.h"
#include "RSpinLocker.h"
class RThreadPrivate
{
public:
static void
run(void *arg);
};
// FIXME: Thread list not guarded by mutex now !
static RForwardList<RThread *> sThreads;
void
RThreadPrivate::run(void *arg)
{
RThread *thread = static_cast<RThread *>(arg);
if(thread)
{
thread->started.emit();
thread->run();
thread->finished.emit();
}
}
RThread::RThread(TaskHandle_t handle)
// So that RObject won't create another RThread lead infinite looping
: RObject(this)
, mStackSize(128)
, mHandle(handle)
, mIsOwnded(false)
{
}
RThread::RThread()
: RObject(this)
, mStackSize(128)
, mHandle(NULL)
, mIsOwnded(false)
{
R_MAKE_SPINLOCKER();
sThreads.pushFront(this);
}
RThread::~RThread()
{
terminate();
R_MAKE_SPINLOCKER();
// Clear this thread pointer in thread list
sThreads.remove(this);
}
void
RThread::exit(int returnCode)
{
REventLoop::instance(this)->exit(returnCode);
}
bool
RThread::isFinished() const
{
if(!mHandle)
{
return true;
}
return (eDeleted == eTaskGetState(mHandle));
}
bool
RThread::isRunning() const
{
if(!mHandle)
{
return false;
}
return (eDeleted != eTaskGetState(mHandle));
}
RThread::Priority
RThread::priority() const
{
if(!mHandle)
{
return IdlePriority;
}
return static_cast<RThread::Priority>(uxTaskPriorityGet(mHandle));
}
void
RThread::setPriority(RThread::Priority priority)
{
if(!mHandle)
{
return;
}
vTaskPrioritySet(mHandle, static_cast<UBaseType_t>(priority));
}
void
RThread::setStackSize(size_t stackSize)
{
mStackSize = stackSize;
}
size_t
RThread::stackSize() const
{
return mStackSize;
}
bool
RThread::wait(unsigned long time)
{
/// FIXME: Ugly way to wait for thread finished.
/* Block for 100ms each time */
const TickType_t ticksPerBlock = 100 / portTICK_PERIOD_MS;
if(currentThreadId() == mHandle)
{
// You can't wait yourself in the samethread!
return false;
}
while(true)
{
if(isFinished())
{
return true;
}
if(time < std::numeric_limits<unsigned long>::max())
{
if(time <= 100)
{
// Timeout!
return false;
}
else
{
time -= 100;
}
}
vTaskDelay(ticksPerBlock);
}
}
void
RThread::quit()
{
this->exit(0);
}
void
RThread::start(RThread::Priority priority)
{
/* Create the task, storing the handle. */
TaskHandle_t handle = NULL;
if(isRunning())
{
return;
}
terminate();
UBaseType_t targetPriority = IdlePriority;
if(InheritPriority == priority)
{
targetPriority = uxTaskPriorityGet(currentThreadId());
}
auto ret = xTaskCreate(
RThreadPrivate::run, /* Function that implements the task. */
"", /* Text name for the task. */
(stackSize() + 1) / sizeof(uint16_t), /* Stack size in words, not bytes. */
static_cast<void *>(this), /* Parameter passed into the task. */
targetPriority, /* Priority at which the task is created. */
&handle); /* Used to pass out the created task's handle. */
if(ret == pdPASS)
{
mIsOwnded = true;
mHandle = handle;
}
}
void
RThread::terminate()
{
if(mIsOwnded && mHandle)
{
// Ensure no tasks and interrupts will be trigger during thread event loop
// destruction.
{
R_MAKE_SPINLOCKER();
REventLoop::_destroy(this);
vTaskDelete(mHandle);
}
terminated.emit();
}
mHandle = NULL;
}
RThread *
RThread::currentThread()
{
TaskHandle_t handle = currentThreadId();
for(auto it = sThreads.begin(); it != sThreads.end(); ++it)
{
if(handle == (*it)->mHandle)
{
return *it;
}
}
// FIXME: Here generated an orphan RThread object!
return new RThread(handle);
}
TaskHandle_t
RThread::currentThreadId()
{
return xTaskGetCurrentTaskHandle();
}
void
RThread::yieldCurrentThread()
{
taskYIELD();
}
int
RThread::exec()
{
REventLoop *loop = REventLoop::instance(this);
return loop->exec();
}
void
RThread::run()
{
exec();
}
void
RThread::msleep(unsigned long msecs)
{
unsigned long blockTime = std::numeric_limits<unsigned long>::max() / 1000;
while(msecs > 0)
{
if(msecs <= std::numeric_limits<unsigned long>::max())
{
usleep(msecs);
return;
}
usleep(std::numeric_limits<unsigned long>::max());
msecs -= blockTime;
}
}
void
RThread::sleep(unsigned long secs)
{
unsigned long blockTime = std::numeric_limits<unsigned long>::max() /
1000000l;
while(secs > 0)
{
if(secs <= std::numeric_limits<unsigned long>::max())
{
usleep(secs);
return;
}
usleep(std::numeric_limits<unsigned long>::max());
secs -= blockTime;
}
}
void
RThread::usleep(unsigned long usecs)
{
unsigned long ticks = usecs / (1000 * portTICK_PERIOD_MS);
while(ticks > 0)
{
if(ticks <= static_cast<decltype(usecs)>(portMAX_DELAY))
{
vTaskDelay(static_cast<decltype(portMAX_DELAY)>(ticks));
return;
}
vTaskDelay(portMAX_DELAY);
ticks -= static_cast<decltype(usecs)>(portMAX_DELAY);
}
}
<|endoftext|>
|
<commit_before>#ifndef SAPLIST_HPP
#define SAPLIST_HPP 1
#include <functional>
#include <map>
#include <typeinfo>
#include <climits>
#include "CollisionManager.hpp"
class Collisionable {
public:
virtual int getXMin() = 0;
virtual int getYMin() = 0;
virtual int getXMax() = 0;
virtual int getYMax() = 0;
virtual ~Collisionable() {};
};
class SAPList : public CollisionManager<Collisionable> {
class EndPoint;
class AABB {
public:
/** min/max
* - first is x axis
* - second is y axis */
EndPoint * min[2];
EndPoint * max[2];
size_t typeId; /* Need to use std::type_info::hash_code() */
void * owner;
AABB (int minX, int minY, int maxX, int maxY, size_t t, void * o) :
typeId(t), owner(o) {
min[0] = new EndPoint(this, minX, true);
min[1] = new EndPoint(this, minY, true);
max[0] = new EndPoint(this, maxX, false);
max[1] = new EndPoint(this, maxY, false);
}
};
/**
* TODO:
* - Optimize merging isMin boolean into another member
* (as a flag)
* - Using doubly-linked list could waste memory but is easier to implement
* than arrays.
* - Implement pair manager
*/
class EndPoint {
public:
AABB * owner;
int value; //FIXME: use a pointer?
bool isMin;
EndPoint * prev;
EndPoint * next;
EndPoint (AABB* o,int v,bool m,EndPoint* p=NULL,EndPoint* n=NULL) :
owner(o), value(v), isMin(m), prev(p), next(n) {}
/** When and EndPoint is destroyed, it updates prev and next */
~EndPoint () {
if (this->prev != NULL) {
this->prev->next = this->next;
}
if (this->next != NULL)
this->next->prev = this->prev;
}
};
/**
* Action manager stores actions to perform on collision or separation
* of two objects depending on their type
* It also stores default actions to execute if no specific action is
* defined for two types.
*/
class ActionManager {
public:
/**
* action table stores 2 actions per types couple:
* - first is onCollision
* - second is onSeparation
*/
std::map < std::pair < size_t,size_t >,
std::pair < std::function < void (void *, void *) >,
std::function < void (void *, void *) > > >
actions;
/**
* @param t1 type id of first object
* @param t2 type id of second object
* @return function to call on t1/t2 collision
*/
std::function < void (void *, void *) >
onCollision(size_t t1, size_t t2) {
return this
->actions[std::pair<size_t, size_t>(t1,t2)].first;
}
/**
* @param t1 type id of first object
* @param t2 type id of second object
* @return function to call on t1/t2 separation
*/
std::function < void (void *, void *) >
onSeparation(size_t t1, size_t t2) {
return this
->actions[std::pair<size_t, size_t>(t1,t2)].second;
}
};
private:
EndPoint * xAxis;
EndPoint * yAxis;
ActionManager actions;
/** Swap two EndPoint * */
void swap(EndPoint * p1, EndPoint * p2) {
p2->next->prev = p1;
p1->next = p2->next;
p1->prev->next = p2;
p1->prev = p2;
p2->next = p1;
}
/** A collision between two AABB on one axis */
inline bool partialCollisionCheck(const AABB & b1,
const AABB & b2,
int dim) {
return (b1.max[dim] <= b2.max[dim] && b1.max[dim] >= b2.min[dim])
|| (b1.min[dim] >= b2.min[dim] && b1.max[dim] <= b2.max[dim]);
}
/**
* Check if two AABB collide using 2 axises
* @see partialCollisionCheck
*/
bool collisionCheck(const AABB & b1, const AABB & b2) {
return partialCollisionCheck (b1, b2, 0)
&& partialCollisionCheck (b1, b2, 1);
}
/** Create the AABB corresponding to a collisionable object
* @param c the object used to create the corresponding AABB
* @return a pointer to freshly heap-allocated AABB
*/
AABB * mk_AABB(Collisionable * c) {
return new AABB(c->getXMin(), c->getYMin(),
c->getXMax(), c->getYMax(),
typeid(c).hash_code(), (void *) c);
}
/** Update EndPoint place and call the appropriate function in case
* of collision/separation
* @param pt the EndPoint to update
*/
void updateEndPoint(EndPoint * pt) {
auto aux =
[&pt, this]
(std::function<EndPoint*(EndPoint*)>succ,
std::function<bool(int,int)>loop_cond,
std::function<bool(EndPoint*,EndPoint*)>mustAdd,
std::function<bool(EndPoint*,EndPoint*)>mustRm) {
EndPoint * tmp = succ(pt);
while (loop_cond(tmp->value, pt->value)) {
this->swap(tmp, pt);
if (mustAdd(pt, tmp)) {
if (this->collisionCheck(*(pt->owner), *(tmp->owner))) {
this->actions.onCollision
(pt->owner->typeId, tmp->owner->typeId)
(pt->owner->owner, tmp->owner->owner);
}
} else if (mustRm(pt, tmp)) {
this->actions.onSeparation
(pt->owner->typeId,tmp->owner->typeId)
(pt->owner->owner, tmp->owner->owner);
}
}
};
/** TODO: use aux to update on x and y axis */
}
public:
SAPList () {
/* not sure about the true/false values */
xAxis = new EndPoint(NULL, INT_MIN, true, NULL, NULL);
xAxis->next = new EndPoint(NULL, INT_MAX, false, xAxis, NULL);
yAxis = new EndPoint(NULL, INT_MIN, true, NULL, NULL);
yAxis->next = new EndPoint(NULL, INT_MAX, false, yAxis, NULL);
}
~SAPList () {
while (xAxis->next != NULL) {
delete xAxis->next;
} delete xAxis;
while (yAxis->next != NULL) {
delete yAxis->next;
} delete yAxis;
}
void addObject(const Collisionable &) {}
void updateObject(const Collisionable &) {}
void removeObject(const Collisionable &) {}
};
#endif
<commit_msg>Added function to add actions in ActionManager.<commit_after>#ifndef SAPLIST_HPP
#define SAPLIST_HPP 1
#include <functional>
#include <map>
#include <typeinfo>
#include <climits>
#include "CollisionManager.hpp"
class Collisionable {
public:
virtual int getXMin() = 0;
virtual int getYMin() = 0;
virtual int getXMax() = 0;
virtual int getYMax() = 0;
virtual ~Collisionable() {};
};
class SAPList : public CollisionManager<Collisionable> {
class EndPoint;
class AABB {
public:
/** min/max
* - first is x axis
* - second is y axis */
EndPoint * min[2];
EndPoint * max[2];
size_t typeId; /* Need to use std::type_info::hash_code() */
void * owner;
AABB (int minX, int minY, int maxX, int maxY, size_t t, void * o) :
typeId(t), owner(o) {
min[0] = new EndPoint(this, minX, true);
min[1] = new EndPoint(this, minY, true);
max[0] = new EndPoint(this, maxX, false);
max[1] = new EndPoint(this, maxY, false);
}
};
/**
* TODO:
* - Optimize merging isMin boolean into another member
* (as a flag)
* - Using doubly-linked list could waste memory but is easier to implement
* than arrays.
* - Implement pair manager
*/
class EndPoint {
public:
AABB * owner;
int value; //FIXME: use a pointer?
bool isMin;
EndPoint * prev;
EndPoint * next;
EndPoint (AABB* o,int v,bool m,EndPoint* p=NULL,EndPoint* n=NULL) :
owner(o), value(v), isMin(m), prev(p), next(n) {}
/** When and EndPoint is destroyed, it updates prev and next */
~EndPoint () {
if (this->prev != NULL) {
this->prev->next = this->next;
}
if (this->next != NULL)
this->next->prev = this->prev;
}
};
/**
* Action manager stores actions to perform on collision or separation
* of two objects depending on their type
* It also stores default actions to execute if no specific action is
* defined for two types.
*/
class ActionManager {
public:
/**
* action table stores 2 actions per types couple:
* - first is onCollision
* - second is onSeparation
*/
std::map < std::pair < size_t,size_t >,
std::pair < std::function < void (void *, void *) >,
std::function < void (void *, void *) > > >
actions;
ActionManager () {}
/** Add an action to ActionManager
* @param t1 first object type (hashcode)
* @param t2 second object type (hashcode)
* @param onCollision function to call on collision of t1 and t2
* @param onSeparation function to call on separation of t1 and t2
*/
void addAction(size_t t1, size_t t2,
std::function <void (void *, void *)> onCollision,
std::function <void (void *, void *)> onSeparation) {
this->actions[std::pair < size_t, size_t > (t1,t2)] =
std::pair < std::function < void (void *, void *) >,
std::function < void (void *, void *) > >
(onCollision, onSeparation);
}
/**
* @param t1 type id of first object
* @param t2 type id of second object
* @return function to call on t1/t2 collision
*/
std::function < void (void *, void *) >
onCollision(size_t t1, size_t t2) {
return this
->actions[std::pair<size_t, size_t>(t1,t2)].first;
}
/**
* @param t1 type id of first object
* @param t2 type id of second object
* @return function to call on t1/t2 separation
*/
std::function < void (void *, void *) >
onSeparation(size_t t1, size_t t2) {
return this
->actions[std::pair<size_t, size_t>(t1,t2)].second;
}
};
private:
EndPoint * xAxis;
EndPoint * yAxis;
ActionManager actions;
/** Swap two EndPoint * */
void swap(EndPoint * p1, EndPoint * p2) {
p2->next->prev = p1;
p1->next = p2->next;
p1->prev->next = p2;
p1->prev = p2;
p2->next = p1;
}
/** A collision between two AABB on one axis */
inline bool partialCollisionCheck(const AABB & b1,
const AABB & b2,
int dim) {
return (b1.max[dim] <= b2.max[dim] && b1.max[dim] >= b2.min[dim])
|| (b1.min[dim] >= b2.min[dim] && b1.max[dim] <= b2.max[dim]);
}
/**
* Check if two AABB collide using 2 axises
* @see partialCollisionCheck
*/
bool collisionCheck(const AABB & b1, const AABB & b2) {
return partialCollisionCheck (b1, b2, 0)
&& partialCollisionCheck (b1, b2, 1);
}
/** Create the AABB corresponding to a collisionable object
* @param c the object used to create the corresponding AABB
* @return a pointer to freshly heap-allocated AABB
*/
AABB * mk_AABB(Collisionable * c) {
return new AABB(c->getXMin(), c->getYMin(),
c->getXMax(), c->getYMax(),
typeid(c).hash_code(), (void *) c);
}
/** Update EndPoint place and call the appropriate function in case
* of collision/separation
* @param pt the EndPoint to update
*/
void updateEndPoint(EndPoint * pt) {
auto aux =
[&pt, this]
(std::function<EndPoint*(EndPoint*)>succ,
std::function<bool(int,int)>loop_cond,
std::function<bool(EndPoint*,EndPoint*)>mustAdd,
std::function<bool(EndPoint*,EndPoint*)>mustRm) {
EndPoint * tmp = succ(pt);
while (loop_cond(tmp->value, pt->value)) {
this->swap(tmp, pt);
if (mustAdd(pt, tmp)) {
if (this->collisionCheck(*(pt->owner), *(tmp->owner))) {
this->actions.onCollision
(pt->owner->typeId, tmp->owner->typeId)
(pt->owner->owner, tmp->owner->owner);
}
} else if (mustRm(pt, tmp)) {
this->actions.onSeparation
(pt->owner->typeId,tmp->owner->typeId)
(pt->owner->owner, tmp->owner->owner);
}
}
};
/** TODO: use aux to update on x and y axis */
}
public:
SAPList () {
/* not sure about the true/false values */
xAxis = new EndPoint(NULL, INT_MIN, true, NULL, NULL);
xAxis->next = new EndPoint(NULL, INT_MAX, false, xAxis, NULL);
yAxis = new EndPoint(NULL, INT_MIN, true, NULL, NULL);
yAxis->next = new EndPoint(NULL, INT_MAX, false, yAxis, NULL);
}
~SAPList () {
while (xAxis->next != NULL) {
delete xAxis->next;
} delete xAxis;
while (yAxis->next != NULL) {
delete yAxis->next;
} delete yAxis;
}
void addObject(const Collisionable &) {}
void updateObject(const Collisionable &) {}
void removeObject(const Collisionable &) {}
};
#endif
<|endoftext|>
|
<commit_before>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>
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 "Sampler.h"
#include <Utility/Debug.h>
#include "Context.h"
#include "Implementation/State.h"
#include "Implementation/TextureState.h"
#include "Extensions.h"
namespace Magnum {
/* Check correctness of binary OR in setMinificationFilter(). If nobody fucks
anything up, this assert should produce the same results on all dimensions,
thus testing only on AbstractTexture. */
#define filter_or(filter, mipmap) (GLint(Sampler::Filter::filter)|GLint(Sampler::Mipmap::mipmap))
static_assert((filter_or(Nearest, Base) == GL_NEAREST) &&
(filter_or(Nearest, Nearest) == GL_NEAREST_MIPMAP_NEAREST) &&
(filter_or(Nearest, Linear) == GL_NEAREST_MIPMAP_LINEAR) &&
(filter_or(Linear, Base) == GL_LINEAR) &&
(filter_or(Linear, Nearest) == GL_LINEAR_MIPMAP_NEAREST) &&
(filter_or(Linear, Linear) == GL_LINEAR_MIPMAP_LINEAR),
"Unsupported constants for GL texture filtering");
#undef filter_or
Float Sampler::maxAnisotropy() {
if(!Context::current()->isExtensionSupported<Extensions::GL::EXT::texture_filter_anisotropic>())
return 0.0f;
GLfloat& value = Context::current()->state().texture->maxAnisotropy;
/** @todo Re-enable when extension header is available */
#ifndef MAGNUM_TARGET_GLES
/* Get the value, if not already cached */
if(value == 0.0f)
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &value);
#endif
return value;
}
#ifndef DOXYGEN_GENERATING_OUTPUT
Debug operator<<(Debug debug, const Sampler::Filter value) {
switch(value) {
#define _c(value) case Sampler::Filter::value: return debug << "Sampler::Filter::" #value;
_c(Nearest)
_c(Linear)
#undef _c
}
return debug << "Sampler::Filter::(invalid)";
}
Debug operator<<(Debug debug, const Sampler::Mipmap value) {
switch(value) {
#define _c(value) case Sampler::Mipmap::value: return debug << "Sampler::Mipmap::" #value;
_c(Base)
_c(Nearest)
_c(Linear)
#undef _c
}
return debug << "Sampler::Mipmap::(invalid)";
}
Debug operator<<(Debug debug, const Sampler::Wrapping value) {
switch(value) {
#define _c(value) case Sampler::Wrapping::value: return debug << "Sampler::Wrapping::" #value;
_c(Repeat)
_c(MirroredRepeat)
_c(ClampToEdge)
_c(ClampToBorder)
#ifndef MAGNUM_TARGET_GLES
_c(MirrorClampToEdge)
#endif
#undef _c
}
return debug << "Sampler::Wrapping::(invalid)";
}
#endif
}
<commit_msg>Sampler: remove old ES-specific workaround.<commit_after>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>
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 "Sampler.h"
#include <Utility/Debug.h>
#include "Context.h"
#include "Implementation/State.h"
#include "Implementation/TextureState.h"
#include "Extensions.h"
namespace Magnum {
/* Check correctness of binary OR in setMinificationFilter(). If nobody fucks
anything up, this assert should produce the same results on all dimensions,
thus testing only on AbstractTexture. */
#define filter_or(filter, mipmap) (GLint(Sampler::Filter::filter)|GLint(Sampler::Mipmap::mipmap))
static_assert((filter_or(Nearest, Base) == GL_NEAREST) &&
(filter_or(Nearest, Nearest) == GL_NEAREST_MIPMAP_NEAREST) &&
(filter_or(Nearest, Linear) == GL_NEAREST_MIPMAP_LINEAR) &&
(filter_or(Linear, Base) == GL_LINEAR) &&
(filter_or(Linear, Nearest) == GL_LINEAR_MIPMAP_NEAREST) &&
(filter_or(Linear, Linear) == GL_LINEAR_MIPMAP_LINEAR),
"Unsupported constants for GL texture filtering");
#undef filter_or
Float Sampler::maxAnisotropy() {
if(!Context::current()->isExtensionSupported<Extensions::GL::EXT::texture_filter_anisotropic>())
return 0.0f;
GLfloat& value = Context::current()->state().texture->maxAnisotropy;
/* Get the value, if not already cached */
if(value == 0.0f)
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &value);
return value;
}
#ifndef DOXYGEN_GENERATING_OUTPUT
Debug operator<<(Debug debug, const Sampler::Filter value) {
switch(value) {
#define _c(value) case Sampler::Filter::value: return debug << "Sampler::Filter::" #value;
_c(Nearest)
_c(Linear)
#undef _c
}
return debug << "Sampler::Filter::(invalid)";
}
Debug operator<<(Debug debug, const Sampler::Mipmap value) {
switch(value) {
#define _c(value) case Sampler::Mipmap::value: return debug << "Sampler::Mipmap::" #value;
_c(Base)
_c(Nearest)
_c(Linear)
#undef _c
}
return debug << "Sampler::Mipmap::(invalid)";
}
Debug operator<<(Debug debug, const Sampler::Wrapping value) {
switch(value) {
#define _c(value) case Sampler::Wrapping::value: return debug << "Sampler::Wrapping::" #value;
_c(Repeat)
_c(MirroredRepeat)
_c(ClampToEdge)
_c(ClampToBorder)
#ifndef MAGNUM_TARGET_GLES
_c(MirrorClampToEdge)
#endif
#undef _c
}
return debug << "Sampler::Wrapping::(invalid)";
}
#endif
}
<|endoftext|>
|
<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <Trigger.hpp>
void trigger(const unsigned int firstSynthesizedBeam, const Options &options, const unsigned int padding, const unsigned int integration, const AstroData::Observation &observation, const HostMemory &hostMemory, TriggeredEvents &triggeredEvents)
{
unsigned int nrDMs = 0;
if (options.subbandDedispersion)
{
nrDMs = observation.getNrDMs(true) * observation.getNrDMs();
}
else
{
nrDMs = observation.getNrDMs();
}
for (unsigned int beam = 0; beam < options.nrSynthesizedBeamsPerChunk; beam++)
{
for (unsigned int dm = 0; dm < nrDMs; dm++)
{
unsigned int maxIndex = 0;
outputDataType maxSNR = 0;
// outputDataType maxSNR_mad = 0;
if (options.snrMode == SNRMode::Standard)
{
maxSNR = hostMemory.snrData.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
maxIndex = hostMemory.snrSamples.at((beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm);
}
else if (options.snrMode == SNRMode::Momad)
{
maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (hostMemory.medianOfMediansAbsoluteDeviation.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) * 1.48);
maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm);
}
else if ( options.snrMode == SNRMode::MomSigmaCut )
{
maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (options.sigmaCorrectionFactor * hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm));
maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
}
if ( (std::isnormal(maxSNR)) && (maxSNR >= options.threshold) )
{
TriggeredEvent event;
event.beam = firstSynthesizedBeam + beam;
event.sample = maxIndex;
event.integration = integration;
event.DM = dm;
event.SNR = maxSNR;
try
{
// Add event to its existing list
triggeredEvents.at(beam).at(dm).push_back(event);
}
catch (std::out_of_range &err)
{
// Add event to new list
std::vector<TriggeredEvent> events;
events.push_back(event);
triggeredEvents.at(beam).insert(std::pair<unsigned int, std::vector<TriggeredEvent>>(dm, events));
}
}
}
}
}
void compact(const AstroData::Observation &observation, const TriggeredEvents &triggeredEvents, CompactedEvents &compactedEvents)
{
CompactedEvents temporaryEvents(observation.getNrSynthesizedBeams());
// Compact integration
for (auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents)
{
for (auto dmEvents = beamEvents->begin(); dmEvents != beamEvents->end(); ++dmEvents)
{
CompactedEvent event;
for (auto dmEvent = dmEvents->second.begin(); dmEvent != dmEvents->second.end(); ++dmEvent)
{
if (dmEvent->SNR > event.SNR)
{
event.beam = dmEvent->beam;
event.sample = dmEvent->sample;
event.integration = dmEvent->integration;
event.DM = dmEvent->DM;
event.SNR = dmEvent->SNR;
}
}
event.compactedIntegration = dmEvents->second.size();
temporaryEvents.at(event.beam).push_back(event);
}
}
// Compact DM
for (auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents)
{
for (auto event = beamEvents->begin(); event != beamEvents->end(); ++event)
{
CompactedEvent finalEvent;
unsigned int window = 0;
while ( (event->DM + window) == (event + window)->DM && ((event + window) != beamEvents->end()) )
{
if ((event + window)->SNR > finalEvent.SNR)
{
finalEvent.beam = (event + window)->beam;
finalEvent.sample = (event + window)->sample;
finalEvent.integration = (event + window)->integration;
finalEvent.compactedIntegration = (event + window)->compactedIntegration;
finalEvent.DM = (event + window)->DM;
finalEvent.SNR = (event + window)->SNR;
}
window++;
}
finalEvent.compactedDMs = window;
compactedEvents.at(finalEvent.beam).push_back(finalEvent);
// Move the iterator forward
event += (window - 1);
}
}
}
<commit_msg>Fixed a bug in the trigger.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <Trigger.hpp>
void trigger(const unsigned int firstSynthesizedBeam, const Options &options, const unsigned int padding, const unsigned int integration, const AstroData::Observation &observation, const HostMemory &hostMemory, TriggeredEvents &triggeredEvents)
{
unsigned int nrDMs = 0;
if (options.subbandDedispersion)
{
nrDMs = observation.getNrDMs(true) * observation.getNrDMs();
}
else
{
nrDMs = observation.getNrDMs();
}
for (unsigned int beam = 0; beam < options.nrSynthesizedBeamsPerChunk; beam++)
{
for (unsigned int dm = 0; dm < nrDMs; dm++)
{
unsigned int maxIndex = 0;
outputDataType maxSNR = 0;
// outputDataType maxSNR_mad = 0;
if (options.snrMode == SNRMode::Standard)
{
maxSNR = hostMemory.snrData.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
maxIndex = hostMemory.snrSamples.at((beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm);
}
else if (options.snrMode == SNRMode::Momad)
{
maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (hostMemory.medianOfMediansAbsoluteDeviation.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) * 1.48);
maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(unsigned int))) + dm);
}
else if ( options.snrMode == SNRMode::MomSigmaCut )
{
maxSNR = (hostMemory.maxValues.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm) - hostMemory.medianOfMedians.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm)) / (options.sigmaCorrectionFactor * hostMemory.stdevs.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm));
maxIndex = hostMemory.maxIndices.at((beam * isa::utils::pad(nrDMs, padding / sizeof(float))) + dm);
}
if ( (std::isnormal(maxSNR)) && (maxSNR >= options.threshold) )
{
TriggeredEvent event;
event.beam = firstSynthesizedBeam + beam;
event.sample = maxIndex;
event.integration = integration;
event.DM = dm;
event.SNR = maxSNR;
try
{
// Add event to its existing list
triggeredEvents.at(firstSynthesizedBeam + beam).at(dm).push_back(event);
}
catch (std::out_of_range &err)
{
// Add event to new list
std::vector<TriggeredEvent> events;
events.push_back(event);
triggeredEvents.at(firstSynthesizedBeam + beam).insert(std::pair<unsigned int, std::vector<TriggeredEvent>>(dm, events));
}
}
}
}
}
void compact(const AstroData::Observation &observation, const TriggeredEvents &triggeredEvents, CompactedEvents &compactedEvents)
{
CompactedEvents temporaryEvents(observation.getNrSynthesizedBeams());
// Compact integration
for (auto beamEvents = triggeredEvents.begin(); beamEvents != triggeredEvents.end(); ++beamEvents)
{
for (auto dmEvents = beamEvents->begin(); dmEvents != beamEvents->end(); ++dmEvents)
{
CompactedEvent event;
for (auto dmEvent = dmEvents->second.begin(); dmEvent != dmEvents->second.end(); ++dmEvent)
{
if (dmEvent->SNR > event.SNR)
{
event.beam = dmEvent->beam;
event.sample = dmEvent->sample;
event.integration = dmEvent->integration;
event.DM = dmEvent->DM;
event.SNR = dmEvent->SNR;
}
}
event.compactedIntegration = dmEvents->second.size();
temporaryEvents.at(event.beam).push_back(event);
}
}
// Compact DM
for (auto beamEvents = temporaryEvents.begin(); beamEvents != temporaryEvents.end(); ++beamEvents)
{
for (auto event = beamEvents->begin(); event != beamEvents->end(); ++event)
{
CompactedEvent finalEvent;
unsigned int window = 0;
while ( (event->DM + window) == (event + window)->DM && ((event + window) != beamEvents->end()) )
{
if ((event + window)->SNR > finalEvent.SNR)
{
finalEvent.beam = (event + window)->beam;
finalEvent.sample = (event + window)->sample;
finalEvent.integration = (event + window)->integration;
finalEvent.compactedIntegration = (event + window)->compactedIntegration;
finalEvent.DM = (event + window)->DM;
finalEvent.SNR = (event + window)->SNR;
}
window++;
}
finalEvent.compactedDMs = window;
compactedEvents.at(finalEvent.beam).push_back(finalEvent);
// Move the iterator forward
event += (window - 1);
}
}
}
<|endoftext|>
|
<commit_before>/*
* Vector2.cpp
*
* Created on: 21/12/2013
* Author: vitor
*/
#include "Vector2.h"
Vector2::Vector2(float x, float y) {
this->x = x;
this->y = y;
}
Vector2::~Vector2() {
}
Vector2 Vector2::operator +(Vector2 other) {
return Vector2(this->x + other.x, this->y + other.y);
}
void Vector2::operator +=(Vector2 other) {
this->x = this->x + other.x;
this->y = this->y + other.y;
}
Vector2 Vector2::operator -(Vector2 other) {
return Vector2(this->x - other.x, this->y - other.y);
}
void Vector2::operator -=(Vector2 other) {
this->x = this->x - other.x;
this->y = this->y - other.y;
}
Vector2 Vector2::operator *(float scalar) {
return Vector2(this->x * scalar, this->y * scalar);
}
void Vector2::operator *=(float scalar) {
this->x = this->x * scalar;
this->y = this->y * scalar;
}
float Vector2::operator *(Vector2 other) {
return this->x * other.x + this->y * other.y;
}
float Vector2::length() {
return sqrt(this->x * this->x + this->y * this->y);
}
/*
* Angle from -180 to 180, inclusive
*/
float Vector2::angle() {
return ((M_PI / 180) * atan2(y, x));
}
Vector2 Vector2::normalize() {
float vecLength = length();
if (vecLength == 0.0) {
throw std::logic_error("Attempted to normalize zero vector.\n");
}
return Vector2(this->x / vecLength, this->y / vecLength);
}
Vector2 Vector2::rotate(float angleInDegrees) {
float angleInRadians = angleInDegrees * M_PI / 180;
return Vector2(
this->x * cos(angleInRadians) - this->y * sin(angleInRadians),
this->x * sin(angleInRadians) + this->y * cos(angleInRadians));
}
Vector2 Vector2::normal_vector() {
return rotate(90);
}
float Vector2::distance(Vector2 other) {
float diffx = this->x - other.x;
float diffy = this->y - other.y;
return sqrt((diffx * diffx) + (diffy * diffy));
}
<commit_msg>Fixed bug with angle method.<commit_after>/*
* Vector2.cpp
*
* Created on: 21/12/2013
* Author: vitor
*/
#include "Vector2.h"
Vector2::Vector2(float x, float y) {
this->x = x;
this->y = y;
}
Vector2::~Vector2() {
}
Vector2 Vector2::operator +(Vector2 other) {
return Vector2(this->x + other.x, this->y + other.y);
}
void Vector2::operator +=(Vector2 other) {
this->x = this->x + other.x;
this->y = this->y + other.y;
}
Vector2 Vector2::operator -(Vector2 other) {
return Vector2(this->x - other.x, this->y - other.y);
}
void Vector2::operator -=(Vector2 other) {
this->x = this->x - other.x;
this->y = this->y - other.y;
}
Vector2 Vector2::operator *(float scalar) {
return Vector2(this->x * scalar, this->y * scalar);
}
void Vector2::operator *=(float scalar) {
this->x = this->x * scalar;
this->y = this->y * scalar;
}
float Vector2::operator *(Vector2 other) {
return this->x * other.x + this->y * other.y;
}
float Vector2::length() {
return sqrt(this->x * this->x + this->y * this->y);
}
/*
* Angle from -180 to 180, inclusive
*/
float Vector2::angle() {
return ((180.0 / M_PI) * atan2(y, x));
}
Vector2 Vector2::normalize() {
float vecLength = length();
if (vecLength == 0.0) {
throw std::logic_error("Attempted to normalize zero vector.\n");
}
return Vector2(this->x / vecLength, this->y / vecLength);
}
Vector2 Vector2::rotate(float angleInDegrees) {
float angleInRadians = angleInDegrees * M_PI / 180;
return Vector2(
this->x * cos(angleInRadians) - this->y * sin(angleInRadians),
this->x * sin(angleInRadians) + this->y * cos(angleInRadians));
}
Vector2 Vector2::normal_vector() {
return rotate(90);
}
float Vector2::distance(Vector2 other) {
float diffx = this->x - other.x;
float diffy = this->y - other.y;
return sqrt((diffx * diffx) + (diffy * diffy));
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2016 2017 2018 Jon Taylor
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "blockdb.h"
#include <sstream>
#include <unistd.h> // open and close
#include "leveldb/db.h"
#include "platform.h"
#include "log.h";
#include <boost/lexical_cast.hpp>
using namespace std;
/**
* getDatabase
*
* Description: Get a levelDB instance.
*/
leveldb::DB * CBlockDB::getDatabase(){
CPlatform platform;
CFunctions functions;
std::string dbPath = platform.getSafirePath();
//std::cout << dbPath << std::endl;
leveldb::DB* db;
leveldb::Options options;
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, "./blockdb", &db);
if (false == status.ok())
{
cerr << "Unable to open/create test database './blockdb'" << endl;
cerr << status.ToString() << endl;
//return null;
}
leveldb::WriteOptions writeOptions;
return db;
}
/**
* AddBlock
*
* Description: Add a block json to the database. Indexed by block number.
*
* @param: CFunctions::block_structure block - structure representing block information.
* @return bool returns 1 is successfull.
*/
bool CBlockDB::AddBlock(CFunctions::block_structure block){
CFunctions functions;
/*
CPlatform platform;
std::string dbPath = platform.getSafirePath();
//std::cout << dbPath << std::endl;
leveldb::DB* db;
leveldb::Options options;
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, "./blockdb", &db);
if (false == status.ok())
{
cerr << "Unable to open/create test database './blockdb'" << endl;
cerr << status.ToString() << endl;
return -1;
}
*/
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
// Insert block record into leveldb
ostringstream keyStream;
keyStream << "b_" << boost::lexical_cast<std::string>(block.number);
ostringstream valueStream;
valueStream << functions.blockJSON(block);
db->Put(writeOptions, keyStream.str(), valueStream.str());
// Insert all sender_key->block_id records for fast lookup.
for(int i = 0; i < block.records.size(); i++ ){
CFunctions::record_structure record = block.records.at(i);
ostringstream sendKeyStream;
sendKeyStream << "s_" << record.sender_public_key;
ostringstream sendValueStream;
sendValueStream << functions.blockJSON(block);
//db->Put(writeOptions, sendKeyStream.str(), sendValueStream.str());
}
// Insert all recipient_public_key->block_id records for fast lookup.
for(int i = 0; i < block.records.size(); i++ ){
}
// Save index to next block
if(block.previous_block_id > -1){
ostringstream keyStream;
keyStream << "next_block_" << block.previous_block_id;
ostringstream valueStream;
valueStream << block.number;
db->Put(writeOptions, keyStream.str(), valueStream.str());
}
setLatestBlockId(block.number);
// Close the database
delete db;
return true;
}
/**
* setFirstBlockId
*
* Description: Set the dedicated entity recording the network wide first genesis block by id.
* Nodes that create a network will set this. Nodes that startup without this value need
* to retrieve past block data starting from this first block.
*/
void CBlockDB::setFirstBlockId(long number){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
ostringstream keyStream;
keyStream << "first_block_id";
ostringstream valueStream;
valueStream << boost::lexical_cast<std::string>(number);
db->Put(writeOptions, keyStream.str(), valueStream.str());
delete db;
//std::cout << " set first " << number << "\n";
}
/**
* getFirstBlockId
*
* Description: Retruen the stord first block id. Represents the start of the chain.
* If this is missing the node has to:
* A) retrieve the chain from other nodes or
* B) start a new network.
*/
long CBlockDB::getFirstBlockId(){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
std::string key = "first_block_id";
std::string firstBlockIdString;
db->Get(leveldb::ReadOptions(), key, &firstBlockIdString);
long result = -1;
if(firstBlockIdString.length() > 0){
//result = std::stol(firstBlockIdString);
result = boost::lexical_cast<long>(firstBlockIdString);
//std::cout << " --- " << firstBlockIdString << "\n";
}
delete db;
//std::cout << " get first " << result << "\n";
return result;
}
void CBlockDB::setLatestBlockId(long number){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
ostringstream keyStream;
keyStream << "latest_block_id";
ostringstream valueStream;
valueStream << boost::lexical_cast<std::string>(number);
db->Put(writeOptions, keyStream.str(), valueStream.str());
delete db;
}
long CBlockDB::getLatestBlockId(){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
std::string key = "latest_block_id"; // boost::lexical_cast<std::string>(number);
std::string latestBlockIdString;
db->Get(leveldb::ReadOptions(), key, &latestBlockIdString);
delete db;
long result = -1;
//std::stol(firstBlockId);
if(latestBlockIdString.length() > 0){
result = boost::lexical_cast<long>(latestBlockIdString);
}
return result;
}
/**
* getNextBlockId
*
* Description: Get a block id for the block that follows after a given block id.
* Blocks are generated in sequance but there may be ommitions if a node does not generate
* a block. Each block contains the previous block id and a db index stores these in an index
* for fast lookup.
*/
long CBlockDB::getNextBlockId(long previousBlockId){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
ostringstream keyStream;
keyStream << "next_block_" << previousBlockId;
std::string nextBlockIdString;
db->Get(leveldb::ReadOptions(), keyStream.str(), &nextBlockIdString);
delete db;
long result = -1; //std::stol(nextBlockIdString);
if(nextBlockIdString.length() > 0){
result = boost::lexical_cast<long>(nextBlockIdString);
}
std::cout << " next " << result << "\n";
return result;
}
/**
* GetBlocks
*
* Description: get a list of blocks from the DB.
*
* @return:
*/
void CBlockDB::GetBlocks(){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
// Iterate over each item in the database and print them
leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next())
{
cout << it->key().ToString() << " : " << it->value().ToString() << endl;
}
if (false == it->status().ok())
{
cerr << "An error was found during the scan" << endl;
cerr << it->status().ToString() << endl;
}
delete it;
// Close the database
delete db;
}
/**
* getBlock
*
* Description: Get a block by number
*
* @param: number (long) id of block to look up as a key
*/
CFunctions::block_structure CBlockDB::getBlock(long number){
CFunctions::block_structure block;
block.number = -1;
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
std::string key = "b_" + boost::lexical_cast<std::string>(number);
std::string blockJson;
db->Get(leveldb::ReadOptions(), key, &blockJson);
CFunctions functions;
std::vector<CFunctions::block_structure> blocks = functions.parseBlockJson(blockJson);
if(blocks.size() > 0){
block = blocks.at(0);
}
// Close the database
delete db;
return block;
}
/**
* getNextBlock
*
* Description: get the next block in the chain.
*/
CFunctions::block_structure CBlockDB::getNextBlock(CFunctions::block_structure block){
long nextId = getNextBlockId(block.number);
CFunctions::block_structure nextBlock = getBlock(nextId);
return nextBlock;
}
/**
* GetBlockWithSender
*
* Description: Return a block record that contains a sender key in it.
* If no block exists, return null.
* This can be used to look up a block record validating a sender has been approved by the network.
*
* @param sender_key string.
* @param index int.
* @return block_structure.
*/
CFunctions::block_structure CBlockDB::GetBlockWithSender( std::string sender_key, int index ){
CFunctions::block_structure block;
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
// todo:
delete db;
return block;
}
/**
* DeleteAll
*
* Description: Delete all data in the levelDB database.
*/
void CBlockDB::DeleteAll(){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
// Iterate over each item in the database and print them
leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next())
{
//cout << it->key().ToString() << " : " << it->value().ToString() << endl;
db->Delete(leveldb::WriteOptions(), it->key().ToString());
cout << "Delete: " << it->key().ToString() << "\n";
}
if (false == it->status().ok())
{
cerr << "An error was found during the scan" << endl;
cerr << it->status().ToString() << endl;
}
delete it;
delete db;
}
<commit_msg>Bug fix.<commit_after>// Copyright (c) 2016 2017 2018 Jon Taylor
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "blockdb.h"
#include <sstream>
#include <unistd.h> // open and close
#include "leveldb/db.h"
#include "platform.h"
#include "log.h";
#include <boost/lexical_cast.hpp>
using namespace std;
/**
* getDatabase
*
* Description: Get a levelDB instance.
*/
leveldb::DB * CBlockDB::getDatabase(){
CPlatform platform;
CFunctions functions;
std::string dbPath = platform.getSafirePath();
//std::cout << dbPath << std::endl;
leveldb::DB* db;
leveldb::Options options;
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, "./blockdb", &db);
if (false == status.ok())
{
cerr << "Unable to open/create test database './blockdb'" << endl;
cerr << status.ToString() << endl;
//return null;
}
leveldb::WriteOptions writeOptions;
return db;
}
/**
* AddBlock
*
* Description: Add a block json to the database. Indexed by block number.
*
* @param: CFunctions::block_structure block - structure representing block information.
* @return bool returns 1 is successfull.
*/
bool CBlockDB::AddBlock(CFunctions::block_structure block){
CFunctions functions;
/*
CPlatform platform;
std::string dbPath = platform.getSafirePath();
//std::cout << dbPath << std::endl;
leveldb::DB* db;
leveldb::Options options;
options.create_if_missing = true;
leveldb::Status status = leveldb::DB::Open(options, "./blockdb", &db);
if (false == status.ok())
{
cerr << "Unable to open/create test database './blockdb'" << endl;
cerr << status.ToString() << endl;
return -1;
}
*/
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
// Insert block record into leveldb
ostringstream keyStream;
keyStream << "b_" << boost::lexical_cast<std::string>(block.number);
ostringstream valueStream;
valueStream << functions.blockJSON(block);
db->Put(writeOptions, keyStream.str(), valueStream.str());
// Insert all sender_key->block_id records for fast lookup.
for(int i = 0; i < block.records.size(); i++ ){
CFunctions::record_structure record = block.records.at(i);
ostringstream sendKeyStream;
sendKeyStream << "s_" << record.sender_public_key;
ostringstream sendValueStream;
sendValueStream << functions.blockJSON(block);
//db->Put(writeOptions, sendKeyStream.str(), sendValueStream.str());
}
// Insert all recipient_public_key->block_id records for fast lookup.
for(int i = 0; i < block.records.size(); i++ ){
}
// Save index to next block
if(block.previous_block_id > -1){
ostringstream keyStream;
keyStream << "next_block_" << block.previous_block_id;
ostringstream valueStream;
valueStream << block.number;
db->Put(writeOptions, keyStream.str(), valueStream.str());
}
// Close the database
delete db;
setLatestBlockId(block.number);
return true;
}
/**
* setFirstBlockId
*
* Description: Set the dedicated entity recording the network wide first genesis block by id.
* Nodes that create a network will set this. Nodes that startup without this value need
* to retrieve past block data starting from this first block.
*/
void CBlockDB::setFirstBlockId(long number){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
ostringstream keyStream;
keyStream << "first_block_id";
ostringstream valueStream;
valueStream << boost::lexical_cast<std::string>(number);
db->Put(writeOptions, keyStream.str(), valueStream.str());
delete db;
//std::cout << " set first " << number << "\n";
}
/**
* getFirstBlockId
*
* Description: Retruen the stord first block id. Represents the start of the chain.
* If this is missing the node has to:
* A) retrieve the chain from other nodes or
* B) start a new network.
*/
long CBlockDB::getFirstBlockId(){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
std::string key = "first_block_id";
std::string firstBlockIdString;
db->Get(leveldb::ReadOptions(), key, &firstBlockIdString);
long result = -1;
if(firstBlockIdString.length() > 0){
//result = std::stol(firstBlockIdString);
result = boost::lexical_cast<long>(firstBlockIdString);
//std::cout << " --- " << firstBlockIdString << "\n";
}
delete db;
//std::cout << " get first " << result << "\n";
return result;
}
void CBlockDB::setLatestBlockId(long number){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
ostringstream keyStream;
keyStream << "latest_block_id";
ostringstream valueStream;
valueStream << boost::lexical_cast<std::string>(number);
db->Put(writeOptions, keyStream.str(), valueStream.str());
delete db;
}
long CBlockDB::getLatestBlockId(){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
std::string key = "latest_block_id"; // boost::lexical_cast<std::string>(number);
std::string latestBlockIdString;
db->Get(leveldb::ReadOptions(), key, &latestBlockIdString);
delete db;
long result = -1;
//std::stol(firstBlockId);
if(latestBlockIdString.length() > 0){
result = boost::lexical_cast<long>(latestBlockIdString);
}
return result;
}
/**
* getNextBlockId
*
* Description: Get a block id for the block that follows after a given block id.
* Blocks are generated in sequance but there may be ommitions if a node does not generate
* a block. Each block contains the previous block id and a db index stores these in an index
* for fast lookup.
*/
long CBlockDB::getNextBlockId(long previousBlockId){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
ostringstream keyStream;
keyStream << "next_block_" << previousBlockId;
std::string nextBlockIdString;
db->Get(leveldb::ReadOptions(), keyStream.str(), &nextBlockIdString);
delete db;
long result = -1; //std::stol(nextBlockIdString);
if(nextBlockIdString.length() > 0){
result = boost::lexical_cast<long>(nextBlockIdString);
}
std::cout << " next " << result << "\n";
return result;
}
/**
* GetBlocks
*
* Description: get a list of blocks from the DB.
*
* @return:
*/
void CBlockDB::GetBlocks(){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
// Iterate over each item in the database and print them
leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next())
{
cout << it->key().ToString() << " : " << it->value().ToString() << endl;
}
if (false == it->status().ok())
{
cerr << "An error was found during the scan" << endl;
cerr << it->status().ToString() << endl;
}
delete it;
// Close the database
delete db;
}
/**
* getBlock
*
* Description: Get a block by number
*
* @param: number (long) id of block to look up as a key
*/
CFunctions::block_structure CBlockDB::getBlock(long number){
CFunctions::block_structure block;
block.number = -1;
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
std::string key = "b_" + boost::lexical_cast<std::string>(number);
std::string blockJson;
db->Get(leveldb::ReadOptions(), key, &blockJson);
CFunctions functions;
std::vector<CFunctions::block_structure> blocks = functions.parseBlockJson(blockJson);
if(blocks.size() > 0){
block = blocks.at(0);
}
// Close the database
delete db;
return block;
}
/**
* getNextBlock
*
* Description: get the next block in the chain.
*/
CFunctions::block_structure CBlockDB::getNextBlock(CFunctions::block_structure block){
long nextId = getNextBlockId(block.number);
CFunctions::block_structure nextBlock = getBlock(nextId);
return nextBlock;
}
/**
* GetBlockWithSender
*
* Description: Return a block record that contains a sender key in it.
* If no block exists, return null.
* This can be used to look up a block record validating a sender has been approved by the network.
*
* @param sender_key string.
* @param index int.
* @return block_structure.
*/
CFunctions::block_structure CBlockDB::GetBlockWithSender( std::string sender_key, int index ){
CFunctions::block_structure block;
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
// todo:
delete db;
return block;
}
/**
* DeleteAll
*
* Description: Delete all data in the levelDB database.
*/
void CBlockDB::DeleteAll(){
leveldb::WriteOptions writeOptions;
leveldb::DB* db = getDatabase();
// Iterate over each item in the database and print them
leveldb::Iterator* it = db->NewIterator(leveldb::ReadOptions());
for (it->SeekToFirst(); it->Valid(); it->Next())
{
//cout << it->key().ToString() << " : " << it->value().ToString() << endl;
db->Delete(leveldb::WriteOptions(), it->key().ToString());
cout << "Delete: " << it->key().ToString() << "\n";
}
if (false == it->status().ok())
{
cerr << "An error was found during the scan" << endl;
cerr << it->status().ToString() << endl;
}
delete it;
delete db;
}
<|endoftext|>
|
<commit_before>#include "bxsplit.h"
#include "bxcommon.h"
#include <string>
#include <getopt.h>
#include <iostream>
#include <sstream>
#include "SeqLib/BamReader.h"
#include "SeqLib/BamWriter.h"
struct BXTag {
SeqLib::BamWriter w;
size_t count = 0;
SeqLib::BamRecordVector buff;
};
namespace opt {
static std::string bam; // the bam to split
static std::string analysis_id = "foo"; // unique prefix for output
static bool verbose = false;
static bool noop = false; // dont write bams, just count
static int min = 0; // minimum number of reads before writing
static std::string tag = "BX"; // tag to split by
}
static const char* shortopts = "hvxb:a:m:t:";
static const struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "no-output", no_argument, NULL, 'x' },
{ "analysis-id", required_argument, NULL, 'a' },
{ "verbose", no_argument, NULL, 'v' },
{ "min-reads", required_argument, NULL, 'm' },
{ "tag", required_argument, NULL, 't' },
{ NULL, 0, NULL, 0 }
};
static const char *SPLIT_USAGE_MESSAGE =
"Usage: bxtools split <BAM/SAM/CRAM> -a <id> > bxcounts.tsv\n"
"Description: Split / count a BAM into multiple BAMs, one BAM per unique BX tag\n"
"\n"
" General options\n"
" -v, --verbose Select verbosity level (0-4). Default: 0 \n"
" -h, --help Display this help and exit\n"
" -a, --analysis-id ID to prefix output files with [foo]\n"
" -x, --no-output Don't output BAMs (count only) [off]\n"
" -m, --min-reads Minumum reads of given tag to see before writing [0]\n"
" -t, --tag Split by a tag other than BX (e.g. MI)\n"
"\n";
void parseSplitOptions(int argc, char** argv) {
bool die = false;
if (argc < 2)
die = true;
else
opt::bam = std::string(argv[1]);
bool help = false;
std::stringstream ss;
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case 'a': arg >> opt::analysis_id; break;
case 'v': opt::verbose = true; break;
case 'x': opt::noop = true; break;
case 'm': arg >> opt::min; break;
case 't': arg >> opt::tag; break;
}
}
if (die || help) {
std::cerr << "\n" << SPLIT_USAGE_MESSAGE;
die ? exit(EXIT_FAILURE) : exit(EXIT_SUCCESS);
}
}
void runSplit(int argc, char** argv) {
parseSplitOptions(argc, argv);
// opeen the BAM
SeqLib::BamReader reader;
if (!reader.Open(opt::bam)) {
std::cerr << "Failed to open bam: " << opt::bam << std::endl;
exit(EXIT_FAILURE);
}
// make a collection of writers
std::unordered_map<std::string, BXTag> tags;
// loop and write
SeqLib::BamRecord r;
size_t count = 0;
bool hit = false;
while (reader.GetNextRecord(r)) {
++count;
// sanity check
BXLOOPCHECK(r, hit, opt::tag)
std::string bx;
r.GetTag(opt::tag, bx);
if (bx.empty()) {
continue;
} else {
hit = true;
}
++tags[bx].count;
if (opt::noop)
continue;
if (tags[bx].count < opt::min) {
tags[bx].buff.push_back(r);
continue;
}
// have a buffer to clear or hit first read with no min
if (tags[bx].buff.size() || (opt::min <= 0 && tags[bx].count == 1)) {
// need to establish a new writer?
std::string bname = opt::analysis_id + "." + bx + ".bam";
if (!tags[bx].w.Open(bname)) {
std::cerr << "Could not open BAM: " << bname << std::endl;
exit(EXIT_FAILURE);
}
std::cerr << "creating new output BAM: " << bname << std::endl;
tags[bx].w.SetHeader(reader.Header());
tags[bx].w.WriteHeader();
for (const auto& rr : tags[bx].buff)
tags[bx].w.WriteRecord(rr);
tags[bx].buff.clear();
continue;
}
if (!tags[bx].w.WriteRecord(r)) {
std::cerr << "failed to write read " << r << " to BAM for " << bx << std::endl;
exit(EXIT_FAILURE);
}
}
// print the final counts to std::out
for (const auto& b : tags)
std::cout << b.first << "\t" << b.second.count << std::endl;
}
<commit_msg>added include_empty flag for issue #26<commit_after>#include "bxsplit.h"
#include "bxcommon.h"
#include <string>
#include <getopt.h>
#include <iostream>
#include <sstream>
#include "SeqLib/BamReader.h"
#include "SeqLib/BamWriter.h"
struct BXTag {
SeqLib::BamWriter w;
size_t count = 0;
SeqLib::BamRecordVector buff;
};
namespace opt {
static std::string bam; // the bam to split
static std::string analysis_id = "foo"; // unique prefix for output
static bool verbose = false;
static bool noop = false; // dont write bams, just count
static int min = 0; // minimum number of reads before writing
static std::string tag = "BX"; // tag to split by
static bool include_empty = false; // output BAM with empty reads
}
static const char* shortopts = "hvxeb:a:m:t:";
static const struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "no-output", no_argument, NULL, 'x' },
{ "analysis-id", required_argument, NULL, 'a' },
{ "verbose", no_argument, NULL, 'v' },
{ "include-empty", no_argument, NULL, 'e' },
{ "min-reads", required_argument, NULL, 'm' },
{ "tag", required_argument, NULL, 't' },
{ NULL, 0, NULL, 0 }
};
static const char *SPLIT_USAGE_MESSAGE =
"Usage: bxtools split <BAM/SAM/CRAM> -a <id> > bxcounts.tsv\n"
"Description: Split / count a BAM into multiple BAMs, one BAM per unique BX tag\n"
"\n"
" General options\n"
" -v, --verbose Select verbosity level (0-4). Default: 0 \n"
" -h, --help Display this help and exit\n"
" -a, --analysis-id ID to prefix output files with [foo]\n"
" -x, --no-output Don't output BAMs (count only) [off]\n"
" -m, --min-reads Minumum reads of given tag to see before writing [0]\n"
" -t, --tag Split by a tag other than BX (e.g. MI)\n"
" -e, --include-empty Output a BAM with all of the reads with empty tag\n"
"\n";
void parseSplitOptions(int argc, char** argv) {
bool die = false;
if (argc < 2)
die = true;
else
opt::bam = std::string(argv[1]);
bool help = false;
std::stringstream ss;
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) {
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case 'a': arg >> opt::analysis_id; break;
case 'v': opt::verbose = true; break;
case 'x': opt::noop = true; break;
case 'e': opt::include_empty = true; break;
case 'm': arg >> opt::min; break;
case 't': arg >> opt::tag; break;
}
}
if (die || help) {
std::cerr << "\n" << SPLIT_USAGE_MESSAGE;
die ? exit(EXIT_FAILURE) : exit(EXIT_SUCCESS);
}
}
void runSplit(int argc, char** argv) {
parseSplitOptions(argc, argv);
// opeen the BAM
SeqLib::BamReader reader;
if (!reader.Open(opt::bam)) {
std::cerr << "Failed to open bam: " << opt::bam << std::endl;
exit(EXIT_FAILURE);
}
// make a collection of writers
std::unordered_map<std::string, BXTag> tags;
// loop and write
SeqLib::BamRecord r;
size_t count = 0;
bool hit = false;
while (reader.GetNextRecord(r)) {
++count;
// sanity check
BXLOOPCHECK(r, hit, opt::tag)
std::string bx;
r.GetTag(opt::tag, bx);
if (bx.empty()) {
if (!opt::include_empty)
continue;
bx="bxe"; // bxtools empty
} else {
hit = true;
}
++tags[bx].count;
if (opt::noop)
continue;
if (tags[bx].count < opt::min) {
tags[bx].buff.push_back(r);
continue;
}
// have a buffer to clear or hit first read with no min
if (tags[bx].buff.size() || (opt::min <= 0 && tags[bx].count == 1)) {
// need to establish a new writer?
std::string bname = opt::analysis_id + "." + bx + ".bam";
if (!tags[bx].w.Open(bname)) {
std::cerr << "Could not open BAM: " << bname << std::endl;
exit(EXIT_FAILURE);
}
std::cerr << "creating new output BAM: " << bname << std::endl;
tags[bx].w.SetHeader(reader.Header());
tags[bx].w.WriteHeader();
for (const auto& rr : tags[bx].buff)
tags[bx].w.WriteRecord(rr);
tags[bx].buff.clear();
continue;
}
if (!tags[bx].w.WriteRecord(r)) {
std::cerr << "failed to write read " << r << " to BAM for " << bx << std::endl;
exit(EXIT_FAILURE);
}
}
// print the final counts to std::out
for (const auto& b : tags)
std::cout << b.first << "\t" << b.second.count << std::endl;
}
<|endoftext|>
|
<commit_before>/* cclive
* Copyright (C) 2010-2011 Toni Gundogdu <legatvs@gmail.com>
*
* 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 <iostream>
#include <ccapplication>
#include <ccquvi>
using namespace cc;
int main(int argc, char *argv[])
{
application app;
int rc = 0; // OK.
try
{
rc = app.exec(argc,argv);
}
// Thrown by quvi::query constructor (e.g. quvi_init failure).
catch (const quvi::error& e)
{
std::clog << "libquvi: error: " << e.what() << std::endl;
}
// Thrown by boost (e.g. cc::go_background failure).
catch (const std::runtime_error& e)
{
std::clog << "error: " << e.what() << std::endl;
}
return rc;
}
// vim: set ts=2 sw=2 tw=72 expandtab:
<commit_msg>main: Use exit_status, have caught exceptions set exit status<commit_after>/* cclive
* Copyright (C) 2010-2011 Toni Gundogdu <legatvs@gmail.com>
*
* 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 <iostream>
#include <ccapplication>
#include <ccquvi>
using namespace cc;
int main(int argc, char *argv[])
{
application::exit_status es = application::ok;
application app;
try
{
es = app.exec(argc, argv);
}
// Thrown by quvi::query constructor (e.g. quvi_init failure).
catch (const quvi::error& e)
{
std::clog << "libquvi: error: " << e.what() << std::endl;
es = application::error;
}
// Thrown by boost (e.g. cc::go_background failure).
catch (const std::runtime_error& e)
{
std::clog << "error: " << e.what() << std::endl;
es = application::error;
}
return es;
}
// vim: set ts=2 sw=2 tw=72 expandtab:
<|endoftext|>
|
<commit_before>#ifndef DICE_CHECKED_HPP_
#define DICE_CHECKED_HPP_
#include <limits>
#include <stdexcept>
namespace dice
{
// Check for arithmetic errors
template<typename T, bool is_signed = std::numeric_limits<T>::is_signed>
class checked;
// signed value specialization
template<typename T>
class checked<T, true>
{
public:
checked() {}
checked(const T& value) : value_(value) {}
// allow copy
checked(const checked&) = default;
checked& operator=(const checked&) = default;
// allow move
checked(checked&&) = default;
checked& operator=(checked&&) = default;
/** Compute addition of the 2 values.
* If an overflow occurs, the std::overflow_error is thrown.
* If an uderflow occurs, the std::underflow_error is thrown.
* @param other raw value
* @return result of the addition as a checked type
*/
auto operator+(const T& other_value) const
{
using namespace std;
if (other_value > 0 && value_ > max() - other_value)
{
throw std::overflow_error{
to_string(value_) + " + " + to_string(other_value) };
}
if (other_value < 0 && value_ < min() - other_value)
{
throw std::underflow_error{
to_string(value_) + " + " + to_string(other_value) };
}
return checked<T>{ value_ + other_value };
}
/** Compute subtraction of the 2 values.
* If an overflow occurs, the std::overflow_error is thrown.
* If an uderflow occurs, the std::underflow_error is thrown.
* @param other raw value
* @return result of the subtraction as a checked type
*/
auto operator-(const T& other_value) const
{
using namespace std;
if (other_value < 0 && value_ > max() + other_value)
{
throw std::overflow_error{
to_string(value_) + " - " + to_string(other_value) };
}
if (other_value > 0 && value_ < min() + other_value)
{
throw std::underflow_error{
to_string(value_) + " - " + to_string(other_value) };
}
return checked<T>{ value_ - other_value };
}
/** Compute multiplication of the 2 values.
* If an overflow occurs, the std::overflow_error is thrown.
* If an uderflow occurs, the std::underflow_error is thrown.
* @param other raw value
* @return result of the multiplication as a checked type
*/
auto operator*(const T& other_value) const
{
using namespace std;
auto diff = max() + min();
if (diff < 0)
{
if (value_ == -1 && other_value == min() ||
value_ == min() && other_value == -1)
{
throw std::overflow_error{
to_string(value_) + " * " + to_string(other_value)
};
}
}
else if (diff > 0)
{
if (value_ == -1 && other_value == max() ||
value_ == max() && other_value == -1)
{
throw std::underflow_error{
to_string(value_) + " * " + to_string(other_value)
};
}
}
if (other_value != 0 && value_ != 0 && other_value != -1)
{
// check whether there would be an overflow error
if (other_value > 0 && value_ > max() / other_value ||
other_value < 0 && value_ < max() / other_value)
{
throw std::overflow_error{
to_string(value_) + " * " + to_string(other_value) };
}
// check whether there would be an underflow error
if (other_value > 0 && value_ < min() / other_value ||
other_value < 0 && value_ > min() / other_value)
{
throw std::underflow_error{
to_string(value_) + " * " + to_string(other_value) };
}
}
return checked<T>{ value_ * other_value };
}
/** Compute division of the 2 values.
* If an overflow occurs, the std::overflow_error is thrown.
* If the other_value is zero, the std::overflow_error is thrown.
* @param other raw value
* @return result of the division as a checked type
*/
auto operator/(const T& other_value) const
{
using namespace std;
if (other_value == 0)
{
throw std::overflow_error{ "Division by zero: " +
to_string(value_) + " / 0" };
}
auto diff = max() + min();
if (diff < 0)
{
if (value_ == min() && other_value == -1)
{
throw std::overflow_error{
to_string(value_) + " / " + to_string(other_value)
};
}
}
else if (diff > 0)
{
if (value_ == max() && other_value == -1)
{
throw std::underflow_error{
to_string(value_) + " / " + to_string(other_value)
};
}
}
return checked<T>{ value_ / other_value };
}
/** Compute unary minus of the value.
* If an overflow occurs, the std::overflow_error is thrown.
* @return result of the unary minus as a checked type
*/
auto operator-() const
{
using namespace std;
auto diff = max() + min();
if (diff < 0 && value_ == min())
{
throw std::overflow_error{ "-" + to_string(value_) };
}
else if (diff > 0 && value_ == max())
{
throw std::underflow_error{ "-" + to_string(value_) };
}
return checked<T>{ -value_ };
}
// cast to type T
operator T() const
{
return value_;
}
// explicit value getter/setter
T& value()
{
return value_;
}
const T& value() const
{
return value_;
}
private:
T value_;
static constexpr T max()
{
return std::numeric_limits<T>::max();
}
static constexpr T min()
{
return std::numeric_limits<T>::min();
}
};
// unsigned value specialization
template<typename T>
class checked<T, false>
{
public:
checked() {}
checked(const T& value) : value_(value) {}
// allow copy
checked(const checked&) = default;
checked& operator=(const checked&) = default;
// allow move
checked(checked&&) = default;
checked& operator=(checked&&) = default;
/** Compute addition of the 2 values.
* If an overflow occurs, the std::overflow_error is thrown.
* @param other raw value
* @return result of the addition as a checked type
*/
auto operator+(const T& other_value) const
{
using namespace std;
if (value_ > max() - other_value)
{
throw std::overflow_error{
to_string(value_) + " + " + to_string(other_value) };
}
return checked<T>{ value_ + other_value };
}
/** Compute subtraction of the 2 values.
* If an uderflow occurs, the std::underflow_error is thrown.
* @param other raw value
* @return result of the subtraction as a checked type
*/
auto operator-(const T& other_value) const
{
using namespace std;
if (value_ < other_value)
{
throw std::underflow_error{
to_string(value_) + " - " + to_string(other_value) };
}
return checked<T>{ value_ - other_value };
}
/** Compute multiplication of the 2 values.
* If an overflow occurs, the std::overflow_error is thrown.
* @param other raw value
* @return result of the multiplication as a checked type
*/
auto operator*(const T& other_value) const
{
using namespace std;
// check whether there would be an overflow error
if (other_value != 0 && value_ > max() / other_value)
{
throw std::overflow_error{
to_string(value_) + " * " + to_string(other_value) };
}
return checked<T>{ value_ * other_value };
}
/** Compute division of the 2 values.
* If the other_value is zero, the std::overflow_error is thrown.
* @param other raw value
* @return result of the division as a checked type
*/
auto operator/(const T& other_value) const
{
using namespace std;
if (other_value == 0)
{
throw std::overflow_error{ "Division by zero: " +
to_string(value_) + " / 0" };
}
return checked<T>{ value_ / other_value };
}
/** Compute unary minus of the value.
* If an overflow occurs, the std::overflow_error is thrown.
* @return result of the unary minus as a checked type
*/
auto operator-() const
{
using namespace std;
if (value_ != 0)
{
throw std::underflow_error{ "-" + to_string(value_) };
}
return checked<T>{ 0 };
}
// cast to type T
operator T() const
{
return value_;
}
// explicit value getter/setter
T& value()
{
return value_;
}
const T& value() const
{
return value_;
}
private:
T value_;
static constexpr T max()
{
return std::numeric_limits<T>::max();
}
};
}
#endif // DICE_CHECKED_HPP_<commit_msg>Add factory functions<commit_after>#ifndef DICE_CHECKED_HPP_
#define DICE_CHECKED_HPP_
#include <limits>
#include <stdexcept>
namespace dice
{
// Check for arithmetic errors
template<
typename T,
bool is_integral = std::numeric_limits<T>::is_integer,
bool is_signed = std::numeric_limits<T>::is_signed>
class checked
{
public:
template<typename ValueType>
static auto make(ValueType&& value)
{
return std::forward<ValueType>(value);
}
};
// signed value specialization
template<typename T>
class checked<T, true, true>
{
public:
template<typename ValueType>
static auto make(ValueType&& value)
{
return checked{ std::forward<ValueType>(value) };
}
checked() {}
checked(const T& value) : value_(value) {}
// allow copy
checked(const checked&) = default;
checked& operator=(const checked&) = default;
// allow move
checked(checked&&) = default;
checked& operator=(checked&&) = default;
/** Compute addition of the 2 values.
* If an overflow occurs, the std::overflow_error is thrown.
* If an uderflow occurs, the std::underflow_error is thrown.
* @param other raw value
* @return result of the addition as a checked type
*/
auto operator+(const T& other_value) const
{
using namespace std;
if (other_value > 0 && value_ > max() - other_value)
{
throw std::overflow_error{
to_string(value_) + " + " + to_string(other_value) };
}
if (other_value < 0 && value_ < min() - other_value)
{
throw std::underflow_error{
to_string(value_) + " + " + to_string(other_value) };
}
return checked<T>{ value_ + other_value };
}
/** Compute subtraction of the 2 values.
* If an overflow occurs, the std::overflow_error is thrown.
* If an uderflow occurs, the std::underflow_error is thrown.
* @param other raw value
* @return result of the subtraction as a checked type
*/
auto operator-(const T& other_value) const
{
using namespace std;
if (other_value < 0 && value_ > max() + other_value)
{
throw std::overflow_error{
to_string(value_) + " - " + to_string(other_value) };
}
if (other_value > 0 && value_ < min() + other_value)
{
throw std::underflow_error{
to_string(value_) + " - " + to_string(other_value) };
}
return checked<T>{ value_ - other_value };
}
/** Compute multiplication of the 2 values.
* If an overflow occurs, the std::overflow_error is thrown.
* If an uderflow occurs, the std::underflow_error is thrown.
* @param other raw value
* @return result of the multiplication as a checked type
*/
auto operator*(const T& other_value) const
{
using namespace std;
auto diff = max() + min();
if (diff < 0)
{
if ((value_ == -1 && other_value == min()) ||
(value_ == min() && other_value == -1))
{
throw std::overflow_error{
to_string(value_) + " * " + to_string(other_value)
};
}
}
else if (diff > 0)
{
if ((value_ == -1 && other_value == max()) ||
(value_ == max() && other_value == -1))
{
throw std::underflow_error{
to_string(value_) + " * " + to_string(other_value)
};
}
}
if (other_value != 0 && value_ != 0 && other_value != -1)
{
// check whether there would be an overflow error
if ((other_value > 0 && value_ > max() / other_value) ||
(other_value < 0 && value_ < max() / other_value))
{
throw std::overflow_error{
to_string(value_) + " * " + to_string(other_value) };
}
// check whether there would be an underflow error
if ((other_value > 0 && value_ < min() / other_value) ||
(other_value < 0 && value_ > min() / other_value))
{
throw std::underflow_error{
to_string(value_) + " * " + to_string(other_value) };
}
}
return checked<T>{ value_ * other_value };
}
/** Compute division of the 2 values.
* If an overflow occurs, the std::overflow_error is thrown.
* If the other_value is zero, the std::overflow_error is thrown.
* @param other raw value
* @return result of the division as a checked type
*/
auto operator/(const T& other_value) const
{
using namespace std;
if (other_value == 0)
{
throw std::overflow_error{ "Division by zero: " +
to_string(value_) + " / 0" };
}
auto diff = max() + min();
if (diff < 0)
{
if (value_ == min() && other_value == -1)
{
throw std::overflow_error{
to_string(value_) + " / " + to_string(other_value)
};
}
}
else if (diff > 0)
{
if (value_ == max() && other_value == -1)
{
throw std::underflow_error{
to_string(value_) + " / " + to_string(other_value)
};
}
}
return checked<T>{ value_ / other_value };
}
/** Compute unary minus of the value.
* If an overflow occurs, the std::overflow_error is thrown.
* @return result of the unary minus as a checked type
*/
auto operator-() const
{
using namespace std;
auto diff = max() + min();
if (diff < 0 && value_ == min())
{
throw std::overflow_error{ "-" + to_string(value_) };
}
else if (diff > 0 && value_ == max())
{
throw std::underflow_error{ "-" + to_string(value_) };
}
return checked<T>{ -value_ };
}
// cast to type T
operator T() const
{
return value_;
}
// explicit value getter/setter
T& value()
{
return value_;
}
const T& value() const
{
return value_;
}
private:
T value_;
static constexpr T max()
{
return std::numeric_limits<T>::max();
}
static constexpr T min()
{
return std::numeric_limits<T>::min();
}
};
// unsigned value specialization
template<typename T>
class checked<T, true, false>
{
public:
template<typename ValueType>
static auto make(ValueType&& value)
{
return checked{ std::forward<ValueType>(value) };
}
checked() {}
checked(const T& value) : value_(value) {}
// allow copy
checked(const checked&) = default;
checked& operator=(const checked&) = default;
// allow move
checked(checked&&) = default;
checked& operator=(checked&&) = default;
/** Compute addition of the 2 values.
* If an overflow occurs, the std::overflow_error is thrown.
* @param other raw value
* @return result of the addition as a checked type
*/
auto operator+(const T& other_value) const
{
using namespace std;
if (value_ > max() - other_value)
{
throw std::overflow_error{
to_string(value_) + " + " + to_string(other_value) };
}
return checked<T>{ value_ + other_value };
}
/** Compute subtraction of the 2 values.
* If an uderflow occurs, the std::underflow_error is thrown.
* @param other raw value
* @return result of the subtraction as a checked type
*/
auto operator-(const T& other_value) const
{
using namespace std;
if (value_ < other_value)
{
throw std::underflow_error{
to_string(value_) + " - " + to_string(other_value) };
}
return checked<T>{ value_ - other_value };
}
/** Compute multiplication of the 2 values.
* If an overflow occurs, the std::overflow_error is thrown.
* @param other raw value
* @return result of the multiplication as a checked type
*/
auto operator*(const T& other_value) const
{
using namespace std;
// check whether there would be an overflow error
if (other_value != 0 && value_ > max() / other_value)
{
throw std::overflow_error{
to_string(value_) + " * " + to_string(other_value) };
}
return checked<T>{ value_ * other_value };
}
/** Compute division of the 2 values.
* If the other_value is zero, the std::overflow_error is thrown.
* @param other raw value
* @return result of the division as a checked type
*/
auto operator/(const T& other_value) const
{
using namespace std;
if (other_value == 0)
{
throw std::overflow_error{ "Division by zero: " +
to_string(value_) + " / 0" };
}
return checked<T>{ value_ / other_value };
}
/** Compute unary minus of the value.
* If an overflow occurs, the std::overflow_error is thrown.
* @return result of the unary minus as a checked type
*/
auto operator-() const
{
using namespace std;
if (value_ != 0)
{
throw std::underflow_error{ "-" + to_string(value_) };
}
return checked<T>{ 0 };
}
// cast to type T
operator T() const
{
return value_;
}
// explicit value getter/setter
T& value()
{
return value_;
}
const T& value() const
{
return value_;
}
private:
T value_;
static constexpr T max()
{
return std::numeric_limits<T>::max();
}
};
template<typename T>
auto make_checked(const T& value)
{
return checked<T>{ value };
}
}
#endif // DICE_CHECKED_HPP_<|endoftext|>
|
<commit_before>/**
* @file command.cpp
* @brief Request command component
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "mega/command.h"
#include "mega/base64.h"
#include "mega/megaclient.h"
namespace mega {
Command::Command()
{
persistent = false;
canceled = false;
result = API_OK;
client = NULL;
tag = 0;
batchSeparately = false;
suppressSID = false;
}
Command::~Command()
{
}
void Command::cancel()
{
canceled = true;
}
// returns completed command JSON string
const char* Command::getstring()
{
return jsonWriter.getstring().c_str();
}
//return true when the response is an error, false otherwise (in that case it doesn't consume JSON chars)
bool Command::checkError(Error& errorDetails, JSON& json)
{
error e;
bool errorDetected = false;
if (json.isNumericError(e))
{
// isNumericError already moved the pointer past the integer (name could imply this?)
errorDetails.setErrorCode(e);
errorDetected = true;
}
else
{
const char* ptr = json.pos;
if (*ptr == ',')
{
ptr++;
}
if (strncmp(ptr, "{\"err\":", 7) == 0)
{
bool exit = false;
json.enterobject();
while (!exit)
{
switch (json.getnameid())
{
case MAKENAMEID3('e', 'r', 'r'):
errorDetails.setErrorCode(static_cast<error>(json.getint()));
errorDetected = true;
break;
case 'u':
errorDetails.setUserStatus(json.getint());
break;
case 'l':
errorDetails.setLinkStatus(json.getint());
break;
case EOO:
exit = true;
break;
default:
json.storeobject();
break;
}
}
json.leaveobject();
}
}
// generic handling of errors for all commands below
if (errorDetected && errorDetails == API_EPAYWALL)
{
client->activateoverquota(0, true);
}
#ifdef ENABLE_SYNC
if (errorDetected && errorDetails == API_EBUSINESSPASTDUE)
{
client->syncs.disableSyncs(BUSINESS_EXPIRED, false);
}
#endif
return errorDetected;
}
// cache urls and ips given in response to avoid further waiting for dns resolution
bool Command::cacheresolvedurls(const std::vector<string>& urls, std::vector<string>&& ips)
{
// cache resolved URLs if received
bool result = client->httpio->cacheresolvedurls(urls, std::move(ips));
if (result == false)
{
assert(false);
client->sendevent(99456, "Unpaired IPs received for URLs in this command");
}
return result;
}
// Store ips from response in the vector passed
bool Command::loadIpsFromJson(std::vector<string>& ips)
{
if (client->json.enterarray()) // for each URL, there will be 2 IPs (IPv4 first, IPv6 second)
{
for (;;)
{
std::string ti;
if (!client->json.storeobject(&ti))
{
break;
}
ips.push_back(ti);
}
client->json.leavearray();
return true;
}
return false;
}
// add opcode
void Command::cmd(const char* cmd)
{
jsonWriter.cmd(cmd);
}
void Command::notself(MegaClient *client)
{
jsonWriter.notself(client);
}
// add comma separator unless first element
void Command::addcomma()
{
jsonWriter.addcomma();
}
// add command argument name:value pair (FIXME: add proper JSON escaping)
void Command::arg(const char* name, const char* value, int quotes)
{
jsonWriter.arg(name, value, quotes);
}
// binary data
void Command::arg(const char* name, const byte* value, int len)
{
jsonWriter.arg(name, value, len);
}
void Command::arg(const char* name, NodeHandle h)
{
jsonWriter.arg(name, h);
}
// 64-bit signed integer
void Command::arg(const char* name, m_off_t n)
{
jsonWriter.arg(name, n);
}
// raw JSON data
void Command::appendraw(const char* s)
{
jsonWriter.appendraw(s);
}
// raw JSON data with length specifier
void Command::appendraw(const char* s, int len)
{
jsonWriter.appendraw(s, len);
}
// begin array
void Command::beginarray()
{
jsonWriter.beginarray();
}
// begin array member
void Command::beginarray(const char* name)
{
jsonWriter.beginarray(name);
}
// close array
void Command::endarray()
{
jsonWriter.endarray();
}
// begin JSON object
void Command::beginobject()
{
jsonWriter.beginobject();
}
void Command::beginobject(const char *name)
{
jsonWriter.beginobject(name);
}
// end JSON object
void Command::endobject()
{
jsonWriter.endobject();
}
// add integer
void Command::element(int n)
{
jsonWriter.element(n);
}
// add handle (with size specifier)
void Command::element(handle h, int len)
{
jsonWriter.element(h, len);
}
// add binary data
void Command::element(const byte* data, int len)
{
jsonWriter.element(data, len);
}
void Command::element(const char *buf)
{
jsonWriter.element(buf);
}
// open object
void Command::openobject()
{
jsonWriter.openobject();
}
// close object
void Command::closeobject()
{
jsonWriter.closeobject();
}
} // namespace
<commit_msg>SDK-2000. Provide methods to retrieve thumbnail/preview upload urls in the intermediate layer.<commit_after>/**
* @file command.cpp
* @brief Request command component
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "mega/command.h"
#include "mega/base64.h"
#include "mega/megaclient.h"
namespace mega {
Command::Command()
{
persistent = false;
canceled = false;
result = API_OK;
client = NULL;
tag = 0;
batchSeparately = false;
suppressSID = false;
}
Command::~Command()
{
}
void Command::cancel()
{
canceled = true;
}
// returns completed command JSON string
const char* Command::getstring()
{
return jsonWriter.getstring().c_str();
}
//return true when the response is an error, false otherwise (in that case it doesn't consume JSON chars)
bool Command::checkError(Error& errorDetails, JSON& json)
{
error e;
bool errorDetected = false;
if (json.isNumericError(e))
{
// isNumericError already moved the pointer past the integer (name could imply this?)
errorDetails.setErrorCode(e);
errorDetected = true;
}
else
{
const char* ptr = json.pos;
if (*ptr == ',')
{
ptr++;
}
if (strncmp(ptr, "{\"err\":", 7) == 0)
{
bool exit = false;
json.enterobject();
while (!exit)
{
switch (json.getnameid())
{
case MAKENAMEID3('e', 'r', 'r'):
errorDetails.setErrorCode(static_cast<error>(json.getint()));
errorDetected = true;
break;
case 'u':
errorDetails.setUserStatus(json.getint());
break;
case 'l':
errorDetails.setLinkStatus(json.getint());
break;
case EOO:
exit = true;
break;
default:
json.storeobject();
break;
}
}
json.leaveobject();
}
}
// generic handling of errors for all commands below
if (errorDetected && errorDetails == API_EPAYWALL)
{
client->activateoverquota(0, true);
}
#ifdef ENABLE_SYNC
if (errorDetected && errorDetails == API_EBUSINESSPASTDUE)
{
client->syncs.disableSyncs(BUSINESS_EXPIRED, false);
}
#endif
return errorDetected;
}
// cache urls and ips given in response to avoid further waiting for dns resolution
bool Command::cacheresolvedurls(const std::vector<string>& urls, std::vector<string>&& ips)
{
// cache resolved URLs if received
bool result = client->httpio->cacheresolvedurls(urls, std::move(ips));
if (result == false)
{
client->sendevent(99456, "Unpaired IPs received for URLs in this command");
}
return result;
}
// Store ips from response in the vector passed
bool Command::loadIpsFromJson(std::vector<string>& ips)
{
if (client->json.enterarray()) // for each URL, there will be 2 IPs (IPv4 first, IPv6 second)
{
for (;;)
{
std::string ti;
if (!client->json.storeobject(&ti))
{
break;
}
ips.push_back(ti);
}
client->json.leavearray();
return true;
}
return false;
}
// add opcode
void Command::cmd(const char* cmd)
{
jsonWriter.cmd(cmd);
}
void Command::notself(MegaClient *client)
{
jsonWriter.notself(client);
}
// add comma separator unless first element
void Command::addcomma()
{
jsonWriter.addcomma();
}
// add command argument name:value pair (FIXME: add proper JSON escaping)
void Command::arg(const char* name, const char* value, int quotes)
{
jsonWriter.arg(name, value, quotes);
}
// binary data
void Command::arg(const char* name, const byte* value, int len)
{
jsonWriter.arg(name, value, len);
}
void Command::arg(const char* name, NodeHandle h)
{
jsonWriter.arg(name, h);
}
// 64-bit signed integer
void Command::arg(const char* name, m_off_t n)
{
jsonWriter.arg(name, n);
}
// raw JSON data
void Command::appendraw(const char* s)
{
jsonWriter.appendraw(s);
}
// raw JSON data with length specifier
void Command::appendraw(const char* s, int len)
{
jsonWriter.appendraw(s, len);
}
// begin array
void Command::beginarray()
{
jsonWriter.beginarray();
}
// begin array member
void Command::beginarray(const char* name)
{
jsonWriter.beginarray(name);
}
// close array
void Command::endarray()
{
jsonWriter.endarray();
}
// begin JSON object
void Command::beginobject()
{
jsonWriter.beginobject();
}
void Command::beginobject(const char *name)
{
jsonWriter.beginobject(name);
}
// end JSON object
void Command::endobject()
{
jsonWriter.endobject();
}
// add integer
void Command::element(int n)
{
jsonWriter.element(n);
}
// add handle (with size specifier)
void Command::element(handle h, int len)
{
jsonWriter.element(h, len);
}
// add binary data
void Command::element(const byte* data, int len)
{
jsonWriter.element(data, len);
}
void Command::element(const char *buf)
{
jsonWriter.element(buf);
}
// open object
void Command::openobject()
{
jsonWriter.openobject();
}
// close object
void Command::closeobject()
{
jsonWriter.closeobject();
}
} // namespace
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <functional>
using namespace std;
namespace {
namespace io {
enum token_type {
REG,
NN
};
ofstream outfile;
ifstream infile;
void exit_ok() {
infile.close();
outfile.close();
exit(0);
}
void exit_err(string const& error) {
cerr << error;
infile.close();
outfile.close();
exit(1);
}
void write_bins(char lhs, char rhs) {
outfile.write(static_cast<char*>(&lhs), 1);
outfile.write(static_cast<char*>(&rhs), 1);
if (outfile.fail()) {
exit_err("Error writing to disk");
}
}
int xtoi(string const& x) {
try {
return stoi(x, 0, 16);
} catch (exception &e) {
return -1;
}
}
string next_token() {
string value;
io::infile >> value;
if (!io::infile) {
io::exit_ok();
}
return value;
}
void tok2n(string const& name, string&& value, char& n) {
int target = xtoi(value);
if (0 > target || 0xF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-F]\n");
}
n = target;
}
void tok2nn(string const& name, string&& value, char& nn) {
int target = xtoi(value);
if (0 > target || 0xFF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-FF]\n");
}
nn = target;
}
void tok2nnn(string const& name, string&& value, char& lhs, char& rhs) {
int target = xtoi(value);
if (0 > target || 0xFFF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-FFF]\n");
}
lhs = target >> 8;
rhs = target & 0xFF;
}
void tok2reg(string const& name, string&& value, char& reg) {
if (value.at(0) != 'r') {
exit_err("Error: " + name + " needs to be supplied with a register r[0-F]\n");
}
int target = xtoi(value.substr(1));
if (0 > target || 0xF < target) {
exit_err("Error: " + name + " needs to be supplied with a register r[0-F]\n");
}
reg = target;
}
void tok2reg_or_nn(string const& name, string&& value, char& reg_or_nn, io::token_type& t) {
if (value.at(0) == 'r') {
t = REG;
tok2reg(name, forward<string>(value), reg_or_nn);
} else {
t = NN;
tok2nn(name, forward<string>(value), reg_or_nn);
}
}
} // io
namespace op {
// These variables are shared between all below functions
char lhs;
char rhs;
char rhs2;
io::token_type t;
inline void OP(char lhs, char rhs) { io::write_bins(lhs, rhs); }
inline void R(string const& name, char lop, char rop) {
io::tok2reg(name, io::next_token(), lhs);
io::write_bins(lop + lhs, rop);
}
inline void RR(string const& name, char lop, char rop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2reg(name, io::next_token(), rhs);
io::write_bins(lop + lhs, (rhs << 4) + rop);
}
inline void NNN(string const& name, char op) {
io::tok2nnn(name, io::next_token(), lhs, rhs);
io::write_bins(op + lhs, rhs);
}
inline void RNN(string const& name, char lop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2nn(name, io::next_token(), rhs);
io::write_bins(lop + lhs, rhs);
}
inline void RRN(string const& name, char lop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2reg(name, io::next_token(), rhs);
io::tok2n(name, io::next_token(), rhs2);
io::write_bins(lop + lhs, (rhs << 4) + rhs2);
}
inline void RV(string const& name, char nnop, char rlop, char rrop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2reg_or_nn(name, io::next_token(), rhs, t);
if (t == io::NN) { io::write_bins(nnop + lhs, rhs); }
else if (t == io::REG) { io::write_bins(rlop + lhs, (rhs << 4) + rrop); }
else { io::exit_err(name + ": Unknown type\n"); }
}
} // op
int help(string program_name) {
cerr
<< "Usage: " << program_name << " FILE\n\n"
<< "Available commands\n"
<< "CLS - 0x00E0\n"
<< "RET - 0x00EE\n"
<< "JMP NNN - 0x1NNN\n"
<< "CALL NNN - 0x2NNN\n"
<< "IFN rX NN - 0x3XNN\n"
<< "IF rX NN - 0x4XNN\n"
<< "IFN rX rY - 0x5XY0\n"
<< "SET rX NN - 0x6XNN\n"
<< "ADD rX NN - 0x7XNN\n"
<< "SET rX rY - 0x8XY0\n"
<< "OR rX rY - 0x8XY1\n"
<< "AND rX rY - 0x8XY2\n"
<< "XOR rX rY - 0x8XY3\n"
<< "ADD rX rY - 0x8XY4\n"
<< "SUB rX rY - 0x8XY5\n"
<< "SHR rX rY - 0x8XY6\n"
<< "RSUB rX rY - 0x8XY7\n"
<< "SHL rX rY - 0x8XYE\n"
<< "IF rX rY - 0x9XY0\n"
<< "IDX NNN - 0xANNN\n"
<< "JMP0 NNN - 0xBNNN\n"
<< "RND rX NN - 0xCXNN\n"
<< "DRAW rX rY N - 0xDXYN\n"
<< "IFK rX - 0xEX9E\n"
<< "IFNK rX - 0xEXA1\n"
<< "GDEL rX - 0xFX07\n"
<< "WKEY rX - 0xFX0A\n"
<< "SDEL rX - 0xFX15\n"
<< "SAUD rX - 0xFX18\n"
<< "IADD rX - 0xFX1E\n"
<< "CHAR rX - 0xFX29\n"
<< "SEP rX - 0xFX33\n"
<< "STOR rX - 0xFX55\n"
<< "LOAD rX - 0xFX65\n";
return 1;
}
} // anonymous namespace
int main(int argc, char* argv[]) {
if (argc != 2 || !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) {
return help(argv[0]);
}
io::infile = ifstream(argv[1], ios::binary);
if (!io::infile) {
cerr << argv[0] << ": Unable to open " << argv[1] << "\n";
return 1;
}
stringstream ss;
ss << argv[1] << ".out";
string const outfile_name{ss.str()};
io::outfile = ofstream(outfile_name, ios::binary);
if (!io::outfile) {
cerr << argv[0] << ": Unable to open " << outfile_name << "\n";
return 1;
}
map<string const, function<void()>> const op2fun {
{"CLS", bind(op::OP, 0x00, 0xE0) },
{"RET", bind(op::OP, 0x00, 0xEE) },
{"JMP", bind(op::NNN, "JMP", 0x10)},
{"CALL", bind(op::NNN,"CALL", 0x20)},
{"IFN", bind(op::RV, "IFN", 0x30, 0x50, 0x00)},
{"IF", bind(op::RV, "IFN", 0x40, 0x90, 0x00)},
{"SET", bind(op::RV, "IFN", 0x60, 0x80, 0x00)},
{"ADD", bind(op::RV, "IFN", 0x70, 0x80, 0x04)},
{"OR", bind(op::RR, "OR", 0x80, 0x01)},
{"AND", bind(op::RR, "AND", 0x80, 0x02)},
{"XOR", bind(op::RR, "XOR", 0x80, 0x03)},
{"SUB", bind(op::RR, "SUB", 0x80, 0x05)},
{"SHR", bind(op::RR, "SHR", 0x80, 0x06)},
{"RSUB", bind(op::RR, "RSUB", 0x80, 0x07)},
{"SHL", bind(op::RR, "SHL", 0x80, 0x0E)},
{"IDX", bind(op::NNN, "IDX", 0xA0)},
{"JMP0", bind(op::NNN,"JMP0", 0xB0)},
{"RND", bind(op::RNN, "RND", 0xC0)},
{"DRAW", bind(op::RRN,"DRAW", 0xD0)},
{"IFK", bind(op::R, "IFK", 0xE0, 0x9E)},
{"IFNK", bind(op::R, "IFNK", 0xE0, 0xA1)},
{"GDEL", bind(op::R, "GDEL", 0xF0, 0x07)},
{"WKEY", bind(op::R, "WKEY", 0xF0, 0x0A)},
{"SDEL", bind(op::R, "SDEL", 0xF0, 0x15)},
{"SAUD", bind(op::R, "SAUD", 0xF0, 0x18)},
{"IADD", bind(op::R, "IADD", 0xF0, 0x1E)},
{"CHAR", bind(op::R, "CHAR", 0xF0, 0x29)},
{"SEP", bind(op::R, "SEP", 0xF0, 0x33)},
{"STOR", bind(op::R, "STOR", 0xF0, 0x55)},
{"LOAD", bind(op::R, "LOAD", 0xF0, 0x65)},
};
for (;;) {
// This constructor will exit when no more input is received
string const tok{io::next_token()};
auto const fun{op2fun.find(tok)};
if (fun == op2fun.end()) {
io::exit_err("Unknown command '" + tok + "'\n");
}
fun->second();
}
// Not reached
}
<commit_msg>Remove typos<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <functional>
using namespace std;
namespace {
namespace io {
enum token_type {
REG,
NN
};
ofstream outfile;
ifstream infile;
void exit_ok() {
infile.close();
outfile.close();
exit(0);
}
void exit_err(string const& error) {
cerr << error;
infile.close();
outfile.close();
exit(1);
}
void write_bins(char lhs, char rhs) {
outfile.write(static_cast<char*>(&lhs), 1);
outfile.write(static_cast<char*>(&rhs), 1);
if (outfile.fail()) {
exit_err("Error writing to disk");
}
}
int xtoi(string const& x) {
try {
return stoi(x, 0, 16);
} catch (exception &e) {
return -1;
}
}
string next_token() {
string value;
io::infile >> value;
if (!io::infile) {
io::exit_ok();
}
return value;
}
void tok2n(string const& name, string&& value, char& n) {
int target = xtoi(value);
if (0 > target || 0xF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-F]\n");
}
n = target;
}
void tok2nn(string const& name, string&& value, char& nn) {
int target = xtoi(value);
if (0 > target || 0xFF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-FF]\n");
}
nn = target;
}
void tok2nnn(string const& name, string&& value, char& lhs, char& rhs) {
int target = xtoi(value);
if (0 > target || 0xFFF < target) {
exit_err("Error: " + name + " needs to be supplied with a value [0-FFF]\n");
}
lhs = target >> 8;
rhs = target & 0xFF;
}
void tok2reg(string const& name, string&& value, char& reg) {
if (value.at(0) != 'r') {
exit_err("Error: " + name + " needs to be supplied with a register r[0-F]\n");
}
int target = xtoi(value.substr(1));
if (0 > target || 0xF < target) {
exit_err("Error: " + name + " needs to be supplied with a register r[0-F]\n");
}
reg = target;
}
void tok2reg_or_nn(string const& name, string&& value, char& reg_or_nn, io::token_type& t) {
if (value.at(0) == 'r') {
t = REG;
tok2reg(name, forward<string>(value), reg_or_nn);
} else {
t = NN;
tok2nn(name, forward<string>(value), reg_or_nn);
}
}
} // io
namespace op {
// These variables are shared between all below functions
char lhs;
char rhs;
char rhs2;
io::token_type t;
inline void OP(char lhs, char rhs) { io::write_bins(lhs, rhs); }
inline void R(string const& name, char lop, char rop) {
io::tok2reg(name, io::next_token(), lhs);
io::write_bins(lop + lhs, rop);
}
inline void RR(string const& name, char lop, char rop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2reg(name, io::next_token(), rhs);
io::write_bins(lop + lhs, (rhs << 4) + rop);
}
inline void NNN(string const& name, char op) {
io::tok2nnn(name, io::next_token(), lhs, rhs);
io::write_bins(op + lhs, rhs);
}
inline void RNN(string const& name, char lop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2nn(name, io::next_token(), rhs);
io::write_bins(lop + lhs, rhs);
}
inline void RRN(string const& name, char lop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2reg(name, io::next_token(), rhs);
io::tok2n(name, io::next_token(), rhs2);
io::write_bins(lop + lhs, (rhs << 4) + rhs2);
}
inline void RV(string const& name, char nnop, char rlop, char rrop) {
io::tok2reg(name, io::next_token(), lhs);
io::tok2reg_or_nn(name, io::next_token(), rhs, t);
if (t == io::NN) { io::write_bins(nnop + lhs, rhs); }
else if (t == io::REG) { io::write_bins(rlop + lhs, (rhs << 4) + rrop); }
else { io::exit_err(name + ": Unknown type\n"); }
}
} // op
int help(string program_name) {
cerr
<< "Usage: " << program_name << " FILE\n\n"
<< "Available commands\n"
<< "CLS - 0x00E0\n"
<< "RET - 0x00EE\n"
<< "JMP NNN - 0x1NNN\n"
<< "CALL NNN - 0x2NNN\n"
<< "IFN rX NN - 0x3XNN\n"
<< "IF rX NN - 0x4XNN\n"
<< "IFN rX rY - 0x5XY0\n"
<< "SET rX NN - 0x6XNN\n"
<< "ADD rX NN - 0x7XNN\n"
<< "SET rX rY - 0x8XY0\n"
<< "OR rX rY - 0x8XY1\n"
<< "AND rX rY - 0x8XY2\n"
<< "XOR rX rY - 0x8XY3\n"
<< "ADD rX rY - 0x8XY4\n"
<< "SUB rX rY - 0x8XY5\n"
<< "SHR rX rY - 0x8XY6\n"
<< "RSUB rX rY - 0x8XY7\n"
<< "SHL rX rY - 0x8XYE\n"
<< "IF rX rY - 0x9XY0\n"
<< "IDX NNN - 0xANNN\n"
<< "JMP0 NNN - 0xBNNN\n"
<< "RND rX NN - 0xCXNN\n"
<< "DRAW rX rY N - 0xDXYN\n"
<< "IFK rX - 0xEX9E\n"
<< "IFNK rX - 0xEXA1\n"
<< "GDEL rX - 0xFX07\n"
<< "WKEY rX - 0xFX0A\n"
<< "SDEL rX - 0xFX15\n"
<< "SAUD rX - 0xFX18\n"
<< "IADD rX - 0xFX1E\n"
<< "CHAR rX - 0xFX29\n"
<< "SEP rX - 0xFX33\n"
<< "STOR rX - 0xFX55\n"
<< "LOAD rX - 0xFX65\n";
return 1;
}
} // anonymous namespace
int main(int argc, char* argv[]) {
if (argc != 2 || !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) {
return help(argv[0]);
}
io::infile = ifstream(argv[1], ios::binary);
if (!io::infile) {
cerr << argv[0] << ": Unable to open " << argv[1] << "\n";
return 1;
}
stringstream ss;
ss << argv[1] << ".out";
string const outfile_name{ss.str()};
io::outfile = ofstream(outfile_name, ios::binary);
if (!io::outfile) {
cerr << argv[0] << ": Unable to open " << outfile_name << "\n";
return 1;
}
map<string const, function<void()>> const op2fun {
{"CLS", bind(op::OP, 0x00, 0xE0) },
{"RET", bind(op::OP, 0x00, 0xEE) },
{"JMP", bind(op::NNN, "JMP", 0x10)},
{"CALL", bind(op::NNN,"CALL", 0x20)},
{"IFN", bind(op::RV, "IFN", 0x30, 0x50, 0x00)},
{"IF", bind(op::RV, "IF", 0x40, 0x90, 0x00)},
{"SET", bind(op::RV, "SET", 0x60, 0x80, 0x00)},
{"ADD", bind(op::RV, "ADD", 0x70, 0x80, 0x04)},
{"OR", bind(op::RR, "OR", 0x80, 0x01)},
{"AND", bind(op::RR, "AND", 0x80, 0x02)},
{"XOR", bind(op::RR, "XOR", 0x80, 0x03)},
{"SUB", bind(op::RR, "SUB", 0x80, 0x05)},
{"SHR", bind(op::RR, "SHR", 0x80, 0x06)},
{"RSUB", bind(op::RR, "RSUB", 0x80, 0x07)},
{"SHL", bind(op::RR, "SHL", 0x80, 0x0E)},
{"IDX", bind(op::NNN, "IDX", 0xA0)},
{"JMP0", bind(op::NNN,"JMP0", 0xB0)},
{"RND", bind(op::RNN, "RND", 0xC0)},
{"DRAW", bind(op::RRN,"DRAW", 0xD0)},
{"IFK", bind(op::R, "IFK", 0xE0, 0x9E)},
{"IFNK", bind(op::R, "IFNK", 0xE0, 0xA1)},
{"GDEL", bind(op::R, "GDEL", 0xF0, 0x07)},
{"WKEY", bind(op::R, "WKEY", 0xF0, 0x0A)},
{"SDEL", bind(op::R, "SDEL", 0xF0, 0x15)},
{"SAUD", bind(op::R, "SAUD", 0xF0, 0x18)},
{"IADD", bind(op::R, "IADD", 0xF0, 0x1E)},
{"CHAR", bind(op::R, "CHAR", 0xF0, 0x29)},
{"SEP", bind(op::R, "SEP", 0xF0, 0x33)},
{"STOR", bind(op::R, "STOR", 0xF0, 0x55)},
{"LOAD", bind(op::R, "LOAD", 0xF0, 0x65)},
};
for (;;) {
// This constructor will exit when no more input is received
string const tok{io::next_token()};
auto const fun{op2fun.find(tok)};
if (fun == op2fun.end()) {
io::exit_err("Unknown command '" + tok + "'\n");
}
fun->second();
}
// Not reached
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/ref_counted.h"
#include "base/scoped_temp_dir.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/in_process_webkit/indexed_db_context.h"
#include "chrome/browser/in_process_webkit/webkit_context.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/testing_profile.h"
#include "chrome/test/thread_test_helper.h"
#include "chrome/test/ui_test_utils.h"
// This browser test is aimed towards exercising the IndexedDB bindings and
// the actual implementation that lives in the browser side (in_process_webkit).
class IndexedDBBrowserTest : public InProcessBrowserTest {
public:
IndexedDBBrowserTest() {
EnableDOMAutomation();
}
GURL testUrl(const FilePath& file_path) {
const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb"));
return ui_test_utils::GetTestUrl(kTestDir, file_path);
}
void SimpleTest(const GURL& test_url) {
// The test page will perform tests on IndexedDB, then navigate to either
// a #pass or #fail ref.
LOG(INFO) << "Navigating to URL and blocking.";
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), test_url, 2);
LOG(INFO) << "Navigation done.";
std::string result = browser()->GetSelectedTabContents()->GetURL().ref();
if (result != "pass") {
std::string js_result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(getLog())", &js_result));
FAIL() << "Failed: " << js_result;
}
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))));
}
// http://code.google.com/p/chromium/issues/detail?id=70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_IndexTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html"))));
}
// http://code.google.com/p/chromium/issues/detail?id=70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_KeyPathTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html"))));
}
// http://code.google.com/p/chromium/issues/detail?id=70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_ObjectStoreTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html"))));
}
// http://code.google.com/p/chromium/issues/detail?id=70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_TransactionTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
// http://code.google.com/p/chromium/issues/detail?id=70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_DoesntHangTest) {
SimpleTest(testUrl(FilePath(
FILE_PATH_LITERAL("transaction_run_forever.html"))));
ui_test_utils::CrashTab(browser()->GetSelectedTabContents());
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
// In proc browser test is needed here because ClearLocalState indirectly calls
// WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) {
// Create test files.
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath indexeddb_dir = temp_dir.path().Append(
IndexedDBContext::kIndexedDBDirectory);
ASSERT_TRUE(file_util::CreateDirectory(indexeddb_dir));
FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0"));
file_name_1.append(IndexedDBContext::kIndexedDBExtension);
FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0"));
file_name_2.append(IndexedDBContext::kIndexedDBExtension);
FilePath temp_file_path_1 = indexeddb_dir.Append(file_name_1);
FilePath temp_file_path_2 = indexeddb_dir.Append(file_name_2);
ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1));
ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1));
// Create the scope which will ensure we run the destructor of the webkit
// context which should trigger the clean up.
{
TestingProfile profile;
WebKitContext *webkit_context = profile.GetWebKitContext();
webkit_context->indexed_db_context()->set_data_path(indexeddb_dir);
webkit_context->set_clear_local_state_on_exit(true);
}
// Make sure we wait until the destructor has run.
scoped_refptr<ThreadTestHelper> helper(
new ThreadTestHelper(BrowserThread::WEBKIT));
ASSERT_TRUE(helper->Run());
// Because we specified https for scheme to be skipped the second file
// should survive and the first go into vanity.
ASSERT_FALSE(file_util::PathExists(temp_file_path_1));
ASSERT_TRUE(file_util::PathExists(temp_file_path_2));
}
<commit_msg>Disable some tests that need to be updated due to a WebKit patch that hasn't been rolled in yet.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/ref_counted.h"
#include "base/scoped_temp_dir.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/in_process_webkit/indexed_db_context.h"
#include "chrome/browser/in_process_webkit/webkit_context.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/testing_profile.h"
#include "chrome/test/thread_test_helper.h"
#include "chrome/test/ui_test_utils.h"
// This browser test is aimed towards exercising the IndexedDB bindings and
// the actual implementation that lives in the browser side (in_process_webkit).
class IndexedDBBrowserTest : public InProcessBrowserTest {
public:
IndexedDBBrowserTest() {
EnableDOMAutomation();
}
GURL testUrl(const FilePath& file_path) {
const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb"));
return ui_test_utils::GetTestUrl(kTestDir, file_path);
}
void SimpleTest(const GURL& test_url) {
// The test page will perform tests on IndexedDB, then navigate to either
// a #pass or #fail ref.
LOG(INFO) << "Navigating to URL and blocking.";
ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
browser(), test_url, 2);
LOG(INFO) << "Navigation done.";
std::string result = browser()->GetSelectedTabContents()->GetURL().ref();
if (result != "pass") {
std::string js_result;
ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString(
browser()->GetSelectedTabContents()->render_view_host(), L"",
L"window.domAutomationController.send(getLog())", &js_result));
FAIL() << "Failed: " << js_result;
}
}
};
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_CursorTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html"))));
}
// http://code.google.com/p/chromium/issues/detail?id=70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_IndexTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html"))));
}
// http://code.google.com/p/chromium/issues/detail?id=70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_KeyPathTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_TransactionGetTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html"))));
}
// http://code.google.com/p/chromium/issues/detail?id=70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_ObjectStoreTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html"))));
}
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_DatabaseTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html"))));
}
// http://code.google.com/p/chromium/issues/detail?id=70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_TransactionTest) {
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
// http://code.google.com/p/chromium/issues/detail?id=70773
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_DoesntHangTest) {
SimpleTest(testUrl(FilePath(
FILE_PATH_LITERAL("transaction_run_forever.html"))));
ui_test_utils::CrashTab(browser()->GetSelectedTabContents());
SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html"))));
}
// In proc browser test is needed here because ClearLocalState indirectly calls
// WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin.
IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_ClearLocalState) {
// Create test files.
ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
FilePath indexeddb_dir = temp_dir.path().Append(
IndexedDBContext::kIndexedDBDirectory);
ASSERT_TRUE(file_util::CreateDirectory(indexeddb_dir));
FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0"));
file_name_1.append(IndexedDBContext::kIndexedDBExtension);
FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0"));
file_name_2.append(IndexedDBContext::kIndexedDBExtension);
FilePath temp_file_path_1 = indexeddb_dir.Append(file_name_1);
FilePath temp_file_path_2 = indexeddb_dir.Append(file_name_2);
ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1));
ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1));
// Create the scope which will ensure we run the destructor of the webkit
// context which should trigger the clean up.
{
TestingProfile profile;
WebKitContext *webkit_context = profile.GetWebKitContext();
webkit_context->indexed_db_context()->set_data_path(indexeddb_dir);
webkit_context->set_clear_local_state_on_exit(true);
}
// Make sure we wait until the destructor has run.
scoped_refptr<ThreadTestHelper> helper(
new ThreadTestHelper(BrowserThread::WEBKIT));
ASSERT_TRUE(helper->Run());
// Because we specified https for scheme to be skipped the second file
// should survive and the first go into vanity.
ASSERT_FALSE(file_util::PathExists(temp_file_path_1));
ASSERT_TRUE(file_util::PathExists(temp_file_path_2));
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "chrome/browser/browser.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "googleurl/src/gurl.h"
namespace {
// Note: WaitableEvent is not used for synchronization between the main thread
// and history backend thread because the history subsystem posts tasks back
// to the main thread. Had we tried to Signal an event in such a task
// and Wait for it on the main thread, the task would not run at all because
// the main thread would be blocked on the Wait call, resulting in a deadlock.
// A task to be scheduled on the history backend thread.
// Notifies the main thread after all history backend thread tasks have run.
class WaitForHistoryTask : public HistoryDBTask {
public:
WaitForHistoryTask() {
}
virtual bool RunOnDBThread(history::HistoryBackend* backend,
history::HistoryDatabase* db) {
return true;
}
virtual void DoneRunOnMainThread() {
MessageLoop::current()->Quit();
}
private:
DISALLOW_COPY_AND_ASSIGN(WaitForHistoryTask);
};
// Enumerates all history contents on the backend thread.
class HistoryEnumerator : public HistoryService::URLEnumerator {
public:
explicit HistoryEnumerator(HistoryService* history) {
EXPECT_TRUE(history);
if (!history)
return;
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(history, &HistoryService::IterateURLs, this));
ui_test_utils::RunMessageLoop();
}
virtual void OnURL(const GURL& url) {
urls_.push_back(url);
}
virtual void OnComplete(bool success) {
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
new MessageLoop::QuitTask());
}
std::vector<GURL>& urls() { return urls_; }
private:
std::vector<GURL> urls_;
DISALLOW_COPY_AND_ASSIGN(HistoryEnumerator);
};
class HistoryBrowserTest : public InProcessBrowserTest {
protected:
PrefService* GetPrefs() {
return GetProfile()->GetPrefs();
}
Profile* GetProfile() {
return browser()->GetProfile();
}
HistoryService* GetHistoryService() {
return GetProfile()->GetHistoryService(Profile::EXPLICIT_ACCESS);
}
std::vector<GURL> GetHistoryContents() {
HistoryEnumerator enumerator(GetHistoryService());
return enumerator.urls();
}
GURL GetTestUrl() {
return ui_test_utils::GetTestUrl(
FilePath(FilePath::kCurrentDirectory),
FilePath(FILE_PATH_LITERAL("title2.html")));
}
void WaitForHistoryBackendToRun() {
CancelableRequestConsumerTSimple<int> request_consumer;
scoped_refptr<HistoryDBTask> task(new WaitForHistoryTask());
HistoryService* history = GetHistoryService();
ChromeThread::PostTask(ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(history,
&HistoryService::ScheduleDBTask,
task.get(),
&request_consumer));
ui_test_utils::RunMessageLoop();
}
void ExpectEmptyHistory() {
std::vector<GURL> urls(GetHistoryContents());
EXPECT_EQ(0U, urls.size());
}
};
// Test that the browser history is saved (default setting).
IN_PROC_BROWSER_TEST_F(HistoryBrowserTest, SavingHistoryEnabled) {
EXPECT_FALSE(GetPrefs()->GetBoolean(prefs::kSavingBrowserHistoryDisabled));
EXPECT_TRUE(GetProfile()->GetHistoryService(Profile::EXPLICIT_ACCESS));
EXPECT_TRUE(GetProfile()->GetHistoryService(Profile::IMPLICIT_ACCESS));
ui_test_utils::WaitForHistoryToLoad(browser());
ExpectEmptyHistory();
ui_test_utils::NavigateToURL(browser(), GetTestUrl());
WaitForHistoryBackendToRun();
{
std::vector<GURL> urls(GetHistoryContents());
ASSERT_EQ(1U, urls.size());
EXPECT_EQ(GetTestUrl().spec(), urls[0].spec());
}
}
// Test that disabling saving browser history really works.
IN_PROC_BROWSER_TEST_F(HistoryBrowserTest, SavingHistoryDisabled) {
GetPrefs()->SetBoolean(prefs::kSavingBrowserHistoryDisabled, true);
EXPECT_TRUE(GetProfile()->GetHistoryService(Profile::EXPLICIT_ACCESS));
EXPECT_FALSE(GetProfile()->GetHistoryService(Profile::IMPLICIT_ACCESS));
ui_test_utils::WaitForHistoryToLoad(browser());
ExpectEmptyHistory();
ui_test_utils::NavigateToURL(browser(), GetTestUrl());
WaitForHistoryBackendToRun();
ExpectEmptyHistory();
}
// Test that changing the pref takes effect immediately
// when the browser is running.
IN_PROC_BROWSER_TEST_F(HistoryBrowserTest, SavingHistoryEnabledThenDisabled) {
EXPECT_FALSE(GetPrefs()->GetBoolean(prefs::kSavingBrowserHistoryDisabled));
ui_test_utils::WaitForHistoryToLoad(browser());
ui_test_utils::NavigateToURL(browser(), GetTestUrl());
WaitForHistoryBackendToRun();
{
std::vector<GURL> urls(GetHistoryContents());
ASSERT_EQ(1U, urls.size());
EXPECT_EQ(GetTestUrl().spec(), urls[0].spec());
}
GetPrefs()->SetBoolean(prefs::kSavingBrowserHistoryDisabled, true);
ui_test_utils::NavigateToURL(browser(), GetTestUrl());
WaitForHistoryBackendToRun();
{
// No additional entries should be present in the history.
std::vector<GURL> urls(GetHistoryContents());
ASSERT_EQ(1U, urls.size());
EXPECT_EQ(GetTestUrl().spec(), urls[0].spec());
}
}
// Test that changing the pref takes effect immediately
// when the browser is running.
IN_PROC_BROWSER_TEST_F(HistoryBrowserTest, SavingHistoryDisabledThenEnabled) {
GetPrefs()->SetBoolean(prefs::kSavingBrowserHistoryDisabled, true);
ui_test_utils::WaitForHistoryToLoad(browser());
ExpectEmptyHistory();
ui_test_utils::NavigateToURL(browser(), GetTestUrl());
WaitForHistoryBackendToRun();
ExpectEmptyHistory();
GetPrefs()->SetBoolean(prefs::kSavingBrowserHistoryDisabled, false);
ui_test_utils::NavigateToURL(browser(), GetTestUrl());
WaitForHistoryBackendToRun();
{
std::vector<GURL> urls(GetHistoryContents());
ASSERT_EQ(1U, urls.size());
EXPECT_EQ(GetTestUrl().spec(), urls[0].spec());
}
}
} // namespace
<commit_msg>HistoryBrowserTest.SavingHistoryDisabled and SavingHistoryDisabledThenEnabled timeout / fails<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "chrome/browser/browser.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "googleurl/src/gurl.h"
namespace {
// Note: WaitableEvent is not used for synchronization between the main thread
// and history backend thread because the history subsystem posts tasks back
// to the main thread. Had we tried to Signal an event in such a task
// and Wait for it on the main thread, the task would not run at all because
// the main thread would be blocked on the Wait call, resulting in a deadlock.
// A task to be scheduled on the history backend thread.
// Notifies the main thread after all history backend thread tasks have run.
class WaitForHistoryTask : public HistoryDBTask {
public:
WaitForHistoryTask() {
}
virtual bool RunOnDBThread(history::HistoryBackend* backend,
history::HistoryDatabase* db) {
return true;
}
virtual void DoneRunOnMainThread() {
MessageLoop::current()->Quit();
}
private:
DISALLOW_COPY_AND_ASSIGN(WaitForHistoryTask);
};
// Enumerates all history contents on the backend thread.
class HistoryEnumerator : public HistoryService::URLEnumerator {
public:
explicit HistoryEnumerator(HistoryService* history) {
EXPECT_TRUE(history);
if (!history)
return;
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(history, &HistoryService::IterateURLs, this));
ui_test_utils::RunMessageLoop();
}
virtual void OnURL(const GURL& url) {
urls_.push_back(url);
}
virtual void OnComplete(bool success) {
ChromeThread::PostTask(
ChromeThread::UI,
FROM_HERE,
new MessageLoop::QuitTask());
}
std::vector<GURL>& urls() { return urls_; }
private:
std::vector<GURL> urls_;
DISALLOW_COPY_AND_ASSIGN(HistoryEnumerator);
};
class HistoryBrowserTest : public InProcessBrowserTest {
protected:
PrefService* GetPrefs() {
return GetProfile()->GetPrefs();
}
Profile* GetProfile() {
return browser()->GetProfile();
}
HistoryService* GetHistoryService() {
return GetProfile()->GetHistoryService(Profile::EXPLICIT_ACCESS);
}
std::vector<GURL> GetHistoryContents() {
HistoryEnumerator enumerator(GetHistoryService());
return enumerator.urls();
}
GURL GetTestUrl() {
return ui_test_utils::GetTestUrl(
FilePath(FilePath::kCurrentDirectory),
FilePath(FILE_PATH_LITERAL("title2.html")));
}
void WaitForHistoryBackendToRun() {
CancelableRequestConsumerTSimple<int> request_consumer;
scoped_refptr<HistoryDBTask> task(new WaitForHistoryTask());
HistoryService* history = GetHistoryService();
ChromeThread::PostTask(ChromeThread::UI,
FROM_HERE,
NewRunnableMethod(history,
&HistoryService::ScheduleDBTask,
task.get(),
&request_consumer));
ui_test_utils::RunMessageLoop();
}
void ExpectEmptyHistory() {
std::vector<GURL> urls(GetHistoryContents());
EXPECT_EQ(0U, urls.size());
}
};
// Test that the browser history is saved (default setting).
IN_PROC_BROWSER_TEST_F(HistoryBrowserTest, SavingHistoryEnabled) {
EXPECT_FALSE(GetPrefs()->GetBoolean(prefs::kSavingBrowserHistoryDisabled));
EXPECT_TRUE(GetProfile()->GetHistoryService(Profile::EXPLICIT_ACCESS));
EXPECT_TRUE(GetProfile()->GetHistoryService(Profile::IMPLICIT_ACCESS));
ui_test_utils::WaitForHistoryToLoad(browser());
ExpectEmptyHistory();
ui_test_utils::NavigateToURL(browser(), GetTestUrl());
WaitForHistoryBackendToRun();
{
std::vector<GURL> urls(GetHistoryContents());
ASSERT_EQ(1U, urls.size());
EXPECT_EQ(GetTestUrl().spec(), urls[0].spec());
}
}
// Times out on Vista only. http://crbug.com/57994
#if defined(OS_WIN)
#define MAYBE_SavingHistoryDisabled DISABLED_SavingHistoryDisabled
#else
#define MAYBE_SavingHistoryDisabled SavingHistoryDisabled
#endif
// Test that disabling saving browser history really works.
IN_PROC_BROWSER_TEST_F(HistoryBrowserTest, MAYBE_SavingHistoryDisabled) {
GetPrefs()->SetBoolean(prefs::kSavingBrowserHistoryDisabled, true);
EXPECT_TRUE(GetProfile()->GetHistoryService(Profile::EXPLICIT_ACCESS));
EXPECT_FALSE(GetProfile()->GetHistoryService(Profile::IMPLICIT_ACCESS));
ui_test_utils::WaitForHistoryToLoad(browser());
ExpectEmptyHistory();
ui_test_utils::NavigateToURL(browser(), GetTestUrl());
WaitForHistoryBackendToRun();
ExpectEmptyHistory();
}
// Times out on Vista only. http://crbug.com/57994
#if defined(OS_WIN)
#define MAYBE_SavingHistoryEnabledThenDisabled \
DISABLED_SavingHistoryEnabledThenDisabled
#else
#define MAYBE_SavingHistoryEnabledThenDisabled SavingHistoryEnabledThenDisabled
#endif
// Test that changing the pref takes effect immediately
// when the browser is running.
IN_PROC_BROWSER_TEST_F(HistoryBrowserTest,
MAYBE_SavingHistoryEnabledThenDisabled) {
EXPECT_FALSE(GetPrefs()->GetBoolean(prefs::kSavingBrowserHistoryDisabled));
ui_test_utils::WaitForHistoryToLoad(browser());
ui_test_utils::NavigateToURL(browser(), GetTestUrl());
WaitForHistoryBackendToRun();
{
std::vector<GURL> urls(GetHistoryContents());
ASSERT_EQ(1U, urls.size());
EXPECT_EQ(GetTestUrl().spec(), urls[0].spec());
}
GetPrefs()->SetBoolean(prefs::kSavingBrowserHistoryDisabled, true);
ui_test_utils::NavigateToURL(browser(), GetTestUrl());
WaitForHistoryBackendToRun();
{
// No additional entries should be present in the history.
std::vector<GURL> urls(GetHistoryContents());
ASSERT_EQ(1U, urls.size());
EXPECT_EQ(GetTestUrl().spec(), urls[0].spec());
}
}
// Test that changing the pref takes effect immediately
// when the browser is running.
IN_PROC_BROWSER_TEST_F(HistoryBrowserTest, SavingHistoryDisabledThenEnabled) {
GetPrefs()->SetBoolean(prefs::kSavingBrowserHistoryDisabled, true);
ui_test_utils::WaitForHistoryToLoad(browser());
ExpectEmptyHistory();
ui_test_utils::NavigateToURL(browser(), GetTestUrl());
WaitForHistoryBackendToRun();
ExpectEmptyHistory();
GetPrefs()->SetBoolean(prefs::kSavingBrowserHistoryDisabled, false);
ui_test_utils::NavigateToURL(browser(), GetTestUrl());
WaitForHistoryBackendToRun();
{
std::vector<GURL> urls(GetHistoryContents());
ASSERT_EQ(1U, urls.size());
EXPECT_EQ(GetTestUrl().spec(), urls[0].spec());
}
}
} // namespace
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file defines a class that contains various method related to branding.
// It provides only default implementations of these methods. Usually to add
// specific branding, we will need to extend this class with a custom
// implementation.
#include "chrome/installer/util/browser_distribution.h"
#include "base/atomicops.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/lock.h"
#include "base/logging.h"
#include "base/win/registry.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/chrome_frame_distribution.h"
#include "chrome/installer/util/google_chrome_distribution.h"
#include "chrome/installer/util/google_chrome_sxs_distribution.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/master_preferences.h"
#include "installer_util_strings.h" // NOLINT
using installer::MasterPreferences;
namespace {
// The BrowserDistribution objects are never freed.
BrowserDistribution* g_browser_distribution = NULL;
BrowserDistribution* g_chrome_frame_distribution = NULL;
BrowserDistribution* g_ceee_distribution = NULL;
// Returns true if currently running in npchrome_frame.dll
bool IsChromeFrameModule() {
FilePath module_path;
PathService::Get(base::FILE_MODULE, &module_path);
return FilePath::CompareEqualIgnoreCase(module_path.BaseName().value(),
installer::kChromeFrameDll);
}
// Returns true if currently running in ceee_broker.exe
bool IsCeeeBrokerProcess() {
FilePath exe_path;
PathService::Get(base::FILE_EXE, &exe_path);
return FilePath::CompareEqualIgnoreCase(exe_path.BaseName().value(),
installer::kCeeeBrokerExe);
}
BrowserDistribution::Type GetCurrentDistributionType() {
static BrowserDistribution::Type type =
(MasterPreferences::ForCurrentProcess().install_chrome_frame() ||
IsChromeFrameModule()) ?
BrowserDistribution::CHROME_FRAME :
BrowserDistribution::CHROME_BROWSER;
return type;
}
} // end namespace
BrowserDistribution::BrowserDistribution(
const installer::MasterPreferences& prefs)
: type_(BrowserDistribution::CHROME_BROWSER) {
}
template<class DistributionClass>
BrowserDistribution* BrowserDistribution::GetOrCreateBrowserDistribution(
const installer::MasterPreferences& prefs,
BrowserDistribution** dist) {
if (!*dist) {
DistributionClass* temp = new DistributionClass(prefs);
if (base::subtle::NoBarrier_CompareAndSwap(
reinterpret_cast<base::subtle::AtomicWord*>(dist), NULL,
reinterpret_cast<base::subtle::AtomicWord>(temp)) != NULL)
delete temp;
}
return *dist;
}
BrowserDistribution* BrowserDistribution::GetDistribution() {
const installer::MasterPreferences& prefs =
installer::MasterPreferences::ForCurrentProcess();
return GetSpecificDistribution(GetCurrentDistributionType(), prefs);
}
// static
BrowserDistribution* BrowserDistribution::GetSpecificDistribution(
BrowserDistribution::Type type,
const installer::MasterPreferences& prefs) {
BrowserDistribution* dist = NULL;
if (type == CHROME_FRAME) {
dist = GetOrCreateBrowserDistribution<ChromeFrameDistribution>(
prefs, &g_chrome_frame_distribution);
} else {
DCHECK_EQ(CHROME_BROWSER, type);
#if defined(GOOGLE_CHROME_BUILD)
if (InstallUtil::IsChromeSxSProcess()) {
dist = GetOrCreateBrowserDistribution<GoogleChromeSxSDistribution>(
prefs, &g_browser_distribution);
} else {
dist = GetOrCreateBrowserDistribution<GoogleChromeDistribution>(
prefs, &g_browser_distribution);
}
#else
dist = GetOrCreateBrowserDistribution<BrowserDistribution>(
prefs, &g_browser_distribution);
#endif
}
return dist;
}
void BrowserDistribution::DoPostUninstallOperations(
const Version& version, const FilePath& local_data_path,
const std::wstring& distribution_data) {
}
std::wstring BrowserDistribution::GetAppGuid() {
return L"";
}
std::wstring BrowserDistribution::GetApplicationName() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetAppShortCutName() {
return GetApplicationName();
}
std::wstring BrowserDistribution::GetAlternateApplicationName() {
return L"The Internet";
}
std::wstring BrowserDistribution::GetBrowserAppId() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetInstallSubDir() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetPublisherName() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetAppDescription() {
return L"Browse the web";
}
std::wstring BrowserDistribution::GetLongAppDescription() {
const std::wstring& app_description =
installer::GetLocalizedString(IDS_PRODUCT_DESCRIPTION_BASE);
return app_description;
}
// static
int BrowserDistribution::GetInstallReturnCode(
installer::InstallStatus status) {
switch (status) {
case installer::FIRST_INSTALL_SUCCESS:
case installer::INSTALL_REPAIRED:
case installer::NEW_VERSION_UPDATED:
case installer::IN_USE_UPDATED:
return 0;
default:
return status;
}
}
std::string BrowserDistribution::GetSafeBrowsingName() {
return "chromium";
}
std::wstring BrowserDistribution::GetStateKey() {
return L"Software\\Chromium";
}
std::wstring BrowserDistribution::GetStateMediumKey() {
return L"Software\\Chromium";
}
std::wstring BrowserDistribution::GetStatsServerURL() {
return L"";
}
std::wstring BrowserDistribution::GetDistributionData(HKEY root_key) {
return L"";
}
std::wstring BrowserDistribution::GetUninstallLinkName() {
return L"Uninstall Chromium";
}
std::wstring BrowserDistribution::GetUninstallRegPath() {
return L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Chromium";
}
std::wstring BrowserDistribution::GetVersionKey() {
return L"Software\\Chromium";
}
bool BrowserDistribution::CanSetAsDefault() {
return true;
}
int BrowserDistribution::GetIconIndex() {
return 0;
}
bool BrowserDistribution::GetChromeChannel(std::wstring* channel) {
return false;
}
void BrowserDistribution::UpdateDiffInstallStatus(bool system_install,
bool incremental_install, installer::InstallStatus install_status) {
}
void BrowserDistribution::LaunchUserExperiment(
installer::InstallStatus status, const Version& version,
const installer::Product& installation, bool system_level) {
}
void BrowserDistribution::InactiveUserToastExperiment(int flavor,
const installer::Product& installation) {
}
std::vector<FilePath> BrowserDistribution::GetKeyFiles() {
std::vector<FilePath> key_files;
key_files.push_back(FilePath(installer::kChromeDll));
return key_files;
}
std::vector<FilePath> BrowserDistribution::GetComDllList() {
return std::vector<FilePath>();
}
void BrowserDistribution::AppendUninstallCommandLineFlags(
CommandLine* cmd_line) {
DCHECK(cmd_line);
cmd_line->AppendSwitch(installer::switches::kChrome);
}
<commit_msg>Fix official build.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file defines a class that contains various method related to branding.
// It provides only default implementations of these methods. Usually to add
// specific branding, we will need to extend this class with a custom
// implementation.
#include "chrome/installer/util/browser_distribution.h"
#include "base/atomicops.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/lock.h"
#include "base/logging.h"
#include "base/win/registry.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/chrome_frame_distribution.h"
#include "chrome/installer/util/google_chrome_distribution.h"
#include "chrome/installer/util/google_chrome_sxs_distribution.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/master_preferences.h"
#include "installer_util_strings.h" // NOLINT
using installer::MasterPreferences;
namespace {
// The BrowserDistribution objects are never freed.
BrowserDistribution* g_browser_distribution = NULL;
BrowserDistribution* g_chrome_frame_distribution = NULL;
BrowserDistribution* g_ceee_distribution = NULL;
// Returns true if currently running in npchrome_frame.dll
bool IsChromeFrameModule() {
FilePath module_path;
PathService::Get(base::FILE_MODULE, &module_path);
return FilePath::CompareEqualIgnoreCase(module_path.BaseName().value(),
installer::kChromeFrameDll);
}
// Returns true if currently running in ceee_broker.exe
bool IsCeeeBrokerProcess() {
FilePath exe_path;
PathService::Get(base::FILE_EXE, &exe_path);
return FilePath::CompareEqualIgnoreCase(exe_path.BaseName().value(),
installer::kCeeeBrokerExe);
}
BrowserDistribution::Type GetCurrentDistributionType() {
static BrowserDistribution::Type type =
(MasterPreferences::ForCurrentProcess().install_chrome_frame() ||
IsChromeFrameModule()) ?
BrowserDistribution::CHROME_FRAME :
BrowserDistribution::CHROME_BROWSER;
return type;
}
} // end namespace
BrowserDistribution::BrowserDistribution(
const installer::MasterPreferences& prefs)
: type_(BrowserDistribution::CHROME_BROWSER) {
}
template<class DistributionClass>
BrowserDistribution* BrowserDistribution::GetOrCreateBrowserDistribution(
const installer::MasterPreferences& prefs,
BrowserDistribution** dist) {
if (!*dist) {
DistributionClass* temp = new DistributionClass(prefs);
if (base::subtle::NoBarrier_CompareAndSwap(
reinterpret_cast<base::subtle::AtomicWord*>(dist), NULL,
reinterpret_cast<base::subtle::AtomicWord>(temp)) != NULL)
delete temp;
}
return *dist;
}
BrowserDistribution* BrowserDistribution::GetDistribution() {
const installer::MasterPreferences& prefs =
installer::MasterPreferences::ForCurrentProcess();
return GetSpecificDistribution(GetCurrentDistributionType(), prefs);
}
// static
BrowserDistribution* BrowserDistribution::GetSpecificDistribution(
BrowserDistribution::Type type,
const installer::MasterPreferences& prefs) {
BrowserDistribution* dist = NULL;
if (type == CHROME_FRAME) {
dist = GetOrCreateBrowserDistribution<ChromeFrameDistribution>(
prefs, &g_chrome_frame_distribution);
} else {
DCHECK_EQ(CHROME_BROWSER, type);
#if defined(GOOGLE_CHROME_BUILD)
if (InstallUtil::IsChromeSxSProcess()) {
dist = GetOrCreateBrowserDistribution<GoogleChromeSxSDistribution>(
prefs, &g_browser_distribution);
} else {
dist = GetOrCreateBrowserDistribution<GoogleChromeDistribution>(
prefs, &g_browser_distribution);
}
#else
dist = GetOrCreateBrowserDistribution<BrowserDistribution>(
prefs, &g_browser_distribution);
#endif
}
return dist;
}
void BrowserDistribution::DoPostUninstallOperations(
const Version& version, const FilePath& local_data_path,
const std::wstring& distribution_data) {
}
std::wstring BrowserDistribution::GetAppGuid() {
return L"";
}
std::wstring BrowserDistribution::GetApplicationName() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetAppShortCutName() {
return GetApplicationName();
}
std::wstring BrowserDistribution::GetAlternateApplicationName() {
return L"The Internet";
}
std::wstring BrowserDistribution::GetBrowserAppId() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetInstallSubDir() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetPublisherName() {
return L"Chromium";
}
std::wstring BrowserDistribution::GetAppDescription() {
return L"Browse the web";
}
std::wstring BrowserDistribution::GetLongAppDescription() {
const std::wstring& app_description =
installer::GetLocalizedString(IDS_PRODUCT_DESCRIPTION_BASE);
return app_description;
}
// static
int BrowserDistribution::GetInstallReturnCode(
installer::InstallStatus status) {
switch (status) {
case installer::FIRST_INSTALL_SUCCESS:
case installer::INSTALL_REPAIRED:
case installer::NEW_VERSION_UPDATED:
case installer::IN_USE_UPDATED:
return 0;
default:
return status;
}
}
std::string BrowserDistribution::GetSafeBrowsingName() {
return "chromium";
}
std::wstring BrowserDistribution::GetStateKey() {
return L"Software\\Chromium";
}
std::wstring BrowserDistribution::GetStateMediumKey() {
return L"Software\\Chromium";
}
std::wstring BrowserDistribution::GetStatsServerURL() {
return L"";
}
std::wstring BrowserDistribution::GetDistributionData(HKEY root_key) {
return L"";
}
std::wstring BrowserDistribution::GetUninstallLinkName() {
return L"Uninstall Chromium";
}
std::wstring BrowserDistribution::GetUninstallRegPath() {
return L"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Chromium";
}
std::wstring BrowserDistribution::GetVersionKey() {
return L"Software\\Chromium";
}
bool BrowserDistribution::CanSetAsDefault() {
return true;
}
int BrowserDistribution::GetIconIndex() {
return 0;
}
bool BrowserDistribution::GetChromeChannel(std::wstring* channel) {
return false;
}
void BrowserDistribution::UpdateDiffInstallStatus(bool system_install,
bool incremental_install, installer::InstallStatus install_status) {
}
void BrowserDistribution::LaunchUserExperiment(
installer::InstallStatus status, const Version& version,
const installer::Product& installation, bool system_level) {
}
void BrowserDistribution::InactiveUserToastExperiment(int flavor,
const installer::Product& installation) {
}
std::vector<FilePath> BrowserDistribution::GetKeyFiles() {
std::vector<FilePath> key_files;
key_files.push_back(FilePath(installer::kChromeDll));
return key_files;
}
std::vector<FilePath> BrowserDistribution::GetComDllList() {
return std::vector<FilePath>();
}
void BrowserDistribution::AppendUninstallCommandLineFlags(
CommandLine* cmd_line) {
DCHECK(cmd_line);
cmd_line->AppendSwitch(installer::switches::kChrome);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/constrained_window_views.h"
#include "views/widget/native_widget_views.h"
class NativeConstrainedWindowViews : public NativeConstrainedWindow,
public views::NativeWidgetViews {
public:
explicit NativeConstrainedWindowViews(
NativeConstrainedWindowDelegate* delegate)
: views::NativeWidgetViews(delegate->AsNativeWidgetDelegate()),
delegate_(delegate) {
}
virtual ~NativeConstrainedWindowViews() {
}
private:
// Overridden from NativeConstrainedWindow:
virtual views::NativeWidget* AsNativeWidget() OVERRIDE {
return this;
}
NativeConstrainedWindowDelegate* delegate_;
DISALLOW_COPY_AND_ASSIGN(NativeConstrainedWindowViews);
};
////////////////////////////////////////////////////////////////////////////////
// NativeConstrainedWindow, public:
// static
NativeConstrainedWindow* NativeConstrainedWindow::CreateNativeConstrainedWindow(
NativeConstrainedWindowDelegate* delegate) {
return new NativeConstrainedWindowViews(delegate);
}
<commit_msg>Explicitly show ConstrainedWindowViews when activated. Views version uses TYPE_WINDOW (to get focus working, i believe) but not TYPE_CONTROL, which is is no longer visible by default as of r103330. Show when activated.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/constrained_window_views.h"
#include "views/widget/native_widget_views.h"
class NativeConstrainedWindowViews : public NativeConstrainedWindow,
public views::NativeWidgetViews {
public:
explicit NativeConstrainedWindowViews(
NativeConstrainedWindowDelegate* delegate)
: views::NativeWidgetViews(delegate->AsNativeWidgetDelegate()),
delegate_(delegate) {
}
virtual ~NativeConstrainedWindowViews() {
}
virtual void Activate() OVERRIDE {
// Views version of ConstrainedWindow is not TYPE_CONTROL and not
// visible by default. Show when it's activated.
Show();
views::NativeWidgetViews::Activate();
}
private:
// Overridden from NativeConstrainedWindow:
virtual views::NativeWidget* AsNativeWidget() OVERRIDE {
return this;
}
NativeConstrainedWindowDelegate* delegate_;
DISALLOW_COPY_AND_ASSIGN(NativeConstrainedWindowViews);
};
////////////////////////////////////////////////////////////////////////////////
// NativeConstrainedWindow, public:
// static
NativeConstrainedWindow* NativeConstrainedWindow::CreateNativeConstrainedWindow(
NativeConstrainedWindowDelegate* delegate) {
return new NativeConstrainedWindowViews(delegate);
}
<|endoftext|>
|
<commit_before>#include "LocalCluster.hpp"
#include "TelegramServer.hpp"
#include "RemoteServerConnection.hpp"
#include "Storage.hpp"
#include "TelegramServerUser.hpp"
#include "DefaultAuthorizationProvider.hpp"
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(c_loggingClusterCategory, "telegram.server.cluster", QtWarningMsg)
namespace Telegram {
namespace Server {
LocalCluster::LocalCluster(QObject *parent)
: QObject(parent)
{
m_constructor = [](QObject *parent) { return new Server(parent); };
}
void LocalCluster::setServerContructor(LocalCluster::ServerConstructor constructor)
{
m_constructor = constructor;
}
void LocalCluster::setStorage(Storage *storage)
{
m_storage = storage;
}
void LocalCluster::setAuthorizationProvider(Authorization::Provider *provider)
{
m_authProvider = provider;
}
void LocalCluster::setServerConfiguration(const DcConfiguration &config)
{
m_serverConfiguration = config;
}
void LocalCluster::setServerPrivateRsaKey(const Telegram::RsaKey &key)
{
m_key = key;
}
bool LocalCluster::start()
{
if (m_serverConfiguration.dcOptions.isEmpty()) {
qCCritical(c_loggingClusterCategory) << Q_FUNC_INFO << "Unable to start cluster: DC options is empty.";
return false;
}
if (!m_key.isPrivate()) {
qCCritical(c_loggingClusterCategory) << Q_FUNC_INFO << "Unable to start cluster: Invalid private key.";
return false;
}
if (!m_storage) {
qCDebug(c_loggingClusterCategory) << Q_FUNC_INFO << "Fallback to default Storage implementation";
m_storage = new Storage(this);
}
if (!m_authProvider) {
qCDebug(c_loggingClusterCategory) << Q_FUNC_INFO << "Fallback to default auth provider";
m_authProvider = new Authorization::DefaultProvider();
}
for (const DcOption &dc : m_serverConfiguration.dcOptions) {
if (!dc.id) {
qCCritical(c_loggingClusterCategory) << Q_FUNC_INFO << "Invalid configuration: DC id is null.";
return false;
}
if (!dc.port) {
qCCritical(c_loggingClusterCategory) << Q_FUNC_INFO << "Invalid configuration: Server port is not set.";
return false;
}
if (dc.address.isEmpty()) {
qCCritical(c_loggingClusterCategory) << Q_FUNC_INFO << "Invalid configuration: Server address is not set.";
return false;
}
Server *server = m_constructor(this);
server->setServerConfiguration(m_serverConfiguration);
server->setDcOption(dc);
server->setServerPrivateRsaKey(m_key);
server->setStorage(m_storage);
server->setAuthorizationProvider(m_authProvider);
m_serverInstances.append(server);
}
bool hasFails = false;
for (Server *server : m_serverInstances) {
for (Server *peer : m_serverInstances) {
if (server == peer) {
continue;
}
RemoteServerConnection *remote = new RemoteServerConnection(server);
remote->setRemoteServer(peer);
server->addServerConnection(remote);
}
if (!server->start()) {
qCCritical(c_loggingClusterCategory) << Q_FUNC_INFO << "Unable to start server" << server->dcId();
hasFails = true;
}
}
return !hasFails;
}
void LocalCluster::stop()
{
for (Server *server : m_serverInstances) {
server->stop();
}
}
LocalUser *LocalCluster::addUser(const QString &identifier, quint32 dcId)
{
Server *server = getServerInstance(dcId);
if (!server) {
qCWarning(c_loggingClusterCategory) << Q_FUNC_INFO << "Unable to add user" << identifier << "to unknown server id" << dcId;
return nullptr;
}
return server->addUser(identifier);
}
LocalUser *LocalCluster::getUser(const QString &identifier)
{
AbstractUser *u = m_serverInstances.first()->getAbstractUser(identifier);
Server *s = getServerInstance(u->dcId());
return s->getUser(identifier);
}
Server *LocalCluster::getServerInstance(quint32 dcId)
{
for (Server *server : m_serverInstances) {
if (server->dcId() == dcId) {
return server;
}
}
return nullptr;
}
ServerApi *LocalCluster::getServerApiInstance(quint32 dcId)
{
return getServerInstance(dcId);
}
} // Server namespace
} // Telegram namespace
<commit_msg>LocalCluster: Check if an identifier is free on addUser()<commit_after>#include "LocalCluster.hpp"
#include "TelegramServer.hpp"
#include "RemoteServerConnection.hpp"
#include "Storage.hpp"
#include "TelegramServerUser.hpp"
#include "DefaultAuthorizationProvider.hpp"
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(c_loggingClusterCategory, "telegram.server.cluster", QtWarningMsg)
namespace Telegram {
namespace Server {
LocalCluster::LocalCluster(QObject *parent)
: QObject(parent)
{
m_constructor = [](QObject *parent) { return new Server(parent); };
}
void LocalCluster::setServerContructor(LocalCluster::ServerConstructor constructor)
{
m_constructor = constructor;
}
void LocalCluster::setStorage(Storage *storage)
{
m_storage = storage;
}
void LocalCluster::setAuthorizationProvider(Authorization::Provider *provider)
{
m_authProvider = provider;
}
void LocalCluster::setServerConfiguration(const DcConfiguration &config)
{
m_serverConfiguration = config;
}
void LocalCluster::setServerPrivateRsaKey(const Telegram::RsaKey &key)
{
m_key = key;
}
bool LocalCluster::start()
{
if (m_serverConfiguration.dcOptions.isEmpty()) {
qCCritical(c_loggingClusterCategory) << Q_FUNC_INFO << "Unable to start cluster: DC options is empty.";
return false;
}
if (!m_key.isPrivate()) {
qCCritical(c_loggingClusterCategory) << Q_FUNC_INFO << "Unable to start cluster: Invalid private key.";
return false;
}
if (!m_storage) {
qCDebug(c_loggingClusterCategory) << Q_FUNC_INFO << "Fallback to default Storage implementation";
m_storage = new Storage(this);
}
if (!m_authProvider) {
qCDebug(c_loggingClusterCategory) << Q_FUNC_INFO << "Fallback to default auth provider";
m_authProvider = new Authorization::DefaultProvider();
}
for (const DcOption &dc : m_serverConfiguration.dcOptions) {
if (!dc.id) {
qCCritical(c_loggingClusterCategory) << Q_FUNC_INFO << "Invalid configuration: DC id is null.";
return false;
}
if (!dc.port) {
qCCritical(c_loggingClusterCategory) << Q_FUNC_INFO << "Invalid configuration: Server port is not set.";
return false;
}
if (dc.address.isEmpty()) {
qCCritical(c_loggingClusterCategory) << Q_FUNC_INFO << "Invalid configuration: Server address is not set.";
return false;
}
Server *server = m_constructor(this);
server->setServerConfiguration(m_serverConfiguration);
server->setDcOption(dc);
server->setServerPrivateRsaKey(m_key);
server->setStorage(m_storage);
server->setAuthorizationProvider(m_authProvider);
m_serverInstances.append(server);
}
bool hasFails = false;
for (Server *server : m_serverInstances) {
for (Server *peer : m_serverInstances) {
if (server == peer) {
continue;
}
RemoteServerConnection *remote = new RemoteServerConnection(server);
remote->setRemoteServer(peer);
server->addServerConnection(remote);
}
if (!server->start()) {
qCCritical(c_loggingClusterCategory) << Q_FUNC_INFO << "Unable to start server" << server->dcId();
hasFails = true;
}
}
return !hasFails;
}
void LocalCluster::stop()
{
for (Server *server : m_serverInstances) {
server->stop();
}
}
LocalUser *LocalCluster::addUser(const QString &identifier, quint32 dcId)
{
if (getUser(identifier)) {
qCWarning(c_loggingClusterCategory) << Q_FUNC_INFO << "Unable to add user"
<< identifier << "(the identifier is already taken)";
return nullptr;
}
Server *server = getServerInstance(dcId);
if (!server) {
qCWarning(c_loggingClusterCategory) << Q_FUNC_INFO << "Unable to add user"
<< identifier << "to unknown server id" << dcId;
return nullptr;
}
return server->addUser(identifier);
}
LocalUser *LocalCluster::getUser(const QString &identifier)
{
AbstractUser *u = m_serverInstances.first()->getAbstractUser(identifier);
if (!u) {
return nullptr;
}
Server *s = getServerInstance(u->dcId());
return s->getUser(identifier);
}
Server *LocalCluster::getServerInstance(quint32 dcId)
{
for (Server *server : m_serverInstances) {
if (server->dcId() == dcId) {
return server;
}
}
return nullptr;
}
ServerApi *LocalCluster::getServerApiInstance(quint32 dcId)
{
return getServerInstance(dcId);
}
} // Server namespace
} // Telegram namespace
<|endoftext|>
|
<commit_before>
#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>
#include <OpenMesh/Tools/Decimater/DecimaterT.hh>
#include <OpenMesh/Tools/Decimater/ModQuadricT.hh>
namespace {
class OpenMeshDecimater : public OpenMeshBase {
protected:
// This function is called before each test is run
virtual void SetUp() {
// Do some initial stuff with the member data here...
}
// This function is called after all tests are through
virtual void TearDown() {
// Do some final stuff with the member data here...
}
// Member already defined in OpenMeshBase
//Mesh mesh_;
};
/*
* ====================================================================
* Define tests below
* ====================================================================
*/
/*
*/
TEST_F(OpenMeshDecimater, DecimateMesh) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to(5000);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526u, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
TEST_F(OpenMeshDecimater, DecimateMeshToFaceVerticesLimit) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to_faces(5000, 8000);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526u, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
TEST_F(OpenMeshDecimater, DecimateMeshToFaceFaceLimit) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to_faces(4500, 9996);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526u, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
TEST_F(OpenMeshDecimater, DecimateMeshExampleFromDoc) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
std::cout << decimaterDBG.module( hModQuadricDBG ).name() << std::endl;
decimaterDBG.module( hModQuadricDBG ).unset_max_err();
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to_faces(4500, 9996);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526u, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
}
<commit_msg>Silence Decimater test<commit_after>
#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>
#include <OpenMesh/Tools/Decimater/DecimaterT.hh>
#include <OpenMesh/Tools/Decimater/ModQuadricT.hh>
namespace {
class OpenMeshDecimater : public OpenMeshBase {
protected:
// This function is called before each test is run
virtual void SetUp() {
// Do some initial stuff with the member data here...
}
// This function is called after all tests are through
virtual void TearDown() {
// Do some final stuff with the member data here...
}
// Member already defined in OpenMeshBase
//Mesh mesh_;
};
/*
* ====================================================================
* Define tests below
* ====================================================================
*/
/*
*/
TEST_F(OpenMeshDecimater, DecimateMesh) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to(5000);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526u, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
TEST_F(OpenMeshDecimater, DecimateMeshToFaceVerticesLimit) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to_faces(5000, 8000);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526u, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
TEST_F(OpenMeshDecimater, DecimateMeshToFaceFaceLimit) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to_faces(4500, 9996);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526u, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
TEST_F(OpenMeshDecimater, DecimateMeshExampleFromDoc) {
bool ok = OpenMesh::IO::read_mesh(mesh_, "cube1.off");
ASSERT_TRUE(ok);
typedef OpenMesh::Decimater::DecimaterT< Mesh > Decimater;
typedef OpenMesh::Decimater::ModQuadricT< Mesh >::Handle HModQuadric;
Decimater decimaterDBG(mesh_);
HModQuadric hModQuadricDBG;
decimaterDBG.add( hModQuadricDBG );
decimaterDBG.module( hModQuadricDBG ).unset_max_err();
decimaterDBG.initialize();
size_t removedVertices = 0;
removedVertices = decimaterDBG.decimate_to_faces(4500, 9996);
decimaterDBG.mesh().garbage_collection();
EXPECT_EQ(2526u, removedVertices) << "The number of remove vertices is not correct!";
EXPECT_EQ(5000u, mesh_.n_vertices()) << "The number of vertices after decimation is not correct!";
EXPECT_EQ(14994u, mesh_.n_edges()) << "The number of edges after decimation is not correct!";
EXPECT_EQ(9996u, mesh_.n_faces()) << "The number of faces after decimation is not correct!";
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbImageToNoDataMaskFilter.h"
#include "otbChangeNoDataValueFilter.h"
#include "itkMaskImageFilter.h"
#include "otbVectorImageToImageListFilter.h"
#include "otbImageListToVectorImageFilter.h"
#include "otbChangeInformationImageFilter.h"
namespace otb
{
namespace Wrapper
{
class ManageNoData : public Application
{
public:
/** Standard class typedefs. */
typedef ManageNoData Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ManageNoData, otb::Application);
/** Filters typedef */
typedef otb::ImageToNoDataMaskFilter<FloatVectorImageType, UInt8ImageType> FilterType;
typedef otb::ChangeNoDataValueFilter<FloatVectorImageType, FloatVectorImageType> ChangeNoDataFilterType;
typedef otb::ImageList<FloatImageType> ImageListType;
typedef otb::VectorImageToImageListFilter<FloatVectorImageType, ImageListType> VectorToListFilterType;
typedef otb::ImageListToVectorImageFilter<ImageListType, FloatVectorImageType> ListToVectorFilterType;
typedef itk::MaskImageFilter<FloatImageType, UInt8ImageType, FloatImageType> MaskFilterType;
typedef otb::ChangeInformationImageFilter<FloatVectorImageType> ChangeInfoFilterType;
private:
void DoInit() override
{
SetName("ManageNoData");
SetDescription("Manage No-Data");
// Documentation
SetDocLongDescription(
"This application has two modes. The first allows building a mask of no-data pixels from the no-data flags read from the image file. The second allows "
"updating the change the no-data value of an image (pixels value and metadata). This last mode also allows replacing NaN in images with a proper "
"no-data value. To do so, one should activate the NaN is no-data option.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("BandMath");
AddDocTag(Tags::Manip);
AddDocTag("Conversion");
AddDocTag("Image Dynamic");
AddParameter(ParameterType_InputImage, "in", "Input image");
SetParameterDescription("in", "Input image");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output image");
AddParameter(ParameterType_Bool, "usenan", "Consider NaN as no-data");
SetParameterDescription("usenan", "If active, the application will consider NaN as no-data values as well");
AddParameter(ParameterType_Choice, "mode", "No-data handling mode");
SetParameterDescription("mode", "Allows choosing between different no-data handling options");
AddChoice("mode.buildmask", "Build a no-data Mask");
AddParameter(ParameterType_Float, "mode.buildmask.inv", "Inside Value");
SetParameterDescription("mode.buildmask.inv", "Value given in the output mask to pixels that are not no data pixels");
SetDefaultParameterInt("mode.buildmask.inv", 1);
AddParameter(ParameterType_Float, "mode.buildmask.outv", "Outside Value");
SetParameterDescription("mode.buildmask.outv", "Value given in the output mask to pixels that are no data pixels");
SetDefaultParameterInt("mode.buildmask.outv", 0);
AddChoice("mode.changevalue", "Change the no-data value");
AddParameter(ParameterType_Float, "mode.changevalue.newv", "The new no-data value");
SetParameterDescription("mode.changevalue.newv", "The new no-data value");
SetDefaultParameterInt("mode.changevalue.newv", 0);
AddChoice("mode.apply", "Apply a mask as no-data");
SetParameterDescription("mode.apply", "Apply an external mask to an image using the no-data value of the input image");
AddParameter(ParameterType_InputImage, "mode.apply.mask", "Mask image");
SetParameterDescription("mode.apply.mask", "Mask to be applied on input image (valid pixels have non null values)");
AddParameter(ParameterType_Float, "mode.apply.ndval", "Nodata value used");
SetParameterDescription("mode.apply.ndval", "No Data value used according to the mask image");
SetDefaultParameterFloat("mode.apply.ndval", 0.0);
SetParameterString("mode", "buildmask");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "QB_Toulouse_Ortho_XS_nodatamask.tif uint8");
SetDocExampleParameterValue("mode.buildmask.inv", "255");
SetDocExampleParameterValue("mode.buildmask.outv", "0");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
// Nothing to do here for the parameters : all are independent
}
void DoExecute() override
{
FloatVectorImageType::Pointer inputPtr = this->GetParameterImage("in");
m_Filter = FilterType::New();
m_Filter->SetInsideValue(this->GetParameterFloat("mode.buildmask.inv"));
m_Filter->SetOutsideValue(this->GetParameterFloat("mode.buildmask.outv"));
m_Filter->SetNaNIsNoData(GetParameterInt("usenan"));
m_Filter->SetInput(inputPtr);
m_ChangeNoDataFilter = ChangeNoDataFilterType::New();
m_ChangeNoDataFilter->SetInput(inputPtr);
m_ChangeNoDataFilter->SetNaNIsNoData(GetParameterInt("usenan"));
std::vector<double> newNoData(inputPtr->GetNumberOfComponentsPerPixel(), GetParameterFloat("mode.changevalue.newv"));
m_ChangeNoDataFilter->SetNewNoDataValues(newNoData);
if (GetParameterString("mode") == "buildmask")
{
SetParameterOutputImage("out", m_Filter->GetOutput());
}
else if (GetParameterString("mode") == "changevalue")
{
SetParameterOutputImage("out", m_ChangeNoDataFilter->GetOutput());
}
else if (GetParameterString("mode") == "apply")
{
m_MaskFilters.clear();
UInt8ImageType::Pointer maskPtr = this->GetParameterUInt8Image("mode.apply.mask");
unsigned int nbBands = inputPtr->GetNumberOfComponentsPerPixel();
const auto & imd = inputPtr->GetImageMetadata();
std::vector<bool> flags;
std::vector<double> values;
bool ret = otb::ReadNoDataFlags(imd, flags, values);
if (!ret)
{
flags.resize(nbBands, true);
values.resize(nbBands, GetParameterFloat("mode.apply.ndval"));
}
m_V2L = VectorToListFilterType::New();
m_V2L->SetInput(inputPtr);
ImageListType::Pointer inputList = m_V2L->GetOutput();
inputList->UpdateOutputInformation();
ImageListType::Pointer outputList = ImageListType::New();
for (unsigned int i = 0; i < nbBands; ++i)
{
if (flags[i])
{
MaskFilterType::Pointer masker = MaskFilterType::New();
masker->SetInput(inputList->GetNthElement(i));
masker->SetMaskImage(maskPtr);
masker->SetMaskingValue(0);
masker->SetOutsideValue(values[i]);
outputList->PushBack(masker->GetOutput());
m_MaskFilters.push_back(masker);
}
else
{
outputList->PushBack(inputList->GetNthElement(i));
}
}
m_L2V = ListToVectorFilterType::New();
m_L2V->SetInput(outputList);
if (!ret)
{
m_MetaDataChanger = ChangeInfoFilterType::New();
m_MetaDataChanger->SetInput(m_L2V->GetOutput());
m_MetaDataChanger->SetOutputMetaData<std::vector<bool>>(otb::MetaDataKey::NoDataValueAvailable, &flags);
m_MetaDataChanger->SetOutputMetaData<std::vector<double>>(otb::MetaDataKey::NoDataValue, &values);
SetParameterOutputImage("out", m_MetaDataChanger->GetOutput());
}
else
{
SetParameterOutputImage("out", m_L2V->GetOutput());
}
}
}
FilterType::Pointer m_Filter;
ChangeNoDataFilterType::Pointer m_ChangeNoDataFilter;
std::vector<MaskFilterType::Pointer> m_MaskFilters;
VectorToListFilterType::Pointer m_V2L;
ListToVectorFilterType::Pointer m_L2V;
ChangeInfoFilterType::Pointer m_MetaDataChanger;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::ManageNoData)
<commit_msg>REFAC: use ImageMetadata instead of itk dictionary to manage NoData in the applymask mode of ManageNoData<commit_after>/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbImageToNoDataMaskFilter.h"
#include "otbChangeNoDataValueFilter.h"
#include "itkMaskImageFilter.h"
#include "otbVectorImageToImageListFilter.h"
#include "otbImageListToVectorImageFilter.h"
namespace otb
{
namespace Wrapper
{
class ManageNoData : public Application
{
public:
/** Standard class typedefs. */
typedef ManageNoData Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ManageNoData, otb::Application);
/** Filters typedef */
typedef otb::ImageToNoDataMaskFilter<FloatVectorImageType, UInt8ImageType> FilterType;
typedef otb::ChangeNoDataValueFilter<FloatVectorImageType, FloatVectorImageType> ChangeNoDataFilterType;
typedef otb::ImageList<FloatImageType> ImageListType;
typedef otb::VectorImageToImageListFilter<FloatVectorImageType, ImageListType> VectorToListFilterType;
typedef otb::ImageListToVectorImageFilter<ImageListType, FloatVectorImageType> ListToVectorFilterType;
typedef itk::MaskImageFilter<FloatImageType, UInt8ImageType, FloatImageType> MaskFilterType;
private:
void DoInit() override
{
SetName("ManageNoData");
SetDescription("Manage No-Data");
// Documentation
SetDocLongDescription(
"This application has two modes. The first allows building a mask of no-data pixels from the no-data flags read from the image file. The second allows "
"updating the change the no-data value of an image (pixels value and metadata). This last mode also allows replacing NaN in images with a proper "
"no-data value. To do so, one should activate the NaN is no-data option.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("BandMath");
AddDocTag(Tags::Manip);
AddDocTag("Conversion");
AddDocTag("Image Dynamic");
AddParameter(ParameterType_InputImage, "in", "Input image");
SetParameterDescription("in", "Input image");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output image");
AddParameter(ParameterType_Bool, "usenan", "Consider NaN as no-data");
SetParameterDescription("usenan", "If active, the application will consider NaN as no-data values as well");
AddParameter(ParameterType_Choice, "mode", "No-data handling mode");
SetParameterDescription("mode", "Allows choosing between different no-data handling options");
AddChoice("mode.buildmask", "Build a no-data Mask");
AddParameter(ParameterType_Float, "mode.buildmask.inv", "Inside Value");
SetParameterDescription("mode.buildmask.inv", "Value given in the output mask to pixels that are not no data pixels");
SetDefaultParameterInt("mode.buildmask.inv", 1);
AddParameter(ParameterType_Float, "mode.buildmask.outv", "Outside Value");
SetParameterDescription("mode.buildmask.outv", "Value given in the output mask to pixels that are no data pixels");
SetDefaultParameterInt("mode.buildmask.outv", 0);
AddChoice("mode.changevalue", "Change the no-data value");
AddParameter(ParameterType_Float, "mode.changevalue.newv", "The new no-data value");
SetParameterDescription("mode.changevalue.newv", "The new no-data value");
SetDefaultParameterInt("mode.changevalue.newv", 0);
AddChoice("mode.apply", "Apply a mask as no-data");
SetParameterDescription("mode.apply", "Apply an external mask to an image using the no-data value of the input image");
AddParameter(ParameterType_InputImage, "mode.apply.mask", "Mask image");
SetParameterDescription("mode.apply.mask", "Mask to be applied on input image (valid pixels have non null values)");
AddParameter(ParameterType_Float, "mode.apply.ndval", "Nodata value used");
SetParameterDescription("mode.apply.ndval", "No Data value used according to the mask image");
SetDefaultParameterFloat("mode.apply.ndval", 0.0);
SetParameterString("mode", "buildmask");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "QB_Toulouse_Ortho_XS_nodatamask.tif uint8");
SetDocExampleParameterValue("mode.buildmask.inv", "255");
SetDocExampleParameterValue("mode.buildmask.outv", "0");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
// Nothing to do here for the parameters : all are independent
}
void DoExecute() override
{
FloatVectorImageType::Pointer inputPtr = this->GetParameterImage("in");
m_Filter = FilterType::New();
m_Filter->SetInsideValue(this->GetParameterFloat("mode.buildmask.inv"));
m_Filter->SetOutsideValue(this->GetParameterFloat("mode.buildmask.outv"));
m_Filter->SetNaNIsNoData(GetParameterInt("usenan"));
m_Filter->SetInput(inputPtr);
m_ChangeNoDataFilter = ChangeNoDataFilterType::New();
m_ChangeNoDataFilter->SetInput(inputPtr);
m_ChangeNoDataFilter->SetNaNIsNoData(GetParameterInt("usenan"));
std::vector<double> newNoData(inputPtr->GetNumberOfComponentsPerPixel(), GetParameterFloat("mode.changevalue.newv"));
m_ChangeNoDataFilter->SetNewNoDataValues(newNoData);
if (GetParameterString("mode") == "buildmask")
{
SetParameterOutputImage("out", m_Filter->GetOutput());
}
else if (GetParameterString("mode") == "changevalue")
{
SetParameterOutputImage("out", m_ChangeNoDataFilter->GetOutput());
}
else if (GetParameterString("mode") == "apply")
{
m_MaskFilters.clear();
UInt8ImageType::Pointer maskPtr = this->GetParameterUInt8Image("mode.apply.mask");
unsigned int nbBands = inputPtr->GetNumberOfComponentsPerPixel();
const auto & imd = inputPtr->GetImageMetadata();
std::vector<bool> flags;
std::vector<double> values;
bool ret = otb::ReadNoDataFlags(imd, flags, values);
if (!ret)
{
flags = std::vector<bool>(nbBands, true);
values = std::vector<double>(nbBands, GetParameterFloat("mode.apply.ndval"));
}
m_V2L = VectorToListFilterType::New();
m_V2L->SetInput(inputPtr);
ImageListType::Pointer inputList = m_V2L->GetOutput();
inputList->UpdateOutputInformation();
ImageListType::Pointer outputList = ImageListType::New();
for (unsigned int i = 0; i < nbBands; ++i)
{
if (flags[i])
{
MaskFilterType::Pointer masker = MaskFilterType::New();
masker->SetInput(inputList->GetNthElement(i));
masker->SetMaskImage(maskPtr);
masker->SetMaskingValue(0);
masker->SetOutsideValue(values[i]);
outputList->PushBack(masker->GetOutput());
m_MaskFilters.push_back(masker);
}
else
{
outputList->PushBack(inputList->GetNthElement(i));
}
}
m_L2V = ListToVectorFilterType::New();
m_L2V->SetInput(outputList);
if (!ret)
{
// write the new NoData values in the output metadata (mode.apply.ndval)
m_L2V->UpdateOutputInformation();
otb::WriteNoDataFlags(flags, values, m_L2V->GetOutput()->GetImageMetadata());
}
SetParameterOutputImage("out", m_L2V->GetOutput());
}
}
FilterType::Pointer m_Filter;
ChangeNoDataFilterType::Pointer m_ChangeNoDataFilter;
std::vector<MaskFilterType::Pointer> m_MaskFilters;
VectorToListFilterType::Pointer m_V2L;
ListToVectorFilterType::Pointer m_L2V;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::ManageNoData)
<|endoftext|>
|
<commit_before>#include <iostream>
#include <list>
#include <gmpxx.h>
#define BITSET_SIZE 64
class DivisorGenerator {
private:
std::list<mpz_class> divisors;
std::string divisorsCSV;
const mpz_class dividend;
const mpz_class firstValueToTest;
const int count;
void computeDivisors();
void computeDivisorsCSV();
public:
DivisorGenerator(mpz_class d, mpz_class f, int c);
DivisorGenerator(std::string d, std::string f, int c);
const std::list<mpz_class> &getDivisors();
const std::string &getDivisorsCSV();
std::list<mpz_class>::const_iterator getIterator();
};<commit_msg>Added class to generate divisors<commit_after>#include <iostream>
#include <list>
#include <gmpxx.h>
class DivisorGenerator {
private:
std::list<mpz_class> divisors;
std::string divisorsCSV;
const mpz_class dividend;
const mpz_class firstValueToTest;
const int count;
void computeDivisors();
void computeDivisorsCSV();
public:
DivisorGenerator(mpz_class d, mpz_class f, int c);
DivisorGenerator(std::string d, std::string f, int c);
const std::list<mpz_class> &getDivisors();
const std::string &getDivisorsCSV();
std::list<mpz_class>::const_iterator getIterator();
};<|endoftext|>
|
<commit_before>#if !defined (__CINT__) || (defined(__MAKECINT__))
#include <iostream>
#include "TObject.h"
#include "AliVEvent.h"
#include "AliAnalysisTaskdNdEtapp13.h"
#include "AliAnalysisManager.h"
#include "TProof.h"
#include "TFile.h"
#include "TROOT.h"
#endif
const Double_t centBinsMultV0MSPD[] = {1e-10, 1., 5., 10., 15., 20., 30., 40., 50., 70., 100};
const Double_t centBinsMultV0M[] = {0., 1., 5., 10., 15., 20., 30., 40., 50., 70., 100};
const Double_t centBinsMultV0M_Ridge[] = {0., 0.01, 0.1, 0.5, 1., 5., 10., 15., 20., 30., 40., 50., 70., 100};
//const Double_t centBinsMultV0M_Ridge[] = {0., 0.001, 0.01, 0.1, 0.5, 1., 5., 10., 15., 20., 30., 40., 50., 70., 100};
//const Double_t centBinsMultV0M_Ridge[] = {0., 0.001, 0.01, 0.1, 0.5, 1., 3., 5., 10., 20., 30., 40., 50., 90., 100};
//const Double_t centBinsMultV0M_Ridge[] = {0., 1., 8., 16., 25., 27., 43., 45., 68., 69., 100.};
const Double_t centBinsMultRef[] = {0., 1., 5., 10., 15., 20., 30., 40., 50., 70., 100};
const Double_t centBinsMB[] = {0., 100.};
//__________________________________________________________________
AliAnalysisTaskdNdEtapp13 *
AddAnalysisTaskdNdEtaPP13(const Char_t *outfilename = "AnalysisResults.root",
const Char_t *listname = "clist",
//
Float_t etaMin =-5, // min eta range to fill in histos
Float_t etaMax = 5, // max eta range to fill in histos
Float_t zMin = -10, // process events with Z vertex min
Float_t zMax = 10, // max positions
const char* useCentVar = "V0M", // centrality variable to use
//
Float_t cutSigNStd = 1.5, // cut on weighed distance used to extract signal
Float_t cutSigDPhiS = -1, // cut on dPhi-phiBent used to extract signal (if negative -> dphi*sqrt(cutSigNStd)
Bool_t useMC = kTRUE, // fill MC info
//
Bool_t doRec = kFALSE, // fill data histos from new reco
Bool_t doInj = kFALSE, // create Inj. bg
Bool_t doRot = kFALSE, // create Rot. bg
//
// specific parameters for reconstruction
float phiRot = 3.14159e+00, // angle for bg. generation with rotation
float injScale = 1.,//0.7, // inject injScale*Ncl(Lr1/Lr2) hits
Bool_t scaleDTheta = kTRUE, // scale dTheta by 1/sin^2(theta) in trackleting
float nStdDev = 25., // number of st.dev. for tracklet cut to keep
float dphi = 0.08, // dphi window (sigma of tracklet cut)
float dtht = 0.025, // dtheta .... (if negative, abs will be used with additional cut on |dthetaX|, apart from w.distance
float phishift = 0.0045, // bending shift
Bool_t remOvl = kTRUE,
float ovlPhiCut = 0.005,
float ovlZetaCut = 0.05,
Bool_t checkReconstructables = kFALSE,
UInt_t trigSel = AliVEvent::kINT7,//kTRUE, // fill histos for reconstructable (needs useMC and doRec)
Bool_t ridgeBins = kFALSE, // VOM percentiles with ridge binning
Bool_t useBCmod = kFALSE, // set Bunch crossing mode 4
Int_t BCmod4 = 2, // set Bunch crossing mode 4
const char* phicuts = "phi0", // set cut on affected phi regions
Float_t mcscale = 1.0, // set mc scale for V0 amplitude
Bool_t mcCalib = kTRUE, // set cut on affected phi regions
TString calibfile = "./V0M_bins_LHC15g3a3.root"
// const Char_t *calibfile = "$HOME/alice/ali-master/AliPhysics/PWGLF/ppVsMult/dNdEtaPP13/task/V0M_bins_LHC15g3a3.root",
)
{
if (cutSigDPhiS<0) cutSigDPhiS = TMath::Sqrt(cutSigNStd)*dphi;
/* init analysis name */
TString analysisName = "dNdEtapp13";
/* check analysis manager */
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("", "cannot get analysis manager");
return NULL;
}
/* check input event handler */
if (!mgr->GetInputEventHandler()) {
Error("", "cannot get input event handler");
return NULL;
}
/* get common input data container */
AliAnalysisDataContainer *inputc = mgr->GetCommonInputContainer();
if (!inputc) {
Error("", "cannot get common input container");
return NULL;
}
/* create output data container */
AliAnalysisDataContainer *outputc1 = mgr->CreateContainer(listname, TList::Class(), AliAnalysisManager::kOutputContainer, outfilename);
if (!outputc1) {
Error("", "cannot create output container \"clist\"");
return NULL;
}
/* create task and connect input/output */
AliAnalysisTaskdNdEtapp13 *task = new AliAnalysisTaskdNdEtapp13("AliAnalysisTaskdNdEtapp13");
mgr->AddTask(task);
mgr->ConnectInput(task, 0, inputc);
mgr->ConnectOutput(task, 1, outputc1);
//__________________________________________________________________
//__________________________________________________________________
//__________________________________________________________________
/* configure task */
//__________________________________________________________________
//__________________________________________________________________
//__________________________________________________________________
//
TFile *fcalib = TFile::Open(calibfile);
TH1D * hMCcalib2 = (TH1D*)fcalib->Get("h3") ;
task->SetCalibfilePath(calibfile);
task->SetCalibHisto(hMCcalib2);
task->SetUseCentralityVar(useCentVar);
const Double_t *centBins = NULL;
//const Float_t *centBins = NULL;
Int_t nCentBins = 0;
TString strCentr = useCentVar;
if (strCentr == "MB"){
centBins = centBinsMB;
nCentBins = sizeof(centBinsMB) / 8 - 1;
}
else if (strCentr == "V0M" && ridgeBins){
centBins = centBinsMultV0M_Ridge;
nCentBins = sizeof(centBinsMultV0M_Ridge) / 8 - 1;
}
else if (strCentr == "V0M" || strCentr == "V0av"){
centBins = centBinsMultV0M;
nCentBins = sizeof(centBinsMultV0M) / 8 - 1;
}
else if(strCentr == "RefMult08"){
centBins = centBinsMultRef;
nCentBins = sizeof(centBinsMultRef) / 8 - 1;
}
else if(strCentr == "SPDClusters1"){
centBins = centBinsMultV0MSPD;
nCentBins = sizeof(centBinsMultV0MSPD) / 8 - 1;
}
else if(strCentr == "CL0"){
centBins = centBinsMultV0M;
nCentBins = sizeof(centBinsMultV0M) / 8 - 1;
}
else if(strCentr == "SPDTracklets08"){
centBins = centBinsMultV0M;
nCentBins = sizeof(centBinsMultV0M) / 8 - 1;
}
else if(strCentr == "SPDTracklets08to15"){
centBins = centBinsMultV0M;
nCentBins = sizeof(centBinsMultV0M) / 8 - 1;
}
else if (strCentr == "SPDTracklets" && ridgeBins){
centBins = centBinsMultV0M_Ridge;
nCentBins = sizeof(centBinsMultV0M_Ridge) / 8 - 1;
}
else if(strCentr == "SPDTracklets"){
centBins = centBinsMultV0M;
nCentBins = sizeof(centBinsMultV0M) / 8 - 1;
}
task->SetCentPercentiles(centBins, nCentBins);
task->SetTriggerSelection(trigSel);
//
task->SetDoNormalReco(doRec);
task->SetDoInjection(doInj);
task->SetDoRotation(doRot);
//
task->SetUseMC(useMC);
task->SetCheckReconstructables(checkReconstructables);
//
task->SetEtaMin(etaMin);
task->SetEtaMax(etaMax);
task->SetZVertexMin(zMin);
task->SetZVertexMax(zMax);
//
task->SetDPhiSCut(cutSigDPhiS);
task->SetNStdCut(cutSigNStd);
//
task->SetScaleDThetaBySin2T(scaleDTheta);
task->SetNStdDev(nStdDev);
task->SetPhiWindow(dphi);
task->SetThetaWindow(dtht);
task->SetPhiShift(phishift);
task->SetPhiOverlapCut(ovlPhiCut);
task->SetZetaOverlapCut(ovlZetaCut);
task->SetPhiRot(phiRot);
task->SetInjScale(injScale);
task->SetRemoveOverlaps(remOvl);
task->SetUseBCMod(useBCmod);
task->SetMCCalib(mcCalib);
task->SetBCMod(BCmod4);
task->SetCutOnPhi(phicuts);
task->SetScaleMCV0(mcscale);
//
// task->Dump();
return task;
}
<commit_msg>changed HM bins<commit_after>#if !defined (__CINT__) || (defined(__MAKECINT__))
#include <iostream>
#include "TObject.h"
#include "AliVEvent.h"
#include "AliAnalysisTaskdNdEtapp13.h"
#include "AliAnalysisManager.h"
#include "TProof.h"
#include "TFile.h"
#include "TROOT.h"
#endif
const Double_t centBinsMultV0MSPD[] = {1e-10, 1., 5., 10., 15., 20., 30., 40., 50., 70., 100.};
const Double_t centBinsMultV0M[] = {0., 1., 5., 10., 15., 20., 30., 40., 50., 70., 100.};
const Double_t centBinsMultV0M_Ridge[] = {0., 0.01, 0.1, 1., 5., 10., 15., 20., 30., 40., 50., 70., 100.};
//const Double_t centBinsMultV0M_Ridge[] = {0., 0.001, 0.01, 0.1, 0.5, 1., 5., 10., 15., 20., 30., 40., 50., 70., 100};
//const Double_t centBinsMultV0M_Ridge[] = {0., 0.001, 0.01, 0.1, 0.5, 1., 3., 5., 10., 20., 30., 40., 50., 90., 100};
//const Double_t centBinsMultV0M_Ridge[] = {0., 1., 8., 16., 25., 27., 43., 45., 68., 69., 100.};
const Double_t centBinsMultRef[] = {0., 1., 5., 10., 15., 20., 30., 40., 50., 70., 100.};
const Double_t centBinsMB[] = {0., 100.};
//__________________________________________________________________
AliAnalysisTaskdNdEtapp13 *
AddAnalysisTaskdNdEtaPP13(const Char_t *outfilename = "AnalysisResults.root",
const Char_t *listname = "clist",
//
Float_t etaMin =-5, // min eta range to fill in histos
Float_t etaMax = 5, // max eta range to fill in histos
Float_t zMin = -10, // process events with Z vertex min
Float_t zMax = 10, // max positions
const char* useCentVar = "V0M", // centrality variable to use
//
Float_t cutSigNStd = 1.5, // cut on weighed distance used to extract signal
Float_t cutSigDPhiS = -1, // cut on dPhi-phiBent used to extract signal (if negative -> dphi*sqrt(cutSigNStd)
Bool_t useMC = kTRUE, // fill MC info
//
Bool_t doRec = kFALSE, // fill data histos from new reco
Bool_t doInj = kFALSE, // create Inj. bg
Bool_t doRot = kFALSE, // create Rot. bg
//
// specific parameters for reconstruction
float phiRot = 3.14159e+00, // angle for bg. generation with rotation
float injScale = 1.,//0.7, // inject injScale*Ncl(Lr1/Lr2) hits
Bool_t scaleDTheta = kTRUE, // scale dTheta by 1/sin^2(theta) in trackleting
float nStdDev = 25., // number of st.dev. for tracklet cut to keep
float dphi = 0.08, // dphi window (sigma of tracklet cut)
float dtht = 0.025, // dtheta .... (if negative, abs will be used with additional cut on |dthetaX|, apart from w.distance
float phishift = 0.0045, // bending shift
Bool_t remOvl = kTRUE,
float ovlPhiCut = 0.005,
float ovlZetaCut = 0.05,
Bool_t checkReconstructables = kFALSE,
UInt_t trigSel = AliVEvent::kINT7,//kTRUE, // fill histos for reconstructable (needs useMC and doRec)
Bool_t ridgeBins = kFALSE, // VOM percentiles with ridge binning
Bool_t useBCmod = kFALSE, // set Bunch crossing mode 4
Int_t BCmod4 = 2, // set Bunch crossing mode 4
const char* phicuts = "phi0", // set cut on affected phi regions
Float_t mcscale = 1.0, // set mc scale for V0 amplitude
Bool_t mcCalib = kTRUE, // set cut on affected phi regions
TString calibfile = "./V0M_bins_LHC15g3a3.root"
// const Char_t *calibfile = "$HOME/alice/ali-master/AliPhysics/PWGLF/ppVsMult/dNdEtaPP13/task/V0M_bins_LHC15g3a3.root",
)
{
if (cutSigDPhiS<0) cutSigDPhiS = TMath::Sqrt(cutSigNStd)*dphi;
/* init analysis name */
TString analysisName = "dNdEtapp13";
/* check analysis manager */
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("", "cannot get analysis manager");
return NULL;
}
/* check input event handler */
if (!mgr->GetInputEventHandler()) {
Error("", "cannot get input event handler");
return NULL;
}
/* get common input data container */
AliAnalysisDataContainer *inputc = mgr->GetCommonInputContainer();
if (!inputc) {
Error("", "cannot get common input container");
return NULL;
}
/* create output data container */
AliAnalysisDataContainer *outputc1 = mgr->CreateContainer(listname, TList::Class(), AliAnalysisManager::kOutputContainer, outfilename);
if (!outputc1) {
Error("", "cannot create output container \"clist\"");
return NULL;
}
/* create task and connect input/output */
AliAnalysisTaskdNdEtapp13 *task = new AliAnalysisTaskdNdEtapp13("AliAnalysisTaskdNdEtapp13");
mgr->AddTask(task);
mgr->ConnectInput(task, 0, inputc);
mgr->ConnectOutput(task, 1, outputc1);
//__________________________________________________________________
//__________________________________________________________________
//__________________________________________________________________
/* configure task */
//__________________________________________________________________
//__________________________________________________________________
//__________________________________________________________________
//
TFile *fcalib = TFile::Open(calibfile);
TH1D * hMCcalib2 = (TH1D*)fcalib->Get("h3") ;
task->SetCalibfilePath(calibfile);
task->SetCalibHisto(hMCcalib2);
task->SetUseCentralityVar(useCentVar);
const Double_t *centBins = NULL;
//const Float_t *centBins = NULL;
Int_t nCentBins = 0;
TString strCentr = useCentVar;
if (strCentr == "MB"){
centBins = centBinsMB;
nCentBins = sizeof(centBinsMB) / 8 - 1;
}
else if (strCentr == "V0M" && ridgeBins){
centBins = centBinsMultV0M_Ridge;
nCentBins = sizeof(centBinsMultV0M_Ridge) / 8 - 1;
}
else if (strCentr == "V0M" || strCentr == "V0av"){
centBins = centBinsMultV0M;
nCentBins = sizeof(centBinsMultV0M) / 8 - 1;
}
else if(strCentr == "RefMult08"){
centBins = centBinsMultRef;
nCentBins = sizeof(centBinsMultRef) / 8 - 1;
}
else if(strCentr == "SPDClusters1"){
centBins = centBinsMultV0MSPD;
nCentBins = sizeof(centBinsMultV0MSPD) / 8 - 1;
}
else if(strCentr == "CL0"){
centBins = centBinsMultV0M;
nCentBins = sizeof(centBinsMultV0M) / 8 - 1;
}
else if(strCentr == "SPDTracklets08"){
centBins = centBinsMultV0M;
nCentBins = sizeof(centBinsMultV0M) / 8 - 1;
}
else if(strCentr == "SPDTracklets08to15"){
centBins = centBinsMultV0M;
nCentBins = sizeof(centBinsMultV0M) / 8 - 1;
}
else if (strCentr == "SPDTracklets" && ridgeBins){
centBins = centBinsMultV0M_Ridge;
nCentBins = sizeof(centBinsMultV0M_Ridge) / 8 - 1;
}
else if(strCentr == "SPDTracklets"){
centBins = centBinsMultV0M;
nCentBins = sizeof(centBinsMultV0M) / 8 - 1;
}
task->SetCentPercentiles(centBins, nCentBins);
task->SetTriggerSelection(trigSel);
//
task->SetDoNormalReco(doRec);
task->SetDoInjection(doInj);
task->SetDoRotation(doRot);
//
task->SetUseMC(useMC);
task->SetCheckReconstructables(checkReconstructables);
//
task->SetEtaMin(etaMin);
task->SetEtaMax(etaMax);
task->SetZVertexMin(zMin);
task->SetZVertexMax(zMax);
//
task->SetDPhiSCut(cutSigDPhiS);
task->SetNStdCut(cutSigNStd);
//
task->SetScaleDThetaBySin2T(scaleDTheta);
task->SetNStdDev(nStdDev);
task->SetPhiWindow(dphi);
task->SetThetaWindow(dtht);
task->SetPhiShift(phishift);
task->SetPhiOverlapCut(ovlPhiCut);
task->SetZetaOverlapCut(ovlZetaCut);
task->SetPhiRot(phiRot);
task->SetInjScale(injScale);
task->SetRemoveOverlaps(remOvl);
task->SetUseBCMod(useBCmod);
task->SetMCCalib(mcCalib);
task->SetBCMod(BCmod4);
task->SetCutOnPhi(phicuts);
task->SetScaleMCV0(mcscale);
//
// task->Dump();
return task;
}
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2HardwareBufferManager.h"
#include "OgreGLES2HardwareVertexBuffer.h"
#include "OgreGLES2HardwareIndexBuffer.h"
#include "OgreGLES2HardwareUniformBuffer.h"
#include "OgreGLES2RenderToVertexBuffer.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreGLVertexArrayObject.h"
#include "OgreGLUtil.h"
#include "OgreRoot.h"
namespace Ogre {
//-----------------------------------------------------------------------
GLES2HardwareBufferManagerBase::GLES2HardwareBufferManagerBase()
{
mRenderSystem = getGLES2RenderSystem();
}
GLES2HardwareBufferManagerBase::~GLES2HardwareBufferManagerBase()
{
destroyAllDeclarations();
destroyAllBindings();
}
GLES2StateCacheManager * GLES2HardwareBufferManagerBase::getStateCacheManager()
{
return mRenderSystem->_getStateCacheManager();
}
void GLES2HardwareBufferManagerBase::::notifyContextDestroyed(GLContext* context)
{
OGRE_LOCK_MUTEX(mVertexDeclarationsMutex);
for(VertexDeclarationList::iterator it = mVertexDeclarations.begin(), it_end = mVertexDeclarations.end(); it != it_end; ++it)
static_cast<GLVertexArrayObject*>(*it)->notifyContextDestroyed(context);
}
HardwareVertexBufferSharedPtr
GLES2HardwareBufferManagerBase::createVertexBuffer(size_t vertexSize,
size_t numVerts,
HardwareBuffer::Usage usage,
bool useShadowBuffer)
{
if(!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_MAPBUFFER))
useShadowBuffer = true;
GLES2HardwareVertexBuffer* buf = OGRE_NEW GLES2HardwareVertexBuffer(this, vertexSize, numVerts, usage, useShadowBuffer);
{
OGRE_LOCK_MUTEX(mVertexBuffersMutex);
mVertexBuffers.insert(buf);
}
return HardwareVertexBufferSharedPtr(buf);
}
HardwareIndexBufferSharedPtr GLES2HardwareBufferManagerBase::createIndexBuffer(HardwareIndexBuffer::IndexType itype,
size_t numIndexes,
HardwareBuffer::Usage usage,
bool useShadowBuffer)
{
if(!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_MAPBUFFER))
useShadowBuffer = true;
GLES2HardwareIndexBuffer* buf = OGRE_NEW GLES2HardwareIndexBuffer(this, itype, numIndexes, usage, useShadowBuffer);
{
OGRE_LOCK_MUTEX(mIndexBuffersMutex);
mIndexBuffers.insert(buf);
}
return HardwareIndexBufferSharedPtr(buf);
}
RenderToVertexBufferSharedPtr GLES2HardwareBufferManagerBase::createRenderToVertexBuffer()
{
#if OGRE_NO_GLES3_SUPPORT == 0
return RenderToVertexBufferSharedPtr(new GLES2RenderToVertexBuffer());
#else
// not supported
return RenderToVertexBufferSharedPtr();
#endif
}
VertexDeclaration* GLES2HardwareBufferManagerBase::createVertexDeclarationImpl(void)
{
return OGRE_NEW GLVertexArrayObject();
}
void GLES2HardwareBufferManagerBase::destroyVertexDeclarationImpl(VertexDeclaration* decl)
{
if(decl)
OGRE_DELETE decl;
}
GLenum GLES2HardwareBufferManagerBase::getGLUsage(unsigned int usage)
{
return (usage & HardwareBuffer::HBU_DISCARDABLE) ? GL_STREAM_DRAW :
(usage & HardwareBuffer::HBU_STATIC) ? GL_STATIC_DRAW :
GL_DYNAMIC_DRAW;
}
GLenum GLES2HardwareBufferManagerBase::getGLType(VertexElementType type)
{
switch(type)
{
case VET_FLOAT1:
case VET_FLOAT2:
case VET_FLOAT3:
case VET_FLOAT4:
return GL_FLOAT;
case VET_SHORT1:
case VET_SHORT2:
case VET_SHORT3:
case VET_SHORT4:
case VET_SHORT2_NORM:
case VET_SHORT4_NORM:
return GL_SHORT;
case VET_COLOUR:
case VET_COLOUR_ABGR:
case VET_COLOUR_ARGB:
case VET_UBYTE4:
case VET_UBYTE4_NORM:
return GL_UNSIGNED_BYTE;
case VET_BYTE4:
case VET_BYTE4_NORM:
return GL_BYTE;
case VET_INT1:
case VET_INT2:
case VET_INT3:
case VET_INT4:
#if OGRE_NO_GLES3_SUPPORT == 0
return GL_INT;
#endif
case VET_UINT1:
case VET_UINT2:
case VET_UINT3:
case VET_UINT4:
#if OGRE_NO_GLES3_SUPPORT == 0
return GL_UNSIGNED_INT;
#endif
case VET_USHORT1:
case VET_USHORT2:
case VET_USHORT3:
case VET_USHORT4:
case VET_USHORT2_NORM:
case VET_USHORT4_NORM:
#if OGRE_NO_GLES3_SUPPORT == 0
return GL_UNSIGNED_SHORT;
#endif
case VET_DOUBLE1:
case VET_DOUBLE2:
case VET_DOUBLE3:
case VET_DOUBLE4:
return 0;
};
OgreAssert(false, "unknown Vertex Element Type");
return 0;
}
//---------------------------------------------------------------------
Ogre::HardwareUniformBufferSharedPtr GLES2HardwareBufferManagerBase::createUniformBuffer( size_t sizeBytes, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name )
{
#if OGRE_NO_GLES3_SUPPORT == 0
GLES2HardwareUniformBuffer* buf =
new GLES2HardwareUniformBuffer(this, sizeBytes, usage, useShadowBuffer, name);
{
OGRE_LOCK_MUTEX(mUniformBuffersMutex);
mUniformBuffers.insert(buf);
}
return HardwareUniformBufferSharedPtr(buf);
#else
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"GLES2 does not support uniform buffer objects",
"GLES2HardwareBufferManagerBase::createUniformBuffer");
#endif
}
//---------------------------------------------------------------------
Ogre::HardwareCounterBufferSharedPtr GLES2HardwareBufferManagerBase::createCounterBuffer( size_t sizeBytes, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name )
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"GLES2 does not support atomic counter buffers",
"GLES2HardwareBufferManagerBase::createCounterBuffer");
}
}
<commit_msg>Fixed GLES2 build<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2HardwareBufferManager.h"
#include "OgreGLES2HardwareVertexBuffer.h"
#include "OgreGLES2HardwareIndexBuffer.h"
#include "OgreGLES2HardwareUniformBuffer.h"
#include "OgreGLES2RenderToVertexBuffer.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreGLVertexArrayObject.h"
#include "OgreGLUtil.h"
#include "OgreRoot.h"
namespace Ogre {
//-----------------------------------------------------------------------
GLES2HardwareBufferManagerBase::GLES2HardwareBufferManagerBase()
{
mRenderSystem = getGLES2RenderSystem();
}
GLES2HardwareBufferManagerBase::~GLES2HardwareBufferManagerBase()
{
destroyAllDeclarations();
destroyAllBindings();
}
GLES2StateCacheManager * GLES2HardwareBufferManagerBase::getStateCacheManager()
{
return mRenderSystem->_getStateCacheManager();
}
void GLES2HardwareBufferManagerBase::notifyContextDestroyed(GLContext* context)
{
OGRE_LOCK_MUTEX(mVertexDeclarationsMutex);
for(VertexDeclarationList::iterator it = mVertexDeclarations.begin(), it_end = mVertexDeclarations.end(); it != it_end; ++it)
static_cast<GLVertexArrayObject*>(*it)->notifyContextDestroyed(context);
}
HardwareVertexBufferSharedPtr
GLES2HardwareBufferManagerBase::createVertexBuffer(size_t vertexSize,
size_t numVerts,
HardwareBuffer::Usage usage,
bool useShadowBuffer)
{
if(!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_MAPBUFFER))
useShadowBuffer = true;
GLES2HardwareVertexBuffer* buf = OGRE_NEW GLES2HardwareVertexBuffer(this, vertexSize, numVerts, usage, useShadowBuffer);
{
OGRE_LOCK_MUTEX(mVertexBuffersMutex);
mVertexBuffers.insert(buf);
}
return HardwareVertexBufferSharedPtr(buf);
}
HardwareIndexBufferSharedPtr GLES2HardwareBufferManagerBase::createIndexBuffer(HardwareIndexBuffer::IndexType itype,
size_t numIndexes,
HardwareBuffer::Usage usage,
bool useShadowBuffer)
{
if(!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_MAPBUFFER))
useShadowBuffer = true;
GLES2HardwareIndexBuffer* buf = OGRE_NEW GLES2HardwareIndexBuffer(this, itype, numIndexes, usage, useShadowBuffer);
{
OGRE_LOCK_MUTEX(mIndexBuffersMutex);
mIndexBuffers.insert(buf);
}
return HardwareIndexBufferSharedPtr(buf);
}
RenderToVertexBufferSharedPtr GLES2HardwareBufferManagerBase::createRenderToVertexBuffer()
{
#if OGRE_NO_GLES3_SUPPORT == 0
return RenderToVertexBufferSharedPtr(new GLES2RenderToVertexBuffer());
#else
// not supported
return RenderToVertexBufferSharedPtr();
#endif
}
VertexDeclaration* GLES2HardwareBufferManagerBase::createVertexDeclarationImpl(void)
{
return OGRE_NEW GLVertexArrayObject();
}
void GLES2HardwareBufferManagerBase::destroyVertexDeclarationImpl(VertexDeclaration* decl)
{
if(decl)
OGRE_DELETE decl;
}
GLenum GLES2HardwareBufferManagerBase::getGLUsage(unsigned int usage)
{
return (usage & HardwareBuffer::HBU_DISCARDABLE) ? GL_STREAM_DRAW :
(usage & HardwareBuffer::HBU_STATIC) ? GL_STATIC_DRAW :
GL_DYNAMIC_DRAW;
}
GLenum GLES2HardwareBufferManagerBase::getGLType(VertexElementType type)
{
switch(type)
{
case VET_FLOAT1:
case VET_FLOAT2:
case VET_FLOAT3:
case VET_FLOAT4:
return GL_FLOAT;
case VET_SHORT1:
case VET_SHORT2:
case VET_SHORT3:
case VET_SHORT4:
case VET_SHORT2_NORM:
case VET_SHORT4_NORM:
return GL_SHORT;
case VET_COLOUR:
case VET_COLOUR_ABGR:
case VET_COLOUR_ARGB:
case VET_UBYTE4:
case VET_UBYTE4_NORM:
return GL_UNSIGNED_BYTE;
case VET_BYTE4:
case VET_BYTE4_NORM:
return GL_BYTE;
case VET_INT1:
case VET_INT2:
case VET_INT3:
case VET_INT4:
#if OGRE_NO_GLES3_SUPPORT == 0
return GL_INT;
#endif
case VET_UINT1:
case VET_UINT2:
case VET_UINT3:
case VET_UINT4:
#if OGRE_NO_GLES3_SUPPORT == 0
return GL_UNSIGNED_INT;
#endif
case VET_USHORT1:
case VET_USHORT2:
case VET_USHORT3:
case VET_USHORT4:
case VET_USHORT2_NORM:
case VET_USHORT4_NORM:
#if OGRE_NO_GLES3_SUPPORT == 0
return GL_UNSIGNED_SHORT;
#endif
case VET_DOUBLE1:
case VET_DOUBLE2:
case VET_DOUBLE3:
case VET_DOUBLE4:
return 0;
};
OgreAssert(false, "unknown Vertex Element Type");
return 0;
}
//---------------------------------------------------------------------
Ogre::HardwareUniformBufferSharedPtr GLES2HardwareBufferManagerBase::createUniformBuffer( size_t sizeBytes, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name )
{
#if OGRE_NO_GLES3_SUPPORT == 0
GLES2HardwareUniformBuffer* buf =
new GLES2HardwareUniformBuffer(this, sizeBytes, usage, useShadowBuffer, name);
{
OGRE_LOCK_MUTEX(mUniformBuffersMutex);
mUniformBuffers.insert(buf);
}
return HardwareUniformBufferSharedPtr(buf);
#else
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"GLES2 does not support uniform buffer objects",
"GLES2HardwareBufferManagerBase::createUniformBuffer");
#endif
}
//---------------------------------------------------------------------
Ogre::HardwareCounterBufferSharedPtr GLES2HardwareBufferManagerBase::createCounterBuffer( size_t sizeBytes, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name )
{
OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
"GLES2 does not support atomic counter buffers",
"GLES2HardwareBufferManagerBase::createCounterBuffer");
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/touchui/touch_factory.h"
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <X11/cursorfont.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include <X11/extensions/XIproto.h>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "ui/base/x/x11_util.h"
namespace {
// The X cursor is hidden if it is idle for kCursorIdleSeconds seconds.
int kCursorIdleSeconds = 5;
// Given the TouchParam, return the correspoding valuator index using
// the X device information through Atom name matching.
char FindTPValuator(Display* display,
XIDeviceInfo* info,
views::TouchFactory::TouchParam touch_param) {
// Lookup table for mapping TouchParam to Atom string used in X.
// A full set of Atom strings can be found at xserver-properties.h.
static struct {
views::TouchFactory::TouchParam tp;
const char* atom;
} kTouchParamAtom[] = {
{ views::TouchFactory::TP_TOUCH_MAJOR, "Abs MT Touch Major" },
{ views::TouchFactory::TP_TOUCH_MINOR, "Abs MT Touch Minor" },
{ views::TouchFactory::TP_ORIENTATION, "Abs MT Orientation" },
{ views::TouchFactory::TP_LAST_ENTRY, NULL },
};
const char* atom_tp = NULL;
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTouchParamAtom); i++) {
if (touch_param == kTouchParamAtom[i].tp) {
atom_tp = kTouchParamAtom[i].atom;
break;
}
}
if (!atom_tp)
return -1;
for (int i = 0; i < info->num_classes; i++) {
if (info->classes[i]->type != XIValuatorClass)
continue;
XIValuatorClassInfo* v =
reinterpret_cast<XIValuatorClassInfo*>(info->classes[i]);
const char* atom = XGetAtomName(display, v->label);
if (atom && strcmp(atom, atom_tp) == 0)
return v->number;
}
return -1;
}
// Setup XInput2 select for the GtkWidget.
gboolean GtkWidgetRealizeCallback(GSignalInvocationHint* hint, guint nparams,
const GValue* pvalues, gpointer data) {
GtkWidget* widget = GTK_WIDGET(g_value_get_object(pvalues));
GdkWindow* window = widget->window;
views::TouchFactory* factory = static_cast<views::TouchFactory*>(data);
if (GDK_WINDOW_TYPE(window) != GDK_WINDOW_TOPLEVEL &&
GDK_WINDOW_TYPE(window) != GDK_WINDOW_CHILD &&
GDK_WINDOW_TYPE(window) != GDK_WINDOW_DIALOG)
return true;
factory->SetupXI2ForXWindow(GDK_WINDOW_XID(window));
return true;
}
// We need to capture all the GDK windows that get created, and start
// listening for XInput2 events. So we setup a callback to the 'realize'
// signal for GTK+ widgets, so that whenever the signal triggers for any
// GtkWidget, which means the GtkWidget should now have a GdkWindow, we can
// setup XInput2 events for the GdkWindow.
guint realize_signal_id = 0;
guint realize_hook_id = 0;
void SetupGtkWidgetRealizeNotifier(views::TouchFactory* factory) {
gpointer klass = g_type_class_ref(GTK_TYPE_WIDGET);
g_signal_parse_name("realize", GTK_TYPE_WIDGET,
&realize_signal_id, NULL, FALSE);
realize_hook_id = g_signal_add_emission_hook(realize_signal_id, 0,
GtkWidgetRealizeCallback, static_cast<gpointer>(factory), NULL);
g_type_class_unref(klass);
}
void RemoveGtkWidgetRealizeNotifier() {
if (realize_signal_id != 0)
g_signal_remove_emission_hook(realize_signal_id, realize_hook_id);
realize_signal_id = 0;
realize_hook_id = 0;
}
} // namespace
namespace views {
// static
TouchFactory* TouchFactory::GetInstance() {
return Singleton<TouchFactory>::get();
}
TouchFactory::TouchFactory()
: is_cursor_visible_(true),
cursor_timer_(),
pointer_device_lookup_(),
touch_device_list_() {
char nodata[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
XColor black;
black.red = black.green = black.blue = 0;
Display* display = ui::GetXDisplay();
Pixmap blank = XCreateBitmapFromData(display, ui::GetX11RootWindow(),
nodata, 8, 8);
invisible_cursor_ = XCreatePixmapCursor(display, blank, blank,
&black, &black, 0, 0);
arrow_cursor_ = XCreateFontCursor(display, XC_arrow);
SetCursorVisible(false, false);
UpdateDeviceList(display);
// TODO(sad): Here, we only setup so that the X windows created by GTK+ are
// setup for XInput2 events. We need a way to listen for XInput2 events for X
// windows created by other means (e.g. for context menus).
SetupGtkWidgetRealizeNotifier(this);
// Make sure the list of devices is kept up-to-date by listening for
// XI_HierarchyChanged event on the root window.
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_HierarchyChanged);
XIEventMask evmask;
evmask.deviceid = XIAllDevices;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
XISelectEvents(display, ui::GetX11RootWindow(), &evmask, 1);
}
TouchFactory::~TouchFactory() {
SetCursorVisible(true, false);
Display* display = ui::GetXDisplay();
XFreeCursor(display, invisible_cursor_);
XFreeCursor(display, arrow_cursor_);
RemoveGtkWidgetRealizeNotifier();
}
void TouchFactory::UpdateDeviceList(Display* display) {
// Detect touch devices.
// NOTE: The new API for retrieving the list of devices (XIQueryDevice) does
// not provide enough information to detect a touch device. As a result, the
// old version of query function (XListInputDevices) is used instead.
// If XInput2 is not supported, this will return null (with count of -1) so
// we assume there cannot be any touch devices.
int count = 0;
touch_device_lookup_.reset();
touch_device_list_.clear();
XDeviceInfo* devlist = XListInputDevices(display, &count);
for (int i = 0; i < count; i++) {
const char* devtype = XGetAtomName(display, devlist[i].type);
if (devtype && !strcmp(devtype, XI_TOUCHSCREEN)) {
touch_device_lookup_[devlist[i].id] = true;
touch_device_list_.push_back(devlist[i].id);
}
}
if (devlist)
XFreeDeviceList(devlist);
// Instead of asking X for the list of devices all the time, let's maintain a
// list of pointer devices we care about.
// It is not necessary to select for slave devices. XInput2 provides enough
// information to the event callback to decide which slave device triggered
// the event, thus decide whether the 'pointer event' is a 'mouse event' or a
// 'touch event'.
// If the touch device has 'GrabDevice' set and 'SendCoreEvents' unset (which
// is possible), then the device is detected as a floating device, and a
// floating device is not connected to a master device. So it is necessary to
// also select on the floating devices.
pointer_device_lookup_.reset();
XIDeviceInfo* devices = XIQueryDevice(display, XIAllDevices, &count);
for (int i = 0; i < count; i++) {
XIDeviceInfo* devinfo = devices + i;
if (devinfo->use == XIFloatingSlave || devinfo->use == XIMasterPointer) {
pointer_device_lookup_[devinfo->deviceid] = true;
}
}
XIFreeDeviceInfo(devices);
SetupValuator();
}
bool TouchFactory::ShouldProcessXI2Event(XEvent* xev) {
DCHECK_EQ(GenericEvent, xev->type);
XGenericEventCookie* cookie = &xev->xcookie;
if (cookie->evtype != XI_ButtonPress &&
cookie->evtype != XI_ButtonRelease &&
cookie->evtype != XI_Motion)
return true;
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data);
return pointer_device_lookup_[xiev->sourceid];
}
void TouchFactory::SetupXI2ForXWindow(Window window) {
// Setup mask for mouse events. It is possible that a device is loaded/plugged
// in after we have setup XInput2 on a window. In such cases, we need to
// either resetup XInput2 for the window, so that we get events from the new
// device, or we need to listen to events from all devices, and then filter
// the events from uninteresting devices. We do the latter because that's
// simpler.
Display* display = ui::GetXDisplay();
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_ButtonPress);
XISetMask(mask, XI_ButtonRelease);
XISetMask(mask, XI_Motion);
XIEventMask evmask;
evmask.deviceid = XIAllDevices;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
XISelectEvents(display, window, &evmask, 1);
XFlush(display);
}
void TouchFactory::SetTouchDeviceList(
const std::vector<unsigned int>& devices) {
touch_device_lookup_.reset();
touch_device_list_.clear();
for (std::vector<unsigned int>::const_iterator iter = devices.begin();
iter != devices.end(); ++iter) {
DCHECK(*iter < touch_device_lookup_.size());
touch_device_lookup_[*iter] = true;
touch_device_list_.push_back(*iter);
}
SetupValuator();
}
bool TouchFactory::IsTouchDevice(unsigned deviceid) const {
return deviceid < touch_device_lookup_.size() ?
touch_device_lookup_[deviceid] : false;
}
bool TouchFactory::GrabTouchDevices(Display* display, ::Window window) {
if (touch_device_list_.empty())
return true;
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
bool success = true;
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_ButtonPress);
XISetMask(mask, XI_ButtonRelease);
XISetMask(mask, XI_Motion);
XIEventMask evmask;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
for (std::vector<int>::const_iterator iter =
touch_device_list_.begin();
iter != touch_device_list_.end(); ++iter) {
evmask.deviceid = *iter;
Status status = XIGrabDevice(display, *iter, window, CurrentTime, None,
GrabModeAsync, GrabModeAsync, False, &evmask);
success = success && status == GrabSuccess;
}
return success;
}
bool TouchFactory::UngrabTouchDevices(Display* display) {
bool success = true;
for (std::vector<int>::const_iterator iter =
touch_device_list_.begin();
iter != touch_device_list_.end(); ++iter) {
Status status = XIUngrabDevice(display, *iter, CurrentTime);
success = success && status == GrabSuccess;
}
return success;
}
void TouchFactory::SetCursorVisible(bool show, bool start_timer) {
// The cursor is going to be shown. Reset the timer for hiding it.
if (show && start_timer) {
cursor_timer_.Stop();
cursor_timer_.Start(base::TimeDelta::FromSeconds(kCursorIdleSeconds),
this, &TouchFactory::HideCursorForInactivity);
} else {
cursor_timer_.Stop();
}
if (show == is_cursor_visible_)
return;
is_cursor_visible_ = show;
Display* display = ui::GetXDisplay();
Window window = DefaultRootWindow(display);
if (is_cursor_visible_) {
XDefineCursor(display, window, arrow_cursor_);
} else {
XDefineCursor(display, window, invisible_cursor_);
}
}
void TouchFactory::SetupValuator() {
memset(valuator_lookup_, -1, sizeof(valuator_lookup_));
Display* display = ui::GetXDisplay();
int ndevice;
XIDeviceInfo* info_list = XIQueryDevice(display, XIAllDevices, &ndevice);
for (int i = 0; i < ndevice; i++) {
XIDeviceInfo* info = info_list + i;
if (!IsTouchDevice(info->deviceid))
continue;
for (int i = 0; i < TP_LAST_ENTRY; i++) {
TouchParam tp = static_cast<TouchParam>(i);
valuator_lookup_[info->deviceid][i] = FindTPValuator(display, info, tp);
}
}
if (info_list)
XIFreeDeviceInfo(info_list);
}
bool TouchFactory::ExtractTouchParam(const XEvent& xev,
TouchParam tp,
float* value) {
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(xev.xcookie.data);
if (xiev->sourceid >= kMaxDeviceNum)
return false;
int v = valuator_lookup_[xiev->sourceid][tp];
if (v >= 0 && XIMaskIsSet(xiev->valuators.mask, v)) {
*value = xiev->valuators.values[v];
return true;
}
return false;
}
} // namespace views
<commit_msg>Select on slave pointers instead of master pointers.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "views/touchui/touch_factory.h"
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <X11/cursorfont.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include <X11/extensions/XIproto.h>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "ui/base/x/x11_util.h"
namespace {
// The X cursor is hidden if it is idle for kCursorIdleSeconds seconds.
int kCursorIdleSeconds = 5;
// Given the TouchParam, return the correspoding valuator index using
// the X device information through Atom name matching.
char FindTPValuator(Display* display,
XIDeviceInfo* info,
views::TouchFactory::TouchParam touch_param) {
// Lookup table for mapping TouchParam to Atom string used in X.
// A full set of Atom strings can be found at xserver-properties.h.
static struct {
views::TouchFactory::TouchParam tp;
const char* atom;
} kTouchParamAtom[] = {
{ views::TouchFactory::TP_TOUCH_MAJOR, "Abs MT Touch Major" },
{ views::TouchFactory::TP_TOUCH_MINOR, "Abs MT Touch Minor" },
{ views::TouchFactory::TP_ORIENTATION, "Abs MT Orientation" },
{ views::TouchFactory::TP_LAST_ENTRY, NULL },
};
const char* atom_tp = NULL;
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTouchParamAtom); i++) {
if (touch_param == kTouchParamAtom[i].tp) {
atom_tp = kTouchParamAtom[i].atom;
break;
}
}
if (!atom_tp)
return -1;
for (int i = 0; i < info->num_classes; i++) {
if (info->classes[i]->type != XIValuatorClass)
continue;
XIValuatorClassInfo* v =
reinterpret_cast<XIValuatorClassInfo*>(info->classes[i]);
const char* atom = XGetAtomName(display, v->label);
if (atom && strcmp(atom, atom_tp) == 0)
return v->number;
}
return -1;
}
// Setup XInput2 select for the GtkWidget.
gboolean GtkWidgetRealizeCallback(GSignalInvocationHint* hint, guint nparams,
const GValue* pvalues, gpointer data) {
GtkWidget* widget = GTK_WIDGET(g_value_get_object(pvalues));
GdkWindow* window = widget->window;
views::TouchFactory* factory = static_cast<views::TouchFactory*>(data);
if (GDK_WINDOW_TYPE(window) != GDK_WINDOW_TOPLEVEL &&
GDK_WINDOW_TYPE(window) != GDK_WINDOW_CHILD &&
GDK_WINDOW_TYPE(window) != GDK_WINDOW_DIALOG)
return true;
factory->SetupXI2ForXWindow(GDK_WINDOW_XID(window));
return true;
}
// We need to capture all the GDK windows that get created, and start
// listening for XInput2 events. So we setup a callback to the 'realize'
// signal for GTK+ widgets, so that whenever the signal triggers for any
// GtkWidget, which means the GtkWidget should now have a GdkWindow, we can
// setup XInput2 events for the GdkWindow.
guint realize_signal_id = 0;
guint realize_hook_id = 0;
void SetupGtkWidgetRealizeNotifier(views::TouchFactory* factory) {
gpointer klass = g_type_class_ref(GTK_TYPE_WIDGET);
g_signal_parse_name("realize", GTK_TYPE_WIDGET,
&realize_signal_id, NULL, FALSE);
realize_hook_id = g_signal_add_emission_hook(realize_signal_id, 0,
GtkWidgetRealizeCallback, static_cast<gpointer>(factory), NULL);
g_type_class_unref(klass);
}
void RemoveGtkWidgetRealizeNotifier() {
if (realize_signal_id != 0)
g_signal_remove_emission_hook(realize_signal_id, realize_hook_id);
realize_signal_id = 0;
realize_hook_id = 0;
}
} // namespace
namespace views {
// static
TouchFactory* TouchFactory::GetInstance() {
return Singleton<TouchFactory>::get();
}
TouchFactory::TouchFactory()
: is_cursor_visible_(true),
cursor_timer_(),
pointer_device_lookup_(),
touch_device_list_() {
char nodata[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
XColor black;
black.red = black.green = black.blue = 0;
Display* display = ui::GetXDisplay();
Pixmap blank = XCreateBitmapFromData(display, ui::GetX11RootWindow(),
nodata, 8, 8);
invisible_cursor_ = XCreatePixmapCursor(display, blank, blank,
&black, &black, 0, 0);
arrow_cursor_ = XCreateFontCursor(display, XC_arrow);
SetCursorVisible(false, false);
UpdateDeviceList(display);
// TODO(sad): Here, we only setup so that the X windows created by GTK+ are
// setup for XInput2 events. We need a way to listen for XInput2 events for X
// windows created by other means (e.g. for context menus).
SetupGtkWidgetRealizeNotifier(this);
// Make sure the list of devices is kept up-to-date by listening for
// XI_HierarchyChanged event on the root window.
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_HierarchyChanged);
XIEventMask evmask;
evmask.deviceid = XIAllDevices;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
XISelectEvents(display, ui::GetX11RootWindow(), &evmask, 1);
}
TouchFactory::~TouchFactory() {
SetCursorVisible(true, false);
Display* display = ui::GetXDisplay();
XFreeCursor(display, invisible_cursor_);
XFreeCursor(display, arrow_cursor_);
RemoveGtkWidgetRealizeNotifier();
}
void TouchFactory::UpdateDeviceList(Display* display) {
// Detect touch devices.
// NOTE: The new API for retrieving the list of devices (XIQueryDevice) does
// not provide enough information to detect a touch device. As a result, the
// old version of query function (XListInputDevices) is used instead.
// If XInput2 is not supported, this will return null (with count of -1) so
// we assume there cannot be any touch devices.
int count = 0;
touch_device_lookup_.reset();
touch_device_list_.clear();
XDeviceInfo* devlist = XListInputDevices(display, &count);
for (int i = 0; i < count; i++) {
const char* devtype = XGetAtomName(display, devlist[i].type);
if (devtype && !strcmp(devtype, XI_TOUCHSCREEN)) {
touch_device_lookup_[devlist[i].id] = true;
touch_device_list_.push_back(devlist[i].id);
}
}
if (devlist)
XFreeDeviceList(devlist);
// Instead of asking X for the list of devices all the time, let's maintain a
// list of pointer devices we care about.
// It should not be necessary to select for slave devices. XInput2 provides
// enough information to the event callback to decide which slave device
// triggered the event, thus decide whether the 'pointer event' is a
// 'mouse event' or a 'touch event'.
// However, on some desktops, some events from a master pointer are
// not delivered to the client. So we select for slave devices instead.
// If the touch device has 'GrabDevice' set and 'SendCoreEvents' unset (which
// is possible), then the device is detected as a floating device, and a
// floating device is not connected to a master device. So it is necessary to
// also select on the floating devices.
pointer_device_lookup_.reset();
XIDeviceInfo* devices = XIQueryDevice(display, XIAllDevices, &count);
for (int i = 0; i < count; i++) {
XIDeviceInfo* devinfo = devices + i;
if (devinfo->use == XIFloatingSlave || devinfo->use == XISlavePointer) {
pointer_device_lookup_[devinfo->deviceid] = true;
}
}
XIFreeDeviceInfo(devices);
SetupValuator();
}
bool TouchFactory::ShouldProcessXI2Event(XEvent* xev) {
DCHECK_EQ(GenericEvent, xev->type);
XGenericEventCookie* cookie = &xev->xcookie;
if (cookie->evtype != XI_ButtonPress &&
cookie->evtype != XI_ButtonRelease &&
cookie->evtype != XI_Motion)
return true;
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data);
return pointer_device_lookup_[xiev->sourceid];
}
void TouchFactory::SetupXI2ForXWindow(Window window) {
// Setup mask for mouse events. It is possible that a device is loaded/plugged
// in after we have setup XInput2 on a window. In such cases, we need to
// either resetup XInput2 for the window, so that we get events from the new
// device, or we need to listen to events from all devices, and then filter
// the events from uninteresting devices. We do the latter because that's
// simpler.
Display* display = ui::GetXDisplay();
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_ButtonPress);
XISetMask(mask, XI_ButtonRelease);
XISetMask(mask, XI_Motion);
XIEventMask evmask;
evmask.deviceid = XIAllDevices;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
XISelectEvents(display, window, &evmask, 1);
XFlush(display);
}
void TouchFactory::SetTouchDeviceList(
const std::vector<unsigned int>& devices) {
touch_device_lookup_.reset();
touch_device_list_.clear();
for (std::vector<unsigned int>::const_iterator iter = devices.begin();
iter != devices.end(); ++iter) {
DCHECK(*iter < touch_device_lookup_.size());
touch_device_lookup_[*iter] = true;
touch_device_list_.push_back(*iter);
}
SetupValuator();
}
bool TouchFactory::IsTouchDevice(unsigned deviceid) const {
return deviceid < touch_device_lookup_.size() ?
touch_device_lookup_[deviceid] : false;
}
bool TouchFactory::GrabTouchDevices(Display* display, ::Window window) {
if (touch_device_list_.empty())
return true;
unsigned char mask[XIMaskLen(XI_LASTEVENT)];
bool success = true;
memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_ButtonPress);
XISetMask(mask, XI_ButtonRelease);
XISetMask(mask, XI_Motion);
XIEventMask evmask;
evmask.mask_len = sizeof(mask);
evmask.mask = mask;
for (std::vector<int>::const_iterator iter =
touch_device_list_.begin();
iter != touch_device_list_.end(); ++iter) {
evmask.deviceid = *iter;
Status status = XIGrabDevice(display, *iter, window, CurrentTime, None,
GrabModeAsync, GrabModeAsync, False, &evmask);
success = success && status == GrabSuccess;
}
return success;
}
bool TouchFactory::UngrabTouchDevices(Display* display) {
bool success = true;
for (std::vector<int>::const_iterator iter =
touch_device_list_.begin();
iter != touch_device_list_.end(); ++iter) {
Status status = XIUngrabDevice(display, *iter, CurrentTime);
success = success && status == GrabSuccess;
}
return success;
}
void TouchFactory::SetCursorVisible(bool show, bool start_timer) {
// The cursor is going to be shown. Reset the timer for hiding it.
if (show && start_timer) {
cursor_timer_.Stop();
cursor_timer_.Start(base::TimeDelta::FromSeconds(kCursorIdleSeconds),
this, &TouchFactory::HideCursorForInactivity);
} else {
cursor_timer_.Stop();
}
if (show == is_cursor_visible_)
return;
is_cursor_visible_ = show;
Display* display = ui::GetXDisplay();
Window window = DefaultRootWindow(display);
if (is_cursor_visible_) {
XDefineCursor(display, window, arrow_cursor_);
} else {
XDefineCursor(display, window, invisible_cursor_);
}
}
void TouchFactory::SetupValuator() {
memset(valuator_lookup_, -1, sizeof(valuator_lookup_));
Display* display = ui::GetXDisplay();
int ndevice;
XIDeviceInfo* info_list = XIQueryDevice(display, XIAllDevices, &ndevice);
for (int i = 0; i < ndevice; i++) {
XIDeviceInfo* info = info_list + i;
if (!IsTouchDevice(info->deviceid))
continue;
for (int i = 0; i < TP_LAST_ENTRY; i++) {
TouchParam tp = static_cast<TouchParam>(i);
valuator_lookup_[info->deviceid][i] = FindTPValuator(display, info, tp);
}
}
if (info_list)
XIFreeDeviceInfo(info_list);
}
bool TouchFactory::ExtractTouchParam(const XEvent& xev,
TouchParam tp,
float* value) {
XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(xev.xcookie.data);
if (xiev->sourceid >= kMaxDeviceNum)
return false;
int v = valuator_lookup_[xiev->sourceid][tp];
if (v >= 0 && XIMaskIsSet(xiev->valuators.mask, v)) {
*value = xiev->valuators.values[v];
return true;
}
return false;
}
} // namespace views
<|endoftext|>
|
<commit_before>/* String is constructed with these four characters:
* w - represents wolf
* s - represents sheep
* . - represents empty space
* # - represents fence
* Write out how many sheeps have been slaughtered.
*
* For example:
* #.vov#o.o#.v#o.v.o#v
* Only two sheeps in between fence #o.o# will survive.
*/
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <vector>
using namespace std;
int howManySheepsHaveBeenEaten();
string genTerrain();
int roll(int min, int max);
void setChar(int num);
int loopBetweenFences(size_t, size_t, const string& );
string terrain;
int main( )
{
srand(time(NULL));
genTerrain();
cout << "Slaughtered: " << howManySheepsHaveBeenEaten() << endl;
return 0;
}
/* Idea:
* 1. Find postion of every fence - #. Store it in fence_pos_vector
* 2. Loop through every char in string from begining to next occurance
* of fence - #.
* 3. If there is one or more wolf - w, count the number of slaughtered
* sheeps.
*/
int howManySheepsHaveBeenEaten()
{
int num_of_dead_sheeps=0;
size_t fence_pos=0;
std::vector<size_t> fence_pos_vector;
if (terrain.find("#", fence_pos) != -1){
for (int i = 0; i < terrain.length(); i++) {
if (i == 0) {
fence_pos = terrain.find("#",0);
fence_pos_vector.push_back(fence_pos);
i = fence_pos;
}
else {
if (terrain.find("#", fence_pos+1) != -1){
fence_pos = terrain.find("#", fence_pos+1);
fence_pos_vector.push_back(fence_pos);
i = fence_pos;
}
else break;
}
}
}
else {
fence_pos_vector.at(0) = 0;
}
for (int i = 0; i < fence_pos_vector.size(); i++) {
if (i == 0)
loopBetweenFences(i, fence_pos_vector.at(i), terrain);
else
loopBetweenFences(fence_pos_vector.at(i-1),
fence_pos_vector.at(i), terrain);
// Here is missing one more call to loopBetweenFences cuz we
// will miss .sw#.sw#.sw last sheep
}
return num_of_dead_sheeps;
}
int loopBetweenFences(size_t start, size_t finish, const string& terrain)
{
int num_of_dead_sheeps = 0;
string temp;
size_t sheep_pos=0;
vector<size_t> sheep_pos_vec;
sheep_pos_vec.clear();
temp = terrain.substr(start, finish);
// if distance between fence is bigger then 1
if ( temp.length() > 1)
// if there is at least one wolf
if (temp.find("w") != -1 ){
for (int i = 0; i < temp.length(); i++) {
if (temp.find("s",sheep_pos) != -1){
if (i == 0){
sheep_pos = temp.find("s",0);
sheep_pos_vec.push_back(sheep_pos);
i = sheep_pos;
num_of_dead_sheeps++;
}
else {
if (temp.find("s",sheep_pos+1) != -1){
sheep_pos = terrain.find("s", sheep_pos+1);
sheep_pos_vec.push_back(sheep_pos);
i = sheep_pos;
num_of_dead_sheeps++;
}
}
}
}
}
// cout << "sheep pos vec: " << sheep_pos_vec.size() << endl;
cout << "num of dead sheeps: " << num_of_dead_sheeps << endl;
return num_of_dead_sheeps;
}
/* Idea, genarate a RAND number between 1 - 4
* if 0 append . to terrain
* if 1 append w to terrain
* if 2 append s to terrain
* if 3 append # to terrain
*/
string genTerrain()
{
for (int i = 0; i < 2; i++) {
int first = roll(0,3);
setChar(first);
int second = roll(0,3);
while (second == first){
second = roll(0,3);
if (second != first) break;
}
setChar(second);
int third = roll(0,3);
while ((third == first) || (third == second)){
third = roll(0,3);
if ((third != first) && (third != second)) break;
}
setChar(third);
int fourth = roll(0,3);
while (1){
fourth = roll(0,3);
if ((fourth != first) && (fourth != second) && (fourth != third)) break;
}
setChar(fourth);
}
cout << terrain << endl;
return terrain;
}
void setChar(int num){
if (num == 0) terrain.append(".");
if (num == 1) terrain.append("w");
if (num == 2) terrain.append("s");
if (num == 3) terrain.append("#");
}
int roll(int min, int max)
{
// x is in [0,1[
double x = rand()/static_cast<double>(RAND_MAX);
// [0,1[ * (max - min) + min is in [min,max[
int that = min + static_cast<int>( x * (max - min + 1) );
return that;
}
<commit_msg>ugly but working version<commit_after>/* String is constructed with these four characters:
* w - represents wolf
* s - represents sheep
* . - represents empty space
* # - represents fence
* Write out how many sheeps have been slaughtered.
*
* For example:
* #.vov#o.o#.v#o.v.o#v
* Only two sheeps in between fence #o.o# will survive.
*/
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <vector>
using namespace std;
int howManySheepsHaveBeenEaten();
string genTerrain();
int roll(int min, int max);
void setChar(int num);
int loopBetweenFences(size_t, size_t, const string& );
string terrain;
int main(int argc, const char *argv[])
{
srand(time(NULL));
if (argc > 1)
terrain = argv[1];
else
genTerrain();
cout << "Slaughtered: " << howManySheepsHaveBeenEaten() << endl;
return 0;
}
/* Idea:
* 1. Find postion of every fence - #. Store it in fence_pos_vector
* 2. Loop through every char in string from begining to next occurance
* of fence - #.
* 3. If there is one or more wolf - w, count the number of slaughtered
* sheeps.
*/
int howManySheepsHaveBeenEaten()
{
int num_of_dead_sheeps=0;
size_t fence_pos=0;
std::vector<size_t> fence_pos_vector;
if (terrain.find("#", fence_pos) != -1){
for (int i = 0; i < terrain.length(); i++) {
if (i == 0) {
fence_pos = terrain.find("#",0);
fence_pos_vector.push_back(fence_pos);
i = fence_pos;
}
else {
if (terrain.find("#", fence_pos+1) != -1){
fence_pos = terrain.find("#", fence_pos+1);
fence_pos_vector.push_back(fence_pos);
i = fence_pos;
}
else break;
}
}
}
else {
fence_pos_vector.at(0) = 0;
}
for (int i = 0; i < fence_pos_vector.size(); i++) {
if (i == 0)
loopBetweenFences(i, fence_pos_vector.at(i), terrain);
// For not missing last sheep in this example: .sw#.sw#.sw
else if (i == (fence_pos_vector.size() - 1)){
loopBetweenFences(fence_pos_vector.at(i-1),
fence_pos_vector.at(i) - fence_pos_vector.at(i-1),
terrain);
loopBetweenFences(fence_pos_vector.at(i), terrain.size(), terrain);
}
else
loopBetweenFences(fence_pos_vector.at(i-1),
fence_pos_vector.at(i) - fence_pos_vector.at(i-1),
terrain);
}
return num_of_dead_sheeps;
}
int loopBetweenFences(size_t start, size_t count, const string& terrain)
{
int num_of_dead_sheeps = 0, num_of_fences = 0;
string temp;
size_t sheep_pos=0;
vector<size_t> sheep_pos_vec;
sheep_pos_vec.clear();
temp = terrain.substr(start, count);
num_of_fences++;
cout << "fence(" << num_of_fences << "): " << temp << endl;
// if distance between fence is bigger then 1
if ( temp.length() > 1)
// if there is at least one wolf
if (temp.find("w") != -1 ){
for (int i = 0; i < temp.length(); i++) {
if (temp.find("s",sheep_pos) != -1){
if (i == 0){
sheep_pos = temp.find("s",0);
sheep_pos_vec.push_back(sheep_pos);
i = sheep_pos;
num_of_dead_sheeps++;
}
else {
if (temp.find("s",sheep_pos+1) != -1){
sheep_pos = temp.find("s", sheep_pos+1);
sheep_pos_vec.push_back(sheep_pos);
i = sheep_pos;
num_of_dead_sheeps++;
}
else break;
}
}
}
}
// cout << "sheep pos vec: " << sheep_pos_vec.size() << endl;
cout << "num of dead sheeps: " << num_of_dead_sheeps << endl;
return num_of_dead_sheeps;
}
/* Idea, genarate a RAND number between 1 - 4
* if 0 append . to terrain
* if 1 append w to terrain
* if 2 append s to terrain
* if 3 append # to terrain
*/
string genTerrain()
{
for (int i = 0; i < 2; i++) {
int first = roll(0,3);
setChar(first);
int second = roll(0,3);
while (second == first){
second = roll(0,3);
if (second != first) break;
}
setChar(second);
int third = roll(0,3);
while ((third == first) || (third == second)){
third = roll(0,3);
if ((third != first) && (third != second)) break;
}
setChar(third);
int fourth = roll(0,3);
while (1){
fourth = roll(0,3);
if ((fourth != first) && (fourth != second) && (fourth != third)) break;
}
setChar(fourth);
}
cout << terrain << endl;
return terrain;
}
void setChar(int num){
if (num == 0) terrain.append(".");
if (num == 1) terrain.append("w");
if (num == 2) terrain.append("s");
if (num == 3) terrain.append("#");
}
int roll(int min, int max)
{
// x is in [0,1[
double x = rand()/static_cast<double>(RAND_MAX);
// [0,1[ * (max - min) + min is in [min,max[
int that = min + static_cast<int>( x * (max - min + 1) );
return that;
}
<|endoftext|>
|
<commit_before>#include "PidProbabilityMapper.h"
#include "PidPhaseSpace.h"
#include "TSF/FitRunner.h"
#include "TH1D.h"
PidProbabilityMapper::PidProbabilityMapper( XmlConfig * _cfg, string _nodePath ) : HistoAnalyzer( _cfg, _nodePath ){
logger->setClassSpace( "PidProbabilityMapper" );
// set up the binning
binsPt = unique_ptr<HistoBins>( new HistoBins( cfg, nodePath + "PSBinning.pt" ) );
binsEta = unique_ptr<HistoBins>( new HistoBins( cfg, nodePath + "PSBinning.eta" ) );
binsCharge = unique_ptr<HistoBins>( new HistoBins( cfg, nodePath + "PSBinning.charge" ) );
}
PidProbabilityMapper::~PidProbabilityMapper(){
}
double PidProbabilityMapper::evaluateGauss( double x, double y, double m, double s ){
return (y / (s *TMath::Sqrt( 2 * 3.1415926 ) )) * TMath::Exp( -(x - m)*( x - m ) / ( 2 * s*s ) );
}
map<string, double> PidProbabilityMapper::pidWeights( int charge, int iCen, double pt, double eta, double zb, double zd ){
map< string, double > weights;
if ( TMath::Abs(charge) != 1 ){
logger->error( __FUNCTION__ ) << "charge zero plc" << endl;
return weights;
}
logger->debug( __FUNCTION__ ) << endl;
int iPt = binsPt->findBin( pt );
int iEta = binsEta->findBin( TMath::Abs(eta) );
if ( iPt < 0 || iEta < 0 )
return weights;
logger->debug( __FUNCTION__ ) << "pt Bin : " << iPt << ", eta Bin : " << iEta << endl;
vector<double> sigmas;
vector<double> mus;
vector<double> yields;
string model = "zb";
double eVal = zd;
if ( "zb" == model )
eVal = zb;
for ( string plc : PidPhaseSpace::species ){
string name = TSF::FitRunner::sigmaName(plc, iCen, charge, iEta);
string fName = plc + "_" + model + "Sigma/" + name;
TH1D * h = ( TH1D * )inFile->Get( fName.c_str() );
if ( !h ){
logger->error( __FUNCTION__ ) << fName << " not found " << endl;
return weights;
}
sigmas.push_back( h->GetBinContent( iPt+1 ) );
name = TSF::FitRunner::muName(plc, iCen, charge, iEta);
fName = plc + "_" + model + "Mu/" + name;
h = ( TH1D * )inFile->Get( fName.c_str() );
mus.push_back( h->GetBinContent( iPt+1 ) );
name = TSF::FitRunner::yieldName(plc, iCen, charge, iEta);
fName = plc + "_yield/" + name;
h = ( TH1D * )inFile->Get( fName.c_str() );
yields.push_back( h->GetBinContent( iPt+1 ) );
}
logger->debug( __FUNCTION__ ) << "parameters loaded" << endl;
double total = 0.0;
int i = 0;
for ( string plc : PidPhaseSpace::species ){
double v = evaluateGauss( eVal, yields[ i ], mus[ i ], sigmas[ i ] );
if ( (eVal - mus[ i ]) / sigmas[ i ] > 8 )
v = 0;
total += v;
weights[ plc ] = v;
//total += yields[ i ];
//weights[ plc ] = yields[ i ];
i++;
}
// normalize
for ( string plc : PidPhaseSpace::species ){
if ( total > 0 )
weights[ plc ] = weights[ plc ] / total;
else
weights[ plc ] = 0;
logger->debug(__FUNCTION__) << "weight[ " << plc << " ] = " << weights[ plc ] << endl;
}
return weights;
}
<commit_msg>set pid mapper to use yield only<commit_after>#include "PidProbabilityMapper.h"
#include "PidPhaseSpace.h"
#include "TSF/FitRunner.h"
#include "TH1D.h"
PidProbabilityMapper::PidProbabilityMapper( XmlConfig * _cfg, string _nodePath ) : HistoAnalyzer( _cfg, _nodePath ){
logger->setClassSpace( "PidProbabilityMapper" );
// set up the binning
binsPt = unique_ptr<HistoBins>( new HistoBins( cfg, nodePath + "PSBinning.pt" ) );
binsEta = unique_ptr<HistoBins>( new HistoBins( cfg, nodePath + "PSBinning.eta" ) );
binsCharge = unique_ptr<HistoBins>( new HistoBins( cfg, nodePath + "PSBinning.charge" ) );
}
PidProbabilityMapper::~PidProbabilityMapper(){
}
double PidProbabilityMapper::evaluateGauss( double x, double y, double m, double s ){
return (y / (s *TMath::Sqrt( 2 * 3.1415926 ) )) * TMath::Exp( -(x - m)*( x - m ) / ( 2 * s*s ) );
}
map<string, double> PidProbabilityMapper::pidWeights( int charge, int iCen, double pt, double eta, double zb, double zd ){
map< string, double > weights;
if ( TMath::Abs(charge) != 1 ){
logger->error( __FUNCTION__ ) << "charge zero plc" << endl;
return weights;
}
logger->debug( __FUNCTION__ ) << endl;
int iPt = binsPt->findBin( pt );
int iEta = binsEta->findBin( TMath::Abs(eta) );
if ( iPt < 0 || iEta < 0 )
return weights;
logger->debug( __FUNCTION__ ) << "pt Bin : " << iPt << ", eta Bin : " << iEta << endl;
vector<double> sigmas;
vector<double> mus;
vector<double> yields;
string model = "zb";
double eVal = zd;
if ( "zb" == model )
eVal = zb;
for ( string plc : PidPhaseSpace::species ){
string name = TSF::FitRunner::sigmaName(plc, iCen, charge, iEta);
string fName = plc + "_" + model + "Sigma/" + name;
TH1D * h = ( TH1D * )inFile->Get( fName.c_str() );
if ( !h ){
logger->error( __FUNCTION__ ) << fName << " not found " << endl;
return weights;
}
sigmas.push_back( h->GetBinContent( iPt+1 ) );
name = TSF::FitRunner::muName(plc, iCen, charge, iEta);
fName = plc + "_" + model + "Mu/" + name;
h = ( TH1D * )inFile->Get( fName.c_str() );
mus.push_back( h->GetBinContent( iPt+1 ) );
name = TSF::FitRunner::yieldName(plc, iCen, charge, iEta);
fName = plc + "_yield/" + name;
h = ( TH1D * )inFile->Get( fName.c_str() );
yields.push_back( h->GetBinContent( iPt+1 ) );
}
logger->debug( __FUNCTION__ ) << "parameters loaded" << endl;
double total = 0.0;
int i = 0;
for ( string plc : PidPhaseSpace::species ){
/*
double v = evaluateGauss( eVal, yields[ i ], mus[ i ], sigmas[ i ] );
if ( (eVal - mus[ i ]) / sigmas[ i ] > 8 )
v = 0;
total += v;
weights[ plc ] = v;*/
total += yields[ i ];
weights[ plc ] = yields[ i ];
i++;
}
// normalize
for ( string plc : PidPhaseSpace::species ){
if ( total > 0 )
weights[ plc ] = weights[ plc ] / total;
else
weights[ plc ] = 0;
logger->debug(__FUNCTION__) << "weight[ " << plc << " ] = " << weights[ plc ] << endl;
}
return weights;
}
<|endoftext|>
|
<commit_before>// -*- c++ -*-
/*=========================================================================
Program: Visualization Toolkit
Module: SLACParticleReader.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.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2009 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkCompositeDataGeometryFilter.h"
#include "vtkInformation.h"
#include "vtkLookupTable.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSLACParticleReader.h"
#include "vtkSLACReader.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTestUtilities.h"
#include "vtkSmartPointer.h"
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
#include <vtksys/ios/sstream>
int SLACParticleReader(int argc, char *argv[])
{
char *meshFileName = vtkTestUtilities::ExpandDataFileName(argc, argv,
"Data/SLAC/pic-example/mesh.ncdf");
char *modeFileNamePattern = vtkTestUtilities::ExpandDataFileName(argc, argv,
"Data/SLAC/pic-example/fields_%d.mod");
char *particleFileName = vtkTestUtilities::ExpandDataFileName(argc, argv,
"Data/SLAC/pic-example/particles_5.ncdf");
// Set up mesh reader.
VTK_CREATE(vtkSLACReader, meshReader);
meshReader->SetMeshFileName(meshFileName);
char *modeFileName = new char[strlen(modeFileNamePattern + 10)];
for (int i = 0; i < 9; i++)
{
sprintf(modeFileName, modeFileNamePattern, i);
meshReader->AddModeFileName(modeFileName);
}
delete[] modeFileName;
meshReader->ReadInternalVolumeOn();
meshReader->ReadExternalSurfaceOff();
meshReader->ReadMidpointsOff();
// Extract geometry that we can render.
VTK_CREATE(vtkCompositeDataGeometryFilter, geometry);
geometry->SetInputConnection(meshReader->GetOutputPort());
// Set up particle reader.
VTK_CREATE(vtkSLACParticleReader, particleReader);
particleReader->SetFileName(particleFileName);
// Set up rendering stuff.
VTK_CREATE(vtkPolyDataMapper, meshMapper);
meshMapper->SetInputConnection(geometry->GetOutputPort());
meshMapper->SetScalarModeToUsePointFieldData();
meshMapper->ColorByArrayComponent("efield", 2);
meshMapper->UseLookupTableScalarRangeOff();
meshMapper->SetScalarRange(1.0, 1e+05);
VTK_CREATE(vtkLookupTable, lut);
lut->SetHueRange(0.66667, 0.0);
lut->SetScaleToLog10();
meshMapper->SetLookupTable(lut);
VTK_CREATE(vtkActor, meshActor);
meshActor->SetMapper(meshMapper);
meshActor->GetProperty()->FrontfaceCullingOn();
VTK_CREATE(vtkPolyDataMapper, particleMapper);
particleMapper->SetInputConnection(particleReader->GetOutputPort());
particleMapper->ScalarVisibilityOff();
VTK_CREATE(vtkActor, particleActor);
particleActor->SetMapper(particleMapper);
VTK_CREATE(vtkRenderer, renderer);
renderer->AddActor(meshActor);
renderer->AddActor(particleActor);
vtkCamera *camera = renderer->GetActiveCamera();
camera->SetPosition(-0.2, 0.05, 0.0);
camera->SetFocalPoint(0.0, 0.05, 0.0);
camera->SetViewUp(0.0, 1.0, 0.0);
VTK_CREATE(vtkRenderWindow, renwin);
renwin->SetSize(300, 200);
renwin->AddRenderer(renderer);
VTK_CREATE(vtkRenderWindowInteractor, iren);
iren->SetRenderWindow(renwin);
renwin->Render();
double time
= particleReader->GetOutput()->GetInformation()->Get(vtkDataObject::DATA_TIME_STEPS())[0];
cout << "Time in particle reader: " << time << endl;
// Change the time to test the time step field load and to have the field
// match the particles in time.
vtkStreamingDemandDrivenPipeline *sdd
= vtkStreamingDemandDrivenPipeline::SafeDownCast(geometry->GetExecutive());
sdd->SetUpdateTimeStep(0, time);
renwin->Render();
// Do the test comparison.
int retVal = vtkRegressionTestImage(renwin);
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
retVal = vtkRegressionTester::PASSED;
}
return (retVal == vtkRegressionTester::PASSED) ? 0 : 1;
}
<commit_msg>BUG: Misplaced parenthesis caused a char array to be 20 shorter than it should be and guaranteed overflow.<commit_after>// -*- c++ -*-
/*=========================================================================
Program: Visualization Toolkit
Module: SLACParticleReader.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.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2009 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkCompositeDataGeometryFilter.h"
#include "vtkInformation.h"
#include "vtkLookupTable.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSLACParticleReader.h"
#include "vtkSLACReader.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTestUtilities.h"
#include "vtkSmartPointer.h"
#define VTK_CREATE(type, name) \
vtkSmartPointer<type> name = vtkSmartPointer<type>::New()
#include <vtksys/ios/sstream>
int SLACParticleReader(int argc, char *argv[])
{
char *meshFileName = vtkTestUtilities::ExpandDataFileName(argc, argv,
"Data/SLAC/pic-example/mesh.ncdf");
char *modeFileNamePattern = vtkTestUtilities::ExpandDataFileName(argc, argv,
"Data/SLAC/pic-example/fields_%d.mod");
char *particleFileName = vtkTestUtilities::ExpandDataFileName(argc, argv,
"Data/SLAC/pic-example/particles_5.ncdf");
// Set up mesh reader.
VTK_CREATE(vtkSLACReader, meshReader);
meshReader->SetMeshFileName(meshFileName);
char *modeFileName = new char[strlen(modeFileNamePattern) + 10];
for (int i = 0; i < 9; i++)
{
sprintf(modeFileName, modeFileNamePattern, i);
meshReader->AddModeFileName(modeFileName);
}
delete[] modeFileName;
meshReader->ReadInternalVolumeOn();
meshReader->ReadExternalSurfaceOff();
meshReader->ReadMidpointsOff();
// Extract geometry that we can render.
VTK_CREATE(vtkCompositeDataGeometryFilter, geometry);
geometry->SetInputConnection(meshReader->GetOutputPort());
// Set up particle reader.
VTK_CREATE(vtkSLACParticleReader, particleReader);
particleReader->SetFileName(particleFileName);
// Set up rendering stuff.
VTK_CREATE(vtkPolyDataMapper, meshMapper);
meshMapper->SetInputConnection(geometry->GetOutputPort());
meshMapper->SetScalarModeToUsePointFieldData();
meshMapper->ColorByArrayComponent("efield", 2);
meshMapper->UseLookupTableScalarRangeOff();
meshMapper->SetScalarRange(1.0, 1e+05);
VTK_CREATE(vtkLookupTable, lut);
lut->SetHueRange(0.66667, 0.0);
lut->SetScaleToLog10();
meshMapper->SetLookupTable(lut);
VTK_CREATE(vtkActor, meshActor);
meshActor->SetMapper(meshMapper);
meshActor->GetProperty()->FrontfaceCullingOn();
VTK_CREATE(vtkPolyDataMapper, particleMapper);
particleMapper->SetInputConnection(particleReader->GetOutputPort());
particleMapper->ScalarVisibilityOff();
VTK_CREATE(vtkActor, particleActor);
particleActor->SetMapper(particleMapper);
VTK_CREATE(vtkRenderer, renderer);
renderer->AddActor(meshActor);
renderer->AddActor(particleActor);
vtkCamera *camera = renderer->GetActiveCamera();
camera->SetPosition(-0.2, 0.05, 0.0);
camera->SetFocalPoint(0.0, 0.05, 0.0);
camera->SetViewUp(0.0, 1.0, 0.0);
VTK_CREATE(vtkRenderWindow, renwin);
renwin->SetSize(300, 200);
renwin->AddRenderer(renderer);
VTK_CREATE(vtkRenderWindowInteractor, iren);
iren->SetRenderWindow(renwin);
renwin->Render();
double time
= particleReader->GetOutput()->GetInformation()->Get(vtkDataObject::DATA_TIME_STEPS())[0];
cout << "Time in particle reader: " << time << endl;
// Change the time to test the time step field load and to have the field
// match the particles in time.
vtkStreamingDemandDrivenPipeline *sdd
= vtkStreamingDemandDrivenPipeline::SafeDownCast(geometry->GetExecutive());
sdd->SetUpdateTimeStep(0, time);
renwin->Render();
// Do the test comparison.
int retVal = vtkRegressionTestImage(renwin);
if (retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
retVal = vtkRegressionTester::PASSED;
}
return (retVal == vtkRegressionTester::PASSED) ? 0 : 1;
}
<|endoftext|>
|
<commit_before>#include "shape/compound.h"
#define rb_array_p(x) RB_TYPE_P(x, T_ARRAY)
VALUE sr_cCompound;
SR_SHAPE_GET(Compound, compound)
SR_SHAPE_CHECK(Compound, compound)
bool siren_compound_install()
{
SR_SHAPE_INIT(Compound)
rb_define_method(sr_cCompound, "initialize", RUBY_METHOD_FUNC(siren_compound_init), -1);
rb_define_method(sr_cCompound, "push", RUBY_METHOD_FUNC(siren_compound_push), -1);
rb_define_method(sr_cCompound, "<<", RUBY_METHOD_FUNC(siren_compound_push), -1);
rb_define_method(sr_cCompound, "delete", RUBY_METHOD_FUNC(siren_compound_delete), -1);
return true;
}
VALUE siren_compound_init(int argc, VALUE* argv, VALUE self)
{
VALUE a;
rb_scan_args(argc, argv, "*", &a);
TopoDS_Compound comp;
BRep_Builder B;
B.MakeCompound(comp);
rb_funcall(a, rb_intern("flatten!"), 0);
for (int i = 0; i < RARRAY_LEN(a); i++) {
VALUE item = RARRAY_AREF(a, i);
TopoDS_Shape* shape = siren_shape_get(item);
B.Add(comp, *shape);
}
auto p = siren_shape_get(self);
*p = comp;
return self;
}
VALUE siren_compound_push(int argc, VALUE* argv, VALUE self)
{
VALUE* a;
VALUE len;
rb_scan_args(argc, argv, "*", &a, &len);
TopoDS_Compound comp = siren_compound_get(self);
BRep_Builder B;
for (int i = 0; i < len; i++) {
VALUE arg = *(a + i);
if (rb_array_p(arg)) {
VALUE subary = rb_funcall(arg, rb_intern("flatten"), 0);
for (int j = 0; j < RARRAY_LEN(subary); j++) {
TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(subary, j));
B.Add(comp, *shape);
}
}
else {
TopoDS_Shape* shape = siren_shape_get(arg);
B.Add(comp, *shape);
}
}
return self;
}
VALUE siren_compound_delete(int argc, VALUE* argv, VALUE self)
{
VALUE* a;
VALUE len;
rb_scan_args(argc, argv, "*", &a, &len);
TopoDS_Compound comp = siren_compound_get(self);
BRep_Builder B;
for (int i = 0; i < len; i++) {
VALUE arg = *(a + i);
if (rb_array_p(arg)) {
VALUE subary = rb_funcall(arg, rb_intern("flatten"), 0);
for (int j = 0; j < RARRAY_LEN(subary); j++) {
TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(subary, j));
B.Remove(comp, *shape);
}
}
else {
TopoDS_Shape* shape = siren_shape_get(arg);
B.Remove(comp, *shape);
}
}
return self;
}
<commit_msg>Update Siren::Compound#push method.<commit_after>#include "shape/compound.h"
#define rb_array_p(x) RB_TYPE_P(x, T_ARRAY)
VALUE sr_cCompound;
SR_SHAPE_GET(Compound, compound)
SR_SHAPE_CHECK(Compound, compound)
bool siren_compound_install()
{
SR_SHAPE_INIT(Compound)
rb_define_method(sr_cCompound, "initialize", RUBY_METHOD_FUNC(siren_compound_init), -1);
rb_define_method(sr_cCompound, "push", RUBY_METHOD_FUNC(siren_compound_push), -1);
rb_define_method(sr_cCompound, "<<", RUBY_METHOD_FUNC(siren_compound_push), -1);
rb_define_method(sr_cCompound, "delete", RUBY_METHOD_FUNC(siren_compound_delete), -1);
return true;
}
VALUE siren_compound_init(int argc, VALUE* argv, VALUE self)
{
VALUE a;
rb_scan_args(argc, argv, "*", &a);
TopoDS_Compound comp;
BRep_Builder B;
B.MakeCompound(comp);
VALUE b = rb_funcall(a, rb_intern("flatten"), 0);
for (int i = 0; i < RARRAY_LEN(b); i++) {
TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(b, i));
B.Add(comp, *shape);
}
auto p = siren_shape_get(self);
*p = comp;
return self;
}
VALUE siren_compound_push(int argc, VALUE* argv, VALUE self)
{
VALUE a;
rb_scan_args(argc, argv, "*", &a);
TopoDS_Compound comp = siren_compound_get(self);
BRep_Builder B;
VALUE b = rb_funcall(a, rb_intern("flatten"), 0);
for (int i = 0; i < RARRAY_LEN(b); i++) {
TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(b, i));
B.Add(comp, *shape);
}
return self;
}
VALUE siren_compound_delete(int argc, VALUE* argv, VALUE self)
{
VALUE a;
rb_scan_args(argc, argv, "*", &a);
TopoDS_Compound comp = siren_compound_get(self);
BRep_Builder B;
VALUE b = rb_funcall(a, rb_intern("flatten"), 0);
for (int i = 0; i < RARRAY_LEN(b); i++) {
TopoDS_Shape* shape = siren_shape_get(RARRAY_AREF(b, i));
B.Remove(comp, *shape);
}
return self;
}
<|endoftext|>
|
<commit_before>#ifndef VOXEL_MATH_VECTOR3_H
#define VOXEL_MATH_VECTOR3_H
namespace math
{
template <typename Ty>
struct basic_vector3
{
typedef Ty scalar;
basic_vector3() {}
basic_vector3(const basic_vector3 ©) : x(copy.x), y(copy.y), z(copy.z) {}
basic_vector3(scalar x, scalar y, scalar z) : x(x), y(y), z(z) {}
friend basic_vector3 operator +(const basic_vector3 &a, const basic_vector3 &b)
{ return basic_vector3(a.x+b.x, a.y+b.y, a.z+b.z); }
friend basic_vector3 operator -(const basic_vector3 &a, const basic_vector3 &b)
{ return basic_vector3(a.x-b.x, a.y-b.y, a.z-b.z); }
friend basic_vector3 operator *(const basic_vector3 &a, scalar b)
{ return basic_vector3(a.x*b, a.y*b, a.z*b); }
friend basic_vector3 operator /(const basic_vector3 &a, scalar b)
{ return basic_vector3(a.x/b, a.y/b, a.z/b); }
basic_vector3 &operator +=(const basic_vector3 &b)
{ x+=b.x, y+=b.y, z+=b.z; return *this; }
basic_vector3 &operator -=(const basic_vector3 &b)
{ x-=b.x, y-=b.y, z-=b.z; return *this; }
basic_vector3 &operator *=(scalar b)
{ x*=b, y*=b, z*=b; return *this; }
basic_vector3 &operator /=(scalar b)
{ x/=b, y/=b, z/=b; return *this; }
scalar &operator [](size_t i) { return (&x)[i]; }
scalar operator [](size_t i) const { return (&x)[i]; }
static const basic_vector3 zero()
{ return basic_vector3(0, 0, 0); }
scalar x, y, z;
};
template <typename Ty>
Ty dot(const basic_vector3<Ty> &a, const basic_vector3<Ty> &b)
{ return a.x*b.x + a.y*b.y + a.z*b.z; }
template <typename Ty>
basic_vector3<Ty> cross(const basic_vector3<Ty> &a, const basic_vector3<Ty> &b)
{ return basic_vector3<Ty>(a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x); }
typedef basic_vector3<float> vector3f;
}; // math
#endif // VOXEL_MATH_VECTOR_H
<commit_msg>Potential fix for bad hack in vector class.<commit_after>#ifndef VOXEL_MATH_VECTOR3_H
#define VOXEL_MATH_VECTOR3_H
namespace math
{
template <typename Ty>
struct basic_vector3
{
typedef Ty scalar;
basic_vector3() : x(els[0]), y(els[1]), z(els[2]) {}
basic_vector3(const basic_vector3 ©)
: x(els[0]), y(els[1]), z(els[2]), els{copy.x, copy.y, copy.z} {}
basic_vector3(scalar x, scalar y, scalar z)
: x(els[0]), y(els[1]), z(els[2]), els{x, y, z} {}
friend basic_vector3 operator +(const basic_vector3 &a, const basic_vector3 &b)
{ return basic_vector3(a.x+b.x, a.y+b.y, a.z+b.z); }
friend basic_vector3 operator -(const basic_vector3 &a, const basic_vector3 &b)
{ return basic_vector3(a.x-b.x, a.y-b.y, a.z-b.z); }
friend basic_vector3 operator *(const basic_vector3 &a, scalar b)
{ return basic_vector3(a.x*b, a.y*b, a.z*b); }
friend basic_vector3 operator /(const basic_vector3 &a, scalar b)
{ return basic_vector3(a.x/b, a.y/b, a.z/b); }
basic_vector3 &operator +=(const basic_vector3 &b)
{ x+=b.x, y+=b.y, z+=b.z; return *this; }
basic_vector3 &operator -=(const basic_vector3 &b)
{ x-=b.x, y-=b.y, z-=b.z; return *this; }
basic_vector3 &operator *=(scalar b)
{ x*=b, y*=b, z*=b; return *this; }
basic_vector3 &operator /=(scalar b)
{ x/=b, y/=b, z/=b; return *this; }
scalar &operator [](size_t i) { return (&x)[i]; }
scalar operator [](size_t i) const { return (&x)[i]; }
static const basic_vector3 zero()
{ return basic_vector3(0, 0, 0); }
scalar &x, &y, &z;
private:
scalar els[3];
};
template <typename Ty>
Ty dot(const basic_vector3<Ty> &a, const basic_vector3<Ty> &b)
{ return a.x*b.x + a.y*b.y + a.z*b.z; }
template <typename Ty>
basic_vector3<Ty> cross(const basic_vector3<Ty> &a, const basic_vector3<Ty> &b)
{ return basic_vector3<Ty>(a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x); }
typedef basic_vector3<float> vector3f;
}; // math
#endif // VOXEL_MATH_VECTOR_H
<|endoftext|>
|
<commit_before>/*
-------------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2014-2019 Kim Kulling
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 <cppcore/Container/TArray.h>
#include <cppcore/CPPCoreCommon.h>
#include "gtest/gtest.h"
#include <sstream>
#include <iostream>
using namespace CPPCore;
static const size_t ArraySize = 4;
static const float ArrayData[ ArraySize ] = {
0.0f,
1.0f,
2.0f,
3.0f
};
//-------------------------------------------------------------------------------------------------
/// @class TArrayTest
/// @ingroup UnitTest
///
/// @brief The array tests.
//-------------------------------------------------------------------------------------------------
class TArrayTest : public testing::Test {
protected:
void createArray( const float *pOrig, size_t numItems, TArray<float> &arrayInstance ) {
for ( size_t i=0; i<numItems; ++i ) {
arrayInstance.add( pOrig[ i ] );
}
}
};
TEST_F( TArrayTest, constructTest ) {
TArray<float> arrayInstance;
EXPECT_EQ( true, arrayInstance.isEmpty() );
EXPECT_EQ( 0U, arrayInstance.size() );
EXPECT_EQ( arrayInstance.begin(), arrayInstance.end() );
}
TEST_F( TArrayTest, constructWithSizeTest) {
TArray<float> arrayInstance( 4 );
EXPECT_EQ( 4u, arrayInstance.size() );
}
TEST_F( TArrayTest, addTest) {
TArray<float> arrayInstance;
arrayInstance.add( 0.0f );
arrayInstance.add( 1.0f );
EXPECT_EQ( 2u, arrayInstance.size() );
EXPECT_EQ( 0.0f, arrayInstance[ 0 ] );
EXPECT_EQ( 1.0f, arrayInstance[ 1 ] );
}
TEST_F( TArrayTest, addItemsTest ) {
TArray<float> arrayInstance;
arrayInstance.add( 0.0f );
float data[2] = { 0, 1 };
arrayInstance.add( data, 2 );
EXPECT_EQ( 3u, arrayInstance.size() );
EXPECT_EQ( 0.0f, arrayInstance[ 0 ] );
EXPECT_EQ( 0.0f, arrayInstance[ 1 ] );
EXPECT_EQ( 1.0f, arrayInstance[ 2 ] );
arrayInstance.add( nullptr, 0 );
EXPECT_EQ( 3u, arrayInstance.size() );
}
TEST_F( TArrayTest, accessTest) {
TArray<float> arrayInstance;
arrayInstance.add( 0.0f );
arrayInstance.add( 1.0f );
EXPECT_EQ( 0.0f, arrayInstance[ 0 ] );
EXPECT_EQ( 1.0f, arrayInstance[ 1 ] );
}
TEST_F( TArrayTest, backTest ) {
float item( 0.0f );
TArray<float> arrayInstance;
arrayInstance.add( 1.0f );
item = arrayInstance.back();
EXPECT_FLOAT_EQ( 1.0f, item );
arrayInstance.add( 2.0f );
item = arrayInstance.back();
EXPECT_FLOAT_EQ( 2.0f, item );
}
struct foo {
float m_item;
foo() : m_item( 1.0f ) {}
};
TEST_F( TArrayTest, constBackTest ) {
TArray<foo> fooArrayInstance;
foo foo1;
foo1.m_item = 1.0f;
fooArrayInstance.add( foo1 );
const foo &res1 = fooArrayInstance.back();
EXPECT_FLOAT_EQ( 1.0f, res1.m_item );
foo foo2;
foo2.m_item = 2.0f;
fooArrayInstance.add( foo2 );
const foo &res2 = fooArrayInstance.back();
EXPECT_FLOAT_EQ( 2.0f, res2.m_item );
}
TEST_F( TArrayTest, removeTest) {
TArray<float> arrayInstance;
createArray( ArrayData, ArraySize, arrayInstance );
std::stringstream stream;
static const size_t Size = 3;
arrayInstance.remove( 1 );
EXPECT_EQ( Size, arrayInstance.size() );
float expectedResult[ Size ] = { 0.0f, 2.0f, 3.0f };
bool equal = true;
for ( size_t i=0; i<Size; ++i ) {
if ( arrayInstance[ i ] != expectedResult[ i ] ) {
stream << "error in index " << i << std::endl;
equal = false;
break;
}
}
EXPECT_TRUE( equal ) << stream.str();
}
TEST_F( TArrayTest, removeItTest) {
TArray<float> arrayInstance;
arrayInstance.add( 1.0f );
EXPECT_EQ( 1u, arrayInstance.size() );
TArray<float>::Iterator it = arrayInstance.find( 1.0f );
EXPECT_NE( arrayInstance.end(), it );
arrayInstance.remove( it );
EXPECT_EQ( 0u, arrayInstance.size() );
}
TEST_F( TArrayTest, removeBackTest) {
TArray<float> arrayInstance;
createArray( ArrayData, ArraySize, arrayInstance );
arrayInstance.removeBack();
EXPECT_EQ( 3u, arrayInstance.size() );
EXPECT_EQ( 2.0f, arrayInstance[ 2 ] );
}
TEST_F( TArrayTest, resizeTest ) {
TArray<float> arrayInstance;
EXPECT_EQ( 0u, arrayInstance.size() );
arrayInstance.resize( 5 );
EXPECT_EQ( 5u, arrayInstance.size() );
}
TEST_F( TArrayTest, moveTest ) {
TArray<float> arrayInstance;
arrayInstance.add( 1.0f );
arrayInstance.add( 2.0f );
arrayInstance.add( 3.0f );
arrayInstance.move( 1, 3 );
}
TEST_F( TArrayTest, reserveTest ) {
TArray<float> arrayInstance;
EXPECT_EQ( 0u, arrayInstance.capacity() );
arrayInstance.reserve( 5 );
EXPECT_EQ( 5u, arrayInstance.capacity() );
static const size_t NewSize = 2000;
arrayInstance.reserve(NewSize);
EXPECT_EQ( NewSize, arrayInstance.capacity() );
}
TEST_F( TArrayTest, resize_with_init_Test ) {
TArray<float> arrayInstance;
EXPECT_EQ( 0u, arrayInstance.capacity() );
arrayInstance.resize( 10, 1.0f );
EXPECT_EQ( 10u, arrayInstance.size() );
for ( size_t i = 0; i < 10; ++i ) {
EXPECT_FLOAT_EQ( 1.0f, arrayInstance[ i ] );
}
}
TEST_F( TArrayTest, iterateTest ) {
TArray<float> arrayInstance;
createArray( ArrayData, ArraySize, arrayInstance );
size_t i( 0 );
for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ) {
++i;
}
EXPECT_EQ( i, arrayInstance.size() );
}
TEST_F( TArrayTest, preIncIterateTest ) {
TArray<float> arrayInstance;
createArray( ArrayData, ArraySize, arrayInstance );
bool ok = true;
try {
size_t i( 0 );
for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ) {
float tmp = *it;
EXPECT_EQ( tmp, ArrayData[ i ] );
++i;
}
} catch (...) {
ok = false;
}
EXPECT_TRUE( ok );
}
TEST_F( TArrayTest, postIncIterateTest ) {
TArray<float> arrayInstance;
createArray( ArrayData, ArraySize, arrayInstance );
bool ok = true;
try {
size_t i(0);
for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); it++ ) {
float tmp = *it;
EXPECT_EQ( tmp, ArrayData[ i ] );
++i;
}
} catch (...) {
ok = false;
}
EXPECT_TRUE( ok );
}
TEST_F( TArrayTest, findTest ) {
TArray<float> arrayInstance;
arrayInstance.add( 0.0f );
arrayInstance.add( 1.0f );
arrayInstance.add( 2.0f );
arrayInstance.add( 3.0f );
EXPECT_EQ( 4u, arrayInstance.size() );
TArray<float>::Iterator it = arrayInstance.find( 1.0f );
EXPECT_NE( it, arrayInstance.end() );
EXPECT_EQ( *it, 1.0f );
}
TEST_F( TArrayTest, ContainerClearTest ) {
TArray<float*> arrayInstance;
ContainerClear( arrayInstance );
EXPECT_TRUE( arrayInstance.isEmpty() );
arrayInstance.add( new float( 0.0f ) );
arrayInstance.add( new float( 1.0f ) );
arrayInstance.add( new float( 2.0f ) );
EXPECT_EQ( arrayInstance.size(), 3U );
ContainerClear( arrayInstance );
EXPECT_EQ( arrayInstance.size(), 0U );
EXPECT_TRUE( arrayInstance.isEmpty() );
}
//---------------------------------------------------------------------------------------------
// Crash when iterating an empty array.
//---------------------------------------------------------------------------------------------
TEST_F( TArrayTest, bug_IterateEmptyListTest ) {
TArray<float> arrayInstance;
bool ok = true;
try {
for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it );
} catch ( ... ) {
ok = false;
}
EXPECT_TRUE( ok );
}
//---------------------------------------------------------------------------------------------
// Heap corruption after grow.
//---------------------------------------------------------------------------------------------
TEST_F( TArrayTest, bug_AddHeapCorruptTest ) {
TArray<float> arrayInstance;
for ( size_t i=0; i<50; ++i ) {
arrayInstance.add( ( float ) i );
}
}
<commit_msg>fix broken unittest.<commit_after>/*
-------------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2014-2019 Kim Kulling
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 <cppcore/Container/TArray.h>
#include <cppcore/CPPCoreCommon.h>
#include "gtest/gtest.h"
#include <sstream>
#include <iostream>
using namespace CPPCore;
static const size_t ArraySize = 4;
static const float ArrayData[ ArraySize ] = {
0.0f,
1.0f,
2.0f,
3.0f
};
//-------------------------------------------------------------------------------------------------
/// @class TArrayTest
/// @ingroup UnitTest
///
/// @brief The array tests.
//-------------------------------------------------------------------------------------------------
class TArrayTest : public testing::Test {
protected:
void createArray( const float *pOrig, size_t numItems, TArray<float> &arrayInstance ) {
for ( size_t i=0; i<numItems; ++i ) {
arrayInstance.add( pOrig[ i ] );
}
}
};
TEST_F( TArrayTest, constructTest ) {
TArray<float> arrayInstance;
EXPECT_EQ( true, arrayInstance.isEmpty() );
EXPECT_EQ( 0U, arrayInstance.size() );
EXPECT_EQ( arrayInstance.begin(), arrayInstance.end() );
}
TEST_F( TArrayTest, constructWithSizeTest) {
TArray<float> arrayInstance( 4 );
EXPECT_EQ( 4u, arrayInstance.size() );
}
TEST_F( TArrayTest, addTest) {
TArray<float> arrayInstance;
arrayInstance.add( 0.0f );
arrayInstance.add( 1.0f );
EXPECT_EQ( 2u, arrayInstance.size() );
EXPECT_EQ( 0.0f, arrayInstance[ 0 ] );
EXPECT_EQ( 1.0f, arrayInstance[ 1 ] );
}
TEST_F( TArrayTest, addItemsTest ) {
TArray<float> arrayInstance;
arrayInstance.add( 0.0f );
float data[2] = { 0, 1 };
arrayInstance.add( data, 2 );
EXPECT_EQ( 3u, arrayInstance.size() );
EXPECT_EQ( 0.0f, arrayInstance[ 0 ] );
EXPECT_EQ( 0.0f, arrayInstance[ 1 ] );
EXPECT_EQ( 1.0f, arrayInstance[ 2 ] );
arrayInstance.add( nullptr, 0 );
EXPECT_EQ( 3u, arrayInstance.size() );
}
TEST_F( TArrayTest, accessTest) {
TArray<float> arrayInstance;
arrayInstance.add( 0.0f );
arrayInstance.add( 1.0f );
EXPECT_EQ( 0.0f, arrayInstance[ 0 ] );
EXPECT_EQ( 1.0f, arrayInstance[ 1 ] );
}
TEST_F( TArrayTest, backTest ) {
float item( 0.0f );
TArray<float> arrayInstance;
arrayInstance.add( 1.0f );
item = arrayInstance.back();
EXPECT_FLOAT_EQ( 1.0f, item );
arrayInstance.add( 2.0f );
item = arrayInstance.back();
EXPECT_FLOAT_EQ( 2.0f, item );
}
struct foo {
float m_item;
foo() : m_item( 1.0f ) {}
};
TEST_F( TArrayTest, constBackTest ) {
TArray<foo> fooArrayInstance;
foo foo1;
foo1.m_item = 1.0f;
fooArrayInstance.add( foo1 );
const foo &res1 = fooArrayInstance.back();
EXPECT_FLOAT_EQ( 1.0f, res1.m_item );
foo foo2;
foo2.m_item = 2.0f;
fooArrayInstance.add( foo2 );
const foo &res2 = fooArrayInstance.back();
EXPECT_FLOAT_EQ( 2.0f, res2.m_item );
}
TEST_F( TArrayTest, removeTest) {
TArray<float> arrayInstance;
createArray( ArrayData, ArraySize, arrayInstance );
std::stringstream stream;
static const size_t Size = 3;
arrayInstance.remove( 1 );
EXPECT_EQ( Size, arrayInstance.size() );
float expectedResult[ Size ] = { 0.0f, 2.0f, 3.0f };
bool equal = true;
for ( size_t i=0; i<Size; ++i ) {
if ( arrayInstance[ i ] != expectedResult[ i ] ) {
stream << "error in index " << i << std::endl;
equal = false;
break;
}
}
EXPECT_TRUE( equal ) << stream.str();
}
TEST_F( TArrayTest, removeItTest) {
TArray<float> arrayInstance;
arrayInstance.add( 1.0f );
EXPECT_EQ( 1u, arrayInstance.size() );
TArray<float>::Iterator it = arrayInstance.find( 1.0f );
EXPECT_NE( arrayInstance.end(), it );
arrayInstance.remove( it );
EXPECT_EQ( 0u, arrayInstance.size() );
}
TEST_F( TArrayTest, removeBackTest) {
TArray<float> arrayInstance;
createArray( ArrayData, ArraySize, arrayInstance );
arrayInstance.removeBack();
EXPECT_EQ( 3u, arrayInstance.size() );
EXPECT_EQ( 2.0f, arrayInstance[ 2 ] );
}
TEST_F( TArrayTest, resizeTest ) {
TArray<float> arrayInstance;
EXPECT_EQ( 0u, arrayInstance.size() );
arrayInstance.resize( 5 );
EXPECT_EQ( 5u, arrayInstance.size() );
}
TEST_F( TArrayTest, moveTest ) {
TArray<float> arrayInstance;
arrayInstance.add( 1.0f );
arrayInstance.add( 2.0f );
arrayInstance.add( 3.0f );
arrayInstance.move( 1, 2 );
}
TEST_F( TArrayTest, reserveTest ) {
TArray<float> arrayInstance;
EXPECT_EQ( 0u, arrayInstance.capacity() );
arrayInstance.reserve( 5 );
EXPECT_EQ( 5u, arrayInstance.capacity() );
static const size_t NewSize = 2000;
arrayInstance.reserve(NewSize);
EXPECT_EQ( NewSize, arrayInstance.capacity() );
}
TEST_F( TArrayTest, resize_with_init_Test ) {
TArray<float> arrayInstance;
EXPECT_EQ( 0u, arrayInstance.capacity() );
arrayInstance.resize( 10, 1.0f );
EXPECT_EQ( 10u, arrayInstance.size() );
for ( size_t i = 0; i < 10; ++i ) {
EXPECT_FLOAT_EQ( 1.0f, arrayInstance[ i ] );
}
}
TEST_F( TArrayTest, iterateTest ) {
TArray<float> arrayInstance;
createArray( ArrayData, ArraySize, arrayInstance );
size_t i( 0 );
for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ) {
++i;
}
EXPECT_EQ( i, arrayInstance.size() );
}
TEST_F( TArrayTest, preIncIterateTest ) {
TArray<float> arrayInstance;
createArray( ArrayData, ArraySize, arrayInstance );
bool ok = true;
try {
size_t i( 0 );
for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it ) {
float tmp = *it;
EXPECT_EQ( tmp, ArrayData[ i ] );
++i;
}
} catch (...) {
ok = false;
}
EXPECT_TRUE( ok );
}
TEST_F( TArrayTest, postIncIterateTest ) {
TArray<float> arrayInstance;
createArray( ArrayData, ArraySize, arrayInstance );
bool ok = true;
try {
size_t i(0);
for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); it++ ) {
float tmp = *it;
EXPECT_EQ( tmp, ArrayData[ i ] );
++i;
}
} catch (...) {
ok = false;
}
EXPECT_TRUE( ok );
}
TEST_F( TArrayTest, findTest ) {
TArray<float> arrayInstance;
arrayInstance.add( 0.0f );
arrayInstance.add( 1.0f );
arrayInstance.add( 2.0f );
arrayInstance.add( 3.0f );
EXPECT_EQ( 4u, arrayInstance.size() );
TArray<float>::Iterator it = arrayInstance.find( 1.0f );
EXPECT_NE( it, arrayInstance.end() );
EXPECT_EQ( *it, 1.0f );
}
TEST_F( TArrayTest, ContainerClearTest ) {
TArray<float*> arrayInstance;
ContainerClear( arrayInstance );
EXPECT_TRUE( arrayInstance.isEmpty() );
arrayInstance.add( new float( 0.0f ) );
arrayInstance.add( new float( 1.0f ) );
arrayInstance.add( new float( 2.0f ) );
EXPECT_EQ( arrayInstance.size(), 3U );
ContainerClear( arrayInstance );
EXPECT_EQ( arrayInstance.size(), 0U );
EXPECT_TRUE( arrayInstance.isEmpty() );
}
//---------------------------------------------------------------------------------------------
// Crash when iterating an empty array.
//---------------------------------------------------------------------------------------------
TEST_F( TArrayTest, bug_IterateEmptyListTest ) {
TArray<float> arrayInstance;
bool ok = true;
try {
for( TArray<float>::Iterator it = arrayInstance.begin( ); it != arrayInstance.end( ); ++it );
} catch ( ... ) {
ok = false;
}
EXPECT_TRUE( ok );
}
//---------------------------------------------------------------------------------------------
// Heap corruption after grow.
//---------------------------------------------------------------------------------------------
TEST_F( TArrayTest, bug_AddHeapCorruptTest ) {
TArray<float> arrayInstance;
for ( size_t i=0; i<50; ++i ) {
arrayInstance.add( ( float ) i );
}
}
<|endoftext|>
|
<commit_before><commit_msg>attempt to fix web build<commit_after><|endoftext|>
|
<commit_before>//===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/CGSCCPassManager.h"
#include "llvm/IR/CallSite.h"
using namespace llvm;
namespace llvm {
// Explicit instantiations for the core proxy templates.
template class AllAnalysesOn<LazyCallGraph::SCC>;
template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
LazyCallGraph &, CGSCCUpdateResult &>;
template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
LazyCallGraph::SCC>;
template class InnerAnalysisManagerProxy<FunctionAnalysisManager,
LazyCallGraph::SCC>;
template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
/// Explicitly specialize the pass manager run method to handle call graph
/// updates.
template <>
PreservedAnalyses
PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
CGSCCAnalysisManager &AM,
LazyCallGraph &G, CGSCCUpdateResult &UR) {
PreservedAnalyses PA = PreservedAnalyses::all();
if (DebugLogging)
dbgs() << "Starting CGSCC pass manager run.\n";
// The SCC may be refined while we are running passes over it, so set up
// a pointer that we can update.
LazyCallGraph::SCC *C = &InitialC;
for (auto &Pass : Passes) {
if (DebugLogging)
dbgs() << "Running pass: " << Pass->name() << " on " << *C << "\n";
PreservedAnalyses PassPA = Pass->run(*C, AM, G, UR);
// Update the SCC if necessary.
C = UR.UpdatedC ? UR.UpdatedC : C;
// Check that we didn't miss any update scenario.
assert(!UR.InvalidatedSCCs.count(C) && "Processing an invalid SCC!");
assert(C->begin() != C->end() && "Cannot have an empty SCC!");
// Update the analysis manager as each pass runs and potentially
// invalidates analyses.
AM.invalidate(*C, PassPA);
// Finally, we intersect the final preserved analyses to compute the
// aggregate preserved set for this pass manager.
PA.intersect(std::move(PassPA));
// FIXME: Historically, the pass managers all called the LLVM context's
// yield function here. We don't have a generic way to acquire the
// context and it isn't yet clear what the right pattern is for yielding
// in the new pass manager so it is currently omitted.
// ...getContext().yield();
}
// Invaliadtion was handled after each pass in the above loop for the current
// SCC. Therefore, the remaining analysis results in the AnalysisManager are
// preserved. We mark this with a set so that we don't need to inspect each
// one individually.
PA.preserve<AllAnalysesOn<LazyCallGraph::SCC>>();
if (DebugLogging)
dbgs() << "Finished CGSCC pass manager run.\n";
return PA;
}
} // End llvm namespace
namespace {
/// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
/// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
/// added SCCs.
///
/// The range of new SCCs must be in postorder already. The SCC they were split
/// out of must be provided as \p C. The current node being mutated and
/// triggering updates must be passed as \p N.
///
/// This function returns the SCC containing \p N. This will be either \p C if
/// no new SCCs have been split out, or it will be the new SCC containing \p N.
template <typename SCCRangeT>
LazyCallGraph::SCC *
incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
bool DebugLogging = false) {
typedef LazyCallGraph::SCC SCC;
if (NewSCCRange.begin() == NewSCCRange.end())
return C;
// Invalidate the analyses of the current SCC and add it to the worklist since
// it has changed its shape.
AM.invalidate(*C, PreservedAnalyses::none());
UR.CWorklist.insert(C);
if (DebugLogging)
dbgs() << "Enqueuing the existing SCC in the worklist:" << *C << "\n";
SCC *OldC = C;
(void)OldC;
// Update the current SCC. Note that if we have new SCCs, this must actually
// change the SCC.
assert(C != &*NewSCCRange.begin() &&
"Cannot insert new SCCs without changing current SCC!");
C = &*NewSCCRange.begin();
assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
for (SCC &NewC :
reverse(make_range(std::next(NewSCCRange.begin()), NewSCCRange.end()))) {
assert(C != &NewC && "No need to re-visit the current SCC!");
assert(OldC != &NewC && "Already handled the original SCC!");
UR.CWorklist.insert(&NewC);
if (DebugLogging)
dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n";
}
return C;
}
}
LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, bool DebugLogging) {
typedef LazyCallGraph::Node Node;
typedef LazyCallGraph::Edge Edge;
typedef LazyCallGraph::SCC SCC;
typedef LazyCallGraph::RefSCC RefSCC;
RefSCC &InitialRC = InitialC.getOuterRefSCC();
SCC *C = &InitialC;
RefSCC *RC = &InitialRC;
Function &F = N.getFunction();
// Walk the function body and build up the set of retained, promoted, and
// demoted edges.
SmallVector<Constant *, 16> Worklist;
SmallPtrSet<Constant *, 16> Visited;
SmallPtrSet<Function *, 16> RetainedEdges;
SmallSetVector<Function *, 4> PromotedRefTargets;
SmallSetVector<Function *, 4> DemotedCallTargets;
// First walk the function and handle all called functions. We do this first
// because if there is a single call edge, whether there are ref edges is
// irrelevant.
for (BasicBlock &BB : F)
for (Instruction &I : BB)
if (auto CS = CallSite(&I))
if (Function *Callee = CS.getCalledFunction())
if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
const Edge *E = N.lookup(*Callee);
// FIXME: We should really handle adding new calls. While it will
// make downstream usage more complex, there is no fundamental
// limitation and it will allow passes within the CGSCC to be a bit
// more flexible in what transforms they can do. Until then, we
// verify that new calls haven't been introduced.
assert(E && "No function transformations should introduce *new* "
"call edges! Any new calls should be modeled as "
"promoted existing ref edges!");
RetainedEdges.insert(Callee);
if (!E->isCall())
PromotedRefTargets.insert(Callee);
}
// Now walk all references.
for (BasicBlock &BB : F)
for (Instruction &I : BB) {
for (Value *Op : I.operand_values())
if (Constant *C = dyn_cast<Constant>(Op))
if (Visited.insert(C).second)
Worklist.push_back(C);
LazyCallGraph::visitReferences(Worklist, Visited, [&](Function &Referee) {
// Skip declarations.
if (Referee.isDeclaration())
return;
const Edge *E = N.lookup(Referee);
// FIXME: Similarly to new calls, we also currently preclude
// introducing new references. See above for details.
assert(E && "No function transformations should introduce *new* ref "
"edges! Any new ref edges would require IPO which "
"function passes aren't allowed to do!");
RetainedEdges.insert(&Referee);
if (E->isCall())
DemotedCallTargets.insert(&Referee);
});
}
// First remove all of the edges that are no longer present in this function.
// We have to build a list of dead targets first and then remove them as the
// data structures will all be invalidated by removing them.
SmallVector<PointerIntPair<Node *, 1, Edge::Kind>, 4> DeadTargets;
for (Edge &E : N)
if (!RetainedEdges.count(&E.getFunction()))
DeadTargets.push_back({E.getNode(), E.getKind()});
for (auto DeadTarget : DeadTargets) {
Node &TargetN = *DeadTarget.getPointer();
bool IsCall = DeadTarget.getInt() == Edge::Call;
SCC &TargetC = *G.lookupSCC(TargetN);
RefSCC &TargetRC = TargetC.getOuterRefSCC();
if (&TargetRC != RC) {
RC->removeOutgoingEdge(N, TargetN);
if (DebugLogging)
dbgs() << "Deleting outgoing edge from '" << N << "' to '" << TargetN
<< "'\n";
continue;
}
if (DebugLogging)
dbgs() << "Deleting internal " << (IsCall ? "call" : "ref")
<< " edge from '" << N << "' to '" << TargetN << "'\n";
if (IsCall)
C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G, N,
C, AM, UR, DebugLogging);
auto NewRefSCCs = RC->removeInternalRefEdge(N, TargetN);
if (!NewRefSCCs.empty()) {
// Note that we don't bother to invalidate analyses as ref-edge
// connectivity is not really observable in any way and is intended
// exclusively to be used for ordering of transforms rather than for
// analysis conclusions.
// The RC worklist is in reverse postorder, so we first enqueue the
// current RefSCC as it will remain the parent of all split RefSCCs, then
// we enqueue the new ones in RPO except for the one which contains the
// source node as that is the "bottom" we will continue processing in the
// bottom-up walk.
UR.RCWorklist.insert(RC);
if (DebugLogging)
dbgs() << "Enqueuing the existing RefSCC in the update worklist: "
<< *RC << "\n";
// Update the RC to the "bottom".
assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!");
RC = &C->getOuterRefSCC();
assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!");
for (RefSCC *NewRC : reverse(NewRefSCCs))
if (NewRC != RC) {
UR.RCWorklist.insert(NewRC);
if (DebugLogging)
dbgs() << "Enqueuing a new RefSCC in the update worklist: "
<< *NewRC << "\n";
}
}
}
// Next demote all the call edges that are now ref edges. This helps make
// the SCCs small which should minimize the work below as we don't want to
// form cycles that this would break.
for (Function *RefTarget : DemotedCallTargets) {
Node &TargetN = *G.lookup(*RefTarget);
SCC &TargetC = *G.lookupSCC(TargetN);
RefSCC &TargetRC = TargetC.getOuterRefSCC();
// The easy case is when the target RefSCC is not this RefSCC. This is
// only supported when the target RefSCC is a child of this RefSCC.
if (&TargetRC != RC) {
assert(RC->isAncestorOf(TargetRC) &&
"Cannot potentially form RefSCC cycles here!");
RC->switchOutgoingEdgeToRef(N, TargetN);
if (DebugLogging)
dbgs() << "Switch outgoing call edge to a ref edge from '" << N
<< "' to '" << TargetN << "'\n";
continue;
}
// Otherwise we are switching an internal call edge to a ref edge. This
// may split up some SCCs.
C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G, N, C,
AM, UR, DebugLogging);
}
// Now promote ref edges into call edges.
for (Function *CallTarget : PromotedRefTargets) {
Node &TargetN = *G.lookup(*CallTarget);
SCC &TargetC = *G.lookupSCC(TargetN);
RefSCC &TargetRC = TargetC.getOuterRefSCC();
// The easy case is when the target RefSCC is not this RefSCC. This is
// only supported when the target RefSCC is a child of this RefSCC.
if (&TargetRC != RC) {
assert(RC->isAncestorOf(TargetRC) &&
"Cannot potentially form RefSCC cycles here!");
RC->switchOutgoingEdgeToCall(N, TargetN);
if (DebugLogging)
dbgs() << "Switch outgoing ref edge to a call edge from '" << N
<< "' to '" << TargetN << "'\n";
continue;
}
if (DebugLogging)
dbgs() << "Switch an internal ref edge to a call edge from '" << N
<< "' to '" << TargetN << "'\n";
// Otherwise we are switching an internal ref edge to a call edge. This
// may merge away some SCCs, and we add those to the UpdateResult. We also
// need to make sure to update the worklist in the event SCCs have moved
// before the current one in the post-order sequence.
auto InitialSCCIndex = RC->find(*C) - RC->begin();
auto InvalidatedSCCs = RC->switchInternalEdgeToCall(N, TargetN);
if (!InvalidatedSCCs.empty()) {
C = &TargetC;
assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
// Any analyses cached for this SCC are no longer precise as the shape
// has changed by introducing this cycle.
AM.invalidate(*C, PreservedAnalyses::none());
for (SCC *InvalidatedC : InvalidatedSCCs) {
assert(InvalidatedC != C && "Cannot invalidate the current SCC!");
UR.InvalidatedSCCs.insert(InvalidatedC);
// Also clear any cached analyses for the SCCs that are dead. This
// isn't really necessary for correctness but can release memory.
AM.clear(*InvalidatedC);
}
}
auto NewSCCIndex = RC->find(*C) - RC->begin();
if (InitialSCCIndex < NewSCCIndex) {
// Put our current SCC back onto the worklist as we'll visit other SCCs
// that are now definitively ordered prior to the current one in the
// post-order sequence, and may end up observing more precise context to
// optimize the current SCC.
UR.CWorklist.insert(C);
if (DebugLogging)
dbgs() << "Enqueuing the existing SCC in the worklist: " << *C << "\n";
// Enqueue in reverse order as we pop off the back of the worklist.
for (SCC &MovedC : reverse(make_range(RC->begin() + InitialSCCIndex,
RC->begin() + NewSCCIndex))) {
UR.CWorklist.insert(&MovedC);
if (DebugLogging)
dbgs() << "Enqueuing a newly earlier in post-order SCC: " << MovedC
<< "\n";
}
}
}
assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");
// Record the current RefSCC and SCC for higher layers of the CGSCC pass
// manager now that all the updates have been applied.
if (RC != &InitialRC)
UR.UpdatedRC = RC;
if (C != &InitialC)
UR.UpdatedC = C;
return *C;
}
<commit_msg>[PM] Basic cleanups to CGSCC update code, NFC.<commit_after>//===- CGSCCPassManager.cpp - Managing & running CGSCC passes -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/CGSCCPassManager.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/InstIterator.h"
using namespace llvm;
namespace llvm {
// Explicit instantiations for the core proxy templates.
template class AllAnalysesOn<LazyCallGraph::SCC>;
template class AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
LazyCallGraph &, CGSCCUpdateResult &>;
template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
template class OuterAnalysisManagerProxy<ModuleAnalysisManager,
LazyCallGraph::SCC>;
template class InnerAnalysisManagerProxy<FunctionAnalysisManager,
LazyCallGraph::SCC>;
template class OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
/// Explicitly specialize the pass manager run method to handle call graph
/// updates.
template <>
PreservedAnalyses
PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
CGSCCAnalysisManager &AM,
LazyCallGraph &G, CGSCCUpdateResult &UR) {
PreservedAnalyses PA = PreservedAnalyses::all();
if (DebugLogging)
dbgs() << "Starting CGSCC pass manager run.\n";
// The SCC may be refined while we are running passes over it, so set up
// a pointer that we can update.
LazyCallGraph::SCC *C = &InitialC;
for (auto &Pass : Passes) {
if (DebugLogging)
dbgs() << "Running pass: " << Pass->name() << " on " << *C << "\n";
PreservedAnalyses PassPA = Pass->run(*C, AM, G, UR);
// Update the SCC if necessary.
C = UR.UpdatedC ? UR.UpdatedC : C;
// Check that we didn't miss any update scenario.
assert(!UR.InvalidatedSCCs.count(C) && "Processing an invalid SCC!");
assert(C->begin() != C->end() && "Cannot have an empty SCC!");
// Update the analysis manager as each pass runs and potentially
// invalidates analyses.
AM.invalidate(*C, PassPA);
// Finally, we intersect the final preserved analyses to compute the
// aggregate preserved set for this pass manager.
PA.intersect(std::move(PassPA));
// FIXME: Historically, the pass managers all called the LLVM context's
// yield function here. We don't have a generic way to acquire the
// context and it isn't yet clear what the right pattern is for yielding
// in the new pass manager so it is currently omitted.
// ...getContext().yield();
}
// Invaliadtion was handled after each pass in the above loop for the current
// SCC. Therefore, the remaining analysis results in the AnalysisManager are
// preserved. We mark this with a set so that we don't need to inspect each
// one individually.
PA.preserve<AllAnalysesOn<LazyCallGraph::SCC>>();
if (DebugLogging)
dbgs() << "Finished CGSCC pass manager run.\n";
return PA;
}
} // End llvm namespace
namespace {
/// Helper function to update both the \c CGSCCAnalysisManager \p AM and the \c
/// CGSCCPassManager's \c CGSCCUpdateResult \p UR based on a range of newly
/// added SCCs.
///
/// The range of new SCCs must be in postorder already. The SCC they were split
/// out of must be provided as \p C. The current node being mutated and
/// triggering updates must be passed as \p N.
///
/// This function returns the SCC containing \p N. This will be either \p C if
/// no new SCCs have been split out, or it will be the new SCC containing \p N.
template <typename SCCRangeT>
LazyCallGraph::SCC *
incorporateNewSCCRange(const SCCRangeT &NewSCCRange, LazyCallGraph &G,
LazyCallGraph::Node &N, LazyCallGraph::SCC *C,
CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
bool DebugLogging = false) {
typedef LazyCallGraph::SCC SCC;
if (NewSCCRange.begin() == NewSCCRange.end())
return C;
// Invalidate the analyses of the current SCC and add it to the worklist since
// it has changed its shape.
AM.invalidate(*C, PreservedAnalyses::none());
UR.CWorklist.insert(C);
if (DebugLogging)
dbgs() << "Enqueuing the existing SCC in the worklist:" << *C << "\n";
SCC *OldC = C;
(void)OldC;
// Update the current SCC. Note that if we have new SCCs, this must actually
// change the SCC.
assert(C != &*NewSCCRange.begin() &&
"Cannot insert new SCCs without changing current SCC!");
C = &*NewSCCRange.begin();
assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
for (SCC &NewC :
reverse(make_range(std::next(NewSCCRange.begin()), NewSCCRange.end()))) {
assert(C != &NewC && "No need to re-visit the current SCC!");
assert(OldC != &NewC && "Already handled the original SCC!");
UR.CWorklist.insert(&NewC);
if (DebugLogging)
dbgs() << "Enqueuing a newly formed SCC:" << NewC << "\n";
}
return C;
}
}
LazyCallGraph::SCC &llvm::updateCGAndAnalysisManagerForFunctionPass(
LazyCallGraph &G, LazyCallGraph::SCC &InitialC, LazyCallGraph::Node &N,
CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR, bool DebugLogging) {
typedef LazyCallGraph::Node Node;
typedef LazyCallGraph::Edge Edge;
typedef LazyCallGraph::SCC SCC;
typedef LazyCallGraph::RefSCC RefSCC;
RefSCC &InitialRC = InitialC.getOuterRefSCC();
SCC *C = &InitialC;
RefSCC *RC = &InitialRC;
Function &F = N.getFunction();
// Walk the function body and build up the set of retained, promoted, and
// demoted edges.
SmallVector<Constant *, 16> Worklist;
SmallPtrSet<Constant *, 16> Visited;
SmallPtrSet<Function *, 16> RetainedEdges;
SmallSetVector<Function *, 4> PromotedRefTargets;
SmallSetVector<Function *, 4> DemotedCallTargets;
// First walk the function and handle all called functions. We do this first
// because if there is a single call edge, whether there are ref edges is
// irrelevant.
for (Instruction &I : instructions(F))
if (auto CS = CallSite(&I))
if (Function *Callee = CS.getCalledFunction())
if (Visited.insert(Callee).second && !Callee->isDeclaration()) {
const Edge *E = N.lookup(*Callee);
// FIXME: We should really handle adding new calls. While it will
// make downstream usage more complex, there is no fundamental
// limitation and it will allow passes within the CGSCC to be a bit
// more flexible in what transforms they can do. Until then, we
// verify that new calls haven't been introduced.
assert(E && "No function transformations should introduce *new* "
"call edges! Any new calls should be modeled as "
"promoted existing ref edges!");
RetainedEdges.insert(Callee);
if (!E->isCall())
PromotedRefTargets.insert(Callee);
}
// Now walk all references.
for (Instruction &I : instructions(F))
for (Value *Op : I.operand_values())
if (Constant *C = dyn_cast<Constant>(Op))
if (Visited.insert(C).second)
Worklist.push_back(C);
LazyCallGraph::visitReferences(Worklist, Visited, [&](Function &Referee) {
const Edge *E = N.lookup(Referee);
// FIXME: Similarly to new calls, we also currently preclude
// introducing new references. See above for details.
assert(E && "No function transformations should introduce *new* ref "
"edges! Any new ref edges would require IPO which "
"function passes aren't allowed to do!");
RetainedEdges.insert(&Referee);
if (E->isCall())
DemotedCallTargets.insert(&Referee);
});
// First remove all of the edges that are no longer present in this function.
// We have to build a list of dead targets first and then remove them as the
// data structures will all be invalidated by removing them.
SmallVector<PointerIntPair<Node *, 1, Edge::Kind>, 4> DeadTargets;
for (Edge &E : N)
if (!RetainedEdges.count(&E.getFunction()))
DeadTargets.push_back({E.getNode(), E.getKind()});
for (auto DeadTarget : DeadTargets) {
Node &TargetN = *DeadTarget.getPointer();
bool IsCall = DeadTarget.getInt() == Edge::Call;
SCC &TargetC = *G.lookupSCC(TargetN);
RefSCC &TargetRC = TargetC.getOuterRefSCC();
if (&TargetRC != RC) {
RC->removeOutgoingEdge(N, TargetN);
if (DebugLogging)
dbgs() << "Deleting outgoing edge from '" << N << "' to '" << TargetN
<< "'\n";
continue;
}
if (DebugLogging)
dbgs() << "Deleting internal " << (IsCall ? "call" : "ref")
<< " edge from '" << N << "' to '" << TargetN << "'\n";
if (IsCall)
C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G, N,
C, AM, UR, DebugLogging);
auto NewRefSCCs = RC->removeInternalRefEdge(N, TargetN);
if (!NewRefSCCs.empty()) {
// Note that we don't bother to invalidate analyses as ref-edge
// connectivity is not really observable in any way and is intended
// exclusively to be used for ordering of transforms rather than for
// analysis conclusions.
// The RC worklist is in reverse postorder, so we first enqueue the
// current RefSCC as it will remain the parent of all split RefSCCs, then
// we enqueue the new ones in RPO except for the one which contains the
// source node as that is the "bottom" we will continue processing in the
// bottom-up walk.
UR.RCWorklist.insert(RC);
if (DebugLogging)
dbgs() << "Enqueuing the existing RefSCC in the update worklist: "
<< *RC << "\n";
// Update the RC to the "bottom".
assert(G.lookupSCC(N) == C && "Changed the SCC when splitting RefSCCs!");
RC = &C->getOuterRefSCC();
assert(G.lookupRefSCC(N) == RC && "Failed to update current RefSCC!");
for (RefSCC *NewRC : reverse(NewRefSCCs))
if (NewRC != RC) {
UR.RCWorklist.insert(NewRC);
if (DebugLogging)
dbgs() << "Enqueuing a new RefSCC in the update worklist: "
<< *NewRC << "\n";
}
}
}
// Next demote all the call edges that are now ref edges. This helps make
// the SCCs small which should minimize the work below as we don't want to
// form cycles that this would break.
for (Function *RefTarget : DemotedCallTargets) {
Node &TargetN = *G.lookup(*RefTarget);
SCC &TargetC = *G.lookupSCC(TargetN);
RefSCC &TargetRC = TargetC.getOuterRefSCC();
// The easy case is when the target RefSCC is not this RefSCC. This is
// only supported when the target RefSCC is a child of this RefSCC.
if (&TargetRC != RC) {
assert(RC->isAncestorOf(TargetRC) &&
"Cannot potentially form RefSCC cycles here!");
RC->switchOutgoingEdgeToRef(N, TargetN);
if (DebugLogging)
dbgs() << "Switch outgoing call edge to a ref edge from '" << N
<< "' to '" << TargetN << "'\n";
continue;
}
// Otherwise we are switching an internal call edge to a ref edge. This
// may split up some SCCs.
C = incorporateNewSCCRange(RC->switchInternalEdgeToRef(N, TargetN), G, N, C,
AM, UR, DebugLogging);
}
// Now promote ref edges into call edges.
for (Function *CallTarget : PromotedRefTargets) {
Node &TargetN = *G.lookup(*CallTarget);
SCC &TargetC = *G.lookupSCC(TargetN);
RefSCC &TargetRC = TargetC.getOuterRefSCC();
// The easy case is when the target RefSCC is not this RefSCC. This is
// only supported when the target RefSCC is a child of this RefSCC.
if (&TargetRC != RC) {
assert(RC->isAncestorOf(TargetRC) &&
"Cannot potentially form RefSCC cycles here!");
RC->switchOutgoingEdgeToCall(N, TargetN);
if (DebugLogging)
dbgs() << "Switch outgoing ref edge to a call edge from '" << N
<< "' to '" << TargetN << "'\n";
continue;
}
if (DebugLogging)
dbgs() << "Switch an internal ref edge to a call edge from '" << N
<< "' to '" << TargetN << "'\n";
// Otherwise we are switching an internal ref edge to a call edge. This
// may merge away some SCCs, and we add those to the UpdateResult. We also
// need to make sure to update the worklist in the event SCCs have moved
// before the current one in the post-order sequence.
auto InitialSCCIndex = RC->find(*C) - RC->begin();
auto InvalidatedSCCs = RC->switchInternalEdgeToCall(N, TargetN);
if (!InvalidatedSCCs.empty()) {
C = &TargetC;
assert(G.lookupSCC(N) == C && "Failed to update current SCC!");
// Any analyses cached for this SCC are no longer precise as the shape
// has changed by introducing this cycle.
AM.invalidate(*C, PreservedAnalyses::none());
for (SCC *InvalidatedC : InvalidatedSCCs) {
assert(InvalidatedC != C && "Cannot invalidate the current SCC!");
UR.InvalidatedSCCs.insert(InvalidatedC);
// Also clear any cached analyses for the SCCs that are dead. This
// isn't really necessary for correctness but can release memory.
AM.clear(*InvalidatedC);
}
}
auto NewSCCIndex = RC->find(*C) - RC->begin();
if (InitialSCCIndex < NewSCCIndex) {
// Put our current SCC back onto the worklist as we'll visit other SCCs
// that are now definitively ordered prior to the current one in the
// post-order sequence, and may end up observing more precise context to
// optimize the current SCC.
UR.CWorklist.insert(C);
if (DebugLogging)
dbgs() << "Enqueuing the existing SCC in the worklist: " << *C << "\n";
// Enqueue in reverse order as we pop off the back of the worklist.
for (SCC &MovedC : reverse(make_range(RC->begin() + InitialSCCIndex,
RC->begin() + NewSCCIndex))) {
UR.CWorklist.insert(&MovedC);
if (DebugLogging)
dbgs() << "Enqueuing a newly earlier in post-order SCC: " << MovedC
<< "\n";
}
}
}
assert(!UR.InvalidatedSCCs.count(C) && "Invalidated the current SCC!");
assert(!UR.InvalidatedRefSCCs.count(RC) && "Invalidated the current RefSCC!");
assert(&C->getOuterRefSCC() == RC && "Current SCC not in current RefSCC!");
// Record the current RefSCC and SCC for higher layers of the CGSCC pass
// manager now that all the updates have been applied.
if (RC != &InitialRC)
UR.UpdatedRC = RC;
if (C != &InitialC)
UR.UpdatedC = C;
return *C;
}
<|endoftext|>
|
<commit_before>/// @file characterUtilities.cpp
/// @author Enrico Fraccaroli
/// @date Jan 29 2017
/// @copyright
/// Copyright (c) 2017 Enrico Fraccaroli <enrico.fraccaroli@gmail.com>
/// Permission is hereby granted, free of charge, to any person obtaining a
/// copy of this software and associated documentation files (the "Software"),
/// to deal in the Software without restriction, including without limitation
/// the rights to use, copy, modify, merge, publish, distribute, sublicense,
/// and/or sell copies of the Software, and to permit persons to whom the
/// Software is furnished to do so, subject to the following conditions:
/// The above copyright notice and this permission notice shall be included
/// in all copies or substantial portions of the Software.
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
/// DEALINGS IN THE SOFTWARE.
#include "characterUtilities.hpp"
#include "rangedWeaponItem.hpp"
#include "meleeWeaponItem.hpp"
#include "resourceModel.hpp"
#include "toolModel.hpp"
#include "character.hpp"
#include "logger.hpp"
#include "room.hpp"
std::vector<MeleeWeaponItem *> GetActiveMeleeWeapons(Character * character)
{
std::vector<MeleeWeaponItem *> weapons;
for (auto item : character->equipment)
{
// If at least one of the occupied body parts can be used to wield
// a weapon, consider it an active weapon.
for (auto bodyPart : item->occupiedBodyParts)
{
if (HasFlag(bodyPart->flags, BodyPartFlag::CanWield))
{
if (item->getType() == ModelType::MeleeWeapon)
{
auto wpn = static_cast<MeleeWeaponItem *>(item);
weapons.emplace_back(wpn);
// Break the loop otherwise the weapon would be added
// for each occupied body part.
break;
}
}
}
}
return weapons;
}
std::vector<RangedWeaponItem *> GetActiveRangedWeapons(Character * character)
{
std::vector<RangedWeaponItem *> weapons;
for (auto item : character->equipment)
{
// If at least one of the occupied body parts can be used to wield
// a range weapon, consider it an active weapon.
for (auto bodyPart : item->occupiedBodyParts)
{
if (HasFlag(bodyPart->flags, BodyPartFlag::CanWield))
{
if (item->getType() == ModelType::RangedWeapon)
{
auto wpn = static_cast<RangedWeaponItem *>(item);
weapons.emplace_back(wpn);
// Break the loop otherwise the weapon would be added
// for each occupied body part.
break;
}
}
}
}
return weapons;
}
std::vector<std::shared_ptr<BodyPart::BodyWeapon>> GetActiveNaturalWeapons(
Character * character)
{
std::vector<std::shared_ptr<BodyPart::BodyWeapon>> naturalWeapons;
for (auto bodyPart : character->race->bodyParts)
{
// If the body part is holding an item, skip it.
if (character->findItemAtBodyPart(bodyPart) != nullptr) continue;
// If the body part cannot be used as natural weapon, skip it.
if (bodyPart->weapon == nullptr) continue;
// Add the natural weapon to the vector.
naturalWeapons.emplace_back(bodyPart->weapon);
}
return naturalWeapons;
}
ItemVector FindPosessedCoins(Character * character)
{
ItemVector foundCoins;
auto FindCoinInContainer = [&](Item * item)
{
if (item->getType() == ModelType::Container)
{
// Cast the item to container.
auto containerItem = static_cast<ContainerItem *>(item);
for (auto content : containerItem->content)
{
if (content->getType() == ModelType::Currency)
{
foundCoins.emplace_back(content);
}
}
}
};
for (auto it : character->equipment)
{
FindCoinInContainer(it);
}
for (auto it : character->inventory)
{
if (it->getType() == ModelType::Currency)
{
foundCoins.emplace_back(it);
}
else
{
FindCoinInContainer(it);
}
}
foundCoins.orderBy(ItemVector::ByPrice);
return foundCoins;
}
// -----------------------------------------------------------------------------
SearchOptionsCharacter::SearchOptionsCharacter() :
searchInRoom(),
searchInInventory(),
searchInEquipment()
{
// Nothing to do.
}
SearchOptionsCharacter::SearchOptionsCharacter(
const SearchOptionsCharacter & other) :
searchInRoom(other.searchInRoom),
searchInInventory(other.searchInInventory),
searchInEquipment(other.searchInEquipment)
{
// Nothing to do.
}
SearchOptionsCharacter::~SearchOptionsCharacter()
{
// Nothing to do.
}
// -----------------------------------------------------------------------------
bool FindNearbyResouces(
Character * character,
std::map<ResourceType, unsigned int> requiredResources,
std::vector<std::pair<Item *, unsigned int>> & foundResources,
const SearchOptionsCharacter & searchOptions)
{
// Create a function which checks if the given item is of the required type.
auto IsValidResource = [](Item * item, const ResourceType & resourceType)
{
// Check the pointer to the model.
if (item->model == nullptr) return false;
// Check if the item is a resource.
if (item->model->getType() != ModelType::Resource) return false;
// Cast the model to ResourceModel.
auto resourceModel = item->model->toResource();
// Check if the type of resource is the same.
return (resourceModel->resourceType == resourceType);
};
// Create a function which reduces the required quantity and checks if
// the zero has been reached.
auto DecrementRequired = [&foundResources](Item * item,
unsigned int & requiredQuantity)
{
// Get the available quantity.
auto quantityAvailable = item->quantity;
// Set the used quantity.
auto quantityUsed = quantityAvailable;
if (quantityAvailable > requiredQuantity)
{
quantityUsed = (quantityAvailable - requiredQuantity);
}
// Add the item to the list of used resources.
foundResources.emplace_back(std::make_pair(item, quantityUsed));
// Reduce the quantity needed.
requiredQuantity -= quantityUsed;
// Returns if we've reached the needed quantity.
return (requiredQuantity == 0);
};
for (auto resource : requiredResources)
{
// Quantity of ingredients that has to be found.
auto quantityNeeded = resource.second;
// Check if we need to search inside the room.
// TODO: Probably I need to check if a given item is not selected twice.
if (searchOptions.searchInRoom)
{
for (auto item : character->room->items)
{
// Check if the item is a valid resource.
if (!IsValidResource(item, resource.first)) continue;
// Decrement the required quantity. If we've reached the
// needed quantity stop the loop.
if (DecrementRequired(item, quantityNeeded)) break;
}
}
// Check if we need to search inside the character's equipment.
if (searchOptions.searchInEquipment)
{
for (auto item : character->equipment)
{
// Check if the item is a valid resource.
if (!IsValidResource(item, resource.first)) continue;
// Decrement the required quantity. If we've reached the
// needed quantity stop the loop.
if (DecrementRequired(item, quantityNeeded)) break;
}
}
// Check if we need to search inside the character's inventory.
if (searchOptions.searchInInventory)
{
for (auto item : character->inventory)
{
// Check if the item is a valid resource.
if (!IsValidResource(item, resource.first)) continue;
// Decrement the required quantity. If we've reached the
// needed quantity stop the loop.
if (DecrementRequired(item, quantityNeeded)) break;
}
}
// If the ingredients are still not enough, return false.
if (quantityNeeded > 0) return false;
}
return true;
}
Item * FindNearbyTool(
Character * character,
const ToolType & toolType,
const ItemVector & exceptions,
const SearchOptionsCharacter & searchOptions)
{
// Create a function which checks if the given item is of the required type.
auto IsValidTool = [toolType, exceptions](Item * item)
{
// Check the pointer to the model.
if (item->model == nullptr) return false;
// Check if the item is a resource.
if (item->model->getType() != ModelType::Tool) return false;
// Cast the model to ResourceModel.
auto toolModel = item->model->toTool();
// Check if the type of resource is the same.
if (toolModel->toolType != toolType) return false;
// Check if the item is inside the exception list.
return std::find_if(exceptions.begin(),
exceptions.end(),
[item](Item * exception)
{
return (item->vnum == exception->vnum);
}) == exceptions.end();
};
if (searchOptions.searchInRoom)
{
for (auto item : character->room->items)
{
// Check if it is a valid item.
if (IsValidTool(item)) return item;
}
}
if (searchOptions.searchInEquipment)
{
for (auto item : character->equipment)
{
// Check if it is a valid item.
if (IsValidTool(item)) return item;
}
}
if (searchOptions.searchInInventory)
{
for (auto item : character->inventory)
{
// Check if it is a valid item.
if (IsValidTool(item)) return item;
}
}
return nullptr;
}
bool FindNearbyTools(
Character * character,
std::vector<ToolType> requiredTools,
ItemVector & foundTools,
const SearchOptionsCharacter & searchOptions)
{
for (auto requiredTool : requiredTools)
{
auto tool = FindNearbyTool(character,
requiredTool,
foundTools,
searchOptions);
if (tool == nullptr) return false;
foundTools.emplace_back(tool);
}
return true;
}
Item * FindNearbyBuilding(
Character * character,
std::shared_ptr<ItemModel> buildingModel,
const SearchOptionsCharacter & searchOptions)
{
// Create a function which checks if the given item is of the required type.
auto IsValidBuilding = [buildingModel](Item * item)
{
// Check the pointer to the model.
if (item->model == nullptr) return false;
return buildingModel->vnum == item->model->vnum;
};
if (searchOptions.searchInRoom)
{
for (auto item : character->room->items)
{
// Check if it is a valid item.
if (IsValidBuilding(item)) return item;
}
}
if (searchOptions.searchInEquipment)
{
for (auto item : character->equipment)
{
// Check if it is a valid item.
if (IsValidBuilding(item)) return item;
}
}
if (searchOptions.searchInInventory)
{
for (auto item : character->inventory)
{
// Check if it is a valid item.
if (IsValidBuilding(item)) return item;
}
}
return nullptr;
}
bool MoveCharacterTo(
Character * character,
Room * destination,
const std::string & msgDepart,
const std::string & msgArrive,
const std::string & msgChar)
{
// Check if the function has received a valid character.
if (WrongAssert(character == nullptr)) return false;
// Check if the function has received a valid destination.
if (WrongAssert(destination == nullptr)) return false;
// Check if the character is inside a valid room.
if (WrongAssert(character->room == nullptr)) return false;
// Activate the entrance event for every mobile in the room.
for (auto mobile : character->room->getAllMobile(character))
{
if (mobile->canSee(character))
{
mobile->triggerEventExit(character);
}
}
// Show a message to the character, if is set.
if (!msgChar.empty()) character->sendMsg(msgChar);
// Tell others where the character went and remove s/he from the old room.
character->room->sendToAll(msgDepart, {character});
// Remove the player from the current room.
character->room->removeCharacter(character);
// Add the character to the destionation room.
destination->addCharacter(character);
// Look around new room.
character->doCommand("look");
// Tell others s/he has arrived and move the character to the new room.
destination->sendToAll(msgArrive, {character});
// Activate the entrance event for every mobile in the room.
for (auto mobile : character->room->getAllMobile(character))
{
if (mobile->canSee(character))
{
mobile->triggerEventEnter(character);
}
}
return true;
}
bool HasRequiredKnowledge(Character * character, Production * production)
{
if (WrongAssert(character == nullptr)) return false;
if (WrongAssert(production == nullptr)) return false;
for (auto knowledge : production->requiredKnowledge)
{
if (character->effectManager.getKnowledge(knowledge) <= 0) return false;
}
return true;
}<commit_msg>Update knowledge check when performing profession<commit_after>/// @file characterUtilities.cpp
/// @author Enrico Fraccaroli
/// @date Jan 29 2017
/// @copyright
/// Copyright (c) 2017 Enrico Fraccaroli <enrico.fraccaroli@gmail.com>
/// Permission is hereby granted, free of charge, to any person obtaining a
/// copy of this software and associated documentation files (the "Software"),
/// to deal in the Software without restriction, including without limitation
/// the rights to use, copy, modify, merge, publish, distribute, sublicense,
/// and/or sell copies of the Software, and to permit persons to whom the
/// Software is furnished to do so, subject to the following conditions:
/// The above copyright notice and this permission notice shall be included
/// in all copies or substantial portions of the Software.
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
/// DEALINGS IN THE SOFTWARE.
#include "characterUtilities.hpp"
#include "rangedWeaponItem.hpp"
#include "meleeWeaponItem.hpp"
#include "resourceModel.hpp"
#include "toolModel.hpp"
#include "character.hpp"
#include "logger.hpp"
#include "room.hpp"
std::vector<MeleeWeaponItem *> GetActiveMeleeWeapons(Character * character)
{
std::vector<MeleeWeaponItem *> weapons;
for (auto item : character->equipment)
{
// If at least one of the occupied body parts can be used to wield
// a weapon, consider it an active weapon.
for (auto bodyPart : item->occupiedBodyParts)
{
if (HasFlag(bodyPart->flags, BodyPartFlag::CanWield))
{
if (item->getType() == ModelType::MeleeWeapon)
{
auto wpn = static_cast<MeleeWeaponItem *>(item);
weapons.emplace_back(wpn);
// Break the loop otherwise the weapon would be added
// for each occupied body part.
break;
}
}
}
}
return weapons;
}
std::vector<RangedWeaponItem *> GetActiveRangedWeapons(Character * character)
{
std::vector<RangedWeaponItem *> weapons;
for (auto item : character->equipment)
{
// If at least one of the occupied body parts can be used to wield
// a range weapon, consider it an active weapon.
for (auto bodyPart : item->occupiedBodyParts)
{
if (HasFlag(bodyPart->flags, BodyPartFlag::CanWield))
{
if (item->getType() == ModelType::RangedWeapon)
{
auto wpn = static_cast<RangedWeaponItem *>(item);
weapons.emplace_back(wpn);
// Break the loop otherwise the weapon would be added
// for each occupied body part.
break;
}
}
}
}
return weapons;
}
std::vector<std::shared_ptr<BodyPart::BodyWeapon>> GetActiveNaturalWeapons(
Character * character)
{
std::vector<std::shared_ptr<BodyPart::BodyWeapon>> naturalWeapons;
for (auto bodyPart : character->race->bodyParts)
{
// If the body part is holding an item, skip it.
if (character->findItemAtBodyPart(bodyPart) != nullptr) continue;
// If the body part cannot be used as natural weapon, skip it.
if (bodyPart->weapon == nullptr) continue;
// Add the natural weapon to the vector.
naturalWeapons.emplace_back(bodyPart->weapon);
}
return naturalWeapons;
}
ItemVector FindPosessedCoins(Character * character)
{
ItemVector foundCoins;
auto FindCoinInContainer = [&](Item * item)
{
if (item->getType() == ModelType::Container)
{
// Cast the item to container.
auto containerItem = static_cast<ContainerItem *>(item);
for (auto content : containerItem->content)
{
if (content->getType() == ModelType::Currency)
{
foundCoins.emplace_back(content);
}
}
}
};
for (auto it : character->equipment)
{
FindCoinInContainer(it);
}
for (auto it : character->inventory)
{
if (it->getType() == ModelType::Currency)
{
foundCoins.emplace_back(it);
}
else
{
FindCoinInContainer(it);
}
}
foundCoins.orderBy(ItemVector::ByPrice);
return foundCoins;
}
// -----------------------------------------------------------------------------
SearchOptionsCharacter::SearchOptionsCharacter() :
searchInRoom(),
searchInInventory(),
searchInEquipment()
{
// Nothing to do.
}
SearchOptionsCharacter::SearchOptionsCharacter(
const SearchOptionsCharacter & other) :
searchInRoom(other.searchInRoom),
searchInInventory(other.searchInInventory),
searchInEquipment(other.searchInEquipment)
{
// Nothing to do.
}
SearchOptionsCharacter::~SearchOptionsCharacter()
{
// Nothing to do.
}
// -----------------------------------------------------------------------------
bool FindNearbyResouces(
Character * character,
std::map<ResourceType, unsigned int> requiredResources,
std::vector<std::pair<Item *, unsigned int>> & foundResources,
const SearchOptionsCharacter & searchOptions)
{
// Create a function which checks if the given item is of the required type.
auto IsValidResource = [](Item * item, const ResourceType & resourceType)
{
// Check the pointer to the model.
if (item->model == nullptr) return false;
// Check if the item is a resource.
if (item->model->getType() != ModelType::Resource) return false;
// Cast the model to ResourceModel.
auto resourceModel = item->model->toResource();
// Check if the type of resource is the same.
return (resourceModel->resourceType == resourceType);
};
// Create a function which reduces the required quantity and checks if
// the zero has been reached.
auto DecrementRequired = [&foundResources](Item * item,
unsigned int & requiredQuantity)
{
// Get the available quantity.
auto quantityAvailable = item->quantity;
// Set the used quantity.
auto quantityUsed = quantityAvailable;
if (quantityAvailable > requiredQuantity)
{
quantityUsed = (quantityAvailable - requiredQuantity);
}
// Add the item to the list of used resources.
foundResources.emplace_back(std::make_pair(item, quantityUsed));
// Reduce the quantity needed.
requiredQuantity -= quantityUsed;
// Returns if we've reached the needed quantity.
return (requiredQuantity == 0);
};
for (auto resource : requiredResources)
{
// Quantity of ingredients that has to be found.
auto quantityNeeded = resource.second;
// Check if we need to search inside the room.
// TODO: Probably I need to check if a given item is not selected twice.
if (searchOptions.searchInRoom)
{
for (auto item : character->room->items)
{
// Check if the item is a valid resource.
if (!IsValidResource(item, resource.first)) continue;
// Decrement the required quantity. If we've reached the
// needed quantity stop the loop.
if (DecrementRequired(item, quantityNeeded)) break;
}
}
// Check if we need to search inside the character's equipment.
if (searchOptions.searchInEquipment)
{
for (auto item : character->equipment)
{
// Check if the item is a valid resource.
if (!IsValidResource(item, resource.first)) continue;
// Decrement the required quantity. If we've reached the
// needed quantity stop the loop.
if (DecrementRequired(item, quantityNeeded)) break;
}
}
// Check if we need to search inside the character's inventory.
if (searchOptions.searchInInventory)
{
for (auto item : character->inventory)
{
// Check if the item is a valid resource.
if (!IsValidResource(item, resource.first)) continue;
// Decrement the required quantity. If we've reached the
// needed quantity stop the loop.
if (DecrementRequired(item, quantityNeeded)) break;
}
}
// If the ingredients are still not enough, return false.
if (quantityNeeded > 0) return false;
}
return true;
}
Item * FindNearbyTool(
Character * character,
const ToolType & toolType,
const ItemVector & exceptions,
const SearchOptionsCharacter & searchOptions)
{
// Create a function which checks if the given item is of the required type.
auto IsValidTool = [toolType, exceptions](Item * item)
{
// Check the pointer to the model.
if (item->model == nullptr) return false;
// Check if the item is a resource.
if (item->model->getType() != ModelType::Tool) return false;
// Cast the model to ResourceModel.
auto toolModel = item->model->toTool();
// Check if the type of resource is the same.
if (toolModel->toolType != toolType) return false;
// Check if the item is inside the exception list.
return std::find_if(exceptions.begin(),
exceptions.end(),
[item](Item * exception)
{
return (item->vnum == exception->vnum);
}) == exceptions.end();
};
if (searchOptions.searchInRoom)
{
for (auto item : character->room->items)
{
// Check if it is a valid item.
if (IsValidTool(item)) return item;
}
}
if (searchOptions.searchInEquipment)
{
for (auto item : character->equipment)
{
// Check if it is a valid item.
if (IsValidTool(item)) return item;
}
}
if (searchOptions.searchInInventory)
{
for (auto item : character->inventory)
{
// Check if it is a valid item.
if (IsValidTool(item)) return item;
}
}
return nullptr;
}
bool FindNearbyTools(
Character * character,
std::vector<ToolType> requiredTools,
ItemVector & foundTools,
const SearchOptionsCharacter & searchOptions)
{
for (auto requiredTool : requiredTools)
{
auto tool = FindNearbyTool(character,
requiredTool,
foundTools,
searchOptions);
if (tool == nullptr) return false;
foundTools.emplace_back(tool);
}
return true;
}
Item * FindNearbyBuilding(
Character * character,
std::shared_ptr<ItemModel> buildingModel,
const SearchOptionsCharacter & searchOptions)
{
// Create a function which checks if the given item is of the required type.
auto IsValidBuilding = [buildingModel](Item * item)
{
// Check the pointer to the model.
if (item->model == nullptr) return false;
return buildingModel->vnum == item->model->vnum;
};
if (searchOptions.searchInRoom)
{
for (auto item : character->room->items)
{
// Check if it is a valid item.
if (IsValidBuilding(item)) return item;
}
}
if (searchOptions.searchInEquipment)
{
for (auto item : character->equipment)
{
// Check if it is a valid item.
if (IsValidBuilding(item)) return item;
}
}
if (searchOptions.searchInInventory)
{
for (auto item : character->inventory)
{
// Check if it is a valid item.
if (IsValidBuilding(item)) return item;
}
}
return nullptr;
}
bool MoveCharacterTo(
Character * character,
Room * destination,
const std::string & msgDepart,
const std::string & msgArrive,
const std::string & msgChar)
{
// Check if the function has received a valid character.
if (WrongAssert(character == nullptr)) return false;
// Check if the function has received a valid destination.
if (WrongAssert(destination == nullptr)) return false;
// Check if the character is inside a valid room.
if (WrongAssert(character->room == nullptr)) return false;
// Activate the entrance event for every mobile in the room.
for (auto mobile : character->room->getAllMobile(character))
{
if (mobile->canSee(character))
{
mobile->triggerEventExit(character);
}
}
// Show a message to the character, if is set.
if (!msgChar.empty()) character->sendMsg(msgChar);
// Tell others where the character went and remove s/he from the old room.
character->room->sendToAll(msgDepart, {character});
// Remove the player from the current room.
character->room->removeCharacter(character);
// Add the character to the destionation room.
destination->addCharacter(character);
// Look around new room.
character->doCommand("look");
// Tell others s/he has arrived and move the character to the new room.
destination->sendToAll(msgArrive, {character});
// Activate the entrance event for every mobile in the room.
for (auto mobile : character->room->getAllMobile(character))
{
if (mobile->canSee(character))
{
mobile->triggerEventEnter(character);
}
}
return true;
}
bool HasRequiredKnowledge(Character * character, Production * production)
{
if (WrongAssert(character == nullptr)) return false;
if (WrongAssert(production == nullptr)) return false;
for (auto const & it : production->requiredKnowledge)
{
if ((character->skillManager.getKnowledge(it) <= 0) &&
(character->effectManager.getKnowledge(it) <= 0))
{
return false;
}
}
return true;
}<|endoftext|>
|
<commit_before><commit_msg>adding header support<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/platform_thread.h"
#include "webrtc/base/atomicops.h"
#include "webrtc/base/checks.h"
#if defined(WEBRTC_LINUX)
#include <sys/prctl.h>
#include <sys/syscall.h>
#endif
namespace rtc {
PlatformThreadId CurrentThreadId() {
PlatformThreadId ret;
#if defined(WEBRTC_WIN)
ret = GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
ret = pthread_mach_thread_np(pthread_self());
#elif defined(WEBRTC_LINUX)
ret = syscall(__NR_gettid);
#elif defined(WEBRTC_ANDROID)
ret = gettid();
#else
// Default implementation for nacl and solaris.
ret = reinterpret_cast<pid_t>(pthread_self());
#endif
#endif // defined(WEBRTC_POSIX)
RTC_DCHECK(ret);
return ret;
}
PlatformThreadRef CurrentThreadRef() {
#if defined(WEBRTC_WIN)
return GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
return pthread_self();
#endif
}
bool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {
#if defined(WEBRTC_WIN)
return a == b;
#elif defined(WEBRTC_POSIX)
return pthread_equal(a, b);
#endif
}
void SetCurrentThreadName(const char* name) {
#if defined(WEBRTC_WIN)
struct {
DWORD dwType;
LPCSTR szName;
DWORD dwThreadID;
DWORD dwFlags;
} threadname_info = {0x1000, name, static_cast<DWORD>(-1), 0};
__try {
::RaiseException(0x406D1388, 0, sizeof(threadname_info) / sizeof(DWORD),
reinterpret_cast<ULONG_PTR*>(&threadname_info));
} __except (EXCEPTION_EXECUTE_HANDLER) {
}
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)
prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name));
#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
pthread_setname_np(name);
#endif
}
namespace {
#if defined(WEBRTC_WIN)
void CALLBACK RaiseFlag(ULONG_PTR param) {
*reinterpret_cast<bool*>(param) = true;
}
#else
struct ThreadAttributes {
ThreadAttributes() { pthread_attr_init(&attr); }
~ThreadAttributes() { pthread_attr_destroy(&attr); }
pthread_attr_t* operator&() { return &attr; }
pthread_attr_t attr;
};
#endif // defined(WEBRTC_WIN)
}
PlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,
void* obj,
const char* thread_name)
: run_function_deprecated_(func),
obj_(obj),
name_(thread_name ? thread_name : "webrtc") {
RTC_DCHECK(func);
RTC_DCHECK(name_.length() < 64);
spawned_thread_checker_.DetachFromThread();
}
PlatformThread::PlatformThread(ThreadRunFunction func,
void* obj,
const char* thread_name,
ThreadPriority priority /*= kNormalPriority*/)
: run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
RTC_DCHECK(func);
RTC_DCHECK(!name_.empty());
// TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
RTC_DCHECK(name_.length() < 64);
spawned_thread_checker_.DetachFromThread();
}
PlatformThread::~PlatformThread() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
RTC_DCHECK(!thread_);
RTC_DCHECK(!thread_id_);
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
DWORD WINAPI PlatformThread::StartThread(void* param) {
// The GetLastError() function only returns valid results when it is called
// after a Win32 API function that returns a "failed" result. A crash dump
// contains the result from GetLastError() and to make sure it does not
// falsely report a Windows error we call SetLastError here.
::SetLastError(ERROR_SUCCESS);
static_cast<PlatformThread*>(param)->Run();
return 0;
}
#else
void* PlatformThread::StartThread(void* param) {
static_cast<PlatformThread*>(param)->Run();
return 0;
}
#endif // defined(WEBRTC_WIN)
void PlatformThread::Start() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(!thread_) << "Thread already started?";
#if defined(WEBRTC_WIN)
stop_ = false;
// See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
// Set the reserved stack stack size to 1M, which is the default on Windows
// and Linux.
thread_ = ::CreateThread(NULL, 1024 * 1024, &StartThread, this,
STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
RTC_CHECK(thread_) << "CreateThread failed";
RTC_DCHECK(thread_id_);
#else
ThreadAttributes attr;
// Set the stack stack size to 1M.
pthread_attr_setstacksize(&attr, 1024 * 1024);
RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
#endif // defined(WEBRTC_WIN)
}
bool PlatformThread::IsRunning() const {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
return thread_ != nullptr;
#else
return thread_ != 0;
#endif // defined(WEBRTC_WIN)
}
PlatformThreadRef PlatformThread::GetThreadRef() const {
#if defined(WEBRTC_WIN)
return thread_id_;
#else
return thread_;
#endif // defined(WEBRTC_WIN)
}
void PlatformThread::Stop() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
if (!IsRunning())
return;
#if defined(WEBRTC_WIN)
// Set stop_ to |true| on the worker thread.
bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
// Queuing the APC can fail if the thread is being terminated.
RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);
WaitForSingleObject(thread_, INFINITE);
CloseHandle(thread_);
thread_ = nullptr;
thread_id_ = 0;
#else
if (!run_function_)
RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
if (!run_function_)
AtomicOps::ReleaseStore(&stop_flag_, 0);
thread_ = 0;
#endif // defined(WEBRTC_WIN)
spawned_thread_checker_.DetachFromThread();
}
// TODO(tommi): Deprecate the loop behavior in PlatformThread.
// * Introduce a new callback type that returns void.
// * Remove potential for a busy loop in PlatformThread.
// * Delegate the responsibility for how to stop the thread, to the
// implementation that actually uses the thread.
// All implementations will need to be aware of how the thread should be stopped
// and encouraging a busy polling loop, can be costly in terms of power and cpu.
void PlatformThread::Run() {
// Attach the worker thread checker to this thread.
RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
rtc::SetCurrentThreadName(name_.c_str());
if (run_function_) {
SetPriority(priority_);
run_function_(obj_);
return;
}
// TODO(tommi): Delete the below.
#if !defined(WEBRTC_MAC) && !defined(WEBRTC_WIN)
const struct timespec ts_null = {0};
#endif
do {
// The interface contract of Start/Stop is that for a successful call to
// Start, there should be at least one call to the run function. So we
// call the function before checking |stop_|.
if (!run_function_deprecated_(obj_))
break;
#if defined(WEBRTC_WIN)
// Alertable sleep to permit RaiseFlag to run and update |stop_|.
SleepEx(0, true);
} while (!stop_);
#else
#if defined(WEBRTC_MAC)
sched_yield();
#else
nanosleep(&ts_null, nullptr);
#endif
} while (!AtomicOps::AcquireLoad(&stop_flag_));
#endif // defined(WEBRTC_WIN)
}
bool PlatformThread::SetPriority(ThreadPriority priority) {
#if RTC_DCHECK_IS_ON
if (run_function_) {
// The non-deprecated way of how this function gets called, is that it must
// be called on the worker thread itself.
RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
} else {
// In the case of deprecated use of this method, it must be called on the
// same thread as the PlatformThread object is constructed on.
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(IsRunning());
}
#endif
#if defined(WEBRTC_WIN)
return SetThreadPriority(thread_, priority) != FALSE;
#elif defined(__native_client__)
// Setting thread priorities is not supported in NaCl.
return true;
#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
// TODO(tommi): Switch to the same mechanism as Chromium uses for changing
// thread priorities.
return true;
#else
#ifdef WEBRTC_THREAD_RR
const int policy = SCHED_RR;
#else
const int policy = SCHED_FIFO;
#endif
const int min_prio = sched_get_priority_min(policy);
const int max_prio = sched_get_priority_max(policy);
if (min_prio == -1 || max_prio == -1) {
return false;
}
if (max_prio - min_prio <= 2)
return false;
// Convert webrtc priority to system priorities:
sched_param param;
const int top_prio = max_prio - 1;
const int low_prio = min_prio + 1;
switch (priority) {
case kLowPriority:
param.sched_priority = low_prio;
break;
case kNormalPriority:
// The -1 ensures that the kHighPriority is always greater or equal to
// kNormalPriority.
param.sched_priority = (low_prio + top_prio - 1) / 2;
break;
case kHighPriority:
param.sched_priority = std::max(top_prio - 2, low_prio);
break;
case kHighestPriority:
param.sched_priority = std::max(top_prio - 1, low_prio);
break;
case kRealtimePriority:
param.sched_priority = top_prio;
break;
}
return pthread_setschedparam(thread_, policy, ¶m) == 0;
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(IsRunning());
return QueueUserAPC(function, thread_, data) != FALSE;
}
#endif
} // namespace rtc
<commit_msg>Use sched_yield on all POSIX platforms in PlatformThread. (not only MacOS)<commit_after>/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/base/platform_thread.h"
#include "webrtc/base/atomicops.h"
#include "webrtc/base/checks.h"
#if defined(WEBRTC_LINUX)
#include <sys/prctl.h>
#include <sys/syscall.h>
#endif
namespace rtc {
PlatformThreadId CurrentThreadId() {
PlatformThreadId ret;
#if defined(WEBRTC_WIN)
ret = GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
ret = pthread_mach_thread_np(pthread_self());
#elif defined(WEBRTC_LINUX)
ret = syscall(__NR_gettid);
#elif defined(WEBRTC_ANDROID)
ret = gettid();
#else
// Default implementation for nacl and solaris.
ret = reinterpret_cast<pid_t>(pthread_self());
#endif
#endif // defined(WEBRTC_POSIX)
RTC_DCHECK(ret);
return ret;
}
PlatformThreadRef CurrentThreadRef() {
#if defined(WEBRTC_WIN)
return GetCurrentThreadId();
#elif defined(WEBRTC_POSIX)
return pthread_self();
#endif
}
bool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {
#if defined(WEBRTC_WIN)
return a == b;
#elif defined(WEBRTC_POSIX)
return pthread_equal(a, b);
#endif
}
void SetCurrentThreadName(const char* name) {
#if defined(WEBRTC_WIN)
struct {
DWORD dwType;
LPCSTR szName;
DWORD dwThreadID;
DWORD dwFlags;
} threadname_info = {0x1000, name, static_cast<DWORD>(-1), 0};
__try {
::RaiseException(0x406D1388, 0, sizeof(threadname_info) / sizeof(DWORD),
reinterpret_cast<ULONG_PTR*>(&threadname_info));
} __except (EXCEPTION_EXECUTE_HANDLER) {
}
#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)
prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name));
#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)
pthread_setname_np(name);
#endif
}
namespace {
#if defined(WEBRTC_WIN)
void CALLBACK RaiseFlag(ULONG_PTR param) {
*reinterpret_cast<bool*>(param) = true;
}
#else
struct ThreadAttributes {
ThreadAttributes() { pthread_attr_init(&attr); }
~ThreadAttributes() { pthread_attr_destroy(&attr); }
pthread_attr_t* operator&() { return &attr; }
pthread_attr_t attr;
};
#endif // defined(WEBRTC_WIN)
}
PlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,
void* obj,
const char* thread_name)
: run_function_deprecated_(func),
obj_(obj),
name_(thread_name ? thread_name : "webrtc") {
RTC_DCHECK(func);
RTC_DCHECK(name_.length() < 64);
spawned_thread_checker_.DetachFromThread();
}
PlatformThread::PlatformThread(ThreadRunFunction func,
void* obj,
const char* thread_name,
ThreadPriority priority /*= kNormalPriority*/)
: run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {
RTC_DCHECK(func);
RTC_DCHECK(!name_.empty());
// TODO(tommi): Consider lowering the limit to 15 (limit on Linux).
RTC_DCHECK(name_.length() < 64);
spawned_thread_checker_.DetachFromThread();
}
PlatformThread::~PlatformThread() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
RTC_DCHECK(!thread_);
RTC_DCHECK(!thread_id_);
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
DWORD WINAPI PlatformThread::StartThread(void* param) {
// The GetLastError() function only returns valid results when it is called
// after a Win32 API function that returns a "failed" result. A crash dump
// contains the result from GetLastError() and to make sure it does not
// falsely report a Windows error we call SetLastError here.
::SetLastError(ERROR_SUCCESS);
static_cast<PlatformThread*>(param)->Run();
return 0;
}
#else
void* PlatformThread::StartThread(void* param) {
static_cast<PlatformThread*>(param)->Run();
return 0;
}
#endif // defined(WEBRTC_WIN)
void PlatformThread::Start() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(!thread_) << "Thread already started?";
#if defined(WEBRTC_WIN)
stop_ = false;
// See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.
// Set the reserved stack stack size to 1M, which is the default on Windows
// and Linux.
thread_ = ::CreateThread(NULL, 1024 * 1024, &StartThread, this,
STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);
RTC_CHECK(thread_) << "CreateThread failed";
RTC_DCHECK(thread_id_);
#else
ThreadAttributes attr;
// Set the stack stack size to 1M.
pthread_attr_setstacksize(&attr, 1024 * 1024);
RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));
#endif // defined(WEBRTC_WIN)
}
bool PlatformThread::IsRunning() const {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
#if defined(WEBRTC_WIN)
return thread_ != nullptr;
#else
return thread_ != 0;
#endif // defined(WEBRTC_WIN)
}
PlatformThreadRef PlatformThread::GetThreadRef() const {
#if defined(WEBRTC_WIN)
return thread_id_;
#else
return thread_;
#endif // defined(WEBRTC_WIN)
}
void PlatformThread::Stop() {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
if (!IsRunning())
return;
#if defined(WEBRTC_WIN)
// Set stop_ to |true| on the worker thread.
bool queued = QueueAPC(&RaiseFlag, reinterpret_cast<ULONG_PTR>(&stop_));
// Queuing the APC can fail if the thread is being terminated.
RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);
WaitForSingleObject(thread_, INFINITE);
CloseHandle(thread_);
thread_ = nullptr;
thread_id_ = 0;
#else
if (!run_function_)
RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));
RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));
if (!run_function_)
AtomicOps::ReleaseStore(&stop_flag_, 0);
thread_ = 0;
#endif // defined(WEBRTC_WIN)
spawned_thread_checker_.DetachFromThread();
}
// TODO(tommi): Deprecate the loop behavior in PlatformThread.
// * Introduce a new callback type that returns void.
// * Remove potential for a busy loop in PlatformThread.
// * Delegate the responsibility for how to stop the thread, to the
// implementation that actually uses the thread.
// All implementations will need to be aware of how the thread should be stopped
// and encouraging a busy polling loop, can be costly in terms of power and cpu.
void PlatformThread::Run() {
// Attach the worker thread checker to this thread.
RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
rtc::SetCurrentThreadName(name_.c_str());
if (run_function_) {
SetPriority(priority_);
run_function_(obj_);
return;
}
// TODO(tommi): Delete the below.
do {
// The interface contract of Start/Stop is that for a successful call to
// Start, there should be at least one call to the run function. So we
// call the function before checking |stop_|.
if (!run_function_deprecated_(obj_))
break;
#if defined(WEBRTC_WIN)
// Alertable sleep to permit RaiseFlag to run and update |stop_|.
SleepEx(0, true);
} while (!stop_);
#else
sched_yield();
} while (!AtomicOps::AcquireLoad(&stop_flag_));
#endif // defined(WEBRTC_WIN)
}
bool PlatformThread::SetPriority(ThreadPriority priority) {
#if RTC_DCHECK_IS_ON
if (run_function_) {
// The non-deprecated way of how this function gets called, is that it must
// be called on the worker thread itself.
RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());
} else {
// In the case of deprecated use of this method, it must be called on the
// same thread as the PlatformThread object is constructed on.
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(IsRunning());
}
#endif
#if defined(WEBRTC_WIN)
return SetThreadPriority(thread_, priority) != FALSE;
#elif defined(__native_client__)
// Setting thread priorities is not supported in NaCl.
return true;
#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)
// TODO(tommi): Switch to the same mechanism as Chromium uses for changing
// thread priorities.
return true;
#else
#ifdef WEBRTC_THREAD_RR
const int policy = SCHED_RR;
#else
const int policy = SCHED_FIFO;
#endif
const int min_prio = sched_get_priority_min(policy);
const int max_prio = sched_get_priority_max(policy);
if (min_prio == -1 || max_prio == -1) {
return false;
}
if (max_prio - min_prio <= 2)
return false;
// Convert webrtc priority to system priorities:
sched_param param;
const int top_prio = max_prio - 1;
const int low_prio = min_prio + 1;
switch (priority) {
case kLowPriority:
param.sched_priority = low_prio;
break;
case kNormalPriority:
// The -1 ensures that the kHighPriority is always greater or equal to
// kNormalPriority.
param.sched_priority = (low_prio + top_prio - 1) / 2;
break;
case kHighPriority:
param.sched_priority = std::max(top_prio - 2, low_prio);
break;
case kHighestPriority:
param.sched_priority = std::max(top_prio - 1, low_prio);
break;
case kRealtimePriority:
param.sched_priority = top_prio;
break;
}
return pthread_setschedparam(thread_, policy, ¶m) == 0;
#endif // defined(WEBRTC_WIN)
}
#if defined(WEBRTC_WIN)
bool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {
RTC_DCHECK(thread_checker_.CalledOnValidThread());
RTC_DCHECK(IsRunning());
return QueueUserAPC(function, thread_, data) != FALSE;
}
#endif
} // namespace rtc
<|endoftext|>
|
<commit_before>#include "telnetpp/routing_visitor.hpp"
#include "telnetpp/options/naws/client.hpp"
#include "telnetpp/options/naws.hpp"
#include "telnetpp/protocol.hpp"
#include "expect_elements.hpp"
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
class routing_visitor_test : public CppUnit::TestFixture
{
public :
CPPUNIT_TEST_SUITE(routing_visitor_test);
CPPUNIT_TEST(text_routes_to_text_function);
CPPUNIT_TEST(text_does_not_route_to_null_function);
CPPUNIT_TEST(command_routes_to_command_router);
CPPUNIT_TEST(negotiation_routes_to_negotiation_router);
CPPUNIT_TEST(subnegotiation_routes_to_subnegotiation_router);
CPPUNIT_TEST(subnegotiation_accumulates_responses);
CPPUNIT_TEST_SUITE_END();
private :
void text_routes_to_text_function();
void text_does_not_route_to_null_function();
void command_routes_to_command_router();
void negotiation_routes_to_negotiation_router();
void subnegotiation_routes_to_subnegotiation_router();
void subnegotiation_accumulates_responses();
};
CPPUNIT_TEST_SUITE_REGISTRATION(routing_visitor_test);
void routing_visitor_test::text_routes_to_text_function()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
std::string text;
std::string expected_text = "expected text";
telnetpp::routing_visitor visitor(
[&text](auto &&new_text) -> std::vector<telnetpp::token>
{
text = new_text;
return {};
},
nullptr,
cmd_router,
neg_router,
sub_router);
telnetpp::element text_token(expected_text);
boost::apply_visitor(visitor, text_token);
CPPUNIT_ASSERT_EQUAL(expected_text, text);
}
void routing_visitor_test::text_does_not_route_to_null_function()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
telnetpp::routing_visitor visitor(
nullptr,
nullptr,
cmd_router,
neg_router,
sub_router);
telnetpp::token text_token(telnetpp::element("text token"));
boost::apply_visitor(visitor, text_token);
}
void routing_visitor_test::command_routes_to_command_router()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
telnetpp::command cmd(0x00);
telnetpp::command expected_command(telnetpp::ayt);
cmd_router.register_route(expected_command,
[&cmd](auto &&new_cmd) -> std::vector<telnetpp::token>
{
cmd = new_cmd;
return {};
});
telnetpp::routing_visitor visitor(
[](auto &&) -> std::vector<telnetpp::token>
{
return {};
},
nullptr,
cmd_router,
neg_router,
sub_router);
telnetpp::element cmd_token(expected_command);
boost::apply_visitor(visitor, cmd_token);
CPPUNIT_ASSERT_EQUAL(expected_command, cmd);
}
void routing_visitor_test::negotiation_routes_to_negotiation_router()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
telnetpp::options::naws::client client;
client.activate();
bool state_changed = false;
client.on_state_changed.connect(
[&state_changed]() -> std::vector<telnetpp::token>
{
state_changed = true;
return {};
});
telnetpp::register_client_option(client, neg_router, sub_router);
telnetpp::routing_visitor visitor(
[](auto &&) -> std::vector<telnetpp::token>
{
return {};
},
nullptr,
cmd_router,
neg_router,
sub_router);
telnetpp::element neg_token(
telnetpp::negotiation(
telnetpp::will, telnetpp::options::naws::option));
boost::apply_visitor(visitor, neg_token);
CPPUNIT_ASSERT_EQUAL(true, state_changed);
CPPUNIT_ASSERT_EQUAL(true, client.is_active());
}
void routing_visitor_test::subnegotiation_routes_to_subnegotiation_router()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
telnetpp::options::naws::client client;
client.activate();
client.negotiate(telnetpp::will);
telnetpp::u16 width = 0;
telnetpp::u16 height = 0;
client.on_window_size_changed.connect(
[&width, &height](auto &&new_width, auto &&new_height)
-> std::vector<telnetpp::token>
{
width = new_width;
height = new_height;
return {};
});
telnetpp::register_route_from_subnegotiation_to_option(
sub_router, client);
telnetpp::routing_visitor visitor(
[](auto &&) -> std::vector<telnetpp::token>
{
return {};
},
nullptr,
cmd_router,
neg_router,
sub_router);
telnetpp::element sub_token(
telnetpp::subnegotiation(
telnetpp::options::naws::option,
{0, 80, 0, 24}));
boost::apply_visitor(visitor, sub_token);
telnetpp::u16 expected_width = 80;
telnetpp::u16 expected_height = 24;
CPPUNIT_ASSERT_EQUAL(expected_width, width);
CPPUNIT_ASSERT_EQUAL(expected_height, height);
}
void routing_visitor_test::subnegotiation_accumulates_responses()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
telnetpp::options::naws::client client;
telnetpp::register_client_option(client, neg_router, sub_router);
client.on_window_size_changed.connect(
[&client](auto &&, auto &&)
{
return client.deactivate();
});
telnetpp::routing_visitor visitor(
[](auto &&) -> std::vector<telnetpp::token>
{
return {};
},
nullptr,
cmd_router,
neg_router,
sub_router);
client.activate();
telnetpp::element do_negotiation_token(
telnetpp::negotiation(telnetpp::will, telnetpp::options::naws::option));
expect_elements(
{},
boost::apply_visitor(visitor, do_negotiation_token));
telnetpp::element sub_token(
telnetpp::subnegotiation(
telnetpp::options::naws::option,
{0, 80, 0, 24}));
expect_elements({
telnetpp::negotiation(
telnetpp::dont, telnetpp::options::naws::option)
},
boost::apply_visitor(visitor, sub_token));
}
<commit_msg>Added a routing test for arbitrary objects.<commit_after>#include "telnetpp/routing_visitor.hpp"
#include "telnetpp/options/naws/client.hpp"
#include "telnetpp/options/naws.hpp"
#include "telnetpp/protocol.hpp"
#include "expect_elements.hpp"
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
class routing_visitor_test : public CppUnit::TestFixture
{
public :
CPPUNIT_TEST_SUITE(routing_visitor_test);
CPPUNIT_TEST(text_routes_to_text_function);
CPPUNIT_TEST(text_does_not_route_to_null_function);
CPPUNIT_TEST(command_routes_to_command_router);
CPPUNIT_TEST(negotiation_routes_to_negotiation_router);
CPPUNIT_TEST(subnegotiation_routes_to_subnegotiation_router);
CPPUNIT_TEST(subnegotiation_accumulates_responses);
CPPUNIT_TEST(arbitrary_object_routes_to_pass_through);
CPPUNIT_TEST_SUITE_END();
private :
void text_routes_to_text_function();
void text_does_not_route_to_null_function();
void command_routes_to_command_router();
void negotiation_routes_to_negotiation_router();
void subnegotiation_routes_to_subnegotiation_router();
void subnegotiation_accumulates_responses();
void arbitrary_object_routes_to_pass_through();
};
CPPUNIT_TEST_SUITE_REGISTRATION(routing_visitor_test);
void routing_visitor_test::text_routes_to_text_function()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
std::string text;
std::string expected_text = "expected text";
telnetpp::routing_visitor visitor(
[&text](auto &&new_text) -> std::vector<telnetpp::token>
{
text = new_text;
return {};
},
nullptr,
cmd_router,
neg_router,
sub_router);
telnetpp::element text_token(expected_text);
boost::apply_visitor(visitor, text_token);
CPPUNIT_ASSERT_EQUAL(expected_text, text);
}
void routing_visitor_test::text_does_not_route_to_null_function()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
telnetpp::routing_visitor visitor(
nullptr,
nullptr,
cmd_router,
neg_router,
sub_router);
telnetpp::token text_token(telnetpp::element("text token"));
boost::apply_visitor(visitor, text_token);
}
void routing_visitor_test::command_routes_to_command_router()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
telnetpp::command cmd(0x00);
telnetpp::command expected_command(telnetpp::ayt);
cmd_router.register_route(expected_command,
[&cmd](auto &&new_cmd) -> std::vector<telnetpp::token>
{
cmd = new_cmd;
return {};
});
telnetpp::routing_visitor visitor(
[](auto &&) -> std::vector<telnetpp::token>
{
return {};
},
nullptr,
cmd_router,
neg_router,
sub_router);
telnetpp::element cmd_token(expected_command);
boost::apply_visitor(visitor, cmd_token);
CPPUNIT_ASSERT_EQUAL(expected_command, cmd);
}
void routing_visitor_test::negotiation_routes_to_negotiation_router()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
telnetpp::options::naws::client client;
client.activate();
bool state_changed = false;
client.on_state_changed.connect(
[&state_changed]() -> std::vector<telnetpp::token>
{
state_changed = true;
return {};
});
telnetpp::register_client_option(client, neg_router, sub_router);
telnetpp::routing_visitor visitor(
[](auto &&) -> std::vector<telnetpp::token>
{
return {};
},
nullptr,
cmd_router,
neg_router,
sub_router);
telnetpp::element neg_token(
telnetpp::negotiation(
telnetpp::will, telnetpp::options::naws::option));
boost::apply_visitor(visitor, neg_token);
CPPUNIT_ASSERT_EQUAL(true, state_changed);
CPPUNIT_ASSERT_EQUAL(true, client.is_active());
}
void routing_visitor_test::subnegotiation_routes_to_subnegotiation_router()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
telnetpp::options::naws::client client;
client.activate();
client.negotiate(telnetpp::will);
telnetpp::u16 width = 0;
telnetpp::u16 height = 0;
client.on_window_size_changed.connect(
[&width, &height](auto &&new_width, auto &&new_height)
-> std::vector<telnetpp::token>
{
width = new_width;
height = new_height;
return {};
});
telnetpp::register_route_from_subnegotiation_to_option(
sub_router, client);
telnetpp::routing_visitor visitor(
[](auto &&) -> std::vector<telnetpp::token>
{
return {};
},
nullptr,
cmd_router,
neg_router,
sub_router);
telnetpp::element sub_token(
telnetpp::subnegotiation(
telnetpp::options::naws::option,
{0, 80, 0, 24}));
boost::apply_visitor(visitor, sub_token);
telnetpp::u16 expected_width = 80;
telnetpp::u16 expected_height = 24;
CPPUNIT_ASSERT_EQUAL(expected_width, width);
CPPUNIT_ASSERT_EQUAL(expected_height, height);
}
void routing_visitor_test::subnegotiation_accumulates_responses()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
telnetpp::options::naws::client client;
telnetpp::register_client_option(client, neg_router, sub_router);
client.on_window_size_changed.connect(
[&client](auto &&, auto &&)
{
return client.deactivate();
});
telnetpp::routing_visitor visitor(
[](auto &&) -> std::vector<telnetpp::token>
{
return {};
},
nullptr,
cmd_router,
neg_router,
sub_router);
client.activate();
telnetpp::element do_negotiation_token(
telnetpp::negotiation(telnetpp::will, telnetpp::options::naws::option));
expect_elements(
{},
boost::apply_visitor(visitor, do_negotiation_token));
telnetpp::element sub_token(
telnetpp::subnegotiation(
telnetpp::options::naws::option,
{0, 80, 0, 24}));
expect_elements({
telnetpp::negotiation(
telnetpp::dont, telnetpp::options::naws::option)
},
boost::apply_visitor(visitor, sub_token));
}
void routing_visitor_test::arbitrary_object_routes_to_pass_through()
{
telnetpp::command_router cmd_router;
telnetpp::negotiation_router neg_router;
telnetpp::subnegotiation_router sub_router;
telnetpp::options::naws::client client;
boost::any any;
telnetpp::routing_visitor visitor(
nullptr,
[&any](auto &&object) -> std::vector<telnetpp::token>
{
any = object;
return {};
},
cmd_router,
neg_router,
sub_router);
std::string test_string = "TEST";
telnetpp::token test_token(boost::any{test_string});
boost::apply_visitor(visitor, test_token);
CPPUNIT_ASSERT_EQUAL(
test_string, boost::any_cast<std::string const&>(any));
}<|endoftext|>
|
<commit_before>// Copyright (c) 2021 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "SessionSetup/TargetLabel.h"
#include <QAction>
#include <QDesktopServices>
#include <QImage>
#include <QMenu>
#include <QPalette>
#include <QPixmap>
#include <QUrl>
#include <memory>
#include <optional>
#include "SessionSetup/DoubleClickableLabel.h"
#include "ui_TargetLabel.h"
namespace {
const QColor kDefaultTextColor{"white"};
const QColor kGreenColor{"#66BB6A"};
const QColor kOrangeColor{"orange"};
const QColor kRedColor{"#E64646"};
const QString kLocalhostName{"localhost"};
QPixmap ColorizeIcon(const QPixmap& pixmap, const QColor& color) {
QImage colored_image = pixmap.toImage();
for (int y = 0; y < colored_image.height(); y++) {
for (int x = 0; x < colored_image.width(); x++) {
QColor color_with_alpha = color;
color_with_alpha.setAlpha(colored_image.pixelColor(x, y).alpha());
colored_image.setPixelColor(x, y, color_with_alpha);
}
}
return QPixmap::fromImage(std::move(colored_image));
}
QPixmap GetGreenConnectedIcon() {
const static QPixmap kGreenConnectedIcon =
ColorizeIcon(QPixmap{":/actions/connected"}, kGreenColor);
return kGreenConnectedIcon;
}
QPixmap GetOrangeDisconnectedIcon() {
const static QPixmap kOrangeDisconnectedIcon =
ColorizeIcon(QPixmap{":/actions/alert"}, kOrangeColor);
return kOrangeDisconnectedIcon;
}
QPixmap GetRedDisconnectedIcon() {
const static QPixmap kRedDisconnectedIcon =
ColorizeIcon(QPixmap{":/actions/disconnected"}, kRedColor);
return kRedDisconnectedIcon;
}
} // namespace
namespace orbit_session_setup {
namespace fs = std::filesystem;
TargetLabel::TargetLabel(QWidget* parent)
: QWidget(parent), ui_(std::make_unique<Ui::TargetLabel>()) {
ui_->setupUi(this);
QObject::connect(ui_->fileLabel, &DoubleClickableLabel::DoubleClicked, this,
&TargetLabel::OpenContainingFolder);
QObject::connect(ui_->fileLabel, &DoubleClickableLabel::customContextMenuRequested, this,
[this](const QPoint& pos) {
QAction action{QIcon(":/actions/folder"), "Open Containing Folder", this};
QObject::connect(&action, &QAction::triggered, this,
&TargetLabel::OpenContainingFolder);
QMenu menu;
menu.addAction(&action);
menu.exec(mapToGlobal(pos));
});
}
TargetLabel::~TargetLabel() = default;
void TargetLabel::ChangeToFileTarget(const FileTarget& file_target) {
ChangeToFileTarget(file_target.GetCaptureFilePath());
}
void TargetLabel::SetFile(const std::filesystem::path& file_path) {
file_path_ = file_path;
ui_->fileLabel->setText(QString::fromStdString(file_path.filename().string()));
ui_->fileLabel->setToolTip(QString::fromStdString(file_path.string()));
ui_->fileLabel->setVisible(true);
emit SizeChanged();
}
void TargetLabel::ChangeToFileTarget(const fs::path& path) {
Clear();
SetFile(path);
ui_->targetLabel->setVisible(false);
emit SizeChanged();
}
void TargetLabel::ChangeToStadiaTarget(const StadiaTarget& stadia_target) {
ChangeToStadiaTarget(*stadia_target.GetProcess(), stadia_target.GetConnection()->GetInstance());
}
void TargetLabel::ChangeToStadiaTarget(const orbit_client_data::ProcessData& process,
const orbit_ggp::Instance& instance) {
ChangeToStadiaTarget(QString::fromStdString(process.name()), process.cpu_usage(),
instance.display_name);
}
void TargetLabel::ChangeToStadiaTarget(const QString& process_name, double cpu_usage,
const QString& instance_name) {
Clear();
process_ = process_name;
machine_ = instance_name;
SetProcessCpuUsageInPercent(cpu_usage);
ui_->targetLabel->setVisible(true);
ui_->fileLabel->setVisible(false);
}
void TargetLabel::ChangeToLocalTarget(const LocalTarget& local_target) {
ChangeToLocalTarget(*local_target.GetProcess());
}
void TargetLabel::ChangeToLocalTarget(const orbit_client_data::ProcessData& process) {
ChangeToLocalTarget(QString::fromStdString(process.name()), process.cpu_usage());
}
void TargetLabel::ChangeToLocalTarget(const QString& process_name, double cpu_usage) {
Clear();
process_ = process_name;
machine_ = kLocalhostName;
SetProcessCpuUsageInPercent(cpu_usage);
ui_->targetLabel->setVisible(true);
ui_->fileLabel->setVisible(false);
}
bool TargetLabel::SetProcessCpuUsageInPercent(double cpu_usage) {
if (process_.isEmpty() || machine_.isEmpty()) return false;
ui_->targetLabel->setText(
QString{"%1 (%2%) @ %3"}.arg(process_).arg(cpu_usage, 0, 'f', 0).arg(machine_));
SetColor(kGreenColor);
setToolTip({});
SetIcon(IconType::kGreenConnectedIcon);
emit SizeChanged();
return true;
}
bool TargetLabel::SetProcessEnded() {
if (process_.isEmpty() || machine_.isEmpty()) return false;
ui_->targetLabel->setText(QString{"%1 @ %2"}.arg(process_, machine_));
SetColor(kOrangeColor);
setToolTip("The process ended.");
SetIcon(IconType::kOrangeDisconnectedIcon);
emit SizeChanged();
return true;
}
bool TargetLabel::SetConnectionDead(const QString& error_message) {
if (process_.isEmpty() || machine_.isEmpty()) return false;
ui_->targetLabel->setText(QString{"%1 @ %2"}.arg(process_, machine_));
SetColor(kRedColor);
setToolTip(error_message);
SetIcon(IconType::kRedDisconnectedIcon);
emit SizeChanged();
return true;
}
void TargetLabel::Clear() {
process_ = "";
machine_ = "";
file_path_.reset();
ui_->fileLabel->setText({});
ui_->targetLabel->setText({});
ui_->fileLabel->setVisible(false);
ui_->targetLabel->setVisible(false);
SetColor(kDefaultTextColor);
setToolTip({});
ClearIcon();
emit SizeChanged();
}
QColor TargetLabel::GetTargetColor() const {
return ui_->targetLabel->palette().color(QPalette::WindowText);
}
QString TargetLabel::GetTargetText() const { return ui_->targetLabel->text(); }
QString TargetLabel::GetFileText() const { return ui_->fileLabel->text(); }
void TargetLabel::SetColor(const QColor& color) {
// This class is used in a QFrame and in QMenuBar. To make the coloring work in a QFrame the
// QColorRole QPalette::WindowText needs to be set. For QMenuBar QPalette::ButtonText needs to be
// set.
QPalette palette{};
palette.setColor(QPalette::WindowText, color);
palette.setColor(QPalette::ButtonText, color);
ui_->targetLabel->setPalette(palette);
}
void TargetLabel::SetIcon(IconType icon_type) {
icon_type_ = icon_type;
switch (icon_type) {
case IconType::kGreenConnectedIcon:
ui_->iconLabel->setPixmap(GetGreenConnectedIcon());
break;
case IconType::kOrangeDisconnectedIcon:
ui_->iconLabel->setPixmap(GetOrangeDisconnectedIcon());
break;
case IconType::kRedDisconnectedIcon:
ui_->iconLabel->setPixmap(GetRedDisconnectedIcon());
break;
}
ui_->iconLabel->setVisible(true);
}
void TargetLabel::ClearIcon() {
icon_type_ = std::nullopt;
ui_->iconLabel->setPixmap(QPixmap{});
ui_->iconLabel->setVisible(false);
}
void TargetLabel::OpenContainingFolder() {
if (!file_path_.has_value()) return;
QUrl url = QUrl::fromLocalFile(QString::fromStdString(file_path_->parent_path().string()));
if (!QDesktopServices::openUrl(url)) {
ERROR("Opening containing folder of \"%s\"", file_path_->string());
}
}
} // namespace orbit_session_setup
<commit_msg>TargetLabel is no longer updated unless needed (#2812)<commit_after>// Copyright (c) 2021 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "SessionSetup/TargetLabel.h"
#include <QAction>
#include <QDesktopServices>
#include <QImage>
#include <QMenu>
#include <QPalette>
#include <QPixmap>
#include <QUrl>
#include <memory>
#include <optional>
#include "SessionSetup/DoubleClickableLabel.h"
#include "ui_TargetLabel.h"
namespace {
const QColor kDefaultTextColor{"white"};
const QColor kGreenColor{"#66BB6A"};
const QColor kOrangeColor{"orange"};
const QColor kRedColor{"#E64646"};
const QString kLocalhostName{"localhost"};
QPixmap ColorizeIcon(const QPixmap& pixmap, const QColor& color) {
QImage colored_image = pixmap.toImage();
for (int y = 0; y < colored_image.height(); y++) {
for (int x = 0; x < colored_image.width(); x++) {
QColor color_with_alpha = color;
color_with_alpha.setAlpha(colored_image.pixelColor(x, y).alpha());
colored_image.setPixelColor(x, y, color_with_alpha);
}
}
return QPixmap::fromImage(std::move(colored_image));
}
QPixmap GetGreenConnectedIcon() {
const static QPixmap kGreenConnectedIcon =
ColorizeIcon(QPixmap{":/actions/connected"}, kGreenColor);
return kGreenConnectedIcon;
}
QPixmap GetOrangeDisconnectedIcon() {
const static QPixmap kOrangeDisconnectedIcon =
ColorizeIcon(QPixmap{":/actions/alert"}, kOrangeColor);
return kOrangeDisconnectedIcon;
}
QPixmap GetRedDisconnectedIcon() {
const static QPixmap kRedDisconnectedIcon =
ColorizeIcon(QPixmap{":/actions/disconnected"}, kRedColor);
return kRedDisconnectedIcon;
}
} // namespace
namespace orbit_session_setup {
namespace fs = std::filesystem;
TargetLabel::TargetLabel(QWidget* parent)
: QWidget(parent), ui_(std::make_unique<Ui::TargetLabel>()) {
ui_->setupUi(this);
QObject::connect(ui_->fileLabel, &DoubleClickableLabel::DoubleClicked, this,
&TargetLabel::OpenContainingFolder);
QObject::connect(ui_->fileLabel, &DoubleClickableLabel::customContextMenuRequested, this,
[this](const QPoint& pos) {
QAction action{QIcon(":/actions/folder"), "Open Containing Folder", this};
QObject::connect(&action, &QAction::triggered, this,
&TargetLabel::OpenContainingFolder);
QMenu menu;
menu.addAction(&action);
menu.exec(mapToGlobal(pos));
});
}
TargetLabel::~TargetLabel() = default;
void TargetLabel::ChangeToFileTarget(const FileTarget& file_target) {
ChangeToFileTarget(file_target.GetCaptureFilePath());
}
void TargetLabel::SetFile(const std::filesystem::path& file_path) {
// Without this, the size of the target label is not correctly updated when a capture is opened
// directly from the connection window. It's unclear why this happens, might be related to
// multiple `SizeChanged` signals being emitted while the main window is still being shown.
if (file_path_ == file_path) return;
file_path_ = file_path;
ui_->fileLabel->setText(QString::fromStdString(file_path.filename().string()));
ui_->fileLabel->setToolTip(QString::fromStdString(file_path.string()));
ui_->fileLabel->setVisible(true);
emit SizeChanged();
}
void TargetLabel::ChangeToFileTarget(const fs::path& path) {
Clear();
SetFile(path);
ui_->targetLabel->setVisible(false);
emit SizeChanged();
}
void TargetLabel::ChangeToStadiaTarget(const StadiaTarget& stadia_target) {
ChangeToStadiaTarget(*stadia_target.GetProcess(), stadia_target.GetConnection()->GetInstance());
}
void TargetLabel::ChangeToStadiaTarget(const orbit_client_data::ProcessData& process,
const orbit_ggp::Instance& instance) {
ChangeToStadiaTarget(QString::fromStdString(process.name()), process.cpu_usage(),
instance.display_name);
}
void TargetLabel::ChangeToStadiaTarget(const QString& process_name, double cpu_usage,
const QString& instance_name) {
Clear();
process_ = process_name;
machine_ = instance_name;
SetProcessCpuUsageInPercent(cpu_usage);
ui_->targetLabel->setVisible(true);
ui_->fileLabel->setVisible(false);
}
void TargetLabel::ChangeToLocalTarget(const LocalTarget& local_target) {
ChangeToLocalTarget(*local_target.GetProcess());
}
void TargetLabel::ChangeToLocalTarget(const orbit_client_data::ProcessData& process) {
ChangeToLocalTarget(QString::fromStdString(process.name()), process.cpu_usage());
}
void TargetLabel::ChangeToLocalTarget(const QString& process_name, double cpu_usage) {
Clear();
process_ = process_name;
machine_ = kLocalhostName;
SetProcessCpuUsageInPercent(cpu_usage);
ui_->targetLabel->setVisible(true);
ui_->fileLabel->setVisible(false);
}
bool TargetLabel::SetProcessCpuUsageInPercent(double cpu_usage) {
if (process_.isEmpty() || machine_.isEmpty()) return false;
ui_->targetLabel->setText(
QString{"%1 (%2%) @ %3"}.arg(process_).arg(cpu_usage, 0, 'f', 0).arg(machine_));
SetColor(kGreenColor);
setToolTip({});
SetIcon(IconType::kGreenConnectedIcon);
emit SizeChanged();
return true;
}
bool TargetLabel::SetProcessEnded() {
if (process_.isEmpty() || machine_.isEmpty()) return false;
ui_->targetLabel->setText(QString{"%1 @ %2"}.arg(process_, machine_));
SetColor(kOrangeColor);
setToolTip("The process ended.");
SetIcon(IconType::kOrangeDisconnectedIcon);
emit SizeChanged();
return true;
}
bool TargetLabel::SetConnectionDead(const QString& error_message) {
if (process_.isEmpty() || machine_.isEmpty()) return false;
ui_->targetLabel->setText(QString{"%1 @ %2"}.arg(process_, machine_));
SetColor(kRedColor);
setToolTip(error_message);
SetIcon(IconType::kRedDisconnectedIcon);
emit SizeChanged();
return true;
}
void TargetLabel::Clear() {
process_ = "";
machine_ = "";
file_path_.reset();
ui_->fileLabel->setText({});
ui_->targetLabel->setText({});
ui_->fileLabel->setVisible(false);
ui_->targetLabel->setVisible(false);
SetColor(kDefaultTextColor);
setToolTip({});
ClearIcon();
emit SizeChanged();
}
QColor TargetLabel::GetTargetColor() const {
return ui_->targetLabel->palette().color(QPalette::WindowText);
}
QString TargetLabel::GetTargetText() const { return ui_->targetLabel->text(); }
QString TargetLabel::GetFileText() const { return ui_->fileLabel->text(); }
void TargetLabel::SetColor(const QColor& color) {
// This class is used in a QFrame and in QMenuBar. To make the coloring work in a QFrame the
// QColorRole QPalette::WindowText needs to be set. For QMenuBar QPalette::ButtonText needs to be
// set.
QPalette palette{};
palette.setColor(QPalette::WindowText, color);
palette.setColor(QPalette::ButtonText, color);
ui_->targetLabel->setPalette(palette);
}
void TargetLabel::SetIcon(IconType icon_type) {
icon_type_ = icon_type;
switch (icon_type) {
case IconType::kGreenConnectedIcon:
ui_->iconLabel->setPixmap(GetGreenConnectedIcon());
break;
case IconType::kOrangeDisconnectedIcon:
ui_->iconLabel->setPixmap(GetOrangeDisconnectedIcon());
break;
case IconType::kRedDisconnectedIcon:
ui_->iconLabel->setPixmap(GetRedDisconnectedIcon());
break;
}
ui_->iconLabel->setVisible(true);
}
void TargetLabel::ClearIcon() {
icon_type_ = std::nullopt;
ui_->iconLabel->setPixmap(QPixmap{});
ui_->iconLabel->setVisible(false);
}
void TargetLabel::OpenContainingFolder() {
if (!file_path_.has_value()) return;
QUrl url = QUrl::fromLocalFile(QString::fromStdString(file_path_->parent_path().string()));
if (!QDesktopServices::openUrl(url)) {
ERROR("Opening containing folder of \"%s\"", file_path_->string());
}
}
} // namespace orbit_session_setup
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2014-2015 Alexandr Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
*/
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonDocument>
#include "GeneratorNG.hpp"
enum StatusCode {
NoError,
InvalidAction,
InvalidArgument,
SchemaReadError,
NetworkError,
ServerError,
FileAccessError
};
enum SchemaFormat {
JsonFormat,
TextFormat,
};
/* Replacing helper */
bool replaceSection(const QString &fileName, const QString &startMarker, const QString &endMarker, const QString &newContent)
{
QFile fileToProcess(fileName);
if (!fileToProcess.open(QIODevice::ReadOnly))
return false;
QString fileContent = fileToProcess.readAll();
fileToProcess.close();
bool winNewLines = fileContent.indexOf(QLatin1String("\r\n")) > 0;
if (winNewLines) {
fileContent.replace(QLatin1String("\r\n"), QLatin1String("\n"));
}
int startPos = fileContent.indexOf(startMarker);
int endPos = fileContent.indexOf(endMarker);
if (startPos >= 0) {
if (endPos < 0) {
printf("There is only start marker in the file %s. Error.\n", fileName.toLocal8Bit().constData());
return false;
}
endPos += endMarker.length();
} else {
return false;
}
const QString previousContent = fileContent.mid(startPos, endPos - startPos);
if (previousContent == startMarker + newContent + endMarker) {
printf("Nothing to do: new and previous contents are exactly same.\n");
return true;
}
fileContent.remove(startPos, endPos - startPos);
fileContent.insert(startPos, startMarker + newContent + endMarker);
if (!fileToProcess.open(QIODevice::WriteOnly)) {
printf("Can not write file: %s.\n", fileName.toLocal8Bit().constData());
return false;
}
if (winNewLines) {
fileContent.replace(QLatin1String("\n"), QLatin1String("\r\n"));
}
fileToProcess.write(fileContent.toLatin1());
fileToProcess.close();
printf("Replacing is done.\n");
return true;
}
bool replacingHelper(const QString &fileName, int spacing, const QString &marker, const QString &newContent)
{
const QString space(spacing, QChar(' '));
if (!replaceSection(fileName,
QString("%1// Generated %2\n").arg(space).arg(marker),
QString("%1// End of generated %2\n").arg(space).arg(marker), newContent)) {
printf("Can not update file %s with marker %s.\n", fileName.toLatin1().constData(), marker.toLatin1().constData());
return false;
} else {
return true;
}
}
/* End of replacing helper */
void debugType(const TLType &type)
{
qDebug() << type.name;
foreach (const TLSubType &subType, type.subTypes) {
qDebug() << " " << subType.name;
foreach (const TLParam &member, subType.members) {
qDebug() << " " << member.type << member.name;
}
}
}
StatusCode fetchJson(const QString &specFileName)
{
QEventLoop eventLoop;
QNetworkAccessManager mgr;
QObject::connect(&mgr, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);
QNetworkRequest req(QUrl(QLatin1String("https://core.telegram.org/schema/json")));
QNetworkReply *reply = mgr.get(req);
eventLoop.exec();
if (reply->error() != QNetworkReply::NoError) {
delete reply;
return NetworkError;
}
QByteArray data = reply->readAll();
delete reply;
if (data.isEmpty()) {
return ServerError;
}
QFile specsOutFile(specFileName);
if (!specsOutFile.open(QIODevice::WriteOnly)) {
return FileAccessError;
}
QJsonDocument document = QJsonDocument::fromJson(data);
specsOutFile.write(document.toJson());
specsOutFile.close();
printf("Spec file successfully downloaded (and formatted).\n");
return NoError; // Not implemented
}
StatusCode format(const QString &specFileName)
{
QFile specsFile(specFileName);
if (!specsFile.open(QIODevice::ReadOnly)) {
return FileAccessError;
}
QByteArray data = specsFile.readAll();
specsFile.close();
if (!specsFile.open(QIODevice::WriteOnly)) {
return FileAccessError;
}
QJsonDocument document = QJsonDocument::fromJson(data);
specsFile.write(document.toJson());
specsFile.close();
printf("Spec file successfully formatted.\n");
return NoError;
}
StatusCode generate(SchemaFormat format, const QString &specFileName)
{
QFile specsFile(specFileName);
specsFile.open(QIODevice::ReadOnly);
const QByteArray data = specsFile.readAll();
if (data.isEmpty()) {
printf("Unable to read the file.\n");
return InvalidArgument;
}
specsFile.close();
GeneratorNG generator;
bool success = true;
switch (format) {
case JsonFormat:
success = generator.loadDataFromJson(data);
break;
case TextFormat:
success = generator.loadDataFromText(data);
break;
}
if (!success) {
printf("Unable to parse the scheme.\n");
return SchemaReadError;
}
generator.generate();
replacingHelper(QLatin1String("../TLValues.hpp"), 8, QLatin1String("TLValues"), generator.codeOfTLValues);
replacingHelper(QLatin1String("../TLTypes.hpp"), 0, QLatin1String("TLTypes"), generator.codeOfTLTypes);
replacingHelper(QLatin1String("../CTelegramStream.hpp"), 4, QLatin1String("read operators"), generator.codeStreamReadDeclarations);
replacingHelper(QLatin1String("../CTelegramStream.cpp"), 0, QLatin1String("read operators implementation"), generator.codeStreamReadDefinitions);
replacingHelper(QLatin1String("../CTelegramStream.cpp"), 0, QLatin1String("vector read templates instancing"), generator.codeStreamReadTemplateInstancing);
replacingHelper(QLatin1String("../CTelegramStream.hpp"), 4, QLatin1String("write operators"), generator.codeStreamWriteDeclarations);
replacingHelper(QLatin1String("../CTelegramStream.cpp"), 0, QLatin1String("write operators implementation"), generator.codeStreamWriteDefinitions);
replacingHelper(QLatin1String("../CTelegramStream.cpp"), 0, QLatin1String("vector write templates instancing"), generator.codeStreamWriteTemplateInstancing);
replacingHelper(QLatin1String("../CTelegramConnection.hpp"), 4, QLatin1String("Telegram API methods declaration"), generator.codeConnectionDeclarations);
replacingHelper(QLatin1String("../CTelegramConnection.cpp"), 0, QLatin1String("Telegram API methods implementation"), generator.codeConnectionDefinitions);
replacingHelper(QLatin1String("../TLTypesDebug.hpp"), 0, QLatin1String("TLTypes debug operators"), generator.codeDebugWriteDeclarations);
replacingHelper(QLatin1String("../TLTypesDebug.cpp"), 0, QLatin1String("TLTypes debug operators"), generator.codeDebugWriteDefinitions);
replacingHelper(QLatin1String("../TLRpcDebug.cpp"), 4, QLatin1String("RPC call debug cases"), generator.codeDebugRpcParse);
printf("Spec file successfully used for generation.\n");
return NoError;
}
StatusCode main2(const QStringList &arguments)
{
if (arguments.count() < 3) {
return InvalidArgument;
}
QString fileName;
if (!arguments.last().startsWith(QLatin1Char('-'))) {
fileName = arguments.last();
} else {
return InvalidArgument;
}
StatusCode code = NoError;
if (arguments.contains(QLatin1String("--fetch-json"))) {
code = fetchJson(fileName);
if (code != NoError) {
return code;
}
}
if (arguments.contains(QLatin1String("--format-json"))) {
code = format(fileName);
if (code != NoError) {
return code;
}
}
if (arguments.contains(QLatin1String("--generate-from-json"))) {
code = generate(JsonFormat, fileName);
if (code != NoError) {
return code;
}
}
if (arguments.contains(QLatin1String("--generate-from-text"))) {
code = generate(TextFormat, fileName);
if (code != NoError) {
return code;
}
}
return code;
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
StatusCode code = main2(app.arguments());
if (code == InvalidAction) {
printf("Invalid arguments. Look at the sources for the list of possible arguments.\n");
}
return code;
}
<commit_msg>GeneratorNG: QCommandLineParser<commit_after>/*
Copyright (C) 2014-2015 Alexandr Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
*/
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QCommandLineParser>
#include <QJsonDocument>
#include "GeneratorNG.hpp"
enum StatusCode {
NoError,
InvalidAction,
InvalidArgument,
SchemaReadError,
NetworkError,
ServerError,
FileAccessError
};
enum SchemaFormat {
JsonFormat,
TextFormat,
};
/* Replacing helper */
bool replaceSection(const QString &fileName, const QString &startMarker, const QString &endMarker, const QString &newContent)
{
QFile fileToProcess(fileName);
if (!fileToProcess.open(QIODevice::ReadOnly))
return false;
QString fileContent = fileToProcess.readAll();
fileToProcess.close();
bool winNewLines = fileContent.indexOf(QLatin1String("\r\n")) > 0;
if (winNewLines) {
fileContent.replace(QLatin1String("\r\n"), QLatin1String("\n"));
}
int startPos = fileContent.indexOf(startMarker);
int endPos = fileContent.indexOf(endMarker);
if (startPos >= 0) {
if (endPos < 0) {
printf("There is only start marker in the file %s. Error.\n", fileName.toLocal8Bit().constData());
return false;
}
endPos += endMarker.length();
} else {
return false;
}
const QString previousContent = fileContent.mid(startPos, endPos - startPos);
if (previousContent == startMarker + newContent + endMarker) {
printf("Nothing to do: new and previous contents are exactly same.\n");
return true;
}
fileContent.remove(startPos, endPos - startPos);
fileContent.insert(startPos, startMarker + newContent + endMarker);
if (!fileToProcess.open(QIODevice::WriteOnly)) {
printf("Can not write file: %s.\n", fileName.toLocal8Bit().constData());
return false;
}
if (winNewLines) {
fileContent.replace(QLatin1String("\n"), QLatin1String("\r\n"));
}
fileToProcess.write(fileContent.toLatin1());
fileToProcess.close();
printf("Replacing is done.\n");
return true;
}
bool replacingHelper(const QString &fileName, int spacing, const QString &marker, const QString &newContent)
{
const QString space(spacing, QChar(' '));
if (!replaceSection(fileName,
QString("%1// Generated %2\n").arg(space).arg(marker),
QString("%1// End of generated %2\n").arg(space).arg(marker), newContent)) {
printf("Can not update file %s with marker %s.\n", fileName.toLatin1().constData(), marker.toLatin1().constData());
return false;
} else {
return true;
}
}
/* End of replacing helper */
void debugType(const TLType &type)
{
qDebug() << type.name;
foreach (const TLSubType &subType, type.subTypes) {
qDebug() << " " << subType.name;
foreach (const TLParam &member, subType.members) {
qDebug() << " " << member.type << member.name;
}
}
}
StatusCode fetchJson(const QString &specFileName)
{
QEventLoop eventLoop;
QNetworkAccessManager mgr;
QObject::connect(&mgr, &QNetworkAccessManager::finished, &eventLoop, &QEventLoop::quit);
QNetworkRequest req(QUrl(QLatin1String("https://core.telegram.org/schema/json")));
QNetworkReply *reply = mgr.get(req);
eventLoop.exec();
if (reply->error() != QNetworkReply::NoError) {
delete reply;
return NetworkError;
}
QByteArray data = reply->readAll();
delete reply;
if (data.isEmpty()) {
return ServerError;
}
QFile specsOutFile(specFileName);
if (!specsOutFile.open(QIODevice::WriteOnly)) {
return FileAccessError;
}
QJsonDocument document = QJsonDocument::fromJson(data);
specsOutFile.write(document.toJson());
specsOutFile.close();
printf("Spec file successfully downloaded (and formatted).\n");
return NoError;
}
StatusCode format(const QString &specFileName)
{
QFile specsFile(specFileName);
if (!specsFile.open(QIODevice::ReadOnly)) {
return FileAccessError;
}
QByteArray data = specsFile.readAll();
specsFile.close();
if (!specsFile.open(QIODevice::WriteOnly)) {
return FileAccessError;
}
QJsonDocument document = QJsonDocument::fromJson(data);
specsFile.write(document.toJson());
specsFile.close();
printf("Spec file successfully formatted.\n");
return NoError;
}
StatusCode generate(SchemaFormat format, const QString &specFileName)
{
QFile specsFile(specFileName);
specsFile.open(QIODevice::ReadOnly);
const QByteArray data = specsFile.readAll();
if (data.isEmpty()) {
printf("Unable to read the file.\n");
return InvalidArgument;
}
specsFile.close();
GeneratorNG generator;
bool success = true;
switch (format) {
case JsonFormat:
success = generator.loadDataFromJson(data);
break;
case TextFormat:
success = generator.loadDataFromText(data);
break;
}
if (!success) {
printf("Unable to parse the scheme.\n");
return SchemaReadError;
}
generator.generate();
replacingHelper(QLatin1String("../TLValues.hpp"), 8, QLatin1String("TLValues"), generator.codeOfTLValues);
replacingHelper(QLatin1String("../TLTypes.hpp"), 0, QLatin1String("TLTypes"), generator.codeOfTLTypes);
replacingHelper(QLatin1String("../CTelegramStream.hpp"), 4, QLatin1String("read operators"), generator.codeStreamReadDeclarations);
replacingHelper(QLatin1String("../CTelegramStream.cpp"), 0, QLatin1String("read operators implementation"), generator.codeStreamReadDefinitions);
replacingHelper(QLatin1String("../CTelegramStream.cpp"), 0, QLatin1String("vector read templates instancing"), generator.codeStreamReadTemplateInstancing);
replacingHelper(QLatin1String("../CTelegramStream.hpp"), 4, QLatin1String("write operators"), generator.codeStreamWriteDeclarations);
replacingHelper(QLatin1String("../CTelegramStream.cpp"), 0, QLatin1String("write operators implementation"), generator.codeStreamWriteDefinitions);
replacingHelper(QLatin1String("../CTelegramStream.cpp"), 0, QLatin1String("vector write templates instancing"), generator.codeStreamWriteTemplateInstancing);
replacingHelper(QLatin1String("../CTelegramConnection.hpp"), 4, QLatin1String("Telegram API methods declaration"), generator.codeConnectionDeclarations);
replacingHelper(QLatin1String("../CTelegramConnection.cpp"), 0, QLatin1String("Telegram API methods implementation"), generator.codeConnectionDefinitions);
replacingHelper(QLatin1String("../TLTypesDebug.hpp"), 0, QLatin1String("TLTypes debug operators"), generator.codeDebugWriteDeclarations);
replacingHelper(QLatin1String("../TLTypesDebug.cpp"), 0, QLatin1String("TLTypes debug operators"), generator.codeDebugWriteDefinitions);
replacingHelper(QLatin1String("../TLRpcDebug.cpp"), 4, QLatin1String("RPC call debug cases"), generator.codeDebugRpcParse);
printf("Spec file successfully used for generation.\n");
return NoError;
}
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QCommandLineParser parser;
parser.addHelpOption();
QCommandLineOption fetchJsonOption(QStringLiteral("fetch-json"));
parser.addOption(fetchJsonOption);
QCommandLineOption formatJsonOption(QStringLiteral("format-json"));
parser.addOption(formatJsonOption);
QCommandLineOption generateFromJsonOption(QStringLiteral("generate-from-json"));
parser.addOption(generateFromJsonOption);
QCommandLineOption generateFromTextOption(QStringLiteral("generate-from-text"));
parser.addOption(generateFromTextOption);
parser.addPositionalArgument(QStringLiteral("spec"), QStringLiteral("The specification file (text or json)"));
parser.process(app);
if (parser.positionalArguments().count() != 1) {
parser.showHelp(InvalidArgument);
}
const QString fileName = parser.positionalArguments().first();
StatusCode code;
if (parser.isSet(fetchJsonOption)) {
code = fetchJson(fileName);
if (code != NoError) {
return code;
}
}
if (parser.isSet(formatJsonOption)) {
code = format(fileName);
if (code != NoError) {
return code;
}
}
if (parser.isSet(generateFromJsonOption)) {
code = generate(JsonFormat, fileName);
if (code != NoError) {
return code;
}
}
if (parser.isSet(generateFromTextOption)) {
code = generate(TextFormat, fileName);
if (code != NoError) {
return code;
}
}
return code;
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////
//Generates forwarding headers using the information
//in the header.lst & vendor.lst files
//
//To create a header list from an existing directory of headers
//dir *.h /b > headers.lst
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <ctime>
using namespace std;
struct Compiler
{
Compiler() {}
Compiler(const string& VersionTest, const string& SubDir) :
version_test(VersionTest), subdir(SubDir)
{}
string version_test;
string subdir;
};
typedef vector<Compiler> cv_t;
int main(int argc, char* argv[])
{
if(argc < 2)
{
cout <<"Usage: <Header List> [Version/Vender List]"<<endl;
return -1;
}
cv_t vendors;
char buf[1024];
string check;
string subdir;
fstream vendor_file;
if(argc >= 3)
{
vendor_file.open(argv[2], ios::in);
if(!vendor_file.is_open())
{
cout << "Unable to open vendor file: " << argv[2] << endl;
return -2;
}
else
{
vendors.reserve(10);
while(!vendor_file.eof())
{
check = "";
subdir = "";
vendor_file.getline(buf, 1024, '\n');
check = buf;
vendor_file.getline(buf, 1024, '\n');
subdir = buf;
vendor_file.getline(buf, 1024, '\n');
if(!(check.empty() || subdir.empty()))
vendors.push_back(Compiler(check, subdir));
else
{
cout << "Error parsing vendors, check:" << check << "\tsubdir:" << subdir << endl;
}
}
}
}
else //if(vendors.empty())
{
cout << "No vendor file provided, using defaults\n";
vendors.reserve(10);
vendors.push_back(Compiler("(_MSC_VER >= 1300)", "MSVC\\1300"));
vendors.push_back(Compiler("(__BORLANDC__)", "Borland"));
vendors.push_back(Compiler("( (__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ > 95)) )", "Reference"));
}
fstream header_list(argv[1]);
string header;
stringstream ss;
if(!header_list.is_open())
{
cout << "Invalid header list file, " << argv[1] << endl;
return -3;
}
while(!header_list.eof())
{
header_list >> header;
cout << header << endl;
fstream header_file(header.c_str(), ios::out);
if(!header_file.is_open())
{
cout << "Unable to open header file for output: " << header << endl;
}
else
{
ss.str("");
ss << "//Generated header: " << header << endl;
size_t n = ss.str().size();
for(size_t i=0; i<n; ++i)
header_file << "/";
header_file << endl;
header_file << ss.str();
header_file << "//Forwards to the appropriate code\n";
header_file << "// that works on the detected compiler\n";
time_t rawtime; time(&rawtime);
header_file << "//Generated on " << ctime(&rawtime);
header_file << endl << endl;
cv_t::iterator it=vendors.begin(), itEnd = vendors.end();
header_file << "#ifdef LOKI_USE_REFERENCE\n";
header_file << "#\tinclude \"./Reference/" << header << "\"\n";
//header_file << "#\tinclude \".\\Reference\\" << header << "\"\n";
header_file << "#else\n";
header_file << "#\tif " << it->version_test << endl;
//header_file << "#\t\tinclude \".\\" << it->subdir;
header_file << "#\t\tinclude \"./" << it->subdir;
//header_file << "\\" << header << "\"\n";
header_file << "/" << header << "\"\n";
++it;
for(; it!=itEnd; ++it)
{
header_file << "#\telif " << it->version_test << endl;
//header_file << "#\t\tinclude \".\\" << it->subdir;
header_file << "#\t\tinclude \"." << it->subdir;
//header_file << "\\" << header << "\"\n";
header_file << "/" << header << "\"\n";
}
header_file << "#\telse\n";
header_file << "\t\t//Define LOKI_USE_REFERENCE and get back to us on the results\n";
header_file << "#\t\terror Compiler not tested with Loki, #define LOKI_USE_REFERENCE\n";
header_file << "#\tendif\n";
header_file << "#endif\n";
}
}
#ifdef _MSC_VER
system("PAUSE");
#endif
return 0;
}<commit_msg>Fixed missing / bug<commit_after>///////////////////////////////////////////////////////////////
//Generates forwarding headers using the information
//in the header.lst & vendor.lst files
//
//To create a header list from an existing directory of headers
//dir *.h /b > headers.lst
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <ctime>
using namespace std;
struct Compiler
{
Compiler() {}
Compiler(const string& VersionTest, const string& SubDir) :
version_test(VersionTest), subdir(SubDir)
{}
string version_test;
string subdir;
};
typedef vector<Compiler> cv_t;
int main(int argc, char* argv[])
{
if(argc < 2)
{
cout <<"Usage: <Header List> [Version/Vendor List]"<<endl;
return -1;
}
cv_t vendors;
char buf[1024];
string check;
string subdir;
fstream vendor_file;
if(argc >= 3)
{
vendor_file.open(argv[2], ios::in);
if(!vendor_file.is_open())
{
cout << "Unable to open vendor file: " << argv[2] << endl;
return -2;
}
else
{
vendors.reserve(10);
while(!vendor_file.eof())
{
check = "";
subdir = "";
vendor_file.getline(buf, 1024, '\n');
check = buf;
vendor_file.getline(buf, 1024, '\n');
subdir = buf;
vendor_file.getline(buf, 1024, '\n');
if(!(check.empty() || subdir.empty()))
vendors.push_back(Compiler(check, subdir));
else
{
cout << "Error parsing vendors, check:" << check << "\tsubdir:" << subdir << endl;
}
}
}
}
else //if(vendors.empty())
{
cout << "No vendor file provided, using defaults\n";
vendors.reserve(10);
vendors.push_back(Compiler("(_MSC_VER >= 1300)", "MSVC\\1300"));
vendors.push_back(Compiler("(__BORLANDC__)", "Borland"));
vendors.push_back(Compiler("( (__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ > 95)) )", "Reference"));
}
fstream header_list(argv[1]);
string header;
stringstream ss;
if(!header_list.is_open())
{
cout << "Invalid header list file, " << argv[1] << endl;
return -3;
}
while(!header_list.eof())
{
header_list >> header;
cout << header << endl;
fstream header_file(header.c_str(), ios::out);
if(!header_file.is_open())
{
cout << "Unable to open header file for output: " << header << endl;
}
else
{
ss.str("");
ss << "//Generated header: " << header << endl;
size_t n = ss.str().size();
for(size_t i=0; i<n; ++i)
header_file << "/";
header_file << endl;
header_file << ss.str();
header_file << "//Forwards to the appropriate code\n";
header_file << "// that works on the detected compiler\n";
time_t rawtime; time(&rawtime);
header_file << "//Generated on " << ctime(&rawtime);
header_file << endl << endl;
cv_t::iterator it=vendors.begin(), itEnd = vendors.end();
header_file << "#ifdef LOKI_USE_REFERENCE\n";
header_file << "#\tinclude \"./Reference/" << header << "\"\n";
//header_file << "#\tinclude \".\\Reference\\" << header << "\"\n";
header_file << "#else\n";
header_file << "#\tif " << it->version_test << endl;
//header_file << "#\t\tinclude \".\\" << it->subdir;
header_file << "#\t\tinclude \"./" << it->subdir;
//header_file << "\\" << header << "\"\n";
header_file << "/" << header << "\"\n";
++it;
for(; it!=itEnd; ++it)
{
header_file << "#\telif " << it->version_test << endl;
//header_file << "#\t\tinclude \".\\" << it->subdir;
header_file << "#\t\tinclude \"./" << it->subdir;
//header_file << "\\" << header << "\"\n";
header_file << "/" << header << "\"\n";
}
header_file << "#\telse\n";
header_file << "\t\t//Define LOKI_USE_REFERENCE and get back to us on the results\n";
header_file << "#\t\terror Compiler not tested with Loki, #define LOKI_USE_REFERENCE\n";
header_file << "#\tendif\n";
header_file << "#endif\n";
}
}
#ifdef _MSC_VER
system("PAUSE");
#endif
return 0;
}<|endoftext|>
|
<commit_before>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include "src/ext/cpputil/include/command_line/command_line.h"
#include "src/ext/cpputil/include/signal/debug_handler.h"
#include "src/ext/cpputil/include/system/terminal.h"
#include "src/cfg/dot_writer.h"
#include "tools/gadgets/target.h"
#include "tools/ui/console.h"
using namespace cpputil;
using namespace std;
using namespace stoke;
auto& content = Heading::create("Content Options:");
auto& dib = FlagArg::create("dib")
.alternate("def_in_block")
.description("Display def in values for basic blocks");
auto& dii = FlagArg::create("dii")
.alternate("def_in_instr")
.description("Display def in values for instructions");
auto& lob = FlagArg::create("lob")
.alternate("live_out_block")
.description("Display live out values for basic blocks");
auto& dom = FlagArg::create("dom")
.alternate("dominators")
.description("Display dominators");
auto& io = Heading::create("I/O Options:");
auto& out = ValueArg<string>::create("o")
.alternate("out")
.usage("<path/to/file.pdf>")
.description("Path to write cfg to")
.default_val("./cfg.pdf");
auto& view = FlagArg::create("view")
.alternate("v")
.description("View cfg immediately");
void to_dot() {
ofstream ofs(string("/tmp/stoke.") + getenv("USER") + ".dot");
TargetGadget target;
DotWriter dw;
dw.set_def_in(dib, dii)
.set_live_out(lob)
.set_dom(dom);
dw(ofs, target);
}
bool to_pdf() {
Terminal term;
term << "cat /tmp/stoke.$USER.dot | dot -Tpdf > " << out.value() << endl;
return term.result() == 0;
}
bool view_pdf() {
Terminal term;
term << "evince " << out.value() << endl;
return term.result() == 0;
}
bool rm_pdf() {
Terminal term;
term << "rm -f " << out.value() << endl;
return term.result() == 0;
}
int main(int argc, char** argv) {
CommandLineConfig::strict_with_convenience(argc, argv);
DebugHandler::install_sigsegv();
DebugHandler::install_sigill();
to_dot();
if (!to_pdf()) {
Console::error(1) << "Unable to save file!" << endl;
} else if (view && !view_pdf()) {
Console::error(1) << "Unable to open file for viewing!" << endl;
} else if (view && !rm_pdf()) {
Console::error(1) << "Unable to remove file!" << endl;
}
return 0;
}
<commit_msg>mkstmp in stoke debug cfg.<commit_after>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule
//
// 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 <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "src/ext/cpputil/include/command_line/command_line.h"
#include "src/ext/cpputil/include/signal/debug_handler.h"
#include "src/ext/cpputil/include/system/terminal.h"
#include "src/cfg/dot_writer.h"
#include "tools/gadgets/target.h"
#include "tools/ui/console.h"
using namespace cpputil;
using namespace std;
using namespace stoke;
auto& content = Heading::create("Content Options:");
auto& dib = FlagArg::create("dib")
.alternate("def_in_block")
.description("Display def in values for basic blocks");
auto& dii = FlagArg::create("dii")
.alternate("def_in_instr")
.description("Display def in values for instructions");
auto& lob = FlagArg::create("lob")
.alternate("live_out_block")
.description("Display live out values for basic blocks");
auto& dom = FlagArg::create("dom")
.alternate("dominators")
.description("Display dominators");
auto& io = Heading::create("I/O Options:");
auto& out = ValueArg<string>::create("o")
.alternate("out")
.usage("<path/to/file.pdf>")
.description("Path to write cfg to")
.default_val("./cfg.pdf");
auto& view = FlagArg::create("view")
.alternate("v")
.description("View cfg immediately");
string tempfile(const string& temp) {
vector<char> v(temp.begin(), temp.end());
v.push_back('\0');
const auto fd = mkstemp(v.data());
return string(v.begin(), v.end()-1);
}
void to_dot(const string& dot_file) {
ofstream ofs(dot_file);
TargetGadget target;
DotWriter dw;
dw.set_def_in(dib, dii)
.set_live_out(lob)
.set_dom(dom);
dw(ofs, target);
}
bool to_pdf(const string& dot_file, const string& pdf_file) {
Terminal term;
term << "cat " << dot_file << " | dot -Tpdf > " << pdf_file << " 2> /dev/null" << endl;
return term.result() == 0;
}
bool view_pdf(const string& pdf_file) {
Terminal term;
term << "evince " << pdf_file << endl;
return term.result() == 0;
}
int main(int argc, char** argv) {
CommandLineConfig::strict_with_convenience(argc, argv);
DebugHandler::install_sigsegv();
DebugHandler::install_sigill();
const auto dot_file = tempfile("/tmp/stoke_debug_cfg.dot.XXXXXX");
to_dot(dot_file);
if (!to_pdf(dot_file, out.value())) {
Console::error(1) << "Unable to save file!" << endl;
} else if (view && !view_pdf(out.value())) {
Console::error(1) << "Unable to open file for viewing!" << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "OrbitClientServices/ProcessClient.h"
#include "OrbitBase/Logging.h"
#include "grpcpp/grpcpp.h"
#include "outcome.hpp"
#include "services.grpc.pb.h"
#include "symbol.pb.h"
#include "tracepoint.pb.h"
namespace {
using orbit_grpc_protos::GetDebugInfoFileRequest;
using orbit_grpc_protos::GetDebugInfoFileResponse;
using orbit_grpc_protos::GetModuleListRequest;
using orbit_grpc_protos::GetModuleListResponse;
using orbit_grpc_protos::GetProcessListRequest;
using orbit_grpc_protos::GetProcessListResponse;
using orbit_grpc_protos::GetProcessMemoryRequest;
using orbit_grpc_protos::GetProcessMemoryResponse;
using orbit_grpc_protos::GetTracepointListRequest;
using orbit_grpc_protos::GetTracepointListResponse;
using orbit_grpc_protos::ModuleInfo;
using orbit_grpc_protos::ProcessInfo;
using orbit_grpc_protos::ProcessService;
using orbit_grpc_protos::TracepointInfo;
constexpr uint64_t kGrpcDefaultTimeoutMilliseconds = 1000;
std::unique_ptr<grpc::ClientContext> CreateContext(uint64_t timeout_milliseconds) {
auto context = std::make_unique<grpc::ClientContext>();
std::chrono::time_point deadline =
std::chrono::system_clock::now() + std::chrono::milliseconds(timeout_milliseconds);
context->set_deadline(deadline);
return context;
}
} // namespace
ErrorMessageOr<std::vector<orbit_grpc_protos::ProcessInfo>> ProcessClient::GetProcessList() {
GetProcessListRequest request;
GetProcessListResponse response;
std::unique_ptr<grpc::ClientContext> context = CreateContext(kGrpcDefaultTimeoutMilliseconds);
grpc::Status status = process_service_->GetProcessList(context.get(), request, &response);
if (!status.ok()) {
ERROR("gRPC call to GetProcessList failed: %s (error_code=%d)", status.error_message(),
status.error_code());
return ErrorMessage(status.error_message());
}
const auto& processes = response.processes();
return std::vector<ProcessInfo>(processes.begin(), processes.end());
}
ErrorMessageOr<std::vector<ModuleInfo>> ProcessClient::LoadModuleList(int32_t pid) {
GetModuleListRequest request;
GetModuleListResponse response;
request.set_process_id(pid);
std::unique_ptr<grpc::ClientContext> context = CreateContext(kGrpcDefaultTimeoutMilliseconds);
grpc::Status status = process_service_->GetModuleList(context.get(), request, &response);
if (!status.ok()) {
ERROR("Grpc call failed: code=%d, message=%s", status.error_code(), status.error_message());
return ErrorMessage(status.error_message());
}
const auto& modules = response.modules();
return std::vector<ModuleInfo>(modules.begin(), modules.end());
}
ErrorMessageOr<std::vector<TracepointInfo>> ProcessClient::LoadTracepointList() {
GetTracepointListRequest request;
GetTracepointListResponse response;
std::unique_ptr<grpc::ClientContext> context = CreateContext(kGrpcDefaultTimeoutMilliseconds);
grpc::Status status = process_service_->GetTracepointList(context.get(), request, &response);
if (!status.ok()) {
ERROR("Grpc call failed: code=%d, message=%s", status.error_code(), status.error_message());
return ErrorMessage(status.error_message());
}
const auto& tracepoints = response.tracepoints();
return std::vector<TracepointInfo>(tracepoints.begin(), tracepoints.end());
}
ErrorMessageOr<std::string> ProcessClient::FindDebugInfoFile(const std::string& module_path) {
GetDebugInfoFileRequest request;
GetDebugInfoFileResponse response;
request.set_module_path(module_path);
std::unique_ptr<grpc::ClientContext> context = CreateContext(kGrpcDefaultTimeoutMilliseconds);
grpc::Status status = process_service_->GetDebugInfoFile(context.get(), request, &response);
if (!status.ok()) {
ERROR("gRPC call to GetDebugInfoFile failed: %s", status.error_message());
return ErrorMessage(status.error_message());
}
return response.debug_info_file_path();
}
ErrorMessageOr<std::string> ProcessClient::LoadProcessMemory(int32_t pid, uint64_t address,
uint64_t size) {
GetProcessMemoryRequest request;
request.set_pid(pid);
request.set_address(address);
request.set_size(size);
GetProcessMemoryResponse response;
std::unique_ptr<grpc::ClientContext> context = CreateContext(kGrpcDefaultTimeoutMilliseconds);
grpc::Status status = process_service_->GetProcessMemory(context.get(), request, &response);
if (!status.ok()) {
ERROR("gRPC call to GetProcessMemory failed: %s", status.error_message());
return ErrorMessage(status.error_message());
}
return std::move(*response.mutable_memory());
}<commit_msg>Add default value for timeout_milliseconds to ProcessClient::CreateContext<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "OrbitClientServices/ProcessClient.h"
#include "OrbitBase/Logging.h"
#include "grpcpp/grpcpp.h"
#include "outcome.hpp"
#include "services.grpc.pb.h"
#include "symbol.pb.h"
#include "tracepoint.pb.h"
namespace {
using orbit_grpc_protos::GetDebugInfoFileRequest;
using orbit_grpc_protos::GetDebugInfoFileResponse;
using orbit_grpc_protos::GetModuleListRequest;
using orbit_grpc_protos::GetModuleListResponse;
using orbit_grpc_protos::GetProcessListRequest;
using orbit_grpc_protos::GetProcessListResponse;
using orbit_grpc_protos::GetProcessMemoryRequest;
using orbit_grpc_protos::GetProcessMemoryResponse;
using orbit_grpc_protos::GetTracepointListRequest;
using orbit_grpc_protos::GetTracepointListResponse;
using orbit_grpc_protos::ModuleInfo;
using orbit_grpc_protos::ProcessInfo;
using orbit_grpc_protos::ProcessService;
using orbit_grpc_protos::TracepointInfo;
constexpr uint64_t kGrpcDefaultTimeoutMilliseconds = 1000;
std::unique_ptr<grpc::ClientContext> CreateContext(
uint64_t timeout_milliseconds = kGrpcDefaultTimeoutMilliseconds) {
auto context = std::make_unique<grpc::ClientContext>();
std::chrono::time_point deadline =
std::chrono::system_clock::now() + std::chrono::milliseconds(timeout_milliseconds);
context->set_deadline(deadline);
return context;
}
} // namespace
ErrorMessageOr<std::vector<orbit_grpc_protos::ProcessInfo>> ProcessClient::GetProcessList() {
GetProcessListRequest request;
GetProcessListResponse response;
std::unique_ptr<grpc::ClientContext> context = CreateContext();
grpc::Status status = process_service_->GetProcessList(context.get(), request, &response);
if (!status.ok()) {
ERROR("gRPC call to GetProcessList failed: %s (error_code=%d)", status.error_message(),
status.error_code());
return ErrorMessage(status.error_message());
}
const auto& processes = response.processes();
return std::vector<ProcessInfo>(processes.begin(), processes.end());
}
ErrorMessageOr<std::vector<ModuleInfo>> ProcessClient::LoadModuleList(int32_t pid) {
GetModuleListRequest request;
GetModuleListResponse response;
request.set_process_id(pid);
std::unique_ptr<grpc::ClientContext> context = CreateContext();
grpc::Status status = process_service_->GetModuleList(context.get(), request, &response);
if (!status.ok()) {
ERROR("Grpc call failed: code=%d, message=%s", status.error_code(), status.error_message());
return ErrorMessage(status.error_message());
}
const auto& modules = response.modules();
return std::vector<ModuleInfo>(modules.begin(), modules.end());
}
ErrorMessageOr<std::vector<TracepointInfo>> ProcessClient::LoadTracepointList() {
GetTracepointListRequest request;
GetTracepointListResponse response;
std::unique_ptr<grpc::ClientContext> context = CreateContext();
grpc::Status status = process_service_->GetTracepointList(context.get(), request, &response);
if (!status.ok()) {
ERROR("Grpc call failed: code=%d, message=%s", status.error_code(), status.error_message());
return ErrorMessage(status.error_message());
}
const auto& tracepoints = response.tracepoints();
return std::vector<TracepointInfo>(tracepoints.begin(), tracepoints.end());
}
ErrorMessageOr<std::string> ProcessClient::FindDebugInfoFile(const std::string& module_path) {
GetDebugInfoFileRequest request;
GetDebugInfoFileResponse response;
request.set_module_path(module_path);
std::unique_ptr<grpc::ClientContext> context = CreateContext();
grpc::Status status = process_service_->GetDebugInfoFile(context.get(), request, &response);
if (!status.ok()) {
ERROR("gRPC call to GetDebugInfoFile failed: %s", status.error_message());
return ErrorMessage(status.error_message());
}
return response.debug_info_file_path();
}
ErrorMessageOr<std::string> ProcessClient::LoadProcessMemory(int32_t pid, uint64_t address,
uint64_t size) {
GetProcessMemoryRequest request;
request.set_pid(pid);
request.set_address(address);
request.set_size(size);
GetProcessMemoryResponse response;
std::unique_ptr<grpc::ClientContext> context = CreateContext();
grpc::Status status = process_service_->GetProcessMemory(context.get(), request, &response);
if (!status.ok()) {
ERROR("gRPC call to GetProcessMemory failed: %s", status.error_message());
return ErrorMessage(status.error_message());
}
return std::move(*response.mutable_memory());
}<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
#include "grins_config.h"
#include <iostream>
// GRINS
#include "grins/mesh_builder.h"
#include "grins/simulation.h"
#include "grins/simulation_builder.h"
#include "grins/multiphysics_sys.h"
#include "grins/parabolic_profile.h"
//libMesh
#include "libmesh/dirichlet_boundaries.h"
#include "libmesh/dof_map.h"
//#include "libmesh/exact_solution.h"
// GRVY
#ifdef GRINS_HAVE_GRVY
#include "grvy.h"
#endif
// libMesh::Number
// exact_solution( const libMesh::Point& p,
// const libMesh::Parameters&, // parameters, not needed
// const std::string&, // sys_name, not needed
// const std::string&); // unk_name, not needed);
// libMesh::Gradient
// exact_derivative( const libMesh::Point& p,
// const libMesh::Parameters&, // parameters, not needed
// const std::string&, // sys_name, not needed
// const std::string&); // unk_name, not needed);
// class ParabolicBCFactory : public GRINS::BoundaryConditionsFactory
// {
// public:
// ParabolicBCFactory()
// : GRINS::BoundaryConditionsFactory()
// { return; };
// ~ParabolicBCFactory(){return;};
// std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > build_dirichlet( );
// };
// Function to set the Dirichlet boundary function for the inlet u velocity and nu profiles
class BdyFunction : public FunctionBase<Number>
{
public:
BdyFunction (MeshFunction)
: MeshFunction.initialize)
{ this->_initialized = true; }
virtual Number operator() (const Point&, const Real = 0)
{ libmesh_not_implemented(); }
virtual void operator() (const Point& p,
const Real,
DenseVector<Number>& output)
{
output.resize(2);
output.zero();
const Real y=p(1);
// Set the parabolic inflow boundary conditions at stations 0 & 1
output(_u_var) = (_sign)*((y-2) * (y-3));
output(_v_var) = 0;
}
virtual AutoPtr<FunctionBase<Number> > clone() const
{ return AutoPtr<FunctionBase<Number> > (new BdyFunction(_u_var, _v_var, _sign)); }
private:
const unsigned int _u_var, _v_var;
};
int main(int argc, char* argv[])
{
#ifdef GRINS_USE_GRVY_TIMERS
GRVY::GRVY_Timer_Class grvy_timer;
grvy_timer.Init("GRINS Timer");
#endif
// Check command line count.
if( argc < 2 )
{
// TODO: Need more consistent error handling.
std::cerr << "Error: Must specify libMesh input file." << std::endl;
exit(1); // TODO: something more sophisticated for parallel runs?
}
// libMesh input file should be first argument
std::string libMesh_input_filename = argv[1];
// Create our GetPot object.
GetPot libMesh_inputfile( libMesh_input_filename );
#ifdef GRINS_USE_GRVY_TIMERS
grvy_timer.BeginTimer("Initialize Solver");
#endif
// Initialize libMesh library.
libMesh::LibMeshInit libmesh_init(argc, argv);
// Build a 1-d turbulent_bc_system to get the bc data from files
libMesh::SerialMesh mesh(libmesh_init.comm);
libMesh::AutoPtr<MeshRefinement> mesh_refinement =
build_mesh_refinement(mesh, param);
mesh.read("file.xda");
//mesh.all_second_order();
// And an EquationSystems to run on it
libMesh::EquationSystems equation_systems (mesh);
libMesh::LinearImplicitSystem & turbulent_bc_system = equation_systems.add_system<libMesh::LinearImplicitSystem>("Turbulent-BC");
equation_systems.read("sol.xda", READ,
libMesh::EquationSystems::READ_HEADER |
libMesh::EquationSystems::READ_DATA |
libMesh::EquationSystems::READ_ADDITIONAL_DATA);
// Prepare a global solution and a MeshFunction of the Turbulent system
libMesh::AutoPtr<MeshFunction> coarse_values;
libMesh::AutoPtr<libMesh::NumericVector<Number> > turbulent_bc_soln = libMesh::NumericVector<Number>::build(equation_systems.comm());
std::vector<unsigned int>turbulent_bc_system_variables;
turbulent_bc_system_variables.push_back(0);
turbulent_bc_system_variables.push_back(1);
turbulent_bc_values = libMesh::AutoPtr<libMesh::MeshFunction>
(new libMesh::MeshFunction(equation_systems,
*turbulent_bc_soln,
turbulent_bc_system.get_dof_map(),
turbulent_bc_system_variables ));
turbulent_bc_values->init();
GRINS::SimulationBuilder sim_builder;
std::tr1::shared_ptr<ParabolicBCFactory> bc_factory( new ParabolicBCFactory );
sim_builder.attach_bc_factory(bc_factory);
GRINS::Simulation grins( libMesh_inputfile,
sim_builder,
libmesh_init.comm() );
#ifdef GRINS_USE_GRVY_TIMERS
grvy_timer.EndTimer("Initialize Solver");
// Attach GRVY timer to solver
grins.attach_grvy_timer( &grvy_timer );
#endif
// Solve
grins.run();
// Get equation systems to create ExactSolution object
//std::tr1::shared_ptr<libMesh::EquationSystems> es = grins.get_equation_system();
// Create Exact solution object and attach exact solution quantities
//libMesh::ExactSolution exact_sol(*es);
//exact_sol.attach_exact_value(&exact_solution);
//exact_sol.attach_exact_deriv(&exact_derivative);
// Compute error and get it in various norms
//exact_sol.compute_error("GRINS", "u");
//double l2error = exact_sol.l2_error("GRINS", "u");
//double h1error = exact_sol.h1_error("GRINS", "u");
// Needs to change to 1 based on comparison
int return_flag = 0;
// if( l2error > 1.0e-9 || h1error > 1.0e-9 )
// {
// return_flag = 1;
// std::cout << "Tolerance exceeded for velocity in Poiseuille test." << std::endl
// << "l2 error = " << l2error << std::endl
// << "h1 error = " << h1error << std::endl;
// }
// // Compute error and get it in various norms
// exact_sol.compute_error("GRINS", "p");
// l2error = exact_sol.l2_error("GRINS", "p");
// h1error = exact_sol.h1_error("GRINS", "p");
// if( l2error > 2.0e-9 || h1error > 2.0e-9 )
// {
// return_flag = 1;
// std::cout << "Tolerance exceeded for pressure in Poiseuille test." << std::endl
// << "l2 error = " << l2error << std::endl
// << "h1 error = " << h1error << std::endl;
// }
return return_flag;
}
// std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > ParabolicBCFactory::build_dirichlet( )
// {
// GRINS::DBCContainer cont;
// cont.add_var_name( "u" );
// cont.add_bc_id( 1 );
// cont.add_bc_id( 3 );
// std::tr1::shared_ptr<libMesh::FunctionBase<libMesh::Number> > u_func( new GRINS::ParabolicProfile );
// cont.set_func( u_func );
// std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > mymap;
// mymap.insert( std::pair<GRINS::PhysicsName, GRINS::DBCContainer >(GRINS::incompressible_navier_stokes, cont) );
// return mymap;
// }
// libMesh::Number
// exact_solution( const libMesh::Point& p,
// const libMesh::Parameters& /*params*/, // parameters, not needed
// const std::string& /*sys_name*/, // sys_name, not needed
// const std::string& var ) // unk_name, not needed);
// {
// const double x = p(0);
// const double y = p(1);
// libMesh::Number f = 0;
// // Hardcoded to velocity in input file.
// if( var == "u" ) f = 4*y*(1-y);
// else if( var == "p" ) f = 120.0 + (80.0-120.0)/5.0*x;
// else libmesh_assert(false);
// return f;
// }
// libMesh::Gradient
// exact_derivative( const libMesh::Point& p,
// const libMesh::Parameters& /*params*/, // parameters, not needed
// const std::string& /*sys_name*/, // sys_name, not needed
// const std::string& var) // unk_name, not needed);
// {
// const double y = p(1);
// libMesh::Gradient g;
// // Hardcoded to velocity in input file.
// if( var == "u" )
// {
// g(0) = 0.0;
// g(1) = 4*(1-y) - 4*y;
// #if LIBMESH_DIM > 2
// g(2) = 0.0;
// #endif
// }
// if( var == "p" )
// {
// g(0) = (80.0-120.0)/5.0;
// g(1) = 0.0;
// #if LIBMESH_DIM > 2
// g(2) = 0.0;
// #endif
// }
// return g;
// }
<commit_msg>Turbulent channel example can now read in Todd's 1d solution<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
#include "grins_config.h"
#include <iostream>
// GRINS
#include "grins/mesh_builder.h"
#include "grins/simulation.h"
#include "grins/simulation_builder.h"
#include "grins/multiphysics_sys.h"
#include "grins/parabolic_profile.h"
//libMesh
#include "libmesh/dirichlet_boundaries.h"
#include "libmesh/dof_map.h"
#include "libmesh/fe_base.h"
#include "libmesh/fe_interface.h"
#include "libmesh/mesh_function.h"
#include "libmesh/linear_implicit_system.h"
//#include "libmesh/exact_solution.h"
// GRVY
#ifdef GRINS_HAVE_GRVY
#include "grvy.h"
#endif
// Function to set the Dirichlet boundary function for the inlet u velocity and nu profiles
class TurbulentBdyFunction : public libMesh::FunctionBase<libMesh::Number>
{
public:
TurbulentBdyFunction (libMesh::MeshFunction* _turbulent_bc_values) :
turbulent_bc_values(_turbulent_bc_values)
{ this->_initialized = true; }
virtual libMesh::Number operator() (const libMesh::Point&, const libMesh::Real = 0)
{ libmesh_not_implemented(); }
virtual void operator() (const libMesh::Point& p,
const libMesh::Real t,
libMesh::DenseVector<libMesh::Number>& output)
{
output.resize(4);
output.zero();
turbulent_bc_values->operator()(p, t, output);
}
virtual libMesh::AutoPtr<libMesh::FunctionBase<libMesh::Number> > clone() const
{ return libMesh::AutoPtr<libMesh::FunctionBase<libMesh::Number> > (new TurbulentBdyFunction(turbulent_bc_values)); }
private:
libMesh::MeshFunction* turbulent_bc_values;
};
int main(int argc, char* argv[])
{
#ifdef GRINS_USE_GRVY_TIMERS
GRVY::GRVY_Timer_Class grvy_timer;
grvy_timer.Init("GRINS Timer");
#endif
// Check command line count.
if( argc < 2 )
{
// TODO: Need more consistent error handling.
std::cerr << "Error: Must specify libMesh input file." << std::endl;
exit(1); // TODO: something more sophisticated for parallel runs?
}
// libMesh input file should be first argument
std::string libMesh_input_filename = argv[1];
// Create our GetPot object.
GetPot libMesh_inputfile( libMesh_input_filename );
#ifdef GRINS_USE_GRVY_TIMERS
grvy_timer.BeginTimer("Initialize Solver");
#endif
// Initialize libMesh library.
libMesh::LibMeshInit libmesh_init(argc, argv);
// Build a 1-d turbulent_bc_system to get the bc data from files
libMesh::SerialMesh mesh(libmesh_init.comm());
mesh.read("/home/vikram/grins/test/test_data/turbulent_channel_Re944_grid.xda");
//mesh.all_second_order();
// And an EquationSystems to run on it
libMesh::EquationSystems equation_systems (mesh);
libMesh::LinearImplicitSystem & turbulent_bc_system = equation_systems.add_system<libMesh::LinearImplicitSystem>("Turbulent-BC");
equation_systems.read("/home/vikram/grins/test/test_data/turbulent_channel_soln.xda", libMesh::XdrMODE::READ,
libMesh::EquationSystems::READ_HEADER |
libMesh::EquationSystems::READ_DATA |
libMesh::EquationSystems::READ_ADDITIONAL_DATA);
// Prepare a global solution and a MeshFunction of the Turbulent system
libMesh::AutoPtr<libMesh::MeshFunction> turbulent_bc_values;
libMesh::AutoPtr<libMesh::NumericVector<libMesh::Number> > turbulent_bc_soln = libMesh::NumericVector<libMesh::Number>::build(turbulent_bc_system.comm());
std::vector<unsigned int>turbulent_bc_system_variables;
turbulent_bc_system_variables.push_back(0);
turbulent_bc_system_variables.push_back(3);
turbulent_bc_values = libMesh::AutoPtr<libMesh::MeshFunction>
(new libMesh::MeshFunction(equation_systems,
*turbulent_bc_soln,
turbulent_bc_system.get_dof_map(),
turbulent_bc_system_variables ));
turbulent_bc_values->init();
TurbulentBdyFunction turbulent_inlet(turbulent_bc_values.get());
const libMesh::boundary_id_type left_inlet_id = 0;
std::set<libMesh::boundary_id_type> left_inlet_bdy;
left_inlet_bdy.insert(left_inlet_id);
// The uv identifier for the setting the inlet and wall velocity boundary conditions
std::vector<unsigned int> unu(1, 0);
unu.push_back(3);
turbulent_bc_system.get_dof_map().add_dirichlet_boundary
(libMesh::DirichletBoundary (left_inlet_bdy, unu, &turbulent_inlet));
GRINS::SimulationBuilder sim_builder;
//std::tr1::shared_ptr<ParabolicBCFactory> bc_factory( new ParabolicBCFactory );
//sim_builder.attach_bc_factory(bc_factory);
GRINS::Simulation grins( libMesh_inputfile,
sim_builder,
libmesh_init.comm() );
#ifdef GRINS_USE_GRVY_TIMERS
grvy_timer.EndTimer("Initialize Solver");
// Attach GRVY timer to solver
grins.attach_grvy_timer( &grvy_timer );
#endif
// Solve
grins.run();
// Get equation systems to create ExactSolution object
//std::tr1::shared_ptr<libMesh::EquationSystems> es = grins.get_equation_system();
// Create Exact solution object and attach exact solution quantities
//libMesh::ExactSolution exact_sol(*es);
//exact_sol.attach_exact_value(&exact_solution);
//exact_sol.attach_exact_deriv(&exact_derivative);
// Compute error and get it in various norms
//exact_sol.compute_error("GRINS", "u");
//double l2error = exact_sol.l2_error("GRINS", "u");
//double h1error = exact_sol.h1_error("GRINS", "u");
// Needs to change to 1 based on comparison
int return_flag = 0;
// if( l2error > 1.0e-9 || h1error > 1.0e-9 )
// {
// return_flag = 1;
// std::cout << "Tolerance exceeded for velocity in Poiseuille test." << std::endl
// << "l2 error = " << l2error << std::endl
// << "h1 error = " << h1error << std::endl;
// }
// // Compute error and get it in various norms
// exact_sol.compute_error("GRINS", "p");
// l2error = exact_sol.l2_error("GRINS", "p");
// h1error = exact_sol.h1_error("GRINS", "p");
// if( l2error > 2.0e-9 || h1error > 2.0e-9 )
// {
// return_flag = 1;
// std::cout << "Tolerance exceeded for pressure in Poiseuille test." << std::endl
// << "l2 error = " << l2error << std::endl
// << "h1 error = " << h1error << std::endl;
// }
return return_flag;
}
// libMesh::Number
// exact_solution( const libMesh::Point& p,
// const libMesh::Parameters&, // parameters, not needed
// const std::string&, // sys_name, not needed
// const std::string&); // unk_name, not needed);
// libMesh::Gradient
// exact_derivative( const libMesh::Point& p,
// const libMesh::Parameters&, // parameters, not needed
// const std::string&, // sys_name, not needed
// const std::string&); // unk_name, not needed);
// class ParabolicBCFactory : public GRINS::BoundaryConditionsFactory
// {
// public:
// ParabolicBCFactory()
// : GRINS::BoundaryConditionsFactory()
// { return; };
// ~ParabolicBCFactory(){return;};
// std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > build_dirichlet( );
// };
// std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > ParabolicBCFactory::build_dirichlet( )
// {
// GRINS::DBCContainer cont;
// cont.add_var_name( "u" );
// cont.add_bc_id( 1 );
// cont.add_bc_id( 3 );
// std::tr1::shared_ptr<libMesh::FunctionBase<libMesh::Number> > u_func( new GRINS::ParabolicProfile );
// cont.set_func( u_func );
// std::multimap< GRINS::PhysicsName, GRINS::DBCContainer > mymap;
// mymap.insert( std::pair<GRINS::PhysicsName, GRINS::DBCContainer >(GRINS::incompressible_navier_stokes, cont) );
// return mymap;
// }
// libMesh::Number
// exact_solution( const libMesh::Point& p,
// const libMesh::Parameters& /*params*/, // parameters, not needed
// const std::string& /*sys_name*/, // sys_name, not needed
// const std::string& var ) // unk_name, not needed);
// {
// const double x = p(0);
// const double y = p(1);
// libMesh::Number f = 0;
// // Hardcoded to velocity in input file.
// if( var == "u" ) f = 4*y*(1-y);
// else if( var == "p" ) f = 120.0 + (80.0-120.0)/5.0*x;
// else libmesh_assert(false);
// return f;
// }
// libMesh::Gradient
// exact_derivative( const libMesh::Point& p,
// const libMesh::Parameters& /*params*/, // parameters, not needed
// const std::string& /*sys_name*/, // sys_name, not needed
// const std::string& var) // unk_name, not needed);
// {
// const double y = p(1);
// libMesh::Gradient g;
// // Hardcoded to velocity in input file.
// if( var == "u" )
// {
// g(0) = 0.0;
// g(1) = 4*(1-y) - 4*y;
// #if LIBMESH_DIM > 2
// g(2) = 0.0;
// #endif
// }
// if( var == "p" )
// {
// g(0) = (80.0-120.0)/5.0;
// g(1) = 0.0;
// #if LIBMESH_DIM > 2
// g(2) = 0.0;
// #endif
// }
// return g;
// }
<|endoftext|>
|
<commit_before>#include "qextserialport.h"
#include "qextserialenumerator.h"
#include "dialog.h"
#include "ui_dialog.h"
#include <QtCore>
#include <QDebug>
#include <QFileDialog>
#include <QThread>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QStandardPaths>
#include <QFileInfo>
#include <QApplication>
#include <QDesktopWidget>
#include <QTimer>
#include <QWebHistory>
#include <QMessageBox>
#include <QSettings>
#include "qgc.h"
#include "qgcfirmwareupgradeworker.h"
Dialog::Dialog(QWidget *parent) :
QWidget(parent),
loading(false),
ui(new Ui::Dialog)
{
ui->setupUi(this);
foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
if (!info.portName.isEmpty())
ui->portBox->addItem(info.portName);
//make sure user can input their own port name!
ui->portBox->setEditable(true);
// ui->led->turnOff();
PortSettings settings = {BAUD9600, DATA_8, PAR_NONE, STOP_1, FLOW_OFF, 10};
port = new QextSerialPort(ui->portBox->currentText(), settings, QextSerialPort::Polling);
enumerator = new QextSerialEnumerator(this);
enumerator->setUpNotifications();
ui->boardComboBox->addItem("PX4FMU v1.6+", 5);
ui->boardComboBox->addItem("PX4FLOW v1.1+", 6);
ui->boardComboBox->addItem("PX4IO v1.3+", 7);
ui->boardComboBox->addItem("PX4 board #8", 8);
ui->boardComboBox->addItem("PX4 board #9", 9);
ui->boardComboBox->addItem("PX4 board #10", 10);
ui->boardComboBox->addItem("PX4 board #11", 11);
connect(ui->portBox, SIGNAL(editTextChanged(QString)), SLOT(onPortNameChanged(QString)));
connect(ui->flashButton, SIGNAL(clicked()), SLOT(onUploadButtonClicked()));
connect(ui->selectFileButton, SIGNAL(clicked()), SLOT(onFileSelectRequested()));
connect(ui->cancelButton, SIGNAL(clicked()), SLOT(onCancelButtonClicked()));
connect(ui->webView->page(), SIGNAL(downloadRequested(const QNetworkRequest&)), this, SLOT(onDownloadRequested(const QNetworkRequest&)));
ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
connect(ui->webView->page(), SIGNAL(linkClicked(const QUrl&)), this, SLOT(onLinkClicked(const QUrl&)));
connect(ui->prevButton, SIGNAL(clicked()), ui->webView, SLOT(back()));
connect(ui->homeButton, SIGNAL(clicked()), this, SLOT(onHomeRequested()));
connect(ui->advancedCheckBox, SIGNAL(clicked(bool)), this, SLOT(onToggleAdvancedMode(bool)));
connect(enumerator, SIGNAL(deviceDiscovered(QextPortInfo)), SLOT(onPortAddedOrRemoved()));
connect(enumerator, SIGNAL(deviceRemoved(QextPortInfo)), SLOT(onPortAddedOrRemoved()));
setWindowTitle(tr("QUpgrade Firmware Upload / Configuration Tool"));
// Adjust the size
const int screenHeight = qMin(1000, QApplication::desktop()->height() - 100);
resize(700, qMax(screenHeight, 550));
// about:blank shouldn't be part of the history
ui->webView->history()->clear();
onHomeRequested();
// load settings
loadSettings();
// Set up initial state
if (!lastFilename.isEmpty()) {
ui->flashButton->setEnabled(true);
} else {
ui->flashButton->setEnabled(false);
}
}
Dialog::~Dialog()
{
storeSettings();
delete ui;
delete port;
}
void Dialog::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void Dialog::onToggleAdvancedMode(bool enabled)
{
ui->selectFileButton->setVisible(enabled);
ui->flashButton->setVisible(enabled);
ui->portBox->setVisible(enabled);
ui->portLabel->setVisible(enabled);
ui->boardIdLabel->setVisible(enabled);
ui->boardComboBox->setVisible(enabled);
// Hide web view if advanced
ui->webView->setVisible(!enabled);
ui->homeButton->setVisible(!enabled);
ui->prevButton->setVisible(!enabled);
}
void Dialog::loadSettings()
{
QSettings set;
lastFilename = set.value("LAST_FILENAME", lastFilename).toString();
ui->advancedCheckBox->setChecked(set.value("ADVANCED_MODE", false).toBool());
int boardIndex = ui->boardComboBox->findData(set.value("BOARD_ID", 5));
if (boardIndex >= 0)
ui->boardComboBox->setCurrentIndex(boardIndex);
int portIndex = ui->portBox->findText(set.value("PORT_NAME", "").toString());
if (portIndex >= 0) {
ui->portBox->setCurrentIndex(portIndex);
} else {
qDebug() << "could not find port" << set.value("PORT_NAME", "");
}
onToggleAdvancedMode(ui->advancedCheckBox->isChecked());
// Check if in advanced mode
if (!lastFilename.isEmpty() && ui->advancedCheckBox->isChecked()) {
ui->upgradeLog->appendPlainText(tr("Pre-selected file %1\nfor flashing (click 'Flash' to upgrade)").arg(lastFilename));
updateBoardId(lastFilename);
}
}
void Dialog::storeSettings()
{
QSettings set;
if (lastFilename != "")
set.setValue("LAST_FILENAME", lastFilename);
set.setValue("ADVANCED_MODE", ui->advancedCheckBox->isChecked());
set.setValue("BOARD_ID", ui->boardComboBox->itemData(ui->boardComboBox->currentIndex()));
set.setValue("PORT_NAME", ui->portBox->currentText());
}
void Dialog::updateBoardId(const QString &fileName) {
// XXX this should be moved in separe classes
if (fileName.endsWith(".px4")) {
// Attempt to decode JSON
QFile json(lastFilename);
json.open(QIODevice::ReadOnly | QIODevice::Text);
QByteArray jbytes = json.readAll();
QJsonDocument doc = QJsonDocument::fromJson(jbytes);
if (doc.isNull()) {
// Error, bail out
ui->upgradeLog->appendPlainText(tr("supplied file is not a valid JSON document"));
}
QJsonObject px4 = doc.object();
int checkBoardId = (int) (px4.value(QString("board_id")).toDouble());
ui->upgradeLog->appendPlainText(tr("loaded file for board ID %1").arg(checkBoardId));
// Set correct board ID
int index = ui->boardComboBox->findData(checkBoardId);
if (index >= 0) {
ui->boardComboBox->setCurrentIndex(index);
} else {
qDebug() << "Combo box: board not found:" << index;
}
}
}
void Dialog::onHomeRequested()
{
// Load start file into web view
ui->webView->setUrl(QUrl::fromUserInput(QCoreApplication::applicationDirPath()+"/files/html/index.html"));
ui->homeButton->setEnabled(false);
ui->prevButton->setEnabled(false);
}
void Dialog::onLinkClicked(const QUrl &url)
{
QString firmwareFile = QFileInfo(url.toString()).fileName();
// If not a firmware file, ignore
if (!(firmwareFile.endsWith(".px4") || firmwareFile.endsWith(".bin"))) {
ui->webView->load(url);
ui->homeButton->setEnabled(true);
ui->prevButton->setEnabled(true);
return;
}
QString filename;
// If a IO firmware file, open save as Dialog
if (firmwareFile.endsWith(".bin") && firmwareFile.contains("px4io")) {
QString path = QString(QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));
qDebug() << path;
filename = QFileDialog::getExistingDirectory(this, tr("Select folder (microSD Card)"),
path);
filename.append("/" + firmwareFile);
} else {
// Make sure the user doesn't screw up flashing
QMessageBox msgBox;
msgBox.setText("Please unplug your PX4 board now");
msgBox.exec();
filename = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
if (filename.isEmpty()) {
qDebug() << "Falling back to temp dir";
QString filename = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
// If still empty, bail out
if (filename.isEmpty())
ui->upgradeLog->appendHtml(tr("FAILED storing firmware to downloads or temp directory. Harddisk not writable."));
return;
}
filename += "/" + firmwareFile;
}
if (filename == "") {
return;
}
// Else, flash the firmware
lastFilename = filename;
// Pattern matched, abort current QWebView load
ui->webView->stop();
ui->upgradeLog->appendHtml(tr("Downloading firmware file <a href=\"%1\">%1</a>").arg(url.toString()));
QNetworkRequest newRequest(url);
newRequest.setUrl(url);
newRequest.setAttribute(QNetworkRequest::User, filename);
QNetworkAccessManager *networkManager = ui->webView->page()->networkAccessManager();
QNetworkReply *reply = networkManager->get(newRequest);
connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onDownloadProgress(qint64, qint64)));
connect(reply, SIGNAL(finished()), this, SLOT(onDownloadFinished()));
}
void Dialog::onDownloadRequested(const QNetworkRequest &request)
{
onLinkClicked(request.url());
}
void Dialog::onPortNameChanged(const QString & /*name*/)
{
if (port->isOpen()) {
port->close();
// ui->led->turnOff();
}
}
void Dialog::onDownloadFinished()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
if (!reply) {
// bail out, nothing to do
return;
}
if (loading) {
onCancelButtonClicked();
ui->upgradeLog->appendPlainText(tr("Waiting for firmware flashing to complete.."));
} else {
// Reset progress
ui->upgradeProgressBar->setValue(0);
// Pick file
QString fileName = lastFilename;
qDebug() << "Handling filename:" << fileName;
// Store file in download location
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
fprintf(stderr, "Could not open %s for writing: %s\n",
qPrintable(fileName),
qPrintable(file.errorString()));
return;
}
file.write(reply->readAll());
if (lastFilename.contains("px4io")) {
// Done, bail out
return;
}
if (fileName.length() > 0) {
// Got a filename, upload
onLoadStart();
lastFilename = fileName;
worker = QGCFirmwareUpgradeWorker::putWorkerInThread(fileName);
// Hook up status from worker to progress bar
connect(worker, SIGNAL(upgradeProgressChanged(int)), ui->upgradeProgressBar, SLOT(setValue(int)));
// Hook up text from worker to label
connect(worker, SIGNAL(upgradeStatusChanged(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
// Hook up error handling
//connect(worker, SIGNAL(error(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
// Hook up status from worker to this class
connect(worker, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
// Make sure user gets the board going now
QMessageBox msgBox;
msgBox.setText("Please connect your PX4 board now");
msgBox.exec();
}
}
}
void Dialog::onFileSelectRequested()
{
if (loading) {
worker->abortUpload();
loading = false;
ui->flashButton->setEnabled(true);
}
// Pick file
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Firmware File"), lastFilename, tr("Firmware Files (*.px4 *.bin)"));
if (fileName != "") {
lastFilename = fileName;
updateBoardId(lastFilename);
}
}
void Dialog::onCancelButtonClicked()
{
if (loading) {
worker->abortUpload();
ui->cancelButton->setEnabled(false);
ui->upgradeLog->appendPlainText(tr("Waiting for last upgrade operaton to abort.."));
}
}
void Dialog::onUploadButtonClicked()
{
if (loading) {
onCancelButtonClicked();
} else {
if (lastFilename.length() > 0) {
// Got a filename, upload
loading = true;
ui->flashButton->setEnabled(false);
ui->cancelButton->setEnabled(true);
int id = -1;
// Set board ID for worker
if (ui->boardComboBox->isVisible()) {
bool ok;
int tmp = ui->boardComboBox->itemData(ui->boardComboBox->currentIndex()).toInt(&ok);
if (ok)
id = tmp;
}
worker = QGCFirmwareUpgradeWorker::putWorkerInThread(lastFilename, ui->portBox->currentText(), id);
connect(ui->portBox, SIGNAL(currentTextChanged(QString)), worker, SLOT(setPort(QString)));
// Hook up status from worker to progress bar
connect(worker, SIGNAL(upgradeProgressChanged(int)), ui->upgradeProgressBar, SLOT(setValue(int)));
// Hook up text from worker to label
connect(worker, SIGNAL(upgradeStatusChanged(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
// Hook up error handling
connect(worker, SIGNAL(error(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
// Hook up status from worker to this class
connect(worker, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
}
}
}
void Dialog::onPortAddedOrRemoved()
{
QString current = ui->portBox->currentText();
ui->portBox->blockSignals(true);
// Delete old ports
for (int i = 0; i < ui->portBox->count(); i++)
{
bool found = false;
foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
if (info.portName == ui->portBox->itemText(i))
found = true;
if (!found && !ui->portBox->itemText(i).contains("Automatic"))
ui->portBox->removeItem(i);
}
// Add new ports
foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
if (ui->portBox->findText(info.portName) < 0) {
if (!info.portName.isEmpty())
ui->portBox->addItem(info.portName);
}
ui->portBox->blockSignals(false);
}
void Dialog::onLoadStart()
{
loading = true;
ui->flashButton->setEnabled(false);
ui->cancelButton->setEnabled(true);
}
void Dialog::onLoadFinished(bool success)
{
loading = false;
ui->flashButton->setEnabled(true);
ui->cancelButton->setEnabled(false);
if (success) {
ui->upgradeLog->appendPlainText(tr("Upload succeeded."));
} else {
ui->upgradeLog->appendPlainText(tr("Upload aborted and failed."));
ui->upgradeProgressBar->setValue(0);
}
}
void Dialog::onDownloadProgress(qint64 curr, qint64 total)
{
// Take care of cases where 0 / 0 is emitted as error return value
if (total > 0)
ui->upgradeProgressBar->setValue((curr*100) / total);
}
<commit_msg>Attempt to fix windows symptoms<commit_after>#include "qextserialport.h"
#include "qextserialenumerator.h"
#include "dialog.h"
#include "ui_dialog.h"
#include <QtCore>
#include <QDebug>
#include <QFileDialog>
#include <QThread>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QStandardPaths>
#include <QFileInfo>
#include <QApplication>
#include <QDesktopWidget>
#include <QTimer>
#include <QWebHistory>
#include <QMessageBox>
#include <QSettings>
#include "qgc.h"
#include "qgcfirmwareupgradeworker.h"
Dialog::Dialog(QWidget *parent) :
QWidget(parent),
loading(false),
ui(new Ui::Dialog)
{
ui->setupUi(this);
foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
if (!info.portName.isEmpty())
ui->portBox->addItem(info.portName);
//make sure user can input their own port name!
ui->portBox->setEditable(true);
// ui->led->turnOff();
PortSettings settings = {BAUD9600, DATA_8, PAR_NONE, STOP_1, FLOW_OFF, 10};
port = new QextSerialPort(ui->portBox->currentText(), settings, QextSerialPort::Polling);
enumerator = new QextSerialEnumerator(this);
enumerator->setUpNotifications();
ui->boardComboBox->addItem("PX4FMU v1.6+", 5);
ui->boardComboBox->addItem("PX4FLOW v1.1+", 6);
ui->boardComboBox->addItem("PX4IO v1.3+", 7);
ui->boardComboBox->addItem("PX4 board #8", 8);
ui->boardComboBox->addItem("PX4 board #9", 9);
ui->boardComboBox->addItem("PX4 board #10", 10);
ui->boardComboBox->addItem("PX4 board #11", 11);
connect(ui->portBox, SIGNAL(editTextChanged(QString)), SLOT(onPortNameChanged(QString)));
connect(ui->flashButton, SIGNAL(clicked()), SLOT(onUploadButtonClicked()));
connect(ui->selectFileButton, SIGNAL(clicked()), SLOT(onFileSelectRequested()));
connect(ui->cancelButton, SIGNAL(clicked()), SLOT(onCancelButtonClicked()));
connect(ui->webView->page(), SIGNAL(downloadRequested(const QNetworkRequest&)), this, SLOT(onDownloadRequested(const QNetworkRequest&)));
ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
connect(ui->webView->page(), SIGNAL(linkClicked(const QUrl&)), this, SLOT(onLinkClicked(const QUrl&)));
connect(ui->prevButton, SIGNAL(clicked()), ui->webView, SLOT(back()));
connect(ui->homeButton, SIGNAL(clicked()), this, SLOT(onHomeRequested()));
connect(ui->advancedCheckBox, SIGNAL(clicked(bool)), this, SLOT(onToggleAdvancedMode(bool)));
connect(enumerator, SIGNAL(deviceDiscovered(QextPortInfo)), SLOT(onPortAddedOrRemoved()));
connect(enumerator, SIGNAL(deviceRemoved(QextPortInfo)), SLOT(onPortAddedOrRemoved()));
setWindowTitle(tr("QUpgrade Firmware Upload / Configuration Tool"));
// Adjust the size
const int screenHeight = qMin(1000, QApplication::desktop()->height() - 100);
resize(700, qMax(screenHeight, 550));
// about:blank shouldn't be part of the history
ui->webView->history()->clear();
onHomeRequested();
// load settings
loadSettings();
// Set up initial state
if (!lastFilename.isEmpty()) {
ui->flashButton->setEnabled(true);
} else {
ui->flashButton->setEnabled(false);
}
}
Dialog::~Dialog()
{
storeSettings();
delete ui;
delete port;
}
void Dialog::changeEvent(QEvent *e)
{
QWidget::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void Dialog::onToggleAdvancedMode(bool enabled)
{
ui->selectFileButton->setVisible(enabled);
ui->flashButton->setVisible(enabled);
ui->portBox->setVisible(enabled);
ui->portLabel->setVisible(enabled);
ui->boardIdLabel->setVisible(enabled);
ui->boardComboBox->setVisible(enabled);
// Hide web view if advanced
ui->webView->setVisible(!enabled);
ui->homeButton->setVisible(!enabled);
ui->prevButton->setVisible(!enabled);
}
void Dialog::loadSettings()
{
QSettings set;
lastFilename = set.value("LAST_FILENAME", lastFilename).toString();
ui->advancedCheckBox->setChecked(set.value("ADVANCED_MODE", false).toBool());
int boardIndex = ui->boardComboBox->findData(set.value("BOARD_ID", 5));
if (boardIndex >= 0)
ui->boardComboBox->setCurrentIndex(boardIndex);
int portIndex = ui->portBox->findText(set.value("PORT_NAME", "").toString());
if (portIndex >= 0) {
ui->portBox->setCurrentIndex(portIndex);
} else {
qDebug() << "could not find port" << set.value("PORT_NAME", "");
}
onToggleAdvancedMode(ui->advancedCheckBox->isChecked());
// Check if in advanced mode
if (!lastFilename.isEmpty() && ui->advancedCheckBox->isChecked()) {
ui->upgradeLog->appendPlainText(tr("Pre-selected file %1\nfor flashing (click 'Flash' to upgrade)").arg(lastFilename));
updateBoardId(lastFilename);
}
}
void Dialog::storeSettings()
{
QSettings set;
if (lastFilename != "")
set.setValue("LAST_FILENAME", lastFilename);
set.setValue("ADVANCED_MODE", ui->advancedCheckBox->isChecked());
set.setValue("BOARD_ID", ui->boardComboBox->itemData(ui->boardComboBox->currentIndex()));
set.setValue("PORT_NAME", ui->portBox->currentText());
}
void Dialog::updateBoardId(const QString &fileName) {
// XXX this should be moved in separe classes
if (fileName.endsWith(".px4")) {
// Attempt to decode JSON
QFile json(lastFilename);
json.open(QIODevice::ReadOnly | QIODevice::Text);
QByteArray jbytes = json.readAll();
QJsonDocument doc = QJsonDocument::fromJson(jbytes);
if (doc.isNull()) {
// Error, bail out
ui->upgradeLog->appendPlainText(tr("supplied file is not a valid JSON document"));
}
QJsonObject px4 = doc.object();
int checkBoardId = (int) (px4.value(QString("board_id")).toDouble());
ui->upgradeLog->appendPlainText(tr("loaded file for board ID %1").arg(checkBoardId));
// Set correct board ID
int index = ui->boardComboBox->findData(checkBoardId);
if (index >= 0) {
ui->boardComboBox->setCurrentIndex(index);
} else {
qDebug() << "Combo box: board not found:" << index;
}
}
}
void Dialog::onHomeRequested()
{
// Load start file into web view
ui->webView->setUrl(QUrl::fromUserInput(QCoreApplication::applicationDirPath()+"/files/html/index.html"));
ui->homeButton->setEnabled(false);
ui->prevButton->setEnabled(false);
}
void Dialog::onLinkClicked(const QUrl &url)
{
QString firmwareFile = QFileInfo(url.toString()).fileName();
// If not a firmware file, ignore
if (!(firmwareFile.endsWith(".px4") || firmwareFile.endsWith(".bin"))) {
ui->webView->load(url);
ui->homeButton->setEnabled(true);
ui->prevButton->setEnabled(true);
return;
}
QString filename;
// If a IO firmware file, open save as Dialog
if (firmwareFile.endsWith(".bin") && firmwareFile.contains("px4io")) {
QString path = QString(QStandardPaths::writableLocation(QStandardPaths::DownloadLocation));
qDebug() << path;
filename = QFileDialog::getExistingDirectory(this, tr("Select folder (microSD Card)"),
path);
filename.append("/" + firmwareFile);
} else {
// Make sure the user doesn't screw up flashing
QMessageBox msgBox;
msgBox.setText("Please unplug your PX4 board now");
msgBox.exec();
filename = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation);
if (filename.isEmpty()) {
qDebug() << "Falling back to temp dir";
QString filename = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
// If still empty, bail out
if (filename.isEmpty())
ui->upgradeLog->appendHtml(tr("FAILED storing firmware to downloads or temp directory. Harddisk not writable."));
return;
}
filename += "/" + firmwareFile;
}
if (filename == "") {
return;
}
// Else, flash the firmware
lastFilename = filename;
ui->upgradeLog->appendHtml(tr("Downloading firmware file <a href=\"%1\">%1</a>").arg(url.toString()));
QNetworkRequest newRequest(url);
newRequest.setUrl(url);
newRequest.setAttribute(QNetworkRequest::User, filename);
QNetworkAccessManager *networkManager = ui->webView->page()->networkAccessManager();
QNetworkReply *reply = networkManager->get(newRequest);
connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(onDownloadProgress(qint64, qint64)));
connect(reply, SIGNAL(finished()), this, SLOT(onDownloadFinished()));
}
void Dialog::onDownloadRequested(const QNetworkRequest &request)
{
onLinkClicked(request.url());
}
void Dialog::onPortNameChanged(const QString & /*name*/)
{
if (port->isOpen()) {
port->close();
// ui->led->turnOff();
}
}
void Dialog::onDownloadFinished()
{
QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
if (!reply) {
// bail out, nothing to do
ui->upgradeLog->appendPlainText("Download failed, invalid context");
return;
}
if (loading) {
onCancelButtonClicked();
ui->upgradeLog->appendPlainText(tr("Still flashing. Waiting for firmware flashing to complete.."));
} else {
// Reset progress
ui->upgradeProgressBar->setValue(0);
// Pick file
QString fileName = lastFilename;
qDebug() << "Handling filename:" << fileName;
// Store file in download location
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly)) {
ui->upgradeLog->appendPlainText(tr("Could not open %s for writing: %s\n").arg(fileName).arg(file.errorString()));
return;
}
file.write(reply->readAll());
file.close();
if (lastFilename.contains("px4io")) {
// Done, bail out
return;
}
if (fileName.length() > 0) {
// Got a filename, upload
onLoadStart();
lastFilename = fileName;
worker = QGCFirmwareUpgradeWorker::putWorkerInThread(fileName);
// Hook up status from worker to progress bar
connect(worker, SIGNAL(upgradeProgressChanged(int)), ui->upgradeProgressBar, SLOT(setValue(int)));
// Hook up text from worker to label
connect(worker, SIGNAL(upgradeStatusChanged(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
// Hook up error handling
//connect(worker, SIGNAL(error(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
// Hook up status from worker to this class
connect(worker, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
// Make sure user gets the board going now
QMessageBox msgBox;
msgBox.setText("Please connect your PX4 board now");
msgBox.exec();
}
}
}
void Dialog::onFileSelectRequested()
{
if (loading) {
worker->abortUpload();
loading = false;
ui->flashButton->setEnabled(true);
}
// Pick file
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open Firmware File"), lastFilename, tr("Firmware Files (*.px4 *.bin)"));
if (fileName != "") {
lastFilename = fileName;
updateBoardId(lastFilename);
}
}
void Dialog::onCancelButtonClicked()
{
if (loading) {
worker->abortUpload();
ui->cancelButton->setEnabled(false);
ui->upgradeLog->appendPlainText(tr("Waiting for last upgrade operaton to abort.."));
}
}
void Dialog::onUploadButtonClicked()
{
if (loading) {
onCancelButtonClicked();
} else {
if (lastFilename.length() > 0) {
// Got a filename, upload
loading = true;
ui->flashButton->setEnabled(false);
ui->cancelButton->setEnabled(true);
int id = -1;
// Set board ID for worker
if (ui->boardComboBox->isVisible()) {
bool ok;
int tmp = ui->boardComboBox->itemData(ui->boardComboBox->currentIndex()).toInt(&ok);
if (ok)
id = tmp;
}
worker = QGCFirmwareUpgradeWorker::putWorkerInThread(lastFilename, ui->portBox->currentText(), id);
connect(ui->portBox, SIGNAL(currentTextChanged(QString)), worker, SLOT(setPort(QString)));
// Hook up status from worker to progress bar
connect(worker, SIGNAL(upgradeProgressChanged(int)), ui->upgradeProgressBar, SLOT(setValue(int)));
// Hook up text from worker to label
connect(worker, SIGNAL(upgradeStatusChanged(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
// Hook up error handling
connect(worker, SIGNAL(error(QString)), ui->upgradeLog, SLOT(appendPlainText(QString)));
// Hook up status from worker to this class
connect(worker, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
}
}
}
void Dialog::onPortAddedOrRemoved()
{
QString current = ui->portBox->currentText();
ui->portBox->blockSignals(true);
// Delete old ports
for (int i = 0; i < ui->portBox->count(); i++)
{
bool found = false;
foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
if (info.portName == ui->portBox->itemText(i))
found = true;
if (!found && !ui->portBox->itemText(i).contains("Automatic"))
ui->portBox->removeItem(i);
}
// Add new ports
foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
if (ui->portBox->findText(info.portName) < 0) {
if (!info.portName.isEmpty())
ui->portBox->addItem(info.portName);
}
ui->portBox->blockSignals(false);
}
void Dialog::onLoadStart()
{
loading = true;
ui->flashButton->setEnabled(false);
ui->cancelButton->setEnabled(true);
}
void Dialog::onLoadFinished(bool success)
{
loading = false;
ui->flashButton->setEnabled(true);
ui->cancelButton->setEnabled(false);
if (success) {
ui->upgradeLog->appendPlainText(tr("Upload succeeded."));
} else {
ui->upgradeLog->appendPlainText(tr("Upload aborted and failed."));
ui->upgradeProgressBar->setValue(0);
}
}
void Dialog::onDownloadProgress(qint64 curr, qint64 total)
{
// Take care of cases where 0 / 0 is emitted as error return value
if (total > 0)
ui->upgradeProgressBar->setValue((curr*100) / total);
}
<|endoftext|>
|
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_random_num.h"
#include "io_proxy.h"
#include "io_proxy_handler.h"
#include "ipv6_hostname.h"
#define IO_PROXY_COOKIE_SIZE 32
static char * cookie_create( int length );
IOProxy::IOProxy()
:
server(NULL),
m_shadow(NULL),
cookie(0),
socket_registered(false),
m_want_io(false),
m_want_updates(false),
m_want_delayed(false)
{
}
IOProxy::~IOProxy()
{
if ( daemonCore && socket_registered && server ) {
daemonCore->Cancel_Socket(server);
}
if ( server ) {
server->close();
delete server;
}
if(cookie) free(cookie);
}
/*
This callback is invoked for each new incoming connection.
In response, fork a new IOProxyHandler child to deal with the stream.
Returns KEEP_STREAM if the stream is still valid, ~KEEP_STREAM otherwise.
*/
int IOProxy::connect_callback( Stream * /*stream*/ )
{
ReliSock *client = new ReliSock;
bool accept_client = false;
int success;
success = server->accept(*client);
if(success) {
// TODO: This is arbitrarily picking IPv4. Should we match protocol of *client?
if(get_local_ipaddr(CP_IPV4).compare_address(client->peer_addr())) {
dprintf(D_FULLDEBUG,"IOProxy: accepting connection from %s\n",client->peer_ip_str());
accept_client = true;
} else {
dprintf(D_ALWAYS,"IOProxy: rejecting connection from %s: invalid ip addr\n",client->peer_ip_str());
}
} else {
dprintf(D_ALWAYS,"IOProxy: Couldn't accept connection: %s\n",strerror(errno));
}
if(accept_client) {
IOProxyHandler *handler = new IOProxyHandler(m_shadow, m_want_io, m_want_updates, m_want_delayed);
if(!handler->init(client,cookie)) {
dprintf(D_ALWAYS,"IOProxy: couldn't register request callback!\n");
client->close();
delete client;
}
} else {
client->close();
delete client;
}
return KEEP_STREAM;
}
/*
Initialize this proxy and dump the contact information into the given file.
Returns true on success, false otherwise.
*/
bool IOProxy::init( JICShadow *shadow, const char *config_file, bool want_io, bool want_updates, bool want_delayed )
{
m_shadow = shadow;
m_want_io = want_io;
m_want_updates = want_updates;
m_want_delayed = want_delayed;
FILE *file=0;
int fd=-1;
server = new ReliSock;
if ( !server ) {
dprintf(D_ALWAYS,"IOProxy: couldn't create socket\n");
return false;
}
if(!server->bind(false)) {
dprintf(D_ALWAYS,"IOProxy: couldn't bind: %s\n",strerror(errno));
return false;
}
if(!server->listen()) {
dprintf(D_ALWAYS,"IOProxy: couldn't listen: %s\n",strerror(errno));
return false;
}
cookie = cookie_create(IO_PROXY_COOKIE_SIZE);
if(!cookie) {
dprintf(D_ALWAYS,"IOProxy: couldn't create cookie: %s\n",strerror(errno));
goto failure;
}
fd = safe_open_wrapper_follow(config_file,
O_CREAT|O_TRUNC|O_WRONLY,
0700);
if(fd<0) {
dprintf(D_ALWAYS,
"IOProxy: couldn't write to %s: %s\n",
config_file,
strerror(errno));
goto failure;
}
file = fdopen(fd,"w");
if(!file) {
dprintf(D_ALWAYS,"IOProxy: couldn't create I/O stream: %s\n",strerror(errno));
goto failure;
}
fprintf(file,"%s %d %s\n",my_ip_string(),server->get_port(),cookie);
fclose(file);
daemonCore->Register_Socket( server, "IOProxy listen socket",
(SocketHandlercpp) &IOProxy::connect_callback,
"IOProxy connect callback", this );
socket_registered = true;
return true;
failure:
if(cookie) free(cookie);
if(file) fclose(file);
IGNORE_RETURN unlink(config_file);
server->close();
return false;
}
/*
On success, returns a newly-allocated random cookie string.
On failure, returns null.
*/
static char * cookie_create( int length )
{
char *c = (char*) malloc(length);
if(!c) return 0;
for( int i=0; i<length; i++ ) {
c[i] = 'a'+get_random_int()%26;
}
c[length-1] = 0;
return c;
}
<commit_msg>The IO proxy (chirp server) in the starter now behaves more sanely in a multiprotocol world.<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_random_num.h"
#include "io_proxy.h"
#include "io_proxy_handler.h"
#include "ipv6_hostname.h"
#include "condor_config.h"
#define IO_PROXY_COOKIE_SIZE 32
static char * cookie_create( int length );
IOProxy::IOProxy()
:
server(NULL),
m_shadow(NULL),
cookie(0),
socket_registered(false),
m_want_io(false),
m_want_updates(false),
m_want_delayed(false)
{
}
IOProxy::~IOProxy()
{
if ( daemonCore && socket_registered && server ) {
daemonCore->Cancel_Socket(server);
}
if ( server ) {
server->close();
delete server;
}
if(cookie) free(cookie);
}
/*
This callback is invoked for each new incoming connection.
In response, fork a new IOProxyHandler child to deal with the stream.
Returns KEEP_STREAM if the stream is still valid, ~KEEP_STREAM otherwise.
*/
int IOProxy::connect_callback( Stream * /*stream*/ )
{
ReliSock *client = new ReliSock;
bool accept_client = false;
int success;
success = server->accept(*client);
if(success) {
// I'm not sure why we believe the socket could be bound to anything
// other than the address we want to hear from, but...
condor_sockaddr remote = client->peer_addr();
if( remote.is_loopback() ) {
dprintf(D_FULLDEBUG,"IOProxy: accepting connection from %s\n",client->peer_ip_str());
accept_client = true;
} else {
dprintf(D_ALWAYS,"IOProxy: rejecting connection from %s: invalid ip addr\n",client->peer_ip_str());
}
} else {
dprintf(D_ALWAYS,"IOProxy: Couldn't accept connection: %s\n",strerror(errno));
}
if(accept_client) {
IOProxyHandler *handler = new IOProxyHandler(m_shadow, m_want_io, m_want_updates, m_want_delayed);
if(!handler->init(client,cookie)) {
dprintf(D_ALWAYS,"IOProxy: couldn't register request callback!\n");
client->close();
delete client;
}
} else {
client->close();
delete client;
}
return KEEP_STREAM;
}
/*
Initialize this proxy and dump the contact information into the given file.
Returns true on success, false otherwise.
*/
bool IOProxy::init( JICShadow *shadow, const char *config_file, bool want_io, bool want_updates, bool want_delayed )
{
m_shadow = shadow;
m_want_io = want_io;
m_want_updates = want_updates;
m_want_delayed = want_delayed;
FILE *file=0;
int fd=-1;
server = new ReliSock;
if ( !server ) {
dprintf(D_ALWAYS,"IOProxy: couldn't create socket\n");
return false;
}
//
// Without other arguments, Sock::bind() now generates an IPv6 loopback
// address if we're in mixed-mode on machines without a real IPv6 address.
// That's fine (we'll rewrite the address on the way out if we have to),
// but my_ip_string() no longer matches, which causes chirp grief (because
// we pass our address to it here, via the chirp.config file).
//
// Instead, just go ahead and bind to IPv4 (unless it's disabled, in
// which case, use IPv6); and use the loopback address, which is more
// secure. Regardless, use the actual address on which we're listening
// to fill in the .chirp.config file.
//
condor_protocol proto = CP_IPV4;
if( ! param_boolean( "ENABLE_IPV4", true ) ) { proto = CP_IPV6; }
if(!server->bind( proto, false, 0, true )) {
dprintf(D_ALWAYS,"IOProxy: couldn't bind: %s\n",strerror(errno));
return false;
}
if(!server->listen()) {
dprintf(D_ALWAYS,"IOProxy: couldn't listen: %s\n",strerror(errno));
return false;
}
cookie = cookie_create(IO_PROXY_COOKIE_SIZE);
if(!cookie) {
dprintf(D_ALWAYS,"IOProxy: couldn't create cookie: %s\n",strerror(errno));
goto failure;
}
fd = safe_open_wrapper_follow(config_file,
O_CREAT|O_TRUNC|O_WRONLY,
0700);
if(fd<0) {
dprintf(D_ALWAYS,
"IOProxy: couldn't write to %s: %s\n",
config_file,
strerror(errno));
goto failure;
}
file = fdopen(fd,"w");
if(!file) {
dprintf(D_ALWAYS,"IOProxy: couldn't create I/O stream: %s\n",strerror(errno));
goto failure;
}
fprintf( file, "%s %d %s\n", server->my_ip_str(), server->get_port(), cookie );
fclose(file);
daemonCore->Register_Socket( server, "IOProxy listen socket",
(SocketHandlercpp) &IOProxy::connect_callback,
"IOProxy connect callback", this );
socket_registered = true;
return true;
failure:
if(cookie) free(cookie);
if(file) fclose(file);
IGNORE_RETURN unlink(config_file);
server->close();
return false;
}
/*
On success, returns a newly-allocated random cookie string.
On failure, returns null.
*/
static char * cookie_create( int length )
{
char *c = (char*) malloc(length);
if(!c) return 0;
for( int i=0; i<length; i++ ) {
c[i] = 'a'+get_random_int()%26;
}
c[length-1] = 0;
return c;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <folly/ScopeGuard.h>
#include <quic/dsr/frontend/WriteFunctions.h>
namespace quic {
uint64_t writePacketizationRequest(
QuicServerConnectionState& connection,
const ConnectionId& dstCid,
size_t packetLimit,
const Aead& aead,
TimePoint writeLoopBeginTime) {
DSRStreamFrameScheduler scheduler(connection);
uint64_t packetCounter = 0;
folly::F14FastSet<DSRPacketizationRequestSender*> senders;
SCOPE_EXIT {
std::for_each(
senders.begin(), senders.end(), [](auto* sender) { sender->flush(); });
};
if (!writeLoopTimeLimit(writeLoopBeginTime, connection)) {
return packetCounter;
}
while (scheduler.hasPendingData() && packetCounter < packetLimit &&
(packetCounter < connection.transportSettings.maxBatchSize ||
writeLoopTimeLimit(writeLoopBeginTime, connection))) {
auto packetNum = getNextPacketNum(connection, PacketNumberSpace::AppData);
ShortHeader header(ProtectionType::KeyPhaseZero, dstCid, packetNum);
auto writableBytes = std::min(
connection.udpSendPacketLen,
congestionControlWritableBytes(connection));
uint64_t cipherOverhead = aead.getCipherOverhead();
if (writableBytes < cipherOverhead) {
writableBytes = 0;
} else {
writableBytes -= cipherOverhead;
}
DSRPacketBuilder packetBuilder(
writableBytes,
std::move(header),
getAckState(connection, PacketNumberSpace::AppData)
.largestAckedByPeer.value_or(0));
auto schedulerResult = scheduler.writeStream(packetBuilder);
if (!schedulerResult.writeSuccess) {
/**
* Scheduling can fail when we:
* (1) run out of flow control
* (2) there is actually no DSR stream to write - we shouldn't come here
* in the first place though.
* (3) Packet is no space left - e.g., due to CC
* (4) Error in write codec - Can that happen?
*
* At least for (1) and (3), we should flush the sender.
*/
if (schedulerResult.sender) {
senders.insert(schedulerResult.sender);
}
return packetCounter;
}
CHECK(schedulerResult.sender);
auto packet = std::move(packetBuilder).buildPacket();
// The contract is that if scheduler can schedule, builder has to be able to
// build.
CHECK_GT(packet.encodedSize, 0);
bool instructionAddError = false;
for (const auto& instruction : packet.sendInstructions) {
if (!schedulerResult.sender->addSendInstruction(instruction)) {
instructionAddError = true;
break;
}
}
// Similar to the regular write case, if we build, we update connection
// states. The connection states are changed already no matter the result
// of addSendInstruction() call.
updateConnection(
connection,
folly::none /* Packet Event */,
packet.packet,
Clock::now(),
packet.encodedSize,
// TODO: (yangchi) Figure out how to calculate the
// packet.encodedBodySize for the DSR case. For now, it's not being
// used, so setting it to 0
0,
true /* isDSRPacket */);
connection.dsrPacketCount++;
if (instructionAddError) {
// TODO: Support empty write loop detection
senders.insert(schedulerResult.sender);
return packetCounter;
}
++packetCounter;
senders.insert(schedulerResult.sender);
}
return packetCounter;
}
} // namespace quic
<commit_msg>Add DSR flushing qlog events.<commit_after>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <folly/ScopeGuard.h>
#include <quic/dsr/frontend/WriteFunctions.h>
namespace quic {
uint64_t writePacketizationRequest(
QuicServerConnectionState& connection,
const ConnectionId& dstCid,
size_t packetLimit,
const Aead& aead,
TimePoint writeLoopBeginTime) {
DSRStreamFrameScheduler scheduler(connection);
uint64_t packetCounter = 0;
folly::F14FastSet<DSRPacketizationRequestSender*> senders;
SCOPE_EXIT {
for (auto sender : senders) {
if (connection.qLogger) {
connection.qLogger->addTransportStateUpdate("DSR flushing sender");
}
sender->flush();
}
};
if (!writeLoopTimeLimit(writeLoopBeginTime, connection)) {
return packetCounter;
}
while (scheduler.hasPendingData() && packetCounter < packetLimit &&
(packetCounter < connection.transportSettings.maxBatchSize ||
writeLoopTimeLimit(writeLoopBeginTime, connection))) {
auto packetNum = getNextPacketNum(connection, PacketNumberSpace::AppData);
ShortHeader header(ProtectionType::KeyPhaseZero, dstCid, packetNum);
auto writableBytes = std::min(
connection.udpSendPacketLen,
congestionControlWritableBytes(connection));
uint64_t cipherOverhead = aead.getCipherOverhead();
if (writableBytes < cipherOverhead) {
writableBytes = 0;
} else {
writableBytes -= cipherOverhead;
}
DSRPacketBuilder packetBuilder(
writableBytes,
std::move(header),
getAckState(connection, PacketNumberSpace::AppData)
.largestAckedByPeer.value_or(0));
auto schedulerResult = scheduler.writeStream(packetBuilder);
if (!schedulerResult.writeSuccess) {
/**
* Scheduling can fail when we:
* (1) run out of flow control
* (2) there is actually no DSR stream to write - we shouldn't come here
* in the first place though.
* (3) Packet is no space left - e.g., due to CC
* (4) Error in write codec - Can that happen?
*
* At least for (1) and (3), we should flush the sender.
*/
if (schedulerResult.sender) {
senders.insert(schedulerResult.sender);
}
return packetCounter;
}
CHECK(schedulerResult.sender);
auto packet = std::move(packetBuilder).buildPacket();
// The contract is that if scheduler can schedule, builder has to be able to
// build.
CHECK_GT(packet.encodedSize, 0);
bool instructionAddError = false;
for (const auto& instruction : packet.sendInstructions) {
if (!schedulerResult.sender->addSendInstruction(instruction)) {
instructionAddError = true;
break;
}
}
// Similar to the regular write case, if we build, we update connection
// states. The connection states are changed already no matter the result
// of addSendInstruction() call.
updateConnection(
connection,
folly::none /* Packet Event */,
packet.packet,
Clock::now(),
packet.encodedSize,
// TODO: (yangchi) Figure out how to calculate the
// packet.encodedBodySize for the DSR case. For now, it's not being
// used, so setting it to 0
0,
true /* isDSRPacket */);
connection.dsrPacketCount++;
if (instructionAddError) {
// TODO: Support empty write loop detection
senders.insert(schedulerResult.sender);
return packetCounter;
}
++packetCounter;
senders.insert(schedulerResult.sender);
}
return packetCounter;
}
} // namespace quic
<|endoftext|>
|
<commit_before>// Copyright 2015 Patrick Putnam
//
// 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 CLOTHO_WEIGHT_ACCUMULATOR_GUARD_HPP_
#define CLOTHO_WEIGHT_ACCUMULATOR_GUARD_HPP_
#include "clotho/data_spaces/phenotype_evaluator/weight_accumulator_def.hpp"
#include "clotho/data_spaces/phenotype_evaluator/column_aligned_weight_accumulator.hpp"
#include "clotho/data_spaces/phenotype_evaluator/row_grouped_weight_accumulator.hpp"
#endif // CLOTHO_WEIGHT_ACCUMULATOR_GUARD_HPP_
<commit_msg>Adding row vector based accumulator<commit_after>// Copyright 2015 Patrick Putnam
//
// 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 CLOTHO_WEIGHT_ACCUMULATOR_GUARD_HPP_
#define CLOTHO_WEIGHT_ACCUMULATOR_GUARD_HPP_
#include "clotho/data_spaces/phenotype_evaluator/weight_accumulator_def.hpp"
#include "clotho/data_spaces/phenotype_evaluator/column_aligned_weight_accumulator.hpp"
#include "clotho/data_spaces/phenotype_evaluator/row_grouped_weight_accumulator.hpp"
#include "clotho/data_spaces/phenotype_evaluator/row_vector_weight_accumulator.hpp"
#endif // CLOTHO_WEIGHT_ACCUMULATOR_GUARD_HPP_
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "test/core/util/test_config.h"
#include <thread>
#include "test/core/util/port.h"
#include "test/cpp/util/echo.grpc.pb.h"
#include "src/core/support/env.h"
#include <grpc++/channel_arguments.h>
#include <grpc++/channel_interface.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/server_credentials.h>
#include <grpc++/status.h>
#include <gtest/gtest.h>
#include <grpc/grpc.h>
#include <grpc/support/sync.h>
using grpc::cpp::test::util::EchoRequest;
using grpc::cpp::test::util::EchoResponse;
namespace grpc {
namespace testing {
class TestServiceImpl : public ::grpc::cpp::test::util::TestService::Service {
public:
explicit TestServiceImpl(gpr_event* ev) : ev_(ev) {}
Status Echo(ServerContext* context, const EchoRequest* request,
EchoResponse* response) GRPC_OVERRIDE {
gpr_event_set(ev_, (void*)1);
while (!context->IsCancelled()) {
}
return Status::OK;
}
private:
gpr_event* ev_;
};
class ShutdownTest : public ::testing::Test {
public:
ShutdownTest() : shutdown_(false), service_(&ev_) { gpr_event_init(&ev_); }
void SetUp() GRPC_OVERRIDE {
port_ = grpc_pick_unused_port_or_die();
server_ = SetUpServer(port_);
}
std::unique_ptr<Server> SetUpServer(const int port) {
grpc::string server_address = "localhost:" + to_string(port);
ServerBuilder builder;
builder.AddListeningPort(server_address, InsecureServerCredentials());
builder.RegisterService(&service_);
std::unique_ptr<Server> server = builder.BuildAndStart();
return server;
}
void TearDown() GRPC_OVERRIDE { GPR_ASSERT(shutdown_); }
void ResetStub() {
string target = "dns:localhost:" + to_string(port_);
channel_ = CreateChannel(target, InsecureCredentials(), ChannelArguments());
stub_ = std::move(grpc::cpp::test::util::TestService::NewStub(channel_));
}
string to_string(const int number) {
std::stringstream strs;
strs << number;
return strs.str();
}
void SendRequest() {
EchoRequest request;
EchoResponse response;
request.set_message("Hello");
ClientContext context;
GPR_ASSERT(!shutdown_);
Status s = stub_->Echo(&context, request, &response);
GPR_ASSERT(shutdown_);
}
protected:
std::shared_ptr<ChannelInterface> channel_;
std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub_;
std::unique_ptr<Server> server_;
bool shutdown_;
int port_;
gpr_event ev_;
TestServiceImpl service_;
};
// Tests zookeeper state change between two RPCs
// TODO(ctiller): leaked objects in this test
TEST_F(ShutdownTest, ShutdownTest) {
ResetStub();
// send the request in a background thread
std::thread thr(std::bind(&ShutdownTest::SendRequest, this));
// wait for the server to get the event
gpr_event_wait(&ev_, gpr_inf_future(GPR_CLOCK_MONOTONIC));
shutdown_ = true;
// shutdown should trigger cancellation causing everything to shutdown
auto deadline =
std::chrono::system_clock::now() + std::chrono::microseconds(100);
server_->Shutdown(deadline);
EXPECT_GE(std::chrono::system_clock::now(), deadline);
thr.join();
}
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc_test_init(argc, argv);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>fix shutdown_test<commit_after>/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "test/core/util/test_config.h"
#include <thread>
#include "test/core/util/port.h"
#include "test/cpp/util/echo.grpc.pb.h"
#include "src/core/support/env.h"
#include <grpc++/channel_arguments.h>
#include <grpc++/channel.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/server_credentials.h>
#include <grpc++/status.h>
#include <gtest/gtest.h>
#include <grpc/grpc.h>
#include <grpc/support/sync.h>
using grpc::cpp::test::util::EchoRequest;
using grpc::cpp::test::util::EchoResponse;
namespace grpc {
namespace testing {
class TestServiceImpl : public ::grpc::cpp::test::util::TestService::Service {
public:
explicit TestServiceImpl(gpr_event* ev) : ev_(ev) {}
Status Echo(ServerContext* context, const EchoRequest* request,
EchoResponse* response) GRPC_OVERRIDE {
gpr_event_set(ev_, (void*)1);
while (!context->IsCancelled()) {
}
return Status::OK;
}
private:
gpr_event* ev_;
};
class ShutdownTest : public ::testing::Test {
public:
ShutdownTest() : shutdown_(false), service_(&ev_) { gpr_event_init(&ev_); }
void SetUp() GRPC_OVERRIDE {
port_ = grpc_pick_unused_port_or_die();
server_ = SetUpServer(port_);
}
std::unique_ptr<Server> SetUpServer(const int port) {
grpc::string server_address = "localhost:" + to_string(port);
ServerBuilder builder;
builder.AddListeningPort(server_address, InsecureServerCredentials());
builder.RegisterService(&service_);
std::unique_ptr<Server> server = builder.BuildAndStart();
return server;
}
void TearDown() GRPC_OVERRIDE { GPR_ASSERT(shutdown_); }
void ResetStub() {
string target = "dns:localhost:" + to_string(port_);
channel_ = CreateChannel(target, InsecureCredentials(), ChannelArguments());
stub_ = std::move(grpc::cpp::test::util::TestService::NewStub(channel_));
}
string to_string(const int number) {
std::stringstream strs;
strs << number;
return strs.str();
}
void SendRequest() {
EchoRequest request;
EchoResponse response;
request.set_message("Hello");
ClientContext context;
GPR_ASSERT(!shutdown_);
Status s = stub_->Echo(&context, request, &response);
GPR_ASSERT(shutdown_);
}
protected:
std::shared_ptr<Channel> channel_;
std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub_;
std::unique_ptr<Server> server_;
bool shutdown_;
int port_;
gpr_event ev_;
TestServiceImpl service_;
};
// Tests zookeeper state change between two RPCs
// TODO(ctiller): leaked objects in this test
TEST_F(ShutdownTest, ShutdownTest) {
ResetStub();
// send the request in a background thread
std::thread thr(std::bind(&ShutdownTest::SendRequest, this));
// wait for the server to get the event
gpr_event_wait(&ev_, gpr_inf_future(GPR_CLOCK_MONOTONIC));
shutdown_ = true;
// shutdown should trigger cancellation causing everything to shutdown
auto deadline =
std::chrono::system_clock::now() + std::chrono::microseconds(100);
server_->Shutdown(deadline);
EXPECT_GE(std::chrono::system_clock::now(), deadline);
thr.join();
}
} // namespace testing
} // namespace grpc
int main(int argc, char** argv) {
grpc_test_init(argc, argv);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>#include <cstring>
#include <string>
#include <turbo/ipc/posix/pipe.hpp>
#include <turbo/filesystem/path.hpp>
#include <turbo/process/status.hpp>
#include <turbo/process/posix/spawn.hpp>
#include <gtest/gtest.h>
namespace tf = turbo::filesystem;
namespace tip = turbo::ipc::posix;
namespace tpp = turbo::process::posix;
namespace tps = turbo::process::status;
tpp::child spawn_child(const char* exe, char* const args[], char* const env[])
{
tpp::child&& child = tpp::spawn(exe, args, env, 2 << 16);
const char* expected = "READY\n";
char signal[256];
child.err.read_all(signal, strlen(expected));
if (strncmp(expected, signal, sizeof(signal)) != 0)
{
std::cerr << "ERROR: ready signal not received; instead received: " << signal << std::endl;
}
return std::move(child);
}
TEST(spawn_test, stdstream_check)
{
tf::path exe = tps::current_exe_path().parent_path() /= "spawn_child";
tpp::child&& child = spawn_child(exe.c_str(), {}, {});
char input[] = "FOO\n";
child.in.write_all(input, strlen(input));
const char* expected = "FOOBAR\n";
char output[256];
child.out.read_all(output, strlen(expected));
EXPECT_EQ(strncmp(expected, output, sizeof(output)), 0) << "Unexpected message from stdout: " << output;
}
<commit_msg>restrict buffer sizes to the exact expected message size<commit_after>#include <cstring>
#include <string>
#include <turbo/ipc/posix/pipe.hpp>
#include <turbo/filesystem/path.hpp>
#include <turbo/process/status.hpp>
#include <turbo/process/posix/spawn.hpp>
#include <gtest/gtest.h>
namespace tf = turbo::filesystem;
namespace tip = turbo::ipc::posix;
namespace tpp = turbo::process::posix;
namespace tps = turbo::process::status;
tpp::child spawn_child(const char* exe, char* const args[], char* const env[])
{
tpp::child&& child = tpp::spawn(exe, args, env, 2 << 16);
const char* expected = "READY\n";
char signal[7];
child.err.read_all(signal, strlen(expected));
if (strncmp(expected, signal, sizeof(signal)) != 0)
{
std::cerr << "ERROR: ready signal not received; instead received: " << signal << std::endl;
}
return std::move(child);
}
TEST(spawn_test, stdstream_check)
{
tf::path exe = tps::current_exe_path().parent_path() /= "spawn_child";
tpp::child&& child = spawn_child(exe.c_str(), {}, {});
char input[] = "FOO\n";
child.in.write_all(input, strlen(input));
const char* expected = "FOOBAR\n";
char output[8];
child.out.read_all(output, strlen(expected));
EXPECT_EQ(strncmp(expected, output, sizeof(output)), 0) << "Unexpected message from stdout: " << output;
}
<|endoftext|>
|
<commit_before>//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass performs loop invariant code motion on machine instructions. We
// attempt to remove as much code from the body of a loop as possible.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "machine-licm"
#include "llvm/ADT/IndexedMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
namespace {
// Hidden options to help debugging
cl::opt<bool>
PerformLICM("machine-licm",
cl::init(false), cl::Hidden,
cl::desc("Perform loop-invariant code motion on machine code"));
}
STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
namespace {
class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
const TargetInstrInfo *TII;
MachineFunction *CurMF; // Current MachineFunction
// Various analyses that we use...
MachineLoopInfo *LI; // Current MachineLoopInfo
MachineDominatorTree *DT; // Machine dominator tree for the current Loop
// State that is updated as we process loops
bool Changed; // True if a loop is changed.
MachineLoop *CurLoop; // The current loop we are working on.
// Map the def of a virtual register to the machine instruction.
IndexedMap<const MachineInstr*, VirtReg2IndexFunctor> VRegDefs;
public:
static char ID; // Pass identification, replacement for typeid
MachineLICM() : MachineFunctionPass((intptr_t)&ID) {}
virtual bool runOnMachineFunction(MachineFunction &MF);
/// FIXME: Loop preheaders?
///
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<MachineLoopInfo>();
AU.addRequired<MachineDominatorTree>();
}
private:
/// VisitAllLoops - Visit all of the loops in depth first order and try to
/// hoist invariant instructions from them.
///
void VisitAllLoops(MachineLoop *L) {
const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
for (MachineLoop::iterator
I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
MachineLoop *ML = *I;
// Traverse the body of the loop in depth first order on the dominator
// tree so that we are guaranteed to see definitions before we see uses.
VisitAllLoops(ML);
HoistRegion(DT->getNode(ML->getHeader()));
}
HoistRegion(DT->getNode(L->getHeader()));
}
/// MapVirtualRegisterDefs - Create a map of which machine instruction
/// defines a virtual register.
///
void MapVirtualRegisterDefs();
/// IsInSubLoop - A little predicate that returns true if the specified
/// basic block is in a subloop of the current one, not the current one
/// itself.
///
bool IsInSubLoop(MachineBasicBlock *BB) {
assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
return LI->getLoopFor(BB) != CurLoop;
}
/// IsLoopInvariantInst - Returns true if the instruction is loop
/// invariant. I.e., all virtual register operands are defined outside of
/// the loop, physical registers aren't accessed (explicitly or implicitly),
/// and the instruction is hoistable.
///
bool IsLoopInvariantInst(MachineInstr &I);
/// FindPredecessors - Get all of the predecessors of the loop that are not
/// back-edges.
///
void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
const MachineBasicBlock *Header = CurLoop->getHeader();
for (MachineBasicBlock::const_pred_iterator
I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
if (!CurLoop->contains(*I))
Preds.push_back(*I);
}
/// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
/// the predecessor basic block (but before the terminator instructions).
///
void MoveInstToEndOfBlock(MachineBasicBlock *MBB, MachineInstr *MI) {
DEBUG({
DOUT << "Hoisting " << *MI;
if (MBB->getBasicBlock())
DOUT << " to MachineBasicBlock "
<< MBB->getBasicBlock()->getName();
DOUT << "\n";
});
MachineBasicBlock::iterator Iter = MBB->getFirstTerminator();
MBB->insert(Iter, MI);
++NumHoisted;
}
/// HoistRegion - Walk the specified region of the CFG (defined by all
/// blocks dominated by the specified block, and that are in the current
/// loop) in depth first order w.r.t the DominatorTree. This allows us to
/// visit definitions before uses, allowing us to hoist a loop body in one
/// pass without iteration.
///
void HoistRegion(MachineDomTreeNode *N);
/// Hoist - When an instruction is found to only use loop invariant operands
/// that is safe to hoist, this instruction is called to do the dirty work.
///
void Hoist(MachineInstr &MI);
};
char MachineLICM::ID = 0;
RegisterPass<MachineLICM> X("machine-licm",
"Machine Loop Invariant Code Motion");
} // end anonymous namespace
FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
/// Hoist expressions out of the specified loop. Note, alias info for inner loop
/// is not preserved so it is not a good idea to run LICM multiple times on one
/// loop.
///
bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
if (!PerformLICM) return false; // For debugging.
DOUT << "******** Machine LICM ********\n";
Changed = false;
CurMF = &MF;
TII = CurMF->getTarget().getInstrInfo();
// Get our Loop information...
LI = &getAnalysis<MachineLoopInfo>();
DT = &getAnalysis<MachineDominatorTree>();
MapVirtualRegisterDefs();
for (MachineLoopInfo::iterator
I = LI->begin(), E = LI->end(); I != E; ++I) {
CurLoop = *I;
// Visit all of the instructions of the loop. We want to visit the subloops
// first, though, so that we can hoist their invariants first into their
// containing loop before we process that loop.
VisitAllLoops(CurLoop);
}
return Changed;
}
/// MapVirtualRegisterDefs - Create a map of which machine instruction defines a
/// virtual register.
///
void MachineLICM::MapVirtualRegisterDefs() {
for (MachineFunction::const_iterator
I = CurMF->begin(), E = CurMF->end(); I != E; ++I) {
const MachineBasicBlock &MBB = *I;
for (MachineBasicBlock::const_iterator
II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
const MachineInstr &MI = *II;
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI.getOperand(i);
if (MO.isRegister() && MO.isDef() &&
MRegisterInfo::isVirtualRegister(MO.getReg())) {
VRegDefs.grow(MO.getReg());
VRegDefs[MO.getReg()] = &MI;
}
}
}
}
}
/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
/// dominated by the specified block, and that are in the current loop) in depth
/// first order w.r.t the DominatorTree. This allows us to visit definitions
/// before uses, allowing us to hoist a loop body in one pass without iteration.
///
void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
assert(N != 0 && "Null dominator tree node?");
MachineBasicBlock *BB = N->getBlock();
// If this subregion is not in the top level loop at all, exit.
if (!CurLoop->contains(BB)) return;
// Only need to process the contents of this block if it is not part of a
// subloop (which would already have been processed).
if (!IsInSubLoop(BB))
for (MachineBasicBlock::iterator
I = BB->begin(), E = BB->end(); I != E; ) {
MachineInstr &MI = *I++;
// Try hoisting the instruction out of the loop. We can only do this if
// all of the operands of the instruction are loop invariant and if it is
// safe to hoist the instruction.
Hoist(MI);
}
const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
for (unsigned I = 0, E = Children.size(); I != E; ++I)
HoistRegion(Children[I]);
}
/// IsLoopInvariantInst - Returns true if the instruction is loop
/// invariant. I.e., all virtual register operands are defined outside of the
/// loop, physical registers aren't accessed explicitly, and there are no side
/// effects that aren't captured by the operands or other flags.
///
bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
DEBUG({
DOUT << "--- Checking if we can hoist " << I;
if (I.getInstrDescriptor()->ImplicitUses) {
DOUT << " * Instruction has implicit uses:\n";
const TargetMachine &TM = CurMF->getTarget();
const MRegisterInfo *MRI = TM.getRegisterInfo();
const unsigned *ImpUses = I.getInstrDescriptor()->ImplicitUses;
for (; *ImpUses; ++ImpUses)
DOUT << " -> " << MRI->getName(*ImpUses) << "\n";
}
if (I.getInstrDescriptor()->ImplicitDefs) {
DOUT << " * Instruction has implicit defines:\n";
const TargetMachine &TM = CurMF->getTarget();
const MRegisterInfo *MRI = TM.getRegisterInfo();
const unsigned *ImpDefs = I.getInstrDescriptor()->ImplicitDefs;
for (; *ImpDefs; ++ImpDefs)
DOUT << " -> " << MRI->getName(*ImpDefs) << "\n";
}
if (TII->hasUnmodelledSideEffects(&I))
DOUT << " * Instruction has side effects.\n";
});
// The instruction is loop invariant if all of its operands are loop-invariant
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
const MachineOperand &MO = I.getOperand(i);
if (!(MO.isRegister() && MO.getReg() && MO.isUse()))
continue;
unsigned Reg = MO.getReg();
// Don't hoist instructions that access physical registers.
if (!MRegisterInfo::isVirtualRegister(Reg))
return false;
assert(VRegDefs[Reg] && "Machine instr not mapped for this vreg?");
// If the loop contains the definition of an operand, then the instruction
// isn't loop invariant.
if (CurLoop->contains(VRegDefs[Reg]->getParent()))
return false;
}
// Don't hoist something that has unmodelled side effects.
if (TII->hasUnmodelledSideEffects(&I)) return false;
// If we got this far, the instruction is loop invariant!
return true;
}
/// Hoist - When an instruction is found to only use loop invariant operands
/// that is safe to hoist, this instruction is called to do the dirty work.
///
void MachineLICM::Hoist(MachineInstr &MI) {
if (!IsLoopInvariantInst(MI)) return;
std::vector<MachineBasicBlock*> Preds;
// Non-back-edge predecessors.
FindPredecessors(Preds);
// Either we don't have any predecessors(?!) or we have more than one, which
// is forbidden.
if (Preds.empty() || Preds.size() != 1) return;
// Check that the predecessor is qualified to take the hoisted
// instruction. I.e., there is only one edge from the predecessor, and it's to
// the loop header.
MachineBasicBlock *MBB = Preds.front();
// FIXME: We are assuming at first that the basic block coming into this loop
// has only one successor. This isn't the case in general because we haven't
// broken critical edges or added preheaders.
if (MBB->succ_size() != 1) return;
assert(*MBB->succ_begin() == CurLoop->getHeader() &&
"The predecessor doesn't feed directly into the loop header!");
// Now move the instructions to the predecessor.
MachineInstr *NewMI = MI.clone();
MoveInstToEndOfBlock(MBB, NewMI);
// Update VRegDefs.
for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = NewMI->getOperand(i);
if (MO.isRegister() && MO.isDef() &&
MRegisterInfo::isVirtualRegister(MO.getReg())) {
VRegDefs.grow(MO.getReg());
VRegDefs[MO.getReg()] = NewMI;
}
}
// Hoisting was successful! Remove bothersome instruction now.
MI.getParent()->remove(&MI);
Changed = true;
}
<commit_msg>Use the new architecture to get the containing machine basic block for a machine instruction. Also, use "splice" to move the new instruction instead of remove/insert (where it was leaking memory anyway).<commit_after>//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass performs loop invariant code motion on machine instructions. We
// attempt to remove as much code from the body of a loop as possible.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "machine-licm"
#include "llvm/ADT/IndexedMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
using namespace llvm;
namespace {
// Hidden options to help debugging
cl::opt<bool>
PerformLICM("machine-licm",
cl::init(false), cl::Hidden,
cl::desc("Perform loop-invariant code motion on machine code"));
}
STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
namespace {
class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
const TargetMachine *TM;
const TargetInstrInfo *TII;
MachineFunction *CurMF; // Current MachineFunction
// Various analyses that we use...
MachineLoopInfo *LI; // Current MachineLoopInfo
MachineDominatorTree *DT; // Machine dominator tree for the current Loop
MachineRegisterInfo *RegInfo; // Machine register information
// State that is updated as we process loops
bool Changed; // True if a loop is changed.
MachineLoop *CurLoop; // The current loop we are working on.
// Map the def of a virtual register to the machine instruction.
IndexedMap<const MachineInstr*, VirtReg2IndexFunctor> VRegDefs;
public:
static char ID; // Pass identification, replacement for typeid
MachineLICM() : MachineFunctionPass((intptr_t)&ID) {}
virtual bool runOnMachineFunction(MachineFunction &MF);
/// FIXME: Loop preheaders?
///
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<MachineLoopInfo>();
AU.addRequired<MachineDominatorTree>();
}
private:
/// VisitAllLoops - Visit all of the loops in depth first order and try to
/// hoist invariant instructions from them.
///
void VisitAllLoops(MachineLoop *L) {
const std::vector<MachineLoop*> &SubLoops = L->getSubLoops();
for (MachineLoop::iterator
I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I) {
MachineLoop *ML = *I;
// Traverse the body of the loop in depth first order on the dominator
// tree so that we are guaranteed to see definitions before we see uses.
VisitAllLoops(ML);
HoistRegion(DT->getNode(ML->getHeader()));
}
HoistRegion(DT->getNode(L->getHeader()));
}
/// MapVirtualRegisterDefs - Create a map of which machine instruction
/// defines a virtual register.
///
void MapVirtualRegisterDefs();
/// IsInSubLoop - A little predicate that returns true if the specified
/// basic block is in a subloop of the current one, not the current one
/// itself.
///
bool IsInSubLoop(MachineBasicBlock *BB) {
assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
return LI->getLoopFor(BB) != CurLoop;
}
/// IsLoopInvariantInst - Returns true if the instruction is loop
/// invariant. I.e., all virtual register operands are defined outside of
/// the loop, physical registers aren't accessed (explicitly or implicitly),
/// and the instruction is hoistable.
///
bool IsLoopInvariantInst(MachineInstr &I);
/// FindPredecessors - Get all of the predecessors of the loop that are not
/// back-edges.
///
void FindPredecessors(std::vector<MachineBasicBlock*> &Preds) {
const MachineBasicBlock *Header = CurLoop->getHeader();
for (MachineBasicBlock::const_pred_iterator
I = Header->pred_begin(), E = Header->pred_end(); I != E; ++I)
if (!CurLoop->contains(*I))
Preds.push_back(*I);
}
/// MoveInstToEndOfBlock - Moves the machine instruction to the bottom of
/// the predecessor basic block (but before the terminator instructions).
///
void MoveInstToEndOfBlock(MachineBasicBlock *ToMBB,
MachineBasicBlock *FromMBB,
MachineInstr *MI) {
DEBUG({
DOUT << "Hoisting " << *MI;
if (ToMBB->getBasicBlock())
DOUT << " to MachineBasicBlock "
<< ToMBB->getBasicBlock()->getName();
DOUT << "\n";
});
MachineBasicBlock::iterator WhereIter = ToMBB->getFirstTerminator();
MachineBasicBlock::iterator To, From = FromMBB->begin();
while (&*From != MI)
++From;
assert(From != FromMBB->end() && "Didn't find instr in BB!");
To = From;
ToMBB->splice(WhereIter, FromMBB, From, ++To);
++NumHoisted;
}
/// HoistRegion - Walk the specified region of the CFG (defined by all
/// blocks dominated by the specified block, and that are in the current
/// loop) in depth first order w.r.t the DominatorTree. This allows us to
/// visit definitions before uses, allowing us to hoist a loop body in one
/// pass without iteration.
///
void HoistRegion(MachineDomTreeNode *N);
/// Hoist - When an instruction is found to only use loop invariant operands
/// that is safe to hoist, this instruction is called to do the dirty work.
///
void Hoist(MachineInstr &MI);
};
char MachineLICM::ID = 0;
RegisterPass<MachineLICM> X("machine-licm",
"Machine Loop Invariant Code Motion");
} // end anonymous namespace
FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
/// Hoist expressions out of the specified loop. Note, alias info for inner loop
/// is not preserved so it is not a good idea to run LICM multiple times on one
/// loop.
///
bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
if (!PerformLICM) return false; // For debugging.
DOUT << "******** Machine LICM ********\n";
Changed = false;
CurMF = &MF;
TM = &CurMF->getTarget();
TII = TM->getInstrInfo();
RegInfo = new MachineRegisterInfo(*TM->getRegisterInfo());
// Get our Loop information...
LI = &getAnalysis<MachineLoopInfo>();
DT = &getAnalysis<MachineDominatorTree>();
MapVirtualRegisterDefs();
for (MachineLoopInfo::iterator
I = LI->begin(), E = LI->end(); I != E; ++I) {
CurLoop = *I;
// Visit all of the instructions of the loop. We want to visit the subloops
// first, though, so that we can hoist their invariants first into their
// containing loop before we process that loop.
VisitAllLoops(CurLoop);
}
delete RegInfo;
return Changed;
}
/// MapVirtualRegisterDefs - Create a map of which machine instruction defines a
/// virtual register.
///
void MachineLICM::MapVirtualRegisterDefs() {
for (MachineFunction::const_iterator
I = CurMF->begin(), E = CurMF->end(); I != E; ++I) {
const MachineBasicBlock &MBB = *I;
for (MachineBasicBlock::const_iterator
II = MBB.begin(), IE = MBB.end(); II != IE; ++II) {
const MachineInstr &MI = *II;
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI.getOperand(i);
if (MO.isRegister() && MO.isDef() &&
MRegisterInfo::isVirtualRegister(MO.getReg())) {
VRegDefs.grow(MO.getReg());
VRegDefs[MO.getReg()] = &MI;
}
}
}
}
}
/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
/// dominated by the specified block, and that are in the current loop) in depth
/// first order w.r.t the DominatorTree. This allows us to visit definitions
/// before uses, allowing us to hoist a loop body in one pass without iteration.
///
void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
assert(N != 0 && "Null dominator tree node?");
MachineBasicBlock *BB = N->getBlock();
// If this subregion is not in the top level loop at all, exit.
if (!CurLoop->contains(BB)) return;
// Only need to process the contents of this block if it is not part of a
// subloop (which would already have been processed).
if (!IsInSubLoop(BB))
for (MachineBasicBlock::iterator
I = BB->begin(), E = BB->end(); I != E; ) {
MachineInstr &MI = *I++;
// Try hoisting the instruction out of the loop. We can only do this if
// all of the operands of the instruction are loop invariant and if it is
// safe to hoist the instruction.
Hoist(MI);
}
const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
for (unsigned I = 0, E = Children.size(); I != E; ++I)
HoistRegion(Children[I]);
}
/// IsLoopInvariantInst - Returns true if the instruction is loop
/// invariant. I.e., all virtual register operands are defined outside of the
/// loop, physical registers aren't accessed explicitly, and there are no side
/// effects that aren't captured by the operands or other flags.
///
bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
DEBUG({
DOUT << "--- Checking if we can hoist " << I;
if (I.getInstrDescriptor()->ImplicitUses) {
DOUT << " * Instruction has implicit uses:\n";
const MRegisterInfo *MRI = TM->getRegisterInfo();
const unsigned *ImpUses = I.getInstrDescriptor()->ImplicitUses;
for (; *ImpUses; ++ImpUses)
DOUT << " -> " << MRI->getName(*ImpUses) << "\n";
}
if (I.getInstrDescriptor()->ImplicitDefs) {
DOUT << " * Instruction has implicit defines:\n";
const MRegisterInfo *MRI = TM->getRegisterInfo();
const unsigned *ImpDefs = I.getInstrDescriptor()->ImplicitDefs;
for (; *ImpDefs; ++ImpDefs)
DOUT << " -> " << MRI->getName(*ImpDefs) << "\n";
}
if (TII->hasUnmodelledSideEffects(&I))
DOUT << " * Instruction has side effects.\n";
});
// The instruction is loop invariant if all of its operands are loop-invariant
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
const MachineOperand &MO = I.getOperand(i);
if (!(MO.isRegister() && MO.getReg() && MO.isUse()))
continue;
unsigned Reg = MO.getReg();
// Don't hoist instructions that access physical registers.
if (!MRegisterInfo::isVirtualRegister(Reg))
return false;
assert(RegInfo->getVRegDef(Reg)&&"Machine instr not mapped for this vreg?");
// If the loop contains the definition of an operand, then the instruction
// isn't loop invariant.
if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
return false;
}
// Don't hoist something that has unmodelled side effects.
if (TII->hasUnmodelledSideEffects(&I)) return false;
// If we got this far, the instruction is loop invariant!
return true;
}
/// Hoist - When an instruction is found to only use loop invariant operands
/// that is safe to hoist, this instruction is called to do the dirty work.
///
void MachineLICM::Hoist(MachineInstr &MI) {
if (!IsLoopInvariantInst(MI)) return;
std::vector<MachineBasicBlock*> Preds;
// Non-back-edge predecessors.
FindPredecessors(Preds);
// Either we don't have any predecessors(?!) or we have more than one, which
// is forbidden.
if (Preds.empty() || Preds.size() != 1) return;
// Check that the predecessor is qualified to take the hoisted
// instruction. I.e., there is only one edge from the predecessor, and it's to
// the loop header.
MachineBasicBlock *MBB = Preds.front();
// FIXME: We are assuming at first that the basic block coming into this loop
// has only one successor. This isn't the case in general because we haven't
// broken critical edges or added preheaders.
if (MBB->succ_size() != 1) return;
assert(*MBB->succ_begin() == CurLoop->getHeader() &&
"The predecessor doesn't feed directly into the loop header!");
// Now move the instructions to the predecessor.
MoveInstToEndOfBlock(MBB, MI.getParent(), &MI);
Changed = true;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* 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 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/>.
*/
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <sys/stat.h>
#include "postprocess/regexrule.h"
#include "licenseplatecandidate.h"
#include "utility.h"
#include "support/filesystem.h"
#include "ocr.h"
using namespace std;
using namespace cv;
using namespace alpr;
// Given a directory full of lp images (named [statecode]#.png) crop out the alphanumeric characters.
// These will be used to train the OCR
#ifdef __APPLE__
const int LEFT_ARROW_KEY = 2;
const int RIGHT_ARROW_KEY = 3;
const int DOWN_ARROW_KEY = 1;
const int UP_ARROW_KEY= 0;
#elif WIN32
const int LEFT_ARROW_KEY = 2424832;
const int RIGHT_ARROW_KEY = 2555904;
const int DOWN_ARROW_KEY = 2621440;
const int UP_ARROW_KEY = 2490368;
const int ENTER_KEY_ONE = 13;
const int ENTER_KEY_TWO = 10;
#else
const int LEFT_ARROW_KEY = 1113937;
const int RIGHT_ARROW_KEY = 1113939;
const int DOWN_ARROW_KEY = 1113940;
const int UP_ARROW_KEY= 1113938;
const int ENTER_KEY_ONE = 1048586;
const int ENTER_KEY_TWO = 1048586;
#endif
const string SPACE = " ";
const int SPACE_KEY = 32;
const int ESCAPE_KEY = 27;
const int DASHBOARD_COLUMNS = 3;
void showDashboard(vector<Mat> images, vector<bool> selectedImages, int selectedIndex);
vector<string> showCharSelection(Mat image, vector<Rect> charRegions, string state);
int main( int argc, const char** argv )
{
string country;
string inDir;
string outDir;
Mat frame;
//Check if user specify image to process
if(argc == 4)
{
country = argv[1];
inDir = argv[2];
outDir = argv[3];
}
else
{
printf("Use:\n\t%s country indirectory outdirectory\n",argv[0]);
printf("Ex: \n\t%s eu ./pics/ ./out\n",argv[0]);
return 0;
}
if (DirectoryExists(outDir.c_str()) == false)
{
printf("Output dir does not exist\n");
return 0;
}
cout << "Usage: " << endl;
cout << "\tn -- Next plate" << endl;
cout << "\tp -- Previous plate" << endl;
cout << "\tW -- Select image and save characters according to OCR results, then go to next image" << endl;
cout << "\ts -- Save characters" << endl;
cout << "\t<- and -> -- Cycle between images" << endl;
cout << "\tEnt/space -- Select plate" << endl;
cout << endl;
cout << "Within a plate" << endl;
cout << "\t<- and -> -- Cycle between characters" << endl;
cout << "\t[0-9A-Z] -- Identify a character (saves the image)" << endl;
cout << "\tESC/Ent/Space -- Back to plate selection" << endl;
Config config(country);
config.debugGeneral = false;
config.debugCharAnalysis = false;
config.debugCharSegmenter = false;
OCR ocr(&config);
if (DirectoryExists(inDir.c_str()))
{
vector<string> files = getFilesInDir(inDir.c_str());
sort( files.begin(), files.end(), stringCompare );
for (int i = 0; i< files.size(); i++)
{
if (hasEnding(files[i], ".png") || hasEnding(files[i], ".jpg"))
{
string fullpath = inDir + "/" + files[i];
cout << fullpath << endl;
frame = imread( fullpath.c_str() );
if(frame.data == NULL)
{
cout << "Unable to read license plate: " << fullpath << endl;
continue;
}
resize(frame, frame, Size(config.ocrImageWidthPx, config.ocrImageHeightPx));
imshow ("Original", frame);
PipelineData pipeline_data(frame, Rect(0, 0, frame.cols, frame.rows), &config);
cvtColor(frame, frame, CV_BGR2GRAY);
pipeline_data.crop_gray = Mat(frame, Rect(0, 0, frame.cols, frame.rows));
char statecode[3];
statecode[0] = files[i][0];
statecode[1] = files[i][1];
statecode[2] = '\0';
string statecodestr(statecode);
CharacterAnalysis regionizer(&pipeline_data);
if (pipeline_data.plate_inverted)
bitwise_not(pipeline_data.crop_gray, pipeline_data.crop_gray);
CharacterSegmenter charSegmenter(&pipeline_data);
//ocr.cleanCharRegions(charSegmenter.thresholds, charSegmenter.characters);
ocr.performOCR(&pipeline_data);
ocr.postProcessor.analyze(statecodestr, 25);
cout << "OCR results: " << ocr.postProcessor.bestChars << endl;
vector<bool> selectedBoxes(pipeline_data.thresholds.size());
for (int z = 0; z < pipeline_data.thresholds.size(); z++)
selectedBoxes[z] = false;
int curDashboardSelection = 0;
vector<string> humanInputs(pipeline_data.charRegionsFlat.size());
for (int z = 0; z < pipeline_data.charRegionsFlat.size(); z++)
humanInputs[z] = SPACE;
showDashboard(pipeline_data.thresholds, selectedBoxes, 0);
int waitkey = waitKey(50);
while ((char) waitkey != 'n' && (char) waitkey != 'p') // Next image
{
if (waitkey == LEFT_ARROW_KEY) // left arrow key
{
if (curDashboardSelection > 0)
curDashboardSelection--;
showDashboard(pipeline_data.thresholds, selectedBoxes, curDashboardSelection);
}
else if (waitkey == RIGHT_ARROW_KEY) // right arrow key
{
if (curDashboardSelection < pipeline_data.thresholds.size() - 1)
curDashboardSelection++;
showDashboard(pipeline_data.thresholds, selectedBoxes, curDashboardSelection);
}
else if (waitkey == DOWN_ARROW_KEY)
{
if (curDashboardSelection + DASHBOARD_COLUMNS <= pipeline_data.thresholds.size() - 1)
curDashboardSelection += DASHBOARD_COLUMNS;
showDashboard(pipeline_data.thresholds, selectedBoxes, curDashboardSelection);
}
else if (waitkey == UP_ARROW_KEY)
{
if (curDashboardSelection - DASHBOARD_COLUMNS >= 0)
curDashboardSelection -= DASHBOARD_COLUMNS;
showDashboard(pipeline_data.thresholds, selectedBoxes, curDashboardSelection);
}
else if (waitkey == ENTER_KEY_ONE || waitkey == ENTER_KEY_TWO)
{
if (pipeline_data.charRegionsFlat.size() > 0)
{
vector<string> tempdata = showCharSelection(pipeline_data.thresholds[curDashboardSelection], pipeline_data.charRegionsFlat, statecodestr);
for (int c = 0; c < pipeline_data.charRegionsFlat.size(); c++)
humanInputs[c] = tempdata[c];
}
else
{
cout << "No character regions available in this image" << endl;
}
}
else if ((char) waitkey == SPACE_KEY)
{
selectedBoxes[curDashboardSelection] = !selectedBoxes[curDashboardSelection];
showDashboard(pipeline_data.thresholds, selectedBoxes, curDashboardSelection);
}
else if ((char) waitkey == 's' || (char) waitkey == 'S' )
{
bool somethingSelected = false;
bool chardataTagged = false;
for (int c = 0; c < pipeline_data.thresholds.size(); c++)
{
if (selectedBoxes[c])
{
somethingSelected = true;
break;
}
}
for (int c = 0; c < pipeline_data.charRegionsFlat.size(); c++)
{
if (humanInputs[c] != SPACE)
{
chardataTagged = true;
break;
}
}
// Save
if (somethingSelected && chardataTagged)
{
for (int c = 0; c < pipeline_data.charRegionsFlat.size(); c++)
{
if (humanInputs[c] == SPACE)
continue;
for (int t = 0; t < pipeline_data.thresholds.size(); t++)
{
if (selectedBoxes[t] == false)
continue;
stringstream filename;
// Ensure that crop rect does not extend beyond extent of image.
cv::Rect char_region = expandRect(pipeline_data.charRegionsFlat[c], 0, 0,
pipeline_data.thresholds[t].cols,
pipeline_data.thresholds[t].rows);
Mat cropped = pipeline_data.thresholds[t](char_region);
filename << outDir << "/" << humanInputs[c] << "-" << t << "-" << files[i];
imwrite(filename.str(), cropped);
cout << "Writing char image: " << filename.str() << endl;
}
}
}
else if (somethingSelected == false)
cout << "Did not select any boxes" << endl;
else if (chardataTagged == false)
cout << "You have not tagged any characters" << endl;
if ((char) waitkey == 'W')
{
waitkey = 'n';
continue;
}
}
waitkey = waitKey(50);
//std::cout << "key: " << (int) waitkey << std::endl;
}
if ((char) waitkey == 'p')
i = i - 2;
if (i < -1)
i = -1;
}
}
}
}
void showDashboard(vector<Mat> images, vector<bool> selectedImages, int selectedIndex)
{
vector<Mat> vecCopy;
if (selectedIndex < 0)
selectedIndex = 0;
if (selectedIndex >= images.size())
selectedIndex = images.size() -1;
for (int i = 0; i < images.size(); i++)
{
Mat imgCopy(images[i].size(), images[i].type());
images[i].copyTo(imgCopy);
cvtColor(imgCopy, imgCopy, CV_GRAY2BGR);
if (i == selectedIndex)
{
rectangle(imgCopy, Point(1,1), Point(imgCopy.size().width - 1, imgCopy.size().height -1), Scalar(0, 255, 0), 1);
}
if (selectedImages[i])
{
rectangle(imgCopy, Point(2,2), Point(imgCopy.size().width - 2, imgCopy.size().height -2), Scalar(255, 0, 0), 1);
}
vecCopy.push_back(imgCopy);
}
Mat dashboard = drawImageDashboard(vecCopy, vecCopy[0].type(), DASHBOARD_COLUMNS);
imshow("Selection dashboard", dashboard);
}
vector<string> showCharSelection(Mat image, vector<Rect> charRegions, string state)
{
int curCharIdx = 0;
vector<string> humanInputs(charRegions.size());
for (int i = 0; i < charRegions.size(); i++)
humanInputs[i] = SPACE;
RegexRule regex_rule("", "[\\pL\\pN]", "", "");
int16_t waitkey = waitKey(50);
while (waitkey != ENTER_KEY_ONE && waitkey != ENTER_KEY_TWO && waitkey != ESCAPE_KEY)
{
Mat imgCopy(image.size(), image.type());
image.copyTo(imgCopy);
cvtColor(imgCopy, imgCopy, CV_GRAY2BGR);
rectangle(imgCopy, charRegions[curCharIdx], Scalar(0, 255, 0), 1);
imshow("Character selector", imgCopy);
if ((char) waitkey == LEFT_ARROW_KEY)
curCharIdx--;
else if ((char) waitkey == RIGHT_ARROW_KEY)
curCharIdx++;
else if (waitkey == SPACE_KEY)
{
humanInputs[curCharIdx] = " ";
curCharIdx++;
}
else if (waitkey > 0 && regex_rule.match(utf8chr(waitkey))) // Verify that it's an actual character
{
// Save the character to disk
humanInputs[curCharIdx] = utf8chr(waitkey);
curCharIdx++;
if (curCharIdx >= charRegions.size())
{
waitkey = (int16_t) ENTER_KEY_ONE;
break;
}
}
if (curCharIdx < 0)
curCharIdx = 0;
if (curCharIdx >= charRegions.size())
curCharIdx = charRegions.size() -1;
waitkey = waitKey(50);
}
if (waitkey == ENTER_KEY_ONE || waitkey == ENTER_KEY_TWO)
{
// Save all the inputs
for (int i = 0; i < charRegions.size(); i++)
{
if (humanInputs[i] != SPACE)
cout << "Tagged " << state << " char code: '" << humanInputs[i] << "' at char position: " << i << endl;
}
}
destroyWindow("Character selector");
return humanInputs;
}
<commit_msg>Fixing the build issue in OSX<commit_after>/*
* Copyright (c) 2015 OpenALPR Technology, Inc.
* Open source Automated License Plate Recognition [http://www.openalpr.com]
*
* This file is part of OpenALPR.
*
* OpenALPR is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License
* version 3 as published by the Free Software Foundation
*
* 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 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/>.
*/
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <sys/stat.h>
#include "postprocess/regexrule.h"
#include "licenseplatecandidate.h"
#include "utility.h"
#include "support/filesystem.h"
#include "ocr.h"
using namespace std;
using namespace cv;
using namespace alpr;
// Given a directory full of lp images (named [statecode]#.png) crop out the alphanumeric characters.
// These will be used to train the OCR
#ifdef __APPLE__
const int LEFT_ARROW_KEY = 2;
const int RIGHT_ARROW_KEY = 3;
const int DOWN_ARROW_KEY = 1;
const int UP_ARROW_KEY= 0;
const int ENTER_KEY_ONE = 13;
const int ENTER_KEY_TWO = 10;
#elif WIN32
const int LEFT_ARROW_KEY = 2424832;
const int RIGHT_ARROW_KEY = 2555904;
const int DOWN_ARROW_KEY = 2621440;
const int UP_ARROW_KEY = 2490368;
const int ENTER_KEY_ONE = 13;
const int ENTER_KEY_TWO = 10;
#else
const int LEFT_ARROW_KEY = 1113937;
const int RIGHT_ARROW_KEY = 1113939;
const int DOWN_ARROW_KEY = 1113940;
const int UP_ARROW_KEY= 1113938;
const int ENTER_KEY_ONE = 1048586;
const int ENTER_KEY_TWO = 1048586;
#endif
const string SPACE = " ";
const int SPACE_KEY = 32;
const int ESCAPE_KEY = 27;
const int DASHBOARD_COLUMNS = 3;
void showDashboard(vector<Mat> images, vector<bool> selectedImages, int selectedIndex);
vector<string> showCharSelection(Mat image, vector<Rect> charRegions, string state);
int main( int argc, const char** argv )
{
string country;
string inDir;
string outDir;
Mat frame;
//Check if user specify image to process
if(argc == 4)
{
country = argv[1];
inDir = argv[2];
outDir = argv[3];
}
else
{
printf("Use:\n\t%s country indirectory outdirectory\n",argv[0]);
printf("Ex: \n\t%s eu ./pics/ ./out\n",argv[0]);
return 0;
}
if (DirectoryExists(outDir.c_str()) == false)
{
printf("Output dir does not exist\n");
return 0;
}
cout << "Usage: " << endl;
cout << "\tn -- Next plate" << endl;
cout << "\tp -- Previous plate" << endl;
cout << "\tW -- Select image and save characters according to OCR results, then go to next image" << endl;
cout << "\ts -- Save characters" << endl;
cout << "\t<- and -> -- Cycle between images" << endl;
cout << "\tEnt/space -- Select plate" << endl;
cout << endl;
cout << "Within a plate" << endl;
cout << "\t<- and -> -- Cycle between characters" << endl;
cout << "\t[0-9A-Z] -- Identify a character (saves the image)" << endl;
cout << "\tESC/Ent/Space -- Back to plate selection" << endl;
Config config(country);
config.debugGeneral = false;
config.debugCharAnalysis = false;
config.debugCharSegmenter = false;
OCR ocr(&config);
if (DirectoryExists(inDir.c_str()))
{
vector<string> files = getFilesInDir(inDir.c_str());
sort( files.begin(), files.end(), stringCompare );
for (int i = 0; i< files.size(); i++)
{
if (hasEnding(files[i], ".png") || hasEnding(files[i], ".jpg"))
{
string fullpath = inDir + "/" + files[i];
cout << fullpath << endl;
frame = imread( fullpath.c_str() );
if(frame.data == NULL)
{
cout << "Unable to read license plate: " << fullpath << endl;
continue;
}
resize(frame, frame, Size(config.ocrImageWidthPx, config.ocrImageHeightPx));
imshow ("Original", frame);
PipelineData pipeline_data(frame, Rect(0, 0, frame.cols, frame.rows), &config);
cvtColor(frame, frame, CV_BGR2GRAY);
pipeline_data.crop_gray = Mat(frame, Rect(0, 0, frame.cols, frame.rows));
char statecode[3];
statecode[0] = files[i][0];
statecode[1] = files[i][1];
statecode[2] = '\0';
string statecodestr(statecode);
CharacterAnalysis regionizer(&pipeline_data);
if (pipeline_data.plate_inverted)
bitwise_not(pipeline_data.crop_gray, pipeline_data.crop_gray);
CharacterSegmenter charSegmenter(&pipeline_data);
//ocr.cleanCharRegions(charSegmenter.thresholds, charSegmenter.characters);
ocr.performOCR(&pipeline_data);
ocr.postProcessor.analyze(statecodestr, 25);
cout << "OCR results: " << ocr.postProcessor.bestChars << endl;
vector<bool> selectedBoxes(pipeline_data.thresholds.size());
for (int z = 0; z < pipeline_data.thresholds.size(); z++)
selectedBoxes[z] = false;
int curDashboardSelection = 0;
vector<string> humanInputs(pipeline_data.charRegionsFlat.size());
for (int z = 0; z < pipeline_data.charRegionsFlat.size(); z++)
humanInputs[z] = SPACE;
showDashboard(pipeline_data.thresholds, selectedBoxes, 0);
int waitkey = waitKey(50);
while ((char) waitkey != 'n' && (char) waitkey != 'p') // Next image
{
if (waitkey == LEFT_ARROW_KEY) // left arrow key
{
if (curDashboardSelection > 0)
curDashboardSelection--;
showDashboard(pipeline_data.thresholds, selectedBoxes, curDashboardSelection);
}
else if (waitkey == RIGHT_ARROW_KEY) // right arrow key
{
if (curDashboardSelection < pipeline_data.thresholds.size() - 1)
curDashboardSelection++;
showDashboard(pipeline_data.thresholds, selectedBoxes, curDashboardSelection);
}
else if (waitkey == DOWN_ARROW_KEY)
{
if (curDashboardSelection + DASHBOARD_COLUMNS <= pipeline_data.thresholds.size() - 1)
curDashboardSelection += DASHBOARD_COLUMNS;
showDashboard(pipeline_data.thresholds, selectedBoxes, curDashboardSelection);
}
else if (waitkey == UP_ARROW_KEY)
{
if (curDashboardSelection - DASHBOARD_COLUMNS >= 0)
curDashboardSelection -= DASHBOARD_COLUMNS;
showDashboard(pipeline_data.thresholds, selectedBoxes, curDashboardSelection);
}
else if (waitkey == ENTER_KEY_ONE || waitkey == ENTER_KEY_TWO)
{
if (pipeline_data.charRegionsFlat.size() > 0)
{
vector<string> tempdata = showCharSelection(pipeline_data.thresholds[curDashboardSelection], pipeline_data.charRegionsFlat, statecodestr);
for (int c = 0; c < pipeline_data.charRegionsFlat.size(); c++)
humanInputs[c] = tempdata[c];
}
else
{
cout << "No character regions available in this image" << endl;
}
}
else if ((char) waitkey == SPACE_KEY)
{
selectedBoxes[curDashboardSelection] = !selectedBoxes[curDashboardSelection];
showDashboard(pipeline_data.thresholds, selectedBoxes, curDashboardSelection);
}
else if ((char) waitkey == 's' || (char) waitkey == 'S' )
{
bool somethingSelected = false;
bool chardataTagged = false;
for (int c = 0; c < pipeline_data.thresholds.size(); c++)
{
if (selectedBoxes[c])
{
somethingSelected = true;
break;
}
}
for (int c = 0; c < pipeline_data.charRegionsFlat.size(); c++)
{
if (humanInputs[c] != SPACE)
{
chardataTagged = true;
break;
}
}
// Save
if (somethingSelected && chardataTagged)
{
for (int c = 0; c < pipeline_data.charRegionsFlat.size(); c++)
{
if (humanInputs[c] == SPACE)
continue;
for (int t = 0; t < pipeline_data.thresholds.size(); t++)
{
if (selectedBoxes[t] == false)
continue;
stringstream filename;
// Ensure that crop rect does not extend beyond extent of image.
cv::Rect char_region = expandRect(pipeline_data.charRegionsFlat[c], 0, 0,
pipeline_data.thresholds[t].cols,
pipeline_data.thresholds[t].rows);
Mat cropped = pipeline_data.thresholds[t](char_region);
filename << outDir << "/" << humanInputs[c] << "-" << t << "-" << files[i];
imwrite(filename.str(), cropped);
cout << "Writing char image: " << filename.str() << endl;
}
}
}
else if (somethingSelected == false)
cout << "Did not select any boxes" << endl;
else if (chardataTagged == false)
cout << "You have not tagged any characters" << endl;
if ((char) waitkey == 'W')
{
waitkey = 'n';
continue;
}
}
waitkey = waitKey(50);
//std::cout << "key: " << (int) waitkey << std::endl;
}
if ((char) waitkey == 'p')
i = i - 2;
if (i < -1)
i = -1;
}
}
}
}
void showDashboard(vector<Mat> images, vector<bool> selectedImages, int selectedIndex)
{
vector<Mat> vecCopy;
if (selectedIndex < 0)
selectedIndex = 0;
if (selectedIndex >= images.size())
selectedIndex = images.size() -1;
for (int i = 0; i < images.size(); i++)
{
Mat imgCopy(images[i].size(), images[i].type());
images[i].copyTo(imgCopy);
cvtColor(imgCopy, imgCopy, CV_GRAY2BGR);
if (i == selectedIndex)
{
rectangle(imgCopy, Point(1,1), Point(imgCopy.size().width - 1, imgCopy.size().height -1), Scalar(0, 255, 0), 1);
}
if (selectedImages[i])
{
rectangle(imgCopy, Point(2,2), Point(imgCopy.size().width - 2, imgCopy.size().height -2), Scalar(255, 0, 0), 1);
}
vecCopy.push_back(imgCopy);
}
Mat dashboard = drawImageDashboard(vecCopy, vecCopy[0].type(), DASHBOARD_COLUMNS);
imshow("Selection dashboard", dashboard);
}
vector<string> showCharSelection(Mat image, vector<Rect> charRegions, string state)
{
int curCharIdx = 0;
vector<string> humanInputs(charRegions.size());
for (int i = 0; i < charRegions.size(); i++)
humanInputs[i] = SPACE;
RegexRule regex_rule("", "[\\pL\\pN]", "", "");
int16_t waitkey = waitKey(50);
while (waitkey != ENTER_KEY_ONE && waitkey != ENTER_KEY_TWO && waitkey != ESCAPE_KEY)
{
Mat imgCopy(image.size(), image.type());
image.copyTo(imgCopy);
cvtColor(imgCopy, imgCopy, CV_GRAY2BGR);
rectangle(imgCopy, charRegions[curCharIdx], Scalar(0, 255, 0), 1);
imshow("Character selector", imgCopy);
if ((char) waitkey == LEFT_ARROW_KEY)
curCharIdx--;
else if ((char) waitkey == RIGHT_ARROW_KEY)
curCharIdx++;
else if (waitkey == SPACE_KEY)
{
humanInputs[curCharIdx] = " ";
curCharIdx++;
}
else if (waitkey > 0 && regex_rule.match(utf8chr(waitkey))) // Verify that it's an actual character
{
// Save the character to disk
humanInputs[curCharIdx] = utf8chr(waitkey);
curCharIdx++;
if (curCharIdx >= charRegions.size())
{
waitkey = (int16_t) ENTER_KEY_ONE;
break;
}
}
if (curCharIdx < 0)
curCharIdx = 0;
if (curCharIdx >= charRegions.size())
curCharIdx = charRegions.size() -1;
waitkey = waitKey(50);
}
if (waitkey == ENTER_KEY_ONE || waitkey == ENTER_KEY_TWO)
{
// Save all the inputs
for (int i = 0; i < charRegions.size(); i++)
{
if (humanInputs[i] != SPACE)
cout << "Tagged " << state << " char code: '" << humanInputs[i] << "' at char position: " << i << endl;
}
}
destroyWindow("Character selector");
return humanInputs;
}
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2013 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgrePlatform.h"
// Sadly we needed to add this #if to solve a NACL compiler bug...
#if (OGRE_PLATFORM == OGRE_PLATFORM_NACL)
#include "ppapi/utility/completion_callback_factory.h"
#endif
using namespace Ogre;
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#include "OgreString.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include "SampleBrowser_OSX.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
#include "SampleBrowser_iOS.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_NACL
#include "SampleBrowser_NaCl.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
#include "SampleBrowser_Android.h"
#include "SampleBrowser.h"
SampleBrowser* OgreAndroidBridge::mBrowser = NULL;
AndroidInputInjector* OgreAndroidBridge::mInputInjector = NULL;
AndroidMultiTouch* OgreAndroidBridge::mTouch = NULL;
AndroidKeyboard* OgreAndroidBridge::mKeyboard = NULL;
RenderWindow* OgreAndroidBridge::mRenderWnd = NULL;
Root* OgreAndroidBridge::mRoot = NULL;
bool OgreAndroidBridge::mInit = false;
# ifdef OGRE_STATIC_LIB
StaticPluginLoader* OgreAndroidBridge::mStaticPluginLoader = NULL;
# endif
#endif
#if OGRE_PLATFORM != OGRE_PLATFORM_NACL
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR cmdLine, INT) {
int argc = __argc;
char** argv = __argv;
#elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
void android_main(struct android_app* state) {
#else
int main(int argc, char *argv[]) {
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, @"UIApplication", @"AppDelegate");
[pool release];
return retVal;
#elif (OGRE_PLATFORM == OGRE_PLATFORM_APPLE) && __LP64__
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
mAppDelegate = [[AppDelegate alloc] init];
[[NSApplication sharedApplication] setDelegate:mAppDelegate];
int retVal = NSApplicationMain(argc, (const char **) argv);
[pool release];
return retVal;
#elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
// Make sure glue isn't stripped.
app_dummy();
OgreAndroidBridge::init(state);
OgreAndroidBridge::go(state);
#else
try
{
bool nograb = false;
if (argc >= 2 && String(argv[1]) == "nograb")
nograb = true;
int startUpSampleIdx = -1;
if (argc >= 3)
{
startUpSampleIdx = StringConverter::parseInt(String(argv[2]), -1);
}
else if (argc >= 2)
{
// first parameter can be either nograb or index. in the former case, we'll just
// get -1, which is fine.
startUpSampleIdx = StringConverter::parseInt(String(argv[1]), -1);
}
OgreBites::SampleBrowser brows (nograb, startUpSampleIdx);
brows.go();
}
catch (Exception& e)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_ICONERROR | MB_TASKMODAL);
#else
std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl;
#endif
}
return 0;
#endif
}
#endif
<commit_msg>For real this time, I'm done breaking the sample browser build.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2013 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgrePlatform.h"
// Sadly we needed to add this #if to solve a NACL compiler bug...
#if (OGRE_PLATFORM == OGRE_PLATFORM_NACL)
#include "ppapi/utility/completion_callback_factory.h"
#endif
#if !defined(OGRE_STATIC_LIB) && (OGRE_PLATFORM != OGRE_PLATFORM_APPLE && __LP64__)
#include "SampleBrowser.h"
#endif
using namespace Ogre;
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#include "OgreString.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include "SampleBrowser_OSX.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
#include "SampleBrowser_iOS.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_NACL
#include "SampleBrowser_NaCl.h"
#elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
#include "SampleBrowser_Android.h"
SampleBrowser* OgreAndroidBridge::mBrowser = NULL;
AndroidInputInjector* OgreAndroidBridge::mInputInjector = NULL;
AndroidMultiTouch* OgreAndroidBridge::mTouch = NULL;
AndroidKeyboard* OgreAndroidBridge::mKeyboard = NULL;
RenderWindow* OgreAndroidBridge::mRenderWnd = NULL;
Root* OgreAndroidBridge::mRoot = NULL;
bool OgreAndroidBridge::mInit = false;
# ifdef OGRE_STATIC_LIB
StaticPluginLoader* OgreAndroidBridge::mStaticPluginLoader = NULL;
# endif
#endif
#if OGRE_PLATFORM != OGRE_PLATFORM_NACL
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR cmdLine, INT) {
int argc = __argc;
char** argv = __argv;
#elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
void android_main(struct android_app* state) {
#else
int main(int argc, char *argv[]) {
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, @"UIApplication", @"AppDelegate");
[pool release];
return retVal;
#elif (OGRE_PLATFORM == OGRE_PLATFORM_APPLE) && __LP64__
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
mAppDelegate = [[AppDelegate alloc] init];
[[NSApplication sharedApplication] setDelegate:mAppDelegate];
int retVal = NSApplicationMain(argc, (const char **) argv);
[pool release];
return retVal;
#elif OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
// Make sure glue isn't stripped.
app_dummy();
OgreAndroidBridge::init(state);
OgreAndroidBridge::go(state);
#else
try
{
bool nograb = false;
if (argc >= 2 && String(argv[1]) == "nograb")
nograb = true;
int startUpSampleIdx = -1;
if (argc >= 3)
{
startUpSampleIdx = StringConverter::parseInt(String(argv[2]), -1);
}
else if (argc >= 2)
{
// first parameter can be either nograb or index. in the former case, we'll just
// get -1, which is fine.
startUpSampleIdx = StringConverter::parseInt(String(argv[1]), -1);
}
OgreBites::SampleBrowser brows (nograb, startUpSampleIdx);
brows.go();
}
catch (Exception& e)
{
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_ICONERROR | MB_TASKMODAL);
#else
std::cerr << "An exception has occurred: " << e.getFullDescription().c_str() << std::endl;
#endif
}
return 0;
#endif
}
#endif
<|endoftext|>
|
<commit_before>#include "ResNinePatch.hpp"
#include "../App.hpp"
#include "../util/util.hpp"
using namespace morda;
namespace{
class ResSubImage : public ResImage, public ResImage::QuadTexture{
friend class ResImage;
std::shared_ptr<ResImage::QuadTexture> tex;
std::array<Vec2r, 4> texCoords;
Vec2r dim_v;
public:
//rect is a rectangle on the texture, Y axis up.
ResSubImage(decltype(tex) tex, Vec2r texDim, const Rectr& rect) :
tex(std::move(tex)),
dim_v(rect.d)
{
Rectr r(rect);
r.p.y = texDim.y - r.p.y - r.d.y;
this->texCoords[0] = texDim.compDiv(r.leftTop());
this->texCoords[1] = texDim.compDiv(r.rightTop());
this->texCoords[2] = texDim.compDiv(r.rightBottom());
this->texCoords[3] = texDim.compDiv(r.p);
}
ResSubImage(const ResSubImage& orig) = delete;
ResSubImage& operator=(const ResSubImage& orig) = delete;
Vec2r dim(real dpi) const noexcept override{
return this->dim_v;
}
virtual std::shared_ptr<const ResImage::QuadTexture> get(Vec2r forDim)const override{
return this->sharedFromThis(this);
}
void render(const Matr4r& matrix, PosTexShader& s, const std::array<kolme::Vec2f, 4>& texCoords) const override{
ASSERT(this->tex)
this->tex->render(matrix, s, texCoords);
}
};
}
std::shared_ptr<ResNinePatch> ResNinePatch::load(const stob::Node& chain, const papki::File& fi){
//TODO: remove?
if(chain.thisOrNext("tex").node()){
auto tex = morda::App::inst().resMan.load<ResTexture>(chain.side("tex").up().value());
auto rect = makeRectrFromSTOB(&chain.side("rect").up());
auto borders = makeRectrFromSTOB(&chain.side("borders").up());
return utki::makeShared<ResNinePatch>(
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.p, borders.p)), //lt
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.p.x + borders.p.x, rect.p.y, rect.d.x - borders.p.x - borders.d.x, borders.p.y)), //t
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.right() - borders.d.x, rect.p.y, borders.d.x, borders.p.y)), //rt
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.p.x, rect.p.y + borders.p.y, borders.p.x, rect.d.y - borders.p.y - borders.d.y)), //l
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.p.x + borders.p.x, rect.p.y + borders.p.y, rect.d.x - borders.p.x - borders.d.x, rect.d.y - borders.p.y - borders.d.y)), //m
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.right() - borders.d.x, rect.p.y + borders.p.y, borders.d.x, rect.d.y - borders.p.y - borders.d.y)), //r
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.p.x, rect.top() - borders.d.y, borders.p.x, borders.d.y)), //lb
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.p.x + borders.p.x, rect.top() - borders.d.y, rect.d.x - borders.p.x - borders.d.x, borders.d.y)), //b
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.right() - borders.d.x, rect.top() - borders.d.y, borders.d.x, borders.d.y)) //br
);
}
auto borders = makeSidesrFromSTOB(&chain.side("borders").up());
auto file = chain.side("file").up().asString();
fi.setPath(file);
auto image = ResImage::load(fi);
return utki::makeShared<ResNinePatch>(image, borders);
}
ResNinePatch::ImageMatrix_t ResNinePatch::get(Sidesr borders) const {
if(!this->image){
return ImageMatrix_t({{{this->lt, this->t, this->rt}, {this->l, this->m, this->r} , {this->lb, this->b, this->rb}}});
}
//TODO: add caching by requested borders
real mul = 1;
auto req = borders.begin();
for(auto orig = this->borders.begin(); orig != this->borders.end(); ++orig, ++req){
if(*orig <= 0 || *req <= 0){
continue;
}
if(*req > (*orig) * mul){
mul = *req / *orig;
}
}
auto dim = this->image->dim() * mul;
auto quadTex = this->image->get(dim);
//TODO:
return ImageMatrix_t();
}
<commit_msg>stuff<commit_after>#include "ResNinePatch.hpp"
#include "../App.hpp"
#include "../util/util.hpp"
using namespace morda;
namespace{
class ResSubImage : public ResImage, public ResImage::QuadTexture{
friend class ResImage;
std::shared_ptr<ResImage::QuadTexture> tex;
std::array<Vec2r, 4> texCoords;
Vec2r dim_v;
public:
//rect is a rectangle on the texture, Y axis up.
ResSubImage(decltype(tex) tex, Vec2r texDim, const Rectr& rect) :
tex(std::move(tex)),
dim_v(rect.d)
{
Rectr r(rect);
r.p.y = texDim.y - r.p.y - r.d.y;
this->texCoords[0] = texDim.compDiv(r.leftTop());
this->texCoords[1] = texDim.compDiv(r.rightTop());
this->texCoords[2] = texDim.compDiv(r.rightBottom());
this->texCoords[3] = texDim.compDiv(r.p);
}
ResSubImage(const ResSubImage& orig) = delete;
ResSubImage& operator=(const ResSubImage& orig) = delete;
Vec2r dim(real dpi) const noexcept override{
return this->dim_v;
}
virtual std::shared_ptr<const ResImage::QuadTexture> get(Vec2r forDim)const override{
return this->sharedFromThis(this);
}
void render(const Matr4r& matrix, PosTexShader& s, const std::array<kolme::Vec2f, 4>& texCoords) const override{
ASSERT(this->tex)
this->tex->render(matrix, s, texCoords);
}
};
}
std::shared_ptr<ResNinePatch> ResNinePatch::load(const stob::Node& chain, const papki::File& fi){
//TODO: remove?
if(chain.thisOrNext("tex").node()){
auto tex = morda::App::inst().resMan.load<ResTexture>(chain.side("tex").up().value());
auto rect = makeRectrFromSTOB(&chain.side("rect").up());
auto borders = makeRectrFromSTOB(&chain.side("borders").up());
return utki::makeShared<ResNinePatch>(
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.p, borders.p)), //lt
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.p.x + borders.p.x, rect.p.y, rect.d.x - borders.p.x - borders.d.x, borders.p.y)), //t
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.right() - borders.d.x, rect.p.y, borders.d.x, borders.p.y)), //rt
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.p.x, rect.p.y + borders.p.y, borders.p.x, rect.d.y - borders.p.y - borders.d.y)), //l
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.p.x + borders.p.x, rect.p.y + borders.p.y, rect.d.x - borders.p.x - borders.d.x, rect.d.y - borders.p.y - borders.d.y)), //m
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.right() - borders.d.x, rect.p.y + borders.p.y, borders.d.x, rect.d.y - borders.p.y - borders.d.y)), //r
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.p.x, rect.top() - borders.d.y, borders.p.x, borders.d.y)), //lb
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.p.x + borders.p.x, rect.top() - borders.d.y, rect.d.x - borders.p.x - borders.d.x, borders.d.y)), //b
utki::makeShared<ResAtlasImage>(tex, Rectr(rect.right() - borders.d.x, rect.top() - borders.d.y, borders.d.x, borders.d.y)) //br
);
}
auto borders = makeSidesrFromSTOB(&chain.side("borders").up());
auto file = chain.side("file").up().asString();
fi.setPath(file);
auto image = ResImage::load(fi);
return utki::makeShared<ResNinePatch>(image, borders);
}
ResNinePatch::ImageMatrix_t ResNinePatch::get(Sidesr borders) const {
if(!this->image){
return ImageMatrix_t({{{{this->lt, this->t, this->rt}}, {{this->l, this->m, this->r}} , {{this->lb, this->b, this->rb}}}});
}
//TODO: add caching by requested borders
real mul = 1;
auto req = borders.begin();
for(auto orig = this->borders.begin(); orig != this->borders.end(); ++orig, ++req){
if(*orig <= 0 || *req <= 0){
continue;
}
if(*req > (*orig) * mul){
mul = *req / *orig;
}
}
auto dim = this->image->dim() * mul;
auto quadTex = this->image->get(dim);
//TODO:
return ImageMatrix_t();
}
<|endoftext|>
|
<commit_before>//
// Created by FyS on 30/05/17.
//
#include <spdlog/spdlog.h>
#include <TokenGenerator.hh>
#include <TcpConnection.hh>
#include <FySMessage.pb.h>
#include "SessionManager.hh"
fys::network::SessionManager::SessionManager(const uint size) : _connections(size), _connectionsToken(size)
{}
uint fys::network::SessionManager::addConnection(const fys::network::TcpConnection::ptr &newConnection) {
uint i = 0;
for (; i < _connections.size(); ++i) {
if (!_connections.at(i)) {
connectionHandle(newConnection, i);
return i;
}
}
_connections.resize(_connections.size() + 1000, nullptr);
_connectionsToken.resize(_connections.size() + 1000);
connectionHandle(newConnection, i);
return i;
}
void fys::network::SessionManager::connectionHandle(const fys::network::TcpConnection::ptr &newConnection, const uint i) {
Token newToken = fys::utils::TokenGenerator::getInstance()->generateByte();
this->_connections.at(i) = newConnection;
this->_connectionsToken.at(i) = newToken;
newConnection->setSessionIndex(i);
newConnection->setCustomShutdownHandler([this, i, token = std::move(newToken)]() { this->disconnectUser(i, token); });
}
void fys::network::SessionManager::disconnectUser(const uint idxSession, const fys::network::Token &token) {
if (idxSession < _connectionsToken.size()) {
if (std::equal(_connectionsToken.at(idxSession).begin(), _connectionsToken.at(idxSession).end(), token.begin())) {
spdlog::get("c")->debug("Disconnect user {} from Session manager ({}) and token {}", idxSession, _name, std::string(token.begin(), token.end()));
_connections.at(idxSession) = nullptr;
_connectionsToken.at(idxSession) = {};
return;
}
}
spdlog::get("c")->error("Couldn't find the specified user's token to disconnect on session manager {}", _name);
}
const std::string fys::network::SessionManager::getConnectionToken(const uint indexInSession) const noexcept {
if (indexInSession < _connectionsToken.size())
return std::string(_connectionsToken.at(indexInSession).begin(), _connectionsToken.at(indexInSession).end());
return "";
}
void fys::network::SessionManager::sendResponse(const uint indexInSession, fys::pb::FySResponseMessage &&msg) const noexcept {
if (indexInSession < _connections.size())
_connections.at(indexInSession)->send(std::move(msg));
}
void fys::network::SessionManager::send(const uint indexInSession, fys::pb::FySMessage &&msg) const noexcept {
if (indexInSession < _connections.size())
_connections.at(indexInSession)->send(std::move(msg));
}
std::pair<std::string, ushort> fys::network::SessionManager::getConnectionData(const uint idxInSession) const noexcept {
if (idxInSession >= _connections.size() || !_connections.at(idxInSession))
return std::make_pair(std::string(""), static_cast<ushort>(0));
return std::make_pair(_connections.at(idxInSession)->getIpAddress(), _connections.at(idxInSession)->getPort());
}
void fys::network::SessionManager::setName(std::string &&name) {
_name = std::move(name);
}
<commit_msg>[FYS] [gateway]: - change resizing of SessionManager<commit_after>//
// Created by FyS on 30/05/17.
//
#include <spdlog/spdlog.h>
#include <TokenGenerator.hh>
#include <TcpConnection.hh>
#include <FySMessage.pb.h>
#include "SessionManager.hh"
fys::network::SessionManager::SessionManager(const uint size) : _connections(size), _connectionsToken(size)
{}
uint fys::network::SessionManager::addConnection(const fys::network::TcpConnection::ptr &newConnection) {
uint i = 0;
for (; i < _connections.size(); ++i) {
if (!_connections.at(i)) {
connectionHandle(newConnection, i);
return i;
}
}
_connections.resize(_connections.size() + 100, nullptr);
_connectionsToken.resize(_connections.size() + 100);
connectionHandle(newConnection, i);
return i;
}
void fys::network::SessionManager::connectionHandle(const fys::network::TcpConnection::ptr &newConnection, const uint i) {
Token newToken = fys::utils::TokenGenerator::getInstance()->generateByte();
this->_connections.at(i) = newConnection;
this->_connectionsToken.at(i) = newToken;
newConnection->setSessionIndex(i);
newConnection->setCustomShutdownHandler([this, i, token = std::move(newToken)]() { this->disconnectUser(i, token); });
}
void fys::network::SessionManager::disconnectUser(const uint idxSession, const fys::network::Token &token) {
if (idxSession < _connectionsToken.size()) {
if (std::equal(_connectionsToken.at(idxSession).begin(), _connectionsToken.at(idxSession).end(), token.begin())) {
spdlog::get("c")->debug("Disconnect user {} from Session manager ({}) and token {}", idxSession, _name, std::string(token.begin(), token.end()));
_connections.at(idxSession) = nullptr;
_connectionsToken.at(idxSession) = {};
return;
}
}
spdlog::get("c")->error("Couldn't find the specified user's token to disconnect on session manager {}", _name);
}
const std::string fys::network::SessionManager::getConnectionToken(const uint indexInSession) const noexcept {
if (indexInSession < _connectionsToken.size())
return std::string(_connectionsToken.at(indexInSession).begin(), _connectionsToken.at(indexInSession).end());
return "";
}
void fys::network::SessionManager::sendResponse(const uint indexInSession, fys::pb::FySResponseMessage &&msg) const noexcept {
if (indexInSession < _connections.size())
_connections.at(indexInSession)->send(std::move(msg));
}
void fys::network::SessionManager::send(const uint indexInSession, fys::pb::FySMessage &&msg) const noexcept {
if (indexInSession < _connections.size())
_connections.at(indexInSession)->send(std::move(msg));
}
std::pair<std::string, ushort> fys::network::SessionManager::getConnectionData(const uint idxInSession) const noexcept {
if (idxInSession >= _connections.size() || !_connections.at(idxInSession))
return std::make_pair(std::string(""), static_cast<ushort>(0));
return std::make_pair(_connections.at(idxInSession)->getIpAddress(), _connections.at(idxInSession)->getPort());
}
void fys::network::SessionManager::setName(std::string &&name) {
_name = std::move(name);
}
<|endoftext|>
|
<commit_before>#include <stdlib.h>
#include "ZWaveModule.h"
#include "azure_c_shared_utility/threadapi.h"
#include "azure_c_shared_utility/xlogging.h"
#include "azure_c_shared_utility/crt_abstractions.h"
#include "messageproperties.h"
#include "message.h"
#include "module.h"
#include "broker.h"
#include <parson.h>
typedef struct ZWAVEDEVICE_DATA_TAG
{
BROKER_HANDLE broker;
THREAD_HANDLE simulatedDeviceThread;
const char * fakeMacAddress;
unsigned int messagePeriod;
unsigned int simulatedDeviceRunning : 1;
} ZWAVEDEVICE_DATA;
typedef struct ZWAVEDEVICE_CONFIG_TAG
{
STRING_HANDLE IoTHubName; //Sergei's comments
STRING_HANDLE IoTHubSuffix; //Sergei's comments
char * macAddress;
unsigned int messagePeriod;
} ZWAVEDEVICE_CONFIG;
#define SUFFIX "IoTHubSuffix" //Sergei's comments
#define HUBNAME "IoTHubName" //Sergei's comments
static void * ZwaveDevice_ParseConfigurationFromJson(const char* configuration)
{
ZWAVEDEVICE_CONFIG * result;
if (configuration == NULL)
{
LogError("invalid module args.");
result = NULL;
}
else
{
JSON_Value* json = json_parse_string((const char*)configuration);
if (json == NULL)
{
LogError("unable to json_parse_string");
result = NULL;
}
else
{
JSON_Object* root = json_value_get_object(json);
if (root == NULL)
{
LogError("unable to json_value_get_object");
result = NULL;
}
else
{
ZWAVEDEVICE_CONFIG config;
const char* macAddress = json_object_get_string(root, "macAddress");
if (macAddress == NULL)
{
LogError("unable to json_object_get_string");
result = NULL;
}
else
{
int period = (int)json_object_get_number(root, "messagePeriod");
if (period <= 0)
{
LogError("Invalid period time specified");
result = NULL;
}
else
{
if (mallocAndStrcpy_s(&(config.macAddress), macAddress) != 0)
{
result = NULL;
}
else
{
config.messagePeriod = period;
result = (ZWAVEDEVICE_CONFIG*)malloc(sizeof(ZWAVEDEVICE_CONFIG));
if (result == NULL) {
free(config.macAddress);
LogError("allocation of configuration failed");
}
else
{
*result = config;
}
}
}
}
}
json_value_free(json);
}
}
return result;
}
/*Sergei's comments*/
static void ZwaveDevice_FreeConfiguration(void* configuration)
{
/*Codes_SRS_IOTHUBMODULE_05_014: [ If `configuration` is NULL then `IotHub_FreeConfiguration` shall do nothing. ]*/
if (configuration != NULL)
{
ZWAVEDEVICE_CONFIG* config = (ZWAVEDEVICE_CONFIG*)configuration;
/*Codes_SRS_IOTHUBMODULE_05_015: [ `IotHub_FreeConfiguration` shall free the strings referenced by the `IoTHubName` and `IoTHubSuffix` data members, and then free the `IOTHUB_CONFIG` structure itself. ]*/
free((void*)config->IoTHubName);
free((void*)config->IoTHubSuffix);
free(config);
}
}
/*Sergei's comments*/
//static MODULE_HANDLE ZwaveDevice_Create(BROKER_HANDLE broker, const void* configuration)
//{
//
// ZWAVEDEVICE_CONFIG *result;
// const ZWAVEDEVICE_CONFIG* config = configuration;
//
// /*Codes_SRS_IOTHUBMODULE_02_001: [ If `broker` is `NULL` then `IotHub_Create` shall fail and return `NULL`. ]*/
// /*Codes_SRS_IOTHUBMODULE_02_002: [ If `configuration` is `NULL` then `IotHub_Create` shall fail and return `NULL`. ]*/
// /*Codes_SRS_IOTHUBMODULE_02_003: [ If `configuration->IoTHubName` is `NULL` then `IotHub_Create` shall and return `NULL`. ]*/
// /*Codes_SRS_IOTHUBMODULE_02_004: [ If `configuration->IoTHubSuffix` is `NULL` then `IotHub_Create` shall fail and return `NULL`. ]*/
// if (
// (broker == NULL) ||
// (configuration == NULL)
// )
// {
// LogError("invalid arg broker=%p, configuration=%p", broker, configuration);
// result = NULL;
// }
// else if (
// (config->IoTHubName == NULL) ||
// (config->IoTHubSuffix == NULL) ||
// (config->transportProvider == NULL)
// )
// {
// LogError("invalid configuration IoTHubName=%s IoTHubSuffix=%s transportProvider=%p",
// (config != NULL) ? config->IoTHubName : "<null>",
// (config != NULL) ? config->IoTHubSuffix : "<null>",
// (config != NULL) ? config->transportProvider : 0);
// result = NULL;
// }
// else
// {
// result = malloc(sizeof(IOTHUB_HANDLE_DATA));
// /*Codes_SRS_IOTHUBMODULE_02_027: [ When `IotHub_Create` encounters an internal failure it shall fail and return `NULL`. ]*/
// if (result == NULL)
// {
// LogError("malloc returned NULL");
// /*return as is*/
// }
// else
// {
// /*Codes_SRS_IOTHUBMODULE_02_006: [ `IotHub_Create` shall create an empty `VECTOR` containing pointers to `PERSONALITY`s. ]*/
// result->personalities = VECTOR_create(sizeof(PERSONALITY_PTR));
// if (result->personalities == NULL)
// {
// /*Codes_SRS_IOTHUBMODULE_02_007: [ If creating the personality vector fails then `IotHub_Create` shall fail and return `NULL`. ]*/
// free(result);
// result = NULL;
// LogError("VECTOR_create returned NULL");
// }
// else
// {
// result->transportProvider = config->transportProvider;
// if (result->transportProvider == HTTP_Protocol ||
// result->transportProvider == AMQP_Protocol)
// {
// /*Codes_SRS_IOTHUBMODULE_17_001: [ If `configuration->transportProvider` is `HTTP_Protocol` or `AMQP_Protocol`, `IotHub_Create` shall create a shared transport by calling `IoTHubTransport_Create`. ]*/
// result->transportHandle = IoTHubTransport_Create(config->transportProvider, config->IoTHubName, config->IoTHubSuffix);
// if (result->transportHandle == NULL)
// {
// /*Codes_SRS_IOTHUBMODULE_17_002: [ If creating the shared transport fails, `IotHub_Create` shall fail and return `NULL`. ]*/
// VECTOR_destroy(result->personalities);
// free(result);
// result = NULL;
// LogError("VECTOR_create returned NULL");
// }
// }
// else
// {
// result->transportHandle = NULL;
// }
//
// if (result != NULL)
// {
// /*Codes_SRS_IOTHUBMODULE_02_028: [ `IotHub_Create` shall create a copy of `configuration->IoTHubName`. ]*/
// /*Codes_SRS_IOTHUBMODULE_02_029: [ `IotHub_Create` shall create a copy of `configuration->IoTHubSuffix`. ]*/
// if ((result->IoTHubName = STRING_construct(config->IoTHubName)) == NULL)
// {
// LogError("STRING_construct returned NULL");
// IoTHubTransport_Destroy(result->transportHandle);
// VECTOR_destroy(result->personalities);
// free(result);
// result = NULL;
// }
// else if ((result->IoTHubSuffix = STRING_construct(config->IoTHubSuffix)) == NULL)
// {
// LogError("STRING_construct returned NULL");
// STRING_delete(result->IoTHubName);
// IoTHubTransport_Destroy(result->transportHandle);
// VECTOR_destroy(result->personalities);
// free(result);
// result = NULL;
// }
// else
// {
// /*Codes_SRS_IOTHUBMODULE_17_004: [ `IotHub_Create` shall store the broker. ]*/
// result->broker = broker;
// /*Codes_SRS_IOTHUBMODULE_02_008: [ Otherwise, `IotHub_Create` shall return a non-`NULL` handle. ]*/
// }
// }
// }
// }
// }
// return result;
//}
/*
* Required for all modules: the public API and the designated implementation functions.
*/
static const MODULE_API_1 ZwaveDevice_APIS_all =
{
{ MODULE_API_VERSION_1 },
ZwaveDevice_ParseConfigurationFromJson,
ZwaveDevice_FreeConfiguration,
//ZwaveDevice_Create //,
//ZwaveDevice_Destroy,
//ZwaveDevice_Receive,
//ZwaveDevice_Start
};
#ifdef BUILD_MODULE_TYPE_STATIC
MODULE_EXPORT const MODULE_API* MODULE_STATIC_GETAPI(ZWAVE_DEVICE_MODULE)(MODULE_API_VERSION gateway_api_version)
#else
MODULE_EXPORT const MODULE_API* Module_GetApi(MODULE_API_VERSION gateway_api_version)
#endif
{
(void)gateway_api_version;
return (const MODULE_API *)&ZwaveDevice_APIS_all;
}
<commit_msg>Add module ZwaveDevice_Create<commit_after>#include <stdlib.h>
#include "ZWaveModule.h"
#include "azure_c_shared_utility/threadapi.h"
#include "azure_c_shared_utility/xlogging.h"
#include "azure_c_shared_utility/crt_abstractions.h"
#include "messageproperties.h"
#include "message.h"
#include "module.h"
#include "broker.h"
#include <parson.h>
typedef struct ZWAVEDEVICE_DATA_TAG
{
BROKER_HANDLE broker;
THREAD_HANDLE simulatedDeviceThread;
const char * fakeMacAddress;
unsigned int messagePeriod;
unsigned int simulatedDeviceRunning : 1;
} ZWAVEDEVICE_DATA;
typedef struct ZWAVEDEVICE_CONFIG_TAG
{
char * macAddress;
unsigned int messagePeriod;
} ZWAVEDEVICE_CONFIG;
/*Sergei's add module*/
static MODULE_HANDLE ZwaveDevice_Create(BROKER_HANDLE broker, const void* configuration)
{
ZWAVEDEVICE_DATA * result;
ZWAVEDEVICE_CONFIG * config = (ZWAVEDEVICE_CONFIG *)configuration;
if (broker == NULL || config == NULL)
{
LogError("invalid SIMULATED DEVICE module args.");
result = NULL;
}
else
{
/* allocate module data struct */
result = (ZWAVEDEVICE_DATA*)malloc(sizeof(ZWAVEDEVICE_DATA));
if (result == NULL)
{
LogError("couldn't allocate memory for BLE Module");
}
else
{
/* save the message broker */
result->broker = broker;
/* set module is running to true */
result->simulatedDeviceRunning = 1;
/* save fake MacAddress */
char * newFakeAddress;
int status = mallocAndStrcpy_s(&newFakeAddress, config->macAddress);
if (status != 0)
{
LogError("MacAddress did not copy");
}
else
{
result->fakeMacAddress = newFakeAddress;
result->messagePeriod = config->messagePeriod;
result->simulatedDeviceThread = NULL;
}
}
}
return result;
}
static void* ZwaveDevice_ParseConfigurationFromJson(const char* configuration)
{
ZWAVEDEVICE_CONFIG * result;
if (configuration == NULL)
{
LogError("invalid module args.");
result = NULL;
}
else
{
JSON_Value* json = json_parse_string((const char*)configuration);
if (json == NULL)
{
LogError("unable to json_parse_string");
result = NULL;
}
else
{
JSON_Object* root = json_value_get_object(json);
if (root == NULL)
{
LogError("unable to json_value_get_object");
result = NULL;
}
else
{
ZWAVEDEVICE_CONFIG config;
const char* macAddress = json_object_get_string(root, "macAddress");
if (macAddress == NULL)
{
LogError("unable to json_object_get_string");
result = NULL;
}
else
{
int period = (int)json_object_get_number(root, "messagePeriod");
if (period <= 0)
{
LogError("Invalid period time specified");
result = NULL;
}
else
{
if (mallocAndStrcpy_s(&(config.macAddress), macAddress) != 0)
{
result = NULL;
}
else
{
config.messagePeriod = period;
result = (ZWAVEDEVICE_CONFIG*)malloc(sizeof(ZWAVEDEVICE_CONFIG));
if (result == NULL) {
free(config.macAddress);
LogError("allocation of configuration failed");
}
else
{
*result = config;
}
}
}
}
}
json_value_free(json);
}
}
return result;
}
/*Sergei's add module*/
void ZwaveDevice_FreeConfiguration(void * configuration)
{
if (configuration != NULL)
{
ZWAVEDEVICE_CONFIG * config = (ZWAVEDEVICE_CONFIG *)configuration;
free(config->macAddress);
free(config);
}
}
/*
* Required for all modules: the public API and the designated implementation functions.
*/
static const MODULE_API_1 ZwaveDevice_APIS_all =
{
{ MODULE_API_VERSION_1 },
ZwaveDevice_ParseConfigurationFromJson,
ZwaveDevice_FreeConfiguration,
ZwaveDevice_Create //,
//ZwaveDevice_Destroy,
//ZwaveDevice_Receive,
//ZwaveDevice_Start
};
#ifdef BUILD_MODULE_TYPE_STATIC
MODULE_EXPORT const MODULE_API* MODULE_STATIC_GETAPI(ZWAVE_DEVICE_MODULE)(MODULE_API_VERSION gateway_api_version)
#else
MODULE_EXPORT const MODULE_API* Module_GetApi(MODULE_API_VERSION gateway_api_version)
#endif
{
(void)gateway_api_version;
return (const MODULE_API *)&ZwaveDevice_APIS_all;
}
<|endoftext|>
|
<commit_before>//===--- Immediate.cpp - the swift immediate mode -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This is the implementation of the swift interpreter, which takes a
// source file and JITs it.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "swift-immediate"
#include "swift/Immediate/Immediate.h"
#include "ImmediateImpl.h"
#include "swift/Subsystems.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Module.h"
#include "swift/Frontend/Frontend.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/Basic/LLVM.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Linker/Linker.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Support/Path.h"
#include <dlfcn.h>
using namespace swift;
using namespace swift::immediate;
static bool loadRuntimeLib(StringRef sharedLibName, StringRef runtimeLibPath) {
// FIXME: Need error-checking.
llvm::SmallString<128> Path = runtimeLibPath;
llvm::sys::path::append(Path, sharedLibName);
return dlopen(Path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
}
bool swift::immediate::loadSwiftRuntime(StringRef runtimeLibPath) {
return loadRuntimeLib("libswiftCore" LTDL_SHLIB_EXT, runtimeLibPath);
}
static bool tryLoadLibrary(LinkLibrary linkLib,
SearchPathOptions searchPathOpts) {
llvm::SmallString<128> path = linkLib.getName();
// If we have an absolute or relative path, just try to load it now.
if (llvm::sys::path::has_parent_path(path.str())) {
return dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
}
bool success = false;
switch (linkLib.getKind()) {
case LibraryKind::Library: {
llvm::SmallString<32> stem;
if (llvm::sys::path::has_extension(path.str())) {
stem = std::move(path);
} else {
// FIXME: Try the appropriate extension for the current platform?
stem = "lib";
stem += path;
stem += LTDL_SHLIB_EXT;
}
// Try user-provided library search paths first.
for (auto &libDir : searchPathOpts.LibrarySearchPaths) {
path = libDir;
llvm::sys::path::append(path, stem.str());
success = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
if (success)
break;
}
// Let dlopen determine the best search paths.
if (!success)
success = dlopen(stem.c_str(), RTLD_LAZY | RTLD_GLOBAL);
// If that fails, try our runtime library path.
if (!success)
success = loadRuntimeLib(stem, searchPathOpts.RuntimeLibraryPath);
break;
}
case LibraryKind::Framework: {
// If we have a framework, mangle the name to point to the framework
// binary.
llvm::SmallString<64> frameworkPart{std::move(path)};
frameworkPart += ".framework";
llvm::sys::path::append(frameworkPart, linkLib.getName());
// Try user-provided framework search paths first; frameworks contain
// binaries as well as modules.
for (auto &frameworkDir : searchPathOpts.FrameworkSearchPaths) {
path = frameworkDir;
llvm::sys::path::append(path, frameworkPart.str());
success = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
if (success)
break;
}
// If that fails, let dlopen search for system frameworks.
if (!success)
success = dlopen(frameworkPart.c_str(), RTLD_LAZY | RTLD_GLOBAL);
break;
}
}
return success;
}
bool swift::immediate::tryLoadLibraries(ArrayRef<LinkLibrary> LinkLibraries,
SearchPathOptions SearchPathOpts,
DiagnosticEngine &Diags) {
SmallVector<bool, 4> LoadedLibraries;
LoadedLibraries.append(LinkLibraries.size(), false);
// Libraries are not sorted in the topological order of dependencies, and we
// don't know the dependencies in advance. Try to load all libraries until
// we stop making progress.
bool HadProgress;
do {
HadProgress = false;
for (unsigned i = 0; i != LinkLibraries.size(); ++i) {
if (!LoadedLibraries[i] &&
tryLoadLibrary(LinkLibraries[i], SearchPathOpts)) {
LoadedLibraries[i] = true;
HadProgress = true;
}
}
} while (HadProgress);
return std::all_of(LoadedLibraries.begin(), LoadedLibraries.end(),
[](bool Value) { return Value; });
}
static void linkerDiagnosticHandlerNoCtx(const llvm::DiagnosticInfo &DI) {
if (DI.getSeverity() != llvm::DS_Error)
return;
std::string MsgStorage;
{
llvm::raw_string_ostream Stream(MsgStorage);
llvm::DiagnosticPrinterRawOStream DP(Stream);
DI.print(DP);
}
llvm::errs() << "Error linking swift modules\n";
llvm::errs() << MsgStorage << "\n";
}
static void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI,
void *Context) {
// This assert self documents our precondition that Context is always
// nullptr. It seems that parts of LLVM are using the flexibility of having a
// context. We don't really care about this.
assert(Context == nullptr && "We assume Context is always a nullptr");
return linkerDiagnosticHandlerNoCtx(DI);
}
bool swift::immediate::linkLLVMModules(llvm::Module *Module,
std::unique_ptr<llvm::Module> SubModule
// TODO: reactivate the linker mode if it is
// supported in llvm again. Otherwise remove the
// commented code completely.
/*, llvm::Linker::LinkerMode LinkerMode */)
{
llvm::LLVMContext &Ctx = SubModule->getContext();
auto OldHandler = Ctx.getDiagnosticHandler();
void *OldDiagnosticContext = Ctx.getDiagnosticContext();
Ctx.setDiagnosticHandler(linkerDiagnosticHandler, nullptr);
// TODO: reactivate the linker mode if it is
// supported in llvm again. Otherwise remove the
// commented code completely.
bool Failed = llvm::Linker::linkModules(*Module, std::move(SubModule),
linkerDiagnosticHandlerNoCtx
/*, LinkerMode*/);
Ctx.setDiagnosticHandler(OldHandler, OldDiagnosticContext);
return !Failed;
}
bool swift::immediate::IRGenImportedModules(
CompilerInstance &CI,
llvm::Module &Module,
llvm::SmallPtrSet<swift::Module *, 8> &ImportedModules,
SmallVectorImpl<llvm::Function*> &InitFns,
IRGenOptions &IRGenOpts,
const SILOptions &SILOpts) {
swift::Module *M = CI.getMainModule();
// Perform autolinking.
SmallVector<LinkLibrary, 4> AllLinkLibraries(IRGenOpts.LinkLibraries);
auto addLinkLibrary = [&](LinkLibrary linkLib) {
AllLinkLibraries.push_back(linkLib);
};
M->forAllVisibleModules({}, /*includePrivateTopLevel=*/true,
[&](Module::ImportedModule import) {
import.second->collectLinkLibraries(addLinkLibrary);
});
// Hack to handle thunks eagerly synthesized by the Clang importer.
swift::Module *prev = nullptr;
for (auto external : CI.getASTContext().ExternalDefinitions) {
swift::Module *next = external->getModuleContext();
if (next == prev)
continue;
next->collectLinkLibraries(addLinkLibrary);
prev = next;
}
tryLoadLibraries(AllLinkLibraries, CI.getASTContext().SearchPathOpts,
CI.getDiags());
ImportedModules.insert(M);
if (!CI.hasSourceImport())
return false;
// IRGen the modules this module depends on. This is only really necessary
// for imported source, but that's a very convenient thing to do in -i mode.
// FIXME: Crawling all loaded modules is a hack.
// FIXME: And re-doing SILGen, SIL-linking, SIL diagnostics, and IRGen is
// expensive, because it's not properly being limited to new things right now.
bool hadError = false;
for (auto &entry : CI.getASTContext().LoadedModules) {
swift::Module *import = entry.second;
if (!ImportedModules.insert(import).second)
continue;
std::unique_ptr<SILModule> SILMod = performSILGeneration(import,
CI.getSILOptions());
performSILLinking(SILMod.get());
if (runSILDiagnosticPasses(*SILMod)) {
hadError = true;
break;
}
// FIXME: We shouldn't need to use the global context here, but
// something is persisting across calls to performIRGeneration.
auto SubModule = performIRGeneration(IRGenOpts, import, SILMod.get(),
import->getName().str(),
llvm::getGlobalContext());
if (CI.getASTContext().hadError()) {
hadError = true;
break;
}
if (!linkLLVMModules(&Module, std::move(SubModule)
// TODO: reactivate the linker mode if it is
// supported in llvm again. Otherwise remove the
// commented code completely.
/*, llvm::Linker::DestroySource */)) {
hadError = true;
break;
}
// FIXME: This is an ugly hack; need to figure out how this should
// actually work.
SmallVector<char, 20> NameBuf;
StringRef InitFnName = (import->getName().str() + ".init").toStringRef(NameBuf);
llvm::Function *InitFn = Module.getFunction(InitFnName);
if (InitFn)
InitFns.push_back(InitFn);
}
return hadError;
}
int swift::RunImmediately(CompilerInstance &CI, const ProcessCmdLine &CmdLine,
IRGenOptions &IRGenOpts, const SILOptions &SILOpts) {
ASTContext &Context = CI.getASTContext();
// IRGen the main module.
auto *swiftModule = CI.getMainModule();
// FIXME: We shouldn't need to use the global context here, but
// something is persisting across calls to performIRGeneration.
auto ModuleOwner = performIRGeneration(
IRGenOpts, swiftModule, CI.getSILModule(), swiftModule->getName().str(),
llvm::getGlobalContext());
auto *Module = ModuleOwner.get();
if (Context.hadError())
return -1;
SmallVector<llvm::Function*, 8> InitFns;
llvm::SmallPtrSet<swift::Module *, 8> ImportedModules;
if (IRGenImportedModules(CI, *Module, ImportedModules, InitFns,
IRGenOpts, SILOpts))
return -1;
llvm::PassManagerBuilder PMBuilder;
PMBuilder.OptLevel = 2;
PMBuilder.Inliner = llvm::createFunctionInliningPass(200);
if (!loadSwiftRuntime(Context.SearchPathOpts.RuntimeLibraryPath)) {
CI.getDiags().diagnose(SourceLoc(),
diag::error_immediate_mode_missing_stdlib);
return -1;
}
// Build the ExecutionEngine.
llvm::EngineBuilder builder(std::move(ModuleOwner));
std::string ErrorMsg;
llvm::TargetOptions TargetOpt;
std::string CPU;
std::vector<std::string> Features;
std::tie(TargetOpt, CPU, Features)
= getIRTargetOptions(IRGenOpts, swiftModule->getASTContext());
builder.setRelocationModel(llvm::Reloc::PIC_);
builder.setTargetOptions(TargetOpt);
builder.setMCPU(CPU);
builder.setMAttrs(Features);
builder.setErrorStr(&ErrorMsg);
builder.setEngineKind(llvm::EngineKind::JIT);
llvm::ExecutionEngine *EE = builder.create();
if (!EE) {
llvm::errs() << "Error loading JIT: " << ErrorMsg;
return -1;
}
DEBUG(llvm::dbgs() << "Module to be executed:\n";
Module->dump());
EE->finalizeObject();
// Run the generated program.
for (auto InitFn : InitFns) {
DEBUG(llvm::dbgs() << "Running initialization function "
<< InitFn->getName() << '\n');
EE->runFunctionAsMain(InitFn, CmdLine, 0);
}
DEBUG(llvm::dbgs() << "Running static constructors\n");
EE->runStaticConstructorsDestructors(false);
DEBUG(llvm::dbgs() << "Running main\n");
llvm::Function *EntryFn = Module->getFunction("main");
return EE->runFunctionAsMain(EntryFn, CmdLine, 0);
}
<commit_msg>[upstream-update] llvm::Linker::linkModules no longer needs a NoCtx diagnostic handler. It always gets it from the llvm context.<commit_after>//===--- Immediate.cpp - the swift immediate mode -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This is the implementation of the swift interpreter, which takes a
// source file and JITs it.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "swift-immediate"
#include "swift/Immediate/Immediate.h"
#include "ImmediateImpl.h"
#include "swift/Subsystems.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Module.h"
#include "swift/Frontend/Frontend.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/Basic/LLVM.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Config/config.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Linker/Linker.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Support/Path.h"
#include <dlfcn.h>
using namespace swift;
using namespace swift::immediate;
static bool loadRuntimeLib(StringRef sharedLibName, StringRef runtimeLibPath) {
// FIXME: Need error-checking.
llvm::SmallString<128> Path = runtimeLibPath;
llvm::sys::path::append(Path, sharedLibName);
return dlopen(Path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
}
bool swift::immediate::loadSwiftRuntime(StringRef runtimeLibPath) {
return loadRuntimeLib("libswiftCore" LTDL_SHLIB_EXT, runtimeLibPath);
}
static bool tryLoadLibrary(LinkLibrary linkLib,
SearchPathOptions searchPathOpts) {
llvm::SmallString<128> path = linkLib.getName();
// If we have an absolute or relative path, just try to load it now.
if (llvm::sys::path::has_parent_path(path.str())) {
return dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
}
bool success = false;
switch (linkLib.getKind()) {
case LibraryKind::Library: {
llvm::SmallString<32> stem;
if (llvm::sys::path::has_extension(path.str())) {
stem = std::move(path);
} else {
// FIXME: Try the appropriate extension for the current platform?
stem = "lib";
stem += path;
stem += LTDL_SHLIB_EXT;
}
// Try user-provided library search paths first.
for (auto &libDir : searchPathOpts.LibrarySearchPaths) {
path = libDir;
llvm::sys::path::append(path, stem.str());
success = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
if (success)
break;
}
// Let dlopen determine the best search paths.
if (!success)
success = dlopen(stem.c_str(), RTLD_LAZY | RTLD_GLOBAL);
// If that fails, try our runtime library path.
if (!success)
success = loadRuntimeLib(stem, searchPathOpts.RuntimeLibraryPath);
break;
}
case LibraryKind::Framework: {
// If we have a framework, mangle the name to point to the framework
// binary.
llvm::SmallString<64> frameworkPart{std::move(path)};
frameworkPart += ".framework";
llvm::sys::path::append(frameworkPart, linkLib.getName());
// Try user-provided framework search paths first; frameworks contain
// binaries as well as modules.
for (auto &frameworkDir : searchPathOpts.FrameworkSearchPaths) {
path = frameworkDir;
llvm::sys::path::append(path, frameworkPart.str());
success = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
if (success)
break;
}
// If that fails, let dlopen search for system frameworks.
if (!success)
success = dlopen(frameworkPart.c_str(), RTLD_LAZY | RTLD_GLOBAL);
break;
}
}
return success;
}
bool swift::immediate::tryLoadLibraries(ArrayRef<LinkLibrary> LinkLibraries,
SearchPathOptions SearchPathOpts,
DiagnosticEngine &Diags) {
SmallVector<bool, 4> LoadedLibraries;
LoadedLibraries.append(LinkLibraries.size(), false);
// Libraries are not sorted in the topological order of dependencies, and we
// don't know the dependencies in advance. Try to load all libraries until
// we stop making progress.
bool HadProgress;
do {
HadProgress = false;
for (unsigned i = 0; i != LinkLibraries.size(); ++i) {
if (!LoadedLibraries[i] &&
tryLoadLibrary(LinkLibraries[i], SearchPathOpts)) {
LoadedLibraries[i] = true;
HadProgress = true;
}
}
} while (HadProgress);
return std::all_of(LoadedLibraries.begin(), LoadedLibraries.end(),
[](bool Value) { return Value; });
}
static void linkerDiagnosticHandlerNoCtx(const llvm::DiagnosticInfo &DI) {
if (DI.getSeverity() != llvm::DS_Error)
return;
std::string MsgStorage;
{
llvm::raw_string_ostream Stream(MsgStorage);
llvm::DiagnosticPrinterRawOStream DP(Stream);
DI.print(DP);
}
llvm::errs() << "Error linking swift modules\n";
llvm::errs() << MsgStorage << "\n";
}
static void linkerDiagnosticHandler(const llvm::DiagnosticInfo &DI,
void *Context) {
// This assert self documents our precondition that Context is always
// nullptr. It seems that parts of LLVM are using the flexibility of having a
// context. We don't really care about this.
assert(Context == nullptr && "We assume Context is always a nullptr");
return linkerDiagnosticHandlerNoCtx(DI);
}
bool swift::immediate::linkLLVMModules(llvm::Module *Module,
std::unique_ptr<llvm::Module> SubModule
// TODO: reactivate the linker mode if it is
// supported in llvm again. Otherwise remove the
// commented code completely.
/*, llvm::Linker::LinkerMode LinkerMode */)
{
llvm::LLVMContext &Ctx = SubModule->getContext();
auto OldHandler = Ctx.getDiagnosticHandler();
void *OldDiagnosticContext = Ctx.getDiagnosticContext();
Ctx.setDiagnosticHandler(linkerDiagnosticHandler, nullptr);
bool Failed = llvm::Linker::linkModules(*Module, std::move(SubModule));
Ctx.setDiagnosticHandler(OldHandler, OldDiagnosticContext);
return !Failed;
}
bool swift::immediate::IRGenImportedModules(
CompilerInstance &CI,
llvm::Module &Module,
llvm::SmallPtrSet<swift::Module *, 8> &ImportedModules,
SmallVectorImpl<llvm::Function*> &InitFns,
IRGenOptions &IRGenOpts,
const SILOptions &SILOpts) {
swift::Module *M = CI.getMainModule();
// Perform autolinking.
SmallVector<LinkLibrary, 4> AllLinkLibraries(IRGenOpts.LinkLibraries);
auto addLinkLibrary = [&](LinkLibrary linkLib) {
AllLinkLibraries.push_back(linkLib);
};
M->forAllVisibleModules({}, /*includePrivateTopLevel=*/true,
[&](Module::ImportedModule import) {
import.second->collectLinkLibraries(addLinkLibrary);
});
// Hack to handle thunks eagerly synthesized by the Clang importer.
swift::Module *prev = nullptr;
for (auto external : CI.getASTContext().ExternalDefinitions) {
swift::Module *next = external->getModuleContext();
if (next == prev)
continue;
next->collectLinkLibraries(addLinkLibrary);
prev = next;
}
tryLoadLibraries(AllLinkLibraries, CI.getASTContext().SearchPathOpts,
CI.getDiags());
ImportedModules.insert(M);
if (!CI.hasSourceImport())
return false;
// IRGen the modules this module depends on. This is only really necessary
// for imported source, but that's a very convenient thing to do in -i mode.
// FIXME: Crawling all loaded modules is a hack.
// FIXME: And re-doing SILGen, SIL-linking, SIL diagnostics, and IRGen is
// expensive, because it's not properly being limited to new things right now.
bool hadError = false;
for (auto &entry : CI.getASTContext().LoadedModules) {
swift::Module *import = entry.second;
if (!ImportedModules.insert(import).second)
continue;
std::unique_ptr<SILModule> SILMod = performSILGeneration(import,
CI.getSILOptions());
performSILLinking(SILMod.get());
if (runSILDiagnosticPasses(*SILMod)) {
hadError = true;
break;
}
// FIXME: We shouldn't need to use the global context here, but
// something is persisting across calls to performIRGeneration.
auto SubModule = performIRGeneration(IRGenOpts, import, SILMod.get(),
import->getName().str(),
llvm::getGlobalContext());
if (CI.getASTContext().hadError()) {
hadError = true;
break;
}
if (!linkLLVMModules(&Module, std::move(SubModule)
// TODO: reactivate the linker mode if it is
// supported in llvm again. Otherwise remove the
// commented code completely.
/*, llvm::Linker::DestroySource */)) {
hadError = true;
break;
}
// FIXME: This is an ugly hack; need to figure out how this should
// actually work.
SmallVector<char, 20> NameBuf;
StringRef InitFnName = (import->getName().str() + ".init").toStringRef(NameBuf);
llvm::Function *InitFn = Module.getFunction(InitFnName);
if (InitFn)
InitFns.push_back(InitFn);
}
return hadError;
}
int swift::RunImmediately(CompilerInstance &CI, const ProcessCmdLine &CmdLine,
IRGenOptions &IRGenOpts, const SILOptions &SILOpts) {
ASTContext &Context = CI.getASTContext();
// IRGen the main module.
auto *swiftModule = CI.getMainModule();
// FIXME: We shouldn't need to use the global context here, but
// something is persisting across calls to performIRGeneration.
auto ModuleOwner = performIRGeneration(
IRGenOpts, swiftModule, CI.getSILModule(), swiftModule->getName().str(),
llvm::getGlobalContext());
auto *Module = ModuleOwner.get();
if (Context.hadError())
return -1;
SmallVector<llvm::Function*, 8> InitFns;
llvm::SmallPtrSet<swift::Module *, 8> ImportedModules;
if (IRGenImportedModules(CI, *Module, ImportedModules, InitFns,
IRGenOpts, SILOpts))
return -1;
llvm::PassManagerBuilder PMBuilder;
PMBuilder.OptLevel = 2;
PMBuilder.Inliner = llvm::createFunctionInliningPass(200);
if (!loadSwiftRuntime(Context.SearchPathOpts.RuntimeLibraryPath)) {
CI.getDiags().diagnose(SourceLoc(),
diag::error_immediate_mode_missing_stdlib);
return -1;
}
// Build the ExecutionEngine.
llvm::EngineBuilder builder(std::move(ModuleOwner));
std::string ErrorMsg;
llvm::TargetOptions TargetOpt;
std::string CPU;
std::vector<std::string> Features;
std::tie(TargetOpt, CPU, Features)
= getIRTargetOptions(IRGenOpts, swiftModule->getASTContext());
builder.setRelocationModel(llvm::Reloc::PIC_);
builder.setTargetOptions(TargetOpt);
builder.setMCPU(CPU);
builder.setMAttrs(Features);
builder.setErrorStr(&ErrorMsg);
builder.setEngineKind(llvm::EngineKind::JIT);
llvm::ExecutionEngine *EE = builder.create();
if (!EE) {
llvm::errs() << "Error loading JIT: " << ErrorMsg;
return -1;
}
DEBUG(llvm::dbgs() << "Module to be executed:\n";
Module->dump());
EE->finalizeObject();
// Run the generated program.
for (auto InitFn : InitFns) {
DEBUG(llvm::dbgs() << "Running initialization function "
<< InitFn->getName() << '\n');
EE->runFunctionAsMain(InitFn, CmdLine, 0);
}
DEBUG(llvm::dbgs() << "Running static constructors\n");
EE->runStaticConstructorsDestructors(false);
DEBUG(llvm::dbgs() << "Running main\n");
llvm::Function *EntryFn = Module->getFunction("main");
return EE->runFunctionAsMain(EntryFn, CmdLine, 0);
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786 )
#endif
#include "common.h"
// interface header
#include "WorldFileObject.h"
// system headers
#include <string.h>
#include <iostream>
#include <vector>
WorldFileObject::WorldFileObject()
{
name = "";
}
bool WorldFileObject::read(const char *cmd, std::istream& input)
{
if (strcasecmp(cmd, "name") == 0) {
input >> name;
return true;
}
return false;
}
void WorldFileObject::writeToWorld(WorldInfo*) const
{
std::cout << "ERROR: writeToWorld() called improperly" << std::endl;
return;
}
void WorldFileObject::writeToManager() const
{
std::cout << "ERROR: writeToManager() called improperly" << std::endl;
return;
}
void WorldFileObject::writeToGroupDef(GroupDefinition*) const
{
std::cout << "ERROR: writeToGroupDef() called improperly" << std::endl;
return;
}
/** delete all of the world file objects from a vector list
*/
void emptyWorldFileObjectList(std::vector<WorldFileObject*>& wlist)
{
const int n = wlist.size();
for (int i = 0; i < n; ++i) {
delete wlist[i];
}
wlist.clear();
}
// Local variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>undo removal of <string> include<commit_after>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifdef _MSC_VER
#pragma warning( 4: 4786 )
#endif
#include "common.h"
// interface header
#include "WorldFileObject.h"
// system headers
#include <string>
#include <string.h>
#include <iostream>
#include <vector>
WorldFileObject::WorldFileObject()
{
name = "";
}
bool WorldFileObject::read(const char *cmd, std::istream& input)
{
if (strcasecmp(cmd, "name") == 0) {
input >> name;
return true;
}
return false;
}
void WorldFileObject::writeToWorld(WorldInfo*) const
{
std::cout << "ERROR: writeToWorld() called improperly" << std::endl;
return;
}
void WorldFileObject::writeToManager() const
{
std::cout << "ERROR: writeToManager() called improperly" << std::endl;
return;
}
void WorldFileObject::writeToGroupDef(GroupDefinition*) const
{
std::cout << "ERROR: writeToGroupDef() called improperly" << std::endl;
return;
}
/** delete all of the world file objects from a vector list
*/
void emptyWorldFileObjectList(std::vector<WorldFileObject*>& wlist)
{
const int n = wlist.size();
for (int i = 0; i < n; ++i) {
delete wlist[i];
}
wlist.clear();
}
// Local variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <cstring>
#include <limits>
#include <memory>
#include <android/log.h>
#include <boost/format.hpp>
#include <boost/utility.hpp>
#include <tbb/blocked_range2d.h>
#include <tbb/parallel_for.h>
#include <tbb/task_scheduler_init.h>
#include "body_parts_recognizer.h"
#include "rgbd_image.h"
#include "sources.h"
#include "stopwatch.h"
const Depth BACKGROUND_DEPTH = std::numeric_limits<Depth>::max();
struct DepthImage
{
private:
unsigned width, height;
std::vector<Depth> depths;
public:
DepthImage(const RGBDImage & image)
: width(image.width), height(image.height), depths(width * height)
{
for (std::size_t i = 0; i < depths.size(); ++i)
depths[i] = image.pixels[i].d == 0 ? BACKGROUND_DEPTH : image.pixels[i].d; // we consider 0 to be invalid depth
}
void
applyThreshold(int threshold)
{
Depth min_depth = *std::min_element(depths.begin (), depths.end ());
for (std::size_t i = 0; i < depths.size (); ++i)
depths[i] = depths[i] <= min_depth + threshold ? depths[i] : BACKGROUND_DEPTH;
}
Depth
getDepth(int x, int y) const
{
if (x < 0 || x >= int (width) || y < 0 || y >= int (height))
return BACKGROUND_DEPTH;
return depths[x + width * y];
}
unsigned getWidth() const { return width; }
unsigned getHeight() const { return height; }
};
struct DecisionTreeCPU
{
tbb::task_scheduler_init tbb_init;
struct Offsets
{
boost::int16_t du1, dv1, du2, dv2;
};
struct Node
{
Offsets offsets;
boost::int16_t threshold;
};
boost::uint16_t depth;
std::vector<Node> nodes;
std::vector<Label> leaves;
DecisionTreeCPU(const char * data)
{
std::memcpy (&depth, data, sizeof depth);
data += sizeof depth;
nodes.resize ((1 << depth) - 1);
std::memcpy (&nodes.front (), data, nodes.size () * sizeof (Node));
data += nodes.size () * sizeof (Node);
leaves.resize (1 << depth);
std::memcpy (&leaves.front (), data, leaves.size () * sizeof (Label));
data += leaves.size () * sizeof (Label);
}
Label
walk(const DepthImage & image, int x, int y) const
{
unsigned nid = 0;
Depth d0 = image.getDepth(x, y);
float scale = 1000.0f / d0;
for(int node_depth = 0; node_depth < depth; ++node_depth)
{
const Node & node = nodes[nid];
Depth d1 = image.getDepth (x + node.offsets.du1 * scale, y + node.offsets.dv1 * scale);
Depth d2 = image.getDepth (x + node.offsets.du2 * scale, y + node.offsets.dv2 * scale);
int feature = int (d1) - int (d2);
if (feature > node.threshold)
nid = nid * 2 + 2;
else
nid = nid * 2 + 1;
}
return leaves[nid - nodes.size()];
}
struct WalkHelper
{
private:
const DecisionTreeCPU & tree;
const DepthImage & image;
std::vector<Label> & labels;
public:
WalkHelper(const DecisionTreeCPU & tree, const DepthImage & image, std::vector<Label> & labels)
: tree(tree), image(image), labels(labels)
{
}
void
operator () (const tbb::blocked_range2d<unsigned> & range) const
{
for (unsigned y = range.rows().begin(); y < range.rows().end(); ++y)
for (unsigned x = range.cols().begin(); x < range.cols().end(); ++x)
labels[x + y * image.getWidth()] = image.getDepth(x, y) == BACKGROUND_DEPTH ?
Labels::Background : tree.walk(image, x, y);
}
};
void
eval(const DepthImage & image, std::vector<Label> & labels) const
{
tbb::parallel_for(
tbb::blocked_range2d<unsigned>(0, image.getHeight(), 0, image.getWidth()),
WalkHelper(*this, image, labels)
);
}
};
int maxElementNoTie(int num, unsigned * elements)
{
int max_element = 0;
unsigned max = elements[max_element];
for (int i = 1; i < num; ++i)
{
unsigned val = elements[i];
if (max < val) { max_element = i; max = val; }
else if (max == val) { max_element = -1; }
}
return max_element;
}
struct ConsensusHelper
{
private:
const std::vector<std::vector<Label> > & multi_labels;
std::vector<Label> & labels;
const DepthImage & depth_image;
public:
ConsensusHelper(
const std::vector<std::vector<Label> > & multi_labels,
std::vector<Label> & labels,
const DepthImage & depth_image
)
: multi_labels(multi_labels), labels(labels), depth_image(depth_image)
{
}
void operator ()(const tbb::blocked_range2d<unsigned> & range) const
{
for (unsigned y = range.rows().begin(); y < range.rows().end(); ++y)
for (unsigned x = range.cols().begin(); x < range.cols().end(); ++x)
{
std::size_t i = x + y * depth_image.getWidth();
bool background = true;
for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)
if (multi_labels[ti][i] != Labels::Background) background = false;
if (background)
{
labels[i] = Labels::Background;
continue;
}
unsigned bins[Labels::NUM_LABELS] = { 0 };
for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)
++bins[multi_labels[ti][i]];
int consensus = maxElementNoTie(Labels::NUM_LABELS, bins);
if (consensus == -1)
{
std::fill (bins, bins + Labels::NUM_LABELS, 0);
Depth d = depth_image.getDepth (x, y);
for (int off_x = -1; off_x <= 1; ++off_x)
for (int off_y = -1; off_y <= 1; ++off_y)
{
Depth off_d = depth_image.getDepth (x + off_x, y + off_y);
if (std::abs (d - off_d) < 50)
for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)
++bins[multi_labels[ti][i]];
}
labels[i] = std::max_element (bins, bins + Labels::NUM_LABELS) - bins;
}
else
{
labels[i] = consensus;
}
}
}
};
BodyPartsRecognizer::BodyPartsRecognizer(std::size_t num_trees, const char * trees[])
{
this->trees.resize(num_trees);
for (std::size_t i = 0; i < num_trees; ++i)
this->trees[i].reset(new Tree(trees[i]));
#if GPU_CONSENSUS
this->consensus_finder.reset(new ConsensusFinderGPU(num_trees));
#endif
}
void
BodyPartsRecognizer::recognize(const RGBDImage & image, std::vector<Label> & labels)
{
labels.clear ();
labels.resize (image.width * image.height);
DepthImage depth_image (image);
Stopwatch watch_threshold;
depth_image.applyThreshold (500);
__android_log_print(ANDROID_LOG_INFO, "BPR", "Thresholding: %d ms", watch_threshold.elapsedMs());
std::vector<std::vector<Label> > multi_labels (trees.size ());
for (std::size_t ti = 0; ti < trees.size (); ++ti)
{
Stopwatch watch_evaluation;
multi_labels[ti].resize (labels.size ());
trees[ti]->eval (depth_image, multi_labels[ti]);
__android_log_print(ANDROID_LOG_INFO, "BPR", "Evaluating tree %d: %d ms", ti, watch_evaluation.elapsedMs());
}
Stopwatch watch_consensus;
#if GPU_CONSENSUS
consensus_finder->run(image.width, image.height, multi_labels, labels);
#else
tbb::parallel_for(
tbb::blocked_range2d<unsigned>(0, depth_image.getHeight(), 0, depth_image.getWidth()),
ConsensusHelper(multi_labels, labels, depth_image)
);
#endif
__android_log_print(ANDROID_LOG_INFO, "BPR", "Finding consensus: %d ms", watch_consensus.elapsedMs());
}
<commit_msg>Removed another remnant of the GPU implementation.<commit_after>#include <algorithm>
#include <cstring>
#include <limits>
#include <memory>
#include <android/log.h>
#include <boost/format.hpp>
#include <boost/utility.hpp>
#include <tbb/blocked_range2d.h>
#include <tbb/parallel_for.h>
#include <tbb/task_scheduler_init.h>
#include "body_parts_recognizer.h"
#include "rgbd_image.h"
#include "sources.h"
#include "stopwatch.h"
const Depth BACKGROUND_DEPTH = std::numeric_limits<Depth>::max();
struct DepthImage
{
private:
unsigned width, height;
std::vector<Depth> depths;
public:
DepthImage(const RGBDImage & image)
: width(image.width), height(image.height), depths(width * height)
{
for (std::size_t i = 0; i < depths.size(); ++i)
depths[i] = image.pixels[i].d == 0 ? BACKGROUND_DEPTH : image.pixels[i].d; // we consider 0 to be invalid depth
}
void
applyThreshold(int threshold)
{
Depth min_depth = *std::min_element(depths.begin (), depths.end ());
for (std::size_t i = 0; i < depths.size (); ++i)
depths[i] = depths[i] <= min_depth + threshold ? depths[i] : BACKGROUND_DEPTH;
}
Depth
getDepth(int x, int y) const
{
if (x < 0 || x >= int (width) || y < 0 || y >= int (height))
return BACKGROUND_DEPTH;
return depths[x + width * y];
}
unsigned getWidth() const { return width; }
unsigned getHeight() const { return height; }
};
struct DecisionTreeCPU
{
tbb::task_scheduler_init tbb_init;
struct Offsets
{
boost::int16_t du1, dv1, du2, dv2;
};
struct Node
{
Offsets offsets;
boost::int16_t threshold;
};
boost::uint16_t depth;
std::vector<Node> nodes;
std::vector<Label> leaves;
DecisionTreeCPU(const char * data)
{
std::memcpy (&depth, data, sizeof depth);
data += sizeof depth;
nodes.resize ((1 << depth) - 1);
std::memcpy (&nodes.front (), data, nodes.size () * sizeof (Node));
data += nodes.size () * sizeof (Node);
leaves.resize (1 << depth);
std::memcpy (&leaves.front (), data, leaves.size () * sizeof (Label));
data += leaves.size () * sizeof (Label);
}
Label
walk(const DepthImage & image, int x, int y) const
{
unsigned nid = 0;
Depth d0 = image.getDepth(x, y);
float scale = 1000.0f / d0;
for(int node_depth = 0; node_depth < depth; ++node_depth)
{
const Node & node = nodes[nid];
Depth d1 = image.getDepth (x + node.offsets.du1 * scale, y + node.offsets.dv1 * scale);
Depth d2 = image.getDepth (x + node.offsets.du2 * scale, y + node.offsets.dv2 * scale);
int feature = int (d1) - int (d2);
if (feature > node.threshold)
nid = nid * 2 + 2;
else
nid = nid * 2 + 1;
}
return leaves[nid - nodes.size()];
}
struct WalkHelper
{
private:
const DecisionTreeCPU & tree;
const DepthImage & image;
std::vector<Label> & labels;
public:
WalkHelper(const DecisionTreeCPU & tree, const DepthImage & image, std::vector<Label> & labels)
: tree(tree), image(image), labels(labels)
{
}
void
operator () (const tbb::blocked_range2d<unsigned> & range) const
{
for (unsigned y = range.rows().begin(); y < range.rows().end(); ++y)
for (unsigned x = range.cols().begin(); x < range.cols().end(); ++x)
labels[x + y * image.getWidth()] = image.getDepth(x, y) == BACKGROUND_DEPTH ?
Labels::Background : tree.walk(image, x, y);
}
};
void
eval(const DepthImage & image, std::vector<Label> & labels) const
{
tbb::parallel_for(
tbb::blocked_range2d<unsigned>(0, image.getHeight(), 0, image.getWidth()),
WalkHelper(*this, image, labels)
);
}
};
int maxElementNoTie(int num, unsigned * elements)
{
int max_element = 0;
unsigned max = elements[max_element];
for (int i = 1; i < num; ++i)
{
unsigned val = elements[i];
if (max < val) { max_element = i; max = val; }
else if (max == val) { max_element = -1; }
}
return max_element;
}
struct ConsensusHelper
{
private:
const std::vector<std::vector<Label> > & multi_labels;
std::vector<Label> & labels;
const DepthImage & depth_image;
public:
ConsensusHelper(
const std::vector<std::vector<Label> > & multi_labels,
std::vector<Label> & labels,
const DepthImage & depth_image
)
: multi_labels(multi_labels), labels(labels), depth_image(depth_image)
{
}
void operator ()(const tbb::blocked_range2d<unsigned> & range) const
{
for (unsigned y = range.rows().begin(); y < range.rows().end(); ++y)
for (unsigned x = range.cols().begin(); x < range.cols().end(); ++x)
{
std::size_t i = x + y * depth_image.getWidth();
bool background = true;
for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)
if (multi_labels[ti][i] != Labels::Background) background = false;
if (background)
{
labels[i] = Labels::Background;
continue;
}
unsigned bins[Labels::NUM_LABELS] = { 0 };
for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)
++bins[multi_labels[ti][i]];
int consensus = maxElementNoTie(Labels::NUM_LABELS, bins);
if (consensus == -1)
{
std::fill (bins, bins + Labels::NUM_LABELS, 0);
Depth d = depth_image.getDepth (x, y);
for (int off_x = -1; off_x <= 1; ++off_x)
for (int off_y = -1; off_y <= 1; ++off_y)
{
Depth off_d = depth_image.getDepth (x + off_x, y + off_y);
if (std::abs (d - off_d) < 50)
for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)
++bins[multi_labels[ti][i]];
}
labels[i] = std::max_element (bins, bins + Labels::NUM_LABELS) - bins;
}
else
{
labels[i] = consensus;
}
}
}
};
BodyPartsRecognizer::BodyPartsRecognizer(std::size_t num_trees, const char * trees[])
{
this->trees.resize(num_trees);
for (std::size_t i = 0; i < num_trees; ++i)
this->trees[i].reset(new Tree(trees[i]));
#if GPU_CONSENSUS
this->consensus_finder.reset(new ConsensusFinderGPU(num_trees));
#endif
}
void
BodyPartsRecognizer::recognize(const RGBDImage & image, std::vector<Label> & labels)
{
labels.clear ();
labels.resize (image.width * image.height);
DepthImage depth_image (image);
Stopwatch watch_threshold;
depth_image.applyThreshold (500);
__android_log_print(ANDROID_LOG_INFO, "BPR", "Thresholding: %d ms", watch_threshold.elapsedMs());
std::vector<std::vector<Label> > multi_labels (trees.size ());
for (std::size_t ti = 0; ti < trees.size (); ++ti)
{
Stopwatch watch_evaluation;
multi_labels[ti].resize (labels.size ());
trees[ti]->eval (depth_image, multi_labels[ti]);
__android_log_print(ANDROID_LOG_INFO, "BPR", "Evaluating tree %d: %d ms", ti, watch_evaluation.elapsedMs());
}
Stopwatch watch_consensus;
tbb::parallel_for(
tbb::blocked_range2d<unsigned>(0, depth_image.getHeight(), 0, depth_image.getWidth()),
ConsensusHelper(multi_labels, labels, depth_image)
);
__android_log_print(ANDROID_LOG_INFO, "BPR", "Finding consensus: %d ms", watch_consensus.elapsedMs());
}
<|endoftext|>
|
<commit_before>#include "json.h"
using namespace std;
// Value
JsonValue * JsonValue::fromString(string message){
int i = 0;
return JsonValue::fromString(message, i);
}
JsonValue * JsonValue::fromString(string message, int &i){
while(i < message.length()){
i += skip_whitespace(message, i);
switch(message[i]){
case '{':
return JsonDict::fromString(message, i);
break;
case '[':
return JsonList::fromString(message, i);
break;
case '"':
return JsonString::fromString(message, i);
break;
case 't':
case 'f':
return JsonBool::fromString(message, i);
case 'n':
return JsonNull::fromString(message, i);
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return JsonInt::fromString(message, i);
break;
default:
throw PARSE_ERROR("unknwown value", i);
}
}
throw PARSE_ERROR("no value found", i);
}
// String
JsonString::JsonString(string val){
replace_all(val, "\\\\", '\\');
replace_all(val, "\\\"", '"');
replace_all(val, "\\t", '\t');
replace_all(val, "\\n", '\n');
replace_all(val, "\\r", '\r');
replace_all(val, "\\b", '\b');
replace_all(val, "\\f", '\f');
// TODO : replace \u four-hex-digits
value = val;
}
JsonString::operator string() const{
return value;
}
JsonString * JsonString::fromString(string message, int &i){
i++;
int start = i;
while(i < message.length()){
switch(message[i]){
case '\\':
i++;
break;
case '"':
string s = message.substr(start, i - start);
i++;
return new JsonString(s);
}
i++;
}
throw PARSE_ERROR("No \" ending string", i);
}
string JsonString::toString(){
string infos = "\"" + this->value + "\"";
return infos;
}
// Dict
JsonDict * JsonDict::fromString(string message, int &i){
i++;
JsonDict * r = new JsonDict();
i += skip_whitespace(message, i);
if(message[i] == '}'){
i++;
return r;
}
while(1){
JsonString * key = NULL;
JsonValue * value = NULL;
i += skip_whitespace(message, i);
key = JsonString::fromString(message, i);
string key_str = *key;
delete key;
i += skip_whitespace(message, i);
i += skip_colon(message, i);
i += skip_whitespace(message, i);
value = JsonValue::fromString(message, i);
r->add(key_str, value);
i += skip_whitespace(message, i);
if(message[i] == ','){
i++;
}
else if(message[i] == '}'){
i++;
return r;
}
else{
throw PARSE_ERROR("expected } or , found '" + string(1, message[i]) + "'", i);
}
}
}
string JsonDict::toString(){
string infos = "{";
for (map<string, JsonValue *>::iterator index = this->dict.begin() ; index != this->dict.end() ; ++index ){
infos += "\"" + ((string) index->first) + "\"" + " : ";
infos += index->second->toString();
infos += ", ";
}
infos = infos.substr(0, infos.size()-2) + "}";
return infos;
}
void JsonDict::add(string key, JsonValue * value){
dict[key] = value;
}
size_t JsonDict::size(){
return dict.size();
}
JsonValue * JsonDict::operator[](const string &str){
// TODO : Should make a copy ?
return this->dict[str];
}
// List
JsonList * JsonList::fromString(string message, int &i){
i++;
JsonList * r = new JsonList();
i += skip_whitespace(message, i);
if(message[i] == ']') {
i++;
return r;
}
while(1){
JsonValue * value = NULL;
i += skip_whitespace(message, i);
value = JsonValue::fromString(message, i);
r->add(value);
i += skip_whitespace(message, i);
switch(message[i]){
case ',':
i++;
break;
case ']':
i++;
return r;
break;
default:
throw PARSE_ERROR("expected ] or , found " + string(1, message[i]), i);
}
}
}
string JsonList::toString(){
string infos = "[";
int index = 0;
while (index < this->content.size()){
infos += this->content[index]->toString();
index++;
infos+=", ";
}
infos = infos.substr(0, infos.size() - 2) + "]";
return infos;
}
void JsonList::add(JsonValue * value){
content.push_back(value);
}
size_t JsonList::size(){
return content.size();
}
JsonValue * JsonList::operator[](const int &i){
return content.at(i);
}
// Int
JsonInt::JsonInt(int val){
value = val;
}
JsonInt * JsonInt::fromString(string message, int &i){
JsonInt * r = new JsonInt();
bool end = false;
int start = i;
while(!end){
switch(message[i]){
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
i++;
break;
default:
end = true;
break;
}
}
r->setValue(message.substr(start, i));
return r;
}
string JsonInt::toString(){
return (string) *this;
}
int JsonInt::getValue(){
return value;
}
void JsonInt::setValue(int val){
value = val;
}
void JsonInt::setValue(string val){
value = stoi(val);
}
JsonInt::operator string() const{
return to_string(value);
}
JsonInt::operator int() const{
return value;
}
// Null
string JsonNull::toString(){
return "null";
}
JsonNull * JsonNull::fromString(string message, int &i){
if(message.substr(0,4) != "null"){
throw PARSE_ERROR("expected null", i);
}
i += 4;
return new JsonNull();
}
bool JsonNull::operator ==(const int * i){
return i == 0;
}
// Bool
JsonBool::JsonBool(bool val){
value = val;
}
JsonBool * JsonBool::fromString(string message, int &i){
JsonBool * r = NULL;
if(message[0] == 't'){
if(message.substr(0,4) != "true"){
throw PARSE_ERROR("expected true", i);
}
r = new JsonBool(true);
i += 4;
}
else {
if(message.substr(0,5) != "false"){
throw PARSE_ERROR("expected false", i);
}
r = new JsonBool(false);
i += 5;
}
return r;
}
string JsonBool::toString(){
if(value){
return "true";
}
else {
return "false";
}
}
bool JsonBool::operator ==(const bool i){
return value == i;
}
JsonBool::operator bool() const{
return value;
}
<commit_msg>More verbose ParseError<commit_after>#include "json.h"
using namespace std;
// Value
JsonValue * JsonValue::fromString(string message){
int i = 0;
return JsonValue::fromString(message, i);
}
JsonValue * JsonValue::fromString(string message, int &i){
while(i < message.length()){
i += skip_whitespace(message, i);
switch(message[i]){
case '{':
return JsonDict::fromString(message, i);
break;
case '[':
return JsonList::fromString(message, i);
break;
case '"':
return JsonString::fromString(message, i);
break;
case 't':
case 'f':
return JsonBool::fromString(message, i);
case 'n':
return JsonNull::fromString(message, i);
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return JsonInt::fromString(message, i);
break;
default:
throw PARSE_ERROR("unknwown value. Got '" + string(1, message[i]) + "'", i);
}
}
throw PARSE_ERROR("no value found", i);
}
// String
JsonString::JsonString(string val){
replace_all(val, "\\\\", '\\');
replace_all(val, "\\\"", '"');
replace_all(val, "\\t", '\t');
replace_all(val, "\\n", '\n');
replace_all(val, "\\r", '\r');
replace_all(val, "\\b", '\b');
replace_all(val, "\\f", '\f');
// TODO : replace \u four-hex-digits
value = val;
}
JsonString::operator string() const{
return value;
}
JsonString * JsonString::fromString(string message, int &i){
i++;
int start = i;
while(i < message.length()){
switch(message[i]){
case '\\':
i++;
break;
case '"':
string s = message.substr(start, i - start);
i++;
return new JsonString(s);
}
i++;
}
throw PARSE_ERROR("No \" ending string", i);
}
string JsonString::toString(){
string infos = "\"" + this->value + "\"";
return infos;
}
// Dict
JsonDict * JsonDict::fromString(string message, int &i){
i++;
JsonDict * r = new JsonDict();
i += skip_whitespace(message, i);
if(message[i] == '}'){
i++;
return r;
}
while(1){
JsonString * key = NULL;
JsonValue * value = NULL;
i += skip_whitespace(message, i);
key = JsonString::fromString(message, i);
string key_str = *key;
delete key;
i += skip_whitespace(message, i);
i += skip_colon(message, i);
i += skip_whitespace(message, i);
value = JsonValue::fromString(message, i);
r->add(key_str, value);
i += skip_whitespace(message, i);
if(message[i] == ','){
i++;
}
else if(message[i] == '}'){
i++;
return r;
}
else{
throw PARSE_ERROR("expected } or , found '" + string(1, message[i]) + "'", i);
}
}
}
string JsonDict::toString(){
string infos = "{";
for (map<string, JsonValue *>::iterator index = this->dict.begin() ; index != this->dict.end() ; ++index ){
infos += "\"" + ((string) index->first) + "\"" + " : ";
infos += index->second->toString();
infos += ", ";
}
infos = infos.substr(0, infos.size()-2) + "}";
return infos;
}
void JsonDict::add(string key, JsonValue * value){
dict[key] = value;
}
size_t JsonDict::size(){
return dict.size();
}
JsonValue * JsonDict::operator[](const string &str){
// TODO : Should make a copy ?
return this->dict[str];
}
// List
JsonList * JsonList::fromString(string message, int &i){
i++;
JsonList * r = new JsonList();
i += skip_whitespace(message, i);
if(message[i] == ']') {
i++;
return r;
}
while(1){
JsonValue * value = NULL;
i += skip_whitespace(message, i);
value = JsonValue::fromString(message, i);
r->add(value);
i += skip_whitespace(message, i);
switch(message[i]){
case ',':
i++;
break;
case ']':
i++;
return r;
break;
default:
throw PARSE_ERROR("expected ] or , found " + string(1, message[i]), i);
}
}
}
string JsonList::toString(){
string infos = "[";
int index = 0;
while (index < this->content.size()){
infos += this->content[index]->toString();
index++;
infos+=", ";
}
infos = infos.substr(0, infos.size() - 2) + "]";
return infos;
}
void JsonList::add(JsonValue * value){
content.push_back(value);
}
size_t JsonList::size(){
return content.size();
}
JsonValue * JsonList::operator[](const int &i){
return content.at(i);
}
// Int
JsonInt::JsonInt(int val){
value = val;
}
JsonInt * JsonInt::fromString(string message, int &i){
JsonInt * r = new JsonInt();
bool end = false;
int start = i;
while(!end){
switch(message[i]){
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
i++;
break;
default:
end = true;
break;
}
}
r->setValue(message.substr(start, i));
return r;
}
string JsonInt::toString(){
return (string) *this;
}
int JsonInt::getValue(){
return value;
}
void JsonInt::setValue(int val){
value = val;
}
void JsonInt::setValue(string val){
value = stoi(val);
}
JsonInt::operator string() const{
return to_string(value);
}
JsonInt::operator int() const{
return value;
}
// Null
string JsonNull::toString(){
return "null";
}
JsonNull * JsonNull::fromString(string message, int &i){
if(message.substr(0,4) != "null"){
throw PARSE_ERROR("expected null, got '" + message.substr(0,4) + "'", i);
}
i += 4;
return new JsonNull();
}
bool JsonNull::operator ==(const int * i){
return i == 0;
}
// Bool
JsonBool::JsonBool(bool val){
value = val;
}
JsonBool * JsonBool::fromString(string message, int &i){
JsonBool * r = NULL;
if(message[0] == 't'){
if(message.substr(0,4) != "true"){
throw PARSE_ERROR("expected true, got '" + message.substr(0,4) + "'", i);
}
r = new JsonBool(true);
i += 4;
}
else {
if(message.substr(0,5) != "false"){
throw PARSE_ERROR("expected false, got '" + message.substr(0,5) + "'", i);
}
r = new JsonBool(false);
i += 5;
}
return r;
}
string JsonBool::toString(){
if(value){
return "true";
}
else {
return "false";
}
}
bool JsonBool::operator ==(const bool i){
return value == i;
}
JsonBool::operator bool() const{
return value;
}
<|endoftext|>
|
<commit_before><commit_msg>removed unused variables<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// See the corresponding header file for description of the functions in this
// file.
#include "chrome/installer/util/install_util.h"
#include <shellapi.h>
#include <shlobj.h>
#include <algorithm>
#include "base/file_util.h"
#include "base/logging.h"
#include "base/registry.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/work_item_list.h"
bool InstallUtil::ExecuteExeAsAdmin(const std::wstring& exe,
const std::wstring& params,
DWORD* exit_code) {
SHELLEXECUTEINFO info = {0};
info.cbSize = sizeof(SHELLEXECUTEINFO);
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.lpVerb = L"runas";
info.lpFile = exe.c_str();
info.lpParameters = params.c_str();
info.nShow = SW_SHOW;
if (::ShellExecuteEx(&info) == FALSE)
return false;
::WaitForSingleObject(info.hProcess, INFINITE);
DWORD ret_val = 0;
if (!::GetExitCodeProcess(info.hProcess, &ret_val))
return false;
if (exit_code)
*exit_code = ret_val;
return true;
}
std::wstring InstallUtil::GetChromeUninstallCmd(bool system_install) {
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
RegKey key(root, dist->GetUninstallRegPath().c_str());
std::wstring uninstall_cmd;
key.ReadValue(installer_util::kUninstallStringField, &uninstall_cmd);
return uninstall_cmd;
}
installer::Version* InstallUtil::GetChromeVersion(bool system_install) {
RegKey key;
std::wstring version_str;
HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
if (!key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_READ) ||
!key.ReadValue(google_update::kRegVersionField, &version_str)) {
LOG(INFO) << "No existing Chrome install found.";
key.Close();
return NULL;
}
key.Close();
LOG(INFO) << "Existing Chrome version found " << version_str;
return installer::Version::GetVersionFromString(version_str);
}
bool InstallUtil::IsOSSupported() {
int major, minor;
win_util::WinVersion version = win_util::GetWinVersion();
win_util::GetServicePackLevel(&major, &minor);
// We do not support Win2K or older, or XP without service pack 1.
LOG(INFO) << "Windows Version: " << version
<< ", Service Pack: " << major << "." << minor;
if ((version > win_util::WINVERSION_XP) ||
(version == win_util::WINVERSION_XP && major >= 1)) {
return true;
}
return false;
}
void InstallUtil::WriteInstallerResult(bool system_install,
installer_util::InstallStatus status,
int string_resource_id,
const std::wstring* const launch_cmd) {
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
std::wstring key = dist->GetStateKey();
int installer_result = (dist->GetInstallReturnCode(status) == 0) ? 0 : 1;
scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList());
install_list->AddCreateRegKeyWorkItem(root, key);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerResult",
installer_result, true);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerError",
status, true);
if (string_resource_id != 0) {
std::wstring msg = installer_util::GetLocalizedString(string_resource_id);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerResultUIString",
msg, true);
}
if (launch_cmd != NULL) {
install_list->AddSetRegValueWorkItem(root, key,
L"InstallerSuccessLaunchCmdLine",
*launch_cmd, true);
}
if (!install_list->Do())
LOG(ERROR) << "Failed to record installer error information in registry.";
}
bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path) {
wchar_t program_files_path[MAX_PATH] = {0};
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL,
SHGFP_TYPE_CURRENT, program_files_path))) {
return !StartsWith(exe_path, program_files_path, false);
} else {
NOTREACHED();
}
return true;
}
bool InstallUtil::BuildDLLRegistrationList(const std::wstring& install_path,
const wchar_t** const dll_names,
int dll_names_count,
bool do_register,
WorkItemList* registration_list) {
DCHECK(NULL != registration_list);
bool success = true;
for (int i = 0; i < dll_names_count; i++) {
std::wstring dll_file_path(install_path);
file_util::AppendToPath(&dll_file_path, dll_names[i]);
success = registration_list->AddSelfRegWorkItem(dll_file_path,
do_register) && success;
}
return (dll_names_count > 0) && success;
}
<commit_msg>Min XP Service Pack required is two not one.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// See the corresponding header file for description of the functions in this
// file.
#include "chrome/installer/util/install_util.h"
#include <shellapi.h>
#include <shlobj.h>
#include <algorithm>
#include "base/file_util.h"
#include "base/logging.h"
#include "base/registry.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/work_item_list.h"
bool InstallUtil::ExecuteExeAsAdmin(const std::wstring& exe,
const std::wstring& params,
DWORD* exit_code) {
SHELLEXECUTEINFO info = {0};
info.cbSize = sizeof(SHELLEXECUTEINFO);
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.lpVerb = L"runas";
info.lpFile = exe.c_str();
info.lpParameters = params.c_str();
info.nShow = SW_SHOW;
if (::ShellExecuteEx(&info) == FALSE)
return false;
::WaitForSingleObject(info.hProcess, INFINITE);
DWORD ret_val = 0;
if (!::GetExitCodeProcess(info.hProcess, &ret_val))
return false;
if (exit_code)
*exit_code = ret_val;
return true;
}
std::wstring InstallUtil::GetChromeUninstallCmd(bool system_install) {
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
RegKey key(root, dist->GetUninstallRegPath().c_str());
std::wstring uninstall_cmd;
key.ReadValue(installer_util::kUninstallStringField, &uninstall_cmd);
return uninstall_cmd;
}
installer::Version* InstallUtil::GetChromeVersion(bool system_install) {
RegKey key;
std::wstring version_str;
HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
if (!key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_READ) ||
!key.ReadValue(google_update::kRegVersionField, &version_str)) {
LOG(INFO) << "No existing Chrome install found.";
key.Close();
return NULL;
}
key.Close();
LOG(INFO) << "Existing Chrome version found " << version_str;
return installer::Version::GetVersionFromString(version_str);
}
bool InstallUtil::IsOSSupported() {
int major, minor;
win_util::WinVersion version = win_util::GetWinVersion();
win_util::GetServicePackLevel(&major, &minor);
// We do not support Win2K or older, or XP without service pack 2.
LOG(INFO) << "Windows Version: " << version
<< ", Service Pack: " << major << "." << minor;
if ((version > win_util::WINVERSION_XP) ||
(version == win_util::WINVERSION_XP && major >= 2)) {
return true;
}
return false;
}
void InstallUtil::WriteInstallerResult(bool system_install,
installer_util::InstallStatus status,
int string_resource_id,
const std::wstring* const launch_cmd) {
HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
std::wstring key = dist->GetStateKey();
int installer_result = (dist->GetInstallReturnCode(status) == 0) ? 0 : 1;
scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList());
install_list->AddCreateRegKeyWorkItem(root, key);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerResult",
installer_result, true);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerError",
status, true);
if (string_resource_id != 0) {
std::wstring msg = installer_util::GetLocalizedString(string_resource_id);
install_list->AddSetRegValueWorkItem(root, key, L"InstallerResultUIString",
msg, true);
}
if (launch_cmd != NULL) {
install_list->AddSetRegValueWorkItem(root, key,
L"InstallerSuccessLaunchCmdLine",
*launch_cmd, true);
}
if (!install_list->Do())
LOG(ERROR) << "Failed to record installer error information in registry.";
}
bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path) {
wchar_t program_files_path[MAX_PATH] = {0};
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL,
SHGFP_TYPE_CURRENT, program_files_path))) {
return !StartsWith(exe_path, program_files_path, false);
} else {
NOTREACHED();
}
return true;
}
bool InstallUtil::BuildDLLRegistrationList(const std::wstring& install_path,
const wchar_t** const dll_names,
int dll_names_count,
bool do_register,
WorkItemList* registration_list) {
DCHECK(NULL != registration_list);
bool success = true;
for (int i = 0; i < dll_names_count; i++) {
std::wstring dll_file_path(install_path);
file_util::AppendToPath(&dll_file_path, dll_names[i]);
success = registration_list->AddSelfRegWorkItem(dll_file_path,
do_register) && success;
}
return (dll_names_count > 0) && success;
}
<|endoftext|>
|
<commit_before>/*-
* Copyright (c) 2009, Ascent Group.
* 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 Ascent Group 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 <common/Database.h>
#include <psql/Schema.h>
#include <psql/Table.h>
#include <psql/Tools.h>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QVariant>
#include <QtDebug>
namespace DbObjects
{
namespace Psql
{
/*!
* Constructor
*
* \param[in] ipName - Name of the given table
* \param[in] ipSchema - Handle to schema containing this view
*/
Table::Table(QString ipName, const DbSchemaPtr &ipSchema)
:DbTable(ipName, ipSchema)
{
// load column definitions
// loadData();
}
/*!
* Destructor
*/
Table::~Table()
{
}
/*!
* Load column definitions data
*
* \return true If data has been successfully loaded
* \return false Otherwise
*/
bool
Table::loadData()
{
// int *p = 0;
// *p = 7;
if (mIsLoaded) {
return true;
}
QSqlDatabase db = QSqlDatabase::database("mainConnect");
QSqlQuery query(db);
QString qstr;
/*! \todo Before creating a query we need to find out postgres version;
* Bersion check can help support different Postgres versions,
* especcialy when the system catalogs change in newer versions
*/
Tools::Version version = Tools::version();
/*! \todo version check */
/*! \todo do version specific actions */
// create query
qstr = QString("SELECT "
"pga.attname, "
"pg_catalog.format_type(pga.atttypid, pga.atttypmod), "
"pga.attnotnull "
"FROM "
"pg_catalog.pg_attribute pga "
"WHERE "
"pga.attnum > 0 "
"AND NOT pga.attisdropped "
"AND pga.attrelid = ("
"SELECT pgc.oid FROM pg_catalog.pg_class pgc "
"LEFT JOIN pg_catalog.pg_namespace pgn ON pgn.oid = pgc.relnamespace "
"WHERE pgc.relname = '%1' and pgn.nspname = '%2'); ")
// "AND pg_catalog.pg_table_is_visible(pgc.oid));")
.arg(mName)
.arg(mSchema->name());
#ifdef DEBUG_QUERY
qDebug() << "Psql::Table::loadData> " << qstr;
#endif
// if query execution failed
if (!query.exec(qstr)) {
qDebug() << query.lastError().text();
return false;
}
// if query result is empty
if (!query.first()) {
return false;
}
// for each retrieved row
do {
/* temporary debug output */
#if DEBUG_TRACE
qDebug() << query.value(0).toString();
qDebug() << query.value(1).toString();
qDebug() << query.value(2).toString();
#endif
// create column definition
struct ColumnDefinition cDef;
// populate column definition
cDef.name = query.value(0).toString();
cDef.type = query.value(1).toString();
cDef.isNullable = !query.value(2).toBool();
cDef.isPrimaryKey = checkPrimaryKey(cDef.name);
cDef.isForeignKey = checkForeignKey(cDef.name, cDef.foreignSchemaName, cDef.foreignTableName, cDef.foreignFieldNames);
cDef.isUnique = checkUnique(cDef.name);
/* temporary debug output */
#if DEBUG_TRACE
qDebug() << "NAME: " << cDef.name;
qDebug() << "isPrimaryKey: " << cDef.isPrimaryKey;
qDebug() << "isForeignKey: " << cDef.isForeignKey;
qDebug() << "isUnique: " << cDef.isUnique;
qDebug() << "FKEY_SCHEMA: " << cDef.foreignSchemaName;
qDebug() << "FKEY_TABLE: " << cDef.foreignTableName;
#endif
// add column definition
mColumnDefs.push_back(cDef);
} while (query.next());
// clear result from previous query
query.clear();
// try to find parents if they exist
qstr = QString("SELECT "
// "childns.nspname AS child_schema, "
// "child.relname AS child_name, "
"parentns.nspname AS parent_schema, "
"parent.relname AS parent_name "
"FROM "
"pg_catalog.pg_inherits i, "
"pg_catalog.pg_class child, "
"pg_catalog.pg_class parent, "
"pg_catalog.pg_namespace childns, "
"pg_catalog.pg_namespace parentns "
"WHERE "
"i.inhrelid = child.oid AND "
"i.inhparent = parent.oid AND "
"childns.oid = child.relnamespace AND "
"parentns.oid = parent.relnamespace AND "
"childns.nspname = '%1' AND "
"child.relname = '%2';")
.arg(mSchema.name())
.arg(mName);
#ifdef DEBUG_QUERY
qDebug() << "Psql::Table::loadData> " << qstr;
#endif
// if query execution failed
if (!query.exec(qstr)) {
qDebug() << query.lastError().text();
return false;
}
// if query result is empty
if (query.first()) {
do {
DbSchemaPtr schema = Common::Database::instance()->findSchema(query.value(0).toString());
// devtime assert
Q_ASSERT(0 != schema.get());
DbTablePtr table = schema->findTable(query.value(1).toString());
// devtime assert
Q_ASSERT(0 != table.get());
// store handle to parent table
mParentTables.push_back(table);
qDebug() << "Psql::Table::loadData> Parent table: " << table.name();
} while (query.next());
}
return DbTable::loadData();
}
/*!
* Checks if column is a primary key for the given table
*
* \param[in] ipColumnName - Name of the column
*
* \return true If the column is primary key
* \return false Otherwise
*/
bool
Table::checkPrimaryKey(const QString &ipColumnName) const
{
QSqlDatabase db = QSqlDatabase::database("mainConnect");
QSqlQuery query(db);
// create query
QString qstr = QString("SELECT "
"pgc.relname, "
"pga.attname "
"FROM "
"pg_class pgc, "
"pg_attribute pga, "
"pg_index pgi, "
"pg_namespace pgn "
"WHERE "
"pgc.oid = pga.attrelid "
"AND pgc.oid = pgi.indrelid "
"AND pgi.indkey[0] = pga.attnum "
"AND pgi.indisprimary = 't' "
"AND pgn.oid = pgc.relnamespace "
"AND pgn.nspname = '%1' "
"AND pgc.relname = '%2' "
"AND pga.attname = '%3';")
.arg(mSchema->name())
.arg(mName)
.arg(ipColumnName);
#ifdef DEBUG_QUERY
qDebug() << "Psql::Table::checkPrimaryKey> " << qstr;
#endif
// if query execution failed
if (!query.exec(qstr)) {
qDebug() << query.lastError().text();
return false;
}
// primary constraint definition found
return query.first();
}
/*!
* Checks if ipColumnName is a foreign key for ipTableName
*
* \param[in] ipColumnName - Name of the column
* \param[out] opForeignSchemaName - Name of the schema that contains the reference table
* \param[out] opForeignTableName - Name of the table references by this column
* \param[out] opForeignFieldsNames - Names of fields references by this column
*
* \return true If the column is a foreign key
* \return false Otherwise
*/
bool
Table::checkForeignKey(const QString &ipColumnName,
QString &opForeignSchemaName,
QString &opForeignTableName,
QStringList &opForeignFieldsNames) const
{
QSqlDatabase db = QSqlDatabase::database("mainConnect");
QSqlQuery query(db);
// create query
QString qstr = QString("SELECT "
"p1.relname, "
"a1.attname, "
"pgn2.nspname AS foreign_schema, "
"p2.relname AS reltable, "
"a2.attname AS ref_field "
"FROM "
"pg_constraint c, "
"pg_class p1, "
"pg_class p2, "
"pg_attribute a1, "
"pg_attribute a2, "
"pg_namespace pgn1, "
"pg_namespace pgn2 "
"WHERE "
"c.contype = 'f' "
"AND c.confrelid > 0 "
"AND c.conrelid = p1.oid "
"AND c.confrelid = p2.oid "
"AND c.conrelid = a1.attrelid "
"AND a1.attnum = ANY (c.conkey) "
"AND c.confrelid = a2.attrelid "
"AND a2.attnum = ANY (c.confkey) "
"AND p2.relnamespace = pgn2.oid "
"AND pgn1.oid = p1.relnamespace "
"AND pgn1.nspname = '%1' "
"AND p1.relname = '%2' "
"AND a1.attname = '%3';")
.arg(mSchema->name())
.arg(mName)
.arg(ipColumnName);
#ifdef DEBUG_QUERY
qDebug() << "Psql::Table::checkForeignKey> " << qstr;
#endif
// if query execution failed
if (!query.exec(qstr)) {
qDebug() << query.lastError().text();
return false;
}
bool flag = false;
qint32 colId;
// if query result is empty
if (!query.first()) {
return flag;
}
// if we are here then the result is not empty
flag = true;
// this needs to be don only once for all fields
colId = query.record().indexOf("reltable");
opForeignTableName = query.value(colId).toString();
colId = query.record().indexOf("foreign_schema");
opForeignSchemaName = query.value(colId).toString();
// fields themselves
do {
colId = query.record().indexOf("ref_field");
opForeignFieldsNames.push_back(query.value(colId).toString());
} while (query.next());
// foreign key constraint definition found
return flag;
}
/*!
* Checks if ipColumnName is unique for ipTableName
*
* \param[in] ipColumnName - Name of the column
*
* \return true If the column has unique constraint
* \return false Otherwise
*/
bool
Table::checkUnique(const QString &ipColumnName) const
{
QSqlDatabase db = QSqlDatabase::database("mainConnect");
QSqlQuery query(db);
// create query
QString qstr = QString("SELECT "
"pgc.relname, "
"pga.attname, "
"pgc.relnamespace "
"FROM "
"pg_constraint constr, "
"pg_class pgc, "
"pg_attribute pga, "
"pg_namespace pgn "
"WHERE "
"pga.attnum = ANY (constr.conkey) "
"AND constr.contype = 'u' "
"AND constr.conrelid = pgc.oid "
"AND constr.conrelid = pga.attrelid "
"AND pgn.oid = pgc.relnamespace "
"AND pgn.nspname = '%1' "
"AND pgc.relname = '%2' "
"AND pga.attname = '%3';")
.arg(mSchema->name())
.arg(mName)
.arg(ipColumnName);
#if DEBUG_QUERY
qDebug() << "Psql::Table::checkUnique> " << qstr;
#endif
// if query execution failed
if (!query.exec(qstr)) {
qDebug() << query.lastError().text();
return false;
}
// unique constraint definition found
return query.first();
}
} // namespace Psql
} // namespace DbObjects
<commit_msg>* Merged 'lyuts_feature_table_inheritance' branch. Added ordering by inheritance sequence number.<commit_after>/*-
* Copyright (c) 2009, Ascent Group.
* 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 Ascent Group 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 <common/Database.h>
#include <psql/Schema.h>
#include <psql/Table.h>
#include <psql/Tools.h>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QVariant>
#include <QtDebug>
namespace DbObjects
{
namespace Psql
{
/*!
* Constructor
*
* \param[in] ipName - Name of the given table
* \param[in] ipSchema - Handle to schema containing this view
*/
Table::Table(QString ipName, const DbSchemaPtr &ipSchema)
:DbTable(ipName, ipSchema)
{
// load column definitions
// loadData();
}
/*!
* Destructor
*/
Table::~Table()
{
}
/*!
* Load column definitions data
*
* \return true If data has been successfully loaded
* \return false Otherwise
*/
bool
Table::loadData()
{
// int *p = 0;
// *p = 7;
if (mIsLoaded) {
return true;
}
QSqlDatabase db = QSqlDatabase::database("mainConnect");
QSqlQuery query(db);
QString qstr;
/*! \todo Before creating a query we need to find out postgres version;
* Bersion check can help support different Postgres versions,
* especcialy when the system catalogs change in newer versions
*/
Tools::Version version = Tools::version();
/*! \todo version check */
/*! \todo do version specific actions */
// create query
qstr = QString("SELECT "
"pga.attname, "
"pg_catalog.format_type(pga.atttypid, pga.atttypmod), "
"pga.attnotnull "
"FROM "
"pg_catalog.pg_attribute pga "
"WHERE "
"pga.attnum > 0 "
"AND NOT pga.attisdropped "
"AND pga.attrelid = ("
"SELECT pgc.oid FROM pg_catalog.pg_class pgc "
"LEFT JOIN pg_catalog.pg_namespace pgn ON pgn.oid = pgc.relnamespace "
"WHERE pgc.relname = '%1' and pgn.nspname = '%2'); ")
// "AND pg_catalog.pg_table_is_visible(pgc.oid));")
.arg(mName)
.arg(mSchema->name());
#ifdef DEBUG_QUERY
qDebug() << "Psql::Table::loadData> " << qstr;
#endif
// if query execution failed
if (!query.exec(qstr)) {
qDebug() << query.lastError().text();
return false;
}
// if query result is empty
if (!query.first()) {
return false;
}
// for each retrieved row
do {
/* temporary debug output */
#if DEBUG_TRACE
qDebug() << query.value(0).toString();
qDebug() << query.value(1).toString();
qDebug() << query.value(2).toString();
#endif
// create column definition
struct ColumnDefinition cDef;
// populate column definition
cDef.name = query.value(0).toString();
cDef.type = query.value(1).toString();
cDef.isNullable = !query.value(2).toBool();
cDef.isPrimaryKey = checkPrimaryKey(cDef.name);
cDef.isForeignKey = checkForeignKey(cDef.name, cDef.foreignSchemaName, cDef.foreignTableName, cDef.foreignFieldNames);
cDef.isUnique = checkUnique(cDef.name);
/* temporary debug output */
#if DEBUG_TRACE
qDebug() << "NAME: " << cDef.name;
qDebug() << "isPrimaryKey: " << cDef.isPrimaryKey;
qDebug() << "isForeignKey: " << cDef.isForeignKey;
qDebug() << "isUnique: " << cDef.isUnique;
qDebug() << "FKEY_SCHEMA: " << cDef.foreignSchemaName;
qDebug() << "FKEY_TABLE: " << cDef.foreignTableName;
#endif
// add column definition
mColumnDefs.push_back(cDef);
} while (query.next());
// clear result from previous query
query.clear();
// try to find parents if they exist
qstr = QString("SELECT "
// "childns.nspname AS child_schema, "
// "child.relname AS child_name, "
"parentns.nspname AS parent_schema, "
"parent.relname AS parent_name "
"FROM "
"pg_catalog.pg_inherits i, "
"pg_catalog.pg_class child, "
"pg_catalog.pg_class parent, "
"pg_catalog.pg_namespace childns, "
"pg_catalog.pg_namespace parentns "
"WHERE "
"i.inhrelid = child.oid AND "
"i.inhparent = parent.oid AND "
"childns.oid = child.relnamespace AND "
"parentns.oid = parent.relnamespace AND "
"childns.nspname = '%1' AND "
"child.relname = '%2' "
"ORDER BY i.inhseqno;")
.arg(mSchema.name())
.arg(mName);
#ifdef DEBUG_QUERY
qDebug() << "Psql::Table::loadData> " << qstr;
#endif
// if query execution failed
if (!query.exec(qstr)) {
qDebug() << query.lastError().text();
return false;
}
// if query result is empty
if (query.first()) {
do {
DbSchemaPtr schema = Common::Database::instance()->findSchema(query.value(0).toString());
// devtime assert
Q_ASSERT(0 != schema.get());
DbTablePtr table = schema->findTable(query.value(1).toString());
// devtime assert
Q_ASSERT(0 != table.get());
// store handle to parent table
mParentTables.push_back(table);
qDebug() << "Psql::Table::loadData> Parent table: " << table.name();
} while (query.next());
}
return DbTable::loadData();
}
/*!
* Checks if column is a primary key for the given table
*
* \param[in] ipColumnName - Name of the column
*
* \return true If the column is primary key
* \return false Otherwise
*/
bool
Table::checkPrimaryKey(const QString &ipColumnName) const
{
QSqlDatabase db = QSqlDatabase::database("mainConnect");
QSqlQuery query(db);
// create query
QString qstr = QString("SELECT "
"pgc.relname, "
"pga.attname "
"FROM "
"pg_class pgc, "
"pg_attribute pga, "
"pg_index pgi, "
"pg_namespace pgn "
"WHERE "
"pgc.oid = pga.attrelid "
"AND pgc.oid = pgi.indrelid "
"AND pgi.indkey[0] = pga.attnum "
"AND pgi.indisprimary = 't' "
"AND pgn.oid = pgc.relnamespace "
"AND pgn.nspname = '%1' "
"AND pgc.relname = '%2' "
"AND pga.attname = '%3';")
.arg(mSchema->name())
.arg(mName)
.arg(ipColumnName);
#ifdef DEBUG_QUERY
qDebug() << "Psql::Table::checkPrimaryKey> " << qstr;
#endif
// if query execution failed
if (!query.exec(qstr)) {
qDebug() << query.lastError().text();
return false;
}
// primary constraint definition found
return query.first();
}
/*!
* Checks if ipColumnName is a foreign key for ipTableName
*
* \param[in] ipColumnName - Name of the column
* \param[out] opForeignSchemaName - Name of the schema that contains the reference table
* \param[out] opForeignTableName - Name of the table references by this column
* \param[out] opForeignFieldsNames - Names of fields references by this column
*
* \return true If the column is a foreign key
* \return false Otherwise
*/
bool
Table::checkForeignKey(const QString &ipColumnName,
QString &opForeignSchemaName,
QString &opForeignTableName,
QStringList &opForeignFieldsNames) const
{
QSqlDatabase db = QSqlDatabase::database("mainConnect");
QSqlQuery query(db);
// create query
QString qstr = QString("SELECT "
"p1.relname, "
"a1.attname, "
"pgn2.nspname AS foreign_schema, "
"p2.relname AS reltable, "
"a2.attname AS ref_field "
"FROM "
"pg_constraint c, "
"pg_class p1, "
"pg_class p2, "
"pg_attribute a1, "
"pg_attribute a2, "
"pg_namespace pgn1, "
"pg_namespace pgn2 "
"WHERE "
"c.contype = 'f' "
"AND c.confrelid > 0 "
"AND c.conrelid = p1.oid "
"AND c.confrelid = p2.oid "
"AND c.conrelid = a1.attrelid "
"AND a1.attnum = ANY (c.conkey) "
"AND c.confrelid = a2.attrelid "
"AND a2.attnum = ANY (c.confkey) "
"AND p2.relnamespace = pgn2.oid "
"AND pgn1.oid = p1.relnamespace "
"AND pgn1.nspname = '%1' "
"AND p1.relname = '%2' "
"AND a1.attname = '%3';")
.arg(mSchema->name())
.arg(mName)
.arg(ipColumnName);
#ifdef DEBUG_QUERY
qDebug() << "Psql::Table::checkForeignKey> " << qstr;
#endif
// if query execution failed
if (!query.exec(qstr)) {
qDebug() << query.lastError().text();
return false;
}
bool flag = false;
qint32 colId;
// if query result is empty
if (!query.first()) {
return flag;
}
// if we are here then the result is not empty
flag = true;
// this needs to be don only once for all fields
colId = query.record().indexOf("reltable");
opForeignTableName = query.value(colId).toString();
colId = query.record().indexOf("foreign_schema");
opForeignSchemaName = query.value(colId).toString();
// fields themselves
do {
colId = query.record().indexOf("ref_field");
opForeignFieldsNames.push_back(query.value(colId).toString());
} while (query.next());
// foreign key constraint definition found
return flag;
}
/*!
* Checks if ipColumnName is unique for ipTableName
*
* \param[in] ipColumnName - Name of the column
*
* \return true If the column has unique constraint
* \return false Otherwise
*/
bool
Table::checkUnique(const QString &ipColumnName) const
{
QSqlDatabase db = QSqlDatabase::database("mainConnect");
QSqlQuery query(db);
// create query
QString qstr = QString("SELECT "
"pgc.relname, "
"pga.attname, "
"pgc.relnamespace "
"FROM "
"pg_constraint constr, "
"pg_class pgc, "
"pg_attribute pga, "
"pg_namespace pgn "
"WHERE "
"pga.attnum = ANY (constr.conkey) "
"AND constr.contype = 'u' "
"AND constr.conrelid = pgc.oid "
"AND constr.conrelid = pga.attrelid "
"AND pgn.oid = pgc.relnamespace "
"AND pgn.nspname = '%1' "
"AND pgc.relname = '%2' "
"AND pga.attname = '%3';")
.arg(mSchema->name())
.arg(mName)
.arg(ipColumnName);
#if DEBUG_QUERY
qDebug() << "Psql::Table::checkUnique> " << qstr;
#endif
// if query execution failed
if (!query.exec(qstr)) {
qDebug() << query.lastError().text();
return false;
}
// unique constraint definition found
return query.first();
}
} // namespace Psql
} // namespace DbObjects
<|endoftext|>
|
<commit_before>
/// *********************************************************************************
/// *********************************************************************************
/// EMSCRIPTEN (for javascript)
/// *********************************************************************************
/// *********************************************************************************
#ifdef EMSCRIPTEN
#include "CoolProp.h"
#include "AbstractState.h"
#include "Configuration.h"
#include "HumidAirProp.h"
#include "DataStructures.h"
#include "Backends/Helmholtz/MixtureParameters.h"
#include <emscripten/bind.h>
using namespace emscripten;
// Binding code
EMSCRIPTEN_BINDINGS(coolprop_bindings) {
function("Props1SI", &CoolProp::Props1SI);
function("PropsSI", &CoolProp::PropsSI);
function("get_global_param_string", &CoolProp::get_global_param_string);
}
// Binding code
EMSCRIPTEN_BINDINGS(humid_air_bindings) {
function("HAPropsSI", &HumidAir::HAPropsSI);
}
CoolProp::AbstractState * factory(const std::string &backend, const std::string &fluid_names)
{
return CoolProp::AbstractState::factory(backend, strsplit(fluid_names, '&'));
}
// Binding code
EMSCRIPTEN_BINDINGS(abstract_state_bindings) {
register_vector<double>("VectorDouble");
register_vector<std::string>("VectorString");
value_object<CoolProp::PhaseEnvelopeData>("CoolProp::PhaseEnvelopeData")
// Use X macros to auto-generate the variables;
// each will look something like: .field("T", &CoolProp::PhaseEnvelopeData::T);
#define X(name) .field(#name, &CoolProp::PhaseEnvelopeData::name)
PHASE_ENVELOPE_VECTORS
#undef X
;
function("factory", &factory, allow_raw_pointers());
class_<CoolProp::AbstractState>("AbstractState")
.function("gas_constant", &CoolProp::AbstractState::gas_constant)
.function("update", &CoolProp::AbstractState::update)
.function("set_mole_fractions", &CoolProp::AbstractState::set_mole_fractions_double)
.function("build_phase_envelope", &CoolProp::AbstractState::build_phase_envelope)
.function("get_phase_envelope_data", &CoolProp::AbstractState::get_phase_envelope_data);
}
#endif<commit_msg>Added a few things to the emscripten interface<commit_after>
/// *********************************************************************************
/// *********************************************************************************
/// EMSCRIPTEN (for javascript)
/// *********************************************************************************
/// *********************************************************************************
#ifdef EMSCRIPTEN
#include "CoolProp.h"
#include "AbstractState.h"
#include "Configuration.h"
#include "HumidAirProp.h"
#include "DataStructures.h"
#include "Backends/Helmholtz/MixtureParameters.h"
#include <emscripten/bind.h>
using namespace emscripten;
// Binding code
EMSCRIPTEN_BINDINGS(coolprop_bindings) {
function("Props1SI", &CoolProp::Props1SI);
function("PropsSI", &CoolProp::PropsSI);
function("get_global_param_string", &CoolProp::get_global_param_string);
enum_<CoolProp::input_pairs>("input_pairs")
.value("PT_INPUTS", CoolProp::PT_INPUTS)
;
}
// Binding code
EMSCRIPTEN_BINDINGS(humid_air_bindings) {
function("HAPropsSI", &HumidAir::HAPropsSI);
}
CoolProp::AbstractState * factory(const std::string &backend, const std::string &fluid_names)
{
return CoolProp::AbstractState::factory(backend, strsplit(fluid_names, '&'));
}
// Binding code
EMSCRIPTEN_BINDINGS(abstract_state_bindings) {
register_vector<double>("VectorDouble");
register_vector<std::string>("VectorString");
value_object<CoolProp::PhaseEnvelopeData>("CoolProp::PhaseEnvelopeData")
// Use X macros to auto-generate the variables;
// each will look something like: .field("T", &CoolProp::PhaseEnvelopeData::T);
#define X(name) .field(#name, &CoolProp::PhaseEnvelopeData::name)
PHASE_ENVELOPE_VECTORS
#undef X
;
function("factory", &factory, allow_raw_pointers());
class_<CoolProp::AbstractState>("AbstractState")
.function("gas_constant", &CoolProp::AbstractState::gas_constant)
.function("update", &CoolProp::AbstractState::update)
.function("p", &CoolProp::AbstractState::p)
.function("rhomass", &CoolProp::AbstractState::rhomass)
.function("viscosity", &CoolProp::AbstractState::viscosity)
.function("set_mole_fractions", &CoolProp::AbstractState::set_mole_fractions_double)
.function("build_phase_envelope", &CoolProp::AbstractState::build_phase_envelope)
.function("get_phase_envelope_data", &CoolProp::AbstractState::get_phase_envelope_data);
}
#endif<|endoftext|>
|
<commit_before>
/// *********************************************************************************
/// *********************************************************************************
/// EMSCRIPTEN (for javascript)
/// *********************************************************************************
/// *********************************************************************************
#ifdef EMSCRIPTEN
#include "CoolProp.h"
#include "AbstractState.h"
#include "Configuration.h"
#include "HumidAirProp.h"
#include "DataStructures.h"
#include "Backends/Helmholtz/MixtureParameters.h"
#include <emscripten/bind.h>
using namespace emscripten;
/// *********************************************************************************
/// *********************************************************************************
/// EMSCRIPTEN (for javascript)
/// *********************************************************************************
/// *********************************************************************************
#ifdef EMSCRIPTEN
#include <emscripten/bind.h>
using namespace emscripten;
// Binding code
EMSCRIPTEN_BINDINGS(coolprop_bindings) {
function("F2K", &F2K);
function("Props1SI", &CoolProp::Props1SI);
function("PropsSI", &CoolProp::PropsSI);
function("get_global_param_string", &CoolProp::get_global_param_string);
enum_<CoolProp::input_pairs>("input_pairs")
.value("PT_INPUTS", CoolProp::PT_INPUTS)
;
}
// Binding code
EMSCRIPTEN_BINDINGS(humid_air_bindings) {
function("HAPropsSI", &HumidAir::HAPropsSI);
}
CoolProp::AbstractState * factory(const std::string &backend, const std::string &fluid_names)
{
return CoolProp::AbstractState::factory(backend, strsplit(fluid_names, '&'));
}
// Binding code
EMSCRIPTEN_BINDINGS(abstract_state_bindings) {
register_vector<double>("VectorDouble");
register_vector<std::string>("VectorString");
value_object<CoolProp::PhaseEnvelopeData>("CoolProp::PhaseEnvelopeData")
// Use X macros to auto-generate the variables;
// each will look something like: .field("T", &CoolProp::PhaseEnvelopeData::T);
#define X(name) .field(#name, &CoolProp::PhaseEnvelopeData::name)
PHASE_ENVELOPE_VECTORS
#undef X
;
function("factory", &factory, allow_raw_pointers());
class_<CoolProp::AbstractState>("AbstractState")
.function("gas_constant", &CoolProp::AbstractState::gas_constant)
.function("update", &CoolProp::AbstractState::update)
.function("p", &CoolProp::AbstractState::p)
.function("rhomass", &CoolProp::AbstractState::rhomass)
.function("viscosity", &CoolProp::AbstractState::viscosity)
.function("set_mole_fractions", &CoolProp::AbstractState::set_mole_fractions_double)
.function("build_phase_envelope", &CoolProp::AbstractState::build_phase_envelope)
.function("get_phase_envelope_data", &CoolProp::AbstractState::get_phase_envelope_data);
}
#endif<commit_msg>Another attempt at emscripten relocation; see #1449<commit_after>
/// *********************************************************************************
/// *********************************************************************************
/// EMSCRIPTEN (for javascript)
/// *********************************************************************************
/// *********************************************************************************
#ifdef EMSCRIPTEN
#include "CoolProp.h"
#include "AbstractState.h"
#include "Configuration.h"
#include "HumidAirProp.h"
#include "DataStructures.h"
#include "Backends/Helmholtz/MixtureParameters.h"
#include "CoolPropLib.h"
/// *********************************************************************************
/// *********************************************************************************
/// EMSCRIPTEN (for javascript)
/// *********************************************************************************
/// *********************************************************************************
#include <emscripten/bind.h>
using namespace emscripten;
// Binding code
EMSCRIPTEN_BINDINGS(coolprop_bindings) {
function("F2K", &CoolProp::F2K);
function("Props1SI", &CoolProp::Props1SI);
function("PropsSI", &CoolProp::PropsSI);
function("get_global_param_string", &CoolProp::get_global_param_string);
enum_<CoolProp::input_pairs>("input_pairs")
.value("PT_INPUTS", CoolProp::PT_INPUTS)
;
}
// Binding code
EMSCRIPTEN_BINDINGS(humid_air_bindings) {
function("HAPropsSI", &HumidAir::HAPropsSI);
}
CoolProp::AbstractState * factory(const std::string &backend, const std::string &fluid_names)
{
return CoolProp::AbstractState::factory(backend, strsplit(fluid_names, '&'));
}
// Binding code
EMSCRIPTEN_BINDINGS(abstract_state_bindings) {
register_vector<double>("VectorDouble");
register_vector<std::string>("VectorString");
value_object<CoolProp::PhaseEnvelopeData>("CoolProp::PhaseEnvelopeData")
// Use X macros to auto-generate the variables;
// each will look something like: .field("T", &CoolProp::PhaseEnvelopeData::T);
#define X(name) .field(#name, &CoolProp::PhaseEnvelopeData::name)
PHASE_ENVELOPE_VECTORS
#undef X
;
function("factory", &factory, allow_raw_pointers());
class_<CoolProp::AbstractState>("AbstractState")
.function("gas_constant", &CoolProp::AbstractState::gas_constant)
.function("update", &CoolProp::AbstractState::update)
.function("p", &CoolProp::AbstractState::p)
.function("rhomass", &CoolProp::AbstractState::rhomass)
.function("viscosity", &CoolProp::AbstractState::viscosity)
.function("set_mole_fractions", &CoolProp::AbstractState::set_mole_fractions_double)
.function("build_phase_envelope", &CoolProp::AbstractState::build_phase_envelope)
.function("get_phase_envelope_data", &CoolProp::AbstractState::get_phase_envelope_data);
}
#endif<|endoftext|>
|
<commit_before>/*
===========================================================================
daemon gpl source code
copyright (c) 2013 unvanquished developers
this file is part of the daemon gpl source code (daemon source code).
daemon source code 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.
daemon source code 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 daemon source code. if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
#include "AudioPrivate.h"
namespace Audio {
// Structures to keep the state of entities we were given
struct entityData_t {
vec3_t position;
vec3_t velocity;
float occlusion;
};
static entityData_t entities[MAX_GENTITIES];
static int listenerEntity = -1;
// Keep Entitymitters in an array because there is at most one per entity.
static std::shared_ptr<Emitter> entityEmitters[MAX_GENTITIES];
// Position Emitters can be reused so we keep the list of all of them
// this is not very efficient but we cannot have more position emitters
// than sounds, that is about 128
static std::vector<std::shared_ptr<PositionEmitter>> posEmitters;
// There is a single LocalEmitter
static std::shared_ptr<Emitter> localEmitter;
static const vec3_t origin = {0.0f, 0.0f, 0.0f};
static Cvar::Modified<Cvar::Cvar<bool>> useReverb("sound.reverb", "should reverb effects be used", Cvar::ARCHIVE, true);
//TODO use optional once we have it
static bool removeReverb = false;
static bool addReverb = false;
static AL::EffectSlot* globalEffect = nullptr;
static bool initialized = false;
void InitEmitters() {
if (initialized) {
return;
}
// This is a temporrary effect to test reverb
AL::Effect effectParams;
effectParams.ApplyReverbPreset(AL::GetHangarEffectPreset());
globalEffect = new AL::EffectSlot();
globalEffect->SetEffect(effectParams);
AL::SetSpeedOfSound(SPEED_OF_SOUND);
AL::SetDopplerExaggerationFactor(1); //keep it small else we get a deadlock in OpenAL's mixer
localEmitter = std::make_shared<LocalEmitter>();
initialized = true;
}
void ShutdownEmitters() {
if (not initialized) {
return;
}
localEmitter = nullptr;
for (int i = 0; i < MAX_GENTITIES; i++) {
if (entityEmitters[i]) {
entityEmitters[i] = nullptr;
}
}
posEmitters.clear();
delete globalEffect;
globalEffect = nullptr;
initialized = false;
}
void UpdateEmitters() {
localEmitter->Update();
// Both PositionEmitters and EntityEmitters are ref-counted.
// If we hold the only reference to them then no sound is still using
// the Emitter that can be destroyed.
for (int i = 0; i < MAX_GENTITIES; i++) {
auto emitter = entityEmitters[i];
if (not emitter) {
continue;
}
emitter->Update();
// No sound is using this emitter, destroy it
if (emitter.unique()) {
entityEmitters[i] = nullptr;
}
}
for (auto it = posEmitters.begin(); it != posEmitters.end();){
(*it)->Update();
// No sound is using this emitter, destroy it
if ((*it).unique()) {
it = posEmitters.erase(it);
} else {
it ++;
}
}
addReverb = removeReverb = false;
bool use;
if (useReverb.GetModifiedValue(use)) {
if (use) {
addReverb = true;
} else {
removeReverb = true;
}
}
}
void UpdateListenerEntity(int entityNum, vec3_t orientation[3]) {
listenerEntity = entityNum;
AL::SetListenerPosition(entities[listenerEntity].position);
AL::SetListenerVelocity(entities[listenerEntity].velocity);
AL::SetListenerOrientation(orientation);
}
std::shared_ptr<Emitter> GetEmitterForEntity(int entityNum) {
if (not entityEmitters[entityNum]) {
entityEmitters[entityNum] = std::make_shared<EntityEmitter>(entityNum);
}
return entityEmitters[entityNum];
}
std::shared_ptr<Emitter> GetEmitterForPosition(const vec3_t position) {
for (auto emitter : posEmitters) {
if (Distance(emitter->GetPosition(), position) <= 1.0f) {
return emitter;
}
}
auto emitter = std::make_shared<PositionEmitter>(position);
posEmitters.push_back(emitter);
return emitter;
}
std::shared_ptr<Emitter> GetLocalEmitter() {
return localEmitter;
}
void UpdateRegisteredEntityPosition(int entityNum, const vec3_t position) {
VectorCopy(position, entities[entityNum].position);
}
void UpdateRegisteredEntityVelocity(int entityNum, const vec3_t velocity) {
VectorCopy(velocity, entities[entityNum].velocity);
}
void UpdateRegisteredEntityOcclusion(int entityNum, float ratio) {
entities[entityNum].occlusion = ratio;
}
// Utility functions for emitters
// TODO avoid more unnecessary al calls
void MakeLocal(AL::Source& source) {
source.SetRelative(true);
source.SetPosition(origin);
source.SetVelocity(origin);
source.DisableEffect(POSITIONAL_EFFECT_SLOT);
}
void Make3D(AL::Source& source, const vec3_t position, const vec3_t velocity, bool forceReverb = false) {
source.SetRelative(false);
source.SetPosition(position);
source.SetVelocity(velocity);
if ((forceReverb and useReverb.Get()) or addReverb) {
source.EnableEffect(POSITIONAL_EFFECT_SLOT, *globalEffect);
} else if ((forceReverb and not useReverb.Get()) or removeReverb) {
source.DisableEffect(POSITIONAL_EFFECT_SLOT);
}
}
// Implementation for Emitter
Emitter::Emitter() {
}
Emitter::~Emitter() {
}
void Emitter::SetupSound(Sound& sound) {
sound.GetSource().SetReferenceDistance(60.0f);
InternalSetupSound(sound);
UpdateSound(sound);
}
// Implementation of EntityEmitter
EntityEmitter::EntityEmitter(int entityNum): entityNum(entityNum) {
}
EntityEmitter::~EntityEmitter(){
}
void EntityEmitter::Update() {
// TODO
}
void EntityEmitter::UpdateSound(Sound& sound) {
AL::Source& source = sound.GetSource();
if (entityNum == listenerEntity) {
MakeLocal(source);
} else {
Make3D(source, entities[entityNum].position, entities[entityNum].velocity);
}
}
void EntityEmitter::InternalSetupSound(Sound& sound) {
AL::Source& source = sound.GetSource();
Make3D(source, entities[entityNum].position, entities[entityNum].velocity, true);
}
// Implementation of PositionEmitter
PositionEmitter::PositionEmitter(const vec3_t position){
VectorCopy(position, this->position);
}
PositionEmitter::~PositionEmitter() {
}
void PositionEmitter::Update() {
//TODO
}
void PositionEmitter::UpdateSound(Sound& sound) {
AL::Source& source = sound.GetSource();
Make3D(source, position, origin);
}
void PositionEmitter::InternalSetupSound(Sound& sound) {
AL::Source& source = sound.GetSource();
Make3D(source, position, origin, true);
}
const vec3_t& PositionEmitter::GetPosition() const {
return position;
}
// Implementation of LocalEmitter
LocalEmitter::LocalEmitter() {
}
LocalEmitter::~LocalEmitter() {
}
void LocalEmitter::Update() {
}
void LocalEmitter::UpdateSound(Sound&) {
}
void LocalEmitter::InternalSetupSound(Sound& sound) {
AL::Source& source = sound.GetSource();
MakeLocal(source);
}
}
<commit_msg>Audio: add sound.doppler to enable/disable doppler at runtime<commit_after>/*
===========================================================================
daemon gpl source code
copyright (c) 2013 unvanquished developers
this file is part of the daemon gpl source code (daemon source code).
daemon source code 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.
daemon source code 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 daemon source code. if not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/
#include "AudioPrivate.h"
namespace Audio {
// Structures to keep the state of entities we were given
struct entityData_t {
vec3_t position;
vec3_t velocity;
float occlusion;
};
static entityData_t entities[MAX_GENTITIES];
static int listenerEntity = -1;
// Keep Entitymitters in an array because there is at most one per entity.
static std::shared_ptr<Emitter> entityEmitters[MAX_GENTITIES];
// Position Emitters can be reused so we keep the list of all of them
// this is not very efficient but we cannot have more position emitters
// than sounds, that is about 128
static std::vector<std::shared_ptr<PositionEmitter>> posEmitters;
// There is a single LocalEmitter
static std::shared_ptr<Emitter> localEmitter;
static const vec3_t origin = {0.0f, 0.0f, 0.0f};
static Cvar::Cvar<bool> useDoppler("sound.doppler", "should the doppler effect be used", Cvar::ARCHIVE, true);
static Cvar::Modified<Cvar::Cvar<bool>> useReverb("sound.reverb", "should reverb effects be used", Cvar::ARCHIVE, true);
//TODO use optional once we have it
static bool removeReverb = false;
static bool addReverb = false;
static AL::EffectSlot* globalEffect = nullptr;
static bool initialized = false;
void UseDoppler(bool use) {
float factor = use ? 1.0f : 0.0f;
AL::SetDopplerExaggerationFactor(factor);
}
void InitEmitters() {
if (initialized) {
return;
}
// This is a temporrary effect to test reverb
AL::Effect effectParams;
effectParams.ApplyReverbPreset(AL::GetHangarEffectPreset());
globalEffect = new AL::EffectSlot();
globalEffect->SetEffect(effectParams);
AL::SetSpeedOfSound(SPEED_OF_SOUND);
UseDoppler(useDoppler.Get());
localEmitter = std::make_shared<LocalEmitter>();
initialized = true;
}
void ShutdownEmitters() {
if (not initialized) {
return;
}
localEmitter = nullptr;
for (int i = 0; i < MAX_GENTITIES; i++) {
if (entityEmitters[i]) {
entityEmitters[i] = nullptr;
}
}
posEmitters.clear();
delete globalEffect;
globalEffect = nullptr;
initialized = false;
}
void UpdateEmitters() {
localEmitter->Update();
// Both PositionEmitters and EntityEmitters are ref-counted.
// If we hold the only reference to them then no sound is still using
// the Emitter that can be destroyed.
for (int i = 0; i < MAX_GENTITIES; i++) {
auto emitter = entityEmitters[i];
if (not emitter) {
continue;
}
emitter->Update();
// No sound is using this emitter, destroy it
if (emitter.unique()) {
entityEmitters[i] = nullptr;
}
}
for (auto it = posEmitters.begin(); it != posEmitters.end();){
(*it)->Update();
// No sound is using this emitter, destroy it
if ((*it).unique()) {
it = posEmitters.erase(it);
} else {
it ++;
}
}
addReverb = removeReverb = false;
bool use;
if (useReverb.GetModifiedValue(use)) {
if (use) {
addReverb = true;
} else {
removeReverb = true;
}
}
UseDoppler(useDoppler.Get());
}
void UpdateListenerEntity(int entityNum, vec3_t orientation[3]) {
listenerEntity = entityNum;
AL::SetListenerPosition(entities[listenerEntity].position);
AL::SetListenerVelocity(entities[listenerEntity].velocity);
AL::SetListenerOrientation(orientation);
}
std::shared_ptr<Emitter> GetEmitterForEntity(int entityNum) {
if (not entityEmitters[entityNum]) {
entityEmitters[entityNum] = std::make_shared<EntityEmitter>(entityNum);
}
return entityEmitters[entityNum];
}
std::shared_ptr<Emitter> GetEmitterForPosition(const vec3_t position) {
for (auto emitter : posEmitters) {
if (Distance(emitter->GetPosition(), position) <= 1.0f) {
return emitter;
}
}
auto emitter = std::make_shared<PositionEmitter>(position);
posEmitters.push_back(emitter);
return emitter;
}
std::shared_ptr<Emitter> GetLocalEmitter() {
return localEmitter;
}
void UpdateRegisteredEntityPosition(int entityNum, const vec3_t position) {
VectorCopy(position, entities[entityNum].position);
}
void UpdateRegisteredEntityVelocity(int entityNum, const vec3_t velocity) {
VectorCopy(velocity, entities[entityNum].velocity);
}
void UpdateRegisteredEntityOcclusion(int entityNum, float ratio) {
entities[entityNum].occlusion = ratio;
}
// Utility functions for emitters
// TODO avoid more unnecessary al calls
void MakeLocal(AL::Source& source) {
source.SetRelative(true);
source.SetPosition(origin);
source.SetVelocity(origin);
source.DisableEffect(POSITIONAL_EFFECT_SLOT);
}
void Make3D(AL::Source& source, const vec3_t position, const vec3_t velocity, bool forceReverb = false) {
source.SetRelative(false);
source.SetPosition(position);
source.SetVelocity(velocity);
if ((forceReverb and useReverb.Get()) or addReverb) {
source.EnableEffect(POSITIONAL_EFFECT_SLOT, *globalEffect);
} else if ((forceReverb and not useReverb.Get()) or removeReverb) {
source.DisableEffect(POSITIONAL_EFFECT_SLOT);
}
}
// Implementation for Emitter
Emitter::Emitter() {
}
Emitter::~Emitter() {
}
void Emitter::SetupSound(Sound& sound) {
sound.GetSource().SetReferenceDistance(60.0f);
InternalSetupSound(sound);
UpdateSound(sound);
}
// Implementation of EntityEmitter
EntityEmitter::EntityEmitter(int entityNum): entityNum(entityNum) {
}
EntityEmitter::~EntityEmitter(){
}
void EntityEmitter::Update() {
// TODO
}
void EntityEmitter::UpdateSound(Sound& sound) {
AL::Source& source = sound.GetSource();
if (entityNum == listenerEntity) {
MakeLocal(source);
} else {
Make3D(source, entities[entityNum].position, entities[entityNum].velocity);
}
}
void EntityEmitter::InternalSetupSound(Sound& sound) {
AL::Source& source = sound.GetSource();
Make3D(source, entities[entityNum].position, entities[entityNum].velocity, true);
}
// Implementation of PositionEmitter
PositionEmitter::PositionEmitter(const vec3_t position){
VectorCopy(position, this->position);
}
PositionEmitter::~PositionEmitter() {
}
void PositionEmitter::Update() {
//TODO
}
void PositionEmitter::UpdateSound(Sound& sound) {
AL::Source& source = sound.GetSource();
Make3D(source, position, origin);
}
void PositionEmitter::InternalSetupSound(Sound& sound) {
AL::Source& source = sound.GetSource();
Make3D(source, position, origin, true);
}
const vec3_t& PositionEmitter::GetPosition() const {
return position;
}
// Implementation of LocalEmitter
LocalEmitter::LocalEmitter() {
}
LocalEmitter::~LocalEmitter() {
}
void LocalEmitter::Update() {
}
void LocalEmitter::UpdateSound(Sound&) {
}
void LocalEmitter::InternalSetupSound(Sound& sound) {
AL::Source& source = sound.GetSource();
MakeLocal(source);
}
}
<|endoftext|>
|
<commit_before>#include "FAST/Testing.hpp"
#include "AirwaySegmentation.hpp"
#include "FAST/Importers/ImageFileImporter.hpp"
#include "FAST/Algorithms/SurfaceExtraction/SurfaceExtraction.hpp"
#include "FAST/Algorithms/CenterlineExtraction/CenterlineExtraction.hpp"
#include "FAST/Visualization/MeshRenderer/MeshRenderer.hpp"
#include "FAST/Visualization/LineRenderer/LineRenderer.hpp"
#include "FAST/Visualization/SimpleWindow.hpp"
using namespace fast;
TEST_CASE("Airway segmentation", "[fast][AirwaySegmentation]") {
Reporter::setGlobalReportMethod(Reporter::COUT);
for(int i = 1; i < 26; ++i) {
ImageFileImporter::pointer importer = ImageFileImporter::New();
//importer->setFilename(std::string(FAST_TEST_DATA_DIR) + "CT-Thorax.mhd");
std::string nr = boost::lexical_cast<std::string>(i);
if(nr.size() == 1) {
nr = "0" + nr;
}
importer->setFilename("/home/smistad/Data/lunge_datasett/pasient" + nr + ".mhd");
AirwaySegmentation::pointer segmentation = AirwaySegmentation::New();
segmentation->setInputConnection(importer->getOutputPort());
CenterlineExtraction::pointer centerline = CenterlineExtraction::New();
centerline->setInputConnection(segmentation->getOutputPort());
centerline->update();
SurfaceExtraction::pointer extraction = SurfaceExtraction::New();
extraction->setInputConnection(segmentation->getOutputPort());
MeshRenderer::pointer renderer = MeshRenderer::New();
renderer->addInputConnection(extraction->getOutputPort());
LineRenderer::pointer lineRenderer = LineRenderer::New();
lineRenderer->addInputConnection(centerline->getOutputPort());
lineRenderer->setDefaultDrawOnTop(true);
SimpleWindow::pointer window = SimpleWindow::New();
window->addRenderer(renderer);
window->addRenderer(lineRenderer);
window->start();
}
}
<commit_msg>added airway test<commit_after>#include "FAST/Testing.hpp"
#include "AirwaySegmentation.hpp"
#include "FAST/Importers/ImageFileImporter.hpp"
#include "FAST/Algorithms/SurfaceExtraction/SurfaceExtraction.hpp"
#include "FAST/Algorithms/CenterlineExtraction/CenterlineExtraction.hpp"
#include "FAST/Visualization/MeshRenderer/MeshRenderer.hpp"
#include "FAST/Visualization/LineRenderer/LineRenderer.hpp"
#include "FAST/Visualization/SimpleWindow.hpp"
using namespace fast;
TEST_CASE("Airway segmentation ALL", "[fast][AirwaySegmentation]") {
Reporter::setGlobalReportMethod(Reporter::COUT);
for(int i = 1; i < 26; ++i) {
ImageFileImporter::pointer importer = ImageFileImporter::New();
//importer->setFilename(std::string(FAST_TEST_DATA_DIR) + "CT-Thorax.mhd");
std::string nr = boost::lexical_cast<std::string>(i);
if(nr.size() == 1) {
nr = "0" + nr;
}
importer->setFilename("/home/smistad/Data/lunge_datasett/pasient" + nr + ".mhd");
AirwaySegmentation::pointer segmentation = AirwaySegmentation::New();
segmentation->setInputConnection(importer->getOutputPort());
CenterlineExtraction::pointer centerline = CenterlineExtraction::New();
centerline->setInputConnection(segmentation->getOutputPort());
centerline->update();
SurfaceExtraction::pointer extraction = SurfaceExtraction::New();
extraction->setInputConnection(segmentation->getOutputPort());
MeshRenderer::pointer renderer = MeshRenderer::New();
renderer->addInputConnection(extraction->getOutputPort());
LineRenderer::pointer lineRenderer = LineRenderer::New();
lineRenderer->addInputConnection(centerline->getOutputPort());
lineRenderer->setDefaultDrawOnTop(true);
SimpleWindow::pointer window = SimpleWindow::New();
window->addRenderer(renderer);
window->addRenderer(lineRenderer);
window->start();
}
}
TEST_CASE("Airway segmentation", "[fast][AirwaySegmentation]") {
Reporter::setGlobalReportMethod(Reporter::COUT);
ImageFileImporter::pointer importer = ImageFileImporter::New();
importer->setFilename(std::string(FAST_TEST_DATA_DIR) + "CT-Thorax.mhd");
AirwaySegmentation::pointer segmentation = AirwaySegmentation::New();
segmentation->setInputConnection(importer->getOutputPort());
CenterlineExtraction::pointer centerline = CenterlineExtraction::New();
centerline->setInputConnection(segmentation->getOutputPort());
centerline->update();
SurfaceExtraction::pointer extraction = SurfaceExtraction::New();
extraction->setInputConnection(segmentation->getOutputPort());
MeshRenderer::pointer renderer = MeshRenderer::New();
renderer->addInputConnection(extraction->getOutputPort());
LineRenderer::pointer lineRenderer = LineRenderer::New();
lineRenderer->addInputConnection(centerline->getOutputPort());
lineRenderer->setDefaultDrawOnTop(true);
SimpleWindow::pointer window = SimpleWindow::New();
window->addRenderer(renderer);
window->addRenderer(lineRenderer);
window->start();
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "subcomponentmanager.h"
#include "model.h"
#include "metainfo.h"
#include <utils/hostosinfo.h>
#include <QDir>
#include <QMetaType>
#include <QUrl>
enum { debug = false };
QT_BEGIN_NAMESPACE
// Allow usage of QFileInfo in qSort
static bool operator<(const QFileInfo &file1, const QFileInfo &file2)
{
return file1.filePath() < file2.filePath();
}
QT_END_NAMESPACE
static inline QStringList importPaths() {
QStringList paths;
// env import paths
QByteArray envImportPath = qgetenv("QML_IMPORT_PATH");
if (!envImportPath.isEmpty()) {
paths = QString::fromLatin1(envImportPath)
.split(Utils::HostOsInfo::pathListSeparator(), QString::SkipEmptyParts);
}
return paths;
}
namespace QmlDesigner {
static const QString s_qmlFilePattern = QString(QLatin1String("*.qml"));
SubComponentManager::SubComponentManager(Model *model, QObject *parent)
: QObject(parent),
m_model(model)
{
connect(&m_watcher, SIGNAL(directoryChanged(QString)), this, SLOT(parseDirectory(QString)));
}
void SubComponentManager::addImport(int pos, const Import &import)
{
if (debug)
qDebug() << Q_FUNC_INFO << pos << import.file().toLatin1();
if (import.isFileImport()) {
QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
if (dirInfo.exists() && dirInfo.isDir()) {
const QString canonicalDirPath = dirInfo.canonicalFilePath();
m_watcher.addPath(canonicalDirPath);
//m_dirToQualifier.insertMulti(canonicalDirPath, import.qualifier()); ### todo: proper support for import as
}
} else {
QString url = import.url();
url.replace(QLatin1Char('.'), QLatin1Char('/'));
foreach (const QString &path, importPaths()) {
url = path + QLatin1Char('/') + url;
QFileInfo dirInfo = QFileInfo(url);
if (dirInfo.exists() && dirInfo.isDir()) {
const QString canonicalDirPath = dirInfo.canonicalFilePath();
m_watcher.addPath(canonicalDirPath);
//m_dirToQualifier.insertMulti(canonicalDirPath, import.qualifier()); ### todo: proper support for import as
}
}
// TODO: QDeclarativeDomImport::Library
}
m_imports.insert(pos, import);
}
void SubComponentManager::removeImport(int pos)
{
const Import import = m_imports.takeAt(pos);
if (import.isFileImport()) {
const QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
const QString canonicalDirPath = dirInfo.canonicalFilePath();
//m_dirToQualifier.remove(canonicalDirPath, import.qualifier()); ### todo: proper support for import as
if (!m_dirToQualifier.contains(canonicalDirPath))
m_watcher.removePath(canonicalDirPath);
// foreach (const QFileInfo &monitoredFile, watchedFiles(canonicalDirPath)) { ### todo: proper support for import as
// if (!m_dirToQualifier.contains(canonicalDirPath))
// unregisterQmlFile(monitoredFile, import.qualifier());
// }
} else {
// TODO: QDeclarativeDomImport::Library
}
}
void SubComponentManager::parseDirectories()
{
if (!m_filePath.isEmpty()) {
const QString file = m_filePath.toLocalFile();
QFileInfo dirInfo = QFileInfo(QFileInfo(file).path());
if (dirInfo.exists() && dirInfo.isDir())
parseDirectory(dirInfo.canonicalFilePath());
foreach (const QString subDir, QDir(QFileInfo(file).path()).entryList(QDir::Dirs | QDir::NoDot | QDir::NoDotDot)) {
parseDirectory(dirInfo.canonicalFilePath() + "/" + subDir, true, subDir);
}
}
foreach (const Import &import, m_imports) {
if (import.isFileImport()) {
QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
if (dirInfo.exists() && dirInfo.isDir()) {
parseDirectory(dirInfo.canonicalFilePath());
}
} else {
QString url = import.url();
foreach (const QString &path, importPaths()) {
url.replace(QLatin1Char('.'), QLatin1Char('/'));
url = path + QLatin1Char('/') + url;
QFileInfo dirInfo = QFileInfo(url);
if (dirInfo.exists() && dirInfo.isDir()) {
//### todo full qualified names QString nameSpace = import.uri();
parseDirectory(dirInfo.canonicalFilePath(), false);
}
}
}
}
}
void SubComponentManager::parseDirectory(const QString &canonicalDirPath, bool addToLibrary, const QString& qualification)
{
if (debug)
qDebug() << Q_FUNC_INFO << canonicalDirPath;
QDir dir(canonicalDirPath);
dir.setNameFilters(QStringList(s_qmlFilePattern));
dir.setFilter(QDir::Files | QDir::Readable | QDir::CaseSensitive);
QList<QFileInfo> monitoredList = watchedFiles(canonicalDirPath);
QList<QFileInfo> newList;
foreach (const QFileInfo &qmlFile, dir.entryInfoList()) {
if (QFileInfo(m_filePath.toLocalFile()) == qmlFile) {
// do not parse main file
continue;
}
if (!qmlFile.fileName().at(0).isUpper()) {
// QML sub components must be upper case
continue;
}
newList << qmlFile;
}
qSort(monitoredList);
qSort(newList);
if (debug)
qDebug() << "monitored list " << monitoredList.size() << "new list " << newList.size();
QList<QFileInfo>::const_iterator oldIter = monitoredList.constBegin();
QList<QFileInfo>::const_iterator newIter = newList.constBegin();
while (oldIter != monitoredList.constEnd() && newIter != newList.constEnd()) {
const QFileInfo oldFileInfo = *oldIter;
const QFileInfo newFileInfo = *newIter;
if (oldFileInfo == newFileInfo) {
++oldIter;
++newIter;
continue;
}
if (oldFileInfo < newFileInfo) {
foreach (const QString &qualifier, m_dirToQualifier.value(canonicalDirPath))
unregisterQmlFile(oldFileInfo, qualifier);
m_watcher.removePath(oldFileInfo.filePath());
++oldIter;
continue;
}
// oldFileInfo > newFileInfo
parseFile(newFileInfo.filePath(), addToLibrary, qualification);
++newIter;
}
while (oldIter != monitoredList.constEnd()) {
foreach (const QString &qualifier, m_dirToQualifier.value(canonicalDirPath))
unregisterQmlFile(*oldIter, qualifier);
++oldIter;
}
while (newIter != newList.constEnd()) {
parseFile(newIter->filePath(), addToLibrary, qualification);
if (debug)
qDebug() << "m_watcher.addPath(" << newIter->filePath() << ')';
++newIter;
}
}
void SubComponentManager::parseFile(const QString &canonicalFilePath, bool addToLibrary, const QString& qualification)
{
if (debug)
qDebug() << Q_FUNC_INFO << canonicalFilePath;
QFile file(canonicalFilePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return;
}
QString dir = QFileInfo(canonicalFilePath).path();
foreach (const QString &qualifier, m_dirToQualifier.values(dir)) {
registerQmlFile(canonicalFilePath, qualifier, addToLibrary);
}
registerQmlFile(canonicalFilePath, qualification, addToLibrary);
}
void SubComponentManager::parseFile(const QString &canonicalFilePath)
{
parseFile(canonicalFilePath, true, QString());
}
// dirInfo must already contain a canonical path
QList<QFileInfo> SubComponentManager::watchedFiles(const QString &canonicalDirPath)
{
QList<QFileInfo> files;
foreach (const QString &monitoredFile, m_watcher.files()) {
QFileInfo fileInfo(monitoredFile);
if (fileInfo.dir().absolutePath() == canonicalDirPath) {
files.append(fileInfo);
}
}
return files;
}
void SubComponentManager::unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier)
{
QString componentName = fileInfo.baseName();
if (!qualifier.isEmpty())
componentName = qualifier + '.' + componentName;
}
static inline bool isDepricatedQtType(const QString &typeName)
{
if (typeName.length() < 8)
return false;
return typeName.contains("Qt.");
}
void SubComponentManager::registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier,
bool addToLibrary)
{
if (!model())
return;
QString componentName = fileInfo.baseName();
if (debug)
qDebug() << "SubComponentManager" << __FUNCTION__ << componentName;
if (addToLibrary) {
// Add file components to the library
ItemLibraryEntry itemLibraryEntry;
itemLibraryEntry.setType(componentName, -1, -1);
itemLibraryEntry.setName(componentName);
itemLibraryEntry.setCategory("QML Components");
if (!qualifier.isEmpty()) {
itemLibraryEntry.setForceImport(true);
itemLibraryEntry.setRequiredImport(qualifier);
}
if (model()->metaInfo(componentName).isValid() && model()->metaInfo(componentName).isSubclassOf("QtQuick.Item", -1, -1) &&
!model()->metaInfo().itemLibraryInfo()->containsEntry(itemLibraryEntry)) {
model()->metaInfo().itemLibraryInfo()->addEntry(itemLibraryEntry);
}
}
}
Model *SubComponentManager::model() const
{
return m_model.data();
}
/*!
\class SubComponentManager
Detects & monitors (potential) component files in a list of directories, and registers
these in the metatype system.
*/
QStringList SubComponentManager::directories() const
{
return m_watcher.directories();
}
QStringList SubComponentManager::qmlFiles() const
{
return m_watcher.files();
}
void SubComponentManager::update(const QUrl &filePath, const QList<Import> &imports)
{
if (debug)
qDebug() << Q_FUNC_INFO << filePath << imports.size();
QFileInfo oldDir, newDir;
if (!m_filePath.isEmpty()) {
const QString file = m_filePath.toLocalFile();
oldDir = QFileInfo(QFileInfo(file).path());
}
if (!filePath.isEmpty()) {
const QString file = filePath.toLocalFile();
newDir = QFileInfo(QFileInfo(file).path());
}
m_filePath = filePath;
//
// (implicit) import of local directory
//
if (oldDir != newDir) {
if (!oldDir.filePath().isEmpty()) {
m_dirToQualifier.remove(oldDir.canonicalFilePath(), QString());
if (!m_dirToQualifier.contains(oldDir.canonicalFilePath()))
m_watcher.removePath(oldDir.filePath());
}
if (!newDir.filePath().isEmpty()) {
m_dirToQualifier.insertMulti(newDir.canonicalFilePath(), QString());
}
}
//
// Imports
//
// skip first list items until the lists differ
int i = 0;
while (i < qMin(imports.size(), m_imports.size())) {
if (!(imports.at(i) == m_imports.at(i)))
break;
++i;
}
for (int ii = m_imports.size() - 1; ii >= i; --ii)
removeImport(ii);
for (int ii = i; ii < imports.size(); ++ii) {
addImport(ii, imports.at(ii));
}
parseDirectories();
}
} // namespace QmlDesigner
<commit_msg>QmlDesigner.SubComponentManager: support for .metainfo files<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include <qmldesignerconstants.h>
#include "subcomponentmanager.h"
#include "model.h"
#include "metainfo.h"
#include "metainforeader.h"
#include <utils/hostosinfo.h>
#include <QDir>
#include <QMetaType>
#include <QMessageBox>
#include <QUrl>
enum { debug = false };
QT_BEGIN_NAMESPACE
// Allow usage of QFileInfo in qSort
static bool operator<(const QFileInfo &file1, const QFileInfo &file2)
{
return file1.filePath() < file2.filePath();
}
QT_END_NAMESPACE
static inline QStringList importPaths() {
QStringList paths;
// env import paths
QByteArray envImportPath = qgetenv("QML_IMPORT_PATH");
if (!envImportPath.isEmpty()) {
paths = QString::fromLatin1(envImportPath)
.split(Utils::HostOsInfo::pathListSeparator(), QString::SkipEmptyParts);
}
return paths;
}
namespace QmlDesigner {
static const QString s_qmlFilePattern = QString(QLatin1String("*.qml"));
SubComponentManager::SubComponentManager(Model *model, QObject *parent)
: QObject(parent),
m_model(model)
{
connect(&m_watcher, SIGNAL(directoryChanged(QString)), this, SLOT(parseDirectory(QString)));
}
void SubComponentManager::addImport(int pos, const Import &import)
{
if (debug)
qDebug() << Q_FUNC_INFO << pos << import.file().toLatin1();
if (import.isFileImport()) {
QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
if (dirInfo.exists() && dirInfo.isDir()) {
const QString canonicalDirPath = dirInfo.canonicalFilePath();
m_watcher.addPath(canonicalDirPath);
//m_dirToQualifier.insertMulti(canonicalDirPath, import.qualifier()); ### todo: proper support for import as
}
} else {
QString url = import.url();
url.replace(QLatin1Char('.'), QLatin1Char('/'));
foreach (const QString &path, importPaths()) {
url = path + QLatin1Char('/') + url;
QFileInfo dirInfo = QFileInfo(url);
if (dirInfo.exists() && dirInfo.isDir()) {
const QString canonicalDirPath = dirInfo.canonicalFilePath();
m_watcher.addPath(canonicalDirPath);
//m_dirToQualifier.insertMulti(canonicalDirPath, import.qualifier()); ### todo: proper support for import as
}
}
// TODO: QDeclarativeDomImport::Library
}
m_imports.insert(pos, import);
}
void SubComponentManager::removeImport(int pos)
{
const Import import = m_imports.takeAt(pos);
if (import.isFileImport()) {
const QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
const QString canonicalDirPath = dirInfo.canonicalFilePath();
//m_dirToQualifier.remove(canonicalDirPath, import.qualifier()); ### todo: proper support for import as
if (!m_dirToQualifier.contains(canonicalDirPath))
m_watcher.removePath(canonicalDirPath);
// foreach (const QFileInfo &monitoredFile, watchedFiles(canonicalDirPath)) { ### todo: proper support for import as
// if (!m_dirToQualifier.contains(canonicalDirPath))
// unregisterQmlFile(monitoredFile, import.qualifier());
// }
} else {
// TODO: QDeclarativeDomImport::Library
}
}
void SubComponentManager::parseDirectories()
{
if (!m_filePath.isEmpty()) {
const QString file = m_filePath.toLocalFile();
QFileInfo dirInfo = QFileInfo(QFileInfo(file).path());
if (dirInfo.exists() && dirInfo.isDir())
parseDirectory(dirInfo.canonicalFilePath());
foreach (const QString subDir, QDir(QFileInfo(file).path()).entryList(QDir::Dirs | QDir::NoDot | QDir::NoDotDot)) {
parseDirectory(dirInfo.canonicalFilePath() + "/" + subDir, true, subDir);
}
}
foreach (const Import &import, m_imports) {
if (import.isFileImport()) {
QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
if (dirInfo.exists() && dirInfo.isDir()) {
parseDirectory(dirInfo.canonicalFilePath());
}
} else {
QString url = import.url();
foreach (const QString &path, importPaths()) {
url.replace(QLatin1Char('.'), QLatin1Char('/'));
url = path + QLatin1Char('/') + url;
QFileInfo dirInfo = QFileInfo(url);
if (dirInfo.exists() && dirInfo.isDir()) {
//### todo full qualified names QString nameSpace = import.uri();
parseDirectory(dirInfo.canonicalFilePath(), false);
}
}
}
}
}
void SubComponentManager::parseDirectory(const QString &canonicalDirPath, bool addToLibrary, const QString& qualification)
{
QDir designerDir(canonicalDirPath + Constants::QML_DESIGNER_SUBFOLDER);
if (designerDir.exists()) {
QStringList filter;
filter << "*.metainfo";
designerDir.setNameFilters(filter);
QStringList metaFiles = designerDir.entryList(QDir::Files);
foreach (const QFileInfo &metaInfoFile, designerDir.entryInfoList(QDir::Files)) {
if (model() && model()->metaInfo().itemLibraryInfo()) {
Internal::MetaInfoReader reader(model()->metaInfo());
try {
reader.readMetaInfoFile(metaInfoFile.absoluteFilePath(), true);
} catch (InvalidMetaInfoException &e) {
qWarning() << e.description();
const QString errorMessage = metaInfoFile.absoluteFilePath() + QLatin1Char('\n') + QLatin1Char('\n') + reader.errors().join(QLatin1String("\n"));
QMessageBox::critical(0,
QCoreApplication::translate("SubComponentManager::parseDirectory", "Invalid meta info"),
errorMessage);
}
}
}
if (!metaFiles.isEmpty()) {
return;
}
}
if (debug)
qDebug() << Q_FUNC_INFO << canonicalDirPath;
QDir dir(canonicalDirPath);
dir.setNameFilters(QStringList(s_qmlFilePattern));
dir.setFilter(QDir::Files | QDir::Readable | QDir::CaseSensitive);
QList<QFileInfo> monitoredList = watchedFiles(canonicalDirPath);
QList<QFileInfo> newList;
foreach (const QFileInfo &qmlFile, dir.entryInfoList()) {
if (QFileInfo(m_filePath.toLocalFile()) == qmlFile) {
// do not parse main file
continue;
}
if (!qmlFile.fileName().at(0).isUpper()) {
// QML sub components must be upper case
continue;
}
newList << qmlFile;
}
qSort(monitoredList);
qSort(newList);
if (debug)
qDebug() << "monitored list " << monitoredList.size() << "new list " << newList.size();
QList<QFileInfo>::const_iterator oldIter = monitoredList.constBegin();
QList<QFileInfo>::const_iterator newIter = newList.constBegin();
while (oldIter != monitoredList.constEnd() && newIter != newList.constEnd()) {
const QFileInfo oldFileInfo = *oldIter;
const QFileInfo newFileInfo = *newIter;
if (oldFileInfo == newFileInfo) {
++oldIter;
++newIter;
continue;
}
if (oldFileInfo < newFileInfo) {
foreach (const QString &qualifier, m_dirToQualifier.value(canonicalDirPath))
unregisterQmlFile(oldFileInfo, qualifier);
m_watcher.removePath(oldFileInfo.filePath());
++oldIter;
continue;
}
// oldFileInfo > newFileInfo
parseFile(newFileInfo.filePath(), addToLibrary, qualification);
++newIter;
}
while (oldIter != monitoredList.constEnd()) {
foreach (const QString &qualifier, m_dirToQualifier.value(canonicalDirPath))
unregisterQmlFile(*oldIter, qualifier);
++oldIter;
}
while (newIter != newList.constEnd()) {
parseFile(newIter->filePath(), addToLibrary, qualification);
if (debug)
qDebug() << "m_watcher.addPath(" << newIter->filePath() << ')';
++newIter;
}
}
void SubComponentManager::parseFile(const QString &canonicalFilePath, bool addToLibrary, const QString& qualification)
{
if (debug)
qDebug() << Q_FUNC_INFO << canonicalFilePath;
QFile file(canonicalFilePath);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return;
}
QString dir = QFileInfo(canonicalFilePath).path();
foreach (const QString &qualifier, m_dirToQualifier.values(dir)) {
registerQmlFile(canonicalFilePath, qualifier, addToLibrary);
}
registerQmlFile(canonicalFilePath, qualification, addToLibrary);
}
void SubComponentManager::parseFile(const QString &canonicalFilePath)
{
parseFile(canonicalFilePath, true, QString());
}
// dirInfo must already contain a canonical path
QList<QFileInfo> SubComponentManager::watchedFiles(const QString &canonicalDirPath)
{
QList<QFileInfo> files;
foreach (const QString &monitoredFile, m_watcher.files()) {
QFileInfo fileInfo(monitoredFile);
if (fileInfo.dir().absolutePath() == canonicalDirPath) {
files.append(fileInfo);
}
}
return files;
}
void SubComponentManager::unregisterQmlFile(const QFileInfo &fileInfo, const QString &qualifier)
{
QString componentName = fileInfo.baseName();
if (!qualifier.isEmpty())
componentName = qualifier + '.' + componentName;
}
static inline bool isDepricatedQtType(const QString &typeName)
{
if (typeName.length() < 8)
return false;
return typeName.contains("Qt.");
}
void SubComponentManager::registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier,
bool addToLibrary)
{
if (!model())
return;
QString componentName = fileInfo.baseName();
if (debug)
qDebug() << "SubComponentManager" << __FUNCTION__ << componentName;
if (addToLibrary) {
// Add file components to the library
ItemLibraryEntry itemLibraryEntry;
itemLibraryEntry.setType(componentName, -1, -1);
itemLibraryEntry.setName(componentName);
itemLibraryEntry.setCategory("QML Components");
if (!qualifier.isEmpty()) {
itemLibraryEntry.setForceImport(true);
itemLibraryEntry.setRequiredImport(qualifier);
}
if (model()->metaInfo(componentName).isValid() && model()->metaInfo(componentName).isSubclassOf("QtQuick.Item", -1, -1) &&
!model()->metaInfo().itemLibraryInfo()->containsEntry(itemLibraryEntry)) {
model()->metaInfo().itemLibraryInfo()->addEntry(itemLibraryEntry);
}
}
}
Model *SubComponentManager::model() const
{
return m_model.data();
}
/*!
\class SubComponentManager
Detects & monitors (potential) component files in a list of directories, and registers
these in the metatype system.
*/
QStringList SubComponentManager::directories() const
{
return m_watcher.directories();
}
QStringList SubComponentManager::qmlFiles() const
{
return m_watcher.files();
}
void SubComponentManager::update(const QUrl &filePath, const QList<Import> &imports)
{
if (debug)
qDebug() << Q_FUNC_INFO << filePath << imports.size();
QFileInfo oldDir, newDir;
if (!m_filePath.isEmpty()) {
const QString file = m_filePath.toLocalFile();
oldDir = QFileInfo(QFileInfo(file).path());
}
if (!filePath.isEmpty()) {
const QString file = filePath.toLocalFile();
newDir = QFileInfo(QFileInfo(file).path());
}
m_filePath = filePath;
//
// (implicit) import of local directory
//
if (oldDir != newDir) {
if (!oldDir.filePath().isEmpty()) {
m_dirToQualifier.remove(oldDir.canonicalFilePath(), QString());
if (!m_dirToQualifier.contains(oldDir.canonicalFilePath()))
m_watcher.removePath(oldDir.filePath());
}
if (!newDir.filePath().isEmpty()) {
m_dirToQualifier.insertMulti(newDir.canonicalFilePath(), QString());
}
}
//
// Imports
//
// skip first list items until the lists differ
int i = 0;
while (i < qMin(imports.size(), m_imports.size())) {
if (!(imports.at(i) == m_imports.at(i)))
break;
++i;
}
for (int ii = m_imports.size() - 1; ii >= i; --ii)
removeImport(ii);
for (int ii = i; ii < imports.size(); ++ii) {
addImport(ii, imports.at(ii));
}
parseDirectories();
}
} // namespace QmlDesigner
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemodeviceconfiglistmodel.h"
#include "maemoconstants.h"
namespace Qt4ProjectManager {
namespace Internal {
MaemoDeviceConfigListModel::MaemoDeviceConfigListModel(QObject *parent)
: QAbstractListModel(parent), m_currentIndex(-1)
{
setupList();
const MaemoDeviceConfigurations &devConfs
= MaemoDeviceConfigurations::instance();
if (m_devConfigs.isEmpty())
setInvalid();
else
setCurrentIndex(0);
connect(&devConfs, SIGNAL(updated()), this,
SLOT(handleDeviceConfigListChange()));
}
void MaemoDeviceConfigListModel::setupList()
{
m_devConfigs.clear();
const MaemoDeviceConfigurations &devConfs
= MaemoDeviceConfigurations::instance();
foreach (const MaemoDeviceConfig &devConfig, devConfs.devConfigs()) {
if (devConfig.freePorts().hasMore())
m_devConfigs << devConfig;
}
}
void MaemoDeviceConfigListModel::setCurrentIndex(int index)
{
const quint64 idForIndex = m_devConfigs.at(index).internalId;
if (idForIndex != m_currentId) {
m_currentId = idForIndex;
m_currentIndex = index;
emit currentChanged();
}
}
void MaemoDeviceConfigListModel::resetCurrentIndex()
{
if (m_devConfigs.isEmpty()) {
setInvalid();
return;
}
for (int i = 0; i < m_devConfigs.count(); ++i) {
if (m_devConfigs.at(i).internalId == m_currentId) {
setCurrentIndex(i);
return;
}
}
setCurrentIndex(0);
}
void MaemoDeviceConfigListModel::setInvalid()
{
m_currentIndex = -1;
m_currentId = MaemoDeviceConfig::InvalidId;
emit currentChanged();
}
MaemoDeviceConfig MaemoDeviceConfigListModel::current() const
{
return MaemoDeviceConfigurations::instance().find(m_currentId);
}
QVariantMap MaemoDeviceConfigListModel::toMap() const
{
QVariantMap map;
map.insert(DeviceIdKey, current().internalId);
return map;
}
void MaemoDeviceConfigListModel::fromMap(const QVariantMap &map)
{
const quint64 oldId = m_currentId;
m_currentId = map.value(DeviceIdKey, 0).toULongLong();
resetCurrentIndex();
if (oldId != m_currentId)
emit currentChanged();
}
void MaemoDeviceConfigListModel::handleDeviceConfigListChange()
{
setupList();
resetCurrentIndex();
reset();
emit currentChanged();
}
int MaemoDeviceConfigListModel::rowCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : m_devConfigs.count();
}
QVariant MaemoDeviceConfigListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() >= rowCount()
|| role != Qt::DisplayRole)
return QVariant();
return m_devConfigs.at(index.row()).name;
}
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Maemo: Make device config list model a bit more robust.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Creator.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "maemodeviceconfiglistmodel.h"
#include "maemoconstants.h"
namespace Qt4ProjectManager {
namespace Internal {
MaemoDeviceConfigListModel::MaemoDeviceConfigListModel(QObject *parent)
: QAbstractListModel(parent), m_currentIndex(-1)
{
setupList();
const MaemoDeviceConfigurations &devConfs
= MaemoDeviceConfigurations::instance();
if (m_devConfigs.isEmpty())
setInvalid();
else
setCurrentIndex(0);
connect(&devConfs, SIGNAL(updated()), this,
SLOT(handleDeviceConfigListChange()));
}
void MaemoDeviceConfigListModel::setupList()
{
m_devConfigs.clear();
const MaemoDeviceConfigurations &devConfs
= MaemoDeviceConfigurations::instance();
foreach (const MaemoDeviceConfig &devConfig, devConfs.devConfigs()) {
if (devConfig.freePorts().hasMore())
m_devConfigs << devConfig;
}
}
void MaemoDeviceConfigListModel::setCurrentIndex(int index)
{
m_currentIndex = index;
m_currentId = m_devConfigs.at(m_currentIndex).internalId;
emit currentChanged();
}
void MaemoDeviceConfigListModel::resetCurrentIndex()
{
if (m_devConfigs.isEmpty()) {
setInvalid();
return;
}
for (int i = 0; i < m_devConfigs.count(); ++i) {
if (m_devConfigs.at(i).internalId == m_currentId) {
setCurrentIndex(i);
return;
}
}
setCurrentIndex(0);
}
void MaemoDeviceConfigListModel::setInvalid()
{
m_currentIndex = -1;
m_currentId = MaemoDeviceConfig::InvalidId;
emit currentChanged();
}
MaemoDeviceConfig MaemoDeviceConfigListModel::current() const
{
return MaemoDeviceConfigurations::instance().find(m_currentId);
}
QVariantMap MaemoDeviceConfigListModel::toMap() const
{
QVariantMap map;
map.insert(DeviceIdKey, current().internalId);
return map;
}
void MaemoDeviceConfigListModel::fromMap(const QVariantMap &map)
{
const quint64 oldId = m_currentId;
m_currentId = map.value(DeviceIdKey, 0).toULongLong();
resetCurrentIndex();
if (oldId != m_currentId)
emit currentChanged();
}
void MaemoDeviceConfigListModel::handleDeviceConfigListChange()
{
setupList();
resetCurrentIndex();
reset();
emit currentChanged();
}
int MaemoDeviceConfigListModel::rowCount(const QModelIndex &parent) const
{
return parent.isValid() ? 0 : m_devConfigs.count();
}
QVariant MaemoDeviceConfigListModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() >= rowCount()
|| role != Qt::DisplayRole)
return QVariant();
return m_devConfigs.at(index.row()).name;
}
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|>
|
<commit_before>#include "classes.h"
#include "win.h"
#include <sycl.hpp>
#include <chrono>
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using std::string;
extern void compute_org(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);
extern void compute_org_openmp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);
extern void compute_org_sp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);
extern void compute_org_sp_openmp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);
extern void compute_sycl_gtx(void* dev, int w, int h, int samps, Ray& cam_, Vec& cx_, Vec& cy_, Vec r_, Vec* c_);
inline double clamp(double x) {
return x < 0 ? 0 : x>1 ? 1 : x;
}
inline int toInt(double x) {
return int(pow(clamp(x), 1 / 2.2) * 255 + .5);
}
void to_file(int w, int h, Vec* c, string filename) {
FILE* f = fopen(filename.c_str(), "w"); // Write image to PPM file.
fprintf(f, "P3\n%d %d\n%d\n", w, h, 255);
for(int i = 0; i < w*h; i++) {
fprintf(f, "%d %d %d\n", toInt(c[i].x), toInt(c[i].y), toInt(c[i].z));
}
fclose(f);
}
using time_point = std::chrono::high_resolution_clock::time_point;
auto now = []() {
return std::chrono::high_resolution_clock::now();
};
auto duration = [](time_point before) {
static const float to_seconds = 1e-6f;
return std::chrono::duration_cast<std::chrono::microseconds>(now() - before).count() * to_seconds;
};
struct testInfo {
using function_ptr = void(*)(void*, int, int, int, Ray&, Vec&, Vec&, Vec, Vec*);
string name;
function_ptr test;
std::unique_ptr<cl::sycl::device> dev;
float lastTime = 0;
static decltype(now()) startTime;
static float totalTime;
testInfo(string name, function_ptr test, cl::sycl::device* dev = nullptr)
: name(name), test(test), dev(dev) {}
testInfo(const testInfo&) = delete;
testInfo(testInfo&& move)
: name(std::move(move.name)), test(move.test), dev(std::move(move.dev)) {}
};
decltype(now()) testInfo::startTime = now();
float testInfo::totalTime = 0;
static std::vector<const testInfo> tests;
static Ray cam(Vec(50, 52, 295.6), Vec(0, -0.042612, -1).norm()); // cam pos, dir
bool tester(int w, int h, int samples, Vec& cx, Vec& cy, int iterations, int from, int to) {
using namespace std;
cout << "samples per pixel: " << samples << endl;
Vec r;
vector<Vec> empty_vectors(w*h, 0);
vector<Vec> vectors;
float time;
for(int ti = from; ti < to; ++ti) {
auto& t = tests[ti];
// Quality of Service
// Prevent the user from waiting too long
if(t.lastTime > 40) {
continue;
}
cout << "Running test: " << t.name << endl;
ns_erand::reset();
#ifndef _DEBUG
try {
#endif
auto start = now();
for(int i = 0; i < iterations; ++i) {
vectors = empty_vectors;
t.test(t.dev.get(), w, h, samples, cam, cx, cy, r, vectors.data());
}
time = (duration(start) / (float)iterations);
#ifndef _DEBUG
}
catch(cl::sycl::exception& e) {
cerr << "SYCL error while testing: " << e.what() << endl;
continue;
}
catch(exception& e) {
cerr << "error while testing: " << e.what() << endl;
continue;
}
cout << "time: " << time << endl;
//to_file(w, h, vectors.data(), string("image_") + t.name + ".ppm");
t.lastTime = time;
testInfo::totalTime = duration(testInfo::startTime);
if(testInfo::totalTime > 300) {
cout << "exceeded 5 minute limit, stopping" << endl;
return false;
}
}
return true;
}
struct version {
int major = 0;
int minor = 0;
version(int major, int minor)
: major(major), minor(minor) {}
version(const string& v) {
// https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetPlatformInfo.html
using namespace std;
string search("OpenCL");
auto pos = v.find(search);
if(pos != string::npos) {
pos += search.length() + 1; // Plus one for space
try {
major = (int)v.at(pos) - '0';
minor = (int)v.at(pos + 2) - '0';; // Plus one for dot
}
catch(std::exception&) {}
}
}
};
template <class T>
void printInfo(string description, const T& data, int offset = 0) {
string indent;
for(int i = 0; i < offset; ++i) {
indent += '\t';
}
std::cout << indent << description << ": " << data << std::endl;
}
void getDevices() {
using namespace std;
try {
using namespace cl::sycl;
auto platforms = platform::get_platforms();
version required(1, 2);
int pNum = 0;
for(auto& p : platforms) {
cout << "- OpenCL platform " << pNum << ':' << endl;
++pNum;
auto openclVersion = p.get_info<info::platform::version>();
version platformVersion(openclVersion);
printInfo("name", p.get_info<info::platform::name>(), 1);
printInfo("vendor", p.get_info<info::platform::vendor>(), 1);
printInfo("version", openclVersion, 1);
printInfo("profile", p.get_info<info::platform::profile>(), 1);
printInfo("extensions", p.get_info<info::platform::extensions>(), 1);
auto devices = p.get_devices();
int dNum = 0;
for(auto& d : devices) {
cout << "\t-- OpenCL device " << dNum << ':' << endl;
auto name = d.get_info<info::device::name>();
printInfo("name", d.get_info<info::device::name>(), 2);
printInfo("device_type", (cl_device_type)d.get_info<info::device::device_type>(), 2);
printInfo("vendor", d.get_info<info::device::vendor>(), 2);
printInfo("device_version", d.get_info<info::device::device_version>(), 2);
printInfo("driver_version", d.get_info<info::device::driver_version>(), 2);
#ifdef SYCL_GTX
printInfo("opencl_version", d.get_info<info::device::opencl_version>(), 2);
printInfo("single_fp_config", d.get_info<info::device::single_fp_config>(), 2);
printInfo("double_fp_config", d.get_info<info::device::double_fp_config>(), 2);
#endif
printInfo("profile", d.get_info<info::device::profile>(), 2);
printInfo("error_correction_support", d.get_info<info::device::error_correction_support>(), 2);
printInfo("host_unified_memory", d.get_info<info::device::host_unified_memory>(), 2);
printInfo("max_clock_frequency", d.get_info<info::device::max_clock_frequency>(), 2);
printInfo("max_compute_units", d.get_info<info::device::max_compute_units>(), 2);
printInfo("max_work_item_dimensions", d.get_info<info::device::max_work_item_dimensions>(), 2);
printInfo("max_work_group_size", d.get_info<info::device::max_work_group_size>(), 2);
printInfo("address_bits", d.get_info<info::device::address_bits>(), 2);
printInfo("max_mem_alloc_size", d.get_info<info::device::max_mem_alloc_size>(), 2);
printInfo("global_mem_cache_line_size", d.get_info<info::device::global_mem_cache_line_size>(), 2);
printInfo("global_mem_cache_size", d.get_info<info::device::global_mem_cache_size>(), 2);
printInfo("global_mem_size", d.get_info<info::device::global_mem_size>(), 2);
printInfo("max_constant_buffer_size", d.get_info<info::device::max_constant_buffer_size>(), 2);
printInfo("max_constant_args", d.get_info<info::device::max_constant_args>(), 2);
printInfo("local_mem_size", d.get_info<info::device::local_mem_size>(), 2);
printInfo("extensions", d.get_info<info::device::extensions>(), 2);
if(
platformVersion.major > required.major ||
(platformVersion.major == required.major && platformVersion.minor >= required.minor)
) {
tests.emplace_back(name + ' ' + openclVersion, compute_sycl_gtx, new device(std::move(d)));
}
++dNum;
}
}
}
catch(cl::sycl::exception& e) {
// TODO
cout << "OpenCL not available: " << e.what() << endl;
}
}
int main(int argc, char *argv[]) {
using namespace std;
cout << "smallpt SYCL tester" << endl;
tests.emplace_back("org_single", compute_org_sp);
tests.emplace_back("openmp_single", compute_org_sp_openmp);
tests.emplace_back("org", compute_org);
tests.emplace_back("openmp", compute_org_openmp);
getDevices();
int w = 1024;
int h = 768;
Vec cx = Vec(w*.5135 / h);
Vec cy = (cx%cam.d).norm()*.5135;
auto numTests = tests.size();
int from = 2;
int to = numTests;
if(argc > 1) {
from = atoi(argv[1]);
if(argc > 2) {
to = atoi(argv[2]);
}
}
cout << "Going through tests in range [" << from << ',' << to << ')' << endl;
if(false) {
tester(w, h, 1, cx, cy, 1, from, to);
cout << "Press any key to exit" << endl;
cin.get();
return 0;
}
// Test suite
int iterations = 1;
bool canContinue;
for(int samples = 5; samples < 10000; samples *= 2) {
canContinue = tester(w, h, samples, cx, cy, iterations, from, to);
if(!canContinue) {
break;
}
}
auto time = duration(testInfo::startTime);
cout << "total test suite duration: " << time << endl;
//cout << "Press any key to exit" << endl;
//cin.get();
return 0;
}
<commit_msg>smallpt - forgot to include #endif after debugging block<commit_after>#include "classes.h"
#include "win.h"
#include <sycl.hpp>
#include <chrono>
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using std::string;
extern void compute_org(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);
extern void compute_org_openmp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);
extern void compute_org_sp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);
extern void compute_org_sp_openmp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);
extern void compute_sycl_gtx(void* dev, int w, int h, int samps, Ray& cam_, Vec& cx_, Vec& cy_, Vec r_, Vec* c_);
inline double clamp(double x) {
return x < 0 ? 0 : x>1 ? 1 : x;
}
inline int toInt(double x) {
return int(pow(clamp(x), 1 / 2.2) * 255 + .5);
}
void to_file(int w, int h, Vec* c, string filename) {
FILE* f = fopen(filename.c_str(), "w"); // Write image to PPM file.
fprintf(f, "P3\n%d %d\n%d\n", w, h, 255);
for(int i = 0; i < w*h; i++) {
fprintf(f, "%d %d %d\n", toInt(c[i].x), toInt(c[i].y), toInt(c[i].z));
}
fclose(f);
}
using time_point = std::chrono::high_resolution_clock::time_point;
auto now = []() {
return std::chrono::high_resolution_clock::now();
};
auto duration = [](time_point before) {
static const float to_seconds = 1e-6f;
return std::chrono::duration_cast<std::chrono::microseconds>(now() - before).count() * to_seconds;
};
struct testInfo {
using function_ptr = void(*)(void*, int, int, int, Ray&, Vec&, Vec&, Vec, Vec*);
string name;
function_ptr test;
std::unique_ptr<cl::sycl::device> dev;
float lastTime = 0;
static decltype(now()) startTime;
static float totalTime;
testInfo(string name, function_ptr test, cl::sycl::device* dev = nullptr)
: name(name), test(test), dev(dev) {}
testInfo(const testInfo&) = delete;
testInfo(testInfo&& move)
: name(std::move(move.name)), test(move.test), dev(std::move(move.dev)) {}
};
decltype(now()) testInfo::startTime = now();
float testInfo::totalTime = 0;
static std::vector<const testInfo> tests;
static Ray cam(Vec(50, 52, 295.6), Vec(0, -0.042612, -1).norm()); // cam pos, dir
bool tester(int w, int h, int samples, Vec& cx, Vec& cy, int iterations, int from, int to) {
using namespace std;
cout << "samples per pixel: " << samples << endl;
Vec r;
vector<Vec> empty_vectors(w*h, 0);
vector<Vec> vectors;
float time;
for(int ti = from; ti < to; ++ti) {
auto& t = tests[ti];
// Quality of Service
// Prevent the user from waiting too long
if(t.lastTime > 40) {
continue;
}
cout << "Running test: " << t.name << endl;
ns_erand::reset();
#ifndef _DEBUG
try {
#endif
auto start = now();
for(int i = 0; i < iterations; ++i) {
vectors = empty_vectors;
t.test(t.dev.get(), w, h, samples, cam, cx, cy, r, vectors.data());
}
time = (duration(start) / (float)iterations);
#ifndef _DEBUG
}
catch(cl::sycl::exception& e) {
cerr << "SYCL error while testing: " << e.what() << endl;
continue;
}
catch(exception& e) {
cerr << "error while testing: " << e.what() << endl;
continue;
}
#endif
cout << "time: " << time << endl;
//to_file(w, h, vectors.data(), string("image_") + t.name + ".ppm");
t.lastTime = time;
testInfo::totalTime = duration(testInfo::startTime);
if(testInfo::totalTime > 300) {
cout << "exceeded 5 minute limit, stopping" << endl;
return false;
}
}
return true;
}
struct version {
int major = 0;
int minor = 0;
version(int major, int minor)
: major(major), minor(minor) {}
version(const string& v) {
// https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetPlatformInfo.html
using namespace std;
string search("OpenCL");
auto pos = v.find(search);
if(pos != string::npos) {
pos += search.length() + 1; // Plus one for space
try {
major = (int)v.at(pos) - '0';
minor = (int)v.at(pos + 2) - '0';; // Plus one for dot
}
catch(std::exception&) {}
}
}
};
template <class T>
void printInfo(string description, const T& data, int offset = 0) {
string indent;
for(int i = 0; i < offset; ++i) {
indent += '\t';
}
std::cout << indent << description << ": " << data << std::endl;
}
void getDevices() {
using namespace std;
try {
using namespace cl::sycl;
auto platforms = platform::get_platforms();
version required(1, 2);
int pNum = 0;
for(auto& p : platforms) {
cout << "- OpenCL platform " << pNum << ':' << endl;
++pNum;
auto openclVersion = p.get_info<info::platform::version>();
version platformVersion(openclVersion);
printInfo("name", p.get_info<info::platform::name>(), 1);
printInfo("vendor", p.get_info<info::platform::vendor>(), 1);
printInfo("version", openclVersion, 1);
printInfo("profile", p.get_info<info::platform::profile>(), 1);
printInfo("extensions", p.get_info<info::platform::extensions>(), 1);
auto devices = p.get_devices();
int dNum = 0;
for(auto& d : devices) {
cout << "\t-- OpenCL device " << dNum << ':' << endl;
auto name = d.get_info<info::device::name>();
printInfo("name", d.get_info<info::device::name>(), 2);
printInfo("device_type", (cl_device_type)d.get_info<info::device::device_type>(), 2);
printInfo("vendor", d.get_info<info::device::vendor>(), 2);
printInfo("device_version", d.get_info<info::device::device_version>(), 2);
printInfo("driver_version", d.get_info<info::device::driver_version>(), 2);
#ifdef SYCL_GTX
printInfo("opencl_version", d.get_info<info::device::opencl_version>(), 2);
printInfo("single_fp_config", d.get_info<info::device::single_fp_config>(), 2);
printInfo("double_fp_config", d.get_info<info::device::double_fp_config>(), 2);
#endif
printInfo("profile", d.get_info<info::device::profile>(), 2);
printInfo("error_correction_support", d.get_info<info::device::error_correction_support>(), 2);
printInfo("host_unified_memory", d.get_info<info::device::host_unified_memory>(), 2);
printInfo("max_clock_frequency", d.get_info<info::device::max_clock_frequency>(), 2);
printInfo("max_compute_units", d.get_info<info::device::max_compute_units>(), 2);
printInfo("max_work_item_dimensions", d.get_info<info::device::max_work_item_dimensions>(), 2);
printInfo("max_work_group_size", d.get_info<info::device::max_work_group_size>(), 2);
printInfo("address_bits", d.get_info<info::device::address_bits>(), 2);
printInfo("max_mem_alloc_size", d.get_info<info::device::max_mem_alloc_size>(), 2);
printInfo("global_mem_cache_line_size", d.get_info<info::device::global_mem_cache_line_size>(), 2);
printInfo("global_mem_cache_size", d.get_info<info::device::global_mem_cache_size>(), 2);
printInfo("global_mem_size", d.get_info<info::device::global_mem_size>(), 2);
printInfo("max_constant_buffer_size", d.get_info<info::device::max_constant_buffer_size>(), 2);
printInfo("max_constant_args", d.get_info<info::device::max_constant_args>(), 2);
printInfo("local_mem_size", d.get_info<info::device::local_mem_size>(), 2);
printInfo("extensions", d.get_info<info::device::extensions>(), 2);
if(
platformVersion.major > required.major ||
(platformVersion.major == required.major && platformVersion.minor >= required.minor)
) {
tests.emplace_back(name + ' ' + openclVersion, compute_sycl_gtx, new device(std::move(d)));
}
++dNum;
}
}
}
catch(cl::sycl::exception& e) {
// TODO
cout << "OpenCL not available: " << e.what() << endl;
}
}
int main(int argc, char *argv[]) {
using namespace std;
cout << "smallpt SYCL tester" << endl;
tests.emplace_back("org_single", compute_org_sp);
tests.emplace_back("openmp_single", compute_org_sp_openmp);
tests.emplace_back("org", compute_org);
tests.emplace_back("openmp", compute_org_openmp);
getDevices();
int w = 1024;
int h = 768;
Vec cx = Vec(w*.5135 / h);
Vec cy = (cx%cam.d).norm()*.5135;
auto numTests = tests.size();
int from = 2;
int to = numTests;
if(argc > 1) {
from = atoi(argv[1]);
if(argc > 2) {
to = atoi(argv[2]);
}
}
cout << "Going through tests in range [" << from << ',' << to << ')' << endl;
if(false) {
tester(w, h, 1, cx, cy, 1, from, to);
cout << "Press any key to exit" << endl;
cin.get();
return 0;
}
// Test suite
int iterations = 1;
bool canContinue;
for(int samples = 5; samples < 10000; samples *= 2) {
canContinue = tester(w, h, samples, cx, cy, iterations, from, to);
if(!canContinue) {
break;
}
}
auto time = duration(testInfo::startTime);
cout << "total test suite duration: " << time << endl;
//cout << "Press any key to exit" << endl;
//cin.get();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include "libjoynrclustercontroller/mqtt/MosquittoConnection.h"
#include "joynr/ClusterControllerSettings.h"
#include "joynr/MessagingSettings.h"
#include "joynr/exceptions/JoynrException.h"
namespace joynr
{
INIT_LOGGER(MosquittoConnection);
MosquittoConnection::MosquittoConnection(const MessagingSettings& messagingSettings,
const ClusterControllerSettings& ccSettings,
const std::string& clientId)
: mosquittopp(clientId.c_str(), false),
messagingSettings(messagingSettings),
host(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getHost()),
port(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getPort()),
channelId(),
subscribeChannelMid(),
topic(),
additionalTopics(),
additionalTopicsMutex(),
isConnected(false),
isInitialConnection(true),
isRunning(false),
isChannelIdRegistered(false),
subscribedToChannelTopic(false),
readyToSend(false),
onMessageReceived(),
onReadyToSendChangedMutex(),
onReadyToSendChanged(),
thread()
{
JOYNR_LOG_DEBUG(logger, "Try to connect to tcp://{}:{}", host, port);
mosqpp::lib_init();
if (ccSettings.isMqttTlsEnabled()) {
int rc = tls_set(ccSettings.getMqttCertificateAuthorityPemFilename().c_str(),
NULL,
ccSettings.getMqttCertificatePemFilename().c_str(),
ccSettings.getMqttPrivateKeyPemFilename().c_str());
if (rc != MOSQ_ERR_SUCCESS) {
JOYNR_LOG_ERROR(
logger, "Could not initialize TLS connection - {}", mosqpp::strerror(rc));
}
} else {
JOYNR_LOG_DEBUG(logger, "MQTT connection not encrypted");
};
connect(host.c_str(), port, messagingSettings.getMqttKeepAliveTime().count());
}
MosquittoConnection::~MosquittoConnection()
{
stop();
}
void MosquittoConnection::on_disconnect(int rc)
{
isConnected = false;
setReadyToSend(false);
if (rc == 0) {
JOYNR_LOG_DEBUG(logger, "Disconnected from tcp://{}:{}", host, port);
} else {
JOYNR_LOG_ERROR(logger,
"Unexpectedly disconnected from tcp://{}:{}, error: {}",
host,
port,
mosqpp::strerror(rc));
}
}
void MosquittoConnection::on_log(int level, const char* str)
{
if (level == MOSQ_LOG_ERR) {
JOYNR_LOG_ERROR(logger, "Mosquitto Log: {}", str);
} else if (level == MOSQ_LOG_WARNING) {
JOYNR_LOG_WARN(logger, "Mosquitto Log: {}", str);
} else if (level == MOSQ_LOG_INFO) {
JOYNR_LOG_INFO(logger, "Mosquitto Log: {}", str);
} else {
// MOSQ_LOG_NOTICE || MOSQ_LOG_DEBUG || any other log level
JOYNR_LOG_DEBUG(logger, "Mosquitto Log: {}", str);
}
}
void MosquittoConnection::on_error()
{
JOYNR_LOG_WARN(logger, "Mosquitto Error");
}
std::uint16_t MosquittoConnection::getMqttQos() const
{
return mqttQos;
}
std::string MosquittoConnection::getMqttPrio() const
{
static const std::string value("low");
return value;
}
bool MosquittoConnection::isMqttRetain() const
{
return mqttRetain;
}
void MosquittoConnection::start()
{
isRunning = true;
thread = std::thread(&MosquittoConnection::runLoop, this);
}
void MosquittoConnection::stop()
{
isRunning = false;
if (thread.joinable()) {
thread.join();
}
}
void MosquittoConnection::runLoop()
{
const int mqttConnectionTimeoutMs = messagingSettings.getMqttConnectionTimeout().count();
while (isRunning) {
int rc = loop(mqttConnectionTimeoutMs);
if (rc != MOSQ_ERR_SUCCESS) {
if (rc == MOSQ_ERR_CONN_LOST) {
JOYNR_LOG_DEBUG(logger,
"error: connection to broker lost ({}), trying to reconnect...",
mosqpp::strerror(rc));
} else if (rc == MOSQ_ERR_NO_CONN) {
JOYNR_LOG_DEBUG(logger,
"error: not connected to a broker ({}), trying to reconnect...",
mosqpp::strerror(rc));
} else {
// MOSQ_ERR_INVAL || MOSQ_ERR_NOMEM || MOSQ_ERR_PROTOCOL || MOSQ_ERR_ERRNO
JOYNR_LOG_ERROR(logger,
"connection to broker lost, unexpected error: {} ({}), trying to "
"reconnect...",
std::to_string(rc),
mosqpp::strerror(rc));
}
std::this_thread::sleep_for(messagingSettings.getMqttReconnectSleepTime());
reconnect();
}
}
JOYNR_LOG_TRACE(logger, "Try to disconnect Mosquitto Connection");
int rc = disconnect();
if (rc == MOSQ_ERR_SUCCESS) {
JOYNR_LOG_DEBUG(logger, "Mosquitto Connection disconnected");
} else {
JOYNR_LOG_ERROR(logger,
"Mosquitto disconnect failed: error: {} ({})",
std::to_string(rc),
mosqpp::strerror(rc));
}
mosqpp::lib_cleanup();
}
void MosquittoConnection::on_connect(int rc)
{
if (rc > 0) {
if (rc == 1) {
JOYNR_LOG_ERROR(logger,
"Mosquitto Connection Error {} ({})",
rc,
"connection refused (unacceptable protocol version)");
} else if (rc == 2) {
JOYNR_LOG_ERROR(logger,
"Mosquitto Connection Error {} ({})",
rc,
"connection refused (identifier rejected)");
} else if (rc == 3) {
JOYNR_LOG_DEBUG(logger,
"Mosquitto Connection Error {} ({})",
rc,
"connection refused (broker unavailable)");
} else {
JOYNR_LOG_ERROR(logger,
"Mosquitto Connection Error {} ({})",
rc,
"unknown error code (reserved for future use)");
}
} else {
JOYNR_LOG_DEBUG(logger, "Mosquitto Connection established");
isConnected = true;
// The MQTT broker will reestablish subscriptions based on the client ID.
if (isInitialConnection) {
isInitialConnection = false;
createSubscriptions();
} else {
setReadyToSend(true);
}
}
}
void MosquittoConnection::createSubscriptions()
{
while (!isChannelIdRegistered && isRunning) {
std::this_thread::sleep_for(std::chrono::milliseconds(25));
}
try {
subscribeToTopicInternal(topic, true);
std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex);
for (const std::string& additionalTopic : additionalTopics) {
subscribeToTopicInternal(additionalTopic);
}
} catch (const exceptions::JoynrRuntimeException& error) {
JOYNR_LOG_ERROR(logger, "Error subscribing to Mqtt topic, error: ", error.getMessage());
}
}
void MosquittoConnection::subscribeToTopicInternal(const std::string& topic,
const bool isChannelTopic)
{
int* mid = nullptr;
if (isChannelTopic) {
mid = &subscribeChannelMid;
}
int rc = subscribe(mid, topic.c_str(), getMqttQos());
switch (rc) {
case (MOSQ_ERR_SUCCESS):
JOYNR_LOG_DEBUG(logger, "Subscribed to {}", topic);
break;
case (MOSQ_ERR_NO_CONN):
JOYNR_LOG_DEBUG(logger,
"Subscription to {} failed: error: {} (not connected to a broker). "
"Subscription will be restored on connect.",
topic,
std::to_string(rc));
break;
default:
// MOSQ_ERR_INVAL, MOSQ_ERR_NOMEM
std::string errorMsg = "Subscription to " + topic + " failed: error: " +
std::to_string(rc) + " (" + mosqpp::strerror(rc) + ")";
throw exceptions::JoynrRuntimeException(errorMsg);
}
}
void MosquittoConnection::subscribeToTopic(const std::string& topic)
{
while (!isChannelIdRegistered && isRunning) {
std::this_thread::sleep_for(std::chrono::milliseconds(25));
}
{
std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex);
if (additionalTopics.find(topic) != additionalTopics.end()) {
JOYNR_LOG_DEBUG(logger, "already subscribed to topic {}", topic);
return;
}
subscribeToTopicInternal(topic);
additionalTopics.insert(topic);
}
}
void MosquittoConnection::unsubscribeFromTopic(const std::string& topic)
{
if (isChannelIdRegistered) {
std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex);
if (additionalTopics.find(topic) == additionalTopics.end()) {
JOYNR_LOG_DEBUG(logger, "Unsubscribe called for non existing topic {}", topic);
return;
}
additionalTopics.erase(topic);
if (isConnected && isRunning) {
int rc = unsubscribe(nullptr, topic.c_str());
if (rc == MOSQ_ERR_SUCCESS) {
JOYNR_LOG_DEBUG(logger, "Unsubscribed from {}", topic);
} else {
// MOSQ_ERR_INVAL || MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN
JOYNR_LOG_ERROR(logger,
"Unsubscribe from {} failed: error: {} ({})",
topic,
std::to_string(rc),
mosqpp::strerror(rc));
}
}
}
}
void MosquittoConnection::publishMessage(
const std::string& topic,
const int qosLevel,
const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure,
uint32_t payloadlen = 0,
const void* payload = nullptr)
{
JOYNR_LOG_DEBUG(logger, "Publish to {}", topic);
int mid;
int rc = publish(&mid, topic.c_str(), payloadlen, payload, qosLevel, isMqttRetain());
if (!(rc == MOSQ_ERR_SUCCESS)) {
if (rc == MOSQ_ERR_INVAL || rc == MOSQ_ERR_PAYLOAD_SIZE) {
onFailure(exceptions::JoynrMessageNotSentException(
"message could not be sent: mid (mqtt message id): " + std::to_string(mid) +
", error: " + std::to_string(rc) + " (" + mosqpp::strerror(rc) + ")"));
}
// MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN || MOSQ_ERR_PROTOCOL ||| unexpected errors
onFailure(exceptions::JoynrDelayMessageException(
"error sending message: mid (mqtt message id): " + std::to_string(mid) +
", error: " + std::to_string(rc) + " (" + mosqpp::strerror(rc) + ")"));
}
JOYNR_LOG_TRACE(logger, "published message with mqtt message id {}", std::to_string(mid));
}
void MosquittoConnection::registerChannelId(const std::string& channelId)
{
this->channelId = channelId;
topic = channelId + "/" + getMqttPrio() + "/" + "#";
isChannelIdRegistered = true;
}
void MosquittoConnection::registerReceiveCallback(
std::function<void(smrf::ByteVector&&)> onMessageReceived)
{
this->onMessageReceived = onMessageReceived;
}
void MosquittoConnection::registerReadyToSendChangedCallback(
std::function<void(bool)> onReadyToSendChanged)
{
std::lock_guard<std::mutex> lock(onReadyToSendChangedMutex);
this->onReadyToSendChanged = std::move(onReadyToSendChanged);
}
bool MosquittoConnection::isSubscribedToChannelTopic() const
{
return subscribedToChannelTopic;
}
bool MosquittoConnection::isReadyToSend() const
{
return readyToSend;
}
void MosquittoConnection::on_subscribe(int mid, int qos_count, const int* granted_qos)
{
JOYNR_LOG_DEBUG(logger, "Subscribed (mid: {} with granted QOS {}", mid, granted_qos[0]);
for (int i = 1; i < qos_count; i++) {
JOYNR_LOG_DEBUG(logger, "QOS: {} granted {}", i, granted_qos[i]);
}
if (mid == subscribeChannelMid) {
subscribedToChannelTopic = true;
setReadyToSend(isConnected);
}
}
void MosquittoConnection::on_message(const mosquitto_message* message)
{
if (!onMessageReceived) {
JOYNR_LOG_ERROR(
logger, "Discarding received message, since onMessageReceived callback is empty.");
return;
}
std::uint8_t* data = static_cast<std::uint8_t*>(message->payload);
smrf::ByteVector rawMessage(data, data + message->payloadlen);
onMessageReceived(std::move(rawMessage));
}
void MosquittoConnection::on_publish(int mid)
{
JOYNR_LOG_TRACE(logger, "published message with mid {}", std::to_string(mid));
}
void MosquittoConnection::setReadyToSend(bool readyToSend)
{
if (this->readyToSend != readyToSend) {
this->readyToSend = readyToSend;
std::lock_guard<std::mutex> lock(onReadyToSendChangedMutex);
if (onReadyToSendChanged) {
onReadyToSendChanged(readyToSend);
}
}
}
} // namespace joynr
<commit_msg>[C++] Reestablish mqtt subscriptions upon connect event<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include "libjoynrclustercontroller/mqtt/MosquittoConnection.h"
#include "joynr/ClusterControllerSettings.h"
#include "joynr/MessagingSettings.h"
#include "joynr/exceptions/JoynrException.h"
namespace joynr
{
INIT_LOGGER(MosquittoConnection);
MosquittoConnection::MosquittoConnection(const MessagingSettings& messagingSettings,
const ClusterControllerSettings& ccSettings,
const std::string& clientId)
: mosquittopp(clientId.c_str(), false),
messagingSettings(messagingSettings),
host(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getHost()),
port(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getPort()),
channelId(),
subscribeChannelMid(),
topic(),
additionalTopics(),
additionalTopicsMutex(),
isConnected(false),
isInitialConnection(true),
isRunning(false),
isChannelIdRegistered(false),
subscribedToChannelTopic(false),
readyToSend(false),
onMessageReceived(),
onReadyToSendChangedMutex(),
onReadyToSendChanged(),
thread()
{
JOYNR_LOG_DEBUG(logger, "Try to connect to tcp://{}:{}", host, port);
mosqpp::lib_init();
if (ccSettings.isMqttTlsEnabled()) {
int rc = tls_set(ccSettings.getMqttCertificateAuthorityPemFilename().c_str(),
NULL,
ccSettings.getMqttCertificatePemFilename().c_str(),
ccSettings.getMqttPrivateKeyPemFilename().c_str());
if (rc != MOSQ_ERR_SUCCESS) {
JOYNR_LOG_ERROR(
logger, "Could not initialize TLS connection - {}", mosqpp::strerror(rc));
}
} else {
JOYNR_LOG_DEBUG(logger, "MQTT connection not encrypted");
};
connect(host.c_str(), port, messagingSettings.getMqttKeepAliveTime().count());
}
MosquittoConnection::~MosquittoConnection()
{
stop();
}
void MosquittoConnection::on_disconnect(int rc)
{
isConnected = false;
setReadyToSend(false);
if (rc == 0) {
JOYNR_LOG_DEBUG(logger, "Disconnected from tcp://{}:{}", host, port);
} else {
JOYNR_LOG_ERROR(logger,
"Unexpectedly disconnected from tcp://{}:{}, error: {}",
host,
port,
mosqpp::strerror(rc));
}
}
void MosquittoConnection::on_log(int level, const char* str)
{
if (level == MOSQ_LOG_ERR) {
JOYNR_LOG_ERROR(logger, "Mosquitto Log: {}", str);
} else if (level == MOSQ_LOG_WARNING) {
JOYNR_LOG_WARN(logger, "Mosquitto Log: {}", str);
} else if (level == MOSQ_LOG_INFO) {
JOYNR_LOG_INFO(logger, "Mosquitto Log: {}", str);
} else {
// MOSQ_LOG_NOTICE || MOSQ_LOG_DEBUG || any other log level
JOYNR_LOG_DEBUG(logger, "Mosquitto Log: {}", str);
}
}
void MosquittoConnection::on_error()
{
JOYNR_LOG_WARN(logger, "Mosquitto Error");
}
std::uint16_t MosquittoConnection::getMqttQos() const
{
return mqttQos;
}
std::string MosquittoConnection::getMqttPrio() const
{
static const std::string value("low");
return value;
}
bool MosquittoConnection::isMqttRetain() const
{
return mqttRetain;
}
void MosquittoConnection::start()
{
isRunning = true;
thread = std::thread(&MosquittoConnection::runLoop, this);
}
void MosquittoConnection::stop()
{
isRunning = false;
if (thread.joinable()) {
thread.join();
}
}
void MosquittoConnection::runLoop()
{
const int mqttConnectionTimeoutMs = messagingSettings.getMqttConnectionTimeout().count();
while (isRunning) {
int rc = loop(mqttConnectionTimeoutMs);
if (rc != MOSQ_ERR_SUCCESS) {
if (rc == MOSQ_ERR_CONN_LOST) {
JOYNR_LOG_DEBUG(logger,
"error: connection to broker lost ({}), trying to reconnect...",
mosqpp::strerror(rc));
} else if (rc == MOSQ_ERR_NO_CONN) {
JOYNR_LOG_DEBUG(logger,
"error: not connected to a broker ({}), trying to reconnect...",
mosqpp::strerror(rc));
} else {
// MOSQ_ERR_INVAL || MOSQ_ERR_NOMEM || MOSQ_ERR_PROTOCOL || MOSQ_ERR_ERRNO
JOYNR_LOG_ERROR(logger,
"connection to broker lost, unexpected error: {} ({}), trying to "
"reconnect...",
std::to_string(rc),
mosqpp::strerror(rc));
}
std::this_thread::sleep_for(messagingSettings.getMqttReconnectSleepTime());
reconnect();
}
}
JOYNR_LOG_TRACE(logger, "Try to disconnect Mosquitto Connection");
int rc = disconnect();
if (rc == MOSQ_ERR_SUCCESS) {
JOYNR_LOG_DEBUG(logger, "Mosquitto Connection disconnected");
} else {
JOYNR_LOG_ERROR(logger,
"Mosquitto disconnect failed: error: {} ({})",
std::to_string(rc),
mosqpp::strerror(rc));
}
mosqpp::lib_cleanup();
}
void MosquittoConnection::on_connect(int rc)
{
if (rc > 0) {
if (rc == 1) {
JOYNR_LOG_ERROR(logger,
"Mosquitto Connection Error {} ({})",
rc,
"connection refused (unacceptable protocol version)");
} else if (rc == 2) {
JOYNR_LOG_ERROR(logger,
"Mosquitto Connection Error {} ({})",
rc,
"connection refused (identifier rejected)");
} else if (rc == 3) {
JOYNR_LOG_DEBUG(logger,
"Mosquitto Connection Error {} ({})",
rc,
"connection refused (broker unavailable)");
} else {
JOYNR_LOG_ERROR(logger,
"Mosquitto Connection Error {} ({})",
rc,
"unknown error code (reserved for future use)");
}
} else {
JOYNR_LOG_DEBUG(logger, "Mosquitto Connection established");
isConnected = true;
createSubscriptions();
if (isInitialConnection) {
isInitialConnection = false;
}
}
}
void MosquittoConnection::createSubscriptions()
{
while (!isChannelIdRegistered && isRunning) {
std::this_thread::sleep_for(std::chrono::milliseconds(25));
}
try {
subscribeToTopicInternal(topic, true);
std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex);
for (const std::string& additionalTopic : additionalTopics) {
subscribeToTopicInternal(additionalTopic);
}
} catch (const exceptions::JoynrRuntimeException& error) {
JOYNR_LOG_ERROR(logger, "Error subscribing to Mqtt topic, error: ", error.getMessage());
}
}
void MosquittoConnection::subscribeToTopicInternal(const std::string& topic,
const bool isChannelTopic)
{
int* mid = nullptr;
if (isChannelTopic) {
mid = &subscribeChannelMid;
}
int rc = subscribe(mid, topic.c_str(), getMqttQos());
switch (rc) {
case (MOSQ_ERR_SUCCESS):
JOYNR_LOG_DEBUG(logger, "Subscribed to {}", topic);
break;
case (MOSQ_ERR_NO_CONN):
JOYNR_LOG_DEBUG(logger,
"Subscription to {} failed: error: {} (not connected to a broker). "
"Subscription will be restored on connect.",
topic,
std::to_string(rc));
break;
default:
// MOSQ_ERR_INVAL, MOSQ_ERR_NOMEM
std::string errorMsg = "Subscription to " + topic + " failed: error: " +
std::to_string(rc) + " (" + mosqpp::strerror(rc) + ")";
throw exceptions::JoynrRuntimeException(errorMsg);
}
}
void MosquittoConnection::subscribeToTopic(const std::string& topic)
{
while (!isChannelIdRegistered && isRunning) {
std::this_thread::sleep_for(std::chrono::milliseconds(25));
}
{
std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex);
if (additionalTopics.find(topic) != additionalTopics.end()) {
JOYNR_LOG_DEBUG(logger, "already subscribed to topic {}", topic);
return;
}
subscribeToTopicInternal(topic);
additionalTopics.insert(topic);
}
}
void MosquittoConnection::unsubscribeFromTopic(const std::string& topic)
{
if (isChannelIdRegistered) {
std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex);
if (additionalTopics.find(topic) == additionalTopics.end()) {
JOYNR_LOG_DEBUG(logger, "Unsubscribe called for non existing topic {}", topic);
return;
}
additionalTopics.erase(topic);
if (isConnected && isRunning) {
int rc = unsubscribe(nullptr, topic.c_str());
if (rc == MOSQ_ERR_SUCCESS) {
JOYNR_LOG_DEBUG(logger, "Unsubscribed from {}", topic);
} else {
// MOSQ_ERR_INVAL || MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN
JOYNR_LOG_ERROR(logger,
"Unsubscribe from {} failed: error: {} ({})",
topic,
std::to_string(rc),
mosqpp::strerror(rc));
}
}
}
}
void MosquittoConnection::publishMessage(
const std::string& topic,
const int qosLevel,
const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure,
uint32_t payloadlen = 0,
const void* payload = nullptr)
{
JOYNR_LOG_DEBUG(logger, "Publish to {}", topic);
int mid;
int rc = publish(&mid, topic.c_str(), payloadlen, payload, qosLevel, isMqttRetain());
if (!(rc == MOSQ_ERR_SUCCESS)) {
if (rc == MOSQ_ERR_INVAL || rc == MOSQ_ERR_PAYLOAD_SIZE) {
onFailure(exceptions::JoynrMessageNotSentException(
"message could not be sent: mid (mqtt message id): " + std::to_string(mid) +
", error: " + std::to_string(rc) + " (" + mosqpp::strerror(rc) + ")"));
}
// MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN || MOSQ_ERR_PROTOCOL ||| unexpected errors
onFailure(exceptions::JoynrDelayMessageException(
"error sending message: mid (mqtt message id): " + std::to_string(mid) +
", error: " + std::to_string(rc) + " (" + mosqpp::strerror(rc) + ")"));
}
JOYNR_LOG_TRACE(logger, "published message with mqtt message id {}", std::to_string(mid));
}
void MosquittoConnection::registerChannelId(const std::string& channelId)
{
this->channelId = channelId;
topic = channelId + "/" + getMqttPrio() + "/" + "#";
isChannelIdRegistered = true;
}
void MosquittoConnection::registerReceiveCallback(
std::function<void(smrf::ByteVector&&)> onMessageReceived)
{
this->onMessageReceived = onMessageReceived;
}
void MosquittoConnection::registerReadyToSendChangedCallback(
std::function<void(bool)> onReadyToSendChanged)
{
std::lock_guard<std::mutex> lock(onReadyToSendChangedMutex);
this->onReadyToSendChanged = std::move(onReadyToSendChanged);
}
bool MosquittoConnection::isSubscribedToChannelTopic() const
{
return subscribedToChannelTopic;
}
bool MosquittoConnection::isReadyToSend() const
{
return readyToSend;
}
void MosquittoConnection::on_subscribe(int mid, int qos_count, const int* granted_qos)
{
JOYNR_LOG_DEBUG(logger, "Subscribed (mid: {} with granted QOS {}", mid, granted_qos[0]);
for (int i = 1; i < qos_count; i++) {
JOYNR_LOG_DEBUG(logger, "QOS: {} granted {}", i, granted_qos[i]);
}
if (mid == subscribeChannelMid) {
subscribedToChannelTopic = true;
setReadyToSend(isConnected);
}
}
void MosquittoConnection::on_message(const mosquitto_message* message)
{
if (!onMessageReceived) {
JOYNR_LOG_ERROR(
logger, "Discarding received message, since onMessageReceived callback is empty.");
return;
}
std::uint8_t* data = static_cast<std::uint8_t*>(message->payload);
smrf::ByteVector rawMessage(data, data + message->payloadlen);
onMessageReceived(std::move(rawMessage));
}
void MosquittoConnection::on_publish(int mid)
{
JOYNR_LOG_TRACE(logger, "published message with mid {}", std::to_string(mid));
}
void MosquittoConnection::setReadyToSend(bool readyToSend)
{
if (this->readyToSend != readyToSend) {
this->readyToSend = readyToSend;
std::lock_guard<std::mutex> lock(onReadyToSendChangedMutex);
if (onReadyToSendChanged) {
onReadyToSendChanged(readyToSend);
}
}
}
} // namespace joynr
<|endoftext|>
|
<commit_before>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2018 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @file
#pragma once
#include <DO/Sara/Core/ArrayIterators/CoordinatesIterator.hpp>
#include <DO/Sara/Core/MultiArray/Padding.hpp>
namespace DO { namespace Sara {
template <typename ArrayView>
class InfiniteArrayIterator
{
public:
using self_type = InfiniteArrayIterator;
using vector_type = typename ArrayView::vector_type;
using value_type = typename ArrayView::value_type;
public:
inline InfiniteArrayIterator(const ArrayView& f, //
const vector_type& a, //
const vector_type& b)
: _f{f}
, _x{a, b}
{
}
//! Dereferencing operator.
inline value_type operator*() const
{
return _f(*_x);
}
//! Prefix increment operator.
inline self_type& operator++()
{
++_x;
return *this;
}
//! Prefix decrement operator.
inline self_type& operator--()
{
--_x;
return *this;
}
//! Postfix increment operator.
inline self_type operator++(int)
{
self_type old{*this};
operator++();
return old;
}
//! Postfix increment operator.
inline self_type operator--(int)
{
self_type old{*this};
operator--();
return old;
}
//! Arithmetic operator (slow).
inline self_type operator+=(const vector_type& offset)
{
_x += offset;
return *this;
}
//! Arithmetic operator (slow).
inline self_type operator-=(const vector_type& offset)
{
_x +=(-offset);
return *this;
}
inline bool end() const
{
return _x.end();
}
inline auto position() const -> const vector_type&
{
return *_x;
}
private:
const ArrayView& _f;
CoordinatesIterator<ArrayView> _x;
};
template <typename ArrayView>
class InfiniteSteppedArrayIterator
{
public:
using self_type = InfiniteSteppedArrayIterator;
using vector_type = typename ArrayView::vector_type;
using value_type = typename ArrayView::value_type;
public:
inline InfiniteSteppedArrayIterator(const ArrayView& f, //
const vector_type& a, //
const vector_type& b, //
const vector_type& steps) //
: _f{f}
, _x{a, b, steps}
{
}
//! Dereferencing operator.
inline value_type operator*() const
{
return _f(*_x);
}
//! Prefix increment operator.
inline self_type& operator++()
{
++_x;
return *this;
}
//! Prefix decrement operator.
inline self_type& operator--()
{
--_x;
return *this;
}
//! Postfix increment operator.
inline self_type operator++(int)
{
self_type old{*this};
operator++();
return old;
}
//! Postfix increment operator.
inline self_type operator--(int)
{
self_type old{*this};
operator--();
return old;
}
//! Arithmetic operator (slow).
inline self_type operator+=(const vector_type& offset)
{
_x += offset;
return *this;
}
//! Arithmetic operator (slow).
inline self_type operator-=(const vector_type& offset)
{
_x +=(-offset);
return *this;
}
inline bool end() const
{
return _x.end();
}
inline auto position() const -> const vector_type&
{
return *_x;
}
inline auto stepped_subarray_sizes() const -> vector_type
{
return _x.stepped_subarray_sizes();
}
private:
const ArrayView& _f;
SteppedCoordinatesIterator<ArrayView> _x;
};
template <typename ArrayView, typename Padding>
class InfiniteMultiArrayView
{
public:
using vector_type = typename ArrayView::vector_type;
using value_type = typename ArrayView::value_type;
enum { StorageOrder = ArrayView::StorageOrder };
enum { Dimension = ArrayView::Dimension };
inline InfiniteMultiArrayView(const ArrayView& f, const Padding& pad)
: _f(f)
, _pad{pad}
{
}
inline auto operator()(const vector_type& x) const -> value_type
{
return _pad.at(_f, x);
}
inline auto begin_subarray(const vector_type& a, const vector_type& b) const
-> InfiniteArrayIterator<InfiniteMultiArrayView>
{
return {*this, a, b};
}
inline auto begin_stepped_subarray(const vector_type& a, //
const vector_type& b, //
const vector_type& steps) const
-> InfiniteSteppedArrayIterator<InfiniteMultiArrayView>
{
return {*this, a, b, steps};
}
private:
const ArrayView& _f;
Padding _pad;
};
template <typename ArrayView, typename Padding>
inline auto make_infinite(const ArrayView& f, const Padding& pad)
-> InfiniteMultiArrayView<ArrayView, Padding>
{
return {f, pad};
}
} /* namespace Sara */
} /* namespace DO */
<commit_msg>MAINT: fix compile errors for Travis CI.<commit_after>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2018 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @file
#pragma once
#include <DO/Sara/Core/ArrayIterators/CoordinatesIterator.hpp>
#include <DO/Sara/Core/MultiArray/Padding.hpp>
namespace DO { namespace Sara {
template <typename ArrayView>
class InfiniteArrayIterator
{
public:
using self_type = InfiniteArrayIterator;
using vector_type = typename ArrayView::vector_type;
using value_type = typename ArrayView::value_type;
public:
inline InfiniteArrayIterator(const ArrayView& f, //
const vector_type& a, //
const vector_type& b)
: _f{f}
, _x{a, b}
{
}
//! Dereferencing operator.
inline value_type operator*() const
{
return _f(*_x);
}
//! Prefix increment operator.
inline self_type& operator++()
{
++_x;
return *this;
}
//! Prefix decrement operator.
inline self_type& operator--()
{
--_x;
return *this;
}
//! Postfix increment operator.
inline self_type operator++(int)
{
self_type old{*this};
operator++();
return old;
}
//! Postfix increment operator.
inline self_type operator--(int)
{
self_type old{*this};
operator--();
return old;
}
//! Arithmetic operator (slow).
inline self_type operator+=(const vector_type& offset)
{
_x += offset;
return *this;
}
//! Arithmetic operator (slow).
inline self_type operator-=(const vector_type& offset)
{
_x +=(-offset);
return *this;
}
inline bool end() const
{
return _x.end();
}
inline auto position() const -> const vector_type&
{
return *_x;
}
private:
const ArrayView& _f;
CoordinatesIterator<ArrayView> _x;
};
template <typename ArrayView>
class InfiniteSteppedArrayIterator
{
public:
using self_type = InfiniteSteppedArrayIterator;
using vector_type = typename ArrayView::vector_type;
using value_type = typename ArrayView::value_type;
public:
inline InfiniteSteppedArrayIterator(const ArrayView& f, //
const vector_type& a, //
const vector_type& b, //
const vector_type& steps) //
: _f{f}
, _x{a, b, steps}
{
}
//! Dereferencing operator.
inline value_type operator*() const
{
return _f(*_x);
}
//! Prefix increment operator.
inline self_type& operator++()
{
++_x;
return *this;
}
//! Prefix decrement operator.
inline self_type& operator--()
{
--_x;
return *this;
}
//! Postfix increment operator.
inline self_type operator++(int)
{
self_type old{*this};
operator++();
return old;
}
//! Postfix increment operator.
inline self_type operator--(int)
{
self_type old{*this};
operator--();
return old;
}
//! Arithmetic operator (slow).
inline self_type operator+=(const vector_type& offset)
{
_x += offset;
return *this;
}
//! Arithmetic operator (slow).
inline self_type operator-=(const vector_type& offset)
{
_x +=(-offset);
return *this;
}
inline bool end() const
{
return _x.end();
}
inline auto position() const -> const vector_type&
{
return *_x;
}
inline auto stepped_subarray_sizes() const -> vector_type
{
return _x.stepped_subarray_sizes();
}
private:
const ArrayView& _f;
SteppedCoordinatesIterator<ArrayView> _x;
};
template <typename ArrayView, typename Padding>
class InfiniteMultiArrayView
{
public:
using vector_type = typename ArrayView::vector_type;
using value_type = typename ArrayView::value_type;
enum { StorageOrder = ArrayView::StorageOrder };
enum { Dimension = ArrayView::Dimension };
inline InfiniteMultiArrayView(const ArrayView& f, const Padding& pad)
: _f(f)
, _pad(pad)
{
}
inline auto operator()(const vector_type& x) const -> value_type
{
return _pad.at(_f, x);
}
inline auto begin_subarray(const vector_type& a, const vector_type& b) const
-> InfiniteArrayIterator<InfiniteMultiArrayView>
{
return {*this, a, b};
}
inline auto begin_stepped_subarray(const vector_type& a, //
const vector_type& b, //
const vector_type& steps) const
-> InfiniteSteppedArrayIterator<InfiniteMultiArrayView>
{
return {*this, a, b, steps};
}
private:
const ArrayView& _f;
Padding _pad;
};
template <typename ArrayView, typename Padding>
inline auto make_infinite(const ArrayView& f, const Padding& pad)
-> InfiniteMultiArrayView<ArrayView, Padding>
{
return {f, pad};
}
} /* namespace Sara */
} /* namespace DO */
<|endoftext|>
|
<commit_before>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ink_stroke_modeler/internal/stylus_state_modeler.h"
#include <limits>
#include "ink_stroke_modeler/internal/internal_types.h"
#include "ink_stroke_modeler/internal/utils.h"
#include "ink_stroke_modeler/params.h"
#include "ink_stroke_modeler/types.h"
namespace ink {
namespace stroke_model {
void StylusStateModeler::Update(Vec2 position, const StylusState &state) {
if (state.pressure < 0) received_unknown_pressure_ = true;
if (state.tilt < 0) received_unknown_tilt_ = true;
if (state.orientation < 0) received_unknown_orientation_ = true;
if (received_unknown_pressure_ && received_unknown_tilt_ &&
received_unknown_orientation_) {
// We've stopped tracking all fields, so there's no need to keep updating.
positions_and_states_.clear();
return;
}
positions_and_states_.push_back({position, state});
if (params_.max_input_samples < 0 ||
positions_and_states_.size() > (uint)params_.max_input_samples) {
positions_and_states_.pop_front();
}
}
void StylusStateModeler::Reset(const StylusStateModelerParams ¶ms) {
params_ = params;
positions_and_states_.clear();
received_unknown_pressure_ = false;
received_unknown_tilt_ = false;
received_unknown_orientation_ = false;
}
StylusState StylusStateModeler::Query(Vec2 position) const {
if (positions_and_states_.empty())
return {.pressure = -1, .tilt = -1, .orientation = -1};
if (positions_and_states_.size() == 1) {
const auto &state = positions_and_states_.front().state;
return {
.pressure = received_unknown_pressure_ ? -1 : state.pressure,
.tilt = received_unknown_tilt_ ? -1 : state.tilt,
.orientation = received_unknown_orientation_ ? -1 : state.orientation};
}
int closest_segment = -1;
float min_distance = std::numeric_limits<float>::infinity();
float interp_value = 0;
for (decltype(positions_and_states_.size()) i = 0;
i < positions_and_states_.size() - 1; ++i) {
const Vec2 segment_start = positions_and_states_[i].position;
const Vec2 segment_end = positions_and_states_[i + 1].position;
float param = NearestPointOnSegment(segment_start, segment_end, position);
float distance =
Distance(position, Interp(segment_start, segment_end, param));
if (distance <= min_distance) {
closest_segment = i;
min_distance = distance;
interp_value = param;
}
}
auto from_state = positions_and_states_[closest_segment].state;
auto to_state = positions_and_states_[closest_segment + 1].state;
return StylusState{
.pressure =
received_unknown_pressure_
? -1
: Interp(from_state.pressure, to_state.pressure, interp_value),
.tilt = received_unknown_tilt_
? -1
: Interp(from_state.tilt, to_state.tilt, interp_value),
.orientation = received_unknown_orientation_
? -1
: InterpAngle(from_state.orientation,
to_state.orientation, interp_value)};
}
} // namespace stroke_model
} // namespace ink
<commit_msg>Avoid segfault in StylusStateModeler::Query<commit_after>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ink_stroke_modeler/internal/stylus_state_modeler.h"
#include <limits>
#include "ink_stroke_modeler/internal/internal_types.h"
#include "ink_stroke_modeler/internal/utils.h"
#include "ink_stroke_modeler/params.h"
#include "ink_stroke_modeler/types.h"
namespace ink {
namespace stroke_model {
void StylusStateModeler::Update(Vec2 position, const StylusState &state) {
if (state.pressure < 0) received_unknown_pressure_ = true;
if (state.tilt < 0) received_unknown_tilt_ = true;
if (state.orientation < 0) received_unknown_orientation_ = true;
if (received_unknown_pressure_ && received_unknown_tilt_ &&
received_unknown_orientation_) {
// We've stopped tracking all fields, so there's no need to keep updating.
positions_and_states_.clear();
return;
}
positions_and_states_.push_back({position, state});
if (params_.max_input_samples < 0 ||
positions_and_states_.size() > (uint)params_.max_input_samples) {
positions_and_states_.pop_front();
}
}
void StylusStateModeler::Reset(const StylusStateModelerParams ¶ms) {
params_ = params;
positions_and_states_.clear();
received_unknown_pressure_ = false;
received_unknown_tilt_ = false;
received_unknown_orientation_ = false;
}
StylusState StylusStateModeler::Query(Vec2 position) const {
if (positions_and_states_.empty())
return {.pressure = -1, .tilt = -1, .orientation = -1};
int closest_segment_index = -1;
float min_distance = std::numeric_limits<float>::infinity();
float interp_value = 0;
for (decltype(positions_and_states_.size()) i = 0;
i < positions_and_states_.size() - 1; ++i) {
const Vec2 segment_start = positions_and_states_[i].position;
const Vec2 segment_end = positions_and_states_[i + 1].position;
float param = NearestPointOnSegment(segment_start, segment_end, position);
float distance =
Distance(position, Interp(segment_start, segment_end, param));
if (distance <= min_distance) {
closest_segment_index = i;
min_distance = distance;
interp_value = param;
}
}
if (closest_segment_index < 0) {
const auto &state = positions_and_states_.front().state;
return {
.pressure = received_unknown_pressure_ ? -1 : state.pressure,
.tilt = received_unknown_tilt_ ? -1 : state.tilt,
.orientation = received_unknown_orientation_ ? -1 : state.orientation};
}
auto from_state = positions_and_states_[closest_segment_index].state;
auto to_state = positions_and_states_[closest_segment_index + 1].state;
return StylusState{
.pressure =
received_unknown_pressure_
? -1
: Interp(from_state.pressure, to_state.pressure, interp_value),
.tilt = received_unknown_tilt_
? -1
: Interp(from_state.tilt, to_state.tilt, interp_value),
.orientation = received_unknown_orientation_
? -1
: InterpAngle(from_state.orientation,
to_state.orientation, interp_value)};
}
} // namespace stroke_model
} // namespace ink
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
// Copyright (c) 2012, John Haddon. 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 Image Engine Design nor the names of any
// other contributors to this software 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 "IECorePython/IECoreBinding.h"
#include "IECorePython/ScopedGILLock.h"
#include "maya/MFnDagNode.h"
#include "maya/MBoundingBox.h"
#include "maya/MPlugArray.h"
#include "maya/MItDependencyGraph.h"
#include "maya/MIteratorType.h"
#include "extension/Extension.h"
#include "translators/shape/ShapeTranslator.h"
#include "IECore/CompoundParameter.h"
#include "IECoreMaya/ProceduralHolder.h"
#include "IECoreMaya/PythonCmd.h"
class ProceduralHolderTranslator : public CShapeTranslator
{
public :
virtual AtNode *CreateArnoldNodes()
{
return AddArnoldNode( "procedural" );
}
virtual void Export( AtNode *node )
{
// do basic node export
ExportMatrix( node, 0 );
AtNode *shader = arnoldShader();
if( shader )
{
AiNodeSetPtr( node, "shader", shader );
}
AiNodeSetInt( node, "visibility", ComputeVisibility() );
MPlug plug = FindMayaObjectPlug( "receiveShadows" );
if( !plug.isNull() )
{
AiNodeSetBool( node, "receive_shadows", plug.asBool() );
}
plug = FindMayaObjectPlug( "aiSelfShadows" );
if( !plug.isNull() )
{
AiNodeSetBool( node, "self_shadows", plug.asBool() );
}
plug = FindMayaObjectPlug( "aiOpaque" );
if( !plug.isNull() )
{
AiNodeSetBool( node, "opaque", plug.asBool() );
}
// export any shading groups or displacement shaders which look like they
// may be connected to procedural parameters. this ensures that maya shaders
// the procedural will expect to find at rendertime will be exported to the
// ass file (they otherwise might not be if they're not assigned to any objects).
exportShadingInputs();
// now set the procedural-specific parameters
MFnDagNode fnDagNode( m_dagPath );
MBoundingBox bound = fnDagNode.boundingBox();
AiNodeSetPnt( node, "min", bound.min().x, bound.min().y, bound.min().z );
AiNodeSetPnt( node, "max", bound.max().x, bound.max().y, bound.max().z );
const char *dsoPath = getenv( "IECOREARNOLD_PROCEDURAL_PATH" );
AiNodeSetStr( node, "dso", dsoPath ? dsoPath : "ieProcedural.so" );
AiNodeDeclare( node, "className", "constant STRING" );
AiNodeDeclare( node, "classVersion", "constant INT" );
AiNodeDeclare( node, "parameterValues", "constant ARRAY STRING" );
// cast should be ok as we're registered to only work on procedural holders
IECoreMaya::ProceduralHolder *pHolder = static_cast<IECoreMaya::ProceduralHolder *>( fnDagNode.userNode() );
std::string className;
int classVersion;
IECore::ParameterisedProceduralPtr procedural = pHolder->getProcedural( &className, &classVersion );
AiNodeSetStr( node, "className", className.c_str() );
AiNodeSetInt( node, "classVersion", classVersion );
IECorePython::ScopedGILLock gilLock;
try
{
boost::python::object parser = IECoreMaya::PythonCmd::globalContext()["IECore"].attr( "ParameterParser" )();
boost::python::object serialised = parser.attr( "serialise" )( procedural->parameters() );
size_t numStrings = IECorePython::len( serialised );
AtArray *stringArray = AiArrayAllocate( numStrings, 1, AI_TYPE_STRING );
for( size_t i=0; i<numStrings; i++ )
{
std::string s = boost::python::extract<std::string>( serialised[i] );
// hack to workaround ass parsing errors
/// \todo Remove when we get the Arnold version that fixes this
for( size_t c = 0; c<s.size(); c++ )
{
if( s[c] == '#' )
{
s[c] = '@';
}
}
AiArraySetStr( stringArray, i, s.c_str() );
}
AiNodeSetArray( node, "parameterValues", stringArray );
}
catch( boost::python::error_already_set )
{
PyErr_Print();
}
}
virtual bool RequiresMotionData()
{
return IsMotionBlurEnabled( MTOA_MBLUR_OBJECT ) && IsLocalMotionBlurEnabled();
}
virtual void ExportMotion( AtNode *node, AtUInt step )
{
if( !IsMotionBlurEnabled() )
{
return;
}
ExportMatrix( node, step );
}
static void nodeInitialiser( CAbTranslator context )
{
CExtensionAttrHelper helper( context.maya, "procedural" );
MakeArnoldVisibilityFlags( helper );
helper.MakeInput( "self_shadows" );
helper.MakeInput( "opaque" );
}
static void *creator()
{
return new ProceduralHolderTranslator();
}
protected :
/// Returns the arnold shader to assign to the procedural.
AtNode *arnoldShader()
{
bool overrideShaders = false;
MPlug plug = FindMayaObjectPlug( "overrideProceduralShaders" );
if( !plug.isNull() )
{
// if we've been told explicitly not to override the shaders
// in the procedurals, then early out.
overrideShaders = plug.asBool();
if( !overrideShaders )
{
return 0;
}
}
unsigned instNumber = m_dagPath.isInstanced() ? m_dagPath.instanceNumber() : 0;
MPlug shadingGroupPlug = GetNodeShadingGroup(m_dagPath.node(), instNumber);
if( !overrideShaders )
{
// if we weren't explicitly told to override the shaders, then
// decide whether to or not based on whether a non-default
// shader has been applied to the shape by the user.
MObject shadingGroupNode = shadingGroupPlug.node();
MFnDependencyNode fnShadingGroupNode( shadingGroupNode );
if( fnShadingGroupNode.name() != "initialShadingGroup" )
{
overrideShaders = true;
}
}
if( overrideShaders )
{
return ExportNode( shadingGroupPlug );
}
else
{
return 0;
}
}
void exportShadingInputs()
{
MObject proceduralNode = m_dagPath.node();
MPlug nullPlug;
MIteratorType filter;
MIntArray filterTypes;
filterTypes.append( MFn::kShadingEngine );
filterTypes.append( MFn::kDisplacementShader );
filter.setFilterList( filterTypes );
MItDependencyGraph itDG( proceduralNode, nullPlug, filter, MItDependencyGraph::kUpstream );
while( !itDG.isDone() )
{
MObject node = itDG.currentItem();
MFnDependencyNode fnNode( node );
MPlug plug;
if( fnNode.typeName() == "displacementShader" )
{
plug = fnNode.findPlug( "displacement" );
}
else
{
plug = fnNode.findPlug( "dsm" );
}
ExportNode( plug );
itDG.next();
}
}
};
extern "C"
{
DLLEXPORT void initializeExtension( CExtension &extension )
{
extension.Requires( "ieCore" );
extension.RegisterTranslator(
"ieProceduralHolder",
"",
ProceduralHolderTranslator::creator,
ProceduralHolderTranslator::nodeInitialiser
);
}
DLLEXPORT void deinitializeExtension( CExtension &extension )
{
}
} // extern "C"
<commit_msg>made MtoA acknoleged instances and generate ginstance nodes in ass output<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011, Image Engine Design Inc. All rights reserved.
// Copyright (c) 2012, John Haddon. 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 Image Engine Design nor the names of any
// other contributors to this software 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 "IECorePython/IECoreBinding.h"
#include "IECorePython/ScopedGILLock.h"
#include "maya/MFnDagNode.h"
#include "maya/MBoundingBox.h"
#include "maya/MPlugArray.h"
#include "maya/MItDependencyGraph.h"
#include "maya/MIteratorType.h"
#include "extension/Extension.h"
#include "translators/shape/ShapeTranslator.h"
#include "IECore/CompoundParameter.h"
#include "IECoreMaya/ProceduralHolder.h"
#include "IECoreMaya/PythonCmd.h"
class ProceduralHolderTranslator : public CShapeTranslator
{
public :
virtual AtNode *CreateArnoldNodes()
{
m_isMasterDag = IsMasterInstance(m_masterDag);
if (m_isMasterDag)
{
return AddArnoldNode( "procedural" );
}
else
{
return AddArnoldNode( "ginstance" );
}
}
virtual void Export( AtNode *node )
{
const char* nodeType = AiNodeEntryGetName(AiNodeGetNodeEntry(node));
if (strcmp(nodeType, "ginstance") == 0)
{
ExportInstance(node, m_masterDag);
}
else
{
ExportProcedural(node);
}
}
virtual AtNode* ExportInstance(AtNode *instance, const MDagPath& masterInstance)
{
AtNode* masterNode = AiNodeLookUpByName(masterInstance.partialPathName().asChar());
int instanceNum = m_dagPath.instanceNumber();
if ( instanceNum > 0 )
{
AiNodeSetStr(instance, "name", m_dagPath.partialPathName().asChar());
ExportMatrix(instance, 0);
AiNodeSetPtr(instance, "node", masterNode);
AiNodeSetBool(instance, "inherit_xform", false);
int visibility = AiNodeGetInt(masterNode, "visibility");
AiNodeSetInt(instance, "visibility", visibility);
AiNodeSetPtr( instance, "shader", arnoldShader() );
// Export light linking per instance
ExportLightLinking(instance);
}
return instance;
}
virtual void ExportProcedural( AtNode *node )
{
// do basic node export
ExportMatrix( node, 0 );
AtNode *shader = arnoldShader();
if( shader )
{
AiNodeSetPtr( node, "shader", shader );
}
AiNodeSetInt( node, "visibility", ComputeVisibility() );
MPlug plug = FindMayaObjectPlug( "receiveShadows" );
if( !plug.isNull() )
{
AiNodeSetBool( node, "receive_shadows", plug.asBool() );
}
plug = FindMayaObjectPlug( "aiSelfShadows" );
if( !plug.isNull() )
{
AiNodeSetBool( node, "self_shadows", plug.asBool() );
}
plug = FindMayaObjectPlug( "aiOpaque" );
if( !plug.isNull() )
{
AiNodeSetBool( node, "opaque", plug.asBool() );
}
// export any shading groups or displacement shaders which look like they
// may be connected to procedural parameters. this ensures that maya shaders
// the procedural will expect to find at rendertime will be exported to the
// ass file (they otherwise might not be if they're not assigned to any objects).
exportShadingInputs();
// now set the procedural-specific parameters
MFnDagNode fnDagNode( m_dagPath );
MBoundingBox bound = fnDagNode.boundingBox();
AiNodeSetPnt( node, "min", bound.min().x, bound.min().y, bound.min().z );
AiNodeSetPnt( node, "max", bound.max().x, bound.max().y, bound.max().z );
const char *dsoPath = getenv( "IECOREARNOLD_PROCEDURAL_PATH" );
AiNodeSetStr( node, "dso", dsoPath ? dsoPath : "ieProcedural.so" );
AiNodeDeclare( node, "className", "constant STRING" );
AiNodeDeclare( node, "classVersion", "constant INT" );
AiNodeDeclare( node, "parameterValues", "constant ARRAY STRING" );
// cast should be ok as we're registered to only work on procedural holders
IECoreMaya::ProceduralHolder *pHolder = static_cast<IECoreMaya::ProceduralHolder *>( fnDagNode.userNode() );
std::string className;
int classVersion;
IECore::ParameterisedProceduralPtr procedural = pHolder->getProcedural( &className, &classVersion );
AiNodeSetStr( node, "className", className.c_str() );
AiNodeSetInt( node, "classVersion", classVersion );
IECorePython::ScopedGILLock gilLock;
try
{
boost::python::object parser = IECoreMaya::PythonCmd::globalContext()["IECore"].attr( "ParameterParser" )();
boost::python::object serialised = parser.attr( "serialise" )( procedural->parameters() );
size_t numStrings = IECorePython::len( serialised );
AtArray *stringArray = AiArrayAllocate( numStrings, 1, AI_TYPE_STRING );
for( size_t i=0; i<numStrings; i++ )
{
std::string s = boost::python::extract<std::string>( serialised[i] );
// hack to workaround ass parsing errors
/// \todo Remove when we get the Arnold version that fixes this
for( size_t c = 0; c<s.size(); c++ )
{
if( s[c] == '#' )
{
s[c] = '@';
}
}
AiArraySetStr( stringArray, i, s.c_str() );
}
AiNodeSetArray( node, "parameterValues", stringArray );
}
catch( boost::python::error_already_set )
{
PyErr_Print();
}
}
virtual bool RequiresMotionData()
{
return IsMotionBlurEnabled( MTOA_MBLUR_OBJECT ) && IsLocalMotionBlurEnabled();
}
virtual void ExportMotion( AtNode *node, AtUInt step )
{
if( !IsMotionBlurEnabled() )
{
return;
}
ExportMatrix( node, step );
}
static void nodeInitialiser( CAbTranslator context )
{
CExtensionAttrHelper helper( context.maya, "procedural" );
MakeArnoldVisibilityFlags( helper );
helper.MakeInput( "self_shadows" );
helper.MakeInput( "opaque" );
}
static void *creator()
{
return new ProceduralHolderTranslator();
}
protected :
/// Returns the arnold shader to assign to the procedural.
AtNode *arnoldShader()
{
bool overrideShaders = false;
MPlug plug = FindMayaObjectPlug( "overrideProceduralShaders" );
if( !plug.isNull() )
{
// if we've been told explicitly not to override the shaders
// in the procedurals, then early out.
overrideShaders = plug.asBool();
if( !overrideShaders )
{
return 0;
}
}
unsigned instNumber = m_dagPath.isInstanced() ? m_dagPath.instanceNumber() : 0;
MPlug shadingGroupPlug = GetNodeShadingGroup(m_dagPath.node(), instNumber);
if( !overrideShaders )
{
// if we weren't explicitly told to override the shaders, then
// decide whether to or not based on whether a non-default
// shader has been applied to the shape by the user.
MObject shadingGroupNode = shadingGroupPlug.node();
MFnDependencyNode fnShadingGroupNode( shadingGroupNode );
if( fnShadingGroupNode.name() != "initialShadingGroup" )
{
overrideShaders = true;
}
}
if( overrideShaders )
{
return ExportNode( shadingGroupPlug );
}
else
{
return 0;
}
}
void exportShadingInputs()
{
MObject proceduralNode = m_dagPath.node();
MPlug nullPlug;
MIteratorType filter;
MIntArray filterTypes;
filterTypes.append( MFn::kShadingEngine );
filterTypes.append( MFn::kDisplacementShader );
filter.setFilterList( filterTypes );
MItDependencyGraph itDG( proceduralNode, nullPlug, filter, MItDependencyGraph::kUpstream );
while( !itDG.isDone() )
{
MObject node = itDG.currentItem();
MFnDependencyNode fnNode( node );
MPlug plug;
if( fnNode.typeName() == "displacementShader" )
{
plug = fnNode.findPlug( "displacement" );
}
else
{
plug = fnNode.findPlug( "dsm" );
}
ExportNode( plug );
itDG.next();
}
}
protected :
bool m_isMasterDag;
MDagPath m_masterDag;
};
extern "C"
{
DLLEXPORT void initializeExtension( CExtension &extension )
{
extension.Requires( "ieCore" );
extension.RegisterTranslator(
"ieProceduralHolder",
"",
ProceduralHolderTranslator::creator,
ProceduralHolderTranslator::nodeInitialiser
);
}
DLLEXPORT void deinitializeExtension( CExtension &extension )
{
}
} // extern "C"
<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief libmad を使った MP3 デコード・クラス @n
※このクラスを使うには、libmad ライブラリーが必要
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <mad.h>
#include "common/file_io.hpp"
#include "sound/audio_out.hpp"
#include "sound/id3_mgr.hpp"
extern "C" {
void set_sample_rate(uint32_t freq);
};
namespace audio {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief MP3 形式デコード・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class mp3_in {
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 制御列挙型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class CTRL {
NONE, ///< 何もしない
STOP, ///< 停止
PAUSE, ///< 一時停止
NEXT, ///< 次の曲
REPLAY, ///< 曲の先頭に戻って再生
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 制御タスク型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef CTRL (*CTRL_TASK)();
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 情報タスク型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef void (*TAG_TASK)(const tag_t&);
private:
static const uint32_t INPUT_BUFFER_SIZE = 2048;
mad_stream mad_stream_;
mad_frame mad_frame_;
mad_synth mad_synth_;
mad_timer_t mad_timer_;
uint8_t input_buffer_[INPUT_BUFFER_SIZE + MAD_BUFFER_GUARD];
// サブバンド領域フィルター特性用。
mad_fixed_t subband_filter_[32];
bool subband_filter_enable_;
bool id3v1_;
uint32_t time_;
CTRL_TASK ctrl_task_;
TAG_TASK tag_task_;
int fill_read_buffer_(utils::file_io& fin, mad_stream& strm)
{
/* The input bucket must be filled if it becomes empty or if
* it's the first execution of the loop.
*/
if(strm.buffer == NULL || strm.error == MAD_ERROR_BUFLEN) {
size_t size;
size_t remaining;
unsigned char* ptr;
/* {2} libmad may not consume all bytes of the input
* buffer. If the last frame in the buffer is not wholly
* contained by it, then that frame's start is pointed by
* the next_frame member of the Stream structure. This
* common situation occurs when mad_frame_decode() fails,
* sets the stream error code to MAD_ERROR_BUFLEN, and
* sets the next_frame pointer to a non NULL value. (See
* also the comment marked {4} bellow.)
*
* When this occurs, the remaining unused bytes must be
* put back at the beginning of the buffer and taken in
* account before refilling the buffer. This means that
* the input buffer must be large enough to hold a whole
* frame at the highest observable bit-rate (currently 448
* kb/s). XXX=XXX Is 2016 bytes the size of the largest
* frame? (448000*(1152/32000))/8
*/
if(strm.next_frame != NULL) {
remaining = strm.bufend - strm.next_frame;
memmove(&input_buffer_[0], strm.next_frame, remaining);
ptr = &input_buffer_[remaining];
size = INPUT_BUFFER_SIZE - remaining;
} else {
size = INPUT_BUFFER_SIZE;
ptr = &input_buffer_[0];
remaining = 0;
}
/* Fill-in the buffer. If an error occurs print a message
* and leave the decoding loop. If the end of stream is
* reached we also leave the loop but the return status is
* left untouched.
*/
// ReadSize = BstdRead(ReadStart, 1, ReadSize, BstdFile);
size_t req = size;
size_t rs = fin.read(ptr, 1, req);
if(id3v1_) {
if(fin.tell() >= (fin.get_file_size() - 128)) return -1;
} else {
if(fin.eof()) return -1;
}
size = rs;
if(rs < req) {
memset(&ptr[rs], 0, MAD_BUFFER_GUARD);
size += MAD_BUFFER_GUARD;
}
/* Pipe the new buffer content to libmad's stream decoder
* facility.
*/
mad_stream_buffer(&strm, &input_buffer_[0], size + remaining);
strm.error = MAD_ERROR_NONE;
return 0;
} else {
return 1;
}
}
/****************************************************************************
* Applies a frequency-domain filter to audio data in the subband-domain. *
****************************************************************************/
void apply_filter_(mad_frame& frame)
{
/* There is two application loops, each optimized for the number
* of audio channels to process. The first alternative is for
* two-channel frames, the second is for mono-audio.
*/
int num = MAD_NSBSAMPLES(&frame.header);
if(frame.header.mode != MAD_MODE_SINGLE_CHANNEL) {
for(int ch = 0; ch < 2; ++ch) {
for(int s = 0; s < num; ++s) {
for(int sb = 0; sb < 32; ++sb) {
frame.sbsample[ch][s][sb] =
mad_f_mul(frame.sbsample[ch][s][sb], subband_filter_[sb]);
}
}
}
} else {
for(int s = 0; s < num; ++s) {
for(int sb = 0; sb < 32; ++sb) {
frame.sbsample[0][s][sb] =
mad_f_mul(frame.sbsample[0][s][sb], subband_filter_[sb]);
}
}
}
}
static const short SHRT_MAX_ = 32767;
/****************************************************************************
* Converts a sample from mad's fixed point number format to a signed *
* short (16 bits). *
****************************************************************************/
static short MadFixedToSshort(mad_fixed_t v)
{
/* A fixed point number is formed of the following bit pattern:
*
* SWWWFFFFFFFFFFFFFFFFFFFFFFFFFFFF
* MSB LSB
* S ==> Sign (0 is positive, 1 is negative)
* W ==> Whole part bits
* F ==> Fractional part bits
*
* This pattern contains MAD_F_FRACBITS fractional bits, one
* should alway use this macro when working on the bits of a fixed
* point number. It is not guaranteed to be constant over the
* different platforms supported by libmad.
*
* The signed short value is formed, after clipping, by the least
* significant whole part bit, followed by the 15 most significant
* fractional part bits. Warning: this is a quick and dirty way to
* compute the 16-bit number, madplay includes much better
* algorithms.
*/
// Clipping..
if(v >= MAD_F_ONE) {
return SHRT_MAX_;
}
if(v <= -MAD_F_ONE) {
return -SHRT_MAX_;
}
return (signed short)(v >> (MAD_F_FRACBITS - 15));
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
mp3_in() : subband_filter_enable_(false), id3v1_(false),
time_(0), ctrl_task_(nullptr), tag_task_(nullptr) { }
//-----------------------------------------------------------------//
/*!
@brief 制御タスクの設定
@param[in] task 制御タスク
*/
//-----------------------------------------------------------------//
void set_ctrl_task(CTRL_TASK task)
{
ctrl_task_ = task;
}
//-----------------------------------------------------------------//
/*!
@brief タグ・タスクの設定
@param[in] task タグ・タスク
*/
//-----------------------------------------------------------------//
void set_tag_task(TAG_TASK task)
{
tag_task_ = task;
}
//-----------------------------------------------------------------//
/*!
@brief デコード
@param[in] fin file_io コンテキスト(参照)
@param[in] out オーディオ出力(参照)
@return 正常終了なら「true」
*/
//-----------------------------------------------------------------//
template <class AUDIO_OUT>
bool decode(utils::file_io& fin, AUDIO_OUT& out)
{
id3_mgr id3;
id3.analize(fin);
if(tag_task_ != nullptr) {
const auto& tag = id3.get_tag();
(*tag_task_)(tag);
// utils::format("Album: '%s'\n") % tag.album_;
// utils::format("Title: '%s'\n") % tag.title_;
// utils::format("Artist: '%s'\n") % tag.artist_;
// utils::format("Year: %s\n") % tag.year_;
// utils::format("Track: %s\n") % tag.track_;
}
mad_stream_init(&mad_stream_);
mad_frame_init(&mad_frame_);
mad_synth_init(&mad_synth_);
mad_timer_reset(&mad_timer_);
uint32_t forg = fin.tell();
bool info = false;
uint32_t pos = 0;
uint32_t frame_count = 0;
bool status = true;
bool pause = false;
while(fill_read_buffer_(fin, mad_stream_) >= 0) {
CTRL ctrl = CTRL::NONE;
if(ctrl_task_ != nullptr) {
ctrl = (*ctrl_task_)();
}
if(ctrl == CTRL::NEXT) {
out.mute();
break;
} else if(ctrl == CTRL::REPLAY) {
out.mute();
fin.seek(utils::file_io::SEEK::SET, forg);
info = false;
pos = 0;
time_ = 0;
frame_count = 0;
status = true;
pause = false;
continue;
} else if(ctrl == CTRL::PAUSE) {
out.mute();
pause = !pause;
} else if(ctrl == CTRL::STOP) {
out.mute();
status = false;
break;
}
if(pause) {
utils::delay::milli_second(5);
continue;
}
if(mad_frame_decode(&mad_frame_, &mad_stream_)) {
if(MAD_RECOVERABLE(mad_stream_.error)) {
continue;
} else {
if(mad_stream_.error == MAD_ERROR_BUFLEN) {
continue;
} else {
status = false;
break;
}
}
}
if(!info) {
set_sample_rate(mad_frame_.header.samplerate);
utils::format("Sample Rate: %d\n") % mad_frame_.header.samplerate;
info = true;
}
frame_count++;
mad_timer_add(&mad_timer_, mad_frame_.header.duration);
if(subband_filter_enable_) {
apply_filter_(mad_frame_);
}
mad_synth_frame(&mad_synth_, &mad_frame_);
for(uint32_t i = 0; i < mad_synth_.pcm.length; ++i) {
while((out.at_fifo().size() - out.at_fifo().length()) < 8) {
}
audio::wave_t t;
if(MAD_NCHANNELS(&mad_frame_.header) == 1) {
t.l_ch = t.r_ch = MadFixedToSshort(mad_synth_.pcm.samples[0][i]);
} else {
t.l_ch = MadFixedToSshort(mad_synth_.pcm.samples[0][i]);
t.r_ch = MadFixedToSshort(mad_synth_.pcm.samples[1][i]);
}
out.at_fifo().put(t);
++pos;
}
{
uint32_t s = pos / mad_frame_.header.samplerate;
if(s != time_) {
uint16_t sec = s % 60;
uint16_t min = (s / 60) % 60;
uint16_t hor = (s / 3600) % 24;
utils::format("\r%02d:%02d:%02d") % hor % min % sec;
time_ = s;
}
}
}
mad_synth_finish(&mad_synth_);
mad_frame_finish(&mad_frame_);
mad_stream_finish(&mad_stream_);
return status;
}
};
}
<commit_msg>update: update task manage<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief libmad を使った MP3 デコード・クラス @n
※このクラスを使うには、libmad ライブラリーが必要
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <mad.h>
#include "common/file_io.hpp"
#include "sound/audio_out.hpp"
#include "sound/id3_mgr.hpp"
extern "C" {
void set_sample_rate(uint32_t freq);
};
namespace audio {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief MP3 形式デコード・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class mp3_in {
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 制御列挙型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class CTRL {
NONE, ///< 何もしない
STOP, ///< 停止
PAUSE, ///< 一時停止
NEXT, ///< 次の曲
REPLAY, ///< 曲の先頭に戻って再生
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 制御タスク型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef CTRL (*CTRL_TASK)();
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 情報タスク型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef void (*TAG_TASK)(const tag_t&);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 更新タスク型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
typedef void (*UPDATE_TASK)(uint32_t);
private:
static const uint32_t INPUT_BUFFER_SIZE = 2048;
mad_stream mad_stream_;
mad_frame mad_frame_;
mad_synth mad_synth_;
mad_timer_t mad_timer_;
uint8_t input_buffer_[INPUT_BUFFER_SIZE + MAD_BUFFER_GUARD];
// サブバンド領域フィルター特性用。
mad_fixed_t subband_filter_[32];
bool subband_filter_enable_;
bool id3v1_;
uint32_t time_;
CTRL_TASK ctrl_task_;
TAG_TASK tag_task_;
UPDATE_TASK update_task_;
int fill_read_buffer_(utils::file_io& fin, mad_stream& strm)
{
/* The input bucket must be filled if it becomes empty or if
* it's the first execution of the loop.
*/
if(strm.buffer == NULL || strm.error == MAD_ERROR_BUFLEN) {
size_t size;
size_t remaining;
unsigned char* ptr;
/* {2} libmad may not consume all bytes of the input
* buffer. If the last frame in the buffer is not wholly
* contained by it, then that frame's start is pointed by
* the next_frame member of the Stream structure. This
* common situation occurs when mad_frame_decode() fails,
* sets the stream error code to MAD_ERROR_BUFLEN, and
* sets the next_frame pointer to a non NULL value. (See
* also the comment marked {4} bellow.)
*
* When this occurs, the remaining unused bytes must be
* put back at the beginning of the buffer and taken in
* account before refilling the buffer. This means that
* the input buffer must be large enough to hold a whole
* frame at the highest observable bit-rate (currently 448
* kb/s). XXX=XXX Is 2016 bytes the size of the largest
* frame? (448000*(1152/32000))/8
*/
if(strm.next_frame != NULL) {
remaining = strm.bufend - strm.next_frame;
memmove(&input_buffer_[0], strm.next_frame, remaining);
ptr = &input_buffer_[remaining];
size = INPUT_BUFFER_SIZE - remaining;
} else {
size = INPUT_BUFFER_SIZE;
ptr = &input_buffer_[0];
remaining = 0;
}
/* Fill-in the buffer. If an error occurs print a message
* and leave the decoding loop. If the end of stream is
* reached we also leave the loop but the return status is
* left untouched.
*/
// ReadSize = BstdRead(ReadStart, 1, ReadSize, BstdFile);
size_t req = size;
size_t rs = fin.read(ptr, 1, req);
if(id3v1_) {
if(fin.tell() >= (fin.get_file_size() - 128)) return -1;
} else {
if(fin.eof()) return -1;
}
size = rs;
if(rs < req) {
memset(&ptr[rs], 0, MAD_BUFFER_GUARD);
size += MAD_BUFFER_GUARD;
}
/* Pipe the new buffer content to libmad's stream decoder
* facility.
*/
mad_stream_buffer(&strm, &input_buffer_[0], size + remaining);
strm.error = MAD_ERROR_NONE;
return 0;
} else {
return 1;
}
}
/****************************************************************************
* Applies a frequency-domain filter to audio data in the subband-domain. *
****************************************************************************/
void apply_filter_(mad_frame& frame)
{
/* There is two application loops, each optimized for the number
* of audio channels to process. The first alternative is for
* two-channel frames, the second is for mono-audio.
*/
int num = MAD_NSBSAMPLES(&frame.header);
if(frame.header.mode != MAD_MODE_SINGLE_CHANNEL) {
for(int ch = 0; ch < 2; ++ch) {
for(int s = 0; s < num; ++s) {
for(int sb = 0; sb < 32; ++sb) {
frame.sbsample[ch][s][sb] =
mad_f_mul(frame.sbsample[ch][s][sb], subband_filter_[sb]);
}
}
}
} else {
for(int s = 0; s < num; ++s) {
for(int sb = 0; sb < 32; ++sb) {
frame.sbsample[0][s][sb] =
mad_f_mul(frame.sbsample[0][s][sb], subband_filter_[sb]);
}
}
}
}
static const short SHRT_MAX_ = 32767;
/****************************************************************************
* Converts a sample from mad's fixed point number format to a signed *
* short (16 bits). *
****************************************************************************/
static short MadFixedToSshort(mad_fixed_t v)
{
/* A fixed point number is formed of the following bit pattern:
*
* SWWWFFFFFFFFFFFFFFFFFFFFFFFFFFFF
* MSB LSB
* S ==> Sign (0 is positive, 1 is negative)
* W ==> Whole part bits
* F ==> Fractional part bits
*
* This pattern contains MAD_F_FRACBITS fractional bits, one
* should alway use this macro when working on the bits of a fixed
* point number. It is not guaranteed to be constant over the
* different platforms supported by libmad.
*
* The signed short value is formed, after clipping, by the least
* significant whole part bit, followed by the 15 most significant
* fractional part bits. Warning: this is a quick and dirty way to
* compute the 16-bit number, madplay includes much better
* algorithms.
*/
// Clipping..
if(v >= MAD_F_ONE) {
return SHRT_MAX_;
}
if(v <= -MAD_F_ONE) {
return -SHRT_MAX_;
}
return (signed short)(v >> (MAD_F_FRACBITS - 15));
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
mp3_in() : subband_filter_enable_(false), id3v1_(false), time_(0),
ctrl_task_(nullptr), tag_task_(nullptr), update_task_(nullptr) { }
//-----------------------------------------------------------------//
/*!
@brief 制御タスクの設定
@param[in] task 制御タスク
*/
//-----------------------------------------------------------------//
void set_ctrl_task(CTRL_TASK task)
{
ctrl_task_ = task;
}
//-----------------------------------------------------------------//
/*!
@brief タグ・タスクの設定
@param[in] task タグ・タスク
*/
//-----------------------------------------------------------------//
void set_tag_task(TAG_TASK task)
{
tag_task_ = task;
}
//-----------------------------------------------------------------//
/*!
@brief アップデート・タスクの設定
@param[in] task アップデート・タスク
*/
//-----------------------------------------------------------------//
void set_update_task(UPDATE_TASK task)
{
update_task_ = task;
}
//-----------------------------------------------------------------//
/*!
@brief デコード
@param[in] fin file_io コンテキスト(参照)
@param[in] out オーディオ出力(参照)
@return 正常終了なら「true」
*/
//-----------------------------------------------------------------//
template <class AUDIO_OUT>
bool decode(utils::file_io& fin, AUDIO_OUT& out)
{
id3_mgr id3;
id3.analize(fin);
if(tag_task_ != nullptr) {
const auto& tag = id3.get_tag();
(*tag_task_)(tag);
// utils::format("Album: '%s'\n") % tag.album_;
// utils::format("Title: '%s'\n") % tag.title_;
// utils::format("Artist: '%s'\n") % tag.artist_;
// utils::format("Year: %s\n") % tag.year_;
// utils::format("Track: %s\n") % tag.track_;
}
mad_stream_init(&mad_stream_);
mad_frame_init(&mad_frame_);
mad_synth_init(&mad_synth_);
mad_timer_reset(&mad_timer_);
uint32_t forg = fin.tell();
bool info = false;
uint32_t pos = 0;
uint32_t frame_count = 0;
bool status = true;
bool pause = false;
while(fill_read_buffer_(fin, mad_stream_) >= 0) {
CTRL ctrl = CTRL::NONE;
if(ctrl_task_ != nullptr) {
ctrl = (*ctrl_task_)();
}
if(ctrl == CTRL::NEXT) {
out.mute();
break;
} else if(ctrl == CTRL::REPLAY) {
out.mute();
fin.seek(utils::file_io::SEEK::SET, forg);
info = false;
pos = 0;
time_ = 0;
frame_count = 0;
status = true;
pause = false;
continue;
} else if(ctrl == CTRL::PAUSE) {
out.mute();
pause = !pause;
} else if(ctrl == CTRL::STOP) {
out.mute();
status = false;
break;
}
if(pause) {
utils::delay::milli_second(5);
continue;
}
if(mad_frame_decode(&mad_frame_, &mad_stream_)) {
if(MAD_RECOVERABLE(mad_stream_.error)) {
continue;
} else {
if(mad_stream_.error == MAD_ERROR_BUFLEN) {
continue;
} else {
status = false;
break;
}
}
}
if(!info) {
set_sample_rate(mad_frame_.header.samplerate);
utils::format("Sample Rate: %d\n") % mad_frame_.header.samplerate;
info = true;
}
frame_count++;
mad_timer_add(&mad_timer_, mad_frame_.header.duration);
if(subband_filter_enable_) {
apply_filter_(mad_frame_);
}
mad_synth_frame(&mad_synth_, &mad_frame_);
for(uint32_t i = 0; i < mad_synth_.pcm.length; ++i) {
while((out.at_fifo().size() - out.at_fifo().length()) < 8) {
}
audio::wave_t t;
if(MAD_NCHANNELS(&mad_frame_.header) == 1) {
t.l_ch = t.r_ch = MadFixedToSshort(mad_synth_.pcm.samples[0][i]);
} else {
t.l_ch = MadFixedToSshort(mad_synth_.pcm.samples[0][i]);
t.r_ch = MadFixedToSshort(mad_synth_.pcm.samples[1][i]);
}
out.at_fifo().put(t);
++pos;
}
{
uint32_t s = pos / mad_frame_.header.samplerate;
if(s != time_) {
if(update_task_ != nullptr) {
(*update_task_)(s);
}
time_ = s;
}
}
}
mad_synth_finish(&mad_synth_);
mad_frame_finish(&mad_frame_);
mad_stream_finish(&mad_stream_);
return status;
}
};
}
<|endoftext|>
|
<commit_before>//needed for testing
#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
//other stuff needed
#include <glm/vec3.hpp>
#include <cmath>
#include <iostream>
//include classes for testing
#include "shape.hpp"
#include "sphere.hpp"
#include "box.hpp"
#include "material.hpp"
#include "color.hpp"
// ----------------------------------
// SHAPE TESTS
// ----------------------------------
//karos änderung
TEST_CASE("getter shape","[shape]")
{
Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
REQUIRE(s.get_name() == "name");
Material c{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f};
REQUIRE(s.get_material() == c); //added operator == in color.hpp
}
TEST_CASE("operator<< and print shape","[shape]")
{
Sphere es {"empty_sphere"};
std::cout << es;
Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
std::cout << s;
}
// ----------------------------------
// SPHERE TESTS
// ----------------------------------
TEST_CASE("constructors of sphere","[sphere]")
{
Sphere s1 {"name"};
Sphere s2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
REQUIRE(s1.get_center() == s2.get_center());
REQUIRE(s1.get_radius() == s2.get_radius());
}
TEST_CASE("get_center and get_radius","[sphere]")
{
Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
REQUIRE(s.get_radius() == 1.0f);
REQUIRE(s.get_center() == glm::vec3{0.0f});
}
TEST_CASE("area","[sphere]")
{
Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
REQUIRE(12.566f == Approx(s.area()).epsilon(0.001));
}
TEST_CASE("volume","[sphere]")
{
Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
REQUIRE(4.189 == Approx(s.volume()).epsilon(0.001));
}
TEST_CASE("print sphere","[sphere]")
{
Sphere es {"empty_sphere"};
std::cout << es;
Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
std::cout << s;
}
// ----------------------------------
// BOX TESTS
// ----------------------------------
TEST_CASE("constructors of box","[box]")
{
Box b1 {"name"};
Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};
REQUIRE(b1.get_min() == b2.get_min());
REQUIRE(b1.get_max() == b2.get_max());
}
TEST_CASE("get_min and get_max","[box]")
{
Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};
REQUIRE(b2.get_min() == glm::vec3{0.0f});
REQUIRE(b2.get_max() == glm::vec3{1.0f});
}
TEST_CASE("area of box","[box]")
{
Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};
REQUIRE(6.0f == Approx(b2.area()).epsilon(0.001));
}
TEST_CASE("volume of box","[box]")
{
Box b2 {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}};
REQUIRE(1.0f == Approx(b2.volume()).epsilon(0.001));
}
TEST_CASE("print box","[box]")
{
Box eb {"empty_box"};
std::cout << eb;
Box b {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}};
std::cout << b;
}
// ----------------------------------
// AUFGABE 5.6 TEST
// ----------------------------------
TEST_CASE("intersectRaySphere", "[intersect]")
{
//Ray
glm::vec3 ray_origin{0.0f, 0.0f, 0.0f};
//ray direction has to be normalized !
//you can use:
//v = glm::normalize(some_vector);
glm::vec3 ray_direction{0.0f, 0.0f, 1.0f};
//Sphere
glm::vec3 sphere_center{0.0f, 0.0f, 5.0f};
float sphere_radius{1.0f};
float distance{0.0f};
auto result = glm::intersectRaySphere(
ray_origin, ray_direction,
sphere_center,
sphere_radius * sphere_radius,
distance);
REQUIRE(distance == Approx(4.0f));
Sphere s {"some_sphere", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},
sphere_center, sphere_radius};
Ray r {ray_origin,ray_direction};
s.intersect(r,distance);
REQUIRE(distance == Approx(4.0f));
}
// ----------------------------------
// AUFGABE 5.8 TEST
// ----------------------------------
TEST_CASE("virtual", "[Destructors]")
{
std::cout << "\ntesting virtual and non-virtual construction and destruction\n";
Color c_red {255.0f, 0.0f, 0.0f};
Material red {"", c_red, c_red, c_red, 0.0f};
glm::vec3 position {0.0f,0.0f,0.0f};
std::cout << "Create s1\n";
Sphere* s1 = new Sphere("sphere0",red,position,1.2f);
std::cout << "Create s2\n";
Shape* s2 = new Sphere("sphere1",red,position,1.2f);
std::cout << "Printing objects: \n";
std::cout << *s1;
std::cout << *s2 << "\n";
std::cout << "Delete s1\n";
delete s1;
std::cout << "Delete s2\n";
delete s2;
}
// ----------------------------------
// MATERIAL Tests
// ----------------------------------
TEST_CASE("material in place of color struct", "Material")
{
Color c{0.0f,0.0f,0.0f};
Material mate1 {};
std::cout << mate1;
Material mate2 {"some material",c,c,c,0.0f};
std::cout << mate2;
}
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}
<commit_msg>noch ein merge test<commit_after>//needed for testing
#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
//other stuff needed
#include <glm/vec3.hpp>
#include <cmath>
#include <iostream>
//include classes for testing
#include "shape.hpp"
#include "sphere.hpp"
#include "box.hpp"
#include "material.hpp"
#include "color.hpp"
// ----------------------------------
// SHAPE TESTS
// ----------------------------------
//karos änderung
TEST_CASE("getter shape","[shape]")
{
Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
REQUIRE(s.get_name() == "name");
Material c{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f};
REQUIRE(s.get_material() == c); //added operator == in color.hpp
}
TEST_CASE("operator<< and print shape","[shape]")
{
Sphere es {"empty_sphere"};
std::cout << es;
Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
std::cout << s;
//trolololo
}
// ----------------------------------
// SPHERE TESTS
// ----------------------------------
TEST_CASE("constructors of sphere","[sphere]")
{
Sphere s1 {"name"};
Sphere s2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
REQUIRE(s1.get_center() == s2.get_center());
REQUIRE(s1.get_radius() == s2.get_radius());
}
TEST_CASE("get_center and get_radius","[sphere]")
{
Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
REQUIRE(s.get_radius() == 1.0f);
REQUIRE(s.get_center() == glm::vec3{0.0f});
}
TEST_CASE("area","[sphere]")
{
Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
REQUIRE(12.566f == Approx(s.area()).epsilon(0.001));
}
TEST_CASE("volume","[sphere]")
{
Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
REQUIRE(4.189 == Approx(s.volume()).epsilon(0.001));
}
TEST_CASE("print sphere","[sphere]")
{
Sphere es {"empty_sphere"};
std::cout << es;
Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
std::cout << s;
}
// ----------------------------------
// BOX TESTS
// ----------------------------------
TEST_CASE("constructors of box","[box]")
{
Box b1 {"name"};
Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};
REQUIRE(b1.get_min() == b2.get_min());
REQUIRE(b1.get_max() == b2.get_max());
}
TEST_CASE("get_min and get_max","[box]")
{
Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};
REQUIRE(b2.get_min() == glm::vec3{0.0f});
REQUIRE(b2.get_max() == glm::vec3{1.0f});
}
TEST_CASE("area of box","[box]")
{
Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};
REQUIRE(6.0f == Approx(b2.area()).epsilon(0.001));
}
TEST_CASE("volume of box","[box]")
{
Box b2 {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}};
REQUIRE(1.0f == Approx(b2.volume()).epsilon(0.001));
}
TEST_CASE("print box","[box]")
{
Box eb {"empty_box"};
std::cout << eb;
Box b {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}};
std::cout << b;
}
// ----------------------------------
// AUFGABE 5.6 TEST
// ----------------------------------
TEST_CASE("intersectRaySphere", "[intersect]")
{
//Ray
glm::vec3 ray_origin{0.0f, 0.0f, 0.0f};
//ray direction has to be normalized !
//you can use:
//v = glm::normalize(some_vector);
glm::vec3 ray_direction{0.0f, 0.0f, 1.0f};
//Sphere
glm::vec3 sphere_center{0.0f, 0.0f, 5.0f};
float sphere_radius{1.0f};
float distance{0.0f};
auto result = glm::intersectRaySphere(
ray_origin, ray_direction,
sphere_center,
sphere_radius * sphere_radius,
distance);
REQUIRE(distance == Approx(4.0f));
Sphere s {"some_sphere", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},
sphere_center, sphere_radius};
Ray r {ray_origin,ray_direction};
s.intersect(r,distance);
REQUIRE(distance == Approx(4.0f));
}
// ----------------------------------
// AUFGABE 5.8 TEST
// ----------------------------------
TEST_CASE("virtual", "[Destructors]")
{
std::cout << "\ntesting virtual and non-virtual construction and destruction\n";
Color c_red {255.0f, 0.0f, 0.0f};
Material red {"", c_red, c_red, c_red, 0.0f};
glm::vec3 position {0.0f,0.0f,0.0f};
std::cout << "Create s1\n";
Sphere* s1 = new Sphere("sphere0",red,position,1.2f);
std::cout << "Create s2\n";
Shape* s2 = new Sphere("sphere1",red,position,1.2f);
std::cout << "Printing objects: \n";
std::cout << *s1;
std::cout << *s2 << "\n";
std::cout << "Delete s1\n";
delete s1;
std::cout << "Delete s2\n";
delete s2;
}
// ----------------------------------
// MATERIAL Tests
// ----------------------------------
TEST_CASE("material in place of color struct", "Material")
{
Color c{0.0f,0.0f,0.0f};
Material mate1 {};
std::cout << mate1;
Material mate2 {"some material",c,c,c,0.0f};
std::cout << mate2;
}
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "base/task.h"
#include "base/waitable_event.h"
#include "chrome/browser/notifications/notifications_prefs_cache.h"
#include "chrome/browser/renderer_host/test/test_render_view_host.h"
#include "chrome/test/testing_profile.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
class DesktopNotificationServiceTest : public RenderViewHostTestHarness {
public:
DesktopNotificationServiceTest()
: event_(false, false),
ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {
}
void LetIOThreadWait() {
event_.Wait();
}
base::WaitableEvent event_;
ScopedRunnableMethodFactory<DesktopNotificationServiceTest> method_factory_;
};
TEST_F(DesktopNotificationServiceTest, DefaultContentSettingSentToCache) {
// The current message loop was already initalized by the superclass.
ChromeThread ui_thread(ChromeThread::UI, MessageLoop::current());
// Create IO thread, start its message loop.
ChromeThread io_thread(ChromeThread::IO);
io_thread.Start();
ChromeThread::PostTask(ChromeThread::UI, FROM_HERE,
method_factory_.NewRunnableMethod(
&DesktopNotificationServiceTest::LetIOThreadWait));
// Creates the service, calls InitPrefs() on it which loads data from the
// profile into the cache and then puts the cache in io thread mode.
DesktopNotificationService* service =
profile()->GetDesktopNotificationService();
NotificationsPrefsCache* cache = service->prefs_cache();
// The default pref registered in DesktopNotificationService is "ask",
// and that's what sent to the cache.
EXPECT_EQ(CONTENT_SETTING_ASK, cache->CachedDefaultContentSetting());
// Change the default content setting. This will post a task on the IO thread
// to update the cache.
service->SetDefaultContentSetting(CONTENT_SETTING_BLOCK);
// The updated pref shouldn't be sent to the cache immediately.
EXPECT_EQ(CONTENT_SETTING_ASK, cache->CachedDefaultContentSetting());
// Run IO thread tasks.
event_.Signal();
io_thread.Stop();
// Now that IO thread events have been processed, it should be there.
EXPECT_EQ(CONTENT_SETTING_BLOCK, cache->CachedDefaultContentSetting());
}
<commit_msg>Attempted build fix: Run IO blocking task actually on IO thread.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "base/task.h"
#include "base/waitable_event.h"
#include "chrome/browser/notifications/notifications_prefs_cache.h"
#include "chrome/browser/renderer_host/test/test_render_view_host.h"
#include "chrome/test/testing_profile.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class WaitTask : public Task {
public:
WaitTask(base::WaitableEvent* event)
: event_(event) {
}
virtual void Run() {
event_->Wait();
}
private:
base::WaitableEvent* event_;
};
class DesktopNotificationServiceTest : public RenderViewHostTestHarness {
public:
DesktopNotificationServiceTest()
: event_(false, false) {
}
base::WaitableEvent event_;
};
TEST_F(DesktopNotificationServiceTest, DefaultContentSettingSentToCache) {
// The current message loop was already initalized by the superclass.
ChromeThread ui_thread(ChromeThread::UI, MessageLoop::current());
// Create IO thread, start its message loop.
ChromeThread io_thread(ChromeThread::IO);
io_thread.Start();
ChromeThread::PostTask(ChromeThread::IO, FROM_HERE, new WaitTask(&event_));
// Creates the service, calls InitPrefs() on it which loads data from the
// profile into the cache and then puts the cache in io thread mode.
DesktopNotificationService* service =
profile()->GetDesktopNotificationService();
NotificationsPrefsCache* cache = service->prefs_cache();
// The default pref registered in DesktopNotificationService is "ask",
// and that's what sent to the cache.
EXPECT_EQ(CONTENT_SETTING_ASK, cache->CachedDefaultContentSetting());
// Change the default content setting. This will post a task on the IO thread
// to update the cache.
service->SetDefaultContentSetting(CONTENT_SETTING_BLOCK);
// The updated pref shouldn't be sent to the cache immediately.
EXPECT_EQ(CONTENT_SETTING_ASK, cache->CachedDefaultContentSetting());
// Run IO thread tasks.
event_.Signal();
io_thread.Stop();
// Now that IO thread events have been processed, it should be there.
EXPECT_EQ(CONTENT_SETTING_BLOCK, cache->CachedDefaultContentSetting());
}
} // namespace
<|endoftext|>
|
<commit_before>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2019 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @example
#include <algorithm>
#include <cmath>
#include <omp.h>
#include <DO/Sara/Core.hpp>
#include <DO/Sara/Graphics.hpp>
#include <DO/Sara/ImageIO.hpp>
#include <DO/Sara/VideoIO.hpp>
#include <drafts/Halide/Draw.hpp>
#include <drafts/Halide/SIFTPipeline.hpp>
#include "shakti_halide_rgb_to_gray.h"
namespace sara = DO::Sara;
namespace halide = DO::Shakti::HalideBackend;
auto test_on_image()
{
const auto image_filepath =
#ifdef __APPLE__
"/Users/david/GitLab/DO-CV/sara/data/sunflowerField.jpg";
#else
"/home/david/GitLab/DO-CV/sara/data/sunflowerField.jpg";
#endif
auto image = sara::imread<float>(image_filepath);
auto image_tensor = tensor_view(image).reshape(
Eigen::Vector4i{1, 1, image.height(), image.width()});
auto buffer_4d = halide::as_runtime_buffer(image_tensor);
auto sift_pipeline = halide::v2::SiftPyramidPipeline{};
sift_pipeline.initialize(-1, image.width(), image.height());
auto timer = sara::Timer{};
timer.restart();
{
buffer_4d.set_host_dirty();
sift_pipeline.feed(buffer_4d);
}
const auto elapsed_ms = timer.elapsed_ms();
SARA_DEBUG << "SIFT pipeline: " << elapsed_ms << " ms" << std::endl;
#ifdef CHECK_INPUT_UPSCALED
if (sift_pipeline.start_octave_index < 0)
{
auto input_upscaled = sift_pipeline.input_upscaled_view();
sara::create_window(input_upscaled.sizes());
sara::display(input_upscaled);
sara::get_key();
sara::resize_window(image.sizes());
}
#endif
if (!sara::active_window())
sara::create_window(image.sizes());
// #define CHECK_PYRAMIDS
#ifdef CHECK_PYRAMIDS
for (auto& octave : sift_pipeline.octaves)
for (auto s = 0; s < octave.params.num_scales + 3; ++s)
sara::display(octave.gaussian_view(s));
sara::get_key();
for (auto& octave : sift_pipeline.octaves)
for (auto s = 0; s < octave.params.num_scales + 2; ++s)
{
sara::display(sara::color_rescale(octave.dog_view(s)));
sara::get_key();
}
sara::get_key();
#endif
sara::set_antialiasing();
sara::display(image);
for (auto o = 0u; o < sift_pipeline.octaves.size(); ++o)
{
auto& octave = sift_pipeline.octaves[o];
for (auto s = 0u; s < octave.extrema_oriented.size(); ++s)
{
SARA_DEBUG << sara::format("[o = %d, s = %d] Num extrema = %d",
sift_pipeline.start_octave_index + o, s,
octave.extrema_oriented[s].size())
<< std::endl;
draw_oriented_extrema(octave.extrema_oriented[s],
sift_pipeline.octave_scaling_factor(
sift_pipeline.start_octave_index + o));
}
}
while (sara::get_key() != sara::KEY_ESCAPE)
;
}
auto test_on_video(int argc, char **argv)
{
using namespace std::string_literals;
#ifdef _WIN32
const auto video_filepath = "C:/Users/David/Desktop/GOPR0542.MP4"s;
#elif __APPLE__
const auto
video_filepath = //"/Users/david/Desktop/Datasets/sfm/Family.mp4"s;
"/Users/david/Desktop/Datasets/videos/sample10.mp4"s;
#else
const auto video_filepath =
argc < 2 ? "/home/david/Desktop/Datasets/sfm/Family.mp4"s
: std::string{argv[1]};
#endif
// ===========================================================================
// SARA PIPELINE
//
// Input and output from Sara.
sara::VideoStream video_stream(video_filepath);
auto frame = video_stream.frame();
auto frame_gray = sara::Image<float>{frame.sizes()};
auto frame_gray_tensor =
tensor_view(frame_gray)
.reshape(
Eigen::Vector4i{1, 1, frame_gray.height(), frame_gray.width()});
// ===========================================================================
// HALIDE PIPELINE.
//
// RGB-grayscale conversion.
auto buffer_rgb = halide::as_interleaved_runtime_buffer(frame);
auto buffer_gray = halide::as_runtime_buffer(frame_gray);
auto buffer_gray_4d = halide::as_runtime_buffer(frame_gray_tensor);
auto sift_pipeline = halide::v2::SiftPyramidPipeline{};
const auto start_octave_index = 0;
sift_pipeline.initialize(start_octave_index, frame.width(), frame.height());
// Show the local extrema.
sara::create_window(frame.sizes());
sara::set_antialiasing();
auto frames_read = 0;
auto timer = sara::Timer{};
auto elapsed_ms = double{};
while (true)
{
sara::tic();
if (!video_stream.read())
{
std::cout << "Reached the end of the video!" << std::endl;
break;
}
sara::toc("Video Decoding");
++frames_read;
SARA_CHECK(frames_read);
// if(frames_read % 3 != 0)
// continue;
timer.restart();
{
sara::tic();
shakti_halide_rgb_to_gray(buffer_rgb, buffer_gray);
sara::toc("CPU RGB to grayscale");
buffer_gray_4d.set_host_dirty();
sift_pipeline.feed(buffer_gray_4d);
}
elapsed_ms = timer.elapsed_ms();
SARA_DEBUG << "[Frame: " << frames_read << "] "
<< "total computation time = " << elapsed_ms << " ms"
<< std::endl;
sara::tic();
for (auto o = 0u; o < sift_pipeline.octaves.size(); ++o)
{
auto& octave = sift_pipeline.octaves[o];
for (auto s = 0u; s < octave.extrema_oriented.size(); ++s)
draw_oriented_extrema(frame, octave.extrema_oriented[s],
sift_pipeline.octave_scaling_factor(
sift_pipeline.start_octave_index + o));
}
sara::display(frame);
sara::toc("Display");
}
}
int __main(int argc, char** argv)
{
// Optimization.
omp_set_num_threads(omp_get_max_threads());
std::ios_base::sync_with_stdio(false);
// test_on_image();
test_on_video(argc, argv);
return 0;
}
int main(int argc, char** argv)
{
DO::Sara::GraphicsApplication app(argc, argv);
app.register_user_main(__main);
return app.exec();
}
<commit_msg>MAINT: fix compiler warning.<commit_after>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2019 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //
//! @example
#include <algorithm>
#include <cmath>
#include <omp.h>
#include <DO/Sara/Core.hpp>
#include <DO/Sara/Graphics.hpp>
#include <DO/Sara/ImageIO.hpp>
#include <DO/Sara/VideoIO.hpp>
#include <drafts/Halide/Draw.hpp>
#include <drafts/Halide/SIFTPipeline.hpp>
#include "shakti_halide_rgb_to_gray.h"
namespace sara = DO::Sara;
namespace halide = DO::Shakti::HalideBackend;
auto test_on_image()
{
const auto image_filepath =
#ifdef __APPLE__
"/Users/david/GitLab/DO-CV/sara/data/sunflowerField.jpg";
#else
"/home/david/GitLab/DO-CV/sara/data/sunflowerField.jpg";
#endif
auto image = sara::imread<float>(image_filepath);
auto image_tensor = tensor_view(image).reshape(
Eigen::Vector4i{1, 1, image.height(), image.width()});
auto buffer_4d = halide::as_runtime_buffer(image_tensor);
auto sift_pipeline = halide::v2::SiftPyramidPipeline{};
sift_pipeline.initialize(-1, image.width(), image.height());
auto timer = sara::Timer{};
timer.restart();
{
buffer_4d.set_host_dirty();
sift_pipeline.feed(buffer_4d);
}
const auto elapsed_ms = timer.elapsed_ms();
SARA_DEBUG << "SIFT pipeline: " << elapsed_ms << " ms" << std::endl;
#ifdef CHECK_INPUT_UPSCALED
if (sift_pipeline.start_octave_index < 0)
{
auto input_upscaled = sift_pipeline.input_upscaled_view();
sara::create_window(input_upscaled.sizes());
sara::display(input_upscaled);
sara::get_key();
sara::resize_window(image.sizes());
}
#endif
if (!sara::active_window())
sara::create_window(image.sizes());
// #define CHECK_PYRAMIDS
#ifdef CHECK_PYRAMIDS
for (auto& octave : sift_pipeline.octaves)
for (auto s = 0; s < octave.params.num_scales + 3; ++s)
sara::display(octave.gaussian_view(s));
sara::get_key();
for (auto& octave : sift_pipeline.octaves)
for (auto s = 0; s < octave.params.num_scales + 2; ++s)
{
sara::display(sara::color_rescale(octave.dog_view(s)));
sara::get_key();
}
sara::get_key();
#endif
sara::set_antialiasing();
sara::display(image);
for (auto o = 0u; o < sift_pipeline.octaves.size(); ++o)
{
auto& octave = sift_pipeline.octaves[o];
for (auto s = 0u; s < octave.extrema_oriented.size(); ++s)
{
SARA_DEBUG << sara::format("[o = %d, s = %d] Num extrema = %d",
sift_pipeline.start_octave_index + o, s,
octave.extrema_oriented[s].size())
<< std::endl;
draw_oriented_extrema(octave.extrema_oriented[s],
sift_pipeline.octave_scaling_factor(
sift_pipeline.start_octave_index + o));
}
}
while (sara::get_key() != sara::KEY_ESCAPE)
;
}
auto test_on_video(int argc, char **argv)
{
using namespace std::string_literals;
#ifdef _WIN32
const auto video_filepath =
argc < 2 ? "C:/Users/David/Desktop/GOPR0542.MP4"s
: std::string{argv[1]};
#elif __APPLE__
const auto video_filepath =
argc < 2 ? "/Users/david/Desktop/Datasets/videos/sample10.mp4"s
: std::string{argv[1]};
#else
const auto video_filepath =
argc < 2 ? "/home/david/Desktop/Datasets/sfm/Family.mp4"s
: std::string{argv[1]};
#endif
// ===========================================================================
// SARA PIPELINE
//
// Input and output from Sara.
sara::VideoStream video_stream(video_filepath);
auto frame = video_stream.frame();
auto frame_gray = sara::Image<float>{frame.sizes()};
auto frame_gray_tensor =
tensor_view(frame_gray)
.reshape(
Eigen::Vector4i{1, 1, frame_gray.height(), frame_gray.width()});
// ===========================================================================
// HALIDE PIPELINE.
//
// RGB-grayscale conversion.
auto buffer_rgb = halide::as_interleaved_runtime_buffer(frame);
auto buffer_gray = halide::as_runtime_buffer(frame_gray);
auto buffer_gray_4d = halide::as_runtime_buffer(frame_gray_tensor);
auto sift_pipeline = halide::v2::SiftPyramidPipeline{};
const auto start_octave_index = 0;
sift_pipeline.initialize(start_octave_index, frame.width(), frame.height());
// Show the local extrema.
sara::create_window(frame.sizes());
sara::set_antialiasing();
auto frames_read = 0;
auto timer = sara::Timer{};
auto elapsed_ms = double{};
while (true)
{
sara::tic();
if (!video_stream.read())
{
std::cout << "Reached the end of the video!" << std::endl;
break;
}
sara::toc("Video Decoding");
++frames_read;
SARA_CHECK(frames_read);
// if(frames_read % 3 != 0)
// continue;
timer.restart();
{
sara::tic();
shakti_halide_rgb_to_gray(buffer_rgb, buffer_gray);
sara::toc("CPU RGB to grayscale");
buffer_gray_4d.set_host_dirty();
sift_pipeline.feed(buffer_gray_4d);
}
elapsed_ms = timer.elapsed_ms();
SARA_DEBUG << "[Frame: " << frames_read << "] "
<< "total computation time = " << elapsed_ms << " ms"
<< std::endl;
sara::tic();
for (auto o = 0u; o < sift_pipeline.octaves.size(); ++o)
{
auto& octave = sift_pipeline.octaves[o];
for (auto s = 0u; s < octave.extrema_oriented.size(); ++s)
draw_oriented_extrema(frame, octave.extrema_oriented[s],
sift_pipeline.octave_scaling_factor(
sift_pipeline.start_octave_index + o));
}
sara::display(frame);
sara::toc("Display");
}
}
int __main(int argc, char** argv)
{
// Optimization.
omp_set_num_threads(omp_get_max_threads());
std::ios_base::sync_with_stdio(false);
// test_on_image();
test_on_video(argc, argv);
return 0;
}
int main(int argc, char** argv)
{
DO::Sara::GraphicsApplication app(argc, argv);
app.register_user_main(__main);
return app.exec();
}
<|endoftext|>
|
<commit_before>void sink(const char *);
void sink(int);
struct S {
void(*f)(const char*);
void apply(char* p) {
f(p);
}
void (*get())(const char*) {
return f;
}
};
void calls_sink_with_argv(const char* a) {
sink(a);
}
extern int i;
class BaseWithPureVirtual {
public:
virtual void f(const char*) = 0;
};
class DerivedCallsSink : public BaseWithPureVirtual {
public:
void f(const char* p) override {
sink(p);
}
};
class DerivedDoesNotCallSink : public BaseWithPureVirtual {
public:
void f(const char* p) override {}
};
class DerivedCallsSinkDiamond1 : virtual public BaseWithPureVirtual {
public:
void f(const char* p) override {
sink(p);
}
};
class DerivedDoesNotCallSinkDiamond2 : virtual public BaseWithPureVirtual {
public:
void f(const char* p) override {}
};
class DerivesMultiple : public DerivedCallsSinkDiamond1, public DerivedDoesNotCallSinkDiamond2 {
void f(const char* p) override {
DerivedCallsSinkDiamond1::f(p);
}
};
template<typename T>
class CRTP {
public:
void f(const char* p) {
static_cast<T*>(this)->g(p);
}
};
class CRTPCallsSink : public CRTP<CRTPCallsSink> {
public:
void g(const char* p) {
sink(p);
}
};
class Derived1 : public BaseWithPureVirtual {};
class Derived2 : public Derived1 {
public:
void f(const char* p) override {}
};
class Derived3 : public Derived2 {
public:
void f(const char* p) override {
sink(p);
}
};
class CRTPDoesNotCallSink : public CRTP<CRTPDoesNotCallSink> {
public:
void g(const char* p) {}
};
int main(int argc, char *argv[]) {
sink(argv[0]);
sink(reinterpret_cast<int>(argv));
calls_sink_with_argv(argv[1]);
char*** p = &argv;
sink(*p[0]);
calls_sink_with_argv(*p[i]);
sink(*(argv + 1)); // flow [NOT DECTED by AST]
BaseWithPureVirtual* b = new DerivedCallsSink;
b->f(argv[1]); // flow [NOT DETECTED by IR]
b = new DerivedDoesNotCallSink;
b->f(argv[0]); // no flow [FALSE POSITIVE by AST]
BaseWithPureVirtual* b2 = new DerivesMultiple;
b2->f(argv[i]); // flow [NOT DETECTED]
CRTP<CRTPDoesNotCallSink> crtp_not_call_sink;
crtp_not_call_sink.f(argv[0]);
CRTP<CRTPCallsSink> crtp_calls_sink;
crtp_calls_sink.f(argv[0]); // flow [NOT DETECTED]
Derived1* calls_sink = new Derived3;
calls_sink->f(argv[1]); // flow [NOT DETECTED by AST]
static_cast<Derived2*>(calls_sink)->f(argv[1]); // flow [NOT DETECTED]
dynamic_cast<Derived2*>(calls_sink)->f(argv[1]); // flow [NOT DETECTED by IR]
}<commit_msg>C++: Fix annotations in testcase file<commit_after>void sink(const char *);
void sink(int);
struct S {
void(*f)(const char*);
void apply(char* p) {
f(p);
}
void (*get())(const char*) {
return f;
}
};
void calls_sink_with_argv(const char* a) {
sink(a);
}
extern int i;
class BaseWithPureVirtual {
public:
virtual void f(const char*) = 0;
};
class DerivedCallsSink : public BaseWithPureVirtual {
public:
void f(const char* p) override {
sink(p);
}
};
class DerivedDoesNotCallSink : public BaseWithPureVirtual {
public:
void f(const char* p) override {}
};
class DerivedCallsSinkDiamond1 : virtual public BaseWithPureVirtual {
public:
void f(const char* p) override {
sink(p);
}
};
class DerivedDoesNotCallSinkDiamond2 : virtual public BaseWithPureVirtual {
public:
void f(const char* p) override {}
};
class DerivesMultiple : public DerivedCallsSinkDiamond1, public DerivedDoesNotCallSinkDiamond2 {
void f(const char* p) override {
DerivedCallsSinkDiamond1::f(p);
}
};
template<typename T>
class CRTP {
public:
void f(const char* p) {
static_cast<T*>(this)->g(p);
}
};
class CRTPCallsSink : public CRTP<CRTPCallsSink> {
public:
void g(const char* p) {
sink(p);
}
};
class Derived1 : public BaseWithPureVirtual {};
class Derived2 : public Derived1 {
public:
void f(const char* p) override {}
};
class Derived3 : public Derived2 {
public:
void f(const char* p) override {
sink(p);
}
};
class CRTPDoesNotCallSink : public CRTP<CRTPDoesNotCallSink> {
public:
void g(const char* p) {}
};
int main(int argc, char *argv[]) {
sink(argv[0]);
sink(reinterpret_cast<int>(argv));
calls_sink_with_argv(argv[1]);
char*** p = &argv;
sink(*p[0]);
calls_sink_with_argv(*p[i]);
sink(*(argv + 1));
BaseWithPureVirtual* b = new DerivedCallsSink;
b->f(argv[1]);
b = new DerivedDoesNotCallSink;
b->f(argv[0]); // no flow [FALSE POSITIVE by AST]
BaseWithPureVirtual* b2 = new DerivesMultiple;
b2->f(argv[i]);
CRTP<CRTPDoesNotCallSink> crtp_not_call_sink;
crtp_not_call_sink.f(argv[0]);
CRTP<CRTPCallsSink> crtp_calls_sink;
crtp_calls_sink.f(argv[0]);
Derived1* calls_sink = new Derived3;
calls_sink->f(argv[1]);
static_cast<Derived2*>(calls_sink)->f(argv[1]);
dynamic_cast<Derived2*>(calls_sink)->f(argv[1]); // flow [NOT DETECTED by IR]
}<|endoftext|>
|
<commit_before>/* Copyright (C) 1995-2002 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/**********************************************************************
This file contains the implementation of error and warnings related
- Whenever an error or warning occurred, it pushes it to a warning list
that the user can retrieve with SHOW WARNINGS or SHOW ERRORS.
- For each statement, we return the number of warnings generated from this
command. Note that this can be different from @@warning_count as
we reset the warning list only for questions that uses a table.
This is done to allow on to do:
INSERT ...;
SELECT @@warning_count;
SHOW WARNINGS;
(If we would reset after each command, we could not retrieve the number
of warnings)
- When client requests the information using SHOW command, then
server processes from this list and returns back in the form of
resultset.
Supported syntaxes:
SHOW [COUNT(*)] ERRORS [LIMIT [offset,] rows]
SHOW [COUNT(*)] WARNINGS [LIMIT [offset,] rows]
SELECT @@warning_count, @@error_count;
***********************************************************************/
#include "mysql_priv.h"
#include "sp_rcontext.h"
/*
Store a new message in an error object
This is used to in group_concat() to register how many warnings we actually
got after the query has been executed.
*/
void MYSQL_ERROR::set_msg(THD *thd, const char *msg_arg)
{
msg= strdup_root(&thd->warn_root, msg_arg);
}
/*
Reset all warnings for the thread
SYNOPSIS
mysql_reset_errors()
thd Thread handle
force Reset warnings even if it has been done before
IMPLEMENTATION
Don't reset warnings if this has already been called for this query.
This may happen if one gets a warning during the parsing stage,
in which case push_warnings() has already called this function.
*/
void mysql_reset_errors(THD *thd, bool force)
{
DBUG_ENTER("mysql_reset_errors");
if (thd->query_id != thd->warn_id || force)
{
thd->warn_id= thd->query_id;
free_root(&thd->warn_root,MYF(0));
bzero((char*) thd->warn_count, sizeof(thd->warn_count));
if (force)
thd->total_warn_count= 0;
thd->warn_list.empty();
thd->row_count= 1; // by default point to row 1
}
DBUG_VOID_RETURN;
}
/*
Push the warning/error to error list if there is still room in the list
SYNOPSIS
push_warning()
thd Thread handle
level Severity of warning (note, warning, error ...)
code Error number
msg Clear error message
RETURN
pointer on MYSQL_ERROR object
*/
MYSQL_ERROR *push_warning(THD *thd, MYSQL_ERROR::enum_warning_level level,
uint code, const char *msg)
{
MYSQL_ERROR *err= 0;
DBUG_ENTER("push_warning");
if (level == MYSQL_ERROR::WARN_LEVEL_NOTE &&
!(thd->options & OPTION_SQL_NOTES))
DBUG_RETURN(0);
if (thd->query_id != thd->warn_id && !thd->spcont)
mysql_reset_errors(thd, 0);
thd->got_warning= 1;
/* Abort if we are using strict mode and we are not using IGNORE */
if ((int) level >= (int) MYSQL_ERROR::WARN_LEVEL_WARN &&
thd->really_abort_on_warning())
{
/* Avoid my_message() calling push_warning */
bool no_warnings_for_error= thd->no_warnings_for_error;
sp_rcontext *spcont= thd->spcont;
thd->no_warnings_for_error= 1;
thd->spcont= 0;
thd->killed= THD::KILL_BAD_DATA;
my_message(code, msg, MYF(0));
thd->spcont= spcont;
thd->no_warnings_for_error= no_warnings_for_error;
/* Store error in error list (as my_message() didn't do it) */
level= MYSQL_ERROR::WARN_LEVEL_ERROR;
}
if (thd->spcont &&
thd->spcont->find_handler(code,
((int) level >=
(int) MYSQL_ERROR::WARN_LEVEL_WARN &&
thd->really_abort_on_warning()) ?
MYSQL_ERROR::WARN_LEVEL_ERROR : level))
{
if (! thd->spcont->found_handler_here())
thd->net.report_error= 1; /* Make "select" abort correctly */
DBUG_RETURN(NULL);
}
query_cache_abort(&thd->net);
if (thd->warn_list.elements < thd->variables.max_error_count)
{
/*
The following code is here to change the allocation to not
use the thd->mem_root, which is freed after each query
*/
MEM_ROOT *old_root= thd->mem_root;
thd->mem_root= &thd->warn_root;
if ((err= new MYSQL_ERROR(thd, code, level, msg)))
thd->warn_list.push_back(err);
thd->mem_root= old_root;
}
thd->warn_count[(uint) level]++;
thd->total_warn_count++;
DBUG_RETURN(err);
}
/*
Push the warning/error to error list if there is still room in the list
SYNOPSIS
push_warning_printf()
thd Thread handle
level Severity of warning (note, warning, error ...)
code Error number
msg Clear error message
*/
void push_warning_printf(THD *thd, MYSQL_ERROR::enum_warning_level level,
uint code, const char *format, ...)
{
va_list args;
char warning[ERRMSGSIZE+20];
DBUG_ENTER("push_warning_printf");
DBUG_PRINT("enter",("warning: %u", code));
va_start(args,format);
my_vsnprintf(warning, sizeof(warning), format, args);
va_end(args);
push_warning(thd, level, code, warning);
DBUG_VOID_RETURN;
}
/*
Send all notes, errors or warnings to the client in a result set
SYNOPSIS
mysqld_show_warnings()
thd Thread handler
levels_to_show Bitmap for which levels to show
DESCRIPTION
Takes into account the current LIMIT
RETURN VALUES
FALSE ok
TRUE Error sending data to client
*/
static const char *warning_level_names[]= {"Note", "Warning", "Error", "?"};
static int warning_level_length[]= { 4, 7, 5, 1 };
bool mysqld_show_warnings(THD *thd, ulong levels_to_show)
{
List<Item> field_list;
DBUG_ENTER("mysqld_show_warnings");
field_list.push_back(new Item_empty_string("Level", 7));
field_list.push_back(new Item_return_int("Code",4, MYSQL_TYPE_LONG));
field_list.push_back(new Item_empty_string("Message",MYSQL_ERRMSG_SIZE));
if (thd->protocol->send_fields(&field_list,
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
DBUG_RETURN(TRUE);
MYSQL_ERROR *err;
SELECT_LEX *sel= &thd->lex->select_lex;
SELECT_LEX_UNIT *unit= &thd->lex->unit;
ha_rows idx= 0;
Protocol *protocol=thd->protocol;
unit->set_limit(sel);
List_iterator_fast<MYSQL_ERROR> it(thd->warn_list);
while ((err= it++))
{
/* Skip levels that the user is not interested in */
if (!(levels_to_show & ((ulong) 1 << err->level)))
continue;
if (++idx <= unit->offset_limit_cnt)
continue;
if (idx > unit->select_limit_cnt)
break;
protocol->prepare_for_resend();
protocol->store(warning_level_names[err->level],
warning_level_length[err->level], system_charset_info);
protocol->store((uint32) err->code);
protocol->store(err->msg, strlen(err->msg), system_charset_info);
if (protocol->write())
DBUG_RETURN(TRUE);
}
send_eof(thd);
DBUG_RETURN(FALSE);
}
<commit_msg>Add extre DBUG_PRINT in push_warning<commit_after>/* Copyright (C) 1995-2002 MySQL AB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/**********************************************************************
This file contains the implementation of error and warnings related
- Whenever an error or warning occurred, it pushes it to a warning list
that the user can retrieve with SHOW WARNINGS or SHOW ERRORS.
- For each statement, we return the number of warnings generated from this
command. Note that this can be different from @@warning_count as
we reset the warning list only for questions that uses a table.
This is done to allow on to do:
INSERT ...;
SELECT @@warning_count;
SHOW WARNINGS;
(If we would reset after each command, we could not retrieve the number
of warnings)
- When client requests the information using SHOW command, then
server processes from this list and returns back in the form of
resultset.
Supported syntaxes:
SHOW [COUNT(*)] ERRORS [LIMIT [offset,] rows]
SHOW [COUNT(*)] WARNINGS [LIMIT [offset,] rows]
SELECT @@warning_count, @@error_count;
***********************************************************************/
#include "mysql_priv.h"
#include "sp_rcontext.h"
/*
Store a new message in an error object
This is used to in group_concat() to register how many warnings we actually
got after the query has been executed.
*/
void MYSQL_ERROR::set_msg(THD *thd, const char *msg_arg)
{
msg= strdup_root(&thd->warn_root, msg_arg);
}
/*
Reset all warnings for the thread
SYNOPSIS
mysql_reset_errors()
thd Thread handle
force Reset warnings even if it has been done before
IMPLEMENTATION
Don't reset warnings if this has already been called for this query.
This may happen if one gets a warning during the parsing stage,
in which case push_warnings() has already called this function.
*/
void mysql_reset_errors(THD *thd, bool force)
{
DBUG_ENTER("mysql_reset_errors");
if (thd->query_id != thd->warn_id || force)
{
thd->warn_id= thd->query_id;
free_root(&thd->warn_root,MYF(0));
bzero((char*) thd->warn_count, sizeof(thd->warn_count));
if (force)
thd->total_warn_count= 0;
thd->warn_list.empty();
thd->row_count= 1; // by default point to row 1
}
DBUG_VOID_RETURN;
}
/*
Push the warning/error to error list if there is still room in the list
SYNOPSIS
push_warning()
thd Thread handle
level Severity of warning (note, warning, error ...)
code Error number
msg Clear error message
RETURN
pointer on MYSQL_ERROR object
*/
MYSQL_ERROR *push_warning(THD *thd, MYSQL_ERROR::enum_warning_level level,
uint code, const char *msg)
{
MYSQL_ERROR *err= 0;
DBUG_ENTER("push_warning");
DBUG_PRINT("enter", ("code: %d, msg: %s", code, msg));
if (level == MYSQL_ERROR::WARN_LEVEL_NOTE &&
!(thd->options & OPTION_SQL_NOTES))
DBUG_RETURN(0);
if (thd->query_id != thd->warn_id && !thd->spcont)
mysql_reset_errors(thd, 0);
thd->got_warning= 1;
/* Abort if we are using strict mode and we are not using IGNORE */
if ((int) level >= (int) MYSQL_ERROR::WARN_LEVEL_WARN &&
thd->really_abort_on_warning())
{
/* Avoid my_message() calling push_warning */
bool no_warnings_for_error= thd->no_warnings_for_error;
sp_rcontext *spcont= thd->spcont;
thd->no_warnings_for_error= 1;
thd->spcont= 0;
thd->killed= THD::KILL_BAD_DATA;
my_message(code, msg, MYF(0));
thd->spcont= spcont;
thd->no_warnings_for_error= no_warnings_for_error;
/* Store error in error list (as my_message() didn't do it) */
level= MYSQL_ERROR::WARN_LEVEL_ERROR;
}
if (thd->spcont &&
thd->spcont->find_handler(code,
((int) level >=
(int) MYSQL_ERROR::WARN_LEVEL_WARN &&
thd->really_abort_on_warning()) ?
MYSQL_ERROR::WARN_LEVEL_ERROR : level))
{
if (! thd->spcont->found_handler_here())
thd->net.report_error= 1; /* Make "select" abort correctly */
DBUG_RETURN(NULL);
}
query_cache_abort(&thd->net);
if (thd->warn_list.elements < thd->variables.max_error_count)
{
/*
The following code is here to change the allocation to not
use the thd->mem_root, which is freed after each query
*/
MEM_ROOT *old_root= thd->mem_root;
thd->mem_root= &thd->warn_root;
if ((err= new MYSQL_ERROR(thd, code, level, msg)))
thd->warn_list.push_back(err);
thd->mem_root= old_root;
}
thd->warn_count[(uint) level]++;
thd->total_warn_count++;
DBUG_RETURN(err);
}
/*
Push the warning/error to error list if there is still room in the list
SYNOPSIS
push_warning_printf()
thd Thread handle
level Severity of warning (note, warning, error ...)
code Error number
msg Clear error message
*/
void push_warning_printf(THD *thd, MYSQL_ERROR::enum_warning_level level,
uint code, const char *format, ...)
{
va_list args;
char warning[ERRMSGSIZE+20];
DBUG_ENTER("push_warning_printf");
DBUG_PRINT("enter",("warning: %u", code));
va_start(args,format);
my_vsnprintf(warning, sizeof(warning), format, args);
va_end(args);
push_warning(thd, level, code, warning);
DBUG_VOID_RETURN;
}
/*
Send all notes, errors or warnings to the client in a result set
SYNOPSIS
mysqld_show_warnings()
thd Thread handler
levels_to_show Bitmap for which levels to show
DESCRIPTION
Takes into account the current LIMIT
RETURN VALUES
FALSE ok
TRUE Error sending data to client
*/
static const char *warning_level_names[]= {"Note", "Warning", "Error", "?"};
static int warning_level_length[]= { 4, 7, 5, 1 };
bool mysqld_show_warnings(THD *thd, ulong levels_to_show)
{
List<Item> field_list;
DBUG_ENTER("mysqld_show_warnings");
field_list.push_back(new Item_empty_string("Level", 7));
field_list.push_back(new Item_return_int("Code",4, MYSQL_TYPE_LONG));
field_list.push_back(new Item_empty_string("Message",MYSQL_ERRMSG_SIZE));
if (thd->protocol->send_fields(&field_list,
Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
DBUG_RETURN(TRUE);
MYSQL_ERROR *err;
SELECT_LEX *sel= &thd->lex->select_lex;
SELECT_LEX_UNIT *unit= &thd->lex->unit;
ha_rows idx= 0;
Protocol *protocol=thd->protocol;
unit->set_limit(sel);
List_iterator_fast<MYSQL_ERROR> it(thd->warn_list);
while ((err= it++))
{
/* Skip levels that the user is not interested in */
if (!(levels_to_show & ((ulong) 1 << err->level)))
continue;
if (++idx <= unit->offset_limit_cnt)
continue;
if (idx > unit->select_limit_cnt)
break;
protocol->prepare_for_resend();
protocol->store(warning_level_names[err->level],
warning_level_length[err->level], system_charset_info);
protocol->store((uint32) err->code);
protocol->store(err->msg, strlen(err->msg), system_charset_info);
if (protocol->write())
DBUG_RETURN(TRUE);
}
send_eof(thd);
DBUG_RETURN(FALSE);
}
<|endoftext|>
|
<commit_before>#include "cvolumeenumerator.h"
#include "volumeinfohelper.hpp"
DISABLE_COMPILER_WARNINGS
#include <QDir>
RESTORE_COMPILER_WARNINGS
const std::vector<VolumeInfo> CVolumeEnumerator::enumerateVolumesImpl()
{
std::vector<VolumeInfo> volumes;
for (const QString& volumeName: QDir("/Volumes/").entryList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Hidden | QDir::System))
{
VolumeInfo info;
info.rootObjectInfo = "/Volumes/" + volumeName;
info.volumeLabel = volumeName;
info.isReady = true;
const auto sys_info = volumeInfoForPath(info.rootObjectInfo.fullAbsolutePath());
info.volumeSize = sys_info.f_bsize * sys_info.f_blocks;
info.freeSize = sys_info.f_bsize * sys_info.f_bavail;
info.fileSystemName = QString(sys_info.f_fstypename).toUpper();
volumes.emplace_back(std::move(info));
}
return volumes;
}
<commit_msg>CVolumeEnumerator::enumerateVolumesImpl() improved on Mac<commit_after>#include "cvolumeenumerator.h"
#include "volumeinfohelper.hpp"
DISABLE_COMPILER_WARNINGS
#include <QDir>
RESTORE_COMPILER_WARNINGS
const std::vector<VolumeInfo> CVolumeEnumerator::enumerateVolumesImpl()
{
std::vector<VolumeInfo> volumes;
for (const QString& volumeName: QDir("/Volumes/").entryList(QDir::NoDotAndDotDot | QDir::Dirs | QDir::Hidden | QDir::System))
{
VolumeInfo info;
info.volumeLabel = volumeName;
info.isReady = true;
const auto sys_info = volumeInfoForPath("/Volumes/" + volumeName);
info.rootObjectInfo = sys_info.f_mntonname;
info.volumeSize = sys_info.f_bsize * sys_info.f_blocks;
info.freeSize = sys_info.f_bsize * sys_info.f_bavail;
info.fileSystemName = QString(sys_info.f_fstypename).toUpper();
volumes.emplace_back(std::move(info));
}
return volumes;
}
<|endoftext|>
|
<commit_before>// Copyright 2021 Google LLC
#include <chrono> // NOLINT(build/c++11)
#include <thread> // NOLINT(build/c++11)
#include "Firestore/core/src/auth/empty_credentials_provider.h"
#include "absl/memory/memory.h"
#include "app_framework.h"
#include "firebase/app.h"
#include "firebase/firestore.h"
#include "firestore/src/common/hard_assert_common.h"
#include "firestore/src/main/firestore_main.h"
namespace firebase {
namespace firestore {
using auth::EmptyCredentialsProvider;
struct TestFriend {
static FirestoreInternal* CreateTestFirestoreInternal(App* app) {
#if !defined(__ANDROID__)
return new FirestoreInternal(app,
absl::make_unique<EmptyCredentialsProvider>());
#else
return new FirestoreInternal(app);
#endif // !defined(__ANDROID__)
}
};
App* GetApp(const char* name) {
// TODO(varconst): try to avoid using a real project ID when possible. iOS
// unit tests achieve this by using fake options:
// https://github.com/firebase/firebase-ios-sdk/blob/9a5afbffc17bb63b7bb7f51b9ea9a6a9e1c88a94/Firestore/core/test/firebase/firestore/testutil/app_testing.mm#L29
if (name == nullptr || std::string{name} == kDefaultAppName) {
#if defined(__ANDROID__)
return App::Create(app_framework::GetJniEnv(),
app_framework::GetActivity());
#else
return App::Create();
#endif // defined(__ANDROID__)
} else {
App* default_app = App::GetInstance();
SIMPLE_HARD_ASSERT(default_app,
"Cannot create a named app before the default app");
#if defined(__ANDROID__)
return App::Create(default_app->options(), name, app_framework::GetJniEnv(),
app_framework::GetActivity());
#else
return App::Create(default_app->options(), name);
#endif // defined(__ANDROID__)
}
}
App* GetApp() { return GetApp(nullptr); }
FirestoreInternal* CreateTestFirestoreInternal(App* app) {
return TestFriend::CreateTestFirestoreInternal(app);
}
void InitializeFirestore(Firestore* instance) {
Firestore::set_log_level(LogLevel::kLogLevelDebug);
}
} // namespace firestore
} // namespace firebase
<commit_msg>Fix ODR violation of FirestoreInternal in integration_test_util.cc (#559)<commit_after>// Copyright 2021 Google LLC
#include <chrono> // NOLINT(build/c++11)
#include <thread> // NOLINT(build/c++11)
#include "Firestore/core/src/auth/empty_credentials_provider.h"
#include "absl/memory/memory.h"
#include "app_framework.h"
#include "firebase/app.h"
#include "firebase/firestore.h"
#include "firestore/src/common/hard_assert_common.h"
#if !defined(__ANDROID__)
#include "firestore/src/main/firestore_main.h"
#else
#include "firestore/src/android/firestore_android.h"
#endif // !defined(__ANDROID__)
namespace firebase {
namespace firestore {
using auth::EmptyCredentialsProvider;
struct TestFriend {
static FirestoreInternal* CreateTestFirestoreInternal(App* app) {
#if !defined(__ANDROID__)
return new FirestoreInternal(app,
absl::make_unique<EmptyCredentialsProvider>());
#else
return new FirestoreInternal(app);
#endif // !defined(__ANDROID__)
}
};
App* GetApp(const char* name) {
// TODO(varconst): try to avoid using a real project ID when possible. iOS
// unit tests achieve this by using fake options:
// https://github.com/firebase/firebase-ios-sdk/blob/9a5afbffc17bb63b7bb7f51b9ea9a6a9e1c88a94/Firestore/core/test/firebase/firestore/testutil/app_testing.mm#L29
if (name == nullptr || std::string{name} == kDefaultAppName) {
#if defined(__ANDROID__)
return App::Create(app_framework::GetJniEnv(),
app_framework::GetActivity());
#else
return App::Create();
#endif // defined(__ANDROID__)
} else {
App* default_app = App::GetInstance();
SIMPLE_HARD_ASSERT(default_app,
"Cannot create a named app before the default app");
#if defined(__ANDROID__)
return App::Create(default_app->options(), name, app_framework::GetJniEnv(),
app_framework::GetActivity());
#else
return App::Create(default_app->options(), name);
#endif // defined(__ANDROID__)
}
}
App* GetApp() { return GetApp(nullptr); }
FirestoreInternal* CreateTestFirestoreInternal(App* app) {
return TestFriend::CreateTestFirestoreInternal(app);
}
void InitializeFirestore(Firestore* instance) {
Firestore::set_log_level(LogLevel::kLogLevelDebug);
}
} // namespace firestore
} // namespace firebase
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) Juergen Riegel (juergen.riegel@web.de) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <App/Document.h>
#include <App/Plane.h>
#include "Part.h"
#include "PartPy.h"
using namespace App;
PROPERTY_SOURCE(App::Part, App::GeoFeatureGroup)
//===========================================================================
// Feature
//===========================================================================
const char* Part::BaseplaneTypes[3] = {"XY-Plane", "XZ-Plane", "YZ-Plane"};
Part::Part(void)
{
ADD_PROPERTY(Type,(""));
ADD_PROPERTY_TYPE(Material, (), 0, App::Prop_None, "Map with material properties");
ADD_PROPERTY_TYPE(Meta, (), 0, App::Prop_None, "Map with additional meta information");
// create the uuid for the document
Base::Uuid id;
ADD_PROPERTY_TYPE(Id, (""), 0, App::Prop_None, "ID (Part-Number) of the Item");
ADD_PROPERTY_TYPE(Uid, (id), 0, App::Prop_None, "UUID of the Item");
// license stuff
ADD_PROPERTY_TYPE(License, ("CC BY 3.0"), 0, App::Prop_None, "License string of the Item");
ADD_PROPERTY_TYPE(LicenseURL, ("http://creativecommons.org/licenses/by/3.0/"), 0, App::Prop_None, "URL to the license text/contract");
// color and apperance
ADD_PROPERTY(Color, (1.0, 1.0, 1.0, 1.0)); // set transparent -> not used
}
Part::~Part(void)
{
}
PyObject *Part::getPyObject()
{
if (PythonObject.is(Py::_None())){
// ref counter is set to 1
PythonObject = Py::Object(new PartPy(this),true);
}
return Py::new_reference_to(PythonObject);
}
// Python feature ---------------------------------------------------------
// Not quit sure yet makeing Part derivable in Python is good Idea!
// JR 2014
//namespace App {
///// @cond DOXERR
//PROPERTY_SOURCE_TEMPLATE(App::PartPython, App::Part)
//template<> const char* App::PartPython::getViewProviderName(void) const {
// return "Gui::ViewProviderPartPython";
//}
//template<> PyObject* App::PartPython::getPyObject(void) {
// if (PythonObject.is(Py::_None())) {
// // ref counter is set to 1
// PythonObject = Py::Object(new FeaturePythonPyT<App::PartPy>(this),true);
// }
// return Py::new_reference_to(PythonObject);
//}
///// @endcond
//
//// explicit template instantiation
//template class AppExport FeaturePythonT<App::Part>;
//}
<commit_msg>App: Part: rename base planes.<commit_after>/***************************************************************************
* Copyright (c) Juergen Riegel (juergen.riegel@web.de) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <App/Document.h>
#include <App/Plane.h>
#include "Part.h"
#include "PartPy.h"
using namespace App;
PROPERTY_SOURCE(App::Part, App::GeoFeatureGroup)
//===========================================================================
// Feature
//===========================================================================
const char* Part::BaseplaneTypes[3] = {"XY_Plane", "XZ_Plane", "YZ_Plane"};
Part::Part(void)
{
ADD_PROPERTY(Type,(""));
ADD_PROPERTY_TYPE(Material, (), 0, App::Prop_None, "Map with material properties");
ADD_PROPERTY_TYPE(Meta, (), 0, App::Prop_None, "Map with additional meta information");
// create the uuid for the document
Base::Uuid id;
ADD_PROPERTY_TYPE(Id, (""), 0, App::Prop_None, "ID (Part-Number) of the Item");
ADD_PROPERTY_TYPE(Uid, (id), 0, App::Prop_None, "UUID of the Item");
// license stuff
ADD_PROPERTY_TYPE(License, ("CC BY 3.0"), 0, App::Prop_None, "License string of the Item");
ADD_PROPERTY_TYPE(LicenseURL, ("http://creativecommons.org/licenses/by/3.0/"), 0, App::Prop_None, "URL to the license text/contract");
// color and apperance
ADD_PROPERTY(Color, (1.0, 1.0, 1.0, 1.0)); // set transparent -> not used
}
Part::~Part(void)
{
}
PyObject *Part::getPyObject()
{
if (PythonObject.is(Py::_None())){
// ref counter is set to 1
PythonObject = Py::Object(new PartPy(this),true);
}
return Py::new_reference_to(PythonObject);
}
// Python feature ---------------------------------------------------------
// Not quit sure yet makeing Part derivable in Python is good Idea!
// JR 2014
//namespace App {
///// @cond DOXERR
//PROPERTY_SOURCE_TEMPLATE(App::PartPython, App::Part)
//template<> const char* App::PartPython::getViewProviderName(void) const {
// return "Gui::ViewProviderPartPython";
//}
//template<> PyObject* App::PartPython::getPyObject(void) {
// if (PythonObject.is(Py::_None())) {
// // ref counter is set to 1
// PythonObject = Py::Object(new FeaturePythonPyT<App::PartPy>(this),true);
// }
// return Py::new_reference_to(PythonObject);
//}
///// @endcond
//
//// explicit template instantiation
//template class AppExport FeaturePythonT<App::Part>;
//}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <iostream>
#include <cstdio>
#include "Compiler.hpp"
#include "Timer.hpp"
#include "DebugTimer.hpp"
#include "Options.hpp"
#include "StringPool.hpp"
#include "FunctionTable.hpp"
#include "ast/Program.hpp"
//Annotators
#include "DefaultValues.hpp"
#include "ContextAnnotator.hpp"
#include "FunctionsAnnotator.hpp"
#include "VariablesAnnotator.hpp"
//Checkers
#include "StringChecker.hpp"
#include "TypeChecker.hpp"
//Visitors
#include "OptimizationEngine.hpp"
#include "TransformerEngine.hpp"
#include "IntermediateCompiler.hpp"
#include "WarningsEngine.hpp"
//Three Address Code
#include "tac/TacCompiler.hpp"
#include "tac/Printer.hpp"
#include "tac/Program.hpp"
#include "tac/BasicBlockExtractor.hpp"
#include "tac/IntelX86CodeGenerator.hpp"
#include "SemanticalException.hpp"
#include "parser/SpiritParser.hpp"
#include "AssemblyFileWriter.hpp"
#ifdef DEBUG
static const bool debug = true;
#else
static const bool debug = false;
#endif
#define TIMER_START(name) Timer name_timer;
#define TIMER_END(name) if(debug){std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl;}
using namespace eddic;
int Compiler::compile(const std::string& file) {
std::cout << "Compile " << file << std::endl;
Timer timer;
std::string output = options["output"].as<std::string>();
int code = 0;
try {
TIMER_START(parsing)
SpiritParser parser;
//The program to build
ast::Program program;
//Parse the file into the program
bool parsing = parser.parse(file, program);
TIMER_END(parsing)
if(parsing){
//Symbol tables
FunctionTable functionTable;
StringPool pool;
//Annotate the AST with more informations
defineDefaultValues(program);
defineContexts(program);
defineVariables(program);
defineFunctions(program, functionTable);
//Transform the AST
transform(program);
//Static analysis
checkStrings(program, pool);
checkTypes(program);
//Check for warnings
checkForWarnings(program, functionTable);
//Optimize the AST
optimize(program, functionTable, pool);
tac::Program tacProgram;
//Generate Three-Address-Code language
tac::TacCompiler compiler;
compiler.compile(program, pool, tacProgram);
//Separate into basic blocks
tac::BasicBlockExtractor extractor;
extractor.extract(tacProgram);
//Generate assembly from TAC
AssemblyFileWriter writer("output.asm");
tac::IntelX86CodeGenerator generator(writer);
generator.generate(tacProgram, pool);
writer.write();
//If it's necessary, assemble and link the assembly
if(!options.count("assembly")){
execCommand("as --32 -o output.o output.asm");
execCommand("ld -m elf_i386 output.o -o " + output);
//Remove temporary files
remove("output.asm");
remove("output.o");
}
}
} catch (const SemanticalException& e) {
std::cout << e.what() << std::endl;
code = 1;
}
std::cout << "Compilation took " << timer.elapsed() << "s" << std::endl;
return code;
}
void eddic::defineDefaultValues(ast::Program& program){
DebugTimer<debug> timer("Annotate with default values");
DefaultValues values;
values.fill(program);
}
void eddic::defineContexts(ast::Program& program){
DebugTimer<debug> timer("Annotate contexts");
ContextAnnotator annotator;
annotator.annotate(program);
}
void eddic::defineVariables(ast::Program& program){
DebugTimer<debug> timer("Annotate variables");
VariablesAnnotator annotator;
annotator.annotate(program);
}
void eddic::defineFunctions(ast::Program& program, FunctionTable& functionTable){
DebugTimer<debug> timer("Annotate functions");
FunctionsAnnotator annotator;
annotator.annotate(program, functionTable);
}
void eddic::checkStrings(ast::Program& program, StringPool& pool){
DebugTimer<debug> timer("Strings checking");
StringChecker checker;
checker.check(program, pool);
}
void eddic::checkTypes(ast::Program& program){
DebugTimer<debug> timer("Types checking");
TypeChecker checker;
checker.check(program);
}
void eddic::checkForWarnings(ast::Program& program, FunctionTable& table){
DebugTimer<debug> timer("Check for warnings");
WarningsEngine engine;
engine.check(program, table);
}
void eddic::transform(ast::Program& program){
DebugTimer<debug> timer("Transformation");
TransformerEngine engine;
engine.transform(program);
}
void eddic::optimize(ast::Program& program, FunctionTable& functionTable, StringPool& pool){
DebugTimer<debug> timer("Optimization");
OptimizationEngine engine;
engine.optimize(program, functionTable, pool);
}
void eddic::execCommand(const std::string& command) {
DebugTimer<debug> timer("Exec " + command);
if(debug){
std::cout << "eddic : exec command : " << command << std::endl;
}
char buffer[1024];
FILE* stream = popen(command.c_str(), "r");
while (fgets(buffer, 1024, stream) != NULL) {
std::cout << buffer;
}
pclose(stream);
}
void eddic::warn(const std::string& warning){
std::cout << "warning: " << warning << std::endl;
}
<commit_msg>Cleanup imports<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <iostream>
#include <cstdio>
#include "Compiler.hpp"
#include "Timer.hpp"
#include "DebugTimer.hpp"
#include "Options.hpp"
#include "StringPool.hpp"
#include "FunctionTable.hpp"
#include "SemanticalException.hpp"
#include "AssemblyFileWriter.hpp"
#include "ast/Program.hpp"
//Annotators
#include "DefaultValues.hpp"
#include "ContextAnnotator.hpp"
#include "FunctionsAnnotator.hpp"
#include "VariablesAnnotator.hpp"
//Checkers
#include "StringChecker.hpp"
#include "TypeChecker.hpp"
//Visitors
#include "OptimizationEngine.hpp"
#include "TransformerEngine.hpp"
#include "IntermediateCompiler.hpp"
#include "WarningsEngine.hpp"
//Three Address Code
#include "tac/TacCompiler.hpp"
#include "tac/Printer.hpp"
#include "tac/Program.hpp"
#include "tac/BasicBlockExtractor.hpp"
#include "tac/IntelX86CodeGenerator.hpp"
#include "parser/SpiritParser.hpp"
#ifdef DEBUG
static const bool debug = true;
#else
static const bool debug = false;
#endif
#define TIMER_START(name) Timer name_timer;
#define TIMER_END(name) if(debug){std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl;}
using namespace eddic;
int Compiler::compile(const std::string& file) {
std::cout << "Compile " << file << std::endl;
Timer timer;
std::string output = options["output"].as<std::string>();
int code = 0;
try {
TIMER_START(parsing)
SpiritParser parser;
//The program to build
ast::Program program;
//Parse the file into the program
bool parsing = parser.parse(file, program);
TIMER_END(parsing)
if(parsing){
//Symbol tables
FunctionTable functionTable;
StringPool pool;
//Annotate the AST with more informations
defineDefaultValues(program);
defineContexts(program);
defineVariables(program);
defineFunctions(program, functionTable);
//Transform the AST
transform(program);
//Static analysis
checkStrings(program, pool);
checkTypes(program);
//Check for warnings
checkForWarnings(program, functionTable);
//Optimize the AST
optimize(program, functionTable, pool);
tac::Program tacProgram;
//Generate Three-Address-Code language
tac::TacCompiler compiler;
compiler.compile(program, pool, tacProgram);
//Separate into basic blocks
tac::BasicBlockExtractor extractor;
extractor.extract(tacProgram);
//Generate assembly from TAC
AssemblyFileWriter writer("output.asm");
tac::IntelX86CodeGenerator generator(writer);
generator.generate(tacProgram, pool);
writer.write();
//If it's necessary, assemble and link the assembly
if(!options.count("assembly")){
execCommand("as --32 -o output.o output.asm");
execCommand("ld -m elf_i386 output.o -o " + output);
//Remove temporary files
remove("output.asm");
remove("output.o");
}
}
} catch (const SemanticalException& e) {
std::cout << e.what() << std::endl;
code = 1;
}
std::cout << "Compilation took " << timer.elapsed() << "s" << std::endl;
return code;
}
void eddic::defineDefaultValues(ast::Program& program){
DebugTimer<debug> timer("Annotate with default values");
DefaultValues values;
values.fill(program);
}
void eddic::defineContexts(ast::Program& program){
DebugTimer<debug> timer("Annotate contexts");
ContextAnnotator annotator;
annotator.annotate(program);
}
void eddic::defineVariables(ast::Program& program){
DebugTimer<debug> timer("Annotate variables");
VariablesAnnotator annotator;
annotator.annotate(program);
}
void eddic::defineFunctions(ast::Program& program, FunctionTable& functionTable){
DebugTimer<debug> timer("Annotate functions");
FunctionsAnnotator annotator;
annotator.annotate(program, functionTable);
}
void eddic::checkStrings(ast::Program& program, StringPool& pool){
DebugTimer<debug> timer("Strings checking");
StringChecker checker;
checker.check(program, pool);
}
void eddic::checkTypes(ast::Program& program){
DebugTimer<debug> timer("Types checking");
TypeChecker checker;
checker.check(program);
}
void eddic::checkForWarnings(ast::Program& program, FunctionTable& table){
DebugTimer<debug> timer("Check for warnings");
WarningsEngine engine;
engine.check(program, table);
}
void eddic::transform(ast::Program& program){
DebugTimer<debug> timer("Transformation");
TransformerEngine engine;
engine.transform(program);
}
void eddic::optimize(ast::Program& program, FunctionTable& functionTable, StringPool& pool){
DebugTimer<debug> timer("Optimization");
OptimizationEngine engine;
engine.optimize(program, functionTable, pool);
}
void eddic::execCommand(const std::string& command) {
DebugTimer<debug> timer("Exec " + command);
if(debug){
std::cout << "eddic : exec command : " << command << std::endl;
}
char buffer[1024];
FILE* stream = popen(command.c_str(), "r");
while (fgets(buffer, 1024, stream) != NULL) {
std::cout << buffer;
}
pclose(stream);
}
void eddic::warn(const std::string& warning){
std::cout << "warning: " << warning << std::endl;
}
<|endoftext|>
|
<commit_before>/*---------------------------------------------------------------------\
| |
| _ _ _ _ __ _ |
| | | | | | \_/ | / \ | | |
| | | | | | |_| | / /\ \ | | |
| | |__ | | | | | | / ____ \ | |__ |
| |____||_| |_| |_|/ / \ \|____| |
| |
| ca-mgm library |
| |
| (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/
File: DNObject.cpp
Author: <Michael Calmer> <mc@suse.de>
Maintainer: <Michael Calmer> <mc@suse.de>
Purpose:
/-*/
#include <limal/ca-mgm/DNObject.hpp>
#include <limal/ca-mgm/CAConfig.hpp>
#include <limal/ValueRegExCheck.hpp>
#include <limal/Exception.hpp>
#include <blocxx/Format.hpp>
#include "DNObject_Priv.hpp"
#include "Utils.hpp"
using namespace limal;
using namespace limal::ca_mgm;
using namespace blocxx;
RDNObject::RDNObject(const RDNObject& rdn)
: type(rdn.type), value(rdn.value)
{}
RDNObject::~RDNObject()
{}
RDNObject&
RDNObject::operator=(const RDNObject& rdn)
{
if(this == &rdn) return *this;
type = rdn.type;
value = rdn.value;
return *this;
}
void
RDNObject::setRDNValue(const String& value)
{
this->value = value;
}
blocxx::String
RDNObject::getType() const
{
return type;
}
blocxx::String
RDNObject::getValue() const
{
return value;
}
bool
RDNObject::valid() const
{
if(type.empty()) {
LOGIT_DEBUG("type is empty");
return false;
}
/*
if(value.empty()) {
LOGIT_DEBUG("value is empty");
return false;
}
*/
// FIXME: define and check pre defined types ?
return true;
}
blocxx::StringArray
RDNObject::verify() const
{
StringArray result;
if(type.empty()) {
result.append("type is empty");
}
/*
if(value.empty()) {
result.append("value is empty");
}
*/
// FIXME: define and check pre defined types ?
LOGIT_DEBUG_STRINGARRAY("RDNObject::verify()", result);
return result;
}
blocxx::StringArray
RDNObject::dump() const
{
StringArray result;
result.append("RDNObject::dump()");
result.append(type + "=" + value);
return result;
}
// protected
RDNObject::RDNObject()
: type(String()), value(String())
{
}
// ######################################################################
DNObject::DNObject()
: dn(blocxx::List<RDNObject>())
{
dn.push_back(RDNObject_Priv("countryName", ""));
dn.push_back(RDNObject_Priv("stateOrProvinceName", ""));
dn.push_back(RDNObject_Priv("localityName", ""));
dn.push_back(RDNObject_Priv("organizationName", ""));
dn.push_back(RDNObject_Priv("organizationalUnitName", ""));
dn.push_back(RDNObject_Priv("commonName", ""));
dn.push_back(RDNObject_Priv("emailAddress", ""));
}
DNObject::DNObject(CAConfig* caConfig, Type type)
: dn(blocxx::List<RDNObject>())
{
// FIXME: get these values from the configfile
dn.push_back(RDNObject_Priv("countryName", ""));
dn.push_back(RDNObject_Priv("stateOrProvinceName", ""));
dn.push_back(RDNObject_Priv("localityName", ""));
dn.push_back(RDNObject_Priv("organizationName", ""));
dn.push_back(RDNObject_Priv("organizationalUnitName", ""));
dn.push_back(RDNObject_Priv("commonName", ""));
dn.push_back(RDNObject_Priv("emailAddress", ""));
}
DNObject::DNObject(const blocxx::List<RDNObject> &dn)
: dn(dn)
{
StringArray r = this->verify();
if(!r.empty()) {
BLOCXX_THROW(limal::ValueException, r[0].c_str());
}
}
DNObject::DNObject(const DNObject& dn)
: dn(dn.dn)
{}
DNObject::~DNObject()
{}
DNObject&
DNObject::operator=(const DNObject& dn)
{
if(this == &dn) return *this;
this->dn = dn.dn;
return *this;
}
void
DNObject::setDN(const blocxx::List<RDNObject> &dn)
{
StringArray r = checkRDNList(dn);
if(!r.empty()) {
LOGIT_ERROR(r[0]);
BLOCXX_THROW(limal::ValueException, r[0].c_str());
}
this->dn = dn;
}
blocxx::List<RDNObject>
DNObject::getDN() const
{
return dn;
}
bool
DNObject::valid() const
{
if(dn.empty()) {
LOGIT_DEBUG("empty DN");
return false;
}
StringArray r = checkRDNList(dn);
if(!r.empty()) {
LOGIT_DEBUG(r[0]);
return false;
}
return true;
}
blocxx::StringArray
DNObject::verify() const
{
StringArray result;
if(dn.empty()) {
result.append("empty DN");
}
result.appendArray(checkRDNList(dn));
LOGIT_DEBUG_STRINGARRAY("DNObject::verify()", result);
return result;
}
blocxx::StringArray
DNObject::checkRDNList(const blocxx::List<RDNObject>& list) const
{
StringArray result;
blocxx::List<RDNObject>::const_iterator it = list.begin();
for(; it != list.end(); ++it) {
result.appendArray((*it).verify());
}
return result;
}
blocxx::StringArray
DNObject::dump() const
{
StringArray result;
result.append("DNObject::dump()");
blocxx::List< RDNObject >::const_iterator it = dn.begin();
for(; it != dn.end(); ++it) {
result.appendArray((*it).dump());
}
return result;
}
<commit_msg>try to implement reading DN keys and order from openssl.cnf; does not work currently<commit_after>/*---------------------------------------------------------------------\
| |
| _ _ _ _ __ _ |
| | | | | | \_/ | / \ | | |
| | | | | | |_| | / /\ \ | | |
| | |__ | | | | | | / ____ \ | |__ |
| |____||_| |_| |_|/ / \ \|____| |
| |
| ca-mgm library |
| |
| (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/
File: DNObject.cpp
Author: <Michael Calmer> <mc@suse.de>
Maintainer: <Michael Calmer> <mc@suse.de>
Purpose:
/-*/
#include <limal/ca-mgm/DNObject.hpp>
#include <limal/ca-mgm/CAConfig.hpp>
#include <limal/ValueRegExCheck.hpp>
#include <limal/Exception.hpp>
#include <blocxx/Format.hpp>
#include "DNObject_Priv.hpp"
#include "Utils.hpp"
using namespace limal;
using namespace limal::ca_mgm;
using namespace blocxx;
RDNObject::RDNObject(const RDNObject& rdn)
: type(rdn.type), value(rdn.value)
{}
RDNObject::~RDNObject()
{}
RDNObject&
RDNObject::operator=(const RDNObject& rdn)
{
if(this == &rdn) return *this;
type = rdn.type;
value = rdn.value;
return *this;
}
void
RDNObject::setRDNValue(const String& value)
{
this->value = value;
}
blocxx::String
RDNObject::getType() const
{
return type;
}
blocxx::String
RDNObject::getValue() const
{
return value;
}
bool
RDNObject::valid() const
{
if(type.empty()) {
LOGIT_DEBUG("type is empty");
return false;
}
/*
if(value.empty()) {
LOGIT_DEBUG("value is empty");
return false;
}
*/
// FIXME: define and check pre defined types ?
return true;
}
blocxx::StringArray
RDNObject::verify() const
{
StringArray result;
if(type.empty()) {
result.append("type is empty");
}
/*
if(value.empty()) {
result.append("value is empty");
}
*/
// FIXME: define and check pre defined types ?
LOGIT_DEBUG_STRINGARRAY("RDNObject::verify()", result);
return result;
}
blocxx::StringArray
RDNObject::dump() const
{
StringArray result;
result.append("RDNObject::dump()");
result.append(type + "=" + value);
return result;
}
// protected
RDNObject::RDNObject()
: type(String()), value(String())
{
}
// ######################################################################
DNObject::DNObject()
: dn(blocxx::List<RDNObject>())
{
dn.push_back(RDNObject_Priv("countryName", ""));
dn.push_back(RDNObject_Priv("stateOrProvinceName", ""));
dn.push_back(RDNObject_Priv("localityName", ""));
dn.push_back(RDNObject_Priv("organizationName", ""));
dn.push_back(RDNObject_Priv("organizationalUnitName", ""));
dn.push_back(RDNObject_Priv("commonName", ""));
dn.push_back(RDNObject_Priv("emailAddress", ""));
}
DNObject::DNObject(CAConfig* caConfig, Type type)
: dn(blocxx::List<RDNObject>())
{
if(type == Client_Cert || type == Server_Cert ||
type == CA_Cert || type == CRL ) {
LOGIT_ERROR("wrong type" << type);
BLOCXX_THROW(limal::ValueException, Format("wrong type: %1", type).c_str());
}
#if 0
// FIXME: does not work till we get the exact order of the keys
// like it is in the configfiles
bool p = caConfig->exists(type2Section(type, false), "distinguished_name");
if(!p) {
LOGIT_ERROR("missing section 'distinguished_name' in config file");
BLOCXX_THROW(limal::SyntaxException,
"missing section 'distinguished_name' in config file");
}
String dnSect = caConfig->getValue(type2Section(type, false),
"distinguished_name");
StringList dnKeys = caConfig->getKeylist(dnSect);
if(dnKeys.empty()) {
LOGIT_ERROR("Can not parse Section " << dnSect);
BLOCXX_THROW(limal::SyntaxException,
Format("Can not parse Section %1", dnSect).c_str());
}
StringList::const_iterator it = dnKeys.begin();
String fieldName;
String prompt;
String defaultValue;
String min;
String max;
Array<Map<String, String> > configDN;
for(; it != dnKeys.end(); ++it) {
if((*it).endsWith("_default", String::E_CASE_INSENSITIVE)) {
if((*it).startsWith(fieldName, String::E_CASE_INSENSITIVE)) {
defaultValue = caConfig->getValue(dnSect, *it);
} else {
LOGIT_INFO("Wrong order of section '" << dnSect <<
"'. FieldName is '" << fieldName <<
"' but parsed Key is '" << *it <<
"'. Ignoring value.");
continue;
}
} else if((*it).endsWith("_min", String::E_CASE_INSENSITIVE)) {
if((*it).startsWith(fieldName, String::E_CASE_INSENSITIVE)) {
min = caConfig->getValue(dnSect, *it);
} else {
LOGIT_INFO("Wrong order of section '" << dnSect <<
"'. FieldName is '" << fieldName <<
"' but parsed Key is '" << *it <<
"'. Ignoring value.");
continue;
}
} else if((*it).endsWith("_max", String::E_CASE_INSENSITIVE)) {
if((*it).startsWith(fieldName, String::E_CASE_INSENSITIVE)) {
max = caConfig->getValue(dnSect, *it);
} else {
LOGIT_INFO("Wrong order of section '" << dnSect <<
"'. FieldName is '" << fieldName <<
"' but parsed Key is '" << *it <<
"'. Ignoring value.");
continue;
}
} else {
// A new fieldName
// commit values
if(!fieldName.empty()) {
dn.push_back(RDNObject_Priv(fieldName, defaultValue));
//FIXME: do something with the other values too
}
// reset
prompt = String();
defaultValue = String();
min = String();
max = String();
fieldName = *it;
prompt = caConfig->getValue(dnSect, *it);
}
}
// commit the last values
if(!fieldName.empty()) {
dn.push_back(RDNObject_Priv(fieldName, defaultValue));
//FIXME: do something with the other values too
}
#endif
dn.push_back(RDNObject_Priv("countryName", ""));
dn.push_back(RDNObject_Priv("stateOrProvinceName", ""));
dn.push_back(RDNObject_Priv("localityName", ""));
dn.push_back(RDNObject_Priv("organizationName", ""));
dn.push_back(RDNObject_Priv("organizationalUnitName", ""));
dn.push_back(RDNObject_Priv("commonName", ""));
dn.push_back(RDNObject_Priv("emailAddress", ""));
}
DNObject::DNObject(const blocxx::List<RDNObject> &dn)
: dn(dn)
{
StringArray r = this->verify();
if(!r.empty()) {
BLOCXX_THROW(limal::ValueException, r[0].c_str());
}
}
DNObject::DNObject(const DNObject& dn)
: dn(dn.dn)
{}
DNObject::~DNObject()
{}
DNObject&
DNObject::operator=(const DNObject& dn)
{
if(this == &dn) return *this;
this->dn = dn.dn;
return *this;
}
void
DNObject::setDN(const blocxx::List<RDNObject> &dn)
{
StringArray r = checkRDNList(dn);
if(!r.empty()) {
LOGIT_ERROR(r[0]);
BLOCXX_THROW(limal::ValueException, r[0].c_str());
}
this->dn = dn;
}
blocxx::List<RDNObject>
DNObject::getDN() const
{
return dn;
}
bool
DNObject::valid() const
{
if(dn.empty()) {
LOGIT_DEBUG("empty DN");
return false;
}
StringArray r = checkRDNList(dn);
if(!r.empty()) {
LOGIT_DEBUG(r[0]);
return false;
}
return true;
}
blocxx::StringArray
DNObject::verify() const
{
StringArray result;
if(dn.empty()) {
result.append("empty DN");
}
result.appendArray(checkRDNList(dn));
LOGIT_DEBUG_STRINGARRAY("DNObject::verify()", result);
return result;
}
blocxx::StringArray
DNObject::checkRDNList(const blocxx::List<RDNObject>& list) const
{
StringArray result;
blocxx::List<RDNObject>::const_iterator it = list.begin();
for(; it != list.end(); ++it) {
result.appendArray((*it).verify());
}
return result;
}
blocxx::StringArray
DNObject::dump() const
{
StringArray result;
result.append("DNObject::dump()");
blocxx::List< RDNObject >::const_iterator it = dn.begin();
for(; it != dn.end(); ++it) {
result.appendArray((*it).dump());
}
return result;
}
<|endoftext|>
|
<commit_before>#include <Refal2.h>
namespace Refal2 {
//-----------------------------------------------------------------------------
class CRulePrintHelper : public CPrintHelper {
public:
CRulePrintHelper( const CPrintHelper& _printHelper,
const CVariables& _variables ) :
printHelper( _printHelper ),
variables( _variables )
{
}
virtual void Variable( std::ostream& outputStream,
const TVariableIndex variable ) const
{
outputStream << variables.GetVariable( variable ).GetType();
variables.GetVariable( variable ).GetQualifier().Print( outputStream,
printHelper );
}
virtual void Label( std::ostream& outputStream,
const TLabel label ) const
{
printHelper.Label( outputStream, label );
}
private:
const CPrintHelper& printHelper;
const CVariables& variables;
};
void CRule::Print( std::ostream& outputStream,
const CPrintHelper& printHelper ) const
{
CRulePrintHelper rulePrintHelper( printHelper, Variables );
outputStream << "\t" << ( RightMatching ? "R" : "" ) << " ";
Left.Print( outputStream, rulePrintHelper );
outputStream << "= ";
Right.Print( outputStream, printHelper );
}
void CRule::Compile( CFunctionCompiler& compiler ) const
{
compiler.CompileRule( const_cast<CRule&>( *this ) );
}
//-----------------------------------------------------------------------------
CPreparatoryFunction::CPreparatoryFunction( const CToken& _nameToken ):
type( PFT_Declared ),
entry( false ),
name( _nameToken.word ),
nameToken( _nameToken ),
firstOperation( nullptr )
{
assert( !name.empty() );
MakeLower( name );
}
const std::string& CPreparatoryFunction::ExternalName() const
{
assert( IsEntry() || IsExternal() );
return externalName;
}
const CToken& CPreparatoryFunction::ExternalNameToken() const
{
assert( IsEntry() || IsExternal() );
return externalNameToken;
}
const CRule* CPreparatoryFunction::FirstRule() const
{
assert( IsOrdinary() );
return firstRule.get();
}
TOperationAddress CPreparatoryFunction::FirstOperation() const
{
assert( IsCompiled() );
return firstOperation;
}
void CPreparatoryFunction::SetDefined( const CToken& _nameToken )
{
assert( _nameToken.type == TT_Word );
assert( CompareNoCase( nameToken.word, _nameToken.word ) );
assert( type == PFT_Declared );
type = PFT_Defined;
nameToken = _nameToken;
}
void CPreparatoryFunction::SetOrdinary( CRulePtr& _firstRule )
{
assert( type == PFT_Defined );
assert( static_cast<bool>( _firstRule ) );
type = PFT_Ordinary;
firstRule.reset( _firstRule.release() );
}
void CPreparatoryFunction::SetEmpty()
{
assert( type == PFT_Defined );
type = PFT_Empty;
}
void CPreparatoryFunction::SetEntry( const CToken& _externalNameToken )
{
assert( type != PFT_External );
entry = true;
setExternalName( _externalNameToken );
}
void CPreparatoryFunction::SetExternal( const CToken& _externalNameToken )
{
assert( !entry );
assert( type == PFT_Defined );
type = PFT_External;
setExternalName( _externalNameToken );
}
void CPreparatoryFunction::Compile( CFunctionCompiler& compiler )
{
assert( IsOrdinary() );
const CRule* rule = FirstRule();
while( rule != nullptr ) {
rule->Compile( compiler );
rule = rule->NextRule.get();
}
type = PFT_Compiled;
firstOperation = compiler.GetFirstOperation();
assert( firstOperation != nullptr );
}
void CPreparatoryFunction::Print( std::ostream& outputStream,
const CPrintHelper& printHelper ) const
{
assert( IsOrdinary() );
const CRule* rule = FirstRule();
while( rule != nullptr ) {
rule->Print( outputStream, printHelper );
outputStream << std::endl;
rule = rule->NextRule.get();
}
}
void CPreparatoryFunction::setExternalName( const CToken& _externalNameToken )
{
assert( ( entry && !IsExternal() ) || ( !entry && IsExternal() ) );
externalNameToken = _externalNameToken;
externalName = externalNameToken.word;
assert( !externalName.empty() );
MakeLower( externalName );
}
//-----------------------------------------------------------------------------
CFunctionBuilder::CFunctionBuilder( IErrorHandler* errorHandler ):
CVariablesBuilder( errorHandler ),
isProcessRightPart( false ),
isRightDirection( false ),
lastRule( nullptr )
{
}
CFunctionBuilder::~CFunctionBuilder()
{
Reset();
}
void CFunctionBuilder::Reset()
{
CVariablesBuilder::Reset();
isProcessRightPart = false;
isRightDirection = false;
acc.Empty();
leftPart.Empty();
emptyRules();
emptyStack();
}
void CFunctionBuilder::Export( CRulePtr& _firstRule )
{
// todo: check rule
if( !HasErrors() && static_cast<bool>( firstRule ) ) {
_firstRule.reset( firstRule.release() );
}
Reset();
}
void CFunctionBuilder::SetRightDirection()
{
isRightDirection = true;
}
void CFunctionBuilder::AddEndOfLeft()
{
if( isProcessRightPart ) {
error( EC_ThereAreMultiplePartsSeparatorInRules );
} else {
while( !balanceStack.empty() ) {
balanceStack.pop();
error( EC_UnclosedLeftParenInLeftPart );
}
if( HasErrors() ) {
acc.Empty();
} else {
acc.Move( leftPart );
}
isProcessRightPart = true;
}
}
void CFunctionBuilder::AddEndOfRight()
{
while( !balanceStack.empty() ) {
CUnitNode* unit = balanceStack.top();
balanceStack.pop();
error( unit->IsLeftParen() ? EC_UnclosedLeftParenInRightPart :
EC_UnclosedLeftBracketInRightPart );
}
if( !isProcessRightPart ) {
error( EC_ThereAreNoPartsSeparatorInRules );
}
if( HasErrors() ) {
acc.Empty();
CVariablesBuilder::Reset();
} else {
addRule();
}
isProcessRightPart = false;
}
void CFunctionBuilder::AddChar( TChar c )
{
if( !HasErrors() ) {
acc.AppendChar( c );
}
}
void CFunctionBuilder::AddLabel( TLabel label )
{
if( !HasErrors() ) {
acc.AppendLabel( label );
}
}
void CFunctionBuilder::AddNumber( TNumber number )
{
if( !HasErrors() ) {
acc.AppendNumber( number );
}
}
void CFunctionBuilder::AddVariable( TVariableTypeTag type, TVariableName name,
CQualifier* qualifier )
{
TVariableIndex index = InvalidVariableIndex;
if( isProcessRightPart ) {
index = CVariablesBuilder::AddRight( name, type );
} else {
index = CVariablesBuilder::AddLeft( name, type );
}
if( !HasErrors() ) {
if( index == InvalidVariableIndex ) {
//SetErrors();
} else {
if( qualifier != nullptr ) {
CVariablesBuilder::AddQualifier( index, *qualifier );
}
acc.AppendVariable( index );
}
}
}
void CFunctionBuilder::AddLeftParen()
{
balanceStack.push( acc.AppendLeftParen() );
}
void CFunctionBuilder::AddRightParen()
{
CUnitNode* leftParen = nullptr;
if( !balanceStack.empty() ) {
leftParen = balanceStack.top();
}
if( leftParen != nullptr && leftParen->IsLeftParen() ) {
leftParen->PairedParen() = acc.AppendRightParen(leftParen);
balanceStack.pop();
} else {
error( EC_RightParenDoesNotMatchLeftParen );
}
}
void CFunctionBuilder::AddLeftBracket()
{
if( isProcessRightPart ) {
balanceStack.push( acc.AppendLeftBracket() );
} else {
error( EC_IllegalLeftBracketInLeftPart );
}
}
void CFunctionBuilder::AddRightBracket()
{
if( isProcessRightPart ) {
CUnitNode* leftBracket = nullptr;
if( !balanceStack.empty() ) {
leftBracket = balanceStack.top();
}
if( leftBracket != nullptr && leftBracket->IsLeftBracket() ) {
leftBracket->PairedParen() = acc.AppendRightBracket(leftBracket);
balanceStack.pop();
} else {
error( EC_RightBracketDoesNotMatchLeftBracket );
}
} else {
error( EC_IllegalRightBracketInLeftPart );
}
}
const char* CFunctionBuilder::getErrorMessage( TErrorCode errorCode )
{
switch( errorCode ) {
case EC_IllegalLeftBracketInLeftPart:
return "illegal left bracket in left part of rule";
case EC_IllegalRightBracketInLeftPart:
return "illegal right bracket in left part of rule";
case EC_RightParenDoesNotMatchLeftParen:
return "right paren does not match left paren";
case EC_RightBracketDoesNotMatchLeftBracket:
return "right bracket does not match left bracket";
case EC_UnclosedLeftParenInLeftPart:
return "unclosed left paren in left part of rule";
case EC_UnclosedLeftParenInRightPart:
return "unclosed left paren in right part of rule";
case EC_UnclosedLeftBracketInRightPart:
return "unclosed left bracket in right part of rule";
case EC_ThereAreMultiplePartsSeparatorInRules:
return "there are multiple parts separator in rule";
case EC_ThereAreNoPartsSeparatorInRules:
return "there are no parts separator in rule";
}
assert( false );
return nullptr;
}
void CFunctionBuilder::error( TErrorCode errorCode )
{
CErrorsHelper::RaiseError( ES_Error, getErrorMessage( errorCode ) );
}
void CFunctionBuilder::emptyStack()
{
std::stack<CUnitNode*> emptyStack;
std::swap( balanceStack, emptyStack );
}
void CFunctionBuilder::emptyRules()
{
firstRule.reset();
lastRule = nullptr;
}
void CFunctionBuilder::addRule()
{
if( static_cast<bool>( firstRule ) ) {
lastRule->NextRule.reset( new CRule );
lastRule = lastRule->NextRule.get();
} else {
firstRule.reset( new CRule );
lastRule = firstRule.get();
}
lastRule->RightMatching = isRightDirection;
leftPart.Move( lastRule->Left );
acc.Move( lastRule->Right );
CVariablesBuilder::Export( lastRule->Variables );
}
//-----------------------------------------------------------------------------
} // end of namespace refal2
<commit_msg>refactoring<commit_after>#include <Refal2.h>
namespace Refal2 {
//-----------------------------------------------------------------------------
class CRulePrintHelper : public CPrintHelper {
public:
CRulePrintHelper( const CPrintHelper& _printHelper,
const CVariables& _variables ) :
printHelper( _printHelper ),
variables( _variables )
{
}
virtual void Variable( std::ostream& outputStream,
const TVariableIndex variable ) const
{
outputStream << variables.GetVariable( variable ).GetType();
variables.GetVariable( variable ).GetQualifier().Print( outputStream,
printHelper );
}
virtual void Label( std::ostream& outputStream,
const TLabel label ) const
{
printHelper.Label( outputStream, label );
}
private:
const CPrintHelper& printHelper;
const CVariables& variables;
};
void CRule::Print( std::ostream& outputStream,
const CPrintHelper& printHelper ) const
{
CRulePrintHelper rulePrintHelper( printHelper, Variables );
outputStream << "\t" << ( RightMatching ? "R" : "" ) << " ";
Left.Print( outputStream, rulePrintHelper );
outputStream << "= ";
Right.Print( outputStream, printHelper );
}
void CRule::Compile( CFunctionCompiler& compiler ) const
{
compiler.CompileRule( const_cast<CRule&>( *this ) );
}
//-----------------------------------------------------------------------------
CPreparatoryFunction::CPreparatoryFunction( const CToken& _nameToken ):
type( PFT_Declared ),
entry( false ),
name( _nameToken.word ),
nameToken( _nameToken ),
firstOperation( nullptr )
{
assert( !name.empty() );
MakeLower( name );
}
const std::string& CPreparatoryFunction::ExternalName() const
{
assert( IsEntry() || IsExternal() );
return externalName;
}
const CToken& CPreparatoryFunction::ExternalNameToken() const
{
assert( IsEntry() || IsExternal() );
return externalNameToken;
}
const CRule* CPreparatoryFunction::FirstRule() const
{
assert( IsOrdinary() );
return firstRule.get();
}
TOperationAddress CPreparatoryFunction::FirstOperation() const
{
assert( IsCompiled() );
return firstOperation;
}
void CPreparatoryFunction::SetDefined( const CToken& _nameToken )
{
assert( _nameToken.type == TT_Word );
assert( CompareNoCase( nameToken.word, _nameToken.word ) );
assert( type == PFT_Declared );
type = PFT_Defined;
nameToken = _nameToken;
}
void CPreparatoryFunction::SetOrdinary( CRulePtr& _firstRule )
{
assert( type == PFT_Defined );
assert( static_cast<bool>( _firstRule ) );
type = PFT_Ordinary;
firstRule.reset( _firstRule.release() );
}
void CPreparatoryFunction::SetEmpty()
{
assert( type == PFT_Defined );
type = PFT_Empty;
}
void CPreparatoryFunction::SetEntry( const CToken& _externalNameToken )
{
assert( type != PFT_External );
entry = true;
setExternalName( _externalNameToken );
}
void CPreparatoryFunction::SetExternal( const CToken& _externalNameToken )
{
assert( !entry );
assert( type == PFT_Defined );
type = PFT_External;
setExternalName( _externalNameToken );
}
void CPreparatoryFunction::Compile( CFunctionCompiler& compiler )
{
assert( IsOrdinary() );
const CRule* rule = FirstRule();
while( rule != nullptr ) {
rule->Compile( compiler );
rule = rule->NextRule.get();
}
type = PFT_Compiled;
firstOperation = compiler.GetFirstOperation();
assert( firstOperation != nullptr );
}
void CPreparatoryFunction::Print( std::ostream& outputStream,
const CPrintHelper& printHelper ) const
{
assert( IsOrdinary() );
const CRule* rule = FirstRule();
while( rule != nullptr ) {
rule->Print( outputStream, printHelper );
outputStream << std::endl;
rule = rule->NextRule.get();
}
}
void CPreparatoryFunction::setExternalName( const CToken& _externalNameToken )
{
assert( ( entry && !IsExternal() ) || ( !entry && IsExternal() ) );
externalNameToken = _externalNameToken;
externalName = externalNameToken.word;
assert( !externalName.empty() );
MakeLower( externalName );
}
//-----------------------------------------------------------------------------
CFunctionBuilder::CFunctionBuilder( IErrorHandler* errorHandler ):
CVariablesBuilder( errorHandler ),
isProcessRightPart( false ),
isRightDirection( false ),
lastRule( nullptr )
{
}
CFunctionBuilder::~CFunctionBuilder()
{
Reset();
}
void CFunctionBuilder::Reset()
{
CVariablesBuilder::Reset();
isProcessRightPart = false;
isRightDirection = false;
acc.Empty();
leftPart.Empty();
emptyRules();
emptyStack();
}
void CFunctionBuilder::Export( CRulePtr& _firstRule )
{
// todo: check rule
if( !HasErrors() && static_cast<bool>( firstRule ) ) {
_firstRule.reset( firstRule.release() );
}
Reset();
}
void CFunctionBuilder::SetRightDirection()
{
isRightDirection = true;
}
void CFunctionBuilder::AddEndOfLeft()
{
if( isProcessRightPart ) {
error( EC_ThereAreMultiplePartsSeparatorInRules );
} else {
while( !balanceStack.empty() ) {
balanceStack.pop();
error( EC_UnclosedLeftParenInLeftPart );
}
if( HasErrors() ) {
acc.Empty();
} else {
acc.Move( leftPart );
}
isProcessRightPart = true;
}
}
void CFunctionBuilder::AddEndOfRight()
{
while( !balanceStack.empty() ) {
CUnitNode* unit = balanceStack.top();
balanceStack.pop();
error( unit->IsLeftParen() ? EC_UnclosedLeftParenInRightPart :
EC_UnclosedLeftBracketInRightPart );
}
if( !isProcessRightPart ) {
error( EC_ThereAreNoPartsSeparatorInRules );
}
if( HasErrors() ) {
acc.Empty();
CVariablesBuilder::Reset();
} else {
addRule();
}
isProcessRightPart = false;
}
void CFunctionBuilder::AddChar( TChar c )
{
if( !HasErrors() ) {
acc.AppendChar( c );
}
}
void CFunctionBuilder::AddLabel( TLabel label )
{
if( !HasErrors() ) {
acc.AppendLabel( label );
}
}
void CFunctionBuilder::AddNumber( TNumber number )
{
if( !HasErrors() ) {
acc.AppendNumber( number );
}
}
void CFunctionBuilder::AddVariable( TVariableTypeTag type, TVariableName name,
CQualifier* qualifier )
{
const TVariableIndex index = isProcessRightPart ?
CVariablesBuilder::AddRight( name, type ) :
CVariablesBuilder::AddLeft( name, type );
if( !HasErrors() ) {
assert( index != InvalidVariableIndex );
if( qualifier != nullptr ) {
CVariablesBuilder::AddQualifier( index, *qualifier );
}
acc.AppendVariable( index );
}
}
void CFunctionBuilder::AddLeftParen()
{
balanceStack.push( acc.AppendLeftParen() );
}
void CFunctionBuilder::AddRightParen()
{
CUnitNode* leftParen = nullptr;
if( !balanceStack.empty() ) {
leftParen = balanceStack.top();
}
if( leftParen != nullptr && leftParen->IsLeftParen() ) {
leftParen->PairedParen() = acc.AppendRightParen(leftParen);
balanceStack.pop();
} else {
error( EC_RightParenDoesNotMatchLeftParen );
}
}
void CFunctionBuilder::AddLeftBracket()
{
if( isProcessRightPart ) {
balanceStack.push( acc.AppendLeftBracket() );
} else {
error( EC_IllegalLeftBracketInLeftPart );
}
}
void CFunctionBuilder::AddRightBracket()
{
if( isProcessRightPart ) {
CUnitNode* leftBracket = nullptr;
if( !balanceStack.empty() ) {
leftBracket = balanceStack.top();
}
if( leftBracket != nullptr && leftBracket->IsLeftBracket() ) {
leftBracket->PairedParen() = acc.AppendRightBracket(leftBracket);
balanceStack.pop();
} else {
error( EC_RightBracketDoesNotMatchLeftBracket );
}
} else {
error( EC_IllegalRightBracketInLeftPart );
}
}
const char* CFunctionBuilder::getErrorMessage( TErrorCode errorCode )
{
switch( errorCode ) {
case EC_IllegalLeftBracketInLeftPart:
return "illegal left bracket in left part of rule";
case EC_IllegalRightBracketInLeftPart:
return "illegal right bracket in left part of rule";
case EC_RightParenDoesNotMatchLeftParen:
return "right paren does not match left paren";
case EC_RightBracketDoesNotMatchLeftBracket:
return "right bracket does not match left bracket";
case EC_UnclosedLeftParenInLeftPart:
return "unclosed left paren in left part of rule";
case EC_UnclosedLeftParenInRightPart:
return "unclosed left paren in right part of rule";
case EC_UnclosedLeftBracketInRightPart:
return "unclosed left bracket in right part of rule";
case EC_ThereAreMultiplePartsSeparatorInRules:
return "there are multiple parts separator in rule";
case EC_ThereAreNoPartsSeparatorInRules:
return "there are no parts separator in rule";
}
assert( false );
return nullptr;
}
void CFunctionBuilder::error( TErrorCode errorCode )
{
CErrorsHelper::RaiseError( ES_Error, getErrorMessage( errorCode ) );
}
void CFunctionBuilder::emptyStack()
{
std::stack<CUnitNode*> emptyStack;
std::swap( balanceStack, emptyStack );
}
void CFunctionBuilder::emptyRules()
{
firstRule.reset();
lastRule = nullptr;
}
void CFunctionBuilder::addRule()
{
if( static_cast<bool>( firstRule ) ) {
lastRule->NextRule.reset( new CRule );
lastRule = lastRule->NextRule.get();
} else {
firstRule.reset( new CRule );
lastRule = firstRule.get();
}
lastRule->RightMatching = isRightDirection;
leftPart.Move( lastRule->Left );
acc.Move( lastRule->Right );
CVariablesBuilder::Export( lastRule->Variables );
}
//-----------------------------------------------------------------------------
} // end of namespace refal2
<|endoftext|>
|
<commit_before>#include <iomanip>
#include <boost/format.hpp>
#include "prefix.hpp"
#include "util.hpp"
#include "stream.hpp"
#include "streamindent.hpp"
#include "printing.hpp"
#include "Function.hpp"
#include <regex>
namespace autobind {
namespace
{
const boost::format FunctionPrototype{
"static PyObject *%s(%s *self, PyObject *args, PyObject *kw)"
};
}
std::string processDocString(const std::string &docstring)
{
auto result = std::regex_replace(docstring, std::regex("(^|\n)\\s*(///|\\*)"), "$1");
replace(result, "\\", "\\\\");
replace(result, "\n", "\\n");
replace(result, "\"", "\\\"");
return result;
}
Function::Function(std::string name, std::vector<Arg> args,
std::string docstring)
: Export(std::move(name))
, _args(std::move(args))
, _docstring(std::move(docstring))
{
auto parts = rsplit(this->name(), "::");
_unqualifiedName = parts.second;
_implName = this->name();
replace(_implName, "::", "_ns_");
_implName += "_py_bind_impl";
}
void Function::codegenCall(std::ostream &out) const
{
out << name();
codegenCallArgs(out);
out << ";\n";
}
void Function::codegenCallArgs(std::ostream &out) const
{
using namespace streams;
auto argStream = stream(_args)
| enumerated()
| pairTransformed([](int i, const Arg &a) {
return a.requiresAdditionalConversion?
str(boost::format("PyConversion<%1%>::load(arg%2%)") % a.cppQualTypeName % i)
: str(boost::format("arg%1%") % i);
})
| interposed(", ");
out << "(" << cat(argStream) << ")";
}
void Function::codegenDeclaration(std::ostream &out) const
{
out << boost::format(FunctionPrototype) % _implName % selfTypeName() << ";\n";
}
void Function::codegenTupleUnpack(std::ostream &out) const
{
using namespace streams;
// declare variables
for(const auto &pair : stream(_args) | enumerated())
{
if(pair.second.requiresAdditionalConversion)
{
out << "PyObject *";
}
else
{
out << pair.second.cppQualTypeName << " ";
}
out << "arg" << pair.first << ";\n";
}
// call PyArg_ParseTuple
auto kwlistStream = stream(_args)
| transformed([](const Arg &a) { return "\"" + a.argName + "\", "; });
out << boost::format("static const char *kwlist[] = {%1%0};\n") % cat(kwlistStream);
auto argStream = count()
| take(_args.size())
| transformed([](int i) { return boost::format(", &arg%d") % i; });
auto formatStream = stream(_args)
| transformed([](const Arg &a) { return a.parseTupleFmt; });
out << boost::format("if(!PyArg_ParseTupleAndKeywords(args, kw, \"%s\", (char **)kwlist%s))\n"
" return 0;\n") % cat(formatStream) % cat(argStream);
}
void Function::codegenDefinitionBody(std::ostream &out) const
{
// emit "try" block
out << "try\n{\n";
{
IndentingOStreambuf indenter2(out);
// call function
{
if(_lineNo >= 0)
out << boost::format("#line %1% %2%\n") % _lineNo % std::quoted(_origFile);
if(_returnType != "void")
{
out << _returnType << " result = ";
}
codegenCall(out);
}
if(_returnType != "void")
{
out << "return PyConversion<" << _returnType << ">::dump(result);\n";
}
else
{
out << "return Py_None;\n";
}
}
out << "}\n";
out << "catch(python::Exception &)\n{\n";
out << " return 0;\n";
out << "}\n";
out << "catch(std::exception &exc)\n{\n";
// emit catch block
{
IndentingOStreambuf indenter2(out);
out << "return PyErr_Format(PyExc_RuntimeError, \"%s\", exc.what());\n";
}
out << "}\n";
}
void Function::codegenDefinition(std::ostream &out) const
{
using namespace streams;
out << boost::format(FunctionPrototype) % _implName % selfTypeName() << "\n{\n";
{
IndentingOStreambuf indenter(out);
codegenTupleUnpack(out);
codegenDefinitionBody(out);
}
out << "}\n";
}
void Function::codegenMethodTable(std::ostream &out) const
{
auto docstring = processDocString(_docstring);
out << boost::format("{\"%1%\", (PyCFunction) %2%, METH_VARARGS|METH_KEYWORDS, %3%},\n")
% pythonName()
% implName()
% ("\"" + docstring + "\"");
}
} // namespace autobind
<commit_msg>Return Py_None correctly so that it doesn't get deallocated.<commit_after>#include <iomanip>
#include <boost/format.hpp>
#include "prefix.hpp"
#include "util.hpp"
#include "stream.hpp"
#include "streamindent.hpp"
#include "printing.hpp"
#include "Function.hpp"
#include <regex>
namespace autobind {
namespace
{
const boost::format FunctionPrototype{
"static PyObject *%s(%s *self, PyObject *args, PyObject *kw)"
};
}
std::string processDocString(const std::string &docstring)
{
auto result = std::regex_replace(docstring, std::regex("(^|\n)\\s*(///|\\*)"), "$1");
replace(result, "\\", "\\\\");
replace(result, "\n", "\\n");
replace(result, "\"", "\\\"");
return result;
}
Function::Function(std::string name, std::vector<Arg> args,
std::string docstring)
: Export(std::move(name))
, _args(std::move(args))
, _docstring(std::move(docstring))
{
auto parts = rsplit(this->name(), "::");
_unqualifiedName = parts.second;
_implName = this->name();
replace(_implName, "::", "_ns_");
_implName += "_py_bind_impl";
}
void Function::codegenCall(std::ostream &out) const
{
out << name();
codegenCallArgs(out);
out << ";\n";
}
void Function::codegenCallArgs(std::ostream &out) const
{
using namespace streams;
auto argStream = stream(_args)
| enumerated()
| pairTransformed([](int i, const Arg &a) {
return a.requiresAdditionalConversion?
str(boost::format("PyConversion<%1%>::load(arg%2%)") % a.cppQualTypeName % i)
: str(boost::format("arg%1%") % i);
})
| interposed(", ");
out << "(" << cat(argStream) << ")";
}
void Function::codegenDeclaration(std::ostream &out) const
{
out << boost::format(FunctionPrototype) % _implName % selfTypeName() << ";\n";
}
void Function::codegenTupleUnpack(std::ostream &out) const
{
using namespace streams;
// declare variables
for(const auto &pair : stream(_args) | enumerated())
{
if(pair.second.requiresAdditionalConversion)
{
out << "PyObject *";
}
else
{
out << pair.second.cppQualTypeName << " ";
}
out << "arg" << pair.first << ";\n";
}
// call PyArg_ParseTuple
auto kwlistStream = stream(_args)
| transformed([](const Arg &a) { return "\"" + a.argName + "\", "; });
out << boost::format("static const char *kwlist[] = {%1%0};\n") % cat(kwlistStream);
auto argStream = count()
| take(_args.size())
| transformed([](int i) { return boost::format(", &arg%d") % i; });
auto formatStream = stream(_args)
| transformed([](const Arg &a) { return a.parseTupleFmt; });
out << boost::format("if(!PyArg_ParseTupleAndKeywords(args, kw, \"%s\", (char **)kwlist%s))\n"
" return 0;\n") % cat(formatStream) % cat(argStream);
}
void Function::codegenDefinitionBody(std::ostream &out) const
{
// emit "try" block
out << "try\n{\n";
{
IndentingOStreambuf indenter2(out);
// call function
{
if(_lineNo >= 0)
out << boost::format("#line %1% %2%\n") % _lineNo % std::quoted(_origFile);
if(_returnType != "void")
{
out << _returnType << " result = ";
}
codegenCall(out);
}
if(_returnType != "void")
{
out << "return PyConversion<" << _returnType << ">::dump(result);\n";
}
else
{
out << "Py_RETURN_NONE;\n";
}
}
out << "}\n";
out << "catch(python::Exception &)\n{\n";
out << " return 0;\n";
out << "}\n";
out << "catch(std::exception &exc)\n{\n";
// emit catch block
{
IndentingOStreambuf indenter2(out);
out << "return PyErr_Format(PyExc_RuntimeError, \"%s\", exc.what());\n";
}
out << "}\n";
}
void Function::codegenDefinition(std::ostream &out) const
{
using namespace streams;
out << boost::format(FunctionPrototype) % _implName % selfTypeName() << "\n{\n";
{
IndentingOStreambuf indenter(out);
codegenTupleUnpack(out);
codegenDefinitionBody(out);
}
out << "}\n";
}
void Function::codegenMethodTable(std::ostream &out) const
{
auto docstring = processDocString(_docstring);
out << boost::format("{\"%1%\", (PyCFunction) %2%, METH_VARARGS|METH_KEYWORDS, %3%},\n")
% pythonName()
% implName()
% ("\"" + docstring + "\"");
}
} // namespace autobind
<|endoftext|>
|
<commit_before>#ifndef QUANT_PDE_FUNCTION_HPP
#define QUANT_PDE_FUNCTION_HPP
#include <cstring> // std::memcpy
namespace QuantPDE {
/**
* Represents a function \f$f\f$ defined on some domain.
*/
class Function {
virtual Real get(const Real *) const = 0;
public:
/**
* @param coordinates Coordinates \f$\left\{c_i\right\}\f$ (passed in
* as an array) specifying a point in \f$f\f$'s
* domain.
* @return The value of \f$f\f$ at the specified coordinates (i.e.
* \f$f\left(c_0, \ldots, c_{n-1}\right)\f$).
*/
Real operator()(const Real *coordinates) const {
return get(coordinates);
}
/**
* @param coordinates Coordinates \f$\left\{c_i\right\}\f$ specifying
* a point in \f$f\f$'s domain.
* @return The value of \f$f\f$ at the specified coordinates (i.e.
* \f$f\left(c_0, \ldots, c_{n-1}\right)\f$).
*/
template <typename ...ArgsT>
Real operator()(ArgsT ...coordinates) const {
Real coords[] {coordinates...};
return get(coords);
}
/**
* @param grid A grid.
* @return The image of this function on the set of grid nodes as a
* vector.
*/
virtual Vector image(const Grid &grid) const {
Vector v = grid.vector();
Real *coordinates = new Real[grid.size()];
for(auto node : grid.accessor(v)) {
grid.coordinates(&node, coordinates);
*node = get(coordinates);
}
delete [] coordinates;
return v;
}
};
/**
* Represents a function defined on a one-dimensional domain.
*/
class Function1d : public Function {
virtual Real get(const Real *coordinates) const {
return get(*coordinates);
}
virtual Real get(Real) const = 0;
public:
virtual Vector image(const Grid &grid) const {
Vector v = grid.vector();
Real coordinates[1];
for(auto node : grid.accessor(v)) {
grid.coordinates(&node, coordinates);
*node = get(*coordinates);
}
return v;
}
};
// TODO: Function2d, Function3d, Function4d
/**
* A function \f$f\f$ whose value is constant (i.e. \f$f\left(x\right)=c\f$ for
* all \f$x\f$ in the domain of \f$f\f$).
*/
class Constant : public Function {
Real c;
virtual Real get(const Real *coordinates) const {
return c;
}
public:
/**
* Constructor.
* @param c The value of the function everywhere.
*/
Constant(Real c) : c(c) {
}
/**
* Copy constructor.
*/
Constant(const Constant &that) : c(that.c) {
}
};
/**
* A function \f$f\f$ defined piecewise whose pieces are affine functions.
* Suppose \f$f\f$ is defined on a grid composed of \f$n\f$ axes, and that the
* \f$i\f$-th axis is a partition consisting of \f$m_i\f$ nodes.
* Querying \f$f\f$ at a point involves a binary search on each axis.
* This procedure has worst-case complexity
* \f$\sim \sum_i \lg m_i \leq n \lg m\f$, where
* \f$m \equiv \max\left\{m_i\right\}\f$.
*/
class PiecewiseLinear : public Function {
const Grid &grid;
const Vector &vector;
Real interpolate(const Index *indices, const Real *start,
const Real *end) const {
if(start == end) {
return grid.accessor(vector)(indices);
}
Index dim = grid.size();
Index *other = new Index[dim];
std::memcpy(other, indices, sizeof(Index) * dim);
other[dim - (end - start)]++;
Real v = (*start)
* interpolate(indices, start + 1, end)
+ (1 - *start) * interpolate(other, start + 1,
end);
delete [] other;
return v;
}
virtual Real get(const Real *coordinates) const {
Index dim = grid.size();
Index *indices = new Index[dim];
Real *weights = new Real[dim];
{
for(Index i = 0; i < grid.size(); i++, coordinates++) {
const Axis &x = grid(i);
Index length = x.size();
if(*coordinates <= x(0)) {
indices[i] = 0;
weights[i] = 1.;
continue;
}
if(*coordinates >= x(length - 1)) {
indices[i] = length - 2;
weights[i] = 0.;
continue;
}
// Binary search to find node
Index lo = 0, hi = length - 2, mid = 0;
Real weight = 0.;
while(lo <= hi) {
mid = (lo + hi) / 2;
if(*coordinates < x(mid)) {
hi = mid - 1;
} else if(*coordinates >= x(mid + 1)) {
lo = mid + 1;
} else {
weight = (x(mid + 1)
- *coordinates)
/ ( x(mid + 1)
- x(mid) );
break;
}
}
indices[i] = mid;
weights[i] = weight;
}
}
Real v = interpolate(indices, weights, weights + dim);
delete [] indices;
delete [] weights;
return v;
}
public:
/**
* Constructor.
* @param grid A grid.
* @param vector A vector containing the values of the function at the
* grid nodes.
*/
PiecewiseLinear(const Grid &grid, const Vector &vector) : grid(grid),
vector(vector) {
}
/**
* Copy constructor.
*/
PiecewiseLinear(const PiecewiseLinear &that) : grid(that.grid),
vector(that.vector) {
}
};
template <bool isConst>
Real Grid::GridVector<isConst>::operator()(const Real *coordinates) const {
return (PiecewiseLinear(grid, vector))(coordinates);
}
}
#endif
<commit_msg>Memory is initialized only once per linear interpolation in arbitrary dimensions.<commit_after>#ifndef QUANT_PDE_FUNCTION_HPP
#define QUANT_PDE_FUNCTION_HPP
#include <cstring> // std::memcpy
namespace QuantPDE {
/**
* Represents a function \f$f\f$ defined on some domain.
*/
class Function {
virtual Real get(const Real *) const = 0;
public:
/**
* @param coordinates Coordinates \f$\left\{c_i\right\}\f$ (passed in
* as an array) specifying a point in \f$f\f$'s
* domain.
* @return The value of \f$f\f$ at the specified coordinates (i.e.
* \f$f\left(c_0, \ldots, c_{n-1}\right)\f$).
*/
Real operator()(const Real *coordinates) const {
return get(coordinates);
}
/**
* @param coordinates Coordinates \f$\left\{c_i\right\}\f$ specifying
* a point in \f$f\f$'s domain.
* @return The value of \f$f\f$ at the specified coordinates (i.e.
* \f$f\left(c_0, \ldots, c_{n-1}\right)\f$).
*/
template <typename ...ArgsT>
Real operator()(ArgsT ...coordinates) const {
Real coords[] {coordinates...};
return get(coords);
}
/**
* @param grid A grid.
* @return The image of this function on the set of grid nodes as a
* vector.
*/
virtual Vector image(const Grid &grid) const {
Vector v = grid.vector();
Real *coordinates = new Real[grid.size()];
for(auto node : grid.accessor(v)) {
grid.coordinates(&node, coordinates);
*node = get(coordinates);
}
delete [] coordinates;
return v;
}
};
/**
* Represents a function defined on a one-dimensional domain.
*/
class Function1d : public Function {
virtual Real get(const Real *coordinates) const {
return get(*coordinates);
}
virtual Real get(Real) const = 0;
public:
virtual Vector image(const Grid &grid) const {
Vector v = grid.vector();
Real coordinates[1];
for(auto node : grid.accessor(v)) {
grid.coordinates(&node, coordinates);
*node = get(*coordinates);
}
return v;
}
};
// TODO: Function2d, Function3d, Function4d
/**
* A function \f$f\f$ whose value is constant (i.e. \f$f\left(x\right)=c\f$ for
* all \f$x\f$ in the domain of \f$f\f$).
*/
class Constant : public Function {
Real c;
virtual Real get(const Real *coordinates) const {
return c;
}
public:
/**
* Constructor.
* @param c The value of the function everywhere.
*/
Constant(Real c) : c(c) {
}
/**
* Copy constructor.
*/
Constant(const Constant &that) : c(that.c) {
}
};
/**
* A function \f$f\f$ defined piecewise whose pieces are affine functions.
* Suppose \f$f\f$ is defined on a grid composed of \f$n\f$ axes, and that the
* \f$i\f$-th axis is a partition consisting of \f$m_i\f$ nodes.
* Querying \f$f\f$ at a point involves a binary search on each axis.
* This procedure has worst-case complexity
* \f$\sim \sum_i \lg m_i \leq n \lg m\f$, where
* \f$m \equiv \max\left\{m_i\right\}\f$.
*/
class PiecewiseLinear : public Function {
const Grid &grid;
const Vector &vector;
Real interpolate(Index *indices, Real *weights, Index n = 0) const {
const Index dim = grid.size();
// Base case
if(n == dim) {
return grid.accessor(vector)(indices);
}
Index *stride = indices + ( (dim - n) * dim );
std::memcpy(stride, indices, sizeof(Index) * dim);
stride[dim - n]++;
return weights[n] * interpolate(indices, weights, n + 1)
+ (1 - weights[n]) * interpolate(stride,
weights, n + 1);
}
virtual Real get(const Real *coordinates) const {
const Index dim = grid.size();
Real *weights = new Real[dim];
// We need 2^dim arrays of size dim to store indices for the
// interpolation routine. Initialize all of this at once.
Index *indices;
{
Index power = 1;
for(Index i = 0; i < dim; i++) {
power *= 2;
}
indices = new Index[power * dim];
}
// For the i-th coordinate, find the ticks on the i-th axis that
// it lies between along with the distance from the leftmost
// tick
for(Index i = 0; i < dim; i++, coordinates++) {
const Axis &x = grid(i);
Index length = x.size();
if(*coordinates <= x(0)) {
indices[i] = 0;
weights[i] = 1.;
continue;
}
if(*coordinates >= x(length - 1)) {
indices[i] = length - 2;
weights[i] = 0.;
continue;
}
// Binary search to find tick
Index lo = 0, hi = length - 2, mid = 0;
Real weight = 0.;
while(lo <= hi) {
mid = (lo + hi) / 2;
if(*coordinates < x(mid)) {
hi = mid - 1;
} else if(*coordinates >= x(mid + 1)) {
lo = mid + 1;
} else {
weight = (x(mid + 1)
- *coordinates)
/ ( x(mid + 1)
- x(mid) );
break;
}
}
indices[i] = mid;
weights[i] = weight;
}
const Real v = interpolate(indices, weights);
delete [] indices;
delete [] weights;
return v;
}
public:
/**
* Constructor.
* @param grid A grid.
* @param vector A vector containing the values of the function at the
* grid nodes.
*/
PiecewiseLinear(const Grid &grid, const Vector &vector) : grid(grid),
vector(vector) {
}
/**
* Copy constructor.
*/
PiecewiseLinear(const PiecewiseLinear &that) : grid(that.grid),
vector(that.vector) {
}
};
template <bool isConst>
Real Grid::GridVector<isConst>::operator()(const Real *coordinates) const {
return (PiecewiseLinear(grid, vector))(coordinates);
}
}
#endif
<|endoftext|>
|
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "InternalVolumetricFlowRate.h"
#include "FVUtils.h"
#include <math.h>
registerMooseObject("NavierStokesApp", InternalVolumetricFlowRate);
InputParameters
InternalVolumetricFlowRate::validParams()
{
InputParameters params = InterfaceIntegralPostprocessor::validParams();
params.addClassDescription(
"Computes the volumetric flow rate of an advected quantity through an internal boundary.");
params.addParam<bool>("fv", false, "Whether finite volume variables are used");
params.addRequiredCoupledVar("vel_x", "The x-axis velocity");
params.addCoupledVar("vel_y", 0, "The y-axis velocity");
params.addCoupledVar("vel_z", 0, "The z-axis velocity");
MooseEnum advected_interp_method("average upwind", "upwind");
params.addParam<MooseEnum>("advected_interp_method",
advected_interp_method,
"The interpolation to use for the advected quantity. Options are "
"'upwind' and 'average', with the default being 'upwind'.");
params.addCoupledVar(
"advected_variable", 0, "The advected variable quantity of which to study the flow");
params.addParam<MaterialPropertyName>(
"advected_mat_prop", 0, "The advected material property of which to study the flow");
return params;
}
InternalVolumetricFlowRate::InternalVolumetricFlowRate(const InputParameters & parameters)
: InterfaceIntegralPostprocessor(parameters),
_fv(getParam<bool>("fv")),
_vel_x(coupledValue("vel_x")),
_vel_y(coupledValue("vel_y")),
_vel_z(coupledValue("vel_z")),
_fv_vel_x(dynamic_cast<const MooseVariableFV<Real> *>(getFieldVar("vel_x", 0))),
_fv_vel_y(dynamic_cast<const MooseVariableFV<Real> *>(getFieldVar("vel_y", 0))),
_fv_vel_z(dynamic_cast<const MooseVariableFV<Real> *>(getFieldVar("vel_z", 0))),
_advected_variable_supplied(parameters.isParamSetByUser("advected_variable")),
_advected_variable(coupledValue("advected_variable")),
_fv_advected_variable(
dynamic_cast<const MooseVariableFV<Real> *>(getFieldVar("advected_variable", 0))),
_advected_mat_prop_supplied(parameters.isParamSetByUser("advected_mat_prop")),
_advected_material_property(getADMaterialProperty<Real>("advected_mat_prop")),
_advected_material_property_neighbor(getNeighborADMaterialProperty<Real>("advected_mat_prop"))
{
// Check that at most one advected quantity has been provided
if (_advected_variable_supplied && _advected_mat_prop_supplied)
mooseError(
"InternalVolumetricFlowRatePostprocessor should be provided either an advected variable or "
"an advected material property");
using namespace Moose::FV;
const auto & advected_interp_method = getParam<MooseEnum>("advected_interp_method");
if (advected_interp_method == "average")
_advected_interp_method = InterpMethod::Average;
else if (advected_interp_method == "upwind")
_advected_interp_method = InterpMethod::Upwind;
else
mooseError("Unrecognized advected quantity interpolation type ",
static_cast<std::string>(advected_interp_method));
}
Real
InternalVolumetricFlowRate::computeQpIntegral()
{
#ifdef MOOSE_GLOBAL_AD_INDEXING
if (_fv)
{
// We should not be at a boundary
const FaceInfo * const fi = _mesh.faceInfo(_current_elem, _current_side);
mooseAssert(fi, "We should have a face info");
mooseAssert(
!fi->isBoundary(),
"Use VolumetricFlowRate instead of InternalVolumetricFlowRate for domain boundaries");
const Elem * const neighbor = _current_elem->neighbor_ptr(_current_side);
// Get face value for velocity
// FIXME Make sure getInternalFaceValue uses the right interpolation method, see #16585
const auto & vx_face =
_fv_vel_x
? MetaPhysicL::raw_value(_fv_vel_x->getInternalFaceValue(neighbor, *fi, _vel_x[_qp]))
: _vel_x[_qp];
const auto & vy_face =
_fv_vel_y
? MetaPhysicL::raw_value(_fv_vel_y->getInternalFaceValue(neighbor, *fi, _vel_y[_qp]))
: _vel_y[_qp];
const auto & vz_face =
_fv_vel_z
? MetaPhysicL::raw_value(_fv_vel_z->getInternalFaceValue(neighbor, *fi, _vel_z[_qp]))
: _vel_z[_qp];
// Compute the advected quantity on the face
Real advected_quantity;
if (_advected_variable_supplied)
{
// Get neighbor value
const auto & advected_variable_neighbor =
_fv_advected_variable ? MetaPhysicL::raw_value(_fv_advected_variable->getNeighborValue(
neighbor, *fi, _advected_variable[_qp]))
: _advected_variable[_qp];
Moose::FV::interpolate(_advected_interp_method,
advected_quantity,
MetaPhysicL::raw_value(_advected_variable[_qp]),
MetaPhysicL::raw_value(advected_variable_neighbor),
RealVectorValue(vx_face, vy_face, vz_face),
*fi,
true);
}
else if (_advected_mat_prop_supplied)
{
// The material property needs to be interpolated since we are on an internal face
Moose::FV::interpolate(_advected_interp_method,
advected_quantity,
MetaPhysicL::raw_value(_advected_material_property[_qp]),
MetaPhysicL::raw_value(_advected_material_property_neighbor[_qp]),
RealVectorValue(vx_face, vy_face, vz_face),
*fi,
true);
}
else
advected_quantity = 1;
return advected_quantity * RealVectorValue(vx_face, vy_face, vz_face) * _normals[_qp];
}
else
#endif
{
if (parameters().isParamSetByUser("advected_variable"))
return _advected_variable[_qp] * RealVectorValue(_vel_x[_qp], _vel_y[_qp], _vel_z[_qp]) *
_normals[_qp];
else if (parameters().isParamSetByUser("advected_mat_prop"))
return MetaPhysicL::raw_value(_advected_material_property[_qp]) *
RealVectorValue(_vel_x[_qp], _vel_y[_qp], _vel_z[_qp]) * _normals[_qp];
else
return RealVectorValue(_vel_x[_qp], _vel_y[_qp], _vel_z[_qp]) * _normals[_qp];
}
}
<commit_msg>Pass current_elem_is_fi_elem to Moose::FV::interpolate<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "InternalVolumetricFlowRate.h"
#include "FVUtils.h"
#include <math.h>
registerMooseObject("NavierStokesApp", InternalVolumetricFlowRate);
InputParameters
InternalVolumetricFlowRate::validParams()
{
InputParameters params = InterfaceIntegralPostprocessor::validParams();
params.addClassDescription(
"Computes the volumetric flow rate of an advected quantity through an internal boundary.");
params.addParam<bool>("fv", false, "Whether finite volume variables are used");
params.addRequiredCoupledVar("vel_x", "The x-axis velocity");
params.addCoupledVar("vel_y", 0, "The y-axis velocity");
params.addCoupledVar("vel_z", 0, "The z-axis velocity");
MooseEnum advected_interp_method("average upwind", "upwind");
params.addParam<MooseEnum>("advected_interp_method",
advected_interp_method,
"The interpolation to use for the advected quantity. Options are "
"'upwind' and 'average', with the default being 'upwind'.");
params.addCoupledVar(
"advected_variable", 0, "The advected variable quantity of which to study the flow");
params.addParam<MaterialPropertyName>(
"advected_mat_prop", 0, "The advected material property of which to study the flow");
return params;
}
InternalVolumetricFlowRate::InternalVolumetricFlowRate(const InputParameters & parameters)
: InterfaceIntegralPostprocessor(parameters),
_fv(getParam<bool>("fv")),
_vel_x(coupledValue("vel_x")),
_vel_y(coupledValue("vel_y")),
_vel_z(coupledValue("vel_z")),
_fv_vel_x(dynamic_cast<const MooseVariableFV<Real> *>(getFieldVar("vel_x", 0))),
_fv_vel_y(dynamic_cast<const MooseVariableFV<Real> *>(getFieldVar("vel_y", 0))),
_fv_vel_z(dynamic_cast<const MooseVariableFV<Real> *>(getFieldVar("vel_z", 0))),
_advected_variable_supplied(parameters.isParamSetByUser("advected_variable")),
_advected_variable(coupledValue("advected_variable")),
_fv_advected_variable(
dynamic_cast<const MooseVariableFV<Real> *>(getFieldVar("advected_variable", 0))),
_advected_mat_prop_supplied(parameters.isParamSetByUser("advected_mat_prop")),
_advected_material_property(getADMaterialProperty<Real>("advected_mat_prop")),
_advected_material_property_neighbor(getNeighborADMaterialProperty<Real>("advected_mat_prop"))
{
// Check that at most one advected quantity has been provided
if (_advected_variable_supplied && _advected_mat_prop_supplied)
mooseError(
"InternalVolumetricFlowRatePostprocessor should be provided either an advected variable or "
"an advected material property");
using namespace Moose::FV;
const auto & advected_interp_method = getParam<MooseEnum>("advected_interp_method");
if (advected_interp_method == "average")
_advected_interp_method = InterpMethod::Average;
else if (advected_interp_method == "upwind")
_advected_interp_method = InterpMethod::Upwind;
else
mooseError("Unrecognized advected quantity interpolation type ",
static_cast<std::string>(advected_interp_method));
}
Real
InternalVolumetricFlowRate::computeQpIntegral()
{
#ifdef MOOSE_GLOBAL_AD_INDEXING
if (_fv)
{
// We should not be at a boundary
const FaceInfo * const fi = _mesh.faceInfo(_current_elem, _current_side);
mooseAssert(fi, "We should have a face info");
mooseAssert(
!fi->isBoundary(),
"Use VolumetricFlowRate instead of InternalVolumetricFlowRate for domain boundaries");
const bool current_elem_is_fi_elem = (_current_elem == &fi->elem());
const Elem * const neighbor = _current_elem->neighbor_ptr(_current_side);
// Get face value for velocity
// FIXME Make sure getInternalFaceValue uses the right interpolation method, see #16585
const auto & vx_face =
_fv_vel_x
? MetaPhysicL::raw_value(_fv_vel_x->getInternalFaceValue(neighbor, *fi, _vel_x[_qp]))
: _vel_x[_qp];
const auto & vy_face =
_fv_vel_y
? MetaPhysicL::raw_value(_fv_vel_y->getInternalFaceValue(neighbor, *fi, _vel_y[_qp]))
: _vel_y[_qp];
const auto & vz_face =
_fv_vel_z
? MetaPhysicL::raw_value(_fv_vel_z->getInternalFaceValue(neighbor, *fi, _vel_z[_qp]))
: _vel_z[_qp];
// Compute the advected quantity on the face
Real advected_quantity;
if (_advected_variable_supplied)
{
// Get neighbor value
const auto & advected_variable_neighbor =
_fv_advected_variable ? MetaPhysicL::raw_value(_fv_advected_variable->getNeighborValue(
neighbor, *fi, _advected_variable[_qp]))
: _advected_variable[_qp];
Moose::FV::interpolate(_advected_interp_method,
advected_quantity,
MetaPhysicL::raw_value(_advected_variable[_qp]),
MetaPhysicL::raw_value(advected_variable_neighbor),
RealVectorValue(vx_face, vy_face, vz_face),
*fi,
current_elem_is_fi_elem);
}
else if (_advected_mat_prop_supplied)
{
// The material property needs to be interpolated since we are on an internal face
Moose::FV::interpolate(_advected_interp_method,
advected_quantity,
MetaPhysicL::raw_value(_advected_material_property[_qp]),
MetaPhysicL::raw_value(_advected_material_property_neighbor[_qp]),
RealVectorValue(vx_face, vy_face, vz_face),
*fi,
current_elem_is_fi_elem);
}
else
advected_quantity = 1;
return advected_quantity * RealVectorValue(vx_face, vy_face, vz_face) * _normals[_qp];
}
else
#endif
{
if (parameters().isParamSetByUser("advected_variable"))
return _advected_variable[_qp] * RealVectorValue(_vel_x[_qp], _vel_y[_qp], _vel_z[_qp]) *
_normals[_qp];
else if (parameters().isParamSetByUser("advected_mat_prop"))
return MetaPhysicL::raw_value(_advected_material_property[_qp]) *
RealVectorValue(_vel_x[_qp], _vel_y[_qp], _vel_z[_qp]) * _normals[_qp];
else
return RealVectorValue(_vel_x[_qp], _vel_y[_qp], _vel_z[_qp]) * _normals[_qp];
}
}
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/planning_request_adapter/planning_request_adapter.h>
#include <functional>
#include <algorithm>
namespace planning_request_adapter
{
namespace
{
bool callPlannerInterfaceSolve(const planning_interface::PlannerManager& planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res)
{
planning_interface::PlanningContextPtr context = planner.getPlanningContext(planning_scene, req, res.error_code_);
if (context)
return context->solve(res);
else
return false;
}
bool callAdapter(const PlanningRequestAdapter& adapter, const PlanningRequestAdapter::PlannerFn& planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest& req, planning_interface::MotionPlanResponse& res,
std::vector<std::size_t>& added_path_index)
{
try
{
bool result = adapter.adaptAndPlan(planner, planning_scene, req, res, added_path_index);
ROS_DEBUG_STREAM_NAMED("planning_request_adapter", adapter.getDescription() << ": " << res.error_code_.val);
return result;
}
catch (std::exception& ex)
{
ROS_ERROR_NAMED("planning_request_adapter",
"Exception caught executing adapter '%s': %s\nSkipping adapter instead.",
adapter.getDescription().c_str(), ex.what());
added_path_index.clear();
return planner(planning_scene, req, res);
}
}
} // namespace
bool PlanningRequestAdapter::adaptAndPlan(const planning_interface::PlannerManagerPtr& planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res,
std::vector<std::size_t>& added_path_index) const
{
return adaptAndPlan(
[&planner](const planning_scene::PlanningSceneConstPtr& scene, const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res) {
return callPlannerInterfaceSolve(*planner, scene, req, res);
},
planning_scene, req, res, added_path_index);
}
bool PlanningRequestAdapter::adaptAndPlan(const planning_interface::PlannerManagerPtr& planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res) const
{
std::vector<std::size_t> dummy;
return adaptAndPlan(planner, planning_scene, req, res, dummy);
}
bool PlanningRequestAdapterChain::adaptAndPlan(const planning_interface::PlannerManagerPtr& planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res) const
{
std::vector<std::size_t> dummy;
return adaptAndPlan(planner, planning_scene, req, res, dummy);
}
bool PlanningRequestAdapterChain::adaptAndPlan(const planning_interface::PlannerManagerPtr& planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res,
std::vector<std::size_t>& added_path_index) const
{
// if there are no adapters, run the planner directly
if (adapters_.empty())
{
added_path_index.clear();
return callPlannerInterfaceSolve(*planner, planning_scene, req, res);
}
else
{
// the index values added by each adapter
std::vector<std::vector<std::size_t> > added_path_index_each(adapters_.size());
// if there are adapters, construct a function for each, in order,
// so that in the end we have a nested sequence of functions that calls all adapters
// and eventually the planner in the correct order.
PlanningRequestAdapter::PlannerFn fn = [&planner = *planner](const planning_scene::PlanningSceneConstPtr& scene,
const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res) {
return callPlannerInterfaceSolve(planner, scene, req, res);
};
for (int i = adapters_.size() - 1; i >= 0; --i)
{
fn = [&adapter = *adapters_[i], fn, &added_path_index = added_path_index_each[i]](
const planning_scene::PlanningSceneConstPtr& scene, const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res) {
return callAdapter(adapter, fn, scene, req, res, added_path_index);
};
}
bool result = fn(planning_scene, req, res);
added_path_index.clear();
// merge the index values from each adapter
for (std::vector<std::size_t>& added_states_by_each_adapter : added_path_index_each)
for (std::size_t& added_index : added_states_by_each_adapter)
{
for (std::size_t& index_in_path : added_path_index)
if (added_index <= index_in_path)
index_in_path++;
added_path_index.push_back(added_index);
}
std::sort(added_path_index.begin(), added_path_index.end());
return result;
}
}
} // end of namespace planning_request_adapter
<commit_msg>Further improve debug message using new operator<<(MoveItErrorCode)<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Ioan Sucan */
#include <moveit/utils/moveit_error_code.h>
#include <moveit/planning_request_adapter/planning_request_adapter.h>
#include <functional>
#include <algorithm>
namespace planning_request_adapter
{
namespace
{
bool callPlannerInterfaceSolve(const planning_interface::PlannerManager& planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res)
{
planning_interface::PlanningContextPtr context = planner.getPlanningContext(planning_scene, req, res.error_code_);
if (context)
return context->solve(res);
else
return false;
}
bool callAdapter(const PlanningRequestAdapter& adapter, const PlanningRequestAdapter::PlannerFn& planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest& req, planning_interface::MotionPlanResponse& res,
std::vector<std::size_t>& added_path_index)
{
try
{
bool result = adapter.adaptAndPlan(planner, planning_scene, req, res, added_path_index);
ROS_DEBUG_STREAM_NAMED("planning_request_adapter", adapter.getDescription()
<< ": " << moveit::core::MoveItErrorCode(res.error_code_));
return result;
}
catch (std::exception& ex)
{
ROS_ERROR_NAMED("planning_request_adapter",
"Exception caught executing adapter '%s': %s\nSkipping adapter instead.",
adapter.getDescription().c_str(), ex.what());
added_path_index.clear();
return planner(planning_scene, req, res);
}
}
} // namespace
bool PlanningRequestAdapter::adaptAndPlan(const planning_interface::PlannerManagerPtr& planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res,
std::vector<std::size_t>& added_path_index) const
{
return adaptAndPlan(
[&planner](const planning_scene::PlanningSceneConstPtr& scene, const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res) {
return callPlannerInterfaceSolve(*planner, scene, req, res);
},
planning_scene, req, res, added_path_index);
}
bool PlanningRequestAdapter::adaptAndPlan(const planning_interface::PlannerManagerPtr& planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res) const
{
std::vector<std::size_t> dummy;
return adaptAndPlan(planner, planning_scene, req, res, dummy);
}
bool PlanningRequestAdapterChain::adaptAndPlan(const planning_interface::PlannerManagerPtr& planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res) const
{
std::vector<std::size_t> dummy;
return adaptAndPlan(planner, planning_scene, req, res, dummy);
}
bool PlanningRequestAdapterChain::adaptAndPlan(const planning_interface::PlannerManagerPtr& planner,
const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res,
std::vector<std::size_t>& added_path_index) const
{
// if there are no adapters, run the planner directly
if (adapters_.empty())
{
added_path_index.clear();
return callPlannerInterfaceSolve(*planner, planning_scene, req, res);
}
else
{
// the index values added by each adapter
std::vector<std::vector<std::size_t> > added_path_index_each(adapters_.size());
// if there are adapters, construct a function for each, in order,
// so that in the end we have a nested sequence of functions that calls all adapters
// and eventually the planner in the correct order.
PlanningRequestAdapter::PlannerFn fn = [&planner = *planner](const planning_scene::PlanningSceneConstPtr& scene,
const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res) {
return callPlannerInterfaceSolve(planner, scene, req, res);
};
for (int i = adapters_.size() - 1; i >= 0; --i)
{
fn = [&adapter = *adapters_[i], fn, &added_path_index = added_path_index_each[i]](
const planning_scene::PlanningSceneConstPtr& scene, const planning_interface::MotionPlanRequest& req,
planning_interface::MotionPlanResponse& res) {
return callAdapter(adapter, fn, scene, req, res, added_path_index);
};
}
bool result = fn(planning_scene, req, res);
added_path_index.clear();
// merge the index values from each adapter
for (std::vector<std::size_t>& added_states_by_each_adapter : added_path_index_each)
for (std::size_t& added_index : added_states_by_each_adapter)
{
for (std::size_t& index_in_path : added_path_index)
if (added_index <= index_in_path)
index_in_path++;
added_path_index.push_back(added_index);
}
std::sort(added_path_index.begin(), added_path_index.end());
return result;
}
}
} // end of namespace planning_request_adapter
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/software/license/
*
* 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 <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include "PercentileGridSampler.h"
#include "GaussianProcessEmulatedModel.h"
#include "RuntimeParameterFileReader.h"
#include "ApplicationUtilities.h"
#include "Paths.h"
#include "Trace.h"
#include "madaisys/SystemTools.hxx"
using madai::Model;
using madai::Paths;
const int DEFAULT_PERCENTILE_GRID_SAMPLES = 100;
template<class S, class T>
int findIndex(const S & v, const T & s)
{
typename S::const_iterator it = std::find(v.begin(), v.end(), s);
if (it == v.end())
return -1;
return std::distance(v.begin(), it);
}
/**
Load a file with experimental observations in it. The model will
be comared against this. */
Model::ErrorType
LoadObservations(Model * model, std::istream & i)
{
// std::ifstream i("DIRECTORY/experimental_results/results.dat");
const std::vector< std::string > & scalarOutputNames = model->GetScalarOutputNames();
unsigned int numberOfScalarOutputs = model->GetNumberOfScalarOutputs();
assert(scalarOutputNames.size() == numberOfScalarOutputs);
assert (numberOfScalarOutputs > 0);
std::vector< double > observedScalarValues(numberOfScalarOutputs, 0.0);
std::vector< double > observedScalarCovariance(
numberOfScalarOutputs * numberOfScalarOutputs, 0.0);
for (unsigned int j = 0; j < numberOfScalarOutputs; ++j)
observedScalarCovariance[j * (1 + numberOfScalarOutputs)] = 1.0;
while (true) { // will loop forever if input stream lasts forever.
std::string name;
double value, uncertainty;
if(! (i >> name >> value >> uncertainty))
break;
int index = findIndex(scalarOutputNames, name);
if (index != -1) {
observedScalarValues[index] = value;
// observedScalarCovariance is a square matrix;
observedScalarCovariance[index * (1 + numberOfScalarOutputs)] = std::pow(uncertainty, 2);
// uncertainty^2 is variance.
}
}
// assume extra values are all zero.
Model::ErrorType e;
e = model->SetObservedScalarValues(observedScalarValues);
if (e != madai::Model::NO_ERROR) {
std::cerr << "Error in Model::SetObservedScalarValues\n";
return e;
}
e = model->SetObservedScalarCovariance(observedScalarCovariance);
if (e != madai::Model::NO_ERROR) {
std::cerr << "Error in Model::SetObservedScalarCovariance\n";
return e;
}
return madai::Model::NO_ERROR;
}
struct PercentileGridRuntimeParameters
{
int numberIter;
std::string ModelOutputDirectory;
std::string ExperimentalResultsDirectory;
};
bool parsePGRuntimeParameters(
int argc, char** argv,
struct PercentileGridRuntimeParameters & Opts )
{
// Initialize as defaults
Opts.ModelOutputDirectory = madai::Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY;
Opts.ExperimentalResultsDirectory = madai::Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY;
Opts.numberIter = DEFAULT_PERCENTILE_GRID_SAMPLES;
for ( unsigned int i = 0; i < argc; i++ ) {
std::string argString( argv[i] );
if ( argString == "MODEL_OUTPUT_DIRECTORY" ) {
Opts.ModelOutputDirectory = std::string( argv[i+1] );
i++;
} else if ( argString == "EXPERIMENTAL_RESULTS_DIRECTORY" ) {
Opts.ExperimentalResultsDirectory = std::string( argv[i+1] );
i++;
} else if ( argString == "PERCENTILE_GRID_SAMPLES" ) {
Opts.numberIter = atoi( argv[i+1] );
if ( Opts.numberIter <= 0 ) {
std::cerr << "Error: PERCENTILE_GRID_SAMPLES given incorrect argument \""
<< Opts.numberIter << "\"\n";
}
i++;
}
}
return true;
}
/**
\fixme document
*/
int main(int argc, char ** argv) {
if (argc < 3) {
std::cerr << "Useage:\n"
<< " generatePercentileGridTrace <StatisticsDirectory> <OutputFileName>\n"
<< "\n"
<< "This file generates a sampling of an emulated model on a\n"
<< "regular lattice of sample points.\n"
<< "\n"
<< "<StatisticsDirectory> is the directory in which all \n"
<< "statistics data are stored. It contains the parameter file "
<< Paths::RUNTIME_PARAMETER_FILE << "\n"
<< "\n"
<< "<OutputFileName> is the name of the comma-separated value-format \n"
<< "file in which the trace will be written. This file will be \n"
<< "written in the directory <StatisticsDirectory>/trace/.\n"
<< "\n"
<< "Format of entries in " << Paths::RUNTIME_PARAMETER_FILE
<< ":\n\n"
<< "MODEL_OUTPUT_DIRECTORY <value> (default: "
<< Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY << ")\n"
<< "EXPERIMENTAL_RESULTS_DIRECTORY <value> (default: "
<< Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY << ")\n"
<< "PERCENTILE_GRID_SAMPLES <value> (default: "
<< DEFAULT_PERCENTILE_GRID_SAMPLES << ")\n";
return EXIT_FAILURE;
}
std::string StatisticsDirectory( argv[1] );
std::string OutputFileName( argv[2] );
madai::EnsurePathSeparatorAtEnd( StatisticsDirectory );
madai::RuntimeParameterFileReader RPFR;
RPFR.ParseFile( StatisticsDirectory + madai::Paths::RUNTIME_PARAMETER_FILE );
char** Args = RPFR.GetArguments();
int NArgs = RPFR.GetNumberOfArguments();
struct PercentileGridRuntimeParameters Opts;
if ( !parsePGRuntimeParameters( NArgs, Args, Opts ) ) {
std::cerr << "Error: Parsing configuration file for gaussian process percentile grid.\n";
return EXIT_FAILURE;
}
madai::GaussianProcessEmulatedModel gpem;
std::string MOD = StatisticsDirectory + Opts.ModelOutputDirectory;
std::string ERD = StatisticsDirectory + Opts.ExperimentalResultsDirectory;
if ( gpem.LoadConfiguration( StatisticsDirectory, MOD, ERD ) != madai::Model::NO_ERROR ) {
std::cerr << "error in GaussianProcessEmulatedModel::LoadConfiguration\n";
return EXIT_FAILURE;
}
gpem.SetUseModelCovarianceToCalulateLogLikelihood(false);
std::string observationsFile = ERD + madai::Paths::SEPARATOR + madai::Paths::RESULTS_FILE;
std::ifstream observations( observationsFile.c_str() );
if (madai::Model::NO_ERROR != LoadObservations(&gpem, observations)) {
std::cerr << "error loading observations.\n";
return EXIT_FAILURE;
}
observations.close();
madai::PercentileGridSampler sampler;
sampler.SetModel( &gpem );
sampler.SetNumberSamples(Opts.numberIter);
int numberIter = sampler.GetNumberSamples();
std::vector< madai::Parameter > const & parameters
= gpem.GetParameters();
madai::Trace trace;
int step = numberIter / 100, percent = 0;
for (int count = 0; count < numberIter; count ++) {
if (count % step == 0)
std::cerr << '\r' << percent++ << "%";
trace.Add(sampler.NextSample());
}
std::cerr << "\r" ;
std::string traceDirectory = StatisticsDirectory + madai::Paths::TRACE_DIRECTORY;
madaisys::SystemTools::MakeDirectory( traceDirectory.c_str() );
std::string OutputFile = traceDirectory + OutputFileName;
std::ofstream Out( OutputFile.c_str() );
trace.WriteCSVOutput(
Out,
gpem.GetParameters(),
gpem.GetScalarOutputNames() );
return EXIT_SUCCESS;
}
<commit_msg>Cleaned up generatePercentileGridTrace<commit_after>/*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/software/license/
*
* 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 <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include "PercentileGridSampler.h"
#include "GaussianProcessEmulatedModel.h"
#include "RuntimeParameterFileReader.h"
#include "ApplicationUtilities.h"
#include "Paths.h"
#include "Trace.h"
#include "madaisys/SystemTools.hxx"
using madai::Model;
using madai::Paths;
static const int DEFAULT_PERCENTILE_GRID_NUMBER_OF_SAMPLES = 100;
template<class S, class T>
int findIndex(const S & v, const T & s)
{
typename S::const_iterator it = std::find(v.begin(), v.end(), s);
if (it == v.end())
return -1;
return std::distance(v.begin(), it);
}
/**
Load a file with experimental observations in it. The model will
be compared against this. */
Model::ErrorType
LoadObservations(Model * model, std::istream & i)
{
// std::ifstream i("DIRECTORY/experimental_results/results.dat");
const std::vector< std::string > & scalarOutputNames = model->GetScalarOutputNames();
unsigned int numberOfScalarOutputs = model->GetNumberOfScalarOutputs();
assert(scalarOutputNames.size() == numberOfScalarOutputs);
assert (numberOfScalarOutputs > 0);
std::vector< double > observedScalarValues(numberOfScalarOutputs, 0.0);
std::vector< double > observedScalarCovariance(
numberOfScalarOutputs * numberOfScalarOutputs, 0.0);
for (unsigned int j = 0; j < numberOfScalarOutputs; ++j)
observedScalarCovariance[j * (1 + numberOfScalarOutputs)] = 1.0;
while (true) { // will loop forever if input stream lasts forever.
std::string name;
double value, uncertainty;
if(! (i >> name >> value >> uncertainty))
break;
int index = findIndex(scalarOutputNames, name);
if (index != -1) {
observedScalarValues[index] = value;
// observedScalarCovariance is a square matrix;
observedScalarCovariance[index * (1 + numberOfScalarOutputs)] = std::pow(uncertainty, 2);
// uncertainty^2 is variance.
}
}
// assume extra values are all zero.
Model::ErrorType e;
e = model->SetObservedScalarValues(observedScalarValues);
if (e != madai::Model::NO_ERROR) {
std::cerr << "Error in Model::SetObservedScalarValues\n";
return e;
}
e = model->SetObservedScalarCovariance(observedScalarCovariance);
if (e != madai::Model::NO_ERROR) {
std::cerr << "Error in Model::SetObservedScalarCovariance\n";
return e;
}
return madai::Model::NO_ERROR;
}
int main(int argc, char ** argv) {
if (argc < 3) {
std::cerr << "Usage:\n"
<< " generatePercentileGridTrace <StatisticsDirectory> <OutputFileName>\n"
<< "\n"
<< "This file generates a sampling of an emulated model on a\n"
<< "regular lattice of sample points.\n"
<< "\n"
<< "<StatisticsDirectory> is the directory in which all \n"
<< "statistics data are stored. It contains the parameter file "
<< Paths::RUNTIME_PARAMETER_FILE << "\n"
<< "\n"
<< "<OutputFileName> is the name of the comma-separated value-format \n"
<< "file in which the trace will be written. This file will be \n"
<< "written in the directory <StatisticsDirectory>/trace/.\n"
<< "\n"
<< "Format of entries in " << Paths::RUNTIME_PARAMETER_FILE
<< ":\n\n"
<< "MODEL_OUTPUT_DIRECTORY <value> (default: "
<< Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY << ")\n"
<< "EXPERIMENTAL_RESULTS_DIRECTORY <value> (default: "
<< Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY << ")\n"
<< "PERCENTILE_GRID_NUMBER_OF_SAMPLES <value> (default: "
<< DEFAULT_PERCENTILE_GRID_NUMBER_OF_SAMPLES << ")\n";
return EXIT_FAILURE;
}
std::string statisticsDirectory( argv[1] );
madai::EnsurePathSeparatorAtEnd( statisticsDirectory );
madai::RuntimeParameterFileReader settings;
std::string settingsFile = statisticsDirectory + madai::Paths::RUNTIME_PARAMETER_FILE;
if ( !settings.ParseFile( settingsFile ) ) {
std::cerr << "Could not open runtime parameter file '" << settingsFile << "'\n";
return EXIT_FAILURE;
}
std::string modelOutputDirectory =
madai::GetModelOutputDirectory( statisticsDirectory, settings );
std::string experimentalResultsDirectory =
madai::GetExperimentalResultsDirectory( statisticsDirectory, settings );
int numberOfSamples = DEFAULT_PERCENTILE_GRID_NUMBER_OF_SAMPLES;
if ( settings.HasOption( "PERCENTILE_GRID_NUMBER_OF_SAMPLES" ) ) {
numberOfSamples = atoi( settings.GetOption( "PERCENTILE_GRID_NUMBER_OF_SAMPLES" ).c_str() );
}
madai::GaussianProcessEmulatedModel gpem;
if ( gpem.LoadConfiguration( statisticsDirectory,
modelOutputDirectory,
experimentalResultsDirectory ) != madai::Model::NO_ERROR ) {
std::cerr << "Error in GaussianProcessEmulatedModel::LoadConfiguration\n";
return EXIT_FAILURE;
}
gpem.SetUseModelCovarianceToCalulateLogLikelihood( false );
std::string observationsFile = experimentalResultsDirectory + Paths::SEPARATOR +
Paths::RESULTS_FILE;
std::ifstream observations( observationsFile.c_str() );
if ( madai::Model::NO_ERROR != LoadObservations( &gpem, observations ) ) {
std::cerr << "Error loading observations.\n";
return EXIT_FAILURE;
}
observations.close();
madai::PercentileGridSampler sampler;
sampler.SetModel( &gpem );
sampler.SetNumberSamples( numberOfSamples );
numberOfSamples = sampler.GetNumberSamples();
std::vector< madai::Parameter > const & parameters = gpem.GetParameters();
madai::Trace trace;
int step = numberOfSamples / 100, percent = 0;
for (int count = 0; count < numberOfSamples; count ++) {
if (count % step == 0)
std::cout << '\r' << percent++ << "%";
trace.Add(sampler.NextSample());
}
std::cout << "\r" ;
std::string traceDirectory = statisticsDirectory + madai::Paths::TRACE_DIRECTORY;
madaisys::SystemTools::MakeDirectory( traceDirectory.c_str() );
std::string outputFileName( argv[2] );
std::string outputFile = traceDirectory + Paths::SEPARATOR + outputFileName;
std::ofstream out( outputFile.c_str() );
trace.WriteCSVOutput( out,
gpem.GetParameters(),
gpem.GetScalarOutputNames() );
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by J-Donald Tournier, 27/06/08.
This file is part of MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include <fstream>
#include <set>
#include "app.h"
#include "progressbar.h"
#include "get_set.h"
#include "image/voxel.h"
#include "dataset/misc.h"
#include "dataset/buffer.h"
#include "dataset/interp/linear.h"
#include "thread/exec.h"
#include "thread/queue.h"
#include "math/hermite.h"
#include "dwi/tractography/file.h"
#include "dwi/tractography/properties.h"
using namespace MR;
using namespace MR::DWI;
using namespace std;
SET_VERSION_DEFAULT;
DESCRIPTION = {
"convert a tracks file into a map of the fraction of tracks to enter each voxel.",
NULL
};
ARGUMENTS = {
Argument ("tracks", "track file", "the input track file.").type_file (),
Argument ("template", "template image", "an image file to be used as a template for the output (the output image wil have the same voxel size and dimensions).").type_image_in(),
Argument ("output", "output image", "the output fraction image").type_image_out(),
Argument::End
};
OPTIONS = {
Option ("fraction", "output fibre fraction", "produce an image of the fraction of fibres through each voxel (as a proportion of the total number in the file), rather than the count."),
Option ("datatype", "data type", "specify output image data type.")
.append (Argument ("spec", "specifier", "the data type specifier.").type_choice (DataType::identifiers)),
Option ("resample", "resample tracks", "resample the tracks at regular intervals using Hermite interpolation.")
.append (Argument ("factor", "factor", "the factor by which to resample.").type_integer (1, INT_MAX, 1)),
Option::End
};
class Voxel
{
public:
Voxel () { }
Voxel (const Point& p) :
x (Math::round<size_t> (p[0])),
y (Math::round<size_t> (p[1])),
z (Math::round<size_t> (p[2])) { }
bool operator< (const Voxel& v) const
{
if (x < v.x) return (true);
if (x > v.x) return (false);
if (y < v.y) return (true);
if (y > v.y) return (false);
if (z < v.z) return (true);
return (false);
}
size_t x, y, z;
};
typedef Thread::Queue<std::vector<Point> > Queue1;
typedef Thread::Queue<std::set<Voxel> > Queue2;
class TrackLoader
{
public:
TrackLoader (Queue1& queue, DWI::Tractography::Reader& file, size_t count) :
writer (queue),
reader (file),
total_count (count) { }
void execute ()
{
Queue1::Writer::Item item (writer);
ProgressBar progress ("mapping tracks to image...", total_count);
while (reader.next (*item)) {
if (!item.write())
throw Exception ("error writing to track-mapping queue!");
++progress;
}
}
private:
Queue1::Writer writer;
DWI::Tractography::Reader& reader;
size_t total_count;
};
class TrackMapper
{
public:
TrackMapper (Queue1& input, Queue2& output, const Image::Header& header, const Math::Matrix<float>* resample_matrix = NULL) :
reader (input),
writer (output),
H (header),
resampler (resample_matrix) {
}
void execute ()
{
Queue1::Reader::Item in (reader);
Queue2::Writer::Item out (writer);
DataSet::Interp::Linear<const Image::Header> interp (H);
Math::Matrix<float> resampled, orig (4,3);
if (resampler)
resampled.allocate (resampler->rows(), 3);
while (in.read()) {
out->clear();
for (std::vector<Point>::const_iterator i = in->begin(); i != in->end(); ++i) {
out->insert (Voxel (interp.scanner2voxel (*i)));
if (resampler) { // TODO: this is not complete!!!
Math::mult (resampled, *resampler, orig);
}
}
if (!out.write())
throw Exception ("error writing to write-back queue!");
}
}
private:
Queue1::Reader reader;
Queue2::Writer writer;
const Image::Header& H;
const Math::Matrix<float>* resampler;
};
class MapWriter
{
public:
MapWriter (Queue2& queue, const Image::Header& header, bool fraction_scaling_factor) :
reader (queue),
H (header),
buffer (H, "buffer"),
interp (H),
scale (fraction_scaling_factor)
{
}
~MapWriter ()
{
if (scale) {
Image::Voxel<float> vox (H);
DataSet::Loop loop ("writing data back to image...", 0, 3);
for (loop.start (vox, buffer); loop.ok(); loop.next (vox, buffer))
vox.value() = scale * buffer.value();
}
else {
Image::Voxel<size_t> vox (H);
DataSet::copy_with_progress_message ("writing data back to image...", vox, buffer, 0, 3);
}
}
void execute ()
{
Queue2::Reader::Item item (reader);
while (item.read()) {
for (std::set<Voxel>::const_iterator i = item->begin(); i != item->end(); ++i) {
buffer[0] = i->x;
buffer[1] = i->y;
buffer[2] = i->z;
buffer.value() += 1;
}
}
}
private:
Queue2::Reader reader;
const Image::Header& H;
DataSet::Buffer<size_t,3> buffer;
DataSet::Interp::Linear<const Image::Header> interp;
float scale;
};
EXECUTE {
Image::Header header (argument[1].get_image());
bool fibre_fraction = get_options("count").size();
std::vector<OptBase> opt = get_options ("datatype");
if (opt.size())
header.datatype().parse (DataType::identifiers[opt[0][0].get_int()]);
else
header.datatype() = fibre_fraction ? DataType::Float32 : DataType::UInt32;
Tractography::Properties properties;
Tractography::Reader file;
file.open (argument[0].get_string(), properties);
header.axes.ndim() = 3;
header.comments.push_back (std::string ("track ") + (fibre_fraction ? "fraction" : "count") + " map");
for (Tractography::Properties::iterator i = properties.begin(); i != properties.end(); ++i)
header.comments.push_back (i->first + ": " + i->second);
for (std::multimap<std::string,std::string>::const_iterator i = properties.roi.begin(); i != properties.roi.end(); ++i)
header.comments.push_back ("ROI: " + i->first + " " + i->second);
for (std::vector<std::string>::iterator i = properties.comments.begin(); i != properties.comments.end(); ++i)
header.comments.push_back ("comment: " + *i);
const Image::Header header_out = argument[2].get_image (header);
size_t total_count = properties["total_count"].empty() ? 0 : to<size_t> (properties["total_count"]);
size_t num_tracks = properties["count"].empty() ? 0 : to<size_t> (properties["count"]);
Queue1 queue1 ("loaded tracks");
Queue2 queue2 ("processed tracks");
TrackLoader loader (queue1, file, num_tracks);
TrackMapper mapper (queue1, queue2, header_out);
MapWriter writer (queue2, header_out, total_count ? 1.0 / total_count : 0.0);
Thread::Exec loader_thread (loader, "loader");
Thread::Array<TrackMapper> mapper_list (mapper);
Thread::Exec mapper_threads (mapper_list, "mapper");
writer.execute();
}
<commit_msg>minor change in tckmap help page<commit_after>/*
Copyright 2008 Brain Research Institute, Melbourne, Australia
Written by J-Donald Tournier, 27/06/08.
This file is part of MRtrix.
MRtrix 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.
MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>.
*/
#include <fstream>
#include <set>
#include "app.h"
#include "progressbar.h"
#include "get_set.h"
#include "image/voxel.h"
#include "dataset/misc.h"
#include "dataset/buffer.h"
#include "dataset/interp/linear.h"
#include "thread/exec.h"
#include "thread/queue.h"
#include "math/hermite.h"
#include "dwi/tractography/file.h"
#include "dwi/tractography/properties.h"
using namespace MR;
using namespace MR::DWI;
using namespace std;
SET_VERSION_DEFAULT;
DESCRIPTION = {
"convert a tracks file into a map of the number of tracks to enter each voxel.",
NULL
};
ARGUMENTS = {
Argument ("tracks", "track file", "the input track file.").type_file (),
Argument ("template", "template image", "an image file to be used as a template for the output (the output image wil have the same voxel size and dimensions).").type_image_in(),
Argument ("output", "output image", "the output fraction image").type_image_out(),
Argument::End
};
OPTIONS = {
Option ("fraction", "output fibre fraction", "produce an image of the fraction of fibres through each voxel (as a proportion of the total number in the file), rather than the count."),
Option ("datatype", "data type", "specify output image data type.")
.append (Argument ("spec", "specifier", "the data type specifier.").type_choice (DataType::identifiers)),
Option ("resample", "resample tracks", "resample the tracks at regular intervals using Hermite interpolation.")
.append (Argument ("factor", "factor", "the factor by which to resample.").type_integer (1, INT_MAX, 1)),
Option::End
};
class Voxel
{
public:
Voxel () { }
Voxel (const Point& p) :
x (Math::round<size_t> (p[0])),
y (Math::round<size_t> (p[1])),
z (Math::round<size_t> (p[2])) { }
bool operator< (const Voxel& v) const
{
if (x < v.x) return (true);
if (x > v.x) return (false);
if (y < v.y) return (true);
if (y > v.y) return (false);
if (z < v.z) return (true);
return (false);
}
size_t x, y, z;
};
typedef Thread::Queue<std::vector<Point> > Queue1;
typedef Thread::Queue<std::set<Voxel> > Queue2;
class TrackLoader
{
public:
TrackLoader (Queue1& queue, DWI::Tractography::Reader& file, size_t count) :
writer (queue),
reader (file),
total_count (count) { }
void execute ()
{
Queue1::Writer::Item item (writer);
ProgressBar progress ("mapping tracks to image...", total_count);
while (reader.next (*item)) {
if (!item.write())
throw Exception ("error writing to track-mapping queue!");
++progress;
}
}
private:
Queue1::Writer writer;
DWI::Tractography::Reader& reader;
size_t total_count;
};
class TrackMapper
{
public:
TrackMapper (Queue1& input, Queue2& output, const Image::Header& header, const Math::Matrix<float>* resample_matrix = NULL) :
reader (input),
writer (output),
H (header),
resampler (resample_matrix) {
}
void execute ()
{
Queue1::Reader::Item in (reader);
Queue2::Writer::Item out (writer);
DataSet::Interp::Linear<const Image::Header> interp (H);
Math::Matrix<float> resampled, orig (4,3);
if (resampler)
resampled.allocate (resampler->rows(), 3);
while (in.read()) {
out->clear();
for (std::vector<Point>::const_iterator i = in->begin(); i != in->end(); ++i) {
out->insert (Voxel (interp.scanner2voxel (*i)));
if (resampler) { // TODO: this is not complete!!!
Math::mult (resampled, *resampler, orig);
}
}
if (!out.write())
throw Exception ("error writing to write-back queue!");
}
}
private:
Queue1::Reader reader;
Queue2::Writer writer;
const Image::Header& H;
const Math::Matrix<float>* resampler;
};
class MapWriter
{
public:
MapWriter (Queue2& queue, const Image::Header& header, bool fraction_scaling_factor) :
reader (queue),
H (header),
buffer (H, "buffer"),
interp (H),
scale (fraction_scaling_factor)
{
}
~MapWriter ()
{
if (scale) {
Image::Voxel<float> vox (H);
DataSet::Loop loop ("writing data back to image...", 0, 3);
for (loop.start (vox, buffer); loop.ok(); loop.next (vox, buffer))
vox.value() = scale * buffer.value();
}
else {
Image::Voxel<size_t> vox (H);
DataSet::copy_with_progress_message ("writing data back to image...", vox, buffer, 0, 3);
}
}
void execute ()
{
Queue2::Reader::Item item (reader);
while (item.read()) {
for (std::set<Voxel>::const_iterator i = item->begin(); i != item->end(); ++i) {
buffer[0] = i->x;
buffer[1] = i->y;
buffer[2] = i->z;
buffer.value() += 1;
}
}
}
private:
Queue2::Reader reader;
const Image::Header& H;
DataSet::Buffer<size_t,3> buffer;
DataSet::Interp::Linear<const Image::Header> interp;
float scale;
};
EXECUTE {
Image::Header header (argument[1].get_image());
bool fibre_fraction = get_options("count").size();
std::vector<OptBase> opt = get_options ("datatype");
if (opt.size())
header.datatype().parse (DataType::identifiers[opt[0][0].get_int()]);
else
header.datatype() = fibre_fraction ? DataType::Float32 : DataType::UInt32;
Tractography::Properties properties;
Tractography::Reader file;
file.open (argument[0].get_string(), properties);
header.axes.ndim() = 3;
header.comments.push_back (std::string ("track ") + (fibre_fraction ? "fraction" : "count") + " map");
for (Tractography::Properties::iterator i = properties.begin(); i != properties.end(); ++i)
header.comments.push_back (i->first + ": " + i->second);
for (std::multimap<std::string,std::string>::const_iterator i = properties.roi.begin(); i != properties.roi.end(); ++i)
header.comments.push_back ("ROI: " + i->first + " " + i->second);
for (std::vector<std::string>::iterator i = properties.comments.begin(); i != properties.comments.end(); ++i)
header.comments.push_back ("comment: " + *i);
const Image::Header header_out = argument[2].get_image (header);
size_t total_count = properties["total_count"].empty() ? 0 : to<size_t> (properties["total_count"]);
size_t num_tracks = properties["count"].empty() ? 0 : to<size_t> (properties["count"]);
Queue1 queue1 ("loaded tracks");
Queue2 queue2 ("processed tracks");
TrackLoader loader (queue1, file, num_tracks);
TrackMapper mapper (queue1, queue2, header_out);
MapWriter writer (queue2, header_out, total_count ? 1.0 / total_count : 0.0);
Thread::Exec loader_thread (loader, "loader");
Thread::Array<TrackMapper> mapper_list (mapper);
Thread::Exec mapper_threads (mapper_list, "mapper");
writer.execute();
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.