text stringlengths 54 60.6k |
|---|
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGOutput.cpp
Author: Jon Berndt
Date started: 12/02/98
Purpose: Manage output of sim parameters to file, stdout or socket
Called by: FGSimExec
------------- Copyright (C) 1999 Jon S. Berndt (jon@jsbsim.org) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
This is the place where you create output routines to dump data for perusal
later.
HISTORY
--------------------------------------------------------------------------------
12/02/98 JSB Created
11/09/07 HDW Added FlightGear Socket Interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGOutput.h"
#include "FGFDMExec.h"
#include "input_output/FGOutputSocket.h"
#include "input_output/FGOutputTextFile.h"
#include "input_output/FGOutputFG.h"
using namespace std;
namespace JSBSim {
static const char *IdSrc = "$Id$";
static const char *IdHdr = ID_OUTPUT;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGOutput::FGOutput(FGFDMExec* fdmex) : FGModel(fdmex)
{
typedef int (FGOutput::*iOPV)(void) const;
Name = "FGOutput";
fdmex->GetPropertyManager()->Tie("simulation/force-output", this, (iOPV)0, &FGOutput::ForceOutput, false);
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGOutput::~FGOutput()
{
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
delete (*it);
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::InitModel(void)
{
bool ret = false;
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
ret &= (*it)->InitModel();
return ret;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::Run(bool Holding)
{
if (FGModel::Run(Holding)) return true;
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
(*it)->Run(Holding);
return false;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutput::Print(void)
{
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
(*it)->Print();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutput::SetStartNewOutput(void)
{
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
(*it)->SetStartNewOutput();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutput::Enable(void)
{
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
(*it)->Enable();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutput::Disable(void)
{
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
(*it)->Disable();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::Toggle(int idx)
{
if (idx >= (int)0 && idx < (int)OutputTypes.size())
return OutputTypes[idx]->Toggle();
return false;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutput::SetRate(double rate)
{
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
(*it)->SetRate(rate);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutput::ForceOutput(int idx)
{
if (idx >= (int)0 && idx < (int)OutputTypes.size())
OutputTypes[idx]->Print();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::SetOutputName(unsigned int idx, const std::string& name)
{
if (idx >= OutputTypes.size()) return false;
OutputTypes[idx]->SetOutputName(name);
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
string FGOutput::GetOutputName(unsigned int idx) const
{
string name;
if (idx < OutputTypes.size())
name = OutputTypes[idx]->GetOutputName();
return name;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::SetDirectivesFile(const std::string& fname)
{
Element* document = LoadXMLDocument(fname);
bool result = Load(document);
ResetParser();
if (!result)
cerr << endl << "Aircraft output element has problems in file " << fname << endl;
return result;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::Load(int subSystems, std::string protocol, std::string type,
std::string port, std::string name, double outRate,
std::vector<FGPropertyNode_ptr> & outputProperties)
{
unsigned int idx = OutputTypes.size();
FGOutputType* Output = 0;
if (debug_lvl > 0) cout << endl << " Output data set: " << idx << " ";
if (type == "CSV") {
FGOutputTextFile* OutputTextFile = new FGOutputTextFile(FDMExec);
OutputTextFile->SetDelimiter(",");
Output = OutputTextFile;
} else if (type == "TABULAR") {
FGOutputTextFile* OutputTextFile = new FGOutputTextFile(FDMExec);
OutputTextFile->SetDelimiter("\t");
Output = OutputTextFile;
} else if (type == "SOCKET") {
Output = new FGOutputSocket(FDMExec);
name += ":" + port + "/" + protocol;
} else if (type == "FLIGHTGEAR") {
Output = new FGOutputFG(FDMExec);
name += ":" + port + "/" + protocol;
} else if (type == "TERMINAL") {
// Not done yet
} else if (type != string("NONE")) {
cerr << "Unknown type of output specified in config file" << endl;
}
if (!Output) return false;
Output->SetIdx(idx);
Output->SetOutputName(name);
Output->SetRate(outRate);
Output->SetSubSystems(subSystems);
Output->SetOutputProperties(outputProperties);
OutputTypes.push_back(Output);
Debug(2);
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::Load(Element* document)
{
if (!document) return false;
unsigned int idx = OutputTypes.size();
string type = document->GetAttributeValue("type");
FGOutputType* Output = 0;
if (debug_lvl > 0) cout << endl << " Output data set: " << idx << " ";
if (type == "CSV") {
Output = new FGOutputTextFile(FDMExec);
} else if (type == "TABULAR") {
Output = new FGOutputTextFile(FDMExec);
} else if (type == "SOCKET") {
Output = new FGOutputSocket(FDMExec);
} else if (type == "FLIGHTGEAR") {
Output = new FGOutputFG(FDMExec);
} else if (type == "TERMINAL") {
// Not done yet
} else if (type != string("NONE")) {
cerr << "Unknown type of output specified in config file" << endl;
}
if (!Output) return false;
Output->SetIdx(idx);
Output->Load(document);
OutputTypes.push_back(Output);
Debug(2);
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGOutput::Debug(int from)
{
string scratch="";
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
}
if (from == 2) {
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGOutput" << endl;
if (from == 1) cout << "Destroyed: FGOutput" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
<commit_msg>Fixed an output typo.<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGOutput.cpp
Author: Jon Berndt
Date started: 12/02/98
Purpose: Manage output of sim parameters to file, stdout or socket
Called by: FGSimExec
------------- Copyright (C) 1999 Jon S. Berndt (jon@jsbsim.org) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
This is the place where you create output routines to dump data for perusal
later.
HISTORY
--------------------------------------------------------------------------------
12/02/98 JSB Created
11/09/07 HDW Added FlightGear Socket Interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGOutput.h"
#include "FGFDMExec.h"
#include "input_output/FGOutputSocket.h"
#include "input_output/FGOutputTextFile.h"
#include "input_output/FGOutputFG.h"
using namespace std;
namespace JSBSim {
static const char *IdSrc = "$Id: FGOutput.cpp,v 1.73 2013/09/11 12:44:02 jberndt Exp $";
static const char *IdHdr = ID_OUTPUT;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGOutput::FGOutput(FGFDMExec* fdmex) : FGModel(fdmex)
{
typedef int (FGOutput::*iOPV)(void) const;
Name = "FGOutput";
fdmex->GetPropertyManager()->Tie("simulation/force-output", this, (iOPV)0, &FGOutput::ForceOutput, false);
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGOutput::~FGOutput()
{
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
delete (*it);
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::InitModel(void)
{
bool ret = false;
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
ret &= (*it)->InitModel();
return ret;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::Run(bool Holding)
{
if (FGModel::Run(Holding)) return true;
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
(*it)->Run(Holding);
return false;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutput::Print(void)
{
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
(*it)->Print();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutput::SetStartNewOutput(void)
{
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
(*it)->SetStartNewOutput();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutput::Enable(void)
{
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
(*it)->Enable();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutput::Disable(void)
{
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
(*it)->Disable();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::Toggle(int idx)
{
if (idx >= (int)0 && idx < (int)OutputTypes.size())
return OutputTypes[idx]->Toggle();
return false;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutput::SetRate(double rate)
{
vector<FGOutputType*>::iterator it;
for (it = OutputTypes.begin(); it != OutputTypes.end(); ++it)
(*it)->SetRate(rate);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGOutput::ForceOutput(int idx)
{
if (idx >= (int)0 && idx < (int)OutputTypes.size())
OutputTypes[idx]->Print();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::SetOutputName(unsigned int idx, const std::string& name)
{
if (idx >= OutputTypes.size()) return false;
OutputTypes[idx]->SetOutputName(name);
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
string FGOutput::GetOutputName(unsigned int idx) const
{
string name;
if (idx < OutputTypes.size())
name = OutputTypes[idx]->GetOutputName();
return name;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::SetDirectivesFile(const std::string& fname)
{
Element* document = LoadXMLDocument(fname);
bool result = Load(document);
ResetParser();
if (!result)
cerr << endl << "Aircraft output element has problems in file " << fname << endl;
return result;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::Load(int subSystems, std::string protocol, std::string type,
std::string port, std::string name, double outRate,
std::vector<FGPropertyNode_ptr> & outputProperties)
{
unsigned int idx = OutputTypes.size();
FGOutputType* Output = 0;
if (debug_lvl > 0) cout << endl << " Output data set: " << idx << endl;
type = to_upper(type);
if (type == "CSV") {
FGOutputTextFile* OutputTextFile = new FGOutputTextFile(FDMExec);
OutputTextFile->SetDelimiter(",");
Output = OutputTextFile;
} else if (type == "TABULAR") {
FGOutputTextFile* OutputTextFile = new FGOutputTextFile(FDMExec);
OutputTextFile->SetDelimiter("\t");
Output = OutputTextFile;
} else if (type == "SOCKET") {
Output = new FGOutputSocket(FDMExec);
name += ":" + port + "/" + protocol;
} else if (type == "FLIGHTGEAR") {
Output = new FGOutputFG(FDMExec);
name += ":" + port + "/" + protocol;
} else if (type == "TERMINAL") {
// Not done yet
} else if (type != string("NONE")) {
cerr << "Unknown type of output specified in config file" << endl;
}
if (!Output) return false;
Output->SetIdx(idx);
Output->SetOutputName(name);
Output->SetRate(outRate);
Output->SetSubSystems(subSystems);
Output->SetOutputProperties(outputProperties);
OutputTypes.push_back(Output);
Debug(2);
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGOutput::Load(Element* document)
{
if (!document) return false;
unsigned int idx = OutputTypes.size();
string type = document->GetAttributeValue("type");
FGOutputType* Output = 0;
if (debug_lvl > 0) cout << endl << " Output data set: " << idx << " " << endl;
type = to_upper(type);
if (type == "CSV") {
Output = new FGOutputTextFile(FDMExec);
} else if (type == "TABULAR") {
Output = new FGOutputTextFile(FDMExec);
} else if (type == "SOCKET") {
Output = new FGOutputSocket(FDMExec);
} else if (type == "FLIGHTGEAR") {
Output = new FGOutputFG(FDMExec);
} else if (type == "TERMINAL") {
// Not done yet
} else if (type != string("NONE")) {
cerr << "Unknown type of output specified in config file" << endl;
}
if (!Output) return false;
Output->SetIdx(idx);
Output->Load(document);
OutputTypes.push_back(Output);
Debug(2);
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGOutput::Debug(int from)
{
string scratch="";
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
}
if (from == 2) {
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGOutput" << endl;
if (from == 1) cout << "Destroyed: FGOutput" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
<|endoftext|> |
<commit_before>/*
* Adapter Pattern
* Author: Kei Nakata
* Date: Oct.6.2014
* Convert the interface of a class into another interface clients expect.
* Adapter lets classes work together that couldn't otherwise because of incompatible
* interfaces.
*/
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <stack>
using std::cout;
using std::endl;
class Target
{
public:
virtual ~Target() {}
virtual void show()
{
cout << "World" << endl;
}
};
class Adaptee
{
public:
virtual ~Adaptee() {}
void print()
{
cout << "Heelo";
}
};
class Adapter : public Target, private Adaptee
{
public:
virtual ~Adapter() {}
virtual void show()
{
Adaptee::print();
cout << " ";
Target::show();
}
};
int main()
{
Adapter a;
a.show();
return EXIT_SUCCESS;
}
<commit_msg>modify Adapter.cpp<commit_after>/*
* Adapter Pattern
* Author: Kei Nakata
* Date: Oct.6.2014
* Convert the interface of a class into another interface clients
* expect. Adapter lets classes work together that couldn't otherwise
* because of incompatible interfaces.
*/
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
class Target
{
public:
virtual ~Target() {}
virtual void show()
{
cout << "World" << endl;
}
};
class Adaptee
{
public:
virtual ~Adaptee() {}
void print()
{
cout << "Heelo";
}
};
class Adapter : public Target, private Adaptee
{
public:
virtual ~Adapter() {}
virtual void show()
{
Adaptee::print();
cout << " ";
Target::show();
}
};
int main()
{
Adapter a;
a.show();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <Keybind.h>
#include <Utility.h>
#include <sstream>
#include <ConfigurationFile.h>
#include <numeric>
#include <Core.h>
namespace GW2Radial
{
Keybind::Keybind(std::string nickname, std::string displayName, std::string category, ScanCode key, Modifier mod, bool saveToConfig) :
nickname_(std::move(nickname)), displayName_(std::move(displayName)), category_(std::move(category)), saveToConfig_(saveToConfig)
{
keyCombo({ key, mod });
Core::i().RegisterOnFocus(this);
}
Keybind::Keybind(std::string nickname, std::string displayName, std::string category) :
nickname_(std::move(nickname)), displayName_(std::move(displayName)), category_(std::move(category))
{
auto keys = ConfigurationFile::i().ini().GetValue("Keybinds.2", nickname_.c_str());
if(keys) ParseConfig(keys);
else {
keys = ConfigurationFile::i().ini().GetValue("Keybinds", nickname_.c_str());
if(keys) ParseKeys(keys);
}
Core::i().RegisterOnFocus(this);
}
Keybind::~Keybind()
{
Core::i([&](auto& i) { i.UnregisterOnFocus(this); });
}
void Keybind::ParseKeys(const char* keys)
{
key_ = ScanCode::NONE;
mod_ = Modifier::NONE;
if (strnlen_s(keys, 256) > 0)
{
std::stringstream ss(keys);
std::vector<std::string> result;
while (ss.good())
{
std::string substr;
std::getline(ss, substr, ',');
auto val = std::stoi(substr);
val = MapVirtualKeyA(val, MAPVK_VK_TO_VSC);
ScanCode code = ScanCode(uint(val));
if (IsModifier(code)) {
if (key_ != ScanCode::NONE)
mod_ = mod_ | ToModifier(code);
else
key_ = code;
} else {
if (IsModifier(key_))
mod_ = mod_ | ToModifier(key_);
key_ = code;
}
}
}
ApplyKeys();
}
void Keybind::ParseConfig(const char* keys)
{
std::vector<std::string> k;
SplitString(keys, ",", std::back_inserter(k));
if (k.empty()) {
key_ = ScanCode::NONE;
return;
}
key_ = ScanCode(uint(std::stoi(k[0].c_str())));
if (k.size() == 1)
mod_ = Modifier::NONE;
else
mod_ = Modifier(ushort(std::stoi(k[1].c_str())));
}
void Keybind::ApplyKeys()
{
UpdateDisplayString();
if(saveToConfig_ && key_ != ScanCode::NONE)
{
std::string settingValue = std::to_string(uint(key_)) + ", " + std::to_string(uint(mod_));
auto& cfg = ConfigurationFile::i();
cfg.ini().SetValue("Keybinds.2", nickname_.c_str(), settingValue.c_str());
cfg.Save();
}
}
[[nodiscard]]
bool Keybind::matches(const KeyCombo& ks) const {
return key_ == ks.key() && (mod_ & ks.mod()) == mod_;
}
void Keybind::UpdateDisplayString(const std::optional<KeyCombo>& kc) const
{
auto k = kc ? *kc : KeyCombo(key_, mod_);
if(k.key() == ScanCode::NONE)
{
keysDisplayString_[0] = '\0';
return;
}
std::wstring keybind;
if (notNone(k.mod() & Modifier::CTRL))
keybind += L"CTRL + ";
if (notNone(k.mod() & Modifier::ALT))
keybind += L"ALT + ";
if (notNone(k.mod() & Modifier::SHIFT))
keybind += L"SHIFT + ";
keybind += GetScanCodeName(k.key());
Log::i().Print(Severity::Debug, L"Setting keybind '{}' to display '{}'", utf8_decode(nickname()), keybind);
strcpy_s(keysDisplayString_.data(), keysDisplayString_.size(), utf8_encode(keybind).c_str());
}
}
<commit_msg>Fixed initial keybind load not updating display string.<commit_after>#include <Keybind.h>
#include <Utility.h>
#include <sstream>
#include <ConfigurationFile.h>
#include <numeric>
#include <Core.h>
namespace GW2Radial
{
Keybind::Keybind(std::string nickname, std::string displayName, std::string category, ScanCode key, Modifier mod, bool saveToConfig) :
nickname_(std::move(nickname)), displayName_(std::move(displayName)), category_(std::move(category)), saveToConfig_(saveToConfig)
{
keyCombo({ key, mod });
Core::i().RegisterOnFocus(this);
}
Keybind::Keybind(std::string nickname, std::string displayName, std::string category) :
nickname_(std::move(nickname)), displayName_(std::move(displayName)), category_(std::move(category))
{
auto keys = ConfigurationFile::i().ini().GetValue("Keybinds.2", nickname_.c_str());
if(keys) ParseConfig(keys);
else {
keys = ConfigurationFile::i().ini().GetValue("Keybinds", nickname_.c_str());
if(keys) ParseKeys(keys);
}
Core::i().RegisterOnFocus(this);
}
Keybind::~Keybind()
{
Core::i([&](auto& i) { i.UnregisterOnFocus(this); });
}
void Keybind::ParseKeys(const char* keys)
{
key_ = ScanCode::NONE;
mod_ = Modifier::NONE;
if (strnlen_s(keys, 256) > 0)
{
std::stringstream ss(keys);
std::vector<std::string> result;
while (ss.good())
{
std::string substr;
std::getline(ss, substr, ',');
auto val = std::stoi(substr);
val = MapVirtualKeyA(val, MAPVK_VK_TO_VSC);
ScanCode code = ScanCode(uint(val));
if (IsModifier(code)) {
if (key_ != ScanCode::NONE)
mod_ = mod_ | ToModifier(code);
else
key_ = code;
} else {
if (IsModifier(key_))
mod_ = mod_ | ToModifier(key_);
key_ = code;
}
}
}
ApplyKeys();
}
void Keybind::ParseConfig(const char* keys)
{
std::vector<std::string> k;
SplitString(keys, ",", std::back_inserter(k));
if (k.empty()) {
key_ = ScanCode::NONE;
return;
}
key_ = ScanCode(uint(std::stoi(k[0].c_str())));
if (k.size() == 1)
mod_ = Modifier::NONE;
else
mod_ = Modifier(ushort(std::stoi(k[1].c_str())));
ApplyKeys();
}
void Keybind::ApplyKeys()
{
UpdateDisplayString();
if(saveToConfig_ && key_ != ScanCode::NONE)
{
std::string settingValue = std::to_string(uint(key_)) + ", " + std::to_string(uint(mod_));
auto& cfg = ConfigurationFile::i();
cfg.ini().SetValue("Keybinds.2", nickname_.c_str(), settingValue.c_str());
cfg.Save();
}
}
[[nodiscard]]
bool Keybind::matches(const KeyCombo& ks) const {
return key_ == ks.key() && (mod_ & ks.mod()) == mod_;
}
void Keybind::UpdateDisplayString(const std::optional<KeyCombo>& kc) const
{
auto k = kc ? *kc : KeyCombo(key_, mod_);
if(k.key() == ScanCode::NONE)
{
keysDisplayString_[0] = '\0';
return;
}
std::wstring keybind;
if (notNone(k.mod() & Modifier::CTRL))
keybind += L"CTRL + ";
if (notNone(k.mod() & Modifier::ALT))
keybind += L"ALT + ";
if (notNone(k.mod() & Modifier::SHIFT))
keybind += L"SHIFT + ";
keybind += GetScanCodeName(k.key());
Log::i().Print(Severity::Debug, L"Setting keybind '{}' to display '{}'", utf8_decode(nickname()), keybind);
strcpy_s(keysDisplayString_.data(), keysDisplayString_.size(), utf8_encode(keybind).c_str());
}
}
<|endoftext|> |
<commit_before>#include "pch.h"
#include "Servo.h"
namespace winrt::servo {
void on_load_started() { sServo->Delegate().OnServoLoadStarted(); }
void on_load_ended() { sServo->Delegate().OnServoLoadEnded(); }
void on_history_changed(bool back, bool forward) {
sServo->Delegate().OnServoHistoryChanged(back, forward);
}
void on_shutdown_complete() { sServo->Delegate().OnServoShutdownComplete(); }
void on_title_changed(const char *title) {
sServo->Delegate().OnServoTitleChanged(char2hstring(title));
}
void on_url_changed(const char *url) {
sServo->Delegate().OnServoURLChanged(char2hstring(url));
}
void flush() { sServo->Delegate().Flush(); }
void make_current() { sServo->Delegate().MakeCurrent(); }
void wakeup() { sServo->Delegate().WakeUp(); }
bool on_allow_navigation(const char *url) {
return sServo->Delegate().OnServoAllowNavigation(char2hstring(url));
};
void on_animating_changed(bool aAnimating) {
sServo->Delegate().OnServoAnimatingChanged(aAnimating);
}
void on_panic(const char *backtrace) {
throw hresult_error(E_FAIL, char2hstring(backtrace));
}
void on_ime_state_changed(bool aShow) {
sServo->Delegate().OnServoIMEStateChanged(aShow);
}
void set_clipboard_contents(const char *content) {
// FIXME
}
const char *get_clipboard_contents() {
// FIXME
return nullptr;
}
void on_media_session_metadata(const char *title, const char *album,
const char *artist) {
return sServo->Delegate().OnServoMediaSessionMetadata(
char2hstring(title), char2hstring(album), char2hstring(artist));
}
void on_media_session_playback_state_change(
const capi::CMediaSessionPlaybackState state) {
return sServo->Delegate().OnServoMediaSessionPlaybackStateChange(state);
}
void prompt_alert(const char *message, bool trusted) {
sServo->Delegate().OnServoPromptAlert(char2hstring(message), trusted);
}
Servo::PromptResult prompt_ok_cancel(const char *message, bool trusted) {
return sServo->Delegate().OnServoPromptOkCancel(char2hstring(message),
trusted);
}
Servo::PromptResult prompt_yes_no(const char *message, bool trusted) {
return sServo->Delegate().OnServoPromptYesNo(char2hstring(message), trusted);
}
const char *prompt_input(const char *message, const char *default,
bool trusted) {
auto input = sServo->Delegate().OnServoPromptInput(
char2hstring(message), char2hstring(default), trusted);
if (input.has_value()) {
return *hstring2char(*input);
} else {
return nullptr;
}
}
Servo::Servo(hstring url, hstring args, GLsizei width, GLsizei height,
float dpi, ServoDelegate &aDelegate)
: mWindowHeight(height), mWindowWidth(width), mDelegate(aDelegate) {
capi::CInitOptions o;
hstring defaultPrefs = L" --pref dom.webxr.enabled";
o.args = *hstring2char(args + defaultPrefs);
o.url = *hstring2char(url);
o.width = mWindowWidth;
o.height = mWindowHeight;
o.density = dpi;
o.enable_subpixel_text_antialiasing = false;
o.vr_pointer = NULL;
// 7 filter modules.
/* Sample list of servo modules to filter.
static char *pfilters[] = {
"servo",
"simpleservo",
"simpleservo::jniapi",
"simpleservo::gl_glue::egl",
// Show JS errors by default.
"script::dom::bindings::error",
// Show GL errors by default.
"canvas::webgl_thread",
"compositing::compositor",
"constellation::constellation",
};
*/
// Example Call when *pfilters[] is used:
// o.vslogger_mod_list = pfilters; // servo log modules
// o.vslogger_mod_size = sizeof(pfilters) / sizeof(pfilters[0]); //
// Important: Number of modules in pfilters
o.vslogger_mod_list = NULL;
o.vslogger_mod_size = 0;
sServo = this; // FIXME;
capi::CHostCallbacks c;
c.flush = &flush;
c.make_current = &make_current;
c.on_load_started = &on_load_started;
c.on_load_ended = &on_load_ended;
c.on_title_changed = &on_title_changed;
c.on_url_changed = &on_url_changed;
c.on_history_changed = &on_history_changed;
c.on_animating_changed = &on_animating_changed;
c.on_shutdown_complete = &on_shutdown_complete;
c.on_allow_navigation = &on_allow_navigation;
c.on_ime_state_changed = &on_ime_state_changed;
c.get_clipboard_contents = &get_clipboard_contents;
c.set_clipboard_contents = &set_clipboard_contents;
c.on_media_session_metadata = &on_media_session_metadata;
c.on_media_session_playback_state_change =
&on_media_session_playback_state_change;
c.prompt_alert = &prompt_alert;
c.prompt_ok_cancel = &prompt_ok_cancel;
c.prompt_yes_no = &prompt_yes_no;
c.prompt_input = &prompt_input;
capi::register_panic_handler(&on_panic);
capi::init_with_egl(o, &wakeup, c);
}
Servo::~Servo() { sServo = nullptr; }
winrt::hstring char2hstring(const char *c_str) {
// FIXME: any better way of doing this?
auto str = std::string(c_str);
int size_needed =
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring str2(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &str2[0],
size_needed);
winrt::hstring str3{str2};
return str3;
}
std::unique_ptr<char *> hstring2char(hstring hstr) {
const wchar_t *wc = hstr.c_str();
size_t size = hstr.size() + 1;
char *str = new char[size];
size_t converted = 0;
wcstombs_s(&converted, str, size, wc, hstr.size());
return std::make_unique<char *>(str);
}
} // namespace winrt::servo
<commit_msg>enable devtools for hololens<commit_after>#include "pch.h"
#include "Servo.h"
namespace winrt::servo {
void on_load_started() { sServo->Delegate().OnServoLoadStarted(); }
void on_load_ended() { sServo->Delegate().OnServoLoadEnded(); }
void on_history_changed(bool back, bool forward) {
sServo->Delegate().OnServoHistoryChanged(back, forward);
}
void on_shutdown_complete() { sServo->Delegate().OnServoShutdownComplete(); }
void on_title_changed(const char *title) {
sServo->Delegate().OnServoTitleChanged(char2hstring(title));
}
void on_url_changed(const char *url) {
sServo->Delegate().OnServoURLChanged(char2hstring(url));
}
void flush() { sServo->Delegate().Flush(); }
void make_current() { sServo->Delegate().MakeCurrent(); }
void wakeup() { sServo->Delegate().WakeUp(); }
bool on_allow_navigation(const char *url) {
return sServo->Delegate().OnServoAllowNavigation(char2hstring(url));
};
void on_animating_changed(bool aAnimating) {
sServo->Delegate().OnServoAnimatingChanged(aAnimating);
}
void on_panic(const char *backtrace) {
throw hresult_error(E_FAIL, char2hstring(backtrace));
}
void on_ime_state_changed(bool aShow) {
sServo->Delegate().OnServoIMEStateChanged(aShow);
}
void set_clipboard_contents(const char *content) {
// FIXME
}
const char *get_clipboard_contents() {
// FIXME
return nullptr;
}
void on_media_session_metadata(const char *title, const char *album,
const char *artist) {
return sServo->Delegate().OnServoMediaSessionMetadata(
char2hstring(title), char2hstring(album), char2hstring(artist));
}
void on_media_session_playback_state_change(
const capi::CMediaSessionPlaybackState state) {
return sServo->Delegate().OnServoMediaSessionPlaybackStateChange(state);
}
void prompt_alert(const char *message, bool trusted) {
sServo->Delegate().OnServoPromptAlert(char2hstring(message), trusted);
}
Servo::PromptResult prompt_ok_cancel(const char *message, bool trusted) {
return sServo->Delegate().OnServoPromptOkCancel(char2hstring(message),
trusted);
}
Servo::PromptResult prompt_yes_no(const char *message, bool trusted) {
return sServo->Delegate().OnServoPromptYesNo(char2hstring(message), trusted);
}
const char *prompt_input(const char *message, const char *default,
bool trusted) {
auto input = sServo->Delegate().OnServoPromptInput(
char2hstring(message), char2hstring(default), trusted);
if (input.has_value()) {
return *hstring2char(*input);
} else {
return nullptr;
}
}
Servo::Servo(hstring url, hstring args, GLsizei width, GLsizei height,
float dpi, ServoDelegate &aDelegate)
: mWindowHeight(height), mWindowWidth(width), mDelegate(aDelegate) {
capi::CInitOptions o;
hstring defaultPrefs = L" --pref dom.webxr.enabled --devtools=6000";
o.args = *hstring2char(args + defaultPrefs);
o.url = *hstring2char(url);
o.width = mWindowWidth;
o.height = mWindowHeight;
o.density = dpi;
o.enable_subpixel_text_antialiasing = false;
o.vr_pointer = NULL;
// 7 filter modules.
/* Sample list of servo modules to filter.
static char *pfilters[] = {
"servo",
"simpleservo",
"simpleservo::jniapi",
"simpleservo::gl_glue::egl",
// Show JS errors by default.
"script::dom::bindings::error",
// Show GL errors by default.
"canvas::webgl_thread",
"compositing::compositor",
"constellation::constellation",
};
*/
// Example Call when *pfilters[] is used:
// o.vslogger_mod_list = pfilters; // servo log modules
// o.vslogger_mod_size = sizeof(pfilters) / sizeof(pfilters[0]); //
// Important: Number of modules in pfilters
o.vslogger_mod_list = NULL;
o.vslogger_mod_size = 0;
sServo = this; // FIXME;
capi::CHostCallbacks c;
c.flush = &flush;
c.make_current = &make_current;
c.on_load_started = &on_load_started;
c.on_load_ended = &on_load_ended;
c.on_title_changed = &on_title_changed;
c.on_url_changed = &on_url_changed;
c.on_history_changed = &on_history_changed;
c.on_animating_changed = &on_animating_changed;
c.on_shutdown_complete = &on_shutdown_complete;
c.on_allow_navigation = &on_allow_navigation;
c.on_ime_state_changed = &on_ime_state_changed;
c.get_clipboard_contents = &get_clipboard_contents;
c.set_clipboard_contents = &set_clipboard_contents;
c.on_media_session_metadata = &on_media_session_metadata;
c.on_media_session_playback_state_change =
&on_media_session_playback_state_change;
c.prompt_alert = &prompt_alert;
c.prompt_ok_cancel = &prompt_ok_cancel;
c.prompt_yes_no = &prompt_yes_no;
c.prompt_input = &prompt_input;
capi::register_panic_handler(&on_panic);
capi::init_with_egl(o, &wakeup, c);
}
Servo::~Servo() { sServo = nullptr; }
winrt::hstring char2hstring(const char *c_str) {
// FIXME: any better way of doing this?
auto str = std::string(c_str);
int size_needed =
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring str2(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &str2[0],
size_needed);
winrt::hstring str3{str2};
return str3;
}
std::unique_ptr<char *> hstring2char(hstring hstr) {
const wchar_t *wc = hstr.c_str();
size_t size = hstr.size() + 1;
char *str = new char[size];
size_t converted = 0;
wcstombs_s(&converted, str, size, wc, hstr.size());
return std::make_unique<char *>(str);
}
} // namespace winrt::servo
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Andrei Pangin
*
* 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 <stdio.h>
#include <stdlib.h>
#include <cstdint>
#include <string.h>
#include <signal.h>
#include <string>
#include <sys/time.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <proto/protocol.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <unordered_set>
#include "profiler.h"
#include "vmEntry.h"
using namespace me::serce::franky;
Profiler Profiler::_instance;
static void sigprofHandler(int signo, siginfo_t *siginfo, void *ucontext) {
Profiler::_instance.recordSample(ucontext);
}
MethodName::MethodName(jmethodID method) {
jclass method_class;
jvmtiEnv *jvmti = VM::jvmti();
jvmti->GetMethodName(method, &_name, &_sig, NULL);
jvmti->GetMethodDeclaringClass(method, &method_class);
jvmti->GetClassSignature(method_class, &_class_sig, NULL);
char *s;
for (s = _class_sig; *s; s++) {
if (*s == '/') *s = '.';
}
s[-1] = 0;
}
MethodName::~MethodName() {
jvmtiEnv *jvmti = VM::jvmti();
jvmti->Deallocate((unsigned char *) _name);
jvmti->Deallocate((unsigned char *) _sig);
jvmti->Deallocate((unsigned char *) _class_sig);
}
void CallTraceSample::assign(ASGCT_CallTrace *trace) {
_call_count = 1;
_num_frames = trace->num_frames;
for (int i = 0; i < trace->num_frames; i++) {
_frames[i] = trace->frames[i];
}
}
uint64_t Profiler::hashCallTrace(ASGCT_CallTrace *trace) {
const uint64_t M = 0xc6a4a7935bd1e995LL;
const int R = 47;
uint64_t h = trace->num_frames * M;
for (int i = 0; i < trace->num_frames; i++) {
uint64_t k = ((uint64_t) trace->frames[i].bci << 32) ^(uint64_t) trace->frames[i].method_id;
k *= M;
k ^= k >> R;
k *= M;
h ^= k;
h *= M;
}
h ^= h >> R;
h *= M;
h ^= h >> R;
return h;
}
void Profiler::storeCallTrace(ASGCT_CallTrace *trace) {
uint64_t hash = hashCallTrace(trace);
int bucket = (int) (hash % MAX_CALLTRACES);
int i = bucket;
do {
if (_hashes[i] == hash && _traces[i]._call_count > 0) {
_traces[i]._call_count++;
return;
} else if (_hashes[i] == 0) {
break;
}
if (++i == MAX_CALLTRACES) i = 0;
} while (i != bucket);
_hashes[i] = hash;
_traces[i].assign(trace);
}
uint64_t Profiler::hashMethod(jmethodID method) {
const uint64_t M = 0xc6a4a7935bd1e995LL;
const int R = 17;
uint64_t h = (uint64_t) method;
h ^= h >> R;
h *= M;
h ^= h >> R;
return h;
}
void Profiler::storeMethod(jmethodID method) {
uint64_t hash = hashMethod(method);
int bucket = (int) (hash % MAX_CALLTRACES);
int i = bucket;
do {
if (_methods[i]._method == method) {
_methods[i]._call_count++;
return;
} else if (_methods[i]._method == NULL) {
break;
}
if (++i == MAX_CALLTRACES) i = 0;
} while (i != bucket);
_methods[i]._call_count = 1;
_methods[i]._method = method;
}
void Profiler::recordSample(void *ucontext) {
_calls_total++;
JNIEnv *jni = VM::jni();
if (jni == NULL) {
_calls_non_java++;
return;
}
ASGCT_CallFrame frames[MAX_FRAMES];
ASGCT_CallTrace trace = {jni, MAX_FRAMES, frames};
AsyncGetCallTrace(&trace, trace.num_frames, ucontext);
if (trace.num_frames > 0) {
storeCallTrace(&trace);
storeMethod(frames[0].method_id);
} else if (trace.num_frames == -2) {
_calls_gc++;
} else if (trace.num_frames == -9) {
_calls_deopt++;
} else {
_calls_unknown++;
}
}
void Profiler::setTimer(long sec, long usec) {
bool enabled = sec != 0 || usec != 0;
struct sigaction sa;
sa.sa_handler = enabled ? NULL : SIG_IGN;
sa.sa_sigaction = enabled ? &sigprofHandler : NULL;
sa.sa_flags = SA_RESTART | SA_SIGINFO;
sigemptyset(&sa.sa_mask);
sigaction(SIGPROF, &sa, NULL);
struct itimerval itv = {{sec, usec},
{sec, usec}};
setitimer(ITIMER_PROF, &itv, NULL);
}
void Profiler::start(long interval) {
if (_running) return;
_running = true;
_calls_total = _calls_non_java = _calls_gc = _calls_deopt = _calls_unknown = 0;
memset(_hashes, 0, sizeof(_hashes));
memset(_traces, 0, sizeof(_traces));
memset(_methods, 0, sizeof(_methods));
setTimer(interval / 1000, interval * 1000);
}
void Profiler::stop() {
if (!_running) return;
_running = false;
setTimer(0, 0);
}
void error(const char *msg) {
std::string res = std::string("ERROR") + std::string(msg);
perror(res.c_str());
exit(0);
}
void sendResponse(int sockfd, me::serce::franky::Response &message) {
using namespace google::protobuf;
using namespace google::protobuf::io;
FileOutputStream raw_output(sockfd);
google::protobuf::io::CodedOutputStream output(&raw_output);
// Write the size.
const int size = message.ByteSize();
output.WriteVarint32((uint32) size);
uint8_t *buffer = output.GetDirectBufferForNBytesAndAdvance(size);
if (buffer != NULL) {
// Optimization: The message fits in one buffer, so use the faster
// direct-to-array serialization path.
message.SerializeWithCachedSizesToArray(buffer);
} else {
// Slightly-slower path when the message is multiple buffers.
message.SerializeWithCachedSizes(&output);
if (output.HadError()) {
error("HAD ERROR");
}
}
}
void Profiler::init(int port) {
portno = (uint16_t) port;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("opening socket");
}
server = gethostbyname("localhost");
if (server == NULL) {
error("unable to connect to localhost");
}
struct sockaddr_in serv_addr;
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy(server->h_addr, (char *) &serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
error("connecting");
}
Response response;
response.set_id(getpid());
response.set_type(Response_ResponseType_INIT);
sendResponse(sockfd, response);
while (true) {
Request request;
readRequest(&request);
switch (request.type()) {
case Request_RequestType_START_PROFILING:
start(DEFAULT_INTERVAL);
break;
case Request_RequestType_STOP_PROFILING:
stop();
writeResult();
break;
case Request_RequestType_DETACH:
close(sockfd);
return;
default:
continue;
}
}
}
void Profiler::readRequest(Request *message) {
using namespace google::protobuf;
using namespace google::protobuf::io;
FileInputStream raw_input(sockfd);
google::protobuf::io::CodedInputStream input(&raw_input);
// Read the size.
uint32_t size;
if (!input.ReadVarint32(&size)) {
error("Error reading variint32");
}
// Tell the stream not to read beyond that size.
input.PushLimit(size);
// Parse the message.
if (!message->MergeFromCodedStream(&input)) {
error("Error paring message 1");
}
if (!input.ConsumedEntireMessage()) {
error("Error paring message 2");
}
}
int64_t jMethodIdToId(const jmethodID &jmethod) {
return (int64_t) jmethod;
}
MethodInfo *fillMethodInfo(MethodInfo *methodInfo, const jmethodID &jmethod) {
MethodName mn(jmethod);
methodInfo->set_jmethodid(jMethodIdToId(jmethod));
methodInfo->set_name(mn.name());
methodInfo->set_holder(mn.holder());
methodInfo->set_sig(mn.signature());
return methodInfo;
}
void Profiler::writeResult() {
Response response;
ProfilingInfo *info = new ProfilingInfo();
info->set_calls_total(_calls_total);
info->set_calls_non_java(_calls_non_java);
info->set_calls_gc(_calls_gc);
info->set_calls_deopt(_calls_deopt);
info->set_calls_unknown(_calls_unknown);
std::unordered_set<jmethodID> methodIds;
saveMethods(info, methodIds);
saveCallTraces(info, methodIds);
saveMethodIds(info, methodIds);
response.set_id(getpid());
response.set_type(Response_ResponseType_PROF_INFO);
response.set_allocated_prof_info(info);
sendResponse(sockfd, response);
}
void Profiler::saveCallTraces(ProfilingInfo *info, std::unordered_set<jmethodID> &methods) {
qsort(_traces, MAX_CALLTRACES, sizeof(CallTraceSample), CallTraceSample::comparator);
int max_traces = MAX_CALLTRACES;
for (int i = 0; i < max_traces; i++) {
const CallTraceSample &trace = _traces[i];
int samples = trace._call_count;
if (samples == 0) break;
CallTraceSampleInfo *sampleInfo = info->add_samples();
sampleInfo->set_call_count(trace._call_count);
for (int j = 0; j < trace._num_frames; j++) {
const ASGCT_CallFrame *frame = &trace._frames[j];
jmethodID jmethod = frame->method_id;
if (jmethod != NULL) {
CallFrame *callFrame = sampleInfo->add_frame();
callFrame->set_bci(frame->bci);
callFrame->set_jmethodid(jMethodIdToId(jmethod));
methods.insert(jmethod);
}
}
}
}
void Profiler::saveMethods(ProfilingInfo *info, std::unordered_set<jmethodID> &methods) {
qsort(_methods, MAX_CALLTRACES, sizeof(MethodSample), MethodSample::comparator);
for (int i = 0; i < MAX_CALLTRACES; i++) {
int samples = _methods[i]._call_count;
if (samples == 0) break;
jmethodID jmethod = _methods[i]._method;
MethodSampleInfo *sampleInfo = info->add_methods();
sampleInfo->set_call_count(samples);
sampleInfo->set_jmethodid(jMethodIdToId(jmethod));
methods.insert(jmethod);
}
}
void Profiler::saveMethodIds(ProfilingInfo *info, std::unordered_set<jmethodID> &methodIds) {
for (auto &jmethod: methodIds) {
MethodInfo *methodInfo = info->add_methodinfos();
fillMethodInfo(methodInfo, jmethod);
}
}
<commit_msg>Deoptimization template<commit_after>/*
* Copyright 2016 Andrei Pangin
*
* 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 <stdio.h>
#include <stdlib.h>
#include <cstdint>
#include <string.h>
#include <signal.h>
#include <string>
#include <sys/time.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <proto/protocol.pb.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <unordered_set>
#include "profiler.h"
#include "vmEntry.h"
using namespace me::serce::franky;
Profiler Profiler::_instance;
static void sigprofHandler(int signo, siginfo_t *siginfo, void *ucontext) {
Profiler::_instance.recordSample(ucontext);
}
MethodName::MethodName(jmethodID method) {
jclass method_class;
jvmtiEnv *jvmti = VM::jvmti();
jvmti->GetMethodName(method, &_name, &_sig, NULL);
jvmti->GetMethodDeclaringClass(method, &method_class);
jvmti->GetClassSignature(method_class, &_class_sig, NULL);
char *s;
for (s = _class_sig; *s; s++) {
if (*s == '/') *s = '.';
}
s[-1] = 0;
}
MethodName::~MethodName() {
jvmtiEnv *jvmti = VM::jvmti();
jvmti->Deallocate((unsigned char *) _name);
jvmti->Deallocate((unsigned char *) _sig);
jvmti->Deallocate((unsigned char *) _class_sig);
}
void CallTraceSample::assign(ASGCT_CallTrace *trace) {
_call_count = 1;
_num_frames = trace->num_frames;
for (int i = 0; i < trace->num_frames; i++) {
_frames[i] = trace->frames[i];
}
}
uint64_t Profiler::hashCallTrace(ASGCT_CallTrace *trace) {
const uint64_t M = 0xc6a4a7935bd1e995LL;
const int R = 47;
uint64_t h = trace->num_frames * M;
for (int i = 0; i < trace->num_frames; i++) {
uint64_t k = ((uint64_t) trace->frames[i].bci << 32) ^(uint64_t) trace->frames[i].method_id;
k *= M;
k ^= k >> R;
k *= M;
h ^= k;
h *= M;
}
h ^= h >> R;
h *= M;
h ^= h >> R;
return h;
}
void Profiler::storeCallTrace(ASGCT_CallTrace *trace) {
uint64_t hash = hashCallTrace(trace);
int bucket = (int) (hash % MAX_CALLTRACES);
int i = bucket;
do {
if (_hashes[i] == hash && _traces[i]._call_count > 0) {
_traces[i]._call_count++;
return;
} else if (_hashes[i] == 0) {
break;
}
if (++i == MAX_CALLTRACES) i = 0;
} while (i != bucket);
_hashes[i] = hash;
_traces[i].assign(trace);
}
uint64_t Profiler::hashMethod(jmethodID method) {
const uint64_t M = 0xc6a4a7935bd1e995LL;
const int R = 17;
uint64_t h = (uint64_t) method;
h ^= h >> R;
h *= M;
h ^= h >> R;
return h;
}
void Profiler::storeMethod(jmethodID method) {
uint64_t hash = hashMethod(method);
int bucket = (int) (hash % MAX_CALLTRACES);
int i = bucket;
do {
if (_methods[i]._method == method) {
_methods[i]._call_count++;
return;
} else if (_methods[i]._method == NULL) {
break;
}
if (++i == MAX_CALLTRACES) i = 0;
} while (i != bucket);
_methods[i]._call_count = 1;
_methods[i]._method = method;
}
void Profiler::recordSample(void *ucontext) {
_calls_total++;
JNIEnv *jni = VM::jni();
if (jni == NULL) {
_calls_non_java++;
return;
}
ASGCT_CallFrame frames[MAX_FRAMES];
ASGCT_CallTrace trace = {jni, MAX_FRAMES, frames};
AsyncGetCallTrace(&trace, trace.num_frames, ucontext);
if (trace.num_frames > 0) {
storeCallTrace(&trace);
storeMethod(frames[0].method_id);
} else if (trace.num_frames == -2) {
_calls_gc++;
} else if (trace.num_frames == -9) {
_calls_deopt++;
} else {
_calls_unknown++;
}
}
void Profiler::setTimer(long sec, long usec) {
bool enabled = sec != 0 || usec != 0;
struct sigaction sa;
sa.sa_handler = enabled ? NULL : SIG_IGN;
sa.sa_sigaction = enabled ? &sigprofHandler : NULL;
sa.sa_flags = SA_RESTART | SA_SIGINFO;
sigemptyset(&sa.sa_mask);
sigaction(SIGPROF, &sa, NULL);
struct itimerval itv = {{sec, usec},
{sec, usec}};
setitimer(ITIMER_PROF, &itv, NULL);
}
void Profiler::start(long interval) {
if (_running) return;
_running = true;
_calls_total = _calls_non_java = _calls_gc = _calls_deopt = _calls_unknown = 0;
memset(_hashes, 0, sizeof(_hashes));
memset(_traces, 0, sizeof(_traces));
memset(_methods, 0, sizeof(_methods));
setTimer(interval / 1000, interval * 1000);
}
void Profiler::stop() {
if (!_running) return;
_running = false;
setTimer(0, 0);
}
void error(const char *msg) {
std::string res = std::string("ERROR") + std::string(msg);
perror(res.c_str());
exit(0);
}
void sendResponse(int sockfd, me::serce::franky::Response &message) {
using namespace google::protobuf;
using namespace google::protobuf::io;
FileOutputStream raw_output(sockfd);
google::protobuf::io::CodedOutputStream output(&raw_output);
// Write the size.
const int size = message.ByteSize();
output.WriteVarint32((uint32) size);
uint8_t *buffer = output.GetDirectBufferForNBytesAndAdvance(size);
if (buffer != NULL) {
// Optimization: The message fits in one buffer, so use the faster
// direct-to-array serialization path.
message.SerializeWithCachedSizesToArray(buffer);
} else {
// Slightly-slower path when the message is multiple buffers.
message.SerializeWithCachedSizes(&output);
if (output.HadError()) {
error("HAD ERROR");
}
}
}
void performDeopt() {
/*
jvmtiEnv *jvmti = VM::jvmti();
JNIEnv *env = VM::jni();
jvmtiClassDefinition jcd;
const char *className = "java.io.Serializable";
const unsigned char *classBytes = {};
jcd.klass = env->FindClass(className);
jcd.class_byte_count = sizeof(classBytes);
jcd.class_bytes = classBytes;
jvmti->RedefineClasses(1, &jcd);
*/
}
void Profiler::init(int port) {
portno = (uint16_t) port;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("opening socket");
}
server = gethostbyname("localhost");
if (server == NULL) {
error("unable to connect to localhost");
}
struct sockaddr_in serv_addr;
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy(server->h_addr, (char *) &serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
error("connecting");
}
performDeopt();
Response response;
response.set_id(getpid());
response.set_type(Response_ResponseType_INIT);
sendResponse(sockfd, response);
while (true) {
Request request;
readRequest(&request);
switch (request.type()) {
case Request_RequestType_START_PROFILING:
start(DEFAULT_INTERVAL);
break;
case Request_RequestType_STOP_PROFILING:
stop();
writeResult();
break;
case Request_RequestType_DETACH:
close(sockfd);
return;
default:
continue;
}
}
}
void Profiler::readRequest(Request *message) {
using namespace google::protobuf;
using namespace google::protobuf::io;
FileInputStream raw_input(sockfd);
google::protobuf::io::CodedInputStream input(&raw_input);
// Read the size.
uint32_t size;
if (!input.ReadVarint32(&size)) {
error("Error reading variint32");
}
// Tell the stream not to read beyond that size.
input.PushLimit(size);
// Parse the message.
if (!message->MergeFromCodedStream(&input)) {
error("Error paring message 1");
}
if (!input.ConsumedEntireMessage()) {
error("Error paring message 2");
}
}
int64_t jMethodIdToId(const jmethodID &jmethod) {
return (int64_t) jmethod;
}
MethodInfo *fillMethodInfo(MethodInfo *methodInfo, const jmethodID &jmethod) {
MethodName mn(jmethod);
methodInfo->set_jmethodid(jMethodIdToId(jmethod));
methodInfo->set_name(mn.name());
methodInfo->set_holder(mn.holder());
methodInfo->set_sig(mn.signature());
return methodInfo;
}
void Profiler::writeResult() {
Response response;
ProfilingInfo *info = new ProfilingInfo();
info->set_calls_total(_calls_total);
info->set_calls_non_java(_calls_non_java);
info->set_calls_gc(_calls_gc);
info->set_calls_deopt(_calls_deopt);
info->set_calls_unknown(_calls_unknown);
std::unordered_set<jmethodID> methodIds;
saveMethods(info, methodIds);
saveCallTraces(info, methodIds);
saveMethodIds(info, methodIds);
response.set_id(getpid());
response.set_type(Response_ResponseType_PROF_INFO);
response.set_allocated_prof_info(info);
sendResponse(sockfd, response);
}
void Profiler::saveCallTraces(ProfilingInfo *info, std::unordered_set<jmethodID> &methods) {
qsort(_traces, MAX_CALLTRACES, sizeof(CallTraceSample), CallTraceSample::comparator);
int max_traces = MAX_CALLTRACES;
for (int i = 0; i < max_traces; i++) {
const CallTraceSample &trace = _traces[i];
int samples = trace._call_count;
if (samples == 0) break;
CallTraceSampleInfo *sampleInfo = info->add_samples();
sampleInfo->set_call_count(trace._call_count);
for (int j = 0; j < trace._num_frames; j++) {
const ASGCT_CallFrame *frame = &trace._frames[j];
jmethodID jmethod = frame->method_id;
if (jmethod != NULL) {
CallFrame *callFrame = sampleInfo->add_frame();
callFrame->set_bci(frame->bci);
callFrame->set_jmethodid(jMethodIdToId(jmethod));
methods.insert(jmethod);
}
}
}
}
void Profiler::saveMethods(ProfilingInfo *info, std::unordered_set<jmethodID> &methods) {
qsort(_methods, MAX_CALLTRACES, sizeof(MethodSample), MethodSample::comparator);
for (int i = 0; i < MAX_CALLTRACES; i++) {
int samples = _methods[i]._call_count;
if (samples == 0) break;
jmethodID jmethod = _methods[i]._method;
MethodSampleInfo *sampleInfo = info->add_methods();
sampleInfo->set_call_count(samples);
sampleInfo->set_jmethodid(jMethodIdToId(jmethod));
methods.insert(jmethod);
}
}
void Profiler::saveMethodIds(ProfilingInfo *info, std::unordered_set<jmethodID> &methodIds) {
for (auto &jmethod: methodIds) {
MethodInfo *methodInfo = info->add_methodinfos();
fillMethodInfo(methodInfo, jmethod);
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include <iostream>
#include <cctype>
#include <iomanip>
#include <sstream>
#include "zlib.h"
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/udp_tracker_connection.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
using namespace libtorrent;
namespace
{
enum
{
minimum_tracker_response_length = 3,
http_buffer_size = 2048
};
enum
{
FTEXT = 0x01,
FHCRC = 0x02,
FEXTRA = 0x04,
FNAME = 0x08,
FCOMMENT = 0x10,
FRESERVED = 0xe0,
GZIP_MAGIC0 = 0x1f,
GZIP_MAGIC1 = 0x8b
};
}
namespace libtorrent
{
// returns -1 if gzip header is invalid or the header size in bytes
int gzip_header(const char* buf, int size)
{
assert(buf != 0);
assert(size > 0);
const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf);
const int total_size = size;
// The zip header cannot be shorter than 10 bytes
if (size < 10) return -1;
// check the magic header of gzip
if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1;
int method = buffer[2];
int flags = buffer[3];
// check for reserved flag and make sure it's compressed with the correct metod
if (method != Z_DEFLATED || (flags & FRESERVED) != 0) return -1;
// skip time, xflags, OS code
size -= 10;
buffer += 10;
if (flags & FEXTRA)
{
int extra_len;
if (size < 2) return -1;
extra_len = (buffer[1] << 8) | buffer[0];
if (size < (extra_len+2)) return -1;
size -= (extra_len + 2);
buffer += (extra_len + 2);
}
if (flags & FNAME)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FCOMMENT)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FHCRC)
{
if (size < 2) return -1;
size -= 2;
buffer += 2;
}
return total_size - size;
}
bool inflate_gzip(
std::vector<char>& buffer
, request_callback* requester
, int maximum_tracker_response_length)
{
assert(maximum_tracker_response_length > 0);
int header_len = gzip_header(&buffer[0], (int)buffer.size());
if (header_len < 0)
{
requester->tracker_request_error(200, "invalid gzip header in tracker response");
return true;
}
// start off wth one kilobyte and grow
// if needed
std::vector<char> inflate_buffer(1024);
// initialize the zlib-stream
z_stream str;
// subtract 8 from the end of the buffer since that's CRC32 and input size
// and those belong to the gzip file
str.avail_in = (int)buffer.size() - header_len - 8;
str.next_in = reinterpret_cast<Bytef*>(&buffer[header_len]);
str.next_out = reinterpret_cast<Bytef*>(&inflate_buffer[0]);
str.avail_out = (int)inflate_buffer.size();
str.zalloc = Z_NULL;
str.zfree = Z_NULL;
str.opaque = 0;
// -15 is really important. It will make inflate() not look for a zlib header
// and just deflate the buffer
if (inflateInit2(&str, -15) != Z_OK)
{
requester->tracker_request_error(200, "gzip out of memory");
return true;
}
// inflate and grow inflate_buffer as needed
int ret = inflate(&str, Z_SYNC_FLUSH);
while (ret == Z_OK)
{
if (str.avail_out == 0)
{
if (inflate_buffer.size() >= (unsigned)maximum_tracker_response_length)
{
inflateEnd(&str);
requester->tracker_request_error(200, "tracker response too large");
return true;
}
int new_size = (int)inflate_buffer.size() * 2;
if (new_size > maximum_tracker_response_length) new_size = maximum_tracker_response_length;
int old_size = (int)inflate_buffer.size();
inflate_buffer.resize(new_size);
str.next_out = reinterpret_cast<Bytef*>(&inflate_buffer[old_size]);
str.avail_out = new_size - old_size;
}
ret = inflate(&str, Z_SYNC_FLUSH);
}
inflate_buffer.resize(inflate_buffer.size() - str.avail_out);
inflateEnd(&str);
if (ret != Z_STREAM_END)
{
requester->tracker_request_error(200, "gzip error");
return true;
}
// commit the resulting buffer
std::swap(buffer, inflate_buffer);
return false;
}
std::string base64encode(const std::string& s)
{
static const char base64_table[] =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
};
unsigned char inbuf[3];
unsigned char outbuf[4];
std::string ret;
for (std::string::const_iterator i = s.begin(); i != s.end();)
{
// available input is 1,2 or 3 bytes
// since we read 3 bytes at a time at most
int available_input = std::min(3, (int)std::distance(i, s.end()));
// clear input buffer
std::fill(inbuf, inbuf+3, 0);
// read a chunk of input into inbuf
for (int j = 0; j < available_input; ++j)
{
inbuf[j] = *i;
++i;
}
// encode inbuf to outbuf
outbuf[0] = (inbuf[0] & 0xfc) >> 2;
outbuf[1] = ((inbuf[0] & 0x03) << 4) | ((inbuf [1] & 0xf0) >> 4);
outbuf[2] = ((inbuf[1] & 0x0f) << 2) | ((inbuf [2] & 0xc0) >> 6);
outbuf[3] = inbuf[2] & 0x3f;
// write output
for (int j = 0; j < available_input+1; ++j)
{
ret += base64_table[outbuf[j]];
}
// write pad
for (int j = 0; j < 3 - available_input; ++j)
{
ret += '=';
}
}
return ret;
}
void tracker_manager::tick()
{
std::vector<boost::shared_ptr<tracker_connection> >::iterator i;
for (i = m_connections.begin(); i != m_connections.end(); ++i)
{
boost::shared_ptr<tracker_connection>& c = *i;
try
{
if (!c->tick()) return;
}
catch (const std::exception& e)
{
if (c->requester())
c->requester()->tracker_request_error(-1, e.what());
}
if (c->requester()) c->requester()->m_manager = 0;
m_connections.erase(i);
--i; // compensate for the remove
}
}
void tracker_manager::queue_request(
tracker_request const& req
, request_callback* c
, std::string const& password)
{
try
{
std::string hostname; // hostname only
std::string protocol; // should be http
int port = 80;
// PARSE URL
std::string::const_iterator start = req.url.begin();
std::string::const_iterator end
= std::find(req.url.begin(), req.url.end(), ':');
protocol = std::string(start, end);
if (end == req.url.end()) throw std::runtime_error("invalid url");
++end;
if (end == req.url.end()) throw std::runtime_error("invalid url");
if (*end != '/') throw std::runtime_error("invalid url");
++end;
if (end == req.url.end()) throw std::runtime_error("invalid url");
if (*end != '/') throw std::runtime_error("invalid url");
++end;
start = end;
end = std::find(start, req.url.end(), '/');
std::string::const_iterator port_pos
= std::find(start, req.url.end(), ':');
if (port_pos < end)
{
hostname.assign(start, port_pos);
++port_pos;
try
{
port = boost::lexical_cast<int>(std::string(port_pos, end));
}
catch(boost::bad_lexical_cast&)
{
throw std::runtime_error("invalid url");
}
}
else
{
hostname.assign(start, end);
}
start = end;
std::string request_string = std::string(start, req.url.end());
boost::shared_ptr<tracker_connection> con;
if (protocol == "http")
{
con.reset(new http_tracker_connection(
req
, hostname
, port
, request_string
, c
, m_settings
, password));
}
else if (protocol == "udp")
{
con.reset(new udp_tracker_connection(
req
, hostname
, port
, c
, m_settings));
}
else
{
throw std::runtime_error("unkown protocol in tracker url");
}
m_connections.push_back(con);
if (con->requester()) con->requester()->m_manager = this;
}
catch (std::exception& e)
{
if (c) c->tracker_request_error(-1, e.what());
}
}
void tracker_manager::abort_request(request_callback* c)
{
assert(c != 0);
std::vector<boost::shared_ptr<tracker_connection> >::iterator i;
for (i = m_connections.begin(); i != m_connections.end(); ++i)
{
if ((*i)->requester() == c)
{
m_connections.erase(i);
break;
}
}
}
void tracker_manager::abort_all_requests()
{
// removes all connections from m_connections
// except those with a requester == 0 (since those are
// 'event=stopped'-requests)
std::vector<boost::shared_ptr<tracker_connection> > keep_connections;
for (std::vector<boost::shared_ptr<tracker_connection> >::const_iterator i =
m_connections.begin();
i != m_connections.end();
++i)
{
if ((*i)->requester() == 0) keep_connections.push_back(*i);
}
std::swap(m_connections, keep_connections);
}
bool tracker_manager::send_finished() const
{
for (std::vector<boost::shared_ptr<tracker_connection> >::const_iterator i =
m_connections.begin();
i != m_connections.end();
++i)
{
if (!(*i)->send_finished()) return false;
}
return true;
}
}
<commit_msg>*** empty log message ***<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include <iostream>
#include <cctype>
#include <iomanip>
#include <sstream>
#include "zlib.h"
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/http_tracker_connection.hpp"
#include "libtorrent/udp_tracker_connection.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
using namespace libtorrent;
namespace
{
enum
{
minimum_tracker_response_length = 3,
http_buffer_size = 2048
};
enum
{
FTEXT = 0x01,
FHCRC = 0x02,
FEXTRA = 0x04,
FNAME = 0x08,
FCOMMENT = 0x10,
FRESERVED = 0xe0,
GZIP_MAGIC0 = 0x1f,
GZIP_MAGIC1 = 0x8b
};
}
namespace libtorrent
{
// returns -1 if gzip header is invalid or the header size in bytes
int gzip_header(const char* buf, int size)
{
assert(buf != 0);
assert(size > 0);
const unsigned char* buffer = reinterpret_cast<const unsigned char*>(buf);
const int total_size = size;
// The zip header cannot be shorter than 10 bytes
if (size < 10) return -1;
// check the magic header of gzip
if ((buffer[0] != GZIP_MAGIC0) || (buffer[1] != GZIP_MAGIC1)) return -1;
int method = buffer[2];
int flags = buffer[3];
// check for reserved flag and make sure it's compressed with the correct metod
if (method != Z_DEFLATED || (flags & FRESERVED) != 0) return -1;
// skip time, xflags, OS code
size -= 10;
buffer += 10;
if (flags & FEXTRA)
{
int extra_len;
if (size < 2) return -1;
extra_len = (buffer[1] << 8) | buffer[0];
if (size < (extra_len+2)) return -1;
size -= (extra_len + 2);
buffer += (extra_len + 2);
}
if (flags & FNAME)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FCOMMENT)
{
while (size && *buffer)
{
--size;
++buffer;
}
if (!size || *buffer) return -1;
--size;
++buffer;
}
if (flags & FHCRC)
{
if (size < 2) return -1;
size -= 2;
buffer += 2;
}
return total_size - size;
}
bool inflate_gzip(
std::vector<char>& buffer
, request_callback* requester
, int maximum_tracker_response_length)
{
assert(maximum_tracker_response_length > 0);
int header_len = gzip_header(&buffer[0], (int)buffer.size());
if (header_len < 0)
{
requester->tracker_request_error(200, "invalid gzip header in tracker response");
return true;
}
// start off wth one kilobyte and grow
// if needed
std::vector<char> inflate_buffer(1024);
// initialize the zlib-stream
z_stream str;
// subtract 8 from the end of the buffer since that's CRC32 and input size
// and those belong to the gzip file
str.avail_in = (int)buffer.size() - header_len - 8;
str.next_in = reinterpret_cast<Bytef*>(&buffer[header_len]);
str.next_out = reinterpret_cast<Bytef*>(&inflate_buffer[0]);
str.avail_out = (int)inflate_buffer.size();
str.zalloc = Z_NULL;
str.zfree = Z_NULL;
str.opaque = 0;
// -15 is really important. It will make inflate() not look for a zlib header
// and just deflate the buffer
if (inflateInit2(&str, -15) != Z_OK)
{
requester->tracker_request_error(200, "gzip out of memory");
return true;
}
// inflate and grow inflate_buffer as needed
int ret = inflate(&str, Z_SYNC_FLUSH);
while (ret == Z_OK)
{
if (str.avail_out == 0)
{
if (inflate_buffer.size() >= (unsigned)maximum_tracker_response_length)
{
inflateEnd(&str);
requester->tracker_request_error(200, "tracker response too large");
return true;
}
int new_size = (int)inflate_buffer.size() * 2;
if (new_size > maximum_tracker_response_length) new_size = maximum_tracker_response_length;
int old_size = (int)inflate_buffer.size();
inflate_buffer.resize(new_size);
str.next_out = reinterpret_cast<Bytef*>(&inflate_buffer[old_size]);
str.avail_out = new_size - old_size;
}
ret = inflate(&str, Z_SYNC_FLUSH);
}
inflate_buffer.resize(inflate_buffer.size() - str.avail_out);
inflateEnd(&str);
if (ret != Z_STREAM_END)
{
requester->tracker_request_error(200, "gzip error");
return true;
}
// commit the resulting buffer
std::swap(buffer, inflate_buffer);
return false;
}
std::string base64encode(const std::string& s)
{
static const char base64_table[] =
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'
};
unsigned char inbuf[3];
unsigned char outbuf[4];
std::string ret;
for (std::string::const_iterator i = s.begin(); i != s.end();)
{
// available input is 1,2 or 3 bytes
// since we read 3 bytes at a time at most
int available_input = std::min(3, (int)std::distance(i, s.end()));
// clear input buffer
std::fill(inbuf, inbuf+3, 0);
// read a chunk of input into inbuf
for (int j = 0; j < available_input; ++j)
{
inbuf[j] = *i;
++i;
}
// encode inbuf to outbuf
outbuf[0] = (inbuf[0] & 0xfc) >> 2;
outbuf[1] = ((inbuf[0] & 0x03) << 4) | ((inbuf [1] & 0xf0) >> 4);
outbuf[2] = ((inbuf[1] & 0x0f) << 2) | ((inbuf [2] & 0xc0) >> 6);
outbuf[3] = inbuf[2] & 0x3f;
// write output
for (int j = 0; j < available_input+1; ++j)
{
ret += base64_table[outbuf[j]];
}
// write pad
for (int j = 0; j < 3 - available_input; ++j)
{
ret += '=';
}
}
return ret;
}
void tracker_manager::tick()
{
std::vector<boost::shared_ptr<tracker_connection> >::iterator i;
for (i = m_connections.begin(); i != m_connections.end(); ++i)
{
boost::shared_ptr<tracker_connection>& c = *i;
try
{
if (!c->tick()) continue;
}
catch (const std::exception& e)
{
if (c->requester())
c->requester()->tracker_request_error(-1, e.what());
}
if (c->requester()) c->requester()->m_manager = 0;
m_connections.erase(i);
--i; // compensate for the remove
}
}
void tracker_manager::queue_request(
tracker_request const& req
, request_callback* c
, std::string const& password)
{
try
{
std::string hostname; // hostname only
std::string protocol; // should be http
int port = 80;
// PARSE URL
std::string::const_iterator start = req.url.begin();
std::string::const_iterator end
= std::find(req.url.begin(), req.url.end(), ':');
protocol = std::string(start, end);
if (end == req.url.end()) throw std::runtime_error("invalid url");
++end;
if (end == req.url.end()) throw std::runtime_error("invalid url");
if (*end != '/') throw std::runtime_error("invalid url");
++end;
if (end == req.url.end()) throw std::runtime_error("invalid url");
if (*end != '/') throw std::runtime_error("invalid url");
++end;
start = end;
end = std::find(start, req.url.end(), '/');
std::string::const_iterator port_pos
= std::find(start, req.url.end(), ':');
if (port_pos < end)
{
hostname.assign(start, port_pos);
++port_pos;
try
{
port = boost::lexical_cast<int>(std::string(port_pos, end));
}
catch(boost::bad_lexical_cast&)
{
throw std::runtime_error("invalid url");
}
}
else
{
hostname.assign(start, end);
}
start = end;
std::string request_string = std::string(start, req.url.end());
boost::shared_ptr<tracker_connection> con;
if (protocol == "http")
{
con.reset(new http_tracker_connection(
req
, hostname
, port
, request_string
, c
, m_settings
, password));
}
else if (protocol == "udp")
{
con.reset(new udp_tracker_connection(
req
, hostname
, port
, c
, m_settings));
}
else
{
throw std::runtime_error("unkown protocol in tracker url");
}
m_connections.push_back(con);
if (con->requester()) con->requester()->m_manager = this;
}
catch (std::exception& e)
{
if (c) c->tracker_request_error(-1, e.what());
}
}
void tracker_manager::abort_request(request_callback* c)
{
assert(c != 0);
std::vector<boost::shared_ptr<tracker_connection> >::iterator i;
for (i = m_connections.begin(); i != m_connections.end(); ++i)
{
if ((*i)->requester() == c)
{
m_connections.erase(i);
break;
}
}
}
void tracker_manager::abort_all_requests()
{
// removes all connections from m_connections
// except those with a requester == 0 (since those are
// 'event=stopped'-requests)
std::vector<boost::shared_ptr<tracker_connection> > keep_connections;
for (std::vector<boost::shared_ptr<tracker_connection> >::const_iterator i =
m_connections.begin();
i != m_connections.end();
++i)
{
if ((*i)->requester() == 0) keep_connections.push_back(*i);
}
std::swap(m_connections, keep_connections);
}
bool tracker_manager::send_finished() const
{
for (std::vector<boost::shared_ptr<tracker_connection> >::const_iterator i =
m_connections.begin();
i != m_connections.end();
++i)
{
if (!(*i)->send_finished()) return false;
}
return true;
}
}
<|endoftext|> |
<commit_before>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
// (C) 2005 Mike Weiblen http://mew.cx/ released under the OSGPL.
// Simple example using GLUT to create an OpenGL window and OSG for rendering.
// Derived from osgGLUTsimple.cpp and osgkeyboardmouse.cpp
#include <osgViewer/SimpleViewer>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>
#include "SDL.h"
#include <iostream>
bool convertEvent(SDL_Event& event, osgGA::EventQueue& eventQueue)
{
switch (event.type) {
case SDL_MOUSEMOTION:
eventQueue.mouseMotion(event.motion.x, event.motion.y);
return true;
case SDL_MOUSEBUTTONDOWN:
eventQueue.mouseButtonPress(event.button.x, event.button.y, event.button.button);
return true;
case SDL_MOUSEBUTTONUP:
eventQueue.mouseButtonRelease(event.button.x, event.button.y, event.button.button);
return true;
case SDL_KEYUP:
eventQueue.keyRelease( (osgGA::GUIEventAdapter::KeySymbol) event.key.keysym.unicode);
return true;
case SDL_KEYDOWN:
eventQueue.keyPress( (osgGA::GUIEventAdapter::KeySymbol) event.key.keysym.unicode);
return true;
case SDL_VIDEORESIZE:
eventQueue.windowResize(0, 0, event.resize.w, event.resize.h );
return true;
default:
break;
}
return false;
}
int main( int argc, char **argv )
{
if (argc<2)
{
std::cout << argv[0] <<": requires filename argument." << std::endl;
return 1;
}
// init SDL
if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
{
fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
exit(1);
}
atexit(SDL_Quit);
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
if (!loadedModel)
{
std::cout << argv[0] <<": No data loaded." << std::endl;
return 1;
}
#if 1
unsigned int windowWidth = 1280;
unsigned int windowHeight = 1024;
#else
// Starting with SDL 1.2.10, passing in 0 will use the system's current resolution.
unsigned int windowWidth = 0;
unsigned int windowHeight = 0;
#endif
// Passing in 0 for bitdepth also uses the system's current bitdepth
unsigned int bitDepth = 0;
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
// set up the surface to render to
SDL_Surface* screen = SDL_SetVideoMode(windowWidth, windowHeight, bitDepth, SDL_OPENGL | SDL_FULLSCREEN | SDL_RESIZABLE);
if ( screen == NULL )
{
std::cerr<<"Unable to set "<<windowWidth<<"x"<<windowHeight<<" video: %s\n"<< SDL_GetError()<<std::endl;
exit(1);
}
SDL_EnableUNICODE(1);
osgViewer::SimpleViewer viewer;
viewer.setSceneData(loadedModel.get());
viewer.setCameraManipulator(new osgGA::TrackballManipulator);
// If we used 0 to set the fields, query the values so we can pass it to osgViewer
windowWidth = screen->w;
windowHeight = screen->h;
viewer.getEventQueue()->windowResize(0, 0, windowWidth, windowHeight );
bool done = false;
while( !done )
{
SDL_Event event;
while ( SDL_PollEvent(&event) )
{
// pass the SDL event into the viewers event queue
convertEvent(event, *viewer.getEventQueue());
switch (event.type) {
case SDL_KEYUP:
if (event.key.keysym.sym==SDLK_ESCAPE) done = true;
if (event.key.keysym.sym=='f') SDL_WM_ToggleFullScreen(screen);
break;
case SDL_QUIT:
done = true;
}
}
if (done) continue;
// draw the new frame
viewer.frame();
// Swap Buffers
SDL_GL_SwapBuffers();
}
return 0;
}
/*EOF*/
<commit_msg>From Eric Wing, add version check for use of automatic resizeing<commit_after>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL.
// (C) 2005 Mike Weiblen http://mew.cx/ released under the OSGPL.
// Simple example using GLUT to create an OpenGL window and OSG for rendering.
// Derived from osgGLUTsimple.cpp and osgkeyboardmouse.cpp
#include <osgViewer/SimpleViewer>
#include <osgGA/TrackballManipulator>
#include <osgDB/ReadFile>
#include "SDL.h"
#include <iostream>
bool convertEvent(SDL_Event& event, osgGA::EventQueue& eventQueue)
{
switch (event.type) {
case SDL_MOUSEMOTION:
eventQueue.mouseMotion(event.motion.x, event.motion.y);
return true;
case SDL_MOUSEBUTTONDOWN:
eventQueue.mouseButtonPress(event.button.x, event.button.y, event.button.button);
return true;
case SDL_MOUSEBUTTONUP:
eventQueue.mouseButtonRelease(event.button.x, event.button.y, event.button.button);
return true;
case SDL_KEYUP:
eventQueue.keyRelease( (osgGA::GUIEventAdapter::KeySymbol) event.key.keysym.unicode);
return true;
case SDL_KEYDOWN:
eventQueue.keyPress( (osgGA::GUIEventAdapter::KeySymbol) event.key.keysym.unicode);
return true;
case SDL_VIDEORESIZE:
eventQueue.windowResize(0, 0, event.resize.w, event.resize.h );
return true;
default:
break;
}
return false;
}
int main( int argc, char **argv )
{
if (argc<2)
{
std::cout << argv[0] <<": requires filename argument." << std::endl;
return 1;
}
// init SDL
if ( SDL_Init(SDL_INIT_VIDEO) < 0 )
{
fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
exit(1);
}
atexit(SDL_Quit);
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]);
if (!loadedModel)
{
std::cout << argv[0] <<": No data loaded." << std::endl;
return 1;
}
// Starting with SDL 1.2.10, passing in 0 will use the system's current resolution.
unsigned int windowWidth = 0;
unsigned int windowHeight = 0;
// Passing in 0 for bitdepth also uses the system's current bitdepth. This works before 1.2.10 too.
unsigned int bitDepth = 0;
// If not linked to SDL 1.2.10+, then we must use hardcoded values
const SDL_version* linked_version = SDL_Linked_Version();
if(linked_version->major == 1 && linked_version->minor == 2)
{
if(linked_version->patch < 10)
{
windowWidth = 1280;
windowHeight = 1024;
}
}
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
// set up the surface to render to
SDL_Surface* screen = SDL_SetVideoMode(windowWidth, windowHeight, bitDepth, SDL_OPENGL | SDL_FULLSCREEN | SDL_RESIZABLE);
if ( screen == NULL )
{
std::cerr<<"Unable to set "<<windowWidth<<"x"<<windowHeight<<" video: %s\n"<< SDL_GetError()<<std::endl;
exit(1);
}
SDL_EnableUNICODE(1);
osgViewer::SimpleViewer viewer;
viewer.setSceneData(loadedModel.get());
viewer.setCameraManipulator(new osgGA::TrackballManipulator);
// If we used 0 to set the fields, query the values so we can pass it to osgViewer
windowWidth = screen->w;
windowHeight = screen->h;
viewer.getEventQueue()->windowResize(0, 0, windowWidth, windowHeight );
bool done = false;
while( !done )
{
SDL_Event event;
while ( SDL_PollEvent(&event) )
{
// pass the SDL event into the viewers event queue
convertEvent(event, *viewer.getEventQueue());
switch (event.type) {
case SDL_KEYUP:
if (event.key.keysym.sym==SDLK_ESCAPE) done = true;
if (event.key.keysym.sym=='f') SDL_WM_ToggleFullScreen(screen);
break;
case SDL_QUIT:
done = true;
}
}
if (done) continue;
// draw the new frame
viewer.frame();
// Swap Buffers
SDL_GL_SwapBuffers();
}
return 0;
}
/*EOF*/
<|endoftext|> |
<commit_before>#include "Runtime/Character/CParticleGenInfo.hpp"
#include "Runtime/CStateManager.hpp"
#include "Runtime/GameGlobalObjects.hpp"
#include "Runtime/Graphics/CBooRenderer.hpp"
#include "Runtime/Graphics/IRenderer.hpp"
#include "Runtime/Particle/CParticleGen.hpp"
#include "Runtime/World/CGameLight.hpp"
#include "TCastTo.hpp" // Generated file, do not modify include path
namespace urde {
CParticleGenInfo::CParticleGenInfo(const SObjectTag& part, int frameCount, std::string_view boneName,
const zeus::CVector3f& scale, CParticleData::EParentedMode parentMode, int flags,
EParticleGenType type)
: x4_part(part)
, xc_seconds(frameCount / 60.f)
, x10_boneName(boneName)
, x28_parentMode(parentMode)
, x2c_flags(flags)
, x30_particleScale(scale)
, x80_type(type) {}
static TUniqueId _initializeLight(const std::weak_ptr<CParticleGen>& system, CStateManager& stateMgr, TAreaId areaId,
int lightId) {
TUniqueId ret = kInvalidUniqueId;
std::shared_ptr<CParticleGen> systemRef = system.lock();
if (systemRef->SystemHasLight()) {
ret = stateMgr.AllocateUniqueId();
stateMgr.AddObject(
new CGameLight(ret, areaId, false, "ParticleLight",
zeus::CTransform(systemRef->GetOrientation().buildMatrix3f(), systemRef->GetTranslation()),
kInvalidUniqueId, systemRef->GetLight(), u32(lightId), 0, 0.f));
}
return ret;
}
CParticleGenInfoGeneric::CParticleGenInfoGeneric(const SObjectTag& part, const std::weak_ptr<CParticleGen>& system,
int frameCount, std::string_view boneName,
const zeus::CVector3f& scale, CParticleData::EParentedMode parentMode,
int flags, CStateManager& stateMgr, TAreaId areaId, int lightId,
EParticleGenType state)
: CParticleGenInfo(part, frameCount, boneName, scale, parentMode, flags, state), x84_system(system) {
if (lightId == -1)
x88_lightId = kInvalidUniqueId;
else
x88_lightId = _initializeLight(system, stateMgr, areaId, lightId);
}
void CParticleGenInfoGeneric::AddToRenderer() { g_Renderer->AddParticleGen(*x84_system.get()); }
void CParticleGenInfoGeneric::Render() { x84_system->Render(); }
void CParticleGenInfoGeneric::Update(float dt, CStateManager& stateMgr) {
x84_system->Update(dt);
if (x88_lightId != kInvalidUniqueId) {
TCastToPtr<CGameLight> gl(stateMgr.ObjectById(x88_lightId));
if (gl)
gl->SetLight(x84_system->GetLight());
}
}
void CParticleGenInfoGeneric::SetOrientation(const zeus::CTransform& xf, CStateManager& stateMgr) {
x84_system->SetOrientation(xf);
if (x88_lightId != kInvalidUniqueId) {
TCastToPtr<CGameLight> gl(stateMgr.ObjectById(x88_lightId));
if (gl)
gl->SetRotation(zeus::CQuaternion(xf.buildMatrix3f()));
}
}
void CParticleGenInfoGeneric::SetTranslation(const zeus::CVector3f& trans, CStateManager& stateMgr) {
x84_system->SetTranslation(trans);
if (x88_lightId != kInvalidUniqueId) {
TCastToPtr<CGameLight> gl(stateMgr.ObjectById(x88_lightId));
if (gl)
gl->SetTranslation(trans);
}
}
void CParticleGenInfoGeneric::SetGlobalOrientation(const zeus::CTransform& xf, CStateManager& stateMgr) {
x84_system->SetGlobalOrientation(xf);
if (x88_lightId != kInvalidUniqueId) {
TCastToPtr<CGameLight> gl(stateMgr.ObjectById(x88_lightId));
if (gl)
gl->SetRotation(zeus::CQuaternion(xf.buildMatrix3f()));
}
}
void CParticleGenInfoGeneric::SetGlobalTranslation(const zeus::CVector3f& trans, CStateManager& stateMgr) {
x84_system->SetGlobalTranslation(trans);
if (x88_lightId != kInvalidUniqueId) {
TCastToPtr<CGameLight> gl(stateMgr.ObjectById(x88_lightId));
if (gl)
gl->SetTranslation(trans);
}
}
void CParticleGenInfoGeneric::SetGlobalScale(const zeus::CVector3f& scale) { x84_system->SetGlobalScale(scale); }
void CParticleGenInfoGeneric::SetParticleEmission(bool isActive, CStateManager& stateMgr) {
x84_system->SetParticleEmission(isActive);
TCastToPtr<CGameLight> gl(stateMgr.ObjectById(x88_lightId));
if (gl) {
gl->SetActive(isActive);
}
}
bool CParticleGenInfoGeneric::IsSystemDeletable() const { return x84_system->IsSystemDeletable(); }
std::optional<zeus::CAABox> CParticleGenInfoGeneric::GetBounds() const { return x84_system->GetBounds(); }
bool CParticleGenInfoGeneric::HasActiveParticles() const { return x84_system->GetParticleCount() != 0; }
void CParticleGenInfoGeneric::DestroyParticles() { x84_system->DestroyParticles(); }
bool CParticleGenInfoGeneric::HasLight() const { return x84_system->SystemHasLight(); }
TUniqueId CParticleGenInfoGeneric::GetLightId() const { return x88_lightId; }
void CParticleGenInfoGeneric::DeleteLight(CStateManager& mgr) {
if (x88_lightId != kInvalidUniqueId) {
mgr.FreeScriptObject(x88_lightId);
x88_lightId = kInvalidUniqueId;
}
}
void CParticleGenInfoGeneric::SetModulationColor(const zeus::CColor& color) { x84_system->SetModulationColor(color); }
} // namespace urde
<commit_msg>CParticleGenInfo: Collapse TCastToPtr into conditions<commit_after>#include "Runtime/Character/CParticleGenInfo.hpp"
#include "Runtime/CStateManager.hpp"
#include "Runtime/GameGlobalObjects.hpp"
#include "Runtime/Graphics/CBooRenderer.hpp"
#include "Runtime/Graphics/IRenderer.hpp"
#include "Runtime/Particle/CParticleGen.hpp"
#include "Runtime/World/CGameLight.hpp"
#include "TCastTo.hpp" // Generated file, do not modify include path
namespace urde {
CParticleGenInfo::CParticleGenInfo(const SObjectTag& part, int frameCount, std::string_view boneName,
const zeus::CVector3f& scale, CParticleData::EParentedMode parentMode, int flags,
EParticleGenType type)
: x4_part(part)
, xc_seconds(frameCount / 60.f)
, x10_boneName(boneName)
, x28_parentMode(parentMode)
, x2c_flags(flags)
, x30_particleScale(scale)
, x80_type(type) {}
static TUniqueId _initializeLight(const std::weak_ptr<CParticleGen>& system, CStateManager& stateMgr, TAreaId areaId,
int lightId) {
TUniqueId ret = kInvalidUniqueId;
std::shared_ptr<CParticleGen> systemRef = system.lock();
if (systemRef->SystemHasLight()) {
ret = stateMgr.AllocateUniqueId();
stateMgr.AddObject(
new CGameLight(ret, areaId, false, "ParticleLight",
zeus::CTransform(systemRef->GetOrientation().buildMatrix3f(), systemRef->GetTranslation()),
kInvalidUniqueId, systemRef->GetLight(), u32(lightId), 0, 0.f));
}
return ret;
}
CParticleGenInfoGeneric::CParticleGenInfoGeneric(const SObjectTag& part, const std::weak_ptr<CParticleGen>& system,
int frameCount, std::string_view boneName,
const zeus::CVector3f& scale, CParticleData::EParentedMode parentMode,
int flags, CStateManager& stateMgr, TAreaId areaId, int lightId,
EParticleGenType state)
: CParticleGenInfo(part, frameCount, boneName, scale, parentMode, flags, state), x84_system(system) {
if (lightId == -1)
x88_lightId = kInvalidUniqueId;
else
x88_lightId = _initializeLight(system, stateMgr, areaId, lightId);
}
void CParticleGenInfoGeneric::AddToRenderer() { g_Renderer->AddParticleGen(*x84_system.get()); }
void CParticleGenInfoGeneric::Render() { x84_system->Render(); }
void CParticleGenInfoGeneric::Update(float dt, CStateManager& stateMgr) {
x84_system->Update(dt);
if (x88_lightId == kInvalidUniqueId) {
return;
}
if (const TCastToPtr<CGameLight> gl = stateMgr.ObjectById(x88_lightId)) {
gl->SetLight(x84_system->GetLight());
}
}
void CParticleGenInfoGeneric::SetOrientation(const zeus::CTransform& xf, CStateManager& stateMgr) {
x84_system->SetOrientation(xf);
if (x88_lightId == kInvalidUniqueId) {
return;
}
if (const TCastToPtr<CGameLight> gl = stateMgr.ObjectById(x88_lightId)) {
gl->SetRotation(zeus::CQuaternion(xf.buildMatrix3f()));
}
}
void CParticleGenInfoGeneric::SetTranslation(const zeus::CVector3f& trans, CStateManager& stateMgr) {
x84_system->SetTranslation(trans);
if (x88_lightId == kInvalidUniqueId) {
return;
}
if (const TCastToPtr<CGameLight> gl = stateMgr.ObjectById(x88_lightId)) {
gl->SetTranslation(trans);
}
}
void CParticleGenInfoGeneric::SetGlobalOrientation(const zeus::CTransform& xf, CStateManager& stateMgr) {
x84_system->SetGlobalOrientation(xf);
if (x88_lightId == kInvalidUniqueId) {
return;
}
if (const TCastToPtr<CGameLight> gl = stateMgr.ObjectById(x88_lightId)) {
gl->SetRotation(zeus::CQuaternion(xf.buildMatrix3f()));
}
}
void CParticleGenInfoGeneric::SetGlobalTranslation(const zeus::CVector3f& trans, CStateManager& stateMgr) {
x84_system->SetGlobalTranslation(trans);
if (x88_lightId == kInvalidUniqueId) {
return;
}
if (const TCastToPtr<CGameLight> gl = stateMgr.ObjectById(x88_lightId)) {
gl->SetTranslation(trans);
}
}
void CParticleGenInfoGeneric::SetGlobalScale(const zeus::CVector3f& scale) { x84_system->SetGlobalScale(scale); }
void CParticleGenInfoGeneric::SetParticleEmission(bool isActive, CStateManager& stateMgr) {
x84_system->SetParticleEmission(isActive);
if (const TCastToPtr<CGameLight> gl = stateMgr.ObjectById(x88_lightId)) {
gl->SetActive(isActive);
}
}
bool CParticleGenInfoGeneric::IsSystemDeletable() const { return x84_system->IsSystemDeletable(); }
std::optional<zeus::CAABox> CParticleGenInfoGeneric::GetBounds() const { return x84_system->GetBounds(); }
bool CParticleGenInfoGeneric::HasActiveParticles() const { return x84_system->GetParticleCount() != 0; }
void CParticleGenInfoGeneric::DestroyParticles() { x84_system->DestroyParticles(); }
bool CParticleGenInfoGeneric::HasLight() const { return x84_system->SystemHasLight(); }
TUniqueId CParticleGenInfoGeneric::GetLightId() const { return x88_lightId; }
void CParticleGenInfoGeneric::DeleteLight(CStateManager& mgr) {
if (x88_lightId != kInvalidUniqueId) {
mgr.FreeScriptObject(x88_lightId);
x88_lightId = kInvalidUniqueId;
}
}
void CParticleGenInfoGeneric::SetModulationColor(const zeus::CColor& color) { x84_system->SetModulationColor(color); }
} // namespace urde
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
//
// Copyright (C) Streamlet. All rights reserved.
//
// File Name: Main.cpp
// Author: Streamlet
// Create Time: 2010-10-26
// Description:
//
// Version history:
//
//
//
//------------------------------------------------------------------------------
#include "../MetaWeblog/XmlParser.h"
#include "../MetaWeblog/HttpIO.h"
#include "../MetaWeblog/XmlRpcValue.h"
#include "../MetaWeblog/Base64.h"
#include "../MetaWeblog/XmlRpc.h"
#include <Windows.h>
#include <tchar.h>
int main()
{
XmlRpc xmlrpc;
return 0;
}
<commit_msg>add a console sample for reading cppblog<commit_after>//------------------------------------------------------------------------------
//
// Copyright (C) Streamlet. All rights reserved.
//
// File Name: Main.cpp
// Author: Streamlet
// Create Time: 2010-10-26
// Description:
//
// Version history:
//
//
//
//------------------------------------------------------------------------------
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NON_CONFORMING_SWPRINTFS
#include "../MetaWeblog/MetaWeblog.h"
#include <Loki/ScopeGuard.h>
#include <Windows.h>
#include <tchar.h>
#include <stdio.h>
#include <locale.h>
#include <conio.h>
xl::String GetInput(const xl::String &strPrompt)
{
_tprintf(strPrompt.GetAddress());
const int BUFFER_SIZE = 80;
TCHAR BUFFER[BUFFER_SIZE];
fflush(stdin);
_tscanf(_T("%s"), BUFFER);
return BUFFER;
}
xl::String GetPassword(const xl::String &strPrompt)
{
_tprintf(strPrompt.GetAddress());
const int BUFFER_SIZE = 80;
TCHAR BUFFER[BUFFER_SIZE];
fflush(stdin);
int i = 0;
wchar_t ch = _T('\0');
while ((ch = _gettch()) != _T('\r'))
{
if (ch == _T('\b') && i > 0)
{
--i;
_puttch(_T('\b'));
_puttch(_T(' '));
_puttch(_T('\b'));
}
else
{
BUFFER[i++] = ch;
_puttch(_T('*'));
}
}
BUFFER[i++] = _T('\0');
_puttch(_T('\n'));
return BUFFER;
}
int main()
{
setlocale(LC_ALL, "");
HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
LOKI_ON_BLOCK_EXIT(CloseHandle, hEvent);
MetaWeblog metaWeblog(hEvent);
_tprintf(_T("MetaWeblog Test\n"));
_tprintf(_T("\n"));
_tprintf(_T("Please input your cppblog username and password.\n"));
xl::String strUserName = GetInput(_T("UserName: "));
xl::String strPassword = GetPassword(_T("Password: "));
xl::String strUrl;
strUrl += _T("http://www.cppblog.com/");
strUrl += strUserName;
strUrl += _T("/services/metaweblog.aspx");
_tprintf(_T("\n"));
_tprintf(_T("Connecting %s ...\n"), strUrl.GetAddress());
if (!metaWeblog.Connect(strUrl, strUserName, strPassword))
{
_tprintf(_T("Failed to connect server.\n"));
_tprintf(_T("Press any key to quit...\n"));
_getch();
return 0;
}
_tprintf(_T("Connected!\n"));
_tprintf(_T("\n"));
_tprintf(_T("Getting blog information...\n"));
auto blogs = metaWeblog.GetUsersBlogs();
if (blogs.Empty())
{
_tprintf(_T("Failed to getting blog information...\n"));
_tprintf(_T("Press any key to quit...\n"));
_getch();
return 0;
}
auto blog = **blogs.Begin();
_tprintf(_T("Blog ID: %s\nBlog Name: %s\nBlog URL: %s\n"),
blog.blogid.GetAddress(), blog.blogName.GetAddress(), blog.url.GetAddress());
_tprintf(_T("\n"));
_tprintf(_T("Listing categories...\n"));
auto categories = metaWeblog.GetCategories(blog.blogid);
for (auto it = categories.Begin(); it != categories.End(); ++it)
{
auto category = **it;
_tprintf(_T("ID: %s, Title: %s\n"),
category.categoryid.GetAddress(), category.title.GetAddress());
}
_tprintf(_T("\n"));
_tprintf(_T("Top 10 posts...\n"));
auto posts = metaWeblog.GetRecentPosts(blog.blogid, 10);
for (auto it = posts.Begin(); it != posts.End(); ++it)
{
auto post = **it;
_tprintf(_T("ID: %s, Time: %s Title:\n%s\n"),
post.postid.GetAddress(), post.dateCreated.GetAddress(), post.title.GetAddress());
}
_tprintf(_T("\n"));
_tprintf(_T("Press any key to quit...\n"));
_getch();
return 0;
}
<|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.
===================================================================*/
// Testing
#include "mitkTestFixture.h"
#include "mitkTestingMacros.h"
// qt includes
#include "QApplication"
// std includes
#include <string>
// MITK includes
#include "QmitkChartWidget.h"
#include "QmitkChartxyData.h"
#include "QmitkChartData.h"
class mitkChartWidgetTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkChartWidgetTestSuite);
// Test the dicom property parsing
MITK_TEST(AddOnce_Test_Success);
MITK_TEST(AddSameLabelTwice_Test_Success);
MITK_TEST(RemoveNonexistingData_Failure);
MITK_TEST(RemoveData_Success);
MITK_TEST(SetandGet_Success);
MITK_TEST(SetC3DataAndGet_Success);
MITK_TEST(AddAndRemoveData_Sucess);
CPPUNIT_TEST_SUITE_END();
private:
std::vector<double> data1D;
std::string label;
public:
void setUp() override
{
data1D = {2, 4, 7, 8, 21, 5, 12, 65, 41, 9};
label = "testLabel";
int argc = 1;
char *argv[] = {(char *)"AppName"};
if (QApplication::instance() == nullptr)
{
new QApplication(argc, argv);
}
}
void tearDown() override {}
void AddOnce_Test_Success()
{
//use QmitkChartWidget without QWebEngineView
QmitkChartWidget widget(nullptr, true);
CPPUNIT_ASSERT_NO_THROW_MESSAGE("Adding data caused an exception", widget.AddData1D(data1D, label));
std::vector<std::unique_ptr<QmitkChartxyData>> *dataVector = widget.GetData();
CPPUNIT_ASSERT_MESSAGE("Adding data failed.", dataVector->size() == 1 && dataVector != nullptr);
QmitkChartxyData *dataPtr = dataVector->at(0).get();
CPPUNIT_ASSERT_MESSAGE("Label differs for no obvious reason",
dataPtr->GetLabel().toString().toStdString() == label);
std::vector<QVariant> insertedYData = dataPtr->GetYData().toVector().toStdVector();
CPPUNIT_ASSERT_MESSAGE("Data differs in size", insertedYData.size() == data1D.size());
for (size_t i = 0; i < data1D.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D[i] == insertedYData[i]);
}
}
void AddSameLabelTwice_Test_Success()
{
QmitkChartWidget widget(nullptr, true);
widget.AddData1D(data1D, label);
widget.AddData1D(data1D, label);
auto dataVector = widget.GetData();
QmitkChartxyData* xyData1 = dataVector->at(0).get();
QmitkChartxyData* xyData2 = dataVector->at(1).get();
QVariant dataLabel1 = xyData1->GetLabel();
QVariant dataLabel2 = xyData2->GetLabel();
CPPUNIT_ASSERT_MESSAGE("The two dataLabel are the same", dataLabel1 != dataLabel2);
QString string1 = dataLabel1.toString();
QString string2 = dataLabel2.toString();
std::string stdString1 = string1.toStdString();
std::string stdString2 = string2.toStdString();
CPPUNIT_ASSERT_MESSAGE("The first dataLabel isn't still the same", stdString1 == label);
CPPUNIT_ASSERT_MESSAGE("The second dataLabel is still the same", stdString2 != label);
}
void AddAndRemoveData_Sucess()
{
std::vector<double> data1D2 = {2, 2};
std::string label2 = "testData2";
std::vector<double> data1D3 = {3, 3, 3};
std::string label3 = "testData3";
QmitkChartWidget widget(nullptr, true);
widget.AddData1D(data1D, label);
widget.AddData1D(data1D2, label2);
widget.AddData1D(data1D3, label3);
auto dataVector = widget.GetData();
// data with {data1D0, data1D2, data1D3}
CPPUNIT_ASSERT_MESSAGE("Adding data failed.", dataVector->size() == 3 && dataVector != nullptr);
widget.RemoveData(label2);
// data with {data1D0, data1D3}
CPPUNIT_ASSERT_MESSAGE("Removing data failed.", dataVector->size() == 2 && dataVector != nullptr);
QmitkChartxyData *xyData1 = dataVector->at(0).get();
std::vector<QVariant> insertedYData = xyData1->GetYData().toVector().toStdVector();
for (size_t i = 0; i < data1D.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D[i] == insertedYData[i]);
}
QmitkChartxyData *xyData2 = dataVector->at(1).get();
insertedYData = xyData2->GetYData().toVector().toStdVector();
for (size_t i = 0; i < data1D3.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D3[i] == insertedYData[i]);
}
widget.RemoveData(label);
// data with {data1D3}
CPPUNIT_ASSERT_MESSAGE("Removing data failed.", dataVector->size() == 1 && dataVector != nullptr);
widget.AddData1D(data1D2, label2);
CPPUNIT_ASSERT_MESSAGE("Adding data failed.", dataVector->size() == 2 && dataVector != nullptr);
//data with {data1D3, data1D2}
xyData1 = dataVector->at(0).get();
insertedYData = xyData1->GetYData().toVector().toStdVector();
for (size_t i = 0; i < data1D3.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D3[i] == insertedYData[i]);
}
xyData2 = dataVector->at(1).get();
insertedYData = xyData2->GetYData().toVector().toStdVector();
for (size_t i = 0; i < data1D2.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D2[i] == insertedYData[i]);
}
}
void RemoveNonexistingData_Failure()
{
QmitkChartWidget widget(nullptr, true);
CPPUNIT_ASSERT_THROW_MESSAGE(
"Removin nonexistend label did not throw exception", widget.RemoveData(label), std::invalid_argument);
}
void RemoveData_Success()
{
QmitkChartWidget widget(nullptr, true);
widget.AddData1D(data1D, label);
CPPUNIT_ASSERT_NO_THROW_MESSAGE("Removin nonexistend label did not throw exception", widget.RemoveData(label));
}
void SetandGet_Success()
{
QmitkChartWidget widget(nullptr, true);
widget.AddData1D(data1D, label);
std::string colorName = "green";
auto mitkChartxyData = widget.GetData();
QmitkChartxyData *xyData1 = mitkChartxyData->at(0).get();
//set color test
widget.SetColor(label, colorName);
auto qVariantColor = xyData1->GetColor();
QString qStringColor = qVariantColor.toString();
CPPUNIT_ASSERT_MESSAGE("The color isn't the assigned color", colorName == qStringColor.toStdString());
//set line style test
QVariant defaultLineStyle = xyData1->GetLineStyle();
widget.SetLineStyle(label, QmitkChartWidget::LineStyle::dashed);
QVariant lineStyle = xyData1->GetLineStyle();
QVariant defaultChartType = xyData1->GetChartType();
auto line= std::make_pair("line", QmitkChartWidget::ChartType::line);
if (defaultChartType.toString().toStdString() != line.first)
{
CPPUNIT_ASSERT_MESSAGE("The line style could be changed without ChartType line",
defaultLineStyle == lineStyle);
}
//set ChartType
widget.SetChartType(label, QmitkChartWidget::ChartType::line);
QVariant chartType = xyData1->GetChartType();
CPPUNIT_ASSERT_MESSAGE("The chart type could not be changed to line",
chartType.toString().toStdString() == line.first);
//set line style with chart type line
widget.SetLineStyle(label, QmitkChartWidget::LineStyle::dashed);
lineStyle = xyData1->GetLineStyle();
CPPUNIT_ASSERT_MESSAGE("The line style could not be changed", "dashed" == lineStyle.toString().toStdString());
}
void SetC3DataAndGet_Success()
{
QmitkChartWidget widget(nullptr, true);
widget.AddData1D(data1D, label);
//set YAxisScale
widget.SetYAxisScale(QmitkChartWidget::AxisScale::log);
QmitkChartData *c3Data = widget.GetC3Data();
QVariant yAxisScale = c3Data->GetYAxisScale();
CPPUNIT_ASSERT_MESSAGE("The YAxisScale could not be changed", "log" == yAxisScale.toString().toStdString());
//set Title
std::string testTitle = "testTitle";
widget.SetTitle(testTitle);
QVariant title = c3Data->GetTitle();
CPPUNIT_ASSERT_MESSAGE("The title could not be set", testTitle == title.toString().toStdString());
//set LegendPosition
widget.SetLegendPosition(QmitkChartWidget::LegendPosition::right);
QVariant legendPosition = c3Data->GetLegendPosition();
CPPUNIT_ASSERT_MESSAGE("The LegendPosition could not be changed", "right" == legendPosition.toString().toStdString());
//show legend
QVariant isShowLegend = c3Data->GetShowLegend();
widget.SetShowLegend(!isShowLegend.toBool());
QVariant isShowLegendInverted = c3Data->GetShowLegend();
CPPUNIT_ASSERT_MESSAGE("The ShowLegend could not be changed",
isShowLegend.toBool() != isShowLegendInverted.toBool());
//show dataPoints
QVariant dataPointSize = c3Data->GetDataPointSize();
bool showDataPoints = dataPointSize.toInt() > 0;
widget.SetShowDataPoints(!showDataPoints);
dataPointSize = c3Data->GetDataPointSize();
bool showDataPointsInvert = dataPointSize.toInt() > 0;
CPPUNIT_ASSERT_MESSAGE("The DataPoints could not be changed",
isShowLegend.toBool() != isShowLegendInverted.toBool());
}
};
MITK_TEST_SUITE_REGISTRATION(mitkChartWidget)<commit_msg>removed warning of unused variable<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.
===================================================================*/
// Testing
#include "mitkTestFixture.h"
#include "mitkTestingMacros.h"
// qt includes
#include "QApplication"
// std includes
#include <string>
// MITK includes
#include "QmitkChartWidget.h"
#include "QmitkChartxyData.h"
#include "QmitkChartData.h"
class mitkChartWidgetTestSuite : public mitk::TestFixture
{
CPPUNIT_TEST_SUITE(mitkChartWidgetTestSuite);
// Test the dicom property parsing
MITK_TEST(AddOnce_Test_Success);
MITK_TEST(AddSameLabelTwice_Test_Success);
MITK_TEST(RemoveNonexistingData_Failure);
MITK_TEST(RemoveData_Success);
MITK_TEST(SetandGet_Success);
MITK_TEST(SetC3DataAndGet_Success);
MITK_TEST(AddAndRemoveData_Sucess);
CPPUNIT_TEST_SUITE_END();
private:
std::vector<double> data1D;
std::string label;
public:
void setUp() override
{
data1D = {2, 4, 7, 8, 21, 5, 12, 65, 41, 9};
label = "testLabel";
int argc = 1;
char *argv[] = {(char *)"AppName"};
if (QApplication::instance() == nullptr)
{
new QApplication(argc, argv);
}
}
void tearDown() override {}
void AddOnce_Test_Success()
{
//use QmitkChartWidget without QWebEngineView
QmitkChartWidget widget(nullptr, true);
CPPUNIT_ASSERT_NO_THROW_MESSAGE("Adding data caused an exception", widget.AddData1D(data1D, label));
std::vector<std::unique_ptr<QmitkChartxyData>> *dataVector = widget.GetData();
CPPUNIT_ASSERT_MESSAGE("Adding data failed.", dataVector->size() == 1 && dataVector != nullptr);
QmitkChartxyData *dataPtr = dataVector->at(0).get();
CPPUNIT_ASSERT_MESSAGE("Label differs for no obvious reason",
dataPtr->GetLabel().toString().toStdString() == label);
std::vector<QVariant> insertedYData = dataPtr->GetYData().toVector().toStdVector();
CPPUNIT_ASSERT_MESSAGE("Data differs in size", insertedYData.size() == data1D.size());
for (size_t i = 0; i < data1D.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D[i] == insertedYData[i]);
}
}
void AddSameLabelTwice_Test_Success()
{
QmitkChartWidget widget(nullptr, true);
widget.AddData1D(data1D, label);
widget.AddData1D(data1D, label);
auto dataVector = widget.GetData();
QmitkChartxyData* xyData1 = dataVector->at(0).get();
QmitkChartxyData* xyData2 = dataVector->at(1).get();
QVariant dataLabel1 = xyData1->GetLabel();
QVariant dataLabel2 = xyData2->GetLabel();
CPPUNIT_ASSERT_MESSAGE("The two dataLabel are the same", dataLabel1 != dataLabel2);
QString string1 = dataLabel1.toString();
QString string2 = dataLabel2.toString();
std::string stdString1 = string1.toStdString();
std::string stdString2 = string2.toStdString();
CPPUNIT_ASSERT_MESSAGE("The first dataLabel isn't still the same", stdString1 == label);
CPPUNIT_ASSERT_MESSAGE("The second dataLabel is still the same", stdString2 != label);
}
void AddAndRemoveData_Sucess()
{
std::vector<double> data1D2 = {2, 2};
std::string label2 = "testData2";
std::vector<double> data1D3 = {3, 3, 3};
std::string label3 = "testData3";
QmitkChartWidget widget(nullptr, true);
widget.AddData1D(data1D, label);
widget.AddData1D(data1D2, label2);
widget.AddData1D(data1D3, label3);
auto dataVector = widget.GetData();
// data with {data1D0, data1D2, data1D3}
CPPUNIT_ASSERT_MESSAGE("Adding data failed.", dataVector->size() == 3 && dataVector != nullptr);
widget.RemoveData(label2);
// data with {data1D0, data1D3}
CPPUNIT_ASSERT_MESSAGE("Removing data failed.", dataVector->size() == 2 && dataVector != nullptr);
QmitkChartxyData *xyData1 = dataVector->at(0).get();
std::vector<QVariant> insertedYData = xyData1->GetYData().toVector().toStdVector();
for (size_t i = 0; i < data1D.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D[i] == insertedYData[i]);
}
QmitkChartxyData *xyData2 = dataVector->at(1).get();
insertedYData = xyData2->GetYData().toVector().toStdVector();
for (size_t i = 0; i < data1D3.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D3[i] == insertedYData[i]);
}
widget.RemoveData(label);
// data with {data1D3}
CPPUNIT_ASSERT_MESSAGE("Removing data failed.", dataVector->size() == 1 && dataVector != nullptr);
widget.AddData1D(data1D2, label2);
CPPUNIT_ASSERT_MESSAGE("Adding data failed.", dataVector->size() == 2 && dataVector != nullptr);
//data with {data1D3, data1D2}
xyData1 = dataVector->at(0).get();
insertedYData = xyData1->GetYData().toVector().toStdVector();
for (size_t i = 0; i < data1D3.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D3[i] == insertedYData[i]);
}
xyData2 = dataVector->at(1).get();
insertedYData = xyData2->GetYData().toVector().toStdVector();
for (size_t i = 0; i < data1D2.size(); ++i)
{
CPPUNIT_ASSERT_MESSAGE("The inserted data differs when checked", data1D2[i] == insertedYData[i]);
}
}
void RemoveNonexistingData_Failure()
{
QmitkChartWidget widget(nullptr, true);
CPPUNIT_ASSERT_THROW_MESSAGE(
"Removin nonexistend label did not throw exception", widget.RemoveData(label), std::invalid_argument);
}
void RemoveData_Success()
{
QmitkChartWidget widget(nullptr, true);
widget.AddData1D(data1D, label);
CPPUNIT_ASSERT_NO_THROW_MESSAGE("Removin nonexistend label did not throw exception", widget.RemoveData(label));
}
void SetandGet_Success()
{
QmitkChartWidget widget(nullptr, true);
widget.AddData1D(data1D, label);
std::string colorName = "green";
auto mitkChartxyData = widget.GetData();
QmitkChartxyData *xyData1 = mitkChartxyData->at(0).get();
//set color test
widget.SetColor(label, colorName);
auto qVariantColor = xyData1->GetColor();
QString qStringColor = qVariantColor.toString();
CPPUNIT_ASSERT_MESSAGE("The color isn't the assigned color", colorName == qStringColor.toStdString());
//set line style test
QVariant defaultLineStyle = xyData1->GetLineStyle();
widget.SetLineStyle(label, QmitkChartWidget::LineStyle::dashed);
QVariant lineStyle = xyData1->GetLineStyle();
QVariant defaultChartType = xyData1->GetChartType();
auto line= std::make_pair("line", QmitkChartWidget::ChartType::line);
if (defaultChartType.toString().toStdString() != line.first)
{
CPPUNIT_ASSERT_MESSAGE("The line style could be changed without ChartType line",
defaultLineStyle == lineStyle);
}
//set ChartType
widget.SetChartType(label, QmitkChartWidget::ChartType::line);
QVariant chartType = xyData1->GetChartType();
CPPUNIT_ASSERT_MESSAGE("The chart type could not be changed to line",
chartType.toString().toStdString() == line.first);
//set line style with chart type line
widget.SetLineStyle(label, QmitkChartWidget::LineStyle::dashed);
lineStyle = xyData1->GetLineStyle();
CPPUNIT_ASSERT_MESSAGE("The line style could not be changed", "dashed" == lineStyle.toString().toStdString());
}
void SetC3DataAndGet_Success()
{
QmitkChartWidget widget(nullptr, true);
widget.AddData1D(data1D, label);
//set YAxisScale
widget.SetYAxisScale(QmitkChartWidget::AxisScale::log);
QmitkChartData *c3Data = widget.GetC3Data();
QVariant yAxisScale = c3Data->GetYAxisScale();
CPPUNIT_ASSERT_MESSAGE("The YAxisScale could not be changed", "log" == yAxisScale.toString().toStdString());
//set Title
std::string testTitle = "testTitle";
widget.SetTitle(testTitle);
QVariant title = c3Data->GetTitle();
CPPUNIT_ASSERT_MESSAGE("The title could not be set", testTitle == title.toString().toStdString());
//set LegendPosition
widget.SetLegendPosition(QmitkChartWidget::LegendPosition::right);
QVariant legendPosition = c3Data->GetLegendPosition();
CPPUNIT_ASSERT_MESSAGE("The LegendPosition could not be changed", "right" == legendPosition.toString().toStdString());
//show legend
QVariant isShowLegend = c3Data->GetShowLegend();
widget.SetShowLegend(!isShowLegend.toBool());
QVariant isShowLegendInverted = c3Data->GetShowLegend();
CPPUNIT_ASSERT_MESSAGE("The ShowLegend could not be changed",
isShowLegend.toBool() != isShowLegendInverted.toBool());
//show dataPoints
QVariant dataPointSize = c3Data->GetDataPointSize();
bool showDataPoints = dataPointSize.toInt() > 0;
widget.SetShowDataPoints(!showDataPoints);
dataPointSize = c3Data->GetDataPointSize();
bool showDataPointsInvert = dataPointSize.toInt() > 0;
CPPUNIT_ASSERT_MESSAGE("The DataPoints could not be changed",
showDataPoints != showDataPointsInvert);
}
};
MITK_TEST_SUITE_REGISTRATION(mitkChartWidget)<|endoftext|> |
<commit_before>#include "VertexShaderDX11.h"
#include "InputLayoutDX11.h"
namespace Mile
{
VertexShaderDX11::VertexShaderDX11( RendererDX11* renderer ) :
m_shader( nullptr ),
m_inputLayout( nullptr ),
ShaderDX11( renderer )
{
}
VertexShaderDX11::~VertexShaderDX11( )
{
SafeRelease( m_shader );
}
bool VertexShaderDX11::Init( const String& shaderPath )
{
if ( m_bIsCompiled || m_renderer == nullptr )
{
return false;
}
if ( !Compile( shaderPath, ShaderType::VertexShader ) )
{
return false;
}
auto device = m_renderer->GetDevice( );
auto result = device->CreateVertexShader( m_blob->GetBufferPointer( ), m_blob->GetBufferSize( ),
nullptr,
&m_shader );
if ( FAILED( result ) )
{
// Failed to create vertex shader
return false;
}
m_inputLayout = std::make_unique<InputLayoutDX11>( m_renderer );
if ( !m_inputLayout->Init( this->Reflect( ), this ) )
{
return false;
}
return true;
}
bool VertexShaderDX11::Bind( )
{
if ( !m_bIsCompiled || m_renderer == nullptr )
{
return false;
}
// Set Input Layout
if ( !m_inputLayout->Bind( ) )
{
return false;
}
m_renderer->GetDeviceContext( )->VSSetShader( m_shader, nullptr, 0 );
return true;
}
void VertexShaderDX11::Unbind( )
{
if ( m_renderer != nullptr )
{
auto deviceContext = m_renderer->GetDeviceContext( );
deviceContext->VSSetShader( nullptr, nullptr, 0 );
}
}
std::vector<D3D11_INPUT_ELEMENT_DESC> VertexShaderDX11::Reflect( ) const
{
auto inputLayoutDescs = std::vector<D3D11_INPUT_ELEMENT_DESC>( );
ID3D11ShaderReflection* vsReflection = nullptr;
auto result = D3DReflect( m_blob->GetBufferPointer( ), m_blob->GetBufferSize( ),
IID_ID3D11ShaderReflection, ( void** )( &m_shader ) );
if ( FAILED( result ) )
{
return std::move( inputLayoutDescs );
}
D3D11_SHADER_DESC shaderDesc;
vsReflection->GetDesc( &shaderDesc );
for ( unsigned int idx = 0; idx < shaderDesc.InputParameters; ++idx )
{
D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
vsReflection->GetInputParameterDesc( idx, ¶mDesc );
D3D11_INPUT_ELEMENT_DESC elementDesc;
elementDesc.SemanticName = paramDesc.SemanticName;
elementDesc.SemanticIndex = paramDesc.SemanticIndex;
elementDesc.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
elementDesc.InputSlot = 0;
elementDesc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
elementDesc.InstanceDataStepRate = 0;
if ( paramDesc.Mask == 1 )
{
if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32 ) elementDesc.Format = DXGI_FORMAT_R32_UINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32 ) elementDesc.Format = DXGI_FORMAT_R32_SINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32 ) elementDesc.Format = DXGI_FORMAT_R32_FLOAT;
}
else if ( paramDesc.Mask < 4 )
{
if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32 ) elementDesc.Format = DXGI_FORMAT_R32G32_UINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32 ) elementDesc.Format = DXGI_FORMAT_R32G32_SINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32 ) elementDesc.Format = DXGI_FORMAT_R32G32_FLOAT;
}
else if ( paramDesc.Mask < 8 )
{
if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32 ) elementDesc.Format = DXGI_FORMAT_R32G32B32_UINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32 ) elementDesc.Format = DXGI_FORMAT_R32G32B32_SINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32 ) elementDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT;
}
else if ( paramDesc.Mask < 16 )
{
if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32 ) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32 ) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_SINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32 ) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
}
inputLayoutDescs.push_back( elementDesc );
}
return std::move( inputLayoutDescs );
}
}<commit_msg>Fixed d3d reflect<commit_after>#include "VertexShaderDX11.h"
#include "InputLayoutDX11.h"
namespace Mile
{
VertexShaderDX11::VertexShaderDX11( RendererDX11* renderer ) :
m_shader( nullptr ),
m_inputLayout( nullptr ),
ShaderDX11( renderer )
{
}
VertexShaderDX11::~VertexShaderDX11( )
{
SafeRelease( m_shader );
}
bool VertexShaderDX11::Init( const String& shaderPath )
{
if ( m_bIsCompiled || m_renderer == nullptr )
{
return false;
}
if ( !Compile( shaderPath, ShaderType::VertexShader ) )
{
return false;
}
auto device = m_renderer->GetDevice( );
auto result = device->CreateVertexShader( m_blob->GetBufferPointer( ), m_blob->GetBufferSize( ),
nullptr,
&m_shader );
if ( FAILED( result ) )
{
// Failed to create vertex shader
return false;
}
m_inputLayout = std::make_unique<InputLayoutDX11>( m_renderer );
if ( !m_inputLayout->Init( this->Reflect( ), this ) )
{
return false;
}
return true;
}
bool VertexShaderDX11::Bind( )
{
if ( !m_bIsCompiled || m_renderer == nullptr )
{
return false;
}
// Set Input Layout
if ( !m_inputLayout->Bind( ) )
{
return false;
}
m_renderer->GetDeviceContext( )->VSSetShader( m_shader, nullptr, 0 );
return true;
}
void VertexShaderDX11::Unbind( )
{
if ( m_renderer != nullptr )
{
auto deviceContext = m_renderer->GetDeviceContext( );
deviceContext->VSSetShader( nullptr, nullptr, 0 );
}
}
std::vector<D3D11_INPUT_ELEMENT_DESC> VertexShaderDX11::Reflect( ) const
{
auto inputLayoutDescs = std::vector<D3D11_INPUT_ELEMENT_DESC>( );
ID3D11ShaderReflection* vsReflection = nullptr;
auto result = D3DReflect( m_blob->GetBufferPointer( ), m_blob->GetBufferSize( ),
IID_ID3D11ShaderReflection, ( void** )( &vsReflection ) );
if ( FAILED( result ) )
{
return std::move( inputLayoutDescs );
}
D3D11_SHADER_DESC shaderDesc;
vsReflection->GetDesc( &shaderDesc );
for ( unsigned int idx = 0; idx < shaderDesc.InputParameters; ++idx )
{
D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
vsReflection->GetInputParameterDesc( idx, ¶mDesc );
D3D11_INPUT_ELEMENT_DESC elementDesc;
elementDesc.SemanticName = paramDesc.SemanticName;
elementDesc.SemanticIndex = paramDesc.SemanticIndex;
elementDesc.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
elementDesc.InputSlot = 0;
elementDesc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
elementDesc.InstanceDataStepRate = 0;
if ( paramDesc.Mask == 1 )
{
if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32 ) elementDesc.Format = DXGI_FORMAT_R32_UINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32 ) elementDesc.Format = DXGI_FORMAT_R32_SINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32 ) elementDesc.Format = DXGI_FORMAT_R32_FLOAT;
}
else if ( paramDesc.Mask < 4 )
{
if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32 ) elementDesc.Format = DXGI_FORMAT_R32G32_UINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32 ) elementDesc.Format = DXGI_FORMAT_R32G32_SINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32 ) elementDesc.Format = DXGI_FORMAT_R32G32_FLOAT;
}
else if ( paramDesc.Mask < 8 )
{
if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32 ) elementDesc.Format = DXGI_FORMAT_R32G32B32_UINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32 ) elementDesc.Format = DXGI_FORMAT_R32G32B32_SINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32 ) elementDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT;
}
else if ( paramDesc.Mask < 16 )
{
if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32 ) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32 ) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_SINT;
else if ( paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32 ) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
}
inputLayoutDescs.push_back( elementDesc );
}
return std::move( inputLayoutDescs );
}
}<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/**
\file KeyValueFileParser.cpp
\author Jens Krueger
SCI Institute
University of Utah
\date September 2008
*/
#include "KeyValueFileParser.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <sstream>
#include <Basics/SysTools.h>
using namespace std;
KeyValPair::KeyValPair() :
strKey(""),
wstrKey(L""),
strKeyUpper(""),
wstrKeyUpper(L""),
strValue(""),
wstrValue(L""),
strValueUpper(""),
wstrValueUpper(L""),
uiValue(0),
iValue(0),
fValue(0),
viValue(0,0,0),
vfValue(0,0,0)
{}
KeyValPair::KeyValPair(const string& key, const string& value) :
strKey(key),
wstrKey(key.begin(), key.end()),
strValue(value),
wstrValue(value.begin(), value.end())
{
istringstream ss1( value ), ss2( value ), ss3( value ), ss4( value ), ss5( value ), ss6( value );
ss1 >> uiValue;
ss2 >> iValue;
ss3 >> fValue;
ss4 >> viValue.x >> viValue.y >> viValue.z;
ss5 >> vuiValue.x >> vuiValue.y >> vuiValue.z;
ss6 >> vfValue.x >> vfValue.y >> vfValue.z;
strKeyUpper = strKey; transform(strKeyUpper.begin(), strKeyUpper.end(), strKeyUpper.begin(), ::toupper);
wstrKeyUpper = wstrKey; transform(wstrKeyUpper.begin(), wstrKeyUpper.end(), wstrKeyUpper.begin(), ::toupper);
strValueUpper = strValue; transform(strValueUpper.begin(), strValueUpper.end(), strValueUpper.begin(), ::toupper);
wstrValueUpper = wstrValue; transform(wstrValueUpper.begin(), wstrValueUpper.end(), wstrValueUpper.begin(), ::toupper);
}
KeyValPair::KeyValPair(const wstring& key, const wstring& value) :
strKey(key.begin(), key.end()),
wstrKey(key),
strValue(value.begin(), value.end()),
wstrValue(value)
{
wistringstream ss1( value ), ss2( value ), ss3( value ), ss4( value ), ss5( value ), ss6( value );
ss1 >> uiValue;
ss2 >> iValue;
ss3 >> fValue;
ss4 >> viValue.x >> viValue.y >> viValue.z;
ss5 >> vuiValue.x >> vuiValue.y >> vuiValue.z;
ss6 >> vfValue.x >> vfValue.y >> vfValue.z;
strKeyUpper = strKey; transform(strKeyUpper.begin(), strKeyUpper.end(), strKeyUpper.begin(), ::toupper);
wstrKeyUpper = wstrKey; transform(wstrKeyUpper.begin(), wstrKeyUpper.end(), wstrKeyUpper.begin(), ::toupper);
strValueUpper = strValue; transform(strValueUpper.begin(), strValueUpper.end(), strValueUpper.begin(), ::toupper);
wstrValueUpper = wstrValue; transform(wstrValueUpper.begin(), wstrValueUpper.end(), wstrValueUpper.begin(), ::toupper);
}
KeyValueFileParser::KeyValueFileParser(const string& strFilename, bool bStopOnEmptyLine, const string& strToken)
{
m_bFileReadable = ParseFile(strFilename, bStopOnEmptyLine, strToken);
}
KeyValueFileParser::KeyValueFileParser(const wstring& wstrFilename, bool bStopOnEmptyLine, const wstring& wstrToken)
{
string strFilename(wstrFilename.begin(), wstrFilename.end());
string strToken(wstrToken.begin(), wstrToken.end());
m_bFileReadable = ParseFile(strFilename, bStopOnEmptyLine, strToken);
}
KeyValueFileParser::~KeyValueFileParser()
{
}
KeyValPair* KeyValueFileParser::GetData(const string& strKey, const bool bCaseSensitive) {
if (!bCaseSensitive) {
string upperKey(strKey);
transform(upperKey.begin(), upperKey.end(), upperKey.begin(), ::toupper);
for (uint i = 0;i<m_vecTokens.size();i++) if (m_vecTokens[i].strKeyUpper == upperKey) return &m_vecTokens[i];
} else {
for (uint i = 0;i<m_vecTokens.size();i++) if (m_vecTokens[i].strKey == strKey) return &m_vecTokens[i];
}
return NULL;
}
KeyValPair* KeyValueFileParser::GetData(const wstring& wstrKey, const bool bCaseSensitive) {
if (!bCaseSensitive) {
wstring wupperKey(wstrKey);
transform(wupperKey.begin(), wupperKey.end(), wupperKey.begin(), ::toupper);
for (uint i = 0;i<m_vecTokens.size();i++) if (m_vecTokens[i].wstrKeyUpper == wupperKey) return &m_vecTokens[i];
} else {
for (uint i = 0;i<m_vecTokens.size();i++) if (m_vecTokens[i].wstrKey == wstrKey) return &m_vecTokens[i];
}
return NULL;
}
bool KeyValueFileParser::ParseFile(const std::string& strFilename, bool bStopOnEmptyLine, const std::string& strToken) {
string line;
ifstream fileData(strFilename.c_str(),ios::binary);
m_iStopPos = 0;
if (fileData.is_open())
{
while (! fileData.eof() )
{
getline (fileData,line);
SysTools::RemoveLeadingWhitespace(line);
if (bStopOnEmptyLine && line.size() == 0) {
m_iStopPos = fileData.tellg();
break;
}
if (line[0] == '#') continue; // skip comments
if (line.find_first_of(strToken) == string::npos) continue; // skip invalid lines
string strKey = line.substr(0, line.find_first_of(strToken));
SysTools::RemoveTailingWhitespace(strKey);
line = line.substr(line.find_first_of(strToken)+strToken.length(), line.length());
SysTools::RemoveLeadingWhitespace(line);
SysTools::RemoveTailingWhitespace(line);
if (strKey.length() == 0 || line.length() == 0) continue;
KeyValPair newKey(strKey, line);
m_vecTokens.push_back(newKey);
}
fileData.close();
} else return false;
return true;
}
<commit_msg>Replace tabs with two spaces.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
/**
\file KeyValueFileParser.cpp
\author Jens Krueger
SCI Institute
University of Utah
\date September 2008
*/
#include "KeyValueFileParser.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <sstream>
#include <Basics/SysTools.h>
using namespace std;
KeyValPair::KeyValPair() :
strKey(""),
wstrKey(L""),
strKeyUpper(""),
wstrKeyUpper(L""),
strValue(""),
wstrValue(L""),
strValueUpper(""),
wstrValueUpper(L""),
uiValue(0),
iValue(0),
fValue(0),
viValue(0,0,0),
vfValue(0,0,0)
{}
KeyValPair::KeyValPair(const string& key, const string& value) :
strKey(key),
wstrKey(key.begin(), key.end()),
strValue(value),
wstrValue(value.begin(), value.end())
{
istringstream ss1( value ), ss2( value ), ss3( value ), ss4( value ), ss5( value ), ss6( value );
ss1 >> uiValue;
ss2 >> iValue;
ss3 >> fValue;
ss4 >> viValue.x >> viValue.y >> viValue.z;
ss5 >> vuiValue.x >> vuiValue.y >> vuiValue.z;
ss6 >> vfValue.x >> vfValue.y >> vfValue.z;
strKeyUpper = strKey; transform(strKeyUpper.begin(), strKeyUpper.end(), strKeyUpper.begin(), ::toupper);
wstrKeyUpper = wstrKey; transform(wstrKeyUpper.begin(), wstrKeyUpper.end(), wstrKeyUpper.begin(), ::toupper);
strValueUpper = strValue; transform(strValueUpper.begin(), strValueUpper.end(), strValueUpper.begin(), ::toupper);
wstrValueUpper = wstrValue; transform(wstrValueUpper.begin(), wstrValueUpper.end(), wstrValueUpper.begin(), ::toupper);
}
KeyValPair::KeyValPair(const wstring& key, const wstring& value) :
strKey(key.begin(), key.end()),
wstrKey(key),
strValue(value.begin(), value.end()),
wstrValue(value)
{
wistringstream ss1( value ), ss2( value ), ss3( value ), ss4( value ), ss5( value ), ss6( value );
ss1 >> uiValue;
ss2 >> iValue;
ss3 >> fValue;
ss4 >> viValue.x >> viValue.y >> viValue.z;
ss5 >> vuiValue.x >> vuiValue.y >> vuiValue.z;
ss6 >> vfValue.x >> vfValue.y >> vfValue.z;
strKeyUpper = strKey; transform(strKeyUpper.begin(), strKeyUpper.end(), strKeyUpper.begin(), ::toupper);
wstrKeyUpper = wstrKey; transform(wstrKeyUpper.begin(), wstrKeyUpper.end(), wstrKeyUpper.begin(), ::toupper);
strValueUpper = strValue; transform(strValueUpper.begin(), strValueUpper.end(), strValueUpper.begin(), ::toupper);
wstrValueUpper = wstrValue; transform(wstrValueUpper.begin(), wstrValueUpper.end(), wstrValueUpper.begin(), ::toupper);
}
KeyValueFileParser::KeyValueFileParser(const string& strFilename, bool bStopOnEmptyLine, const string& strToken)
{
m_bFileReadable = ParseFile(strFilename, bStopOnEmptyLine, strToken);
}
KeyValueFileParser::KeyValueFileParser(const wstring& wstrFilename, bool bStopOnEmptyLine, const wstring& wstrToken)
{
string strFilename(wstrFilename.begin(), wstrFilename.end());
string strToken(wstrToken.begin(), wstrToken.end());
m_bFileReadable = ParseFile(strFilename, bStopOnEmptyLine, strToken);
}
KeyValueFileParser::~KeyValueFileParser()
{
}
KeyValPair* KeyValueFileParser::GetData(const string& strKey, const bool bCaseSensitive) {
if (!bCaseSensitive) {
string upperKey(strKey);
transform(upperKey.begin(), upperKey.end(), upperKey.begin(), ::toupper);
for (uint i = 0;i<m_vecTokens.size();i++) if (m_vecTokens[i].strKeyUpper == upperKey) return &m_vecTokens[i];
} else {
for (uint i = 0;i<m_vecTokens.size();i++) if (m_vecTokens[i].strKey == strKey) return &m_vecTokens[i];
}
return NULL;
}
KeyValPair* KeyValueFileParser::GetData(const wstring& wstrKey, const bool bCaseSensitive) {
if (!bCaseSensitive) {
wstring wupperKey(wstrKey);
transform(wupperKey.begin(), wupperKey.end(), wupperKey.begin(), ::toupper);
for (uint i = 0;i<m_vecTokens.size();i++) if (m_vecTokens[i].wstrKeyUpper == wupperKey) return &m_vecTokens[i];
} else {
for (uint i = 0;i<m_vecTokens.size();i++) if (m_vecTokens[i].wstrKey == wstrKey) return &m_vecTokens[i];
}
return NULL;
}
bool KeyValueFileParser::ParseFile(const std::string& strFilename, bool bStopOnEmptyLine, const std::string& strToken) {
string line;
ifstream fileData(strFilename.c_str(),ios::binary);
m_iStopPos = 0;
if (fileData.is_open())
{
while (! fileData.eof() )
{
getline (fileData,line);
SysTools::RemoveLeadingWhitespace(line);
if (bStopOnEmptyLine && line.size() == 0) {
m_iStopPos = fileData.tellg();
break;
}
if (line[0] == '#') continue; // skip comments
if (line.find_first_of(strToken) == string::npos) continue; // skip invalid lines
string strKey = line.substr(0, line.find_first_of(strToken));
SysTools::RemoveTailingWhitespace(strKey);
line = line.substr(line.find_first_of(strToken)+strToken.length(), line.length());
SysTools::RemoveLeadingWhitespace(line);
SysTools::RemoveTailingWhitespace(line);
if (strKey.length() == 0 || line.length() == 0) continue;
KeyValPair newKey(strKey, line);
m_vecTokens.push_back(newKey);
}
fileData.close();
} else return false;
return true;
}
<|endoftext|> |
<commit_before>#include "Transform.h"
#include <assert.h>
using namespace Core;
using namespace Math;
const Matrix& Transform::ComputeLocalMatrix()
{
_localMat._11 = _scale.x * _right.x;
_localMat._12 = _scale.y * _up.x;
_localMat._13 = _scale.z * _forward.x;
_localMat._14 = 0.0f;
_localMat._21 = _scale.x * _right.y;
_localMat._22 = _scale.y * _up.y;
_localMat._23 = _scale.z * _forward.y;
_localMat._24 = 0.0f;
_localMat._31 = _scale.x * _right.z;
_localMat._32 = _scale.y * _up.z;
_localMat._33 = _scale.z * _forward.z;
_localMat._34 = 0.0f;
_localMat._41 = _position.x;
_localMat._42 = _position.y;
_localMat._43 = _position.z;
_localMat._44 = 1.0f;
return _localMat;
}
void Transform::UpdateLocalRight(const Vector3& r)
{
LookAtWorldDir(Vector3::Cross(_up, r));
}
void Transform::UpdateLocalUp(const Vector3& u)
{
LookAtWorldDir(Vector3::Cross(u, _right));
}
void Transform::UpdateLocalForward(const Vector3& f)
{
LookAtWorldDir(f);
}
void Transform::UpdateLocalEulerAngle(const Vector3& e)
{
_eulerAngle = Vector3::EulerNormalize(e);
_quaternion = Quaternion::FromEuler(-Vector3(DEG_TO_RAD(_eulerAngle.x),
DEG_TO_RAD(_eulerAngle.y),
DEG_TO_RAD(_eulerAngle.z)));
_right = _quaternion.GetRight();
_up = _quaternion.GetUp();
_forward = _quaternion.GetForward();
_dirty = true;
}
void Transform::UpdateLocalQuaternion(const Quaternion& q)
{
_quaternion = q;
Matrix rotationMatrix = Matrix::RotateUsingQuaternion(_quaternion);
_eulerAngle = Vector3::FromRotationMatrix(rotationMatrix);
_right = _quaternion.GetRight();
_up = _quaternion.GetUp();
_forward = _quaternion.GetForward();
_dirty = true;
}
void Transform::LookAtWorldDir(const Vector3& targetDir, const Vector3* upVec)
{
Matrix rotMat = Matrix::LookAtDir(targetDir, upVec);
_eulerAngle = Vector3::FromRotationMatrix(rotMat);
_quaternion = Quaternion::FromRotationMatrix(rotMat);
_right = _quaternion.GetRight();
_up = _quaternion.GetUp();
_forward = _quaternion.GetForward();
_dirty = true;
}
void Transform::AddChild(Transform& child)
{
bool hasParent = child._parentID != Core::ObjectID::Undefined();
assert(hasParent == false);
assert(HasChild(child.GetObjectID()) == false);
child._parentID = GetObjectID();
_childIDs.push_back(child.GetObjectID());
}
const Vector3 Transform::GetWorldPosition() const
{
return Vector3(_worldMat._41, _worldMat._42, _worldMat._43);
}
const Vector3 Transform::GetWorldScale() const
{
return Vector3( Vector3(_worldMat._11, _worldMat._12, _worldMat._13).Length(),
Vector3(_worldMat._21, _worldMat._22, _worldMat._23).Length(),
Vector3(_worldMat._31, _worldMat._32, _worldMat._33).Length() );
}
const Vector3 Transform::GetWorldRight(const Vector3& scale) const
{
return Vector3( _worldMat._11 / scale.x,
_worldMat._21 / scale.y,
_worldMat._31 / scale.z ).Normalized();
}
const Vector3 Transform::GetWorldUp(const Vector3& scale) const
{
return Vector3( _worldMat._12 / scale.x,
_worldMat._22 / scale.y,
_worldMat._32 / scale.z ).Normalized();
}
const Vector3 Transform::GetWorldForward(const Vector3& scale) const
{
return Vector3( _worldMat._13 / scale.x,
_worldMat._23 / scale.y,
_worldMat._33 / scale.z ).Normalized();
}
const Vector3 Transform::FetchWorldEulerAngle() const
{
Vector3 scale = GetWorldScale();
Matrix rotMat = Matrix::MakeRotationMatrix(GetWorldRight(scale), GetWorldUp(scale), GetWorldForward(scale));
return Vector3::FromRotationMatrix(rotMat);
}
const Quaternion Transform::FetchWorldQuaternion() const
{
Vector3 scale = GetWorldScale();
Matrix rotMat = Matrix::MakeRotationMatrix(GetWorldRight(scale), GetWorldUp(scale), GetWorldForward(scale));
return Quaternion::FromRotationMatrix(rotMat);
}
bool Transform::HasChild(ObjectID id) const
{
for (const auto childID : _childIDs)
{
if(childID == id)
return true;
}
return false;
}
void Transform::DeleteChild(ObjectID id)
{
uint pos = 0;
for (pos; pos < _childIDs.size() && _childIDs[pos] != id; ++pos);
assert(pos == _childIDs.size());
_childIDs.erase(_childIDs.begin() + pos);
}
void Transform::ClearDirty()
{
_dirty = false;
}
void Transform::_ComputeWorldMatrixWithDirty(TransformPool& pool, bool parentDirty)
{
_dirty |= parentDirty;
for (auto childID : _childIDs)
{
auto child = pool.Find(childID.Literal());
assert(child);
if(child->GetDirty() | _dirty)
child->_worldMat = child->ComputeLocalMatrix() * _worldMat;
child->_ComputeWorldMatrixWithDirty(pool, _dirty);
}
}
void Transform::UpdateWorldMatrix(TransformPool& pool)
{
// this func must be run in root
assert(_parentID == ObjectID::Undefined());
if (_dirty)
_worldMat = ComputeLocalMatrix();
_ComputeWorldMatrixWithDirty(pool, false);
}<commit_msg>Transform - GetWorldScale이 잘못 계산 되던 문제 수정<commit_after>#include "Transform.h"
#include <assert.h>
using namespace Core;
using namespace Math;
const Matrix& Transform::ComputeLocalMatrix()
{
_localMat._11 = _scale.x * _right.x;
_localMat._12 = _scale.y * _up.x;
_localMat._13 = _scale.z * _forward.x;
_localMat._14 = 0.0f;
_localMat._21 = _scale.x * _right.y;
_localMat._22 = _scale.y * _up.y;
_localMat._23 = _scale.z * _forward.y;
_localMat._24 = 0.0f;
_localMat._31 = _scale.x * _right.z;
_localMat._32 = _scale.y * _up.z;
_localMat._33 = _scale.z * _forward.z;
_localMat._34 = 0.0f;
_localMat._41 = _position.x;
_localMat._42 = _position.y;
_localMat._43 = _position.z;
_localMat._44 = 1.0f;
return _localMat;
}
void Transform::UpdateLocalRight(const Vector3& r)
{
LookAtWorldDir(Vector3::Cross(_up, r));
}
void Transform::UpdateLocalUp(const Vector3& u)
{
LookAtWorldDir(Vector3::Cross(u, _right));
}
void Transform::UpdateLocalForward(const Vector3& f)
{
LookAtWorldDir(f);
}
void Transform::UpdateLocalEulerAngle(const Vector3& e)
{
_eulerAngle = Vector3::EulerNormalize(e);
_quaternion = Quaternion::FromEuler(-Vector3(DEG_TO_RAD(_eulerAngle.x),
DEG_TO_RAD(_eulerAngle.y),
DEG_TO_RAD(_eulerAngle.z)));
_right = _quaternion.GetRight();
_up = _quaternion.GetUp();
_forward = _quaternion.GetForward();
_dirty = true;
}
void Transform::UpdateLocalQuaternion(const Quaternion& q)
{
_quaternion = q;
Matrix rotationMatrix = Matrix::RotateUsingQuaternion(_quaternion);
_eulerAngle = Vector3::FromRotationMatrix(rotationMatrix);
_right = _quaternion.GetRight();
_up = _quaternion.GetUp();
_forward = _quaternion.GetForward();
_dirty = true;
}
void Transform::LookAtWorldDir(const Vector3& targetDir, const Vector3* upVec)
{
Matrix rotMat = Matrix::LookAtDir(targetDir, upVec);
_eulerAngle = Vector3::FromRotationMatrix(rotMat);
_quaternion = Quaternion::FromRotationMatrix(rotMat);
_right = _quaternion.GetRight();
_up = _quaternion.GetUp();
_forward = _quaternion.GetForward();
_dirty = true;
}
void Transform::AddChild(Transform& child)
{
bool hasParent = child._parentID != Core::ObjectID::Undefined();
assert(hasParent == false);
assert(HasChild(child.GetObjectID()) == false);
child._parentID = GetObjectID();
_childIDs.push_back(child.GetObjectID());
}
const Vector3 Transform::GetWorldPosition() const
{
return Vector3(_worldMat._41, _worldMat._42, _worldMat._43);
}
const Vector3 Transform::GetWorldScale() const
{
// Forward Up Right
return Vector3( Vector3(_worldMat._11, _worldMat._21, _worldMat._31).Length(),
Vector3(_worldMat._12, _worldMat._22, _worldMat._32).Length(),
Vector3(_worldMat._13, _worldMat._23, _worldMat._33).Length() );
}
const Vector3 Transform::GetWorldRight(const Vector3& scale) const
{
return Vector3( _worldMat._11 / scale.x,
_worldMat._21 / scale.y,
_worldMat._31 / scale.z ).Normalized();
}
const Vector3 Transform::GetWorldUp(const Vector3& scale) const
{
return Vector3( _worldMat._12 / scale.x,
_worldMat._22 / scale.y,
_worldMat._32 / scale.z ).Normalized();
}
const Vector3 Transform::GetWorldForward(const Vector3& scale) const
{
return Vector3( _worldMat._13 / scale.x,
_worldMat._23 / scale.y,
_worldMat._33 / scale.z ).Normalized();
}
const Vector3 Transform::FetchWorldEulerAngle() const
{
Vector3 scale = GetWorldScale();
Matrix rotMat = Matrix::MakeRotationMatrix(GetWorldRight(scale), GetWorldUp(scale), GetWorldForward(scale));
return Vector3::FromRotationMatrix(rotMat);
}
const Quaternion Transform::FetchWorldQuaternion() const
{
Vector3 scale = GetWorldScale();
Matrix rotMat = Matrix::MakeRotationMatrix(GetWorldRight(scale), GetWorldUp(scale), GetWorldForward(scale));
return Quaternion::FromRotationMatrix(rotMat);
}
bool Transform::HasChild(ObjectID id) const
{
for (const auto childID : _childIDs)
{
if(childID == id)
return true;
}
return false;
}
void Transform::DeleteChild(ObjectID id)
{
uint pos = 0;
for (pos; pos < _childIDs.size() && _childIDs[pos] != id; ++pos);
assert(pos == _childIDs.size());
_childIDs.erase(_childIDs.begin() + pos);
}
void Transform::ClearDirty()
{
_dirty = false;
}
void Transform::_ComputeWorldMatrixWithDirty(TransformPool& pool, bool parentDirty)
{
_dirty |= parentDirty;
for (auto childID : _childIDs)
{
auto child = pool.Find(childID.Literal());
assert(child);
if(child->GetDirty() | _dirty)
child->_worldMat = child->ComputeLocalMatrix() * _worldMat;
child->_ComputeWorldMatrixWithDirty(pool, _dirty);
}
}
void Transform::UpdateWorldMatrix(TransformPool& pool)
{
// this func must be run in root
assert(_parentID == ObjectID::Undefined());
if (_dirty)
_worldMat = ComputeLocalMatrix();
_ComputeWorldMatrixWithDirty(pool, false);
}<|endoftext|> |
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2022 Baldur Karlsson
*
* 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.
******************************************************************************/
// Metal-cpp project: https://developer.apple.com/metal/cpp/
// https://developer.apple.com/metal/cpp/files/metal-cpp_macOS12_iOS15.zip
#define NS_PRIVATE_IMPLEMENTATION
#define CA_PRIVATE_IMPLEMENTATION
#define MTL_PRIVATE_IMPLEMENTATION
#include "metal-cpp.h"
<commit_msg>Updated copyright year to 2022<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2022 Baldur Karlsson
*
* 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.
******************************************************************************/
// Metal-cpp project: https://developer.apple.com/metal/cpp/
// https://developer.apple.com/metal/cpp/files/metal-cpp_macOS12_iOS15.zip
#define NS_PRIVATE_IMPLEMENTATION
#define CA_PRIVATE_IMPLEMENTATION
#define MTL_PRIVATE_IMPLEMENTATION
#include "metal-cpp.h"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ModuleHelper.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2008-02-25 16:26:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _RPTUI_MODULE_HELPER_RPT_HXX_
#include "ModuleHelper.hxx"
#endif
#ifndef _COMPHELPER_CONFIGURATIONHELPER_HXX_
#include <comphelper/configurationhelper.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMACROEXPANDER_HPP_
#include <com/sun/star/util/XMacroExpander.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _RTL_URI_HXX_
#include <rtl/uri.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SOLAR_HRC
#include <svtools/solar.hrc>
#endif
#define EXPAND_PROTOCOL "vnd.sun.star.expand:"
#define ENTER_MOD_METHOD() \
::osl::MutexGuard aGuard(s_aMutex); \
ensureImpl()
//.........................................................................
namespace rptui
{
//.........................................................................
using namespace ::com::sun::star;
//=========================================================================
//= OModuleImpl
//=========================================================================
/** implementation for <type>OModule</type>. not threadsafe, has to be guarded by it's owner
*/
class OModuleImpl
{
ResMgr* m_pRessources;
public:
/// ctor
OModuleImpl();
~OModuleImpl();
/// get the manager for the ressources of the module
ResMgr* getResManager();
};
DBG_NAME( rpt_OModuleImpl )
//-------------------------------------------------------------------------
OModuleImpl::OModuleImpl()
:m_pRessources(NULL)
{
DBG_CTOR( rpt_OModuleImpl,NULL);
}
//-------------------------------------------------------------------------
OModuleImpl::~OModuleImpl()
{
if (m_pRessources)
delete m_pRessources;
DBG_DTOR( rpt_OModuleImpl,NULL);
}
//-------------------------------------------------------------------------
ResMgr* OModuleImpl::getResManager()
{
// note that this method is not threadsafe, which counts for the whole class !
if (!m_pRessources)
{
// create a manager with a fixed prefix
rtl::OString sName = rtl::OString( "rptui" );
m_pRessources = ResMgr::CreateResMgr(sName);
}
return m_pRessources;
}
//=========================================================================
//= OModule
//=========================================================================
::osl::Mutex OModule::s_aMutex;
sal_Int32 OModule::s_nClients = 0;
OModuleImpl* OModule::s_pImpl = NULL;
//-------------------------------------------------------------------------
ResMgr* OModule::getResManager()
{
ENTER_MOD_METHOD();
return s_pImpl->getResManager();
}
//-------------------------------------------------------------------------
void OModule::registerClient()
{
::osl::MutexGuard aGuard(s_aMutex);
++s_nClients;
}
//-------------------------------------------------------------------------
void OModule::revokeClient()
{
::osl::MutexGuard aGuard(s_aMutex);
if (!--s_nClients && s_pImpl)
{
delete s_pImpl;
s_pImpl = NULL;
}
}
//-------------------------------------------------------------------------
void OModule::ensureImpl()
{
if (s_pImpl)
return;
s_pImpl = new OModuleImpl();
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.3.16); FILE MERGED 2008/04/01 15:23:36 thb 1.3.16.3: #i85898# Stripping all external header guards 2008/04/01 12:33:07 thb 1.3.16.2: #i85898# Stripping all external header guards 2008/03/31 13:32:04 rt 1.3.16.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ModuleHelper.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "ModuleHelper.hxx"
#include <comphelper/configurationhelper.hxx>
#include <comphelper/processfactory.hxx>
#include <osl/thread.h>
#include <com/sun/star/util/XMacroExpander.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <rtl/uri.hxx>
#include <tools/debug.hxx>
#ifndef _SOLAR_HRC
#include <svtools/solar.hrc>
#endif
#define EXPAND_PROTOCOL "vnd.sun.star.expand:"
#define ENTER_MOD_METHOD() \
::osl::MutexGuard aGuard(s_aMutex); \
ensureImpl()
//.........................................................................
namespace rptui
{
//.........................................................................
using namespace ::com::sun::star;
//=========================================================================
//= OModuleImpl
//=========================================================================
/** implementation for <type>OModule</type>. not threadsafe, has to be guarded by it's owner
*/
class OModuleImpl
{
ResMgr* m_pRessources;
public:
/// ctor
OModuleImpl();
~OModuleImpl();
/// get the manager for the ressources of the module
ResMgr* getResManager();
};
DBG_NAME( rpt_OModuleImpl )
//-------------------------------------------------------------------------
OModuleImpl::OModuleImpl()
:m_pRessources(NULL)
{
DBG_CTOR( rpt_OModuleImpl,NULL);
}
//-------------------------------------------------------------------------
OModuleImpl::~OModuleImpl()
{
if (m_pRessources)
delete m_pRessources;
DBG_DTOR( rpt_OModuleImpl,NULL);
}
//-------------------------------------------------------------------------
ResMgr* OModuleImpl::getResManager()
{
// note that this method is not threadsafe, which counts for the whole class !
if (!m_pRessources)
{
// create a manager with a fixed prefix
rtl::OString sName = rtl::OString( "rptui" );
m_pRessources = ResMgr::CreateResMgr(sName);
}
return m_pRessources;
}
//=========================================================================
//= OModule
//=========================================================================
::osl::Mutex OModule::s_aMutex;
sal_Int32 OModule::s_nClients = 0;
OModuleImpl* OModule::s_pImpl = NULL;
//-------------------------------------------------------------------------
ResMgr* OModule::getResManager()
{
ENTER_MOD_METHOD();
return s_pImpl->getResManager();
}
//-------------------------------------------------------------------------
void OModule::registerClient()
{
::osl::MutexGuard aGuard(s_aMutex);
++s_nClients;
}
//-------------------------------------------------------------------------
void OModule::revokeClient()
{
::osl::MutexGuard aGuard(s_aMutex);
if (!--s_nClients && s_pImpl)
{
delete s_pImpl;
s_pImpl = NULL;
}
}
//-------------------------------------------------------------------------
void OModule::ensureImpl()
{
if (s_pImpl)
return;
s_pImpl = new OModuleImpl();
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<|endoftext|> |
<commit_before>#include "AppDelegate.h"
#include "MainScene.h"
#include "config.h"
#include "IntroScene.h"
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
bool AppDelegate::applicationDidFinishLaunching() {
// initialize director
CCDirector* pDirector = CCDirector::sharedDirector();
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
//이것은 프레임 사이즈입니다.
CCEGLView::sharedOpenGLView()->setFrameSize(winSize.width,winSize.height);
#else
CCEGLView::sharedOpenGLView()->setFrameSize(WINDOW_WIDTH/2,WINDOW_HEIGHT/2);
#endif
//이것은 실제 우리가 만든 화면을 나타냅니다. 이 비율에 맞춰 모든 그림들이 프레임 사이즈로 줄어드는 것!!
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(WINDOW_WIDTH,WINDOW_HEIGHT,kResolutionShowAll);
// turn on display FPS
pDirector->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60);
// create a scene. it's an autorelease object
CCScene *pScene = CIntroScene::create();
// run
pDirector->runWithScene(CCTransitionFade::create(1.0,pScene));
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
CCDirector::sharedDirector()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
CCDirector::sharedDirector()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
<commit_msg>frame rate 숨기기<commit_after>#include "AppDelegate.h"
#include "MainScene.h"
#include "config.h"
#include "IntroScene.h"
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
bool AppDelegate::applicationDidFinishLaunching() {
// initialize director
CCDirector* pDirector = CCDirector::sharedDirector();
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
//이것은 프레임 사이즈입니다.
CCEGLView::sharedOpenGLView()->setFrameSize(winSize.width,winSize.height);
#else
CCEGLView::sharedOpenGLView()->setFrameSize(WINDOW_WIDTH/2,WINDOW_HEIGHT/2);
#endif
//이것은 실제 우리가 만든 화면을 나타냅니다. 이 비율에 맞춰 모든 그림들이 프레임 사이즈로 줄어드는 것!!
CCEGLView::sharedOpenGLView()->setDesignResolutionSize(WINDOW_WIDTH,WINDOW_HEIGHT,kResolutionShowAll);
// turn on display FPS
pDirector->setDisplayStats(false);
// set FPS. the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60);
// create a scene. it's an autorelease object
CCScene *pScene = CIntroScene::create();
// run
pDirector->runWithScene(CCTransitionFade::create(1.0,pScene));
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
CCDirector::sharedDirector()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
CCDirector::sharedDirector()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
<|endoftext|> |
<commit_before><commit_msg>VKSC command pool creation should respect maxCommandBufferSize<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2012 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 <stdio.h>
#include "client/linux/handler/minidump_descriptor.h"
#include "common/linux/guid_creator.h"
namespace google_breakpad {
MinidumpDescriptor::MinidumpDescriptor(const MinidumpDescriptor& descriptor)
: fd_(descriptor.fd_),
directory_(descriptor.directory_),
c_path_(NULL) {
// The copy constructor is not allowed to be called on a MinidumpDescriptor
// with a valid path_, as getting its c_path_ would require the heap which
// can cause problems in compromised environments.
assert(descriptor.path_.empty());
}
MinidumpDescriptor& MinidumpDescriptor::operator=(
const MinidumpDescriptor& descriptor) {
assert(descriptor.path_.empty());
fd_ = descriptor.fd_;
directory_ = descriptor.directory_;
path_.clear();
if (c_path_) {
// This descriptor already had a path set, so generate a new one.
c_path_ = NULL;
UpdatePath();
}
return *this;
}
void MinidumpDescriptor::UpdatePath() {
assert(fd_ == -1 && !directory_.empty());
GUID guid;
char guid_str[kGUIDStringLength + 1];
bool r = CreateGUID(&guid) && GUIDToString(&guid, guid_str, sizeof(guid_str));
assert(r);
path_.clear();
path_ = directory_ + "/" + guid_str + ".dmp";
c_path_ = path_.c_str();
}
} // namespace google_breakpad
<commit_msg>Fix unused variable warning in optimized build (fix proveded by Matthew Riley)<commit_after>// Copyright (c) 2012 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 <stdio.h>
#include "client/linux/handler/minidump_descriptor.h"
#include "common/linux/guid_creator.h"
namespace google_breakpad {
MinidumpDescriptor::MinidumpDescriptor(const MinidumpDescriptor& descriptor)
: fd_(descriptor.fd_),
directory_(descriptor.directory_),
c_path_(NULL) {
// The copy constructor is not allowed to be called on a MinidumpDescriptor
// with a valid path_, as getting its c_path_ would require the heap which
// can cause problems in compromised environments.
assert(descriptor.path_.empty());
}
MinidumpDescriptor& MinidumpDescriptor::operator=(
const MinidumpDescriptor& descriptor) {
assert(descriptor.path_.empty());
fd_ = descriptor.fd_;
directory_ = descriptor.directory_;
path_.clear();
if (c_path_) {
// This descriptor already had a path set, so generate a new one.
c_path_ = NULL;
UpdatePath();
}
return *this;
}
void MinidumpDescriptor::UpdatePath() {
assert(fd_ == -1 && !directory_.empty());
GUID guid;
char guid_str[kGUIDStringLength + 1];
if (!CreateGUID(&guid) || !GUIDToString(&guid, guid_str, sizeof(guid_str))) {
assert(false);
}
path_.clear();
path_ = directory_ + "/" + guid_str + ".dmp";
c_path_ = path_.c_str();
}
} // namespace google_breakpad
<|endoftext|> |
<commit_before>#pragma once
#include<algorithm>
#include<vector>
#include<universal/blas/matrix.hpp>
#include<mtl/operation/qr.hpp>
#include<mtl/operation/svd.hpp>
const double EPS = 1E-9;
double k = 0.0000001;
namespace sw {
namespace universal {
namespace blas {
template<typename T>
int find_rank(vector<vector<T>> A) {
int n = num_rows(A);
int m = num_cols(A);
int rank = 0;
vector<bool> row(n, false);
for (T i = 0; i < m; ++i) {
for (T j = 0; j < n; ++j) {
if (abs(A[j][i]) > EPS && !row[j]) break;
}
if (j != n) {
++rank;
row[j] = true;
for (T p = i + 1; p < m; ++p) A[j][p] /= A[j][i];
for (T k = 0; k < n; ++k) {
if (abs(A[k][i]) > EPS && k != j) {
for (T p = i + 1; p < m; ++p)
A[k][p] -= A[j][p] * A[k][i];
}
}
}
}
return rank;
}
template<typename T>
boost::tuple randsvd(vector<vector<T>> A) {
int k = min(num_cols(A), num_rows(A));
int n = num_cols(A), m = num_row(A);
//generate a gaussian random matrix of size n x k
vector<vector<T>> omega(n, vector<T>(k));
vector<vector<T>> Y(m, vector<T>(k));
vector<vector<T>> Q(m, vector<T>(k));
vector<vector<T>> R(m, vector<T>(k));
vector<vector<T>> B(n, vector<T>(k));
vector<vector<T>> S(n, vector<T>(n));
vector<vector<T>> V(n, vector<T>(k));
vector<vector<T>> D(k, vector<T>(k));
//omega(n x k) x A(m x n) == Y(m x k)
Y = A * omega;
boost::tie(Q, R) = qr(Y);
Q = transpose();
B = Q * A;
boost::tie(S, V, D) = svd(B,k);
return boost::make_tuple(S, V, D);
}
}
}
}<commit_msg>Updated randsvd.hpp<commit_after>#pragma once
#include<algorithm>
#include<vector>
#include<tuple>
#include<universal/blas/matrix.hpp>
#include<mtl/operation/qr.hpp>
#include<mtl/operation/svd.hpp>
const double EPS = 1E-9;
double k = 0.0000001;
namespace sw {
namespace universal {
namespace blas {
template<typename Scalar>
size_t find_rank(const matrix<Scalar> A) {
size_t n = num_rows(A);
size_t m = num_cols(A);
size_t rank = 0;
vector<bool> row(n, false);
for (size_t i = 0; i < m; ++i) {
for (size_t j = 0; j < n; ++j) {
if (abs(A[j][i]) > EPS && !row[j]) break;
}
if (j != n) {
++rank;
row[j] = true;
for (size_t p = i + 1; p < m; ++p) A[j][p] /= A[j][i];
for (size_t k = 0; k < n; ++k) {
if (abs(A[k][i]) > EPS && k != j) {
for (size_t p = i + 1; p < m; ++p)
A[k][p] -= A[j][p] * A[k][i];
}
}
}
}
return rank;
}
template<typename Scalar>
void qr(const matrix<Scalar> A, matrix<Scalar> Q, matrix<Scalar> R) {
}
template<typename Scalar>
tuple randsvd(const matrix<Scalar> &A) {
size_t k = min(num_cols(A), num_rows(A));
size_t n = num_cols(A), m = num_row(A);
//generate a gaussian random matrix of size n x k omega in this case
matrix<Scalar> omega,Y,Q,R,B,S,V,D;
//omega(n x k) x A(m x n) == Y(m x k)
Y = A * omega;
tie(Q, R) = qr(Y);
//implement qr decomposition & svd here
Q = transpose();
B = Q * A;
std::tie(S, V, D) = svd(B,k);
return std::make_tuple(S, V, D);
}
}
}
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: attrlist.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2003-03-27 18:20:11 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <vector>
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#include <rtl/uuid.h>
#include <rtl/memory.h>
#include <assert.h>
#include "attrlist.hxx"
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
struct SvXMLTagAttribute_Impl
{
SvXMLTagAttribute_Impl(){}
SvXMLTagAttribute_Impl( const OUString &rName,
const OUString &rValue )
: sName(rName),
sValue(rValue)
{
}
OUString sName;
OUString sValue;
};
struct SvXMLAttributeList_Impl
{
SvXMLAttributeList_Impl()
{
// performance improvement during adding
vecAttribute.reserve(20);
}
::std::vector<struct SvXMLTagAttribute_Impl> vecAttribute;
};
sal_Int16 SAL_CALL SvXMLAttributeList::getLength(void) throw( ::com::sun::star::uno::RuntimeException )
{
return m_pImpl->vecAttribute.size();
}
SvXMLAttributeList::SvXMLAttributeList( const SvXMLAttributeList &r )
{
m_pImpl = new SvXMLAttributeList_Impl;
*m_pImpl = *(r.m_pImpl);
}
OUString SAL_CALL SvXMLAttributeList::getNameByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException )
{
if( i < m_pImpl->vecAttribute.size() ) {
return m_pImpl->vecAttribute[i].sName;
}
return OUString();
}
OUString SAL_CALL SvXMLAttributeList::getTypeByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException )
{
return sType;
}
OUString SAL_CALL SvXMLAttributeList::getValueByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException )
{
if( i < m_pImpl->vecAttribute.size() ) {
return m_pImpl->vecAttribute[i].sValue;
}
return OUString();
}
OUString SAL_CALL SvXMLAttributeList::getTypeByName( const OUString& sName ) throw( ::com::sun::star::uno::RuntimeException )
{
return sType;
}
OUString SAL_CALL SvXMLAttributeList::getValueByName(const OUString& sName) throw( ::com::sun::star::uno::RuntimeException )
{
::std::vector<struct SvXMLTagAttribute_Impl>::iterator ii = m_pImpl->vecAttribute.begin();
for( ; ii != m_pImpl->vecAttribute.end() ; ii ++ ) {
if( (*ii).sName == sName ) {
return (*ii).sValue;
}
}
return OUString();
}
uno::Reference< ::com::sun::star::util::XCloneable > SvXMLAttributeList::createClone() throw( ::com::sun::star::uno::RuntimeException )
{
uno::Reference< ::com::sun::star::util::XCloneable > r = new SvXMLAttributeList( *this );
return r;
}
SvXMLAttributeList::SvXMLAttributeList()
: sType( GetXMLToken(XML_CDATA) )
{
m_pImpl = new SvXMLAttributeList_Impl;
}
SvXMLAttributeList::~SvXMLAttributeList()
{
delete m_pImpl;
}
void SvXMLAttributeList::AddAttribute( const OUString &sName ,
const OUString &sValue )
{
m_pImpl->vecAttribute.push_back( SvXMLTagAttribute_Impl( sName , sValue ) );
}
void SvXMLAttributeList::Clear()
{
m_pImpl->vecAttribute.clear();
assert( ! getLength() );
}
void SvXMLAttributeList::RemoveAttribute( const OUString sName )
{
::std::vector<struct SvXMLTagAttribute_Impl>::iterator ii = m_pImpl->vecAttribute.begin();
for( ; ii != m_pImpl->vecAttribute.end() ; ii ++ ) {
if( (*ii).sName == sName ) {
m_pImpl->vecAttribute.erase( ii );
break;
}
}
}
void SvXMLAttributeList::SetAttributeList( const uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &r )
{
Clear();
AppendAttributeList( r );
}
void SvXMLAttributeList::AppendAttributeList( const uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &r )
{
assert( r.is() );
sal_Int32 nMax = r->getLength();
sal_Int32 nTotalSize = m_pImpl->vecAttribute.size() + nMax;
m_pImpl->vecAttribute.reserve( nTotalSize );
for( sal_Int32 i = 0 ; i < nMax ; i ++ ) {
m_pImpl->vecAttribute.push_back( SvXMLTagAttribute_Impl(
r->getNameByIndex( i ) ,
r->getValueByIndex( i )));
}
assert( nTotalSize == getLength());
}
// XUnoTunnel & co
const uno::Sequence< sal_Int8 > & SvXMLAttributeList::getUnoTunnelId() throw()
{
static uno::Sequence< sal_Int8 > * pSeq = 0;
if( !pSeq )
{
Guard< Mutex > aGuard( Mutex::getGlobalMutex() );
if( !pSeq )
{
static uno::Sequence< sal_Int8 > aSeq( 16 );
rtl_createUuid( (sal_uInt8*)aSeq.getArray(), 0, sal_True );
pSeq = &aSeq;
}
}
return *pSeq;
}
SvXMLAttributeList* SvXMLAttributeList::getImplementation( uno::Reference< uno::XInterface > xInt ) throw()
{
uno::Reference< lang::XUnoTunnel > xUT( xInt, uno::UNO_QUERY );
if( xUT.is() )
return (SvXMLAttributeList*)xUT->getSomething( SvXMLAttributeList::getUnoTunnelId() );
else
return NULL;
}
// XUnoTunnel
sal_Int64 SAL_CALL SvXMLAttributeList::getSomething( const uno::Sequence< sal_Int8 >& rId )
throw( uno::RuntimeException )
{
if( rId.getLength() == 16 && 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(),
rId.getConstArray(), 16 ) )
{
return (sal_Int64)this;
}
return 0;
}
<commit_msg>INTEGRATION: CWS dbgmacros1 (1.4.30.1.36); FILE MERGED 2003/04/10 09:32:48 kso 1.4.30.1.36.1: #108413# - debug macro unification.<commit_after>/*************************************************************************
*
* $RCSfile: attrlist.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2003-04-15 16:32:44 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <vector>
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#include <rtl/uuid.h>
#include <rtl/memory.h>
#if OSL_DEBUG_LEVEL == 0
#define NDEBUG
#endif
#include <assert.h>
#include "attrlist.hxx"
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
struct SvXMLTagAttribute_Impl
{
SvXMLTagAttribute_Impl(){}
SvXMLTagAttribute_Impl( const OUString &rName,
const OUString &rValue )
: sName(rName),
sValue(rValue)
{
}
OUString sName;
OUString sValue;
};
struct SvXMLAttributeList_Impl
{
SvXMLAttributeList_Impl()
{
// performance improvement during adding
vecAttribute.reserve(20);
}
::std::vector<struct SvXMLTagAttribute_Impl> vecAttribute;
};
sal_Int16 SAL_CALL SvXMLAttributeList::getLength(void) throw( ::com::sun::star::uno::RuntimeException )
{
return m_pImpl->vecAttribute.size();
}
SvXMLAttributeList::SvXMLAttributeList( const SvXMLAttributeList &r )
{
m_pImpl = new SvXMLAttributeList_Impl;
*m_pImpl = *(r.m_pImpl);
}
OUString SAL_CALL SvXMLAttributeList::getNameByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException )
{
if( i < m_pImpl->vecAttribute.size() ) {
return m_pImpl->vecAttribute[i].sName;
}
return OUString();
}
OUString SAL_CALL SvXMLAttributeList::getTypeByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException )
{
return sType;
}
OUString SAL_CALL SvXMLAttributeList::getValueByIndex(sal_Int16 i) throw( ::com::sun::star::uno::RuntimeException )
{
if( i < m_pImpl->vecAttribute.size() ) {
return m_pImpl->vecAttribute[i].sValue;
}
return OUString();
}
OUString SAL_CALL SvXMLAttributeList::getTypeByName( const OUString& sName ) throw( ::com::sun::star::uno::RuntimeException )
{
return sType;
}
OUString SAL_CALL SvXMLAttributeList::getValueByName(const OUString& sName) throw( ::com::sun::star::uno::RuntimeException )
{
::std::vector<struct SvXMLTagAttribute_Impl>::iterator ii = m_pImpl->vecAttribute.begin();
for( ; ii != m_pImpl->vecAttribute.end() ; ii ++ ) {
if( (*ii).sName == sName ) {
return (*ii).sValue;
}
}
return OUString();
}
uno::Reference< ::com::sun::star::util::XCloneable > SvXMLAttributeList::createClone() throw( ::com::sun::star::uno::RuntimeException )
{
uno::Reference< ::com::sun::star::util::XCloneable > r = new SvXMLAttributeList( *this );
return r;
}
SvXMLAttributeList::SvXMLAttributeList()
: sType( GetXMLToken(XML_CDATA) )
{
m_pImpl = new SvXMLAttributeList_Impl;
}
SvXMLAttributeList::~SvXMLAttributeList()
{
delete m_pImpl;
}
void SvXMLAttributeList::AddAttribute( const OUString &sName ,
const OUString &sValue )
{
m_pImpl->vecAttribute.push_back( SvXMLTagAttribute_Impl( sName , sValue ) );
}
void SvXMLAttributeList::Clear()
{
m_pImpl->vecAttribute.clear();
assert( ! getLength() );
}
void SvXMLAttributeList::RemoveAttribute( const OUString sName )
{
::std::vector<struct SvXMLTagAttribute_Impl>::iterator ii = m_pImpl->vecAttribute.begin();
for( ; ii != m_pImpl->vecAttribute.end() ; ii ++ ) {
if( (*ii).sName == sName ) {
m_pImpl->vecAttribute.erase( ii );
break;
}
}
}
void SvXMLAttributeList::SetAttributeList( const uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &r )
{
Clear();
AppendAttributeList( r );
}
void SvXMLAttributeList::AppendAttributeList( const uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &r )
{
assert( r.is() );
sal_Int32 nMax = r->getLength();
sal_Int32 nTotalSize = m_pImpl->vecAttribute.size() + nMax;
m_pImpl->vecAttribute.reserve( nTotalSize );
for( sal_Int32 i = 0 ; i < nMax ; i ++ ) {
m_pImpl->vecAttribute.push_back( SvXMLTagAttribute_Impl(
r->getNameByIndex( i ) ,
r->getValueByIndex( i )));
}
assert( nTotalSize == getLength());
}
// XUnoTunnel & co
const uno::Sequence< sal_Int8 > & SvXMLAttributeList::getUnoTunnelId() throw()
{
static uno::Sequence< sal_Int8 > * pSeq = 0;
if( !pSeq )
{
Guard< Mutex > aGuard( Mutex::getGlobalMutex() );
if( !pSeq )
{
static uno::Sequence< sal_Int8 > aSeq( 16 );
rtl_createUuid( (sal_uInt8*)aSeq.getArray(), 0, sal_True );
pSeq = &aSeq;
}
}
return *pSeq;
}
SvXMLAttributeList* SvXMLAttributeList::getImplementation( uno::Reference< uno::XInterface > xInt ) throw()
{
uno::Reference< lang::XUnoTunnel > xUT( xInt, uno::UNO_QUERY );
if( xUT.is() )
return (SvXMLAttributeList*)xUT->getSomething( SvXMLAttributeList::getUnoTunnelId() );
else
return NULL;
}
// XUnoTunnel
sal_Int64 SAL_CALL SvXMLAttributeList::getSomething( const uno::Sequence< sal_Int8 >& rId )
throw( uno::RuntimeException )
{
if( rId.getLength() == 16 && 0 == rtl_compareMemory( getUnoTunnelId().getConstArray(),
rId.getConstArray(), 16 ) )
{
return (sal_Int64)this;
}
return 0;
}
<|endoftext|> |
<commit_before>#define WIN32_LEAN_AND_MEAN
#define STRICT
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define _CRTDBG_MAP_ALLOC
#include <windows.h>
#include <atlbase.h>
#include <pathcch.h>
#include <shlwapi.h>
#include <winioctl.h>
#include <algorithm>
#include <clocale>
#include <cstdio>
#include <memory>
#include <crtdbg.h>
#pragma comment(lib, "pathcch")
#pragma comment(lib, "shlwapi")
#pragma comment(lib, "user32")
std::unique_ptr<WCHAR[]> GetWindowsError( ULONG error_code = GetLastError() )
{
auto msg = std::make_unique<WCHAR[]>( USHRT_MAX );
if( FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error_code, 0, msg.get(), USHRT_MAX, nullptr ) )
{
return msg;
}
return nullptr;
}
void PrintWindowsError( ULONG error_code = GetLastError() )
{
if( auto error_msg = GetWindowsError( error_code ) )
{
fprintf( stderr, "%ls\n", error_msg.get() );
}
}
_Success_( return == true )
bool reflink( _In_z_ PCWSTR oldpath, _In_z_ PCWSTR newpath )
{
_ASSERTE( oldpath != nullptr && newpath != nullptr );
ATL::CHandle source{ CreateFileW( oldpath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr ) };
if( source == INVALID_HANDLE_VALUE )
{
source.Detach();
return false;
}
ULONG fs_flags;
if( !GetVolumeInformationByHandleW( source, nullptr, 0, nullptr, nullptr, &fs_flags, nullptr, 0 ) )
{
return false;
}
if( !( fs_flags & FILE_SUPPORTS_BLOCK_REFCOUNTING ) )
{
SetLastError( ERROR_NOT_CAPABLE );
return false;
}
FILE_STANDARD_INFO file_standard;
if( !GetFileInformationByHandleEx( source, FileStandardInfo, &file_standard, sizeof file_standard ) )
{
return false;
}
FILE_BASIC_INFO file_basic;
if( !GetFileInformationByHandleEx( source, FileBasicInfo, &file_basic, sizeof file_basic ) )
{
return false;
}
#ifdef _DEBUG
ATL::CHandle destination{ CreateFileW( newpath, GENERIC_WRITE | DELETE, 0, nullptr, CREATE_ALWAYS, 0, source ) };
#else
ATL::CHandle destination{ CreateFileW( newpath, GENERIC_WRITE | DELETE, 0, nullptr, CREATE_NEW, 0, source ) };
#endif
if( destination == INVALID_HANDLE_VALUE )
{
destination.Detach();
return false;
}
FILE_DISPOSITION_INFO dispose = { TRUE };
if( !SetFileInformationByHandle( destination, FileDispositionInfo, &dispose, sizeof dispose ) )
{
return false;
}
if( file_basic.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE )
{
ULONG dummy;
if( !DeviceIoControl( destination, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &dummy, nullptr ) )
{
return false;
}
}
FILE_END_OF_FILE_INFO end_of_file = { file_standard.EndOfFile };
if( !SetFileInformationByHandle( destination, FileEndOfFileInfo, &end_of_file, sizeof end_of_file ) )
{
return false;
}
const unsigned split_threshold = 2U * 1024 * 1024 * 1024;
auto mount_point = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
if( !GetVolumePathNameW( oldpath, mount_point.get(), PATHCCH_MAX_CCH ) )
{
return false;
}
ULONG sectors_per_cluster, sector_size, junk;
if( !GetDiskFreeSpaceW( mount_point.get(), §ors_per_cluster, §or_size, &junk, &junk ) )
{
return false;
}
ULONG cluster_size = sectors_per_cluster * sector_size;
if( split_threshold % cluster_size != 0 )
{
SetLastError( ERROR_NOT_SUPPORTED );
return false;
}
DUPLICATE_EXTENTS_DATA dup_extent = { source };
for( LONG64 offset = 0, remain = file_standard.AllocationSize.QuadPart; remain > 0; offset += split_threshold, remain -= split_threshold )
{
dup_extent.SourceFileOffset.QuadPart = dup_extent.TargetFileOffset.QuadPart = offset;
dup_extent.ByteCount.QuadPart = std::min<LONG64>( split_threshold, remain );
_ASSERTE( dup_extent.ByteCount.HighPart == 0 );
_RPT3( _CRT_WARN, "r=%llx\no=%llx\nb=%llx\n\n", remain, dup_extent.SourceFileOffset.QuadPart, dup_extent.ByteCount.QuadPart );
ULONG dummy;
if( !DeviceIoControl( destination, FSCTL_DUPLICATE_EXTENTS_TO_FILE, &dup_extent, sizeof dup_extent, nullptr, 0, &dummy, nullptr ) )
{
_CrtDbgBreak();
return false;
}
}
FILETIME atime = { file_basic.LastAccessTime.LowPart, ULONG( file_basic.LastAccessTime.HighPart ) };
FILETIME mtime = { file_basic.LastWriteTime.LowPart, ULONG( file_basic.LastWriteTime.HighPart ) };
SetFileTime( destination, nullptr, &atime, &mtime );
dispose.DeleteFile = FALSE;
return SetFileInformationByHandle( destination, FileDispositionInfo, &dispose, sizeof dispose ) != 0;
}
int __cdecl wmain( int argc, PWSTR argv[] )
{
_CrtSetDbgFlag( _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ) | _CRTDBG_LEAK_CHECK_DF );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE );
setlocale( LC_ALL, "" );
if( argc != 3 )
{
fprintf(
stderr,
"Copy file without actual data write.\n"
"\n"
"%ls source destination\n"
"\n"
"source Specifies a file to copy.\n"
" source must have placed on the ReFS volume.\n"
"destination Specifies new file name.\n"
" destination must have placed on the same volume as source.\n",
PathFindFileNameW( argv[0] )
);
return EXIT_FAILURE;
}
auto source = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
auto destination = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
if( FAILED( PathCchCanonicalizeEx( source.get(), PATHCCH_MAX_CCH, argv[1], PATHCCH_ALLOW_LONG_PATHS ) )
|| FAILED( PathCchCanonicalizeEx( destination.get(), PATHCCH_MAX_CCH, argv[2], PATHCCH_ALLOW_LONG_PATHS ) ) )
{
PrintWindowsError();
return EXIT_FAILURE;
}
if( !reflink( source.get(), destination.get() ) )
{
PrintWindowsError();
return EXIT_FAILURE;
}
}<commit_msg>Try whole before split<commit_after>#define WIN32_LEAN_AND_MEAN
#define STRICT
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define _CRTDBG_MAP_ALLOC
#include <windows.h>
#include <atlbase.h>
#include <pathcch.h>
#include <shlwapi.h>
#include <winioctl.h>
#include <algorithm>
#include <clocale>
#include <cstdio>
#include <memory>
#include <crtdbg.h>
#pragma comment(lib, "pathcch")
#pragma comment(lib, "shlwapi")
#pragma comment(lib, "user32")
std::unique_ptr<WCHAR[]> GetWindowsError( ULONG error_code = GetLastError() )
{
auto msg = std::make_unique<WCHAR[]>( USHRT_MAX );
if( FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error_code, 0, msg.get(), USHRT_MAX, nullptr ) )
{
return msg;
}
return nullptr;
}
void PrintWindowsError( ULONG error_code = GetLastError() )
{
if( auto error_msg = GetWindowsError( error_code ) )
{
fprintf( stderr, "%ls\n", error_msg.get() );
}
}
_Success_( return == true )
bool reflink( _In_z_ PCWSTR oldpath, _In_z_ PCWSTR newpath )
{
_ASSERTE( oldpath != nullptr && newpath != nullptr );
ATL::CHandle source{ CreateFileW( oldpath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr ) };
if( source == INVALID_HANDLE_VALUE )
{
source.Detach();
return false;
}
ULONG fs_flags;
if( !GetVolumeInformationByHandleW( source, nullptr, 0, nullptr, nullptr, &fs_flags, nullptr, 0 ) )
{
return false;
}
if( !( fs_flags & FILE_SUPPORTS_BLOCK_REFCOUNTING ) )
{
SetLastError( ERROR_NOT_CAPABLE );
return false;
}
FILE_STANDARD_INFO file_standard;
if( !GetFileInformationByHandleEx( source, FileStandardInfo, &file_standard, sizeof file_standard ) )
{
return false;
}
FILE_BASIC_INFO file_basic;
if( !GetFileInformationByHandleEx( source, FileBasicInfo, &file_basic, sizeof file_basic ) )
{
return false;
}
#ifdef _DEBUG
ATL::CHandle destination{ CreateFileW( newpath, GENERIC_WRITE | DELETE, 0, nullptr, CREATE_ALWAYS, 0, source ) };
#else
ATL::CHandle destination{ CreateFileW( newpath, GENERIC_WRITE | DELETE, 0, nullptr, CREATE_NEW, 0, source ) };
#endif
if( destination == INVALID_HANDLE_VALUE )
{
destination.Detach();
return false;
}
FILE_DISPOSITION_INFO dispose = { TRUE };
if( !SetFileInformationByHandle( destination, FileDispositionInfo, &dispose, sizeof dispose ) )
{
return false;
}
if( file_basic.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE )
{
ULONG dummy;
if( !DeviceIoControl( destination, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &dummy, nullptr ) )
{
return false;
}
}
FILE_END_OF_FILE_INFO end_of_file = { file_standard.EndOfFile };
if( !SetFileInformationByHandle( destination, FileEndOfFileInfo, &end_of_file, sizeof end_of_file ) )
{
return false;
}
_RPT0( _CRT_WARN, "Try 1st\n" );
DUPLICATE_EXTENTS_DATA dup_extent = { source, { 0 }, { 0 }, file_standard.AllocationSize };
_ASSERTE( dup_extent.SourceFileOffset.QuadPart == 0 );
_ASSERTE( dup_extent.TargetFileOffset.QuadPart == 0 );
ULONG dummy;
if( !DeviceIoControl( destination, FSCTL_DUPLICATE_EXTENTS_TO_FILE, &dup_extent, sizeof dup_extent, nullptr, 0, &dummy, nullptr ) )
{
if( GetLastError() != ERROR_ARITHMETIC_OVERFLOW )
{
_CrtDbgBreak();
return false;
}
_RPT0( _CRT_WARN, "Try 2nd\n" );
const unsigned split_threshold = 2U * 1024 * 1024 * 1024;
auto mount_point = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
if( !GetVolumePathNameW( oldpath, mount_point.get(), PATHCCH_MAX_CCH ) )
{
return false;
}
ULONG sectors_per_cluster, sector_size, junk;
if( !GetDiskFreeSpaceW( mount_point.get(), §ors_per_cluster, §or_size, &junk, &junk ) )
{
return false;
}
if( split_threshold % ( sectors_per_cluster * sector_size ) != 0 )
{
SetLastError( ERROR_NOT_SUPPORTED );
return false;
}
for( LONG64 offset = 0, remain = file_standard.AllocationSize.QuadPart; remain > 0; offset += split_threshold, remain -= split_threshold )
{
dup_extent.SourceFileOffset.QuadPart = dup_extent.TargetFileOffset.QuadPart = offset;
dup_extent.ByteCount.QuadPart = std::min<LONG64>( split_threshold, remain );
_ASSERTE( dup_extent.ByteCount.QuadPart <= UINT32_MAX );
_RPT3( _CRT_WARN, "r=%llx\no=%llx\nb=%llx\n\n", remain, dup_extent.SourceFileOffset.QuadPart, dup_extent.ByteCount.QuadPart );
if( !DeviceIoControl( destination, FSCTL_DUPLICATE_EXTENTS_TO_FILE, &dup_extent, sizeof dup_extent, nullptr, 0, &dummy, nullptr ) )
{
_CrtDbgBreak();
return false;
}
}
}
FILETIME atime = { file_basic.LastAccessTime.LowPart, ULONG( file_basic.LastAccessTime.HighPart ) };
FILETIME mtime = { file_basic.LastWriteTime.LowPart, ULONG( file_basic.LastWriteTime.HighPart ) };
SetFileTime( destination, nullptr, &atime, &mtime );
dispose.DeleteFile = FALSE;
return SetFileInformationByHandle( destination, FileDispositionInfo, &dispose, sizeof dispose ) != 0;
}
int __cdecl wmain( int argc, PWSTR argv[] )
{
_CrtSetDbgFlag( _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ) | _CRTDBG_LEAK_CHECK_DF );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE );
setlocale( LC_ALL, "" );
if( argc != 3 )
{
fprintf(
stderr,
"Copy file without actual data write.\n"
"\n"
"%ls source destination\n"
"\n"
"source Specifies a file to copy.\n"
" source must have placed on the ReFS volume.\n"
"destination Specifies new file name.\n"
" destination must have placed on the same volume as source.\n",
PathFindFileNameW( argv[0] )
);
return EXIT_FAILURE;
}
auto source = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
auto destination = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
if( FAILED( PathCchCanonicalizeEx( source.get(), PATHCCH_MAX_CCH, argv[1], PATHCCH_ALLOW_LONG_PATHS ) )
|| FAILED( PathCchCanonicalizeEx( destination.get(), PATHCCH_MAX_CCH, argv[2], PATHCCH_ALLOW_LONG_PATHS ) ) )
{
PrintWindowsError();
return EXIT_FAILURE;
}
if( !reflink( source.get(), destination.get() ) )
{
PrintWindowsError();
return EXIT_FAILURE;
}
}<|endoftext|> |
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file gaussian_test.cpp
* \date October 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#include <gtest/gtest.h>
#include "../typecast.hpp"
#include <Eigen/Dense>
#include <cmath>
#include <iostream>
#include <fl/distribution/decorrelated_gaussian.hpp>
template <typename TestType>
class DecorrelatedGaussianTests
: public testing::Test
{
public:
typedef typename TestType::Parameter Configuration;
enum: signed int
{
Dim = Configuration::Dim,
Size = fl::TestSize<Dim, TestType>::Value
};
typedef Eigen::Matrix<fl::Real, Size, 1> Vector;
protected:
template <typename Gaussian>
void test_gaussian_covariance(Gaussian& gaussian)
{
typedef typename Gaussian::SecondMoment SecondMoment;
SecondMoment covariance;
SecondMoment square_root;
SecondMoment precision;
covariance.setIdentity(Dim);
precision.setIdentity(Dim);
square_root.setIdentity(Dim);
// first verify standard gaussian
{
SCOPED_TRACE("Unchanged");
test_gaussian_attributes(
gaussian, covariance, precision, square_root);
}
// set covariance and verify representations
{
SCOPED_TRACE("Covariance setter");
covariance.diagonal().setRandom(Dim);
covariance.diagonal() = covariance.diagonal().cwiseProduct(
covariance.diagonal());
square_root.diagonal() = covariance.diagonal().cwiseSqrt();
precision.diagonal() = covariance.diagonal().cwiseInverse();
gaussian.covariance(covariance);
test_gaussian_attributes(
gaussian, covariance, precision, square_root);
}
// set square root and verify representations
{
SCOPED_TRACE("SquareRoot setter");
covariance.diagonal().setRandom(Dim);
covariance.diagonal() = covariance.diagonal().cwiseProduct(
covariance.diagonal());
square_root.diagonal() = covariance.diagonal().cwiseSqrt();
precision.diagonal() = covariance.diagonal().cwiseInverse();
gaussian.square_root(square_root);
test_gaussian_attributes(
gaussian, covariance, precision, square_root);
}
// set covariance and verify representations
{
SCOPED_TRACE("Precision setter");
covariance.diagonal().setRandom(Dim);
covariance.diagonal() = covariance.diagonal().cwiseProduct(
covariance.diagonal());
square_root.diagonal() = covariance.diagonal().cwiseSqrt();
precision.diagonal() = covariance.diagonal().cwiseInverse();
gaussian.precision(precision);
test_gaussian_attributes(
gaussian, covariance, precision, square_root);
}
}
template <typename Gaussian, typename Covariance>
void test_gaussian_attributes(Gaussian& gaussian,
const Covariance& covariance,
const Covariance& precision,
const Covariance& square_root)
{
EXPECT_GT(gaussian.dimension(), 0);
EXPECT_TRUE(
fl::are_similar(gaussian.covariance().diagonal(),
covariance.diagonal()));
EXPECT_TRUE(
fl::are_similar(gaussian.precision().diagonal(),
precision.diagonal()));
EXPECT_TRUE(
fl::are_similar(gaussian.square_root().diagonal(),
square_root.diagonal()));
EXPECT_TRUE(gaussian.has_full_rank());
}
};
TYPED_TEST_CASE_P(DecorrelatedGaussianTests);
TYPED_TEST_P(DecorrelatedGaussianTests, dimension)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
auto gaussian = Gaussian(This::Dim);
EXPECT_EQ(gaussian.dimension(), This::Dim);
EXPECT_EQ(gaussian.standard_variate_dimension(), This::Dim);
EXPECT_EQ(gaussian.mean().size(), This::Dim);
EXPECT_EQ(gaussian.covariance().rows(), This::Dim);
EXPECT_EQ(gaussian.precision().rows(), This::Dim);
EXPECT_EQ(gaussian.square_root().rows(), This::Dim);
auto noise = Gaussian::StandardVariate::Random(
gaussian.standard_variate_dimension(), 1).eval();
EXPECT_EQ(gaussian.map_standard_normal(noise).size(), This::Dim);
}
TYPED_TEST_P(DecorrelatedGaussianTests, standard_covariance)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
auto gaussian = Gaussian(This::Dim);
test_gaussian_covariance(gaussian);
}
TYPED_TEST_P(DecorrelatedGaussianTests, dynamic_uninitialized_gaussian)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
typedef typename Gaussian::SecondMoment SecondMoment;
auto gaussian = Gaussian();
if (This::Size != Eigen::Dynamic)
{
EXPECT_NO_THROW(gaussian.covariance());
EXPECT_NO_THROW(gaussian.precision());
EXPECT_NO_THROW(gaussian.square_root());
}
else
{
EXPECT_THROW(gaussian.covariance(), fl::GaussianUninitializedException);
EXPECT_THROW(gaussian.precision(), fl::GaussianUninitializedException);
EXPECT_THROW(gaussian.square_root(), fl::GaussianUninitializedException);
gaussian.dimension(1);
EXPECT_NO_THROW(gaussian.covariance());
EXPECT_NO_THROW(gaussian.precision());
EXPECT_NO_THROW(gaussian.square_root());
gaussian.dimension(0);
EXPECT_THROW(gaussian.covariance(), fl::GaussianUninitializedException);
EXPECT_THROW(gaussian.precision(), fl::GaussianUninitializedException);
EXPECT_THROW(gaussian.square_root(), fl::GaussianUninitializedException);
}
}
TYPED_TEST_P(DecorrelatedGaussianTests, gaussian_covariance_dimension_init)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
typedef typename Gaussian::SecondMoment SecondMoment;
auto gaussian = Gaussian();
gaussian.dimension(This::Dim);
EXPECT_NO_THROW(test_gaussian_covariance(gaussian));
}
TYPED_TEST_P(DecorrelatedGaussianTests, gaussian_covariance_constructor_init)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
typedef typename Gaussian::SecondMoment SecondMoment;
auto gaussian = Gaussian(This::Dim);
EXPECT_NO_THROW(test_gaussian_covariance(gaussian));
}
REGISTER_TYPED_TEST_CASE_P(DecorrelatedGaussianTests,
dimension,
standard_covariance,
dynamic_uninitialized_gaussian,
gaussian_covariance_dimension_init,
gaussian_covariance_constructor_init);
template <int Dimension>
struct TestConfiguration
{
enum: signed int { Dim = Dimension };
};
typedef ::testing::Types<
fl::StaticTest<TestConfiguration<2>>,
fl::StaticTest<TestConfiguration<3>>,
fl::StaticTest<TestConfiguration<10>>,
fl::StaticTest<TestConfiguration<100>>,
fl::StaticTest<TestConfiguration<1000>>,
fl::StaticTest<TestConfiguration<10000>>,
fl::DynamicTest<TestConfiguration<2>>,
fl::DynamicTest<TestConfiguration<3>>,
fl::DynamicTest<TestConfiguration<10>>,
fl::DynamicTest<TestConfiguration<100>>,
fl::DynamicTest<TestConfiguration<1000>>,
fl::DynamicTest<TestConfiguration<10000>>,
fl::DynamicTest<TestConfiguration<100000>>,
fl::DynamicTest<TestConfiguration<1000000>>,
fl::DynamicTest<TestConfiguration<10000000>>
> TestTypes;
INSTANTIATE_TYPED_TEST_CASE_P(DecorrelatedGaussianTestCases,
DecorrelatedGaussianTests,
TestTypes);
<commit_msg>ADL fix<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file gaussian_test.cpp
* \date October 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#include <gtest/gtest.h>
#include "../typecast.hpp"
#include <Eigen/Dense>
#include <cmath>
#include <iostream>
#include <fl/distribution/decorrelated_gaussian.hpp>
template <typename TestType>
class DecorrelatedGaussianTests
: public testing::Test
{
public:
typedef typename TestType::Parameter Configuration;
enum: signed int
{
Dim = Configuration::Dim,
Size = fl::TestSize<Dim, TestType>::Value
};
typedef Eigen::Matrix<fl::Real, Size, 1> Vector;
protected:
template <typename Gaussian, typename Covariance>
void test_gaussian_attributes(Gaussian& gaussian,
const Covariance& covariance,
const Covariance& precision,
const Covariance& square_root)
{
EXPECT_GT(gaussian.dimension(), 0);
EXPECT_TRUE(
fl::are_similar(gaussian.covariance().diagonal(),
covariance.diagonal()));
EXPECT_TRUE(
fl::are_similar(gaussian.precision().diagonal(),
precision.diagonal()));
EXPECT_TRUE(
fl::are_similar(gaussian.square_root().diagonal(),
square_root.diagonal()));
EXPECT_TRUE(gaussian.has_full_rank());
}
template <typename Gaussian>
void test_gaussian_covariance(Gaussian& gaussian)
{
typedef typename Gaussian::SecondMoment SecondMoment;
SecondMoment covariance;
SecondMoment square_root;
SecondMoment precision;
covariance.setIdentity(Dim);
precision.setIdentity(Dim);
square_root.setIdentity(Dim);
// first verify standard gaussian
{
SCOPED_TRACE("Unchanged");
test_gaussian_attributes(
gaussian, covariance, precision, square_root);
}
// set covariance and verify representations
{
SCOPED_TRACE("Covariance setter");
covariance.diagonal().setRandom(Dim);
covariance.diagonal() = covariance.diagonal().cwiseProduct(
covariance.diagonal());
square_root.diagonal() = covariance.diagonal().cwiseSqrt();
precision.diagonal() = covariance.diagonal().cwiseInverse();
gaussian.covariance(covariance);
test_gaussian_attributes(
gaussian, covariance, precision, square_root);
}
// set square root and verify representations
{
SCOPED_TRACE("SquareRoot setter");
covariance.diagonal().setRandom(Dim);
covariance.diagonal() = covariance.diagonal().cwiseProduct(
covariance.diagonal());
square_root.diagonal() = covariance.diagonal().cwiseSqrt();
precision.diagonal() = covariance.diagonal().cwiseInverse();
gaussian.square_root(square_root);
test_gaussian_attributes(
gaussian, covariance, precision, square_root);
}
// set covariance and verify representations
{
SCOPED_TRACE("Precision setter");
covariance.diagonal().setRandom(Dim);
covariance.diagonal() = covariance.diagonal().cwiseProduct(
covariance.diagonal());
square_root.diagonal() = covariance.diagonal().cwiseSqrt();
precision.diagonal() = covariance.diagonal().cwiseInverse();
gaussian.precision(precision);
test_gaussian_attributes(
gaussian, covariance, precision, square_root);
}
}
};
TYPED_TEST_CASE_P(DecorrelatedGaussianTests);
TYPED_TEST_P(DecorrelatedGaussianTests, dimension)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
auto gaussian = Gaussian(This::Dim);
EXPECT_EQ(gaussian.dimension(), This::Dim);
EXPECT_EQ(gaussian.standard_variate_dimension(), This::Dim);
EXPECT_EQ(gaussian.mean().size(), This::Dim);
EXPECT_EQ(gaussian.covariance().rows(), This::Dim);
EXPECT_EQ(gaussian.precision().rows(), This::Dim);
EXPECT_EQ(gaussian.square_root().rows(), This::Dim);
auto noise = Gaussian::StandardVariate::Random(
gaussian.standard_variate_dimension(), 1).eval();
EXPECT_EQ(gaussian.map_standard_normal(noise).size(), This::Dim);
}
TYPED_TEST_P(DecorrelatedGaussianTests, standard_covariance)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
auto gaussian = Gaussian(This::Dim);
test_gaussian_covariance(gaussian);
}
TYPED_TEST_P(DecorrelatedGaussianTests, dynamic_uninitialized_gaussian)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
typedef typename Gaussian::SecondMoment SecondMoment;
auto gaussian = Gaussian();
if (This::Size != Eigen::Dynamic)
{
EXPECT_NO_THROW(gaussian.covariance());
EXPECT_NO_THROW(gaussian.precision());
EXPECT_NO_THROW(gaussian.square_root());
}
else
{
EXPECT_THROW(gaussian.covariance(), fl::GaussianUninitializedException);
EXPECT_THROW(gaussian.precision(), fl::GaussianUninitializedException);
EXPECT_THROW(gaussian.square_root(), fl::GaussianUninitializedException);
gaussian.dimension(1);
EXPECT_NO_THROW(gaussian.covariance());
EXPECT_NO_THROW(gaussian.precision());
EXPECT_NO_THROW(gaussian.square_root());
gaussian.dimension(0);
EXPECT_THROW(gaussian.covariance(), fl::GaussianUninitializedException);
EXPECT_THROW(gaussian.precision(), fl::GaussianUninitializedException);
EXPECT_THROW(gaussian.square_root(), fl::GaussianUninitializedException);
}
}
TYPED_TEST_P(DecorrelatedGaussianTests, gaussian_covariance_dimension_init)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
typedef typename Gaussian::SecondMoment SecondMoment;
auto gaussian = Gaussian();
gaussian.dimension(This::Dim);
EXPECT_NO_THROW(test_gaussian_covariance(gaussian));
}
TYPED_TEST_P(DecorrelatedGaussianTests, gaussian_covariance_constructor_init)
{
typedef TestFixture This;
typedef fl::DecorrelatedGaussian<typename This::Vector> Gaussian;
typedef typename Gaussian::SecondMoment SecondMoment;
auto gaussian = Gaussian(This::Dim);
EXPECT_NO_THROW(test_gaussian_covariance(gaussian));
}
REGISTER_TYPED_TEST_CASE_P(DecorrelatedGaussianTests,
dimension,
standard_covariance,
dynamic_uninitialized_gaussian,
gaussian_covariance_dimension_init,
gaussian_covariance_constructor_init);
template <int Dimension>
struct TestConfiguration
{
enum: signed int { Dim = Dimension };
};
typedef ::testing::Types<
fl::StaticTest<TestConfiguration<2>>,
fl::StaticTest<TestConfiguration<3>>,
fl::StaticTest<TestConfiguration<10>>,
fl::StaticTest<TestConfiguration<100>>,
fl::StaticTest<TestConfiguration<1000>>,
fl::StaticTest<TestConfiguration<10000>>,
fl::DynamicTest<TestConfiguration<2>>,
fl::DynamicTest<TestConfiguration<3>>,
fl::DynamicTest<TestConfiguration<10>>,
fl::DynamicTest<TestConfiguration<100>>,
fl::DynamicTest<TestConfiguration<1000>>,
fl::DynamicTest<TestConfiguration<10000>>,
fl::DynamicTest<TestConfiguration<100000>>,
fl::DynamicTest<TestConfiguration<1000000>>,
fl::DynamicTest<TestConfiguration<10000000>>
> TestTypes;
INSTANTIATE_TYPED_TEST_CASE_P(DecorrelatedGaussianTestCases,
DecorrelatedGaussianTests,
TestTypes);
<|endoftext|> |
<commit_before>#include <fstream>
#include <chdl/chdl.h>
#include <chdl/cassign.h>
#include "config.h"
#include "interfaces.h"
#include "harpinst.h"
using namespace std;
using namespace chdl;
void PredRegs(pred_reg_t &out, fetch_pred_t &in, splitter_pred_t &wb);
void GpRegs(reg_func_t &out, pred_reg_t &in, splitter_reg_t &wb);
void PredRegs(pred_reg_t &out, fetch_pred_t &in, splitter_pred_t &wb) {
HIERARCHY_ENTER();
harpinst<N, RR, RR> inst(_(_(in, "contents"), "ir"));
bvec<WW> wid(_(_(_(in, "contents"), "warp"), "id")),
wb_wid(_(_(wb, "contents"), "wid"));
bvec<WW + RR> a_ipred(Cat(wid, inst.get_pred())),
a_src0 (Cat(wid, inst.get_psrc0())),
a_src1 (Cat(wid, inst.get_psrc1())),
a_wb (Cat(wb_wid, _(_(wb, "contents"), "dest")));
bvec<L> wb_mask(_(_(wb, "contents"), "mask") & bvec<L>(_(wb, "valid"))),
wb_val(_(_(wb, "contents"), "val"));
vec<3, bvec<WW + RR> > rd_addr;
rd_addr[0] = a_ipred;
rd_addr[1] = a_src0;
rd_addr[2] = a_src1;
vec<L, vec<3, bvec<1> > > q;
if (SRAM_REGS) {
for (unsigned i = 0; i < L; ++i)
q[i] = Syncmem(rd_addr, bvec<1>(wb_val[i]), a_wb, wb_mask[i]);
} else {
vec<L, bvec<W*R> > pregs;
for (unsigned l = 0; l < L; ++l) {
for (unsigned w = 0; w < W; ++w) {
for (unsigned r = 0; r < R; ++r) {
node wr(wb_mask[l] && a_wb == Lit<WW + RR>(w*R + r));
pregs[l][w*R + r] = Wreg(wr, wb_val[l]);
ostringstream oss;
oss << "preg" << '_' << w << '_' << l << '_' << r;
tap(oss.str(), pregs[l][w*R + r]);
}
}
q[l][0] = Reg(Mux(rd_addr[0], pregs[l]));
q[l][1] = Reg(Mux(rd_addr[1], pregs[l]));
q[l][2] = Reg(Mux(rd_addr[2], pregs[l]));
}
}
bvec<L> pval0, pval1, pmask;
for (unsigned i = 0; i < L; ++i) {
pmask[i] = q[i][0][0];
pval0[i] = q[i][1][0];
pval1[i] = q[i][2][0];
}
_(wb, "ready") = Lit(1); // Always ready to accept writebacks.
tap("pred_wb_wid", _(_(wb, "contents"), "wid"));
// Handle ready and valid signals
node ready(_(out, "ready"));
_(in, "ready") = ready;
_(out, "valid") = Wreg(ready, _(in, "valid"));
_(_(out, "contents"), "warp") = Wreg(ready, _(_(in, "contents"), "warp"));
_(_(out, "contents"), "ir") = Wreg(ready, _(_(in, "contents"), "ir"));
// The mask should be all 1s if the instruction is not predicated.
_(_(_(out, "contents"), "pval"), "pmask")
= Latch(!ready, pmask | bvec<L>(Reg(!inst.has_pred())));
_(_(_(out, "contents"), "pval"), "val0") = Latch(!ready, pval0);
_(_(_(out, "contents"), "pval"), "val1") = Latch(!ready, pval1);
HIERARCHY_EXIT();
}
void GpRegs(reg_func_t &out_buffered, pred_reg_t &in, splitter_reg_t &wb) {
HIERARCHY_ENTER();
reg_func_t out;
harpinst<N, RR, RR> inst(_(_(in, "contents"), "ir"));
bvec<RR> wb_dest(_(_(wb, "contents"), "dest"));
bvec<WW> wid(_(_(_(in, "contents"), "warp"), "id")),
wb_wid(_(_(wb, "contents"), "wid"));
bvec<LL> wb_clonesrc(_(_(wb, "contents"), "clonesrc")),
wb_clonedest(_(_(wb, "contents"), "clonedest"));
vec<L, bvec<N> > wb_val(_(_(wb, "contents"), "val"));
bvec<L> wbMask(_(_(wb, "contents"), "mask"));
vec<R, bvec<N> > clonebus;
_(wb, "ready") = Lit(1); // Always ready to accept writebacks.
vec<L, bvec<N> > rval0, rval1, rval2;
node clone(_(wb, "valid") && _(_(wb, "contents"), "clone"));
bvec<L> wb_mask(_(_(wb, "contents"), "mask") &
bvec<L>(_(wb, "valid") && !clone));
vec<L, vec<R, vec<2, bvec<N> > > > q;
vec<2, bvec<WW> > a;
a[0] = wid;
a[1] = wb_wid;
for (unsigned l = 0; l < L; ++l) {
for (unsigned i = 0; i < R; ++i) {
node wr(wb_mask[l] && wb_dest == Lit<RR>(i) ||
wb_clonedest == Lit<LL>(l) && clone);
if (SRAM_REGS) {
q[l][i] = Syncmem(a, Mux(Reg(clone), Reg(wb_val[l]), clonebus[i]), Reg(wb_wid), Reg(wr));
} else {
vec<W, bvec<N> > regs;
for (unsigned w = 0; w < W; ++w) {
unsigned initialVal(0);
if (i == 0) initialVal = l;
if (i == 1) initialVal = w;
regs[w] = Wreg(
Reg(wr && wb_wid == Lit<WW>(w)),
Mux(Reg(clone), Reg(wb_val[l]), clonebus[i]),
initialVal
);
ostringstream rname;
rname << "reg_" << w << '_' << l << '_' << i;
tap(rname.str(), regs[w]);
}
q[l][i][0] = Reg(Mux(a[0], regs));
q[l][i][1] = Reg(Mux(a[1], regs));
}
}
}
for (unsigned i = 0; i < R; ++i) {
vec<L, bvec<N> > cb_slice;
for (unsigned l = 0; l < L; ++l)
cb_slice[l] = q[l][i][1];
clonebus[i] = Mux(Reg(wb_clonesrc), cb_slice);
}
for (unsigned l = 0; l < L; ++l) {
rval0[l] = Mux(Reg(inst.get_rsrc0()), q[l])[0];
rval1[l] = Mux(Reg(inst.get_rsrc1()), q[l])[0];
rval2[l] = Mux(Reg(inst.get_rsrc2()), q[l])[0];
}
TAP(rval0);
TAP(rval1);
TAP(rval2);
TAP(wb_wid);
node ready(_(out, "ready"));
_(in, "ready") = ready;
_(out, "valid") = Wreg(ready, _(in, "valid"));
_(_(out, "contents"), "warp") = Wreg(ready, _(_(in, "contents"), "warp"));
_(_(out, "contents"), "ir") = Wreg(ready, _(_(in, "contents"), "ir"));
_(_(out, "contents"), "pval") = Wreg(ready, _(_(in, "contents"), "pval"));
Flatten(_(_(_(out,"contents"),"rval"),"val0")) =
Latch(Reg(!ready),Flatten(rval0));
Flatten(_(_(_(out,"contents"),"rval"),"val1")) =
Latch(Reg(!ready),Flatten(rval1));
Flatten(_(_(_(out,"contents"),"rval"),"val2")) =
Latch(Reg(!ready),Flatten(rval2));
Buffer<1>(out_buffered, out);
HIERARCHY_EXIT();
}
<commit_msg>Only latch if the output _was_ not-ready in the previous cycle.<commit_after>#include <fstream>
#include <chdl/chdl.h>
#include <chdl/cassign.h>
#include "config.h"
#include "interfaces.h"
#include "harpinst.h"
using namespace std;
using namespace chdl;
void PredRegs(pred_reg_t &out, fetch_pred_t &in, splitter_pred_t &wb);
void GpRegs(reg_func_t &out, pred_reg_t &in, splitter_reg_t &wb);
void PredRegs(pred_reg_t &out, fetch_pred_t &in, splitter_pred_t &wb) {
HIERARCHY_ENTER();
harpinst<N, RR, RR> inst(_(_(in, "contents"), "ir"));
bvec<WW> wid(_(_(_(in, "contents"), "warp"), "id")),
wb_wid(_(_(wb, "contents"), "wid"));
bvec<WW + RR> a_ipred(Cat(wid, inst.get_pred())),
a_src0 (Cat(wid, inst.get_psrc0())),
a_src1 (Cat(wid, inst.get_psrc1())),
a_wb (Cat(wb_wid, _(_(wb, "contents"), "dest")));
bvec<L> wb_mask(_(_(wb, "contents"), "mask") & bvec<L>(_(wb, "valid"))),
wb_val(_(_(wb, "contents"), "val"));
vec<3, bvec<WW + RR> > rd_addr;
rd_addr[0] = a_ipred;
rd_addr[1] = a_src0;
rd_addr[2] = a_src1;
vec<L, vec<3, bvec<1> > > q;
if (SRAM_REGS) {
for (unsigned i = 0; i < L; ++i)
q[i] = Syncmem(rd_addr, bvec<1>(wb_val[i]), a_wb, wb_mask[i]);
} else {
vec<L, bvec<W*R> > pregs;
for (unsigned l = 0; l < L; ++l) {
for (unsigned w = 0; w < W; ++w) {
for (unsigned r = 0; r < R; ++r) {
node wr(wb_mask[l] && a_wb == Lit<WW + RR>(w*R + r));
pregs[l][w*R + r] = Wreg(wr, wb_val[l]);
ostringstream oss;
oss << "preg" << '_' << w << '_' << l << '_' << r;
tap(oss.str(), pregs[l][w*R + r]);
}
}
q[l][0] = Reg(Mux(rd_addr[0], pregs[l]));
q[l][1] = Reg(Mux(rd_addr[1], pregs[l]));
q[l][2] = Reg(Mux(rd_addr[2], pregs[l]));
}
}
bvec<L> pval0, pval1, pmask;
for (unsigned i = 0; i < L; ++i) {
pmask[i] = q[i][0][0];
pval0[i] = q[i][1][0];
pval1[i] = q[i][2][0];
}
_(wb, "ready") = Lit(1); // Always ready to accept writebacks.
tap("pred_wb_wid", _(_(wb, "contents"), "wid"));
// Handle ready and valid signals
node ready(_(out, "ready"));
_(in, "ready") = ready;
_(out, "valid") = Wreg(ready, _(in, "valid"));
_(_(out, "contents"), "warp") = Wreg(ready, _(_(in, "contents"), "warp"));
_(_(out, "contents"), "ir") = Wreg(ready, _(_(in, "contents"), "ir"));
// The mask should be all 1s if the instruction is not predicated.
_(_(_(out, "contents"), "pval"), "pmask")
= Latch(Reg(!ready), pmask | bvec<L>(Reg(!inst.has_pred())));
_(_(_(out, "contents"), "pval"), "val0") = Latch(Reg(!ready), pval0);
_(_(_(out, "contents"), "pval"), "val1") = Latch(Reg(!ready), pval1);
HIERARCHY_EXIT();
}
void GpRegs(reg_func_t &out_buffered, pred_reg_t &in, splitter_reg_t &wb) {
HIERARCHY_ENTER();
reg_func_t out;
harpinst<N, RR, RR> inst(_(_(in, "contents"), "ir"));
bvec<RR> wb_dest(_(_(wb, "contents"), "dest"));
bvec<WW> wid(_(_(_(in, "contents"), "warp"), "id")),
wb_wid(_(_(wb, "contents"), "wid"));
bvec<LL> wb_clonesrc(_(_(wb, "contents"), "clonesrc")),
wb_clonedest(_(_(wb, "contents"), "clonedest"));
vec<L, bvec<N> > wb_val(_(_(wb, "contents"), "val"));
bvec<L> wbMask(_(_(wb, "contents"), "mask"));
vec<R, bvec<N> > clonebus;
_(wb, "ready") = Lit(1); // Always ready to accept writebacks.
vec<L, bvec<N> > rval0, rval1, rval2;
node clone(_(wb, "valid") && _(_(wb, "contents"), "clone"));
bvec<L> wb_mask(_(_(wb, "contents"), "mask") &
bvec<L>(_(wb, "valid") && !clone));
vec<L, vec<R, vec<2, bvec<N> > > > q;
vec<2, bvec<WW> > a;
a[0] = wid;
a[1] = wb_wid;
for (unsigned l = 0; l < L; ++l) {
for (unsigned i = 0; i < R; ++i) {
node wr(wb_mask[l] && wb_dest == Lit<RR>(i) ||
wb_clonedest == Lit<LL>(l) && clone);
if (SRAM_REGS) {
q[l][i] = Syncmem(a, Mux(Reg(clone), Reg(wb_val[l]), clonebus[i]), Reg(wb_wid), Reg(wr));
} else {
vec<W, bvec<N> > regs;
for (unsigned w = 0; w < W; ++w) {
unsigned initialVal(0);
if (i == 0) initialVal = l;
if (i == 1) initialVal = w;
regs[w] = Wreg(
Reg(wr && wb_wid == Lit<WW>(w)),
Mux(Reg(clone), Reg(wb_val[l]), clonebus[i]),
initialVal
);
ostringstream rname;
rname << "reg_" << w << '_' << l << '_' << i;
tap(rname.str(), regs[w]);
}
q[l][i][0] = Reg(Mux(a[0], regs));
q[l][i][1] = Reg(Mux(a[1], regs));
}
}
}
for (unsigned i = 0; i < R; ++i) {
vec<L, bvec<N> > cb_slice;
for (unsigned l = 0; l < L; ++l)
cb_slice[l] = q[l][i][1];
clonebus[i] = Mux(Reg(wb_clonesrc), cb_slice);
}
for (unsigned l = 0; l < L; ++l) {
rval0[l] = Mux(Reg(inst.get_rsrc0()), q[l])[0];
rval1[l] = Mux(Reg(inst.get_rsrc1()), q[l])[0];
rval2[l] = Mux(Reg(inst.get_rsrc2()), q[l])[0];
}
TAP(rval0);
TAP(rval1);
TAP(rval2);
TAP(wb_wid);
node ready(_(out, "ready"));
_(in, "ready") = ready;
_(out, "valid") = Wreg(ready, _(in, "valid"));
_(_(out, "contents"), "warp") = Wreg(ready, _(_(in, "contents"), "warp"));
_(_(out, "contents"), "ir") = Wreg(ready, _(_(in, "contents"), "ir"));
_(_(out, "contents"), "pval") = Wreg(ready, _(_(in, "contents"), "pval"));
Flatten(_(_(_(out,"contents"),"rval"),"val0")) =
Latch(Reg(!ready),Flatten(rval0));
Flatten(_(_(_(out,"contents"),"rval"),"val1")) =
Latch(Reg(!ready),Flatten(rval1));
Flatten(_(_(_(out,"contents"),"rval"),"val2")) =
Latch(Reg(!ready),Flatten(rval2));
Buffer<1>(out_buffered, out);
HIERARCHY_EXIT();
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <unistd.h>
#include <sstream>
#include <iomanip>
#include "jabbersession.hpp"
#define BUFFERLENGTH 2000
JabberSession::JabberSession(const std::string &host, unsigned short port, bool isSecure) : m_s(host, port, isSecure) {
m_state = Connected;
m_depth = 0;
m_idCount = 0;
pthread_mutex_init(&m_stateMutex, NULL);
m_node = NULL;
if (0 == pthread_create(&m_listenerThread, NULL, ListenerThreadFunction, this)) {
// SYZYGY -- RFC 3920 specifies an "xml:lang" attribute and a "version" attribute
// SYZYGY -- I need to configure the "to" somehow
std::string xml = "<?xml version='1.0'?><stream:stream to='jabber.brokersys.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>";
m_s.Send(xml);
pthread_mutex_lock(&m_stateMutex);
while (m_state < GotStreamTag) {
pthread_mutex_unlock(&m_stateMutex);
usleep(500);
pthread_mutex_lock(&m_stateMutex);
}
pthread_mutex_unlock(&m_stateMutex);
}
}
JabberSession::~JabberSession(void) {
void *listenerData;
pthread_mutex_lock(&m_stateMutex);
m_state = Closing;
pthread_mutex_unlock(&m_stateMutex);
std::string xml = "</stream:stream>";
m_s.Send(xml);
pthread_join(m_listenerThread, &listenerData);
}
void JabberSession::on_start_element(const Glib::ustring &name, const AttributeList &attributes) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_start_element(): " << name << std::endl;
if (0 == m_depth) {
if ((Connected == m_state) && ("stream:stream" == name)) {
bool has_id = false;
bool has_from = false;
for(xmlpp::SaxParser::AttributeList::const_iterator i = attributes.begin(); i != attributes.end(); ++i) {
if (i->name == "xmlns:stream") {
std::cout << " The stream namespace is \"" << i->value << "\"" << std::endl;
}
if (i->name == "id") {
std::cout << " The session identifier is \"" << i->value << "\"" << std::endl;
has_id = true;
m_sessionIdentifier = i->value;
}
if (i->name == "xmlns") {
std::cout << " Declaring XML namespace \"" << i->value << "\"" << std::endl;
}
if (i->name == "from") {
has_from = true;
std::cout << " The logical server name is \"" << i->value << "\"" << std::endl;
m_logicalServer = i->value;
}
}
if (has_from and has_id) {
m_state = GotStreamTag;
}
else {
m_state = Error;
}
}
else {
m_state = Error;
}
}
else {
if (1 == m_depth) {
if (("message" == name) || ("presence" == name) || ("iq" == name)) {
m_node = new JabberElementNode(NULL, name, attributes);
}
else {
m_state = Error;
}
}
else {
// std::cout << "Recursing into node " << name << std::endl;
JabberElementNode *temp = new JabberElementNode(m_node, name, attributes);
m_node->m_children.push_back(temp);
m_node = temp;
}
}
++m_depth;
pthread_mutex_unlock(&m_stateMutex);
}
void JabberSession::on_end_element(const Glib::ustring &name) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_end_element(): " << name << std::endl;
--m_depth;
if (NULL != m_node->m_parent) {
m_node = m_node->m_parent;
}
if (1 == m_depth) {
bool isResponse = false;
Stanza *message = Stanza::parse(m_node);
isResponse = ("result" == *message->Type()) || ("error" == *message->Type());
if (isResponse && (NULL != message->Id())) {
jabberEventMap_t::iterator i = m_jabberEvents.find(*message->Id());
if (m_jabberEvents.end() != i) {
i->second->s = message;
pthread_mutex_unlock(&i->second->c);
m_jabberEvents.erase(i);
}
m_node = NULL;
}
else {
// SYZYGY -- dispatch the message to the handler, if any
if (NULL != message->Namespace()) {
handlerMap_t::iterator i = m_handlers.find(*message->Namespace());
if (m_handlers.end() != i) {
m_handlers[*message->Namespace()](*message, this);
}
}
}
}
pthread_mutex_unlock(&m_stateMutex);
}
void JabberSession::on_characters(const Glib::ustring &characters) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_characters(): " << characters << std::endl;
if (NULL != m_node) {
JabberTextNode *node = new JabberTextNode(m_node, characters);
m_node->m_children.push_back(node);
}
pthread_mutex_unlock(&m_stateMutex);
}
void JabberSession::on_comment(const Glib::ustring &text) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_comment(): " << text << std::endl;
pthread_mutex_unlock(&m_stateMutex);
}
void JabberSession::on_warning(const Glib::ustring &text) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_warning(): " << text << std::endl;
pthread_mutex_unlock(&m_stateMutex);
}
void JabberSession::on_error(const Glib::ustring &text) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_error(): " << text << std::endl;
pthread_mutex_unlock(&m_stateMutex);
}
void JabberSession::on_fatal_error(const Glib::ustring &text) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_fatal_error(): " << text << std::endl;
pthread_mutex_unlock(&m_stateMutex);
}
void *JabberSession::ListenerThreadFunction(void *data) {
JabberSession *t = (JabberSession *)data;
uint8_t buff[BUFFERLENGTH];
pthread_mutex_lock(&t->m_stateMutex);
while (t->m_state < Closing) {
pthread_mutex_unlock(&t->m_stateMutex);
// Get the state mutex
long l = t->m_s.Receive(buff, BUFFERLENGTH);
buff[l] = '\0';
std::cout << "Received " << l << " chars \"" << buff << "\"" << std::endl;
if (0 < l) {
Glib::ustring input((char *)buff, l);
t->parse_chunk(input);
pthread_mutex_lock(&t->m_stateMutex);
}
else {
if (0 > l) {
// Get the state mutex
pthread_mutex_lock(&t->m_stateMutex);
t->m_state = Closed;
}
else {
pthread_mutex_lock(&t->m_stateMutex);
}
}
}
pthread_mutex_unlock(&t->m_stateMutex);
t->finish_chunk_parsing();
return NULL;
}
const Stanza *JabberSession::SendMessage(const Stanza &request, bool expectingReply) {
jabberEvent_t *e = NULL;
// SYZYGY -- I need to rework this logic because currently there's no way to send a message that
// SYZYGY -- doesn't have an ID
const std::string *xml;
if (expectingReply) {
pthread_mutex_lock(&m_stateMutex);
unsigned long local_count = m_idCount++;
e = new(jabberEvent_t);
std::ostringstream id;
id << std::hex << std::setw(8) << std::setfill('0') << local_count;
std::string *id_string = new std::string(id.str());
xml = request.render(id_string);
delete id_string;
pthread_mutex_init(&e->c, NULL);
pthread_mutex_lock(&e->c);
m_jabberEvents[id.str()] = e;
pthread_mutex_unlock(&m_stateMutex);
}
else {
xml = request.render(NULL);
}
m_s.Send(*xml);
if (expectingReply) {
pthread_mutex_lock(&e->c);
Stanza *result = e->s;
delete e;
return result;
}
// It falls through to here if it's not expecting a reply. Since I'm not expecting
// a reply, I can return a pointer to nothing
return NULL;
}
void JabberSession::Register(handler_t handler, const std::string &name_space) {
m_handlers[name_space] = handler;
}
<commit_msg>Don't call the handler unless it's not a response.<commit_after>#include <iostream>
#include <unistd.h>
#include <sstream>
#include <iomanip>
#include "jabbersession.hpp"
#define BUFFERLENGTH 2000
JabberSession::JabberSession(const std::string &host, unsigned short port, bool isSecure) : m_s(host, port, isSecure) {
m_state = Connected;
m_depth = 0;
m_idCount = 0;
pthread_mutex_init(&m_stateMutex, NULL);
m_node = NULL;
if (0 == pthread_create(&m_listenerThread, NULL, ListenerThreadFunction, this)) {
// SYZYGY -- RFC 3920 specifies an "xml:lang" attribute and a "version" attribute
// SYZYGY -- I need to configure the "to" somehow
std::string xml = "<?xml version='1.0'?><stream:stream to='jabber.brokersys.com' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>";
m_s.Send(xml);
pthread_mutex_lock(&m_stateMutex);
while (m_state < GotStreamTag) {
pthread_mutex_unlock(&m_stateMutex);
usleep(500);
pthread_mutex_lock(&m_stateMutex);
}
pthread_mutex_unlock(&m_stateMutex);
}
}
JabberSession::~JabberSession(void) {
void *listenerData;
pthread_mutex_lock(&m_stateMutex);
m_state = Closing;
pthread_mutex_unlock(&m_stateMutex);
std::string xml = "</stream:stream>";
m_s.Send(xml);
pthread_join(m_listenerThread, &listenerData);
}
void JabberSession::on_start_element(const Glib::ustring &name, const AttributeList &attributes) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_start_element(): " << name << std::endl;
if (0 == m_depth) {
if ((Connected == m_state) && ("stream:stream" == name)) {
bool has_id = false;
bool has_from = false;
for(xmlpp::SaxParser::AttributeList::const_iterator i = attributes.begin(); i != attributes.end(); ++i) {
if (i->name == "xmlns:stream") {
std::cout << " The stream namespace is \"" << i->value << "\"" << std::endl;
}
if (i->name == "id") {
std::cout << " The session identifier is \"" << i->value << "\"" << std::endl;
has_id = true;
m_sessionIdentifier = i->value;
}
if (i->name == "xmlns") {
std::cout << " Declaring XML namespace \"" << i->value << "\"" << std::endl;
}
if (i->name == "from") {
has_from = true;
std::cout << " The logical server name is \"" << i->value << "\"" << std::endl;
m_logicalServer = i->value;
}
}
if (has_from and has_id) {
m_state = GotStreamTag;
}
else {
m_state = Error;
}
}
else {
m_state = Error;
}
}
else {
if (1 == m_depth) {
if (("message" == name) || ("presence" == name) || ("iq" == name)) {
m_node = new JabberElementNode(NULL, name, attributes);
}
else {
m_state = Error;
}
}
else {
// std::cout << "Recursing into node " << name << std::endl;
JabberElementNode *temp = new JabberElementNode(m_node, name, attributes);
m_node->m_children.push_back(temp);
m_node = temp;
}
}
++m_depth;
pthread_mutex_unlock(&m_stateMutex);
}
void JabberSession::on_end_element(const Glib::ustring &name) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_end_element(): " << name << std::endl;
--m_depth;
if (NULL != m_node->m_parent) {
m_node = m_node->m_parent;
}
if (1 == m_depth) {
bool isResponse = false;
Stanza *message = Stanza::parse(m_node);
m_node = NULL;
isResponse = ("result" == *message->Type()) || ("error" == *message->Type());
if (isResponse) {
if (NULL != message->Id()) {
jabberEventMap_t::iterator i = m_jabberEvents.find(*message->Id());
if (m_jabberEvents.end() != i) {
i->second->s = message;
pthread_mutex_unlock(&i->second->c);
m_jabberEvents.erase(i);
}
}
}
else {
// SYZYGY -- dispatch the message to the handler, if any
if (NULL != message->Namespace()) {
handlerMap_t::iterator i = m_handlers.find(*message->Namespace());
if (m_handlers.end() != i) {
m_handlers[*message->Namespace()](*message, this);
}
}
}
}
pthread_mutex_unlock(&m_stateMutex);
}
void JabberSession::on_characters(const Glib::ustring &characters) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_characters(): " << characters << std::endl;
if (NULL != m_node) {
JabberTextNode *node = new JabberTextNode(m_node, characters);
m_node->m_children.push_back(node);
}
pthread_mutex_unlock(&m_stateMutex);
}
void JabberSession::on_comment(const Glib::ustring &text) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_comment(): " << text << std::endl;
pthread_mutex_unlock(&m_stateMutex);
}
void JabberSession::on_warning(const Glib::ustring &text) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_warning(): " << text << std::endl;
pthread_mutex_unlock(&m_stateMutex);
}
void JabberSession::on_error(const Glib::ustring &text) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_error(): " << text << std::endl;
pthread_mutex_unlock(&m_stateMutex);
}
void JabberSession::on_fatal_error(const Glib::ustring &text) {
pthread_mutex_lock(&m_stateMutex);
std::cout << "on_fatal_error(): " << text << std::endl;
pthread_mutex_unlock(&m_stateMutex);
}
void *JabberSession::ListenerThreadFunction(void *data) {
JabberSession *t = (JabberSession *)data;
uint8_t buff[BUFFERLENGTH];
pthread_mutex_lock(&t->m_stateMutex);
while (t->m_state < Closing) {
pthread_mutex_unlock(&t->m_stateMutex);
// Get the state mutex
long l = t->m_s.Receive(buff, BUFFERLENGTH);
buff[l] = '\0';
std::cout << "Received " << l << " chars \"" << buff << "\"" << std::endl;
if (0 < l) {
Glib::ustring input((char *)buff, l);
t->parse_chunk(input);
pthread_mutex_lock(&t->m_stateMutex);
}
else {
if (0 > l) {
// Get the state mutex
pthread_mutex_lock(&t->m_stateMutex);
t->m_state = Closed;
}
else {
pthread_mutex_lock(&t->m_stateMutex);
}
}
}
pthread_mutex_unlock(&t->m_stateMutex);
t->finish_chunk_parsing();
return NULL;
}
const Stanza *JabberSession::SendMessage(const Stanza &request, bool expectingReply) {
jabberEvent_t *e = NULL;
// SYZYGY -- I need to rework this logic because currently there's no way to send a message that
// SYZYGY -- doesn't have an ID
const std::string *xml;
if (expectingReply) {
pthread_mutex_lock(&m_stateMutex);
unsigned long local_count = m_idCount++;
e = new(jabberEvent_t);
std::ostringstream id;
id << std::hex << std::setw(8) << std::setfill('0') << local_count;
std::string *id_string = new std::string(id.str());
xml = request.render(id_string);
delete id_string;
pthread_mutex_init(&e->c, NULL);
pthread_mutex_lock(&e->c);
m_jabberEvents[id.str()] = e;
pthread_mutex_unlock(&m_stateMutex);
}
else {
xml = request.render(NULL);
}
m_s.Send(*xml);
if (expectingReply) {
pthread_mutex_lock(&e->c);
Stanza *result = e->s;
delete e;
return result;
}
// It falls through to here if it's not expecting a reply. Since I'm not expecting
// a reply, I can return a pointer to nothing
return NULL;
}
void JabberSession::Register(handler_t handler, const std::string &name_space) {
m_handlers[name_space] = handler;
}
<|endoftext|> |
<commit_before>// WCSRequest.cc
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of wcs_module, A C++ module that can be loaded in to
// the OPeNDAP Back-End Server (BES) and is able to handle wcs requests.
// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: Patrick West <pwest@ucar.edu>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// (c) COPYRIGHT URI/MIT 1994-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
// pcw Patrick West <pwest@ucar.edu>
#include <HTTPConnect.h>
#include <RCReader.h>
#include <Error.h>
using namespace libdap ;
#include <BESInternalError.h>
#include <BESDebug.h>
#include "WCSRequest.h"
#include "WCSError.h"
#include "WCSUtils.h"
#include "config.h"
/** @brief make the WCS request against the given information
*
* function that makes a WCS request using HTTPConnect from libdap given the
* WCS request url. An HTTPResponse object is returned from the HTTPConnect
* fetch_url method. This response contains the FILE pointer as well as the
* name of the file to be used by the corresponding data handler (determined
* by the format parameter in the WCS url).
*
* @param url WCS request url
* @return HTTPResponse pointer for the wcs request response
* @throws BESInternalError if there is a problem making the WCS request or
* the request fails
*/
HTTPResponse *
WCSRequest::make_request( const string &url )
{
if( url.empty() )
{
string err = "WCS Request URL is empty" ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
BESDEBUG( "wcs", "WCSRequest::make_request" << endl )
BESDEBUG( "wcs", " request = " << url << endl )
HTTPConnect connect( RCReader::instance() ) ;
connect.set_cache_enabled( false ) ;
HTTPResponse *response = 0 ;
try
{
response = connect.fetch_url( url ) ;
}
catch( Error &e )
{
BESInternalError err( e.get_error_message(), __FILE__, __LINE__ ) ;
throw err ;
}
catch( ... )
{
string msg = (string)"Unknown exception fetching wcs request " + url ;
BESInternalError err( msg, __FILE__, __LINE__ ) ;
throw err ;
}
if( !response )
{
string msg = (string)"Response empty fetching wcs request " + url ;
BESInternalError err( msg, __FILE__, __LINE__ ) ;
throw err ;
}
// A WCS request is successful if we get data or if there is an xml
// error, in some cases. Sometimes an XML error also returns an HTTP
// error, but not always. So ... check the headers from the HTTPResponse
// object.
// WCS request errors could come as a regular HTML response (not found,
// whatever) or could come as a WCS request XML error. So we have to
// check to make sure which kind of error it is.
bool request_status = true ;
bool xml_error = false ;
if( response->get_status() != 200 )
{
request_status = false ;
}
vector<string> *hdrs = response->get_headers() ;
if( hdrs )
{
vector<string>::const_iterator i = hdrs->begin() ;
vector<string>::const_iterator e = hdrs->end() ;
for( ; i != e; i++ )
{
string hdr_line = (*i) ;
if( hdr_line.find( "text/xml" ) != string::npos )
{
BESDEBUG( "wcs", " found xml error" << endl )
request_status = false ;
xml_error = true ;
}
}
}
if( request_status == false )
{
BESDEBUG( "wcs", " request FAILED" << endl )
// get the error information from the temoorary file
string err ;
if( xml_error )
{
BESDEBUG( "wcs", " reading xml error" << endl )
WCSError::read_xml_error( response->get_file(), err, url ) ;
}
else
{
BESDEBUG( "wcs", " reading text error" << endl )
WCSError::read_error( response->get_file(), err, url ) ;
}
// toss the response
delete response ;
response = 0 ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
BESDEBUG( "wcs", "WCSRequest::make_request - done" << endl )
return response ;
}
<commit_msg>Setting use cache on RCReader to false after creating to make sure cache is NOT being used in HTTPConnect and HTTPCache.<commit_after>// WCSRequest.cc
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of wcs_module, A C++ module that can be loaded in to
// the OPeNDAP Back-End Server (BES) and is able to handle wcs requests.
// Copyright (c) 2002,2003 OPeNDAP, Inc.
// Author: Patrick West <pwest@ucar.edu>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
// (c) COPYRIGHT URI/MIT 1994-1999
// Please read the full copyright statement in the file COPYRIGHT_URI.
//
// Authors:
// pcw Patrick West <pwest@ucar.edu>
#include <HTTPConnect.h>
#include <RCReader.h>
#include <Error.h>
using namespace libdap ;
#include <BESInternalError.h>
#include <BESDebug.h>
#include "WCSRequest.h"
#include "WCSError.h"
#include "WCSUtils.h"
#include "config.h"
/** @brief make the WCS request against the given information
*
* function that makes a WCS request using HTTPConnect from libdap given the
* WCS request url. An HTTPResponse object is returned from the HTTPConnect
* fetch_url method. This response contains the FILE pointer as well as the
* name of the file to be used by the corresponding data handler (determined
* by the format parameter in the WCS url).
*
* @param url WCS request url
* @return HTTPResponse pointer for the wcs request response
* @throws BESInternalError if there is a problem making the WCS request or
* the request fails
*/
HTTPResponse *
WCSRequest::make_request( const string &url )
{
if( url.empty() )
{
string err = "WCS Request URL is empty" ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
BESDEBUG( "wcs", "WCSRequest::make_request" << endl )
BESDEBUG( "wcs", " request = " << url << endl )
RCReader *rcr = RCReader::instance() ;
rcr->set_use_cache( false ) ;
HTTPConnect connect( RCReader::instance() ) ;
connect.set_cache_enabled( false ) ;
HTTPResponse *response = 0 ;
try
{
response = connect.fetch_url( url ) ;
}
catch( Error &e )
{
BESInternalError err( e.get_error_message(), __FILE__, __LINE__ ) ;
throw err ;
}
catch( ... )
{
string msg = (string)"Unknown exception fetching wcs request " + url ;
BESInternalError err( msg, __FILE__, __LINE__ ) ;
throw err ;
}
if( !response )
{
string msg = (string)"Response empty fetching wcs request " + url ;
BESInternalError err( msg, __FILE__, __LINE__ ) ;
throw err ;
}
// A WCS request is successful if we get data or if there is an xml
// error, in some cases. Sometimes an XML error also returns an HTTP
// error, but not always. So ... check the headers from the HTTPResponse
// object.
// WCS request errors could come as a regular HTML response (not found,
// whatever) or could come as a WCS request XML error. So we have to
// check to make sure which kind of error it is.
bool request_status = true ;
bool xml_error = false ;
if( response->get_status() != 200 )
{
request_status = false ;
}
vector<string> *hdrs = response->get_headers() ;
if( hdrs )
{
vector<string>::const_iterator i = hdrs->begin() ;
vector<string>::const_iterator e = hdrs->end() ;
for( ; i != e; i++ )
{
string hdr_line = (*i) ;
if( hdr_line.find( "text/xml" ) != string::npos )
{
BESDEBUG( "wcs", " found xml error" << endl )
request_status = false ;
xml_error = true ;
}
}
}
if( request_status == false )
{
BESDEBUG( "wcs", " request FAILED" << endl )
// get the error information from the temoorary file
string err ;
if( xml_error )
{
BESDEBUG( "wcs", " reading xml error" << endl )
WCSError::read_xml_error( response->get_file(), err, url ) ;
}
else
{
BESDEBUG( "wcs", " reading text error" << endl )
WCSError::read_error( response->get_file(), err, url ) ;
}
// toss the response
delete response ;
response = 0 ;
throw BESInternalError( err, __FILE__, __LINE__ ) ;
}
BESDEBUG( "wcs", "WCSRequest::make_request - done" << endl )
return response ;
}
<|endoftext|> |
<commit_before>// $Id: directory.C,v 1.13 2000/07/03 12:24:52 oliver Exp $
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <errno.h>
#include <BALL/SYSTEM/directory.h>
#define BALL_MAX_PATH_LENGTH 8192
namespace BALL
{
Directory::Directory()
{
dir_ = 0;
dirent_ = 0;
char* buffer_;
if ((buffer_ = ::getcwd(NULL, BALL_MAX_PATH_LENGTH)) != NULL) directory_path_ = buffer_;
else directory_path_ = "";
}
Directory::Directory(const String& directory_path, bool set_current)
{
if (!set(directory_path, set_current)) directory_path_ = "";
}
Directory::Directory(const Directory& directory)
{
set(directory);
}
Directory::~Directory()
{
if (dir_ != 0) ::closedir(dir_);
}
void Directory::swap(Directory& directory)
{
DIR* temp_dir = dir_;
dir_ = directory.dir_;
directory.dir_ = temp_dir;
dirent* temp_dirent = dirent_;
dirent_ = directory.dirent_;
directory.dirent_ = temp_dirent;
backup_path_.swap(directory.backup_path_);
directory_path_.swap(directory.directory_path_);
}
bool Directory::getFirstEntry(String& entry)
{
synchronize_();
if (dir_ != 0) ::closedir(dir_);
dir_ = ::opendir(directory_path_.data());
if (dir_ == 0) return desynchronize_(false);
dirent_ = ::readdir(dir_);
if (dirent_ == 0)
{
::closedir(dir_);
dir_ = 0;
return desynchronize_(false);
}
else
{
entry = dirent_->d_name;
return desynchronize_(true);
}
}
bool Directory::getNextEntry(String& entry)
{
synchronize_();
if (dir_ == 0) dir_ = ::opendir(directory_path_.data());
if (dir_ == 0) return desynchronize_(false);
dirent_ = ::readdir(dir_);
if (dirent_ == 0)
{
::closedir(dir_);
dir_ = 0;
return desynchronize_(false);
}
entry = dirent_->d_name;
return desynchronize_(true);
}
Size Directory::countItems()
{
synchronize_();
Size size = 0;
DIR* dir = ::opendir(directory_path_.data());
if (dir == 0)
{
desynchronize_();
return 0;
}
while(::readdir(dir) != 0) ++size;
::closedir(dir);
desynchronize_();
return (size - 2);
} // ignore current (.) and parent directory entry (..)
Size Directory::countFiles()
{
synchronize_();
struct stat stats;
Size size = 0;
dirent* myDirent;
DIR* dir = ::opendir(directory_path_.data());
if (dir == 0)
{
desynchronize_();
return 0;
}
while((myDirent = ::readdir(dir)) != 0)
{
if (lstat(myDirent->d_name, &stats) < 0) continue;
if (S_ISDIR(stats.st_mode) == 0) ++size;
}
::closedir(dir);
desynchronize_();
return size;
}
Size Directory::countDirectories()
{
synchronize_();
struct stat stats;
Size size = 0;
dirent* myDirent;
DIR *dir = ::opendir(directory_path_.data());
if (dir == 0)
{
desynchronize_();
return 0;
}
while((myDirent = ::readdir(dir)) != 0)
{
if (lstat(myDirent->d_name, &stats) < 0) continue;
if (S_ISDIR(stats.st_mode) != 0) ++size;
}
::closedir(dir);
desynchronize_();
return (size - 2);
} // ignore current (.) and parent directory entry (..)
bool Directory::isCurrent() const
{
char* buffer_;
if ((buffer_ = ::getcwd(NULL, BALL_MAX_PATH_LENGTH)) == 0) return false;
return (buffer_ == directory_path_);
}
bool Directory::has(const String& item) //const
{
synchronize_();
String entry;
while (getNextEntry(entry))
{
if (entry == item) return desynchronize_(true);
}
return desynchronize_(false);
}
bool Directory::find(const String& item, String& filepath)
{
if (has(item))
{
filepath = directory_path_;
return true; // no sync needed...
}
synchronize_();
struct stat stats;
dirent* myDirent;
Directory directory;
String s;
DIR* dir = ::opendir(FileSystem::CURRENT_DIRECTORY);
if (dir == 0) return desynchronize_(false);
while((myDirent = ::readdir(dir)) != 0)
{
if (lstat(myDirent->d_name, &stats) < 0) continue;
if (S_ISDIR(stats.st_mode) != 0 &&
strcmp(myDirent->d_name, FileSystem::CURRENT_DIRECTORY) != 0 &&
strcmp(myDirent->d_name, FileSystem::PARENT_DIRECTORY ) != 0)
{
directory =Directory(myDirent->d_name);
if (directory.find(item, s))
{
filepath = s;
::closedir(dir);
return desynchronize_(true);
}
}
}
::closedir(dir);
return desynchronize_(false);
}
bool Directory::set(const String& directory_path, bool set_current)
{
dir_ = 0;
dirent_ = 0;
backup_path_ = "";
char* buffer_;
if (directory_path[0] == '/') //absolute path
{
directory_path_ = directory_path;
FileSystem::canonizePath(directory_path_);
return isValid();
}
if ((buffer_ = ::getcwd(NULL, BALL_MAX_PATH_LENGTH)) != NULL)
{
directory_path_ = buffer_;
directory_path_ += FileSystem::PATH_SEPARATOR;
directory_path_ += directory_path;
FileSystem::canonizePath(directory_path_);
if (directory_path_.hasSuffix(String(FileSystem::PATH_SEPARATOR)))
{
directory_path_.truncate(directory_path_.size() - 1);
}
}
else
{
directory_path_ = "";
return false;
}
if (!isValid()) return false;
if (set_current) return (::chdir(directory_path_.data()) == 0);
return true;
}
bool Directory::remove()
{
synchronize_();
if (::chdir("..") != 0) return desynchronize_(false);
bool result1 = (::rmdir(directory_path_.data()) == 0);
bool result2;
if (backup_path_ != "")
{
result2 = ::chdir(backup_path_.data());
backup_path_ = "";
}
dir_ = 0;
dirent_ = 0;
directory_path_ = "";
return (result1 && result2);
}
bool Directory::renameTo(String new_path)
{
synchronize_();
FileSystem::canonizePath(new_path);
if (::chdir("..") != 0) return desynchronize_(false);
if (::rename(directory_path_.data(), new_path.data()) == 0)
{
directory_path_ = new_path;
return desynchronize_(true);
}
return desynchronize_(false);
}
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/SYSTEM/directory.iC>
# endif
} // namespace BALL
<commit_msg>fixed: MAX_PATH_LENGTH is the member that holds the maximum buffer length required by some system calls (getcwd)<commit_after>// $Id: directory.C,v 1.14 2000/07/04 08:20:07 oliver Exp $
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <errno.h>
#include <BALL/SYSTEM/directory.h>
namespace BALL
{
const Size Directory::MAX_PATH_LENGTH = 8192;
Directory::Directory()
{
dir_ = 0;
dirent_ = 0;
char* buffer_;
if ((buffer_ = ::getcwd(NULL, MAX_PATH_LENGTH)) != NULL) directory_path_ = buffer_;
else directory_path_ = "";
}
Directory::Directory(const String& directory_path, bool set_current)
{
if (!set(directory_path, set_current)) directory_path_ = "";
}
Directory::Directory(const Directory& directory)
{
set(directory);
}
Directory::~Directory()
{
if (dir_ != 0) ::closedir(dir_);
}
void Directory::swap(Directory& directory)
{
DIR* temp_dir = dir_;
dir_ = directory.dir_;
directory.dir_ = temp_dir;
dirent* temp_dirent = dirent_;
dirent_ = directory.dirent_;
directory.dirent_ = temp_dirent;
backup_path_.swap(directory.backup_path_);
directory_path_.swap(directory.directory_path_);
}
bool Directory::getFirstEntry(String& entry)
{
synchronize_();
if (dir_ != 0) ::closedir(dir_);
dir_ = ::opendir(directory_path_.data());
if (dir_ == 0) return desynchronize_(false);
dirent_ = ::readdir(dir_);
if (dirent_ == 0)
{
::closedir(dir_);
dir_ = 0;
return desynchronize_(false);
}
else
{
entry = dirent_->d_name;
return desynchronize_(true);
}
}
bool Directory::getNextEntry(String& entry)
{
synchronize_();
if (dir_ == 0) dir_ = ::opendir(directory_path_.data());
if (dir_ == 0) return desynchronize_(false);
dirent_ = ::readdir(dir_);
if (dirent_ == 0)
{
::closedir(dir_);
dir_ = 0;
return desynchronize_(false);
}
entry = dirent_->d_name;
return desynchronize_(true);
}
Size Directory::countItems()
{
synchronize_();
Size size = 0;
DIR* dir = ::opendir(directory_path_.data());
if (dir == 0)
{
desynchronize_();
return 0;
}
while(::readdir(dir) != 0) ++size;
::closedir(dir);
desynchronize_();
return (size - 2);
} // ignore current (.) and parent directory entry (..)
Size Directory::countFiles()
{
synchronize_();
struct stat stats;
Size size = 0;
dirent* myDirent;
DIR* dir = ::opendir(directory_path_.data());
if (dir == 0)
{
desynchronize_();
return 0;
}
while((myDirent = ::readdir(dir)) != 0)
{
if (lstat(myDirent->d_name, &stats) < 0) continue;
if (S_ISDIR(stats.st_mode) == 0) ++size;
}
::closedir(dir);
desynchronize_();
return size;
}
Size Directory::countDirectories()
{
synchronize_();
struct stat stats;
Size size = 0;
dirent* myDirent;
DIR *dir = ::opendir(directory_path_.data());
if (dir == 0)
{
desynchronize_();
return 0;
}
while((myDirent = ::readdir(dir)) != 0)
{
if (lstat(myDirent->d_name, &stats) < 0) continue;
if (S_ISDIR(stats.st_mode) != 0) ++size;
}
::closedir(dir);
desynchronize_();
return (size - 2);
} // ignore current (.) and parent directory entry (..)
bool Directory::isCurrent() const
{
char* buffer_;
if ((buffer_ = ::getcwd(NULL, MAX_PATH_LENGTH)) == 0) return false;
return (buffer_ == directory_path_);
}
bool Directory::has(const String& item) //const
{
synchronize_();
String entry;
while (getNextEntry(entry))
{
if (entry == item) return desynchronize_(true);
}
return desynchronize_(false);
}
bool Directory::find(const String& item, String& filepath)
{
if (has(item))
{
filepath = directory_path_;
return true; // no sync needed...
}
synchronize_();
struct stat stats;
dirent* myDirent;
Directory directory;
String s;
DIR* dir = ::opendir(FileSystem::CURRENT_DIRECTORY);
if (dir == 0) return desynchronize_(false);
while((myDirent = ::readdir(dir)) != 0)
{
if (lstat(myDirent->d_name, &stats) < 0) continue;
if (S_ISDIR(stats.st_mode) != 0 &&
strcmp(myDirent->d_name, FileSystem::CURRENT_DIRECTORY) != 0 &&
strcmp(myDirent->d_name, FileSystem::PARENT_DIRECTORY ) != 0)
{
directory =Directory(myDirent->d_name);
if (directory.find(item, s))
{
filepath = s;
::closedir(dir);
return desynchronize_(true);
}
}
}
::closedir(dir);
return desynchronize_(false);
}
bool Directory::set(const String& directory_path, bool set_current)
{
dir_ = 0;
dirent_ = 0;
backup_path_ = "";
char* buffer_;
if (directory_path[0] == '/') //absolute path
{
directory_path_ = directory_path;
FileSystem::canonizePath(directory_path_);
return isValid();
}
if ((buffer_ = ::getcwd(NULL, MAX_PATH_LENGTH)) != NULL)
{
directory_path_ = buffer_;
directory_path_ += FileSystem::PATH_SEPARATOR;
directory_path_ += directory_path;
FileSystem::canonizePath(directory_path_);
if (directory_path_.hasSuffix(String(FileSystem::PATH_SEPARATOR)))
{
directory_path_.truncate(directory_path_.size() - 1);
}
}
else
{
directory_path_ = "";
return false;
}
if (!isValid()) return false;
if (set_current) return (::chdir(directory_path_.data()) == 0);
return true;
}
bool Directory::remove()
{
synchronize_();
if (::chdir("..") != 0) return desynchronize_(false);
bool result1 = (::rmdir(directory_path_.data()) == 0);
bool result2;
if (backup_path_ != "")
{
result2 = ::chdir(backup_path_.data());
backup_path_ = "";
}
dir_ = 0;
dirent_ = 0;
directory_path_ = "";
return (result1 && result2);
}
bool Directory::renameTo(String new_path)
{
synchronize_();
FileSystem::canonizePath(new_path);
if (::chdir("..") != 0) return desynchronize_(false);
if (::rename(directory_path_.data(), new_path.data()) == 0)
{
directory_path_ = new_path;
return desynchronize_(true);
}
return desynchronize_(false);
}
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/SYSTEM/directory.iC>
# endif
} // namespace BALL
<|endoftext|> |
<commit_before>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
Version 1.0.0, packaged on August, 2008.
http://glc-lib.sourceforge.net
GLC-lib 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.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_mesh2.cpp implementation of the GLC_Mesh2 class.
#include "glc_mesh2.h"
#include "glc_openglexception.h"
#include "glc_selectionmaterial.h"
#include <QtDebug>
//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Mesh2::GLC_Mesh2()
:GLC_VboGeom("Mesh", false)
, m_Vertex()
, m_MaterialGroup()
, m_MaterialHash()
, m_NumberOfFaces(0)
, m_IsSelected(false)
, m_ColorPearVertex(false)
{
//qDebug() << "GLC_Mesh2::GLC_Mesh2" << getID();
// Index group with default material
IndexList* pIndexList= new IndexList;
m_MaterialGroup.insert(0, pIndexList);
}
GLC_Mesh2::GLC_Mesh2(const GLC_Mesh2 &meshToCopy)
: GLC_VboGeom(meshToCopy)
, m_Vertex(meshToCopy.m_Vertex)
, m_MaterialGroup()
, m_MaterialHash(meshToCopy.m_MaterialHash)
, m_NumberOfFaces(meshToCopy.m_NumberOfFaces)
, m_IsSelected(false)
, m_ColorPearVertex(meshToCopy.m_ColorPearVertex)
{
//qDebug() << "GLC_Mesh2::GLC_Mesh2" << getID();
// Add this mesh to inner material
MaterialHash::const_iterator i= m_MaterialHash.begin();
while (i != m_MaterialHash.constEnd())
{
// update inner material use table
i.value()->addGLC_Geom(this);
++i;
}
// Copy Material group IBO
MaterialGroupHash::const_iterator j= meshToCopy.m_MaterialGroup.begin();
while (j != meshToCopy.m_MaterialGroup.constEnd())
{
IndexList* pIndexList= new IndexList(*j.value());
m_MaterialGroup.insert(j.key(), pIndexList);
++j;
}
}
GLC_Mesh2::~GLC_Mesh2(void)
{
// delete mesh inner material
{
MaterialHash::const_iterator i= m_MaterialHash.begin();
while (i != m_MaterialHash.constEnd())
{
// delete the material if necessary
i.value()->delGLC_Geom(getID());
if (i.value()->isUnused()) delete i.value();
++i;
}
}
// delete mesh inner index material group
{
MaterialGroupHash::const_iterator i= m_MaterialGroup.begin();
while (i != m_MaterialGroup.constEnd())
{
// Delete index vector
delete i.value();
++i;
}
}
m_MaterialHash.clear();
}
/////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
//! Return material index if Material is the same than a material already in the mesh
GLC_uint GLC_Mesh2::materialIndex(const GLC_Material& mat) const
{
int index= 0;
MaterialHash::const_iterator iEntry= m_MaterialHash.begin();
while ((iEntry != m_MaterialHash.constEnd()) and !(*(iEntry.value()) == mat))
{
++iEntry;
}
if (iEntry != m_MaterialHash.constEnd())
{
index= iEntry.key();
}
return index;
}
// return the mesh bounding box
GLC_BoundingBox* GLC_Mesh2::getBoundingBox(void) const
{
GLC_BoundingBox* pBoundingBox= new GLC_BoundingBox();
const int max= m_Vertex.size();
for (int i= 0; i < max; ++i)
{
GLC_Vector3d vector(m_Vertex[i].x, m_Vertex[i].y, m_Vertex[i].z);
pBoundingBox->combine(vector);
}
return pBoundingBox;
}
// Return a copy of the current geometry
GLC_VboGeom* GLC_Mesh2::clone() const
{
return new GLC_Mesh2(*this);
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Add material to mesh
void GLC_Mesh2::addMaterial(GLC_Material* pMaterial)
{
if (pMaterial != NULL)
{
const GLC_uint materialID= pMaterial->getID();
MaterialHash::const_iterator iMaterial= m_MaterialHash.find(materialID);
// Check if there is a material at specified index
Q_ASSERT(iMaterial == m_MaterialHash.end());
// Add this geometry in the material use table
pMaterial->addGLC_Geom(this);
// Add the Material to Material hash table
m_MaterialHash.insert(materialID, pMaterial);
// Test if the material is transparent
if (pMaterial->isTransparent() && (m_MaterialHash.size() == 1))
{
setTransparency(true);
}
else if (isTransparent() && !pMaterial->isTransparent())
{
setTransparency(false);
}
// Invalid the geometry
m_GeometryIsValid = false;
}
}
// Add triangles with the same material to the mesh
void GLC_Mesh2::addTriangles(const VertexList &triangles, GLC_Material* pMaterial)
{
// test if the material is already in the mesh
GLC_uint materialID;
if (NULL != pMaterial)
{
materialID= pMaterial->getID();
}
else
{
materialID= 0;
}
IndexList* pCurIndexList= NULL;
if ((materialID == 0) or m_MaterialHash.contains(materialID))
{
pCurIndexList= m_MaterialGroup.value(materialID);
}
else
{
addMaterial(pMaterial);
pCurIndexList= new IndexList;
m_MaterialGroup.insert(materialID, pCurIndexList);
}
const int startVertexIndex= m_Vertex.size();
const int delta= triangles.size();
// Add triangles vertex to the mesh
m_Vertex+= triangles;
for (int i= 0; i < delta; ++i)
{
pCurIndexList->append(startVertexIndex + static_cast<GLuint>(i));
}
// Invalid the geometry
m_GeometryIsValid = false;
m_NumberOfFaces+= delta / 3;
}
// Reverse mesh normal
void GLC_Mesh2::reverseNormal()
{
const int max= m_Vertex.size();
for (int i= 0; i < max; ++i)
{
m_Vertex[i].nx= m_Vertex[i].nx * -1.0f;
m_Vertex[i].ny= m_Vertex[i].ny * -1.0f;
m_Vertex[i].nz= m_Vertex[i].nz * -1.0f;
}
// Invalid the geometry
m_GeometryIsValid = false;
}
// Specific glExecute method
void GLC_Mesh2::glExecute(bool isSelected, bool forceWire)
{
m_IsSelected= isSelected;
GLC_VboGeom::glExecute(isSelected, forceWire);
m_IsSelected= false;
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// if the geometry have a texture, load it
void GLC_Mesh2::glLoadTexture(void)
{
// Load texture of the master material
m_pMaterial->glLoadTexture();
MaterialHash::iterator iMaterial= m_MaterialHash.begin();
while (iMaterial != m_MaterialHash.constEnd())
{
// Load texture of mesh materials
iMaterial.value()->glLoadTexture();
++iMaterial;
}
}
// Virtual interface for OpenGL Geometry set up.
void GLC_Mesh2::glDraw()
{
IndexList iboList;
MaterialGroupHash::iterator iMaterialGroup;
// Create VBO and IBO
if (!m_GeometryIsValid)
{
// Create VBO
const GLsizei dataNbr= static_cast<GLsizei>(m_Vertex.size());
const GLsizeiptr dataSize= dataNbr * sizeof(GLC_Vertex);
QVector<GLC_Vertex> vectorVertex(m_Vertex.toVector());
const GLC_Vertex* pPositionData= vectorVertex.data();
glBufferData(GL_ARRAY_BUFFER, dataSize, pPositionData, GL_STATIC_DRAW);
// Create IBO
iMaterialGroup= m_MaterialGroup.begin();
while (iMaterialGroup != m_MaterialGroup.constEnd())
{
if (!iMaterialGroup.value()->isEmpty())
{
iboList+= *(iMaterialGroup.value());
}
++iMaterialGroup;
}
const GLsizei indexNbr= static_cast<GLsizei>(iboList.size());
const GLsizeiptr indexSize = indexNbr * sizeof(GLuint);
QVector<GLuint> vectorIndex(iboList.toVector());
const GLuint* pIndexData= vectorIndex.data();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexSize, pIndexData, GL_STATIC_DRAW);
}
glVertexPointer(3, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(0));
glNormalPointer(GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(12));
glTexCoordPointer(2, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(24));
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// test if color pear vertex is acivated
if (m_ColorPearVertex and !m_IsSelected)
{
glDisable(GL_LIGHTING);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(32));
}
GLC_Material* pCurrentMaterial;
GLuint max;
GLuint cur= 0;
iMaterialGroup= m_MaterialGroup.begin();
while (iMaterialGroup != m_MaterialGroup.constEnd())
{
if (!iMaterialGroup.value()->isEmpty())
{
// Set current material
if (iMaterialGroup.key() == 0)
{
// Use default material
pCurrentMaterial= m_pMaterial;
}
else
{
pCurrentMaterial= m_MaterialHash.value(iMaterialGroup.key());
Q_ASSERT(pCurrentMaterial != NULL);
}
// Execute current material
if (pCurrentMaterial->getAddRgbaTexture())
{
glEnable(GL_TEXTURE_2D);
}
else
{
glDisable(GL_TEXTURE_2D);
}
// Activate material
pCurrentMaterial->glExecute();
const GLfloat red= pCurrentMaterial->getDiffuseColor().redF();
const GLfloat green= pCurrentMaterial->getDiffuseColor().greenF();
const GLfloat blue= pCurrentMaterial->getDiffuseColor().blueF();
const GLfloat alpha= pCurrentMaterial->getDiffuseColor().alphaF();
glColor4f(red, green, blue, alpha);
if (m_IsSelected) GLC_SelectionMaterial::glExecute();
max= static_cast<GLuint>(iMaterialGroup.value()->size());
// Draw cylinder
glDrawRangeElements(GL_TRIANGLES, 0, max, max, GL_UNSIGNED_INT, BUFFER_OFFSET((cur) * sizeof(unsigned int)));
cur+= max;
}
++iMaterialGroup;
}
if (m_ColorPearVertex and !m_IsSelected)
{
glDisableClientState(GL_COLOR_ARRAY);
}
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Mesh2::GlDraw ", error);
throw(OpenGlException);
}
}
<commit_msg>Move call of selection shader from the GLC_VboGeometry to glc_Collection class.<commit_after>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
Version 1.0.0, packaged on August, 2008.
http://glc-lib.sourceforge.net
GLC-lib 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.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_mesh2.cpp implementation of the GLC_Mesh2 class.
#include "glc_mesh2.h"
#include "glc_openglexception.h"
#include "glc_selectionmaterial.h"
#include "glc_state.h"
#include <QtDebug>
//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Mesh2::GLC_Mesh2()
:GLC_VboGeom("Mesh", false)
, m_Vertex()
, m_MaterialGroup()
, m_MaterialHash()
, m_NumberOfFaces(0)
, m_IsSelected(false)
, m_ColorPearVertex(false)
{
//qDebug() << "GLC_Mesh2::GLC_Mesh2" << getID();
// Index group with default material
IndexList* pIndexList= new IndexList;
m_MaterialGroup.insert(0, pIndexList);
}
GLC_Mesh2::GLC_Mesh2(const GLC_Mesh2 &meshToCopy)
: GLC_VboGeom(meshToCopy)
, m_Vertex(meshToCopy.m_Vertex)
, m_MaterialGroup()
, m_MaterialHash(meshToCopy.m_MaterialHash)
, m_NumberOfFaces(meshToCopy.m_NumberOfFaces)
, m_IsSelected(false)
, m_ColorPearVertex(meshToCopy.m_ColorPearVertex)
{
//qDebug() << "GLC_Mesh2::GLC_Mesh2" << getID();
// Add this mesh to inner material
MaterialHash::const_iterator i= m_MaterialHash.begin();
while (i != m_MaterialHash.constEnd())
{
// update inner material use table
i.value()->addGLC_Geom(this);
++i;
}
// Copy Material group IBO
MaterialGroupHash::const_iterator j= meshToCopy.m_MaterialGroup.begin();
while (j != meshToCopy.m_MaterialGroup.constEnd())
{
IndexList* pIndexList= new IndexList(*j.value());
m_MaterialGroup.insert(j.key(), pIndexList);
++j;
}
}
GLC_Mesh2::~GLC_Mesh2(void)
{
// delete mesh inner material
{
MaterialHash::const_iterator i= m_MaterialHash.begin();
while (i != m_MaterialHash.constEnd())
{
// delete the material if necessary
i.value()->delGLC_Geom(getID());
if (i.value()->isUnused()) delete i.value();
++i;
}
}
// delete mesh inner index material group
{
MaterialGroupHash::const_iterator i= m_MaterialGroup.begin();
while (i != m_MaterialGroup.constEnd())
{
// Delete index vector
delete i.value();
++i;
}
}
m_MaterialHash.clear();
}
/////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////
//! Return material index if Material is the same than a material already in the mesh
GLC_uint GLC_Mesh2::materialIndex(const GLC_Material& mat) const
{
int index= 0;
MaterialHash::const_iterator iEntry= m_MaterialHash.begin();
while ((iEntry != m_MaterialHash.constEnd()) and !(*(iEntry.value()) == mat))
{
++iEntry;
}
if (iEntry != m_MaterialHash.constEnd())
{
index= iEntry.key();
}
return index;
}
// return the mesh bounding box
GLC_BoundingBox* GLC_Mesh2::getBoundingBox(void) const
{
GLC_BoundingBox* pBoundingBox= new GLC_BoundingBox();
const int max= m_Vertex.size();
for (int i= 0; i < max; ++i)
{
GLC_Vector3d vector(m_Vertex[i].x, m_Vertex[i].y, m_Vertex[i].z);
pBoundingBox->combine(vector);
}
return pBoundingBox;
}
// Return a copy of the current geometry
GLC_VboGeom* GLC_Mesh2::clone() const
{
return new GLC_Mesh2(*this);
}
/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////
// Add material to mesh
void GLC_Mesh2::addMaterial(GLC_Material* pMaterial)
{
if (pMaterial != NULL)
{
const GLC_uint materialID= pMaterial->getID();
MaterialHash::const_iterator iMaterial= m_MaterialHash.find(materialID);
// Check if there is a material at specified index
Q_ASSERT(iMaterial == m_MaterialHash.end());
// Add this geometry in the material use table
pMaterial->addGLC_Geom(this);
// Add the Material to Material hash table
m_MaterialHash.insert(materialID, pMaterial);
// Test if the material is transparent
if (pMaterial->isTransparent() && (m_MaterialHash.size() == 1))
{
setTransparency(true);
}
else if (isTransparent() && !pMaterial->isTransparent())
{
setTransparency(false);
}
// Invalid the geometry
m_GeometryIsValid = false;
}
}
// Add triangles with the same material to the mesh
void GLC_Mesh2::addTriangles(const VertexList &triangles, GLC_Material* pMaterial)
{
// test if the material is already in the mesh
GLC_uint materialID;
if (NULL != pMaterial)
{
materialID= pMaterial->getID();
}
else
{
materialID= 0;
}
IndexList* pCurIndexList= NULL;
if ((materialID == 0) or m_MaterialHash.contains(materialID))
{
pCurIndexList= m_MaterialGroup.value(materialID);
}
else
{
addMaterial(pMaterial);
pCurIndexList= new IndexList;
m_MaterialGroup.insert(materialID, pCurIndexList);
}
const int startVertexIndex= m_Vertex.size();
const int delta= triangles.size();
// Add triangles vertex to the mesh
m_Vertex+= triangles;
for (int i= 0; i < delta; ++i)
{
pCurIndexList->append(startVertexIndex + static_cast<GLuint>(i));
}
// Invalid the geometry
m_GeometryIsValid = false;
m_NumberOfFaces+= delta / 3;
}
// Reverse mesh normal
void GLC_Mesh2::reverseNormal()
{
const int max= m_Vertex.size();
for (int i= 0; i < max; ++i)
{
m_Vertex[i].nx= m_Vertex[i].nx * -1.0f;
m_Vertex[i].ny= m_Vertex[i].ny * -1.0f;
m_Vertex[i].nz= m_Vertex[i].nz * -1.0f;
}
// Invalid the geometry
m_GeometryIsValid = false;
}
// Specific glExecute method
void GLC_Mesh2::glExecute(bool isSelected, bool forceWire)
{
m_IsSelected= isSelected;
GLC_VboGeom::glExecute(isSelected, forceWire);
m_IsSelected= false;
}
//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////
// if the geometry have a texture, load it
void GLC_Mesh2::glLoadTexture(void)
{
// Load texture of the master material
m_pMaterial->glLoadTexture();
MaterialHash::iterator iMaterial= m_MaterialHash.begin();
while (iMaterial != m_MaterialHash.constEnd())
{
// Load texture of mesh materials
iMaterial.value()->glLoadTexture();
++iMaterial;
}
}
// Virtual interface for OpenGL Geometry set up.
void GLC_Mesh2::glDraw()
{
IndexList iboList;
MaterialGroupHash::iterator iMaterialGroup;
// Create VBO and IBO
if (!m_GeometryIsValid)
{
// Create VBO
const GLsizei dataNbr= static_cast<GLsizei>(m_Vertex.size());
const GLsizeiptr dataSize= dataNbr * sizeof(GLC_Vertex);
QVector<GLC_Vertex> vectorVertex(m_Vertex.toVector());
const GLC_Vertex* pPositionData= vectorVertex.data();
glBufferData(GL_ARRAY_BUFFER, dataSize, pPositionData, GL_STATIC_DRAW);
// Create IBO
iMaterialGroup= m_MaterialGroup.begin();
while (iMaterialGroup != m_MaterialGroup.constEnd())
{
if (!iMaterialGroup.value()->isEmpty())
{
iboList+= *(iMaterialGroup.value());
}
++iMaterialGroup;
}
const GLsizei indexNbr= static_cast<GLsizei>(iboList.size());
const GLsizeiptr indexSize = indexNbr * sizeof(GLuint);
QVector<GLuint> vectorIndex(iboList.toVector());
const GLuint* pIndexData= vectorIndex.data();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexSize, pIndexData, GL_STATIC_DRAW);
}
glVertexPointer(3, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(0));
glNormalPointer(GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(12));
glTexCoordPointer(2, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(24));
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
// test if color pear vertex is acivated
if (m_ColorPearVertex and !m_IsSelected)
{
glDisable(GL_LIGHTING);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_FLOAT, sizeof(GLC_Vertex), BUFFER_OFFSET(32));
}
GLC_Material* pCurrentMaterial;
GLuint max;
GLuint cur= 0;
iMaterialGroup= m_MaterialGroup.begin();
while (iMaterialGroup != m_MaterialGroup.constEnd())
{
if (!iMaterialGroup.value()->isEmpty())
{
if (not GLC_State::selectionShaderUsed() or not m_IsSelected)
{
// Set current material
if (iMaterialGroup.key() == 0)
{
// Use default material
pCurrentMaterial= m_pMaterial;
}
else
{
pCurrentMaterial= m_MaterialHash.value(iMaterialGroup.key());
Q_ASSERT(pCurrentMaterial != NULL);
}
// Execute current material
if (pCurrentMaterial->getAddRgbaTexture())
{
glEnable(GL_TEXTURE_2D);
}
else
{
glDisable(GL_TEXTURE_2D);
}
// Activate material
pCurrentMaterial->glExecute();
const GLfloat red= pCurrentMaterial->getDiffuseColor().redF();
const GLfloat green= pCurrentMaterial->getDiffuseColor().greenF();
const GLfloat blue= pCurrentMaterial->getDiffuseColor().blueF();
const GLfloat alpha= pCurrentMaterial->getDiffuseColor().alphaF();
glColor4f(red, green, blue, alpha);
if (m_IsSelected) GLC_SelectionMaterial::glExecute();
}
else
{
// Use Shader
glDisable(GL_TEXTURE_2D);
}
max= static_cast<GLuint>(iMaterialGroup.value()->size());
// Draw cylinder
glDrawRangeElements(GL_TRIANGLES, 0, max, max, GL_UNSIGNED_INT, BUFFER_OFFSET((cur) * sizeof(unsigned int)));
cur+= max;
}
++iMaterialGroup;
}
if (m_ColorPearVertex and !m_IsSelected)
{
glDisableClientState(GL_COLOR_ARRAY);
}
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
// OpenGL error handler
GLenum error= glGetError();
if (error != GL_NO_ERROR)
{
GLC_OpenGlException OpenGlException("GLC_Mesh2::GlDraw ", error);
throw(OpenGlException);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <node/chainstate.h>
#include <consensus/params.h>
#include <node/blockstorage.h>
#include <validation.h>
std::optional<ChainstateLoadingError> LoadChainstate(bool fReset,
ChainstateManager& chainman,
CTxMemPool* mempool,
bool fPruneMode,
const Consensus::Params& consensus_params,
bool fReindexChainState,
int64_t nBlockTreeDBCache,
int64_t nCoinDBCache,
int64_t nCoinCacheUsage,
bool block_tree_db_in_memory,
bool coins_db_in_memory,
std::function<bool()> shutdown_requested,
std::function<void()> coins_error_cb)
{
auto is_coinsview_empty = [&](CChainState* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
return fReset || fReindexChainState || chainstate->CoinsTip().GetBestBlock().IsNull();
};
{
LOCK(cs_main);
chainman.InitializeChainstate(mempool);
chainman.m_total_coinstip_cache = nCoinCacheUsage;
chainman.m_total_coinsdb_cache = nCoinDBCache;
UnloadBlockIndex(mempool, chainman);
auto& pblocktree{chainman.m_blockman.m_block_tree_db};
// new CBlockTreeDB tries to delete the existing file, which
// fails if it's still open from the previous loop. Close it first:
pblocktree.reset();
pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, block_tree_db_in_memory, fReset));
if (fReset) {
pblocktree->WriteReindexing(true);
//If we're reindexing in prune mode, wipe away unusable block files and all undo data files
if (fPruneMode)
CleanupBlockRevFiles();
}
if (shutdown_requested && shutdown_requested()) return ChainstateLoadingError::SHUTDOWN_PROBED;
// LoadBlockIndex will load fHavePruned if we've ever removed a
// block file from disk.
// Note that it also sets fReindex based on the disk flag!
// From here on out fReindex and fReset mean something different!
if (!chainman.LoadBlockIndex()) {
if (shutdown_requested && shutdown_requested()) return ChainstateLoadingError::SHUTDOWN_PROBED;
return ChainstateLoadingError::ERROR_LOADING_BLOCK_DB;
}
if (!chainman.BlockIndex().empty() &&
!chainman.m_blockman.LookupBlockIndex(consensus_params.hashGenesisBlock)) {
return ChainstateLoadingError::ERROR_BAD_GENESIS_BLOCK;
}
// Check for changed -prune state. What we are concerned about is a user who has pruned blocks
// in the past, but is now trying to run unpruned.
if (fHavePruned && !fPruneMode) {
return ChainstateLoadingError::ERROR_PRUNED_NEEDS_REINDEX;
}
// At this point blocktree args are consistent with what's on disk.
// If we're not mid-reindex (based on disk + args), add a genesis block on disk
// (otherwise we use the one already on disk).
// This is called again in ThreadImport after the reindex completes.
if (!fReindex && !chainman.ActiveChainstate().LoadGenesisBlock()) {
return ChainstateLoadingError::ERROR_LOAD_GENESIS_BLOCK_FAILED;
}
// At this point we're either in reindex or we've loaded a useful
// block tree into BlockIndex()!
for (CChainState* chainstate : chainman.GetAll()) {
chainstate->InitCoinsDB(
/* cache_size_bytes */ nCoinDBCache,
/* in_memory */ coins_db_in_memory,
/* should_wipe */ fReset || fReindexChainState);
if (coins_error_cb) {
chainstate->CoinsErrorCatcher().AddReadErrCallback(coins_error_cb);
}
// If necessary, upgrade from older database format.
// This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
if (!chainstate->CoinsDB().Upgrade()) {
return ChainstateLoadingError::ERROR_CHAINSTATE_UPGRADE_FAILED;
}
// ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
if (!chainstate->ReplayBlocks()) {
return ChainstateLoadingError::ERROR_REPLAYBLOCKS_FAILED;
}
// The on-disk coinsdb is now in a good state, create the cache
chainstate->InitCoinsCache(nCoinCacheUsage);
assert(chainstate->CanFlushToDisk());
if (!is_coinsview_empty(chainstate)) {
// LoadChainTip initializes the chain based on CoinsTip()'s best block
if (!chainstate->LoadChainTip()) {
return ChainstateLoadingError::ERROR_LOADCHAINTIP_FAILED;
}
assert(chainstate->m_chain.Tip() != nullptr);
}
}
}
if (!fReset) {
LOCK(cs_main);
auto chainstates{chainman.GetAll()};
if (std::any_of(chainstates.begin(), chainstates.end(),
[](const CChainState* cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->NeedsRedownload(); })) {
return ChainstateLoadingError::ERROR_BLOCKS_WITNESS_INSUFFICIENTLY_VALIDATED;
}
}
return std::nullopt;
}
std::optional<ChainstateLoadVerifyError> VerifyLoadedChainstate(ChainstateManager& chainman,
bool fReset,
bool fReindexChainState,
const Consensus::Params& consensus_params,
unsigned int check_blocks,
unsigned int check_level,
std::function<int64_t()> get_unix_time_seconds)
{
auto is_coinsview_empty = [&](CChainState* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
return fReset || fReindexChainState || chainstate->CoinsTip().GetBestBlock().IsNull();
};
{
LOCK(cs_main);
for (CChainState* chainstate : chainman.GetAll()) {
if (!is_coinsview_empty(chainstate)) {
const CBlockIndex* tip = chainstate->m_chain.Tip();
if (tip && tip->nTime > get_unix_time_seconds() + 2 * 60 * 60) {
return ChainstateLoadVerifyError::ERROR_BLOCK_FROM_FUTURE;
}
if (!CVerifyDB().VerifyDB(
*chainstate, consensus_params, chainstate->CoinsDB(),
check_level,
check_blocks)) {
return ChainstateLoadVerifyError::ERROR_CORRUPTED_BLOCK_DB;
}
}
}
}
return std::nullopt;
}
<commit_msg>Collapse the 2 cs_main locks in LoadChainstate<commit_after>// Copyright (c) 2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <node/chainstate.h>
#include <consensus/params.h>
#include <node/blockstorage.h>
#include <validation.h>
std::optional<ChainstateLoadingError> LoadChainstate(bool fReset,
ChainstateManager& chainman,
CTxMemPool* mempool,
bool fPruneMode,
const Consensus::Params& consensus_params,
bool fReindexChainState,
int64_t nBlockTreeDBCache,
int64_t nCoinDBCache,
int64_t nCoinCacheUsage,
bool block_tree_db_in_memory,
bool coins_db_in_memory,
std::function<bool()> shutdown_requested,
std::function<void()> coins_error_cb)
{
auto is_coinsview_empty = [&](CChainState* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
return fReset || fReindexChainState || chainstate->CoinsTip().GetBestBlock().IsNull();
};
{
LOCK(cs_main);
chainman.InitializeChainstate(mempool);
chainman.m_total_coinstip_cache = nCoinCacheUsage;
chainman.m_total_coinsdb_cache = nCoinDBCache;
UnloadBlockIndex(mempool, chainman);
auto& pblocktree{chainman.m_blockman.m_block_tree_db};
// new CBlockTreeDB tries to delete the existing file, which
// fails if it's still open from the previous loop. Close it first:
pblocktree.reset();
pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, block_tree_db_in_memory, fReset));
if (fReset) {
pblocktree->WriteReindexing(true);
//If we're reindexing in prune mode, wipe away unusable block files and all undo data files
if (fPruneMode)
CleanupBlockRevFiles();
}
if (shutdown_requested && shutdown_requested()) return ChainstateLoadingError::SHUTDOWN_PROBED;
// LoadBlockIndex will load fHavePruned if we've ever removed a
// block file from disk.
// Note that it also sets fReindex based on the disk flag!
// From here on out fReindex and fReset mean something different!
if (!chainman.LoadBlockIndex()) {
if (shutdown_requested && shutdown_requested()) return ChainstateLoadingError::SHUTDOWN_PROBED;
return ChainstateLoadingError::ERROR_LOADING_BLOCK_DB;
}
if (!chainman.BlockIndex().empty() &&
!chainman.m_blockman.LookupBlockIndex(consensus_params.hashGenesisBlock)) {
return ChainstateLoadingError::ERROR_BAD_GENESIS_BLOCK;
}
// Check for changed -prune state. What we are concerned about is a user who has pruned blocks
// in the past, but is now trying to run unpruned.
if (fHavePruned && !fPruneMode) {
return ChainstateLoadingError::ERROR_PRUNED_NEEDS_REINDEX;
}
// At this point blocktree args are consistent with what's on disk.
// If we're not mid-reindex (based on disk + args), add a genesis block on disk
// (otherwise we use the one already on disk).
// This is called again in ThreadImport after the reindex completes.
if (!fReindex && !chainman.ActiveChainstate().LoadGenesisBlock()) {
return ChainstateLoadingError::ERROR_LOAD_GENESIS_BLOCK_FAILED;
}
// At this point we're either in reindex or we've loaded a useful
// block tree into BlockIndex()!
for (CChainState* chainstate : chainman.GetAll()) {
chainstate->InitCoinsDB(
/* cache_size_bytes */ nCoinDBCache,
/* in_memory */ coins_db_in_memory,
/* should_wipe */ fReset || fReindexChainState);
if (coins_error_cb) {
chainstate->CoinsErrorCatcher().AddReadErrCallback(coins_error_cb);
}
// If necessary, upgrade from older database format.
// This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
if (!chainstate->CoinsDB().Upgrade()) {
return ChainstateLoadingError::ERROR_CHAINSTATE_UPGRADE_FAILED;
}
// ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
if (!chainstate->ReplayBlocks()) {
return ChainstateLoadingError::ERROR_REPLAYBLOCKS_FAILED;
}
// The on-disk coinsdb is now in a good state, create the cache
chainstate->InitCoinsCache(nCoinCacheUsage);
assert(chainstate->CanFlushToDisk());
if (!is_coinsview_empty(chainstate)) {
// LoadChainTip initializes the chain based on CoinsTip()'s best block
if (!chainstate->LoadChainTip()) {
return ChainstateLoadingError::ERROR_LOADCHAINTIP_FAILED;
}
assert(chainstate->m_chain.Tip() != nullptr);
}
}
if (!fReset) {
auto chainstates{chainman.GetAll()};
if (std::any_of(chainstates.begin(), chainstates.end(),
[](const CChainState* cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->NeedsRedownload(); })) {
return ChainstateLoadingError::ERROR_BLOCKS_WITNESS_INSUFFICIENTLY_VALIDATED;
}
}
}
return std::nullopt;
}
std::optional<ChainstateLoadVerifyError> VerifyLoadedChainstate(ChainstateManager& chainman,
bool fReset,
bool fReindexChainState,
const Consensus::Params& consensus_params,
unsigned int check_blocks,
unsigned int check_level,
std::function<int64_t()> get_unix_time_seconds)
{
auto is_coinsview_empty = [&](CChainState* chainstate) EXCLUSIVE_LOCKS_REQUIRED(::cs_main) {
return fReset || fReindexChainState || chainstate->CoinsTip().GetBestBlock().IsNull();
};
{
LOCK(cs_main);
for (CChainState* chainstate : chainman.GetAll()) {
if (!is_coinsview_empty(chainstate)) {
const CBlockIndex* tip = chainstate->m_chain.Tip();
if (tip && tip->nTime > get_unix_time_seconds() + 2 * 60 * 60) {
return ChainstateLoadVerifyError::ERROR_BLOCK_FROM_FUTURE;
}
if (!CVerifyDB().VerifyDB(
*chainstate, consensus_params, chainstate->CoinsDB(),
check_level,
check_blocks)) {
return ChainstateLoadVerifyError::ERROR_CORRUPTED_BLOCK_DB;
}
}
}
}
return std::nullopt;
}
<|endoftext|> |
<commit_before>#include "CAssembler.h"
#include <sstream>
#include <iostream>
CAssembler::CAssembler()
{
m_lexer.addKeyword("func");
m_lexer.addKeyword("extern");
m_lexer.addKeyword("calle");
m_lexer.addKeyword("pushi");
m_lexer.addKeyword("pushf");
// Disable emitting of newline token
m_lexer.ignoreNewLine(true);
}
bool CAssembler::assemble(std::istream& asmCode, std::ostream& byteCode)
{
m_functions.clear();
m_externFunctions.clear();
m_strings.clear();
// Parse code
do
{
m_lexer.lex(asmCode);
// At the top level of the assembly code are allowed
// - extern function declares, which hold name and parameter count information
// - function declare/definition, groups assembly instructions for the script function
// - comments, which are ignored
switch (m_lexer.getToken())
{
case ELexerToken::Keyword:
if (m_lexer.getLexeme() == "func")
{
// Script function
if (!parseFunction(asmCode))
{
std::cout << "Parse function failed." << std::endl;
return false;
}
}
else if (m_lexer.getLexeme() == "extern")
{
// Extern function
if (!parseExternFunction(asmCode))
{
std::cout << "Parse extern function failed." << std::endl;
return false;
}
}
break;
case ELexerToken::Comment:
case ELexerToken::NewLine:
case ELexerToken::End:
// Ignore
break;
default:
// Invalid token
std::cout << "Invalid token: " << m_lexer.getLexeme() << ", " << (int) m_lexer.getToken() << std::endl;
return false;
}
}
while (m_lexer.getToken() != ELexerToken::End);
std::cout << "Serializing" << std::endl;
// Serialize to byte code
if (!serializeStrings(byteCode))
{
std::cout << "Serialize strings failed" << std::endl;
return false;
}
if (!serializeExternFunctions(byteCode))
{
std::cout << "Serialize extern functions failed" << std::endl;
return false;
}
if (!serializeFunctions(byteCode))
{
std::cout << "Serialize functions failed" << std::endl;
return false;
}
return true;
}
bool CAssembler::parseFunction(std::istream& stream)
{
// 'func' keyword already parsed, next is identifier
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::Identifier)
{
return false;
}
// Store function name
SFunction function;
function.name = m_lexer.getLexeme();
// Next is '{'
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::OpenBrace)
{
return false;
}
do
{
SInstruction instruction;
m_lexer.lex(stream);
switch (m_lexer.getToken())
{
case ELexerToken::Keyword:
if (m_lexer.getLexeme() == "pushi")
{
// Push integer instruction
instruction.id = EInstructon::Pushi;
// Expects one integer constant as argument
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::Integer)
{
std::cout << "Unexpected token: " << m_lexer.getLexeme() << std::endl;
return false;
}
// TODO Slow!!!
std::stringstream ss;
ss << m_lexer.getLexeme();
ss >> instruction.args[0];
}
if (m_lexer.getLexeme() == "pushf")
{
// Push float instruction
instruction.id = EInstructon::Pushf;
// Expects one float constant as argument
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::Float)
{
std::cout << "Unexpected token: " << m_lexer.getLexeme() << std::endl;
return false;
}
// TODO Slow!!!
std::stringstream ss;
ss << m_lexer.getLexeme();
float temp;
ss >> temp;
// Store float binary data in arg
memcpy((void*) &instruction.args[0], (void*) &temp, sizeof(float));
}
else if (m_lexer.getLexeme() == "pushs")
{
// Push string instruction
instruction.id = EInstructon::Pushs;
// Expects one string constant as argumment
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::String)
{
std::cout << "Unexpected token: " << m_lexer.getLexeme() << std::endl;
return false;
}
// TODO Add string to strings list and write id
return false;
}
else if (m_lexer.getLexeme() == "calle")
{
// Call extern function instruction
instruction.id = EInstructon::Calle;
// Expects one identifier
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::Identifier)
{
std::cout << "Unexpected token: " << m_lexer.getLexeme() << std::endl;
return false;
}
// Identifier must be extern function
if (!isExternFunction(m_lexer.getLexeme()))
{
std::cout << "The identifier is not an extern function: " << m_lexer.getLexeme() << std::endl;
return false;
}
// Set function index
instruction.args[0] = getExternFunctionId(m_lexer.getLexeme());
}
// Add assembled instruction
function.instructions.push_back(instruction);
break;
case ELexerToken::Comment:
case ELexerToken::NewLine:
case ELexerToken::CloseBrace:
// Ignore
break;
default:
std::cout << "Invalid token: '" << m_lexer.getLexeme() << "', " << (int)m_lexer.getToken() << std::endl;
return false;
}
}
while (m_lexer.getToken() != ELexerToken::CloseBrace);
// Add assembled function
m_functions.push_back(function);
return true;
}
bool CAssembler::parseExternFunction(std::istream& stream)
{
// 'extern* keyword already parsed, next is identifier
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::Identifier)
{
return false;
}
// Create extern function and store name
SExternFunction externFunction;
externFunction.name = m_lexer.getLexeme();
// Next is integer constant which denotes the number of expected arguments
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::Integer)
{
return false;
}
// String to int convert
// TODO SLOW!!
std::stringstream ss;
ss << m_lexer.getLexeme();
int temp;
ss >> temp;
externFunction.argCount = temp;
// Add extern function
m_externFunctions.push_back(externFunction);
return true;
}
bool CAssembler::isExternFunction(const std::string& name)
{
// Linear search
// TODO Slow?
for (const auto& externFunction : m_externFunctions)
{
if (externFunction.name == name)
{
return true;
}
}
return false;
}
int32_t CAssembler::getExternFunctionId(const std::string& name)
{
// Linear search
// TODO Slow?
int32_t index = 0;
for (const auto& externFunction : m_externFunctions)
{
if (externFunction.name == name)
{
return index;
}
++index;
}
return -1;
}
bool CAssembler::serializeStrings(std::ostream& stream) const
{
// Write string count
uint32_t size = m_strings.size();
stream.write((char*)&size, 4);
// Serialize strings
for (const auto& str : m_strings)
{
// Write size
uint32_t length = str.length();
stream.write((char*)&length, 4);
// Write data
stream.write(str.data(), length);
}
return stream.good();
}
bool CAssembler::serializeExternFunctions(std::ostream& stream) const
{
// Write extern function count
uint32_t size = m_externFunctions.size();
stream.write((char*)&size, 4);
// Serialize extern functions
for (const auto& externFunction : m_externFunctions)
{
// Serialize extern function
if (!serialize(externFunction, stream))
{
return false;
}
}
return stream.good();
}
bool CAssembler::serializeFunctions(std::ostream& stream) const
{
// Write function count
uint32_t size = m_functions.size();
stream.write((char*)&size, sizeof(size));
// Serialize functions
for (const auto& function : m_functions)
{
// Write name
// Write size
uint32_t length = function.name.length();
stream.write((char*)&length, sizeof(length));
// Write data
stream.write(function.name.data(), length);
// Write instructions
// Write instruction size
size = function.instructions.size();
stream.write((char*)&size, sizeof(size));
for (const auto& instruction : function.instructions)
{
if (!serialize(instruction, stream))
{
return false;
}
}
}
return stream.good();
}<commit_msg>Added call keyword to assembler<commit_after>#include "CAssembler.h"
#include <sstream>
#include <iostream>
CAssembler::CAssembler()
{
m_lexer.addKeyword("func");
m_lexer.addKeyword("extern");
m_lexer.addKeyword("calle");
m_lexer.addKeyword("call");
m_lexer.addKeyword("pushi");
m_lexer.addKeyword("pushf");
// Disable emitting of newline token
m_lexer.ignoreNewLine(true);
}
bool CAssembler::assemble(std::istream& asmCode, std::ostream& byteCode)
{
m_functions.clear();
m_externFunctions.clear();
m_strings.clear();
// Parse code
do
{
m_lexer.lex(asmCode);
// At the top level of the assembly code are allowed
// - extern function declares, which hold name and parameter count information
// - function declare/definition, groups assembly instructions for the script function
// - comments, which are ignored
switch (m_lexer.getToken())
{
case ELexerToken::Keyword:
if (m_lexer.getLexeme() == "func")
{
// Script function
if (!parseFunction(asmCode))
{
std::cout << "Parse function failed." << std::endl;
return false;
}
}
else if (m_lexer.getLexeme() == "extern")
{
// Extern function
if (!parseExternFunction(asmCode))
{
std::cout << "Parse extern function failed." << std::endl;
return false;
}
}
break;
case ELexerToken::Comment:
case ELexerToken::NewLine:
case ELexerToken::End:
// Ignore
break;
default:
// Invalid token
std::cout << "Invalid token: " << m_lexer.getLexeme() << ", " << (int) m_lexer.getToken() << std::endl;
return false;
}
}
while (m_lexer.getToken() != ELexerToken::End);
std::cout << "Serializing" << std::endl;
// Serialize to byte code
if (!serializeStrings(byteCode))
{
std::cout << "Serialize strings failed" << std::endl;
return false;
}
if (!serializeExternFunctions(byteCode))
{
std::cout << "Serialize extern functions failed" << std::endl;
return false;
}
if (!serializeFunctions(byteCode))
{
std::cout << "Serialize functions failed" << std::endl;
return false;
}
return true;
}
bool CAssembler::parseFunction(std::istream& stream)
{
// 'func' keyword already parsed, next is identifier
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::Identifier)
{
return false;
}
// Store function name
SFunction function;
function.name = m_lexer.getLexeme();
// Next is '{'
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::OpenBrace)
{
return false;
}
do
{
SInstruction instruction;
m_lexer.lex(stream);
switch (m_lexer.getToken())
{
case ELexerToken::Keyword:
if (m_lexer.getLexeme() == "pushi")
{
// Push integer instruction
instruction.id = EInstructon::Pushi;
// Expects one integer constant as argument
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::Integer)
{
std::cout << "Unexpected token: " << m_lexer.getLexeme() << std::endl;
return false;
}
// TODO Slow!!!
std::stringstream ss;
ss << m_lexer.getLexeme();
ss >> instruction.args[0];
}
if (m_lexer.getLexeme() == "pushf")
{
// Push float instruction
instruction.id = EInstructon::Pushf;
// Expects one float constant as argument
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::Float)
{
std::cout << "Unexpected token: " << m_lexer.getLexeme() << std::endl;
return false;
}
// TODO Slow!!!
std::stringstream ss;
ss << m_lexer.getLexeme();
float temp;
ss >> temp;
// Store float binary data in arg
memcpy((void*) &instruction.args[0], (void*) &temp, sizeof(float));
}
else if (m_lexer.getLexeme() == "pushs")
{
// Push string instruction
instruction.id = EInstructon::Pushs;
// Expects one string constant as argumment
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::String)
{
std::cout << "Unexpected token: " << m_lexer.getLexeme() << std::endl;
return false;
}
// TODO Add string to strings list and write id
return false;
}
else if (m_lexer.getLexeme() == "calle")
{
// Call extern function instruction
instruction.id = EInstructon::Calle;
// Expects one identifier
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::Identifier)
{
std::cout << "Unexpected token: " << m_lexer.getLexeme() << std::endl;
return false;
}
// Identifier must be extern function
if (!isExternFunction(m_lexer.getLexeme()))
{
std::cout << "The identifier is not an extern function: " << m_lexer.getLexeme() << std::endl;
return false;
}
// Set function index
instruction.args[0] = getExternFunctionId(m_lexer.getLexeme());
}
// Add assembled instruction
function.instructions.push_back(instruction);
break;
case ELexerToken::Comment:
case ELexerToken::NewLine:
case ELexerToken::CloseBrace:
// Ignore
break;
default:
std::cout << "Invalid token: '" << m_lexer.getLexeme() << "', " << (int)m_lexer.getToken() << std::endl;
return false;
}
}
while (m_lexer.getToken() != ELexerToken::CloseBrace);
// Add assembled function
m_functions.push_back(function);
return true;
}
bool CAssembler::parseExternFunction(std::istream& stream)
{
// 'extern* keyword already parsed, next is identifier
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::Identifier)
{
return false;
}
// Create extern function and store name
SExternFunction externFunction;
externFunction.name = m_lexer.getLexeme();
// Next is integer constant which denotes the number of expected arguments
m_lexer.lex(stream);
if (m_lexer.getToken() != ELexerToken::Integer)
{
return false;
}
// String to int convert
// TODO SLOW!!
std::stringstream ss;
ss << m_lexer.getLexeme();
int temp;
ss >> temp;
externFunction.argCount = temp;
// Add extern function
m_externFunctions.push_back(externFunction);
return true;
}
bool CAssembler::isExternFunction(const std::string& name)
{
// Linear search
// TODO Slow?
for (const auto& externFunction : m_externFunctions)
{
if (externFunction.name == name)
{
return true;
}
}
return false;
}
int32_t CAssembler::getExternFunctionId(const std::string& name)
{
// Linear search
// TODO Slow?
int32_t index = 0;
for (const auto& externFunction : m_externFunctions)
{
if (externFunction.name == name)
{
return index;
}
++index;
}
return -1;
}
bool CAssembler::serializeStrings(std::ostream& stream) const
{
// Write string count
uint32_t size = m_strings.size();
stream.write((char*)&size, 4);
// Serialize strings
for (const auto& str : m_strings)
{
// Write size
uint32_t length = str.length();
stream.write((char*)&length, 4);
// Write data
stream.write(str.data(), length);
}
return stream.good();
}
bool CAssembler::serializeExternFunctions(std::ostream& stream) const
{
// Write extern function count
uint32_t size = m_externFunctions.size();
stream.write((char*)&size, 4);
// Serialize extern functions
for (const auto& externFunction : m_externFunctions)
{
// Serialize extern function
if (!serialize(externFunction, stream))
{
return false;
}
}
return stream.good();
}
bool CAssembler::serializeFunctions(std::ostream& stream) const
{
// Write function count
uint32_t size = m_functions.size();
stream.write((char*)&size, sizeof(size));
// Serialize functions
for (const auto& function : m_functions)
{
// Write name
// Write size
uint32_t length = function.name.length();
stream.write((char*)&length, sizeof(length));
// Write data
stream.write(function.name.data(), length);
// Write instructions
// Write instruction size
size = function.instructions.size();
stream.write((char*)&size, sizeof(size));
for (const auto& instruction : function.instructions)
{
if (!serialize(instruction, stream))
{
return false;
}
}
}
return stream.good();
}<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/platform_util.h"
#include "base/logging.h"
#include "ui/aura/window.h"
namespace platform_util {
gfx::NativeWindow GetTopLevel(gfx::NativeView view) {
return view->GetToplevelWindow();
}
gfx::NativeView GetParent(gfx::NativeView view) {
return view->parent();
}
bool IsWindowActive(gfx::NativeWindow window) {
NOTIMPLEMENTED();
return false;
}
void ActivateWindow(gfx::NativeWindow window) {
NOTIMPLEMENTED();
}
bool IsVisible(gfx::NativeView view) {
return view->IsVisible();
}
} // namespace platform_util
<commit_msg>Include the right header in runtime_platform_util_aura.cc.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/runtime/browser/runtime_platform_util.h"
#include "base/logging.h"
#include "ui/aura/window.h"
namespace platform_util {
gfx::NativeWindow GetTopLevel(gfx::NativeView view) {
return view->GetToplevelWindow();
}
gfx::NativeView GetParent(gfx::NativeView view) {
return view->parent();
}
bool IsWindowActive(gfx::NativeWindow window) {
NOTIMPLEMENTED();
return false;
}
void ActivateWindow(gfx::NativeWindow window) {
NOTIMPLEMENTED();
}
bool IsVisible(gfx::NativeView view) {
return view->IsVisible();
}
} // namespace platform_util
<|endoftext|> |
<commit_before>#include "TPDGCode.h"
#include "TFile.h"
#include "TTree.h"
#include "TEventList.h"
#include "TObjArray.h"
#include "TH2.h"
#include "AliLog.h"
#include "AliESDtrack.h"
#include "AliTrackReference.h"
#include "AliTRDReconstructor.h"
#include "AliTRDtrackV1.h"
#include "AliTRDseedV1.h"
#include "AliTRDpidRefMaker.h"
#include "info/AliTRDv0Info.h"
#include "info/AliTRDpidInfo.h"
// Defines and implements basic functionality for building reference data for TRD PID.
//
// Here is the list of functionality provided by this class
// 1.
// 2.
//
// Authors:
// Alex Bercuci <A.Bercuci@gsi.de>
// Alex Wilk <wilka@uni-muenster.de>
// Markus Fasel <mfasel@gsi.de>
// Markus Heide <mheide@uni-muenster.de>
//
ClassImp(AliTRDpidRefMaker)
//________________________________________________________________________
AliTRDpidRefMaker::AliTRDpidRefMaker()
:AliTRDrecoTask()
,fReconstructor(NULL)
,fV0s(NULL)
,fData(NULL)
,fInfo(NULL)
,fPIDdataArray(NULL)
,fRefPID(kMC)
,fRefP(kMC)
,fFreq(1.)
,fP(-1.)
,fPthreshold(0.)
{
//
// Default constructor
//
SetNameTitle("PIDrefMaker", "PID Reference Maker");
}
//________________________________________________________________________
AliTRDpidRefMaker::AliTRDpidRefMaker(const char *name, const char *title)
:AliTRDrecoTask(name, title)
,fReconstructor(NULL)
,fV0s(NULL)
,fData(NULL)
,fInfo(NULL)
,fPIDdataArray(NULL)
,fRefPID(kMC)
,fRefP(kMC)
,fFreq(1.)
,fP(-1.)
,fPthreshold(0.5)
{
//
// Default constructor
//
fReconstructor = new AliTRDReconstructor();
fReconstructor->SetRecoParam(AliTRDrecoParam::GetLowFluxParam());
memset(fdEdx, 0, 10*sizeof(Float_t));
memset(fPID, 0, AliPID::kSPECIES*sizeof(Float_t));
DefineInput(2, TObjArray::Class()); // v0 list
DefineInput(3, TObjArray::Class()); // pid info list
DefineOutput(2, TTree::Class());
}
//________________________________________________________________________
AliTRDpidRefMaker::~AliTRDpidRefMaker()
{
if(fPIDdataArray) delete fPIDdataArray;
if(fReconstructor) delete fReconstructor;
}
//________________________________________________________________________
Bool_t AliTRDpidRefMaker::CheckQuality(AliTRDseedV1* /*trklt*/)
{
// Place holder for checking tracklet quality for PID.
return kTRUE;
}
//________________________________________________________________________
Float_t* AliTRDpidRefMaker::CookdEdx(AliTRDseedV1 *trklt)
{
trklt->CookdEdx(AliTRDpidUtil::kNNslices);
memcpy(fdEdx, trklt->GetdEdx(), AliTRDpidUtil::kNNslices*sizeof(Float_t));
return fdEdx;
}
//________________________________________________________________________
void AliTRDpidRefMaker::UserCreateOutputObjects()
{
// Create histograms
// Called once
fContainer = new TObjArray();
fContainer->SetName(Form("Moni%s", GetName()));
TH2 *h2 = new TH2I("hPDG","Particle abundance", AliPID::kSPECIES, -0.5, 4.5, AliTRDCalPID::kNMom, -0.5, AliTRDCalPID::kNMom-0.5);
TAxis *ax = h2->GetXaxis();
ax->SetNdivisions(505);
ax->SetTitle("Particle species");
for(Int_t is=AliPID::kSPECIES; is--;) ax->SetBinLabel(is+1, AliPID::ParticleShortName(is));
h2->GetYaxis()->SetTitle("P bins");
h2->GetYaxis()->SetNdivisions(511);
fContainer->AddAt(h2, 0);
fData = new TTree("RefPID", "Reference data for PID");
fData->Branch("data", &fPIDdataArray);
}
//________________________________________________________________________
void AliTRDpidRefMaker::UserExec(Option_t *)
{
// Main loop
// Called for each event
if(!(fTracks = dynamic_cast<TObjArray*>(GetInputData(1)))) return;
if(!(fV0s = dynamic_cast<TObjArray*>(GetInputData(2)))) return;
if(!(fInfo = dynamic_cast<TObjArray*>(GetInputData(3)))) return;
AliDebug(1, Form("Entries: Tracks[%d] V0[%d] PID[%d]", fTracks->GetEntriesFast(), fV0s->GetEntriesFast(), fInfo->GetEntriesFast()));
AliTRDtrackInfo *track = NULL;
AliTRDtrackV1 *trackTRD = NULL;
AliTrackReference *ref = NULL;
const AliTRDtrackInfo::AliESDinfo *infoESD = NULL;
for(Int_t itrk=0; itrk<fTracks->GetEntriesFast(); itrk++){
track = (AliTRDtrackInfo*)fTracks->UncheckedAt(itrk);
if(!track->HasESDtrack()) continue;
trackTRD = track->GetTrack();
infoESD = track->GetESDinfo();
Double32_t *infoPID = infoESD->GetSliceIter();
Int_t n = infoESD->GetNSlices() - AliTRDgeometry::kNlayer;
if(n==0){
AliWarning(Form("dEdx info missing in ESD track %d", itrk));
continue;
}
Double32_t *p = &infoPID[n];
AliDebug(4, Form("n[%d] p[GeV/c]{%6.2f %6.2f %6.2f %6.2f %6.2f %6.2f}", n, p[0], p[1], p[2], p[3], p[4], p[5]));
ULong_t status = track->GetStatus();
if(!(status&AliESDtrack::kTPCout)) continue;
// fill the pid information
SetRefPID(fRefPID, track, fPID);
// get particle type
Int_t idx(TMath::LocMax(AliPID::kSPECIES, fPID));
if(idx == 0 && fPID[0]<1.e-5) continue;
// prepare PID data array
if(!fPIDdataArray){
fPIDdataArray = new AliTRDpidInfo();
} else fPIDdataArray->Reset();
fPIDdataArray->SetPID(idx);
// fill PID information
for(Int_t ily = 0; ily < AliTRDgeometry::kNlayer; ily++){
// fill P & dE/dx information
if(HasFriends()){ // from TRD track
if(!trackTRD) continue;
AliTRDseedV1 *trackletTRD(NULL);
trackTRD -> SetReconstructor(fReconstructor);
if(!(trackletTRD = trackTRD -> GetTracklet(ily))) continue;
if(!CheckQuality(trackletTRD)) continue;
if(!CookdEdx(trackletTRD)) continue;
// fill momentum information
fP = 0.;
switch(fRefP){
case kMC:
if(!(ref = track->GetTrackRef(trackletTRD))) continue;
fP = ref->P();
break;
case kRec:
fP = trackletTRD->GetMomentum();
break;
default: continue;
}
} else { // from ESD track
// fill momentum information
switch(fRefP){
case kMC:
if(!(ref = track->GetTrackRef(ily))) continue;
fP = ref->P();
break;
case kRec:
fP = p[ily];
break;
default: continue;
}
Double32_t *it = &infoPID[ily*AliTRDCalPID::kNSlicesNN];
for(Int_t is=AliTRDCalPID::kNSlicesNN; is--; it++) fdEdx[is] = (*it);
}
// momentum threshold
if(fP < fPthreshold) continue;
// store information
fPIDdataArray->PushBack(ily, AliTRDpidUtil::GetMomentumBin(fP), fdEdx);
}
Fill();
}
PostData(1, fContainer);
PostData(2, fData);
}
//________________________________________________________________________
void AliTRDpidRefMaker::Fill()
{
// Fill data tree
if(!fPIDdataArray->GetNtracklets()) return;
// Fill data tree
fData->Fill();
// fill monitor
for(Int_t itrklt=fPIDdataArray->GetNtracklets(); itrklt--;){
Int_t pBin = fPIDdataArray->GetData(itrklt)->Momentum();
((TH2*)fContainer->At(0))->Fill(fPIDdataArray->GetPID(), pBin);
}
}
//________________________________________________________________________
void AliTRDpidRefMaker::LinkPIDdata()
{
// Link data tree to data members
fData->SetBranchAddress("data", &fPIDdataArray);
}
//________________________________________________________________________
void AliTRDpidRefMaker::SetRefPID(ETRDpidRefMakerSource select, AliTRDtrackInfo *track, Float_t *pid)
{
// Fill the reference PID values "pid" from "source" object
// according to the option "select". Possible options are
// - kV0 - v0 based PID
// - kMC - MC truth [default]
// - kRec - outside detectors
if(!track){
AliError("No trackInfo found");
return;
}
memset(fPID, 0, AliPID::kSPECIES*sizeof(Float_t));
switch(select){
case kV0:
{
//Get V0 PID decisions from the AliTRDv0Info for all particle species (implemented so far : electrons from conversions, pions from K0s and protons from Lambdas) :
AliTRDv0Info *v0(NULL);
for(Int_t iv(0); iv<fV0s->GetEntriesFast(); iv++){
if(!(v0 = (AliTRDv0Info*)fV0s->At(iv))) continue;
if(!v0->HasTrack(track)) continue;
for(Int_t is=AliPID::kSPECIES; is--;) fPID[is] = v0->GetPID(is, track);
break;
}
}
break;
case kMC:
if(!HasMCdata()){
AliError("Could not retrive reference PID from MC");
return;
}
switch(track->GetPDG()){
case kElectron:
case kPositron:
fPID[AliPID::kElectron] = 1.;
break;
case kMuonPlus:
case kMuonMinus:
fPID[AliPID::kMuon] = 1.;
break;
case kPiPlus:
case kPiMinus:
fPID[AliPID::kPion] = 1.;
break;
case kKPlus:
case kKMinus:
fPID[AliPID::kKaon] = 1.;
break;
case kProton:
case kProtonBar:
fPID[AliPID::kProton] = 1.;
break;
}
break;
case kRec:
{
AliTRDtrackV1 *trackTRD = track->GetTrack();
trackTRD -> SetReconstructor(fReconstructor);
//fReconstructor -> SetOption("nn");
trackTRD -> CookPID();
for(Int_t iPart = 0; iPart < AliPID::kSPECIES; iPart++){
pid[iPart] = trackTRD -> GetPID(iPart);
AliDebug(4, Form("PDG is (in V0info) %d %f", iPart, pid[iPart]));
}
}
break;
default:
AliWarning("PID reference source not implemented");
return;
}
AliDebug(4, Form("Ref PID [%] : %s[%5.2f] %s[%5.2f] %s[%5.2f] %s[%5.2f] %s[%5.2f]"
,AliPID::ParticleShortName(0), 1.e2*fPID[0]
,AliPID::ParticleShortName(1), 1.e2*fPID[1]
,AliPID::ParticleShortName(2), 1.e2*fPID[2]
,AliPID::ParticleShortName(3), 1.e2*fPID[3]
,AliPID::ParticleShortName(4), 1.e2*fPID[4]
));
}
//________________________________________________________________________
void AliTRDpidRefMaker::SetAbundance(Float_t train)
{
// Split data sample between trainning and testing
if(train<0. || train >1.){
AliWarning("The input data should be in the interval [0, 1]");
return;
}
fFreq = train;
}
<commit_msg>Set acceptance condition on kTRDpid (Alex W)<commit_after>#include "TPDGCode.h"
#include "TFile.h"
#include "TTree.h"
#include "TEventList.h"
#include "TObjArray.h"
#include "TH2.h"
#include "AliLog.h"
#include "AliESDtrack.h"
#include "AliTrackReference.h"
#include "AliTRDReconstructor.h"
#include "AliTRDtrackV1.h"
#include "AliTRDseedV1.h"
#include "AliTRDpidRefMaker.h"
#include "info/AliTRDv0Info.h"
#include "info/AliTRDpidInfo.h"
// Defines and implements basic functionality for building reference data for TRD PID.
//
// Here is the list of functionality provided by this class
// 1.
// 2.
//
// Authors:
// Alex Bercuci <A.Bercuci@gsi.de>
// Alex Wilk <wilka@uni-muenster.de>
// Markus Fasel <mfasel@gsi.de>
// Markus Heide <mheide@uni-muenster.de>
//
ClassImp(AliTRDpidRefMaker)
//________________________________________________________________________
AliTRDpidRefMaker::AliTRDpidRefMaker()
:AliTRDrecoTask()
,fReconstructor(NULL)
,fV0s(NULL)
,fData(NULL)
,fInfo(NULL)
,fPIDdataArray(NULL)
,fRefPID(kMC)
,fRefP(kMC)
,fFreq(1.)
,fP(-1.)
,fPthreshold(0.)
{
//
// Default constructor
//
SetNameTitle("PIDrefMaker", "PID Reference Maker");
}
//________________________________________________________________________
AliTRDpidRefMaker::AliTRDpidRefMaker(const char *name, const char *title)
:AliTRDrecoTask(name, title)
,fReconstructor(NULL)
,fV0s(NULL)
,fData(NULL)
,fInfo(NULL)
,fPIDdataArray(NULL)
,fRefPID(kMC)
,fRefP(kMC)
,fFreq(1.)
,fP(-1.)
,fPthreshold(0.5)
{
//
// Default constructor
//
fReconstructor = new AliTRDReconstructor();
fReconstructor->SetRecoParam(AliTRDrecoParam::GetLowFluxParam());
memset(fdEdx, 0, 10*sizeof(Float_t));
memset(fPID, 0, AliPID::kSPECIES*sizeof(Float_t));
DefineInput(2, TObjArray::Class()); // v0 list
DefineInput(3, TObjArray::Class()); // pid info list
DefineOutput(2, TTree::Class());
}
//________________________________________________________________________
AliTRDpidRefMaker::~AliTRDpidRefMaker()
{
if(fPIDdataArray) delete fPIDdataArray;
if(fReconstructor) delete fReconstructor;
}
//________________________________________________________________________
Bool_t AliTRDpidRefMaker::CheckQuality(AliTRDseedV1* /*trklt*/)
{
// Place holder for checking tracklet quality for PID.
return kTRUE;
}
//________________________________________________________________________
Float_t* AliTRDpidRefMaker::CookdEdx(AliTRDseedV1 *trklt)
{
trklt->CookdEdx(AliTRDpidUtil::kNNslices);
memcpy(fdEdx, trklt->GetdEdx(), AliTRDpidUtil::kNNslices*sizeof(Float_t));
return fdEdx;
}
//________________________________________________________________________
void AliTRDpidRefMaker::UserCreateOutputObjects()
{
// Create histograms
// Called once
fContainer = new TObjArray();
fContainer->SetName(Form("Moni%s", GetName()));
TH2 *h2 = new TH2I("hPDG","Particle abundance", AliPID::kSPECIES, -0.5, 4.5, AliTRDCalPID::kNMom, -0.5, AliTRDCalPID::kNMom-0.5);
TAxis *ax = h2->GetXaxis();
ax->SetNdivisions(505);
ax->SetTitle("Particle species");
for(Int_t is=AliPID::kSPECIES; is--;) ax->SetBinLabel(is+1, AliPID::ParticleShortName(is));
h2->GetYaxis()->SetTitle("P bins");
h2->GetYaxis()->SetNdivisions(511);
fContainer->AddAt(h2, 0);
fData = new TTree("RefPID", "Reference data for PID");
fData->Branch("data", &fPIDdataArray);
}
//________________________________________________________________________
void AliTRDpidRefMaker::UserExec(Option_t *)
{
// Main loop
// Called for each event
if(!(fTracks = dynamic_cast<TObjArray*>(GetInputData(1)))) return;
if(!(fV0s = dynamic_cast<TObjArray*>(GetInputData(2)))) return;
if(!(fInfo = dynamic_cast<TObjArray*>(GetInputData(3)))) return;
AliDebug(1, Form("Entries: Tracks[%d] V0[%d] PID[%d]", fTracks->GetEntriesFast(), fV0s->GetEntriesFast(), fInfo->GetEntriesFast()));
AliTRDtrackInfo *track = NULL;
AliTRDtrackV1 *trackTRD = NULL;
AliTrackReference *ref = NULL;
const AliTRDtrackInfo::AliESDinfo *infoESD = NULL;
for(Int_t itrk=0; itrk<fTracks->GetEntriesFast(); itrk++){
track = (AliTRDtrackInfo*)fTracks->UncheckedAt(itrk);
if(!track->HasESDtrack()) continue;
trackTRD = track->GetTrack();
infoESD = track->GetESDinfo();
Double32_t *infoPID = infoESD->GetSliceIter();
Int_t n = infoESD->GetNSlices() - AliTRDgeometry::kNlayer;
if(n==0){
AliWarning(Form("dEdx info missing in ESD track %d", itrk));
continue;
}
Double32_t *p = &infoPID[n];
AliDebug(4, Form("n[%d] p[GeV/c]{%6.2f %6.2f %6.2f %6.2f %6.2f %6.2f}", n, p[0], p[1], p[2], p[3], p[4], p[5]));
ULong_t status = track->GetStatus();
if(!(status&AliESDtrack::kTRDpid)) continue;
// fill the pid information
SetRefPID(fRefPID, track, fPID);
// get particle type
Int_t idx(TMath::LocMax(AliPID::kSPECIES, fPID));
if(idx == 0 && fPID[0]<1.e-5) continue;
// prepare PID data array
if(!fPIDdataArray){
fPIDdataArray = new AliTRDpidInfo();
} else fPIDdataArray->Reset();
fPIDdataArray->SetPID(idx);
// fill PID information
for(Int_t ily = 0; ily < AliTRDgeometry::kNlayer; ily++){
// fill P & dE/dx information
if(HasFriends()){ // from TRD track
if(!trackTRD) continue;
AliTRDseedV1 *trackletTRD(NULL);
trackTRD -> SetReconstructor(fReconstructor);
if(!(trackletTRD = trackTRD -> GetTracklet(ily))) continue;
if(!CheckQuality(trackletTRD)) continue;
if(!CookdEdx(trackletTRD)) continue;
// fill momentum information
fP = 0.;
switch(fRefP){
case kMC:
if(!(ref = track->GetTrackRef(trackletTRD))) continue;
fP = ref->P();
break;
case kRec:
fP = trackletTRD->GetMomentum();
break;
default: continue;
}
} else { // from ESD track
// fill momentum information
switch(fRefP){
case kMC:
if(!(ref = track->GetTrackRef(ily))) continue;
fP = ref->P();
break;
case kRec:
fP = p[ily];
break;
default: continue;
}
Double32_t *it = &infoPID[ily*AliTRDCalPID::kNSlicesNN];
for(Int_t is=AliTRDCalPID::kNSlicesNN; is--; it++) fdEdx[is] = (*it);
}
// momentum threshold
if(fP < fPthreshold) continue;
// store information
fPIDdataArray->PushBack(ily, AliTRDpidUtil::GetMomentumBin(fP), fdEdx);
}
Fill();
}
PostData(1, fContainer);
PostData(2, fData);
}
//________________________________________________________________________
void AliTRDpidRefMaker::Fill()
{
// Fill data tree
if(!fPIDdataArray->GetNtracklets()) return;
// Fill data tree
fData->Fill();
// fill monitor
for(Int_t itrklt=fPIDdataArray->GetNtracklets(); itrklt--;){
Int_t pBin = fPIDdataArray->GetData(itrklt)->Momentum();
((TH2*)fContainer->At(0))->Fill(fPIDdataArray->GetPID(), pBin);
}
}
//________________________________________________________________________
void AliTRDpidRefMaker::LinkPIDdata()
{
// Link data tree to data members
fData->SetBranchAddress("data", &fPIDdataArray);
}
//________________________________________________________________________
void AliTRDpidRefMaker::SetRefPID(ETRDpidRefMakerSource select, AliTRDtrackInfo *track, Float_t *pid)
{
// Fill the reference PID values "pid" from "source" object
// according to the option "select". Possible options are
// - kV0 - v0 based PID
// - kMC - MC truth [default]
// - kRec - outside detectors
if(!track){
AliError("No trackInfo found");
return;
}
memset(fPID, 0, AliPID::kSPECIES*sizeof(Float_t));
switch(select){
case kV0:
{
//Get V0 PID decisions from the AliTRDv0Info for all particle species (implemented so far : electrons from conversions, pions from K0s and protons from Lambdas) :
AliTRDv0Info *v0(NULL);
for(Int_t iv(0); iv<fV0s->GetEntriesFast(); iv++){
if(!(v0 = (AliTRDv0Info*)fV0s->At(iv))) continue;
if(!v0->HasTrack(track)) continue;
for(Int_t is=AliPID::kSPECIES; is--;) fPID[is] = v0->GetPID(is, track);
break;
}
}
break;
case kMC:
if(!HasMCdata()){
AliError("Could not retrive reference PID from MC");
return;
}
switch(track->GetPDG()){
case kElectron:
case kPositron:
fPID[AliPID::kElectron] = 1.;
break;
case kMuonPlus:
case kMuonMinus:
fPID[AliPID::kMuon] = 1.;
break;
case kPiPlus:
case kPiMinus:
fPID[AliPID::kPion] = 1.;
break;
case kKPlus:
case kKMinus:
fPID[AliPID::kKaon] = 1.;
break;
case kProton:
case kProtonBar:
fPID[AliPID::kProton] = 1.;
break;
}
break;
case kRec:
{
AliTRDtrackV1 *trackTRD = track->GetTrack();
trackTRD -> SetReconstructor(fReconstructor);
//fReconstructor -> SetOption("nn");
trackTRD -> CookPID();
for(Int_t iPart = 0; iPart < AliPID::kSPECIES; iPart++){
pid[iPart] = trackTRD -> GetPID(iPart);
AliDebug(4, Form("PDG is (in V0info) %d %f", iPart, pid[iPart]));
}
}
break;
default:
AliWarning("PID reference source not implemented");
return;
}
AliDebug(4, Form("Ref PID [%] : %s[%5.2f] %s[%5.2f] %s[%5.2f] %s[%5.2f] %s[%5.2f]"
,AliPID::ParticleShortName(0), 1.e2*fPID[0]
,AliPID::ParticleShortName(1), 1.e2*fPID[1]
,AliPID::ParticleShortName(2), 1.e2*fPID[2]
,AliPID::ParticleShortName(3), 1.e2*fPID[3]
,AliPID::ParticleShortName(4), 1.e2*fPID[4]
));
}
//________________________________________________________________________
void AliTRDpidRefMaker::SetAbundance(Float_t train)
{
// Split data sample between trainning and testing
if(train<0. || train >1.){
AliWarning("The input data should be in the interval [0, 1]");
return;
}
fFreq = train;
}
<|endoftext|> |
<commit_before>/*
Clique: a scalable implementation of the multifrontal algorithm
Copyright (C) 2011 Jack Poulson, Lexing Ying, and
The University of Texas at Austin
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 "clique.hpp"
using namespace elemental;
template<typename F> // F represents a real or complex field
void clique::numeric::DistLDL
( Orientation orientation,
symbolic::DistSymmFact& S, // can't be const due to map...
const numeric::LocalSymmFact<F>& localL,
numeric::DistSymmFact<F>& distL )
{
#ifndef RELEASE
PushCallStack("numeric::DistLDL");
if( orientation == NORMAL )
throw std::logic_error("LDL must be (conjugate-)transposed");
#endif
const int numSupernodes = S.supernodes.size();
if( numSupernodes == 0 )
return;
// The bottom front is already computed, so just view it
distL.fronts[0].LocalMatrix().LockedView( localL.fronts.back() );
// Perform the distributed portion of the factorization
std::vector<int>::const_iterator it;
for( unsigned k=1; k<numSupernodes; ++k )
{
const symbolic::DistSymmFactSupernode& childSymbSN = S.supernodes[k-1];
const symbolic::DistSymmFactSupernode& symbSN = S.supernodes[k];
const DistMatrix<F,MC,MR>& childFront = distL.fronts[k-1];
DistMatrix<F,MC,MR>& front = distL.fronts[k];
const bool computeRecvIndices = ( symbSN.childRecvIndices.size() == 0 );
// Grab this front's grid information
const Grid& grid = front.Grid();
mpi::Comm comm = grid.VCComm();
const unsigned commRank = mpi::CommRank( comm );
const unsigned commSize = mpi::CommSize( comm );
const unsigned gridHeight = grid.Height();
const unsigned gridWidth = grid.Width();
// Grab the child's grid information
const Grid& childGrid = childFront.Grid();
mpi::Comm childComm = childGrid.VCComm();
const unsigned childCommRank = mpi::CommRank( childComm );
const unsigned childCommSize = mpi::CommSize( childComm );
const unsigned childGridHeight = childGrid.Height();
const unsigned childGridWidth = childGrid.Width();
const unsigned childGridRow = childGrid.MCRank();
const unsigned childGridCol = childGrid.MRRank();
#ifndef RELEASE
if( front.Height() != symbSN.size+symbSN.lowerStruct.size() ||
front.Width() != symbSN.size+symbSN.lowerStruct.size() )
throw std::logic_error("Front was not the proper size");
#endif
// Pack our child's updates
DistMatrix<F,MC,MR> childUpdate(childGrid);
const int updateSize = childFront.Height()-childSymbSN.size;
childUpdate.LockedView
( childFront,
childSymbSN.size, childSymbSN.size, updateSize, updateSize );
const bool isLeftChild = ( commRank < commSize/2 );
it = std::max_element
( symbSN.numChildSendIndices.begin(),
symbSN.numChildSendIndices.end() );
const int sendPortionSize = std::max(*it,mpi::MIN_COLL_MSG);
std::vector<F> sendBuffer( sendPortionSize*commSize );
std::vector<int> sendOffsets( commSize, 0 );
const std::vector<int>& myChildRelIndices =
( isLeftChild ? symbSN.leftChildRelIndices
: symbSN.rightChildRelIndices );
const int updateRowAlignment = childUpdate.RowAlignment();
const int updateColShift = childUpdate.ColShift();
const int updateRowShift = childUpdate.RowShift();
const int updateLocalHeight = childUpdate.LocalHeight();
const int updateLocalWidth = childUpdate.LocalWidth();
for( int jChildLocal=0; jChildLocal<updateLocalWidth; ++jChildLocal )
{
const int jChild = updateRowShift + jChildLocal*childGridWidth;
const int destGridCol = myChildRelIndices[jChild] % gridWidth;
const int align = (jChild+updateRowAlignment) % childGridHeight;
const int shift =
(childGridRow+childGridHeight-align) % childGridHeight;
const int localColShift =
(jChild+shift-updateColShift) / childGridHeight;
for( int iChildLocal=localColShift;
iChildLocal<updateLocalHeight; ++iChildLocal )
{
const int iChild = updateColShift + iChildLocal*childGridHeight;
const int destGridRow = myChildRelIndices[iChild] % gridHeight;
const int destRank = destGridRow + destGridCol*gridHeight;
sendBuffer[sendOffsets[destRank]++] =
childUpdate.GetLocalEntry(iChildLocal,jChildLocal);
}
}
// AllToAll to send and receive the child updates
if( computeRecvIndices )
symbolic::ComputeRecvIndices( symbSN );
int recvPortionSize = mpi::MIN_COLL_MSG;
for( int i=0; i<commSize; ++i )
{
const int thisPortion = symbSN.childRecvIndices[i].size();
recvPortionSize = std::max(thisPortion,recvPortionSize);
}
std::vector<F> recvBuffer( recvPortionSize*commSize );
// TODO
// Unpack the child udpates (with an Axpy)
// TODO
symbSN.childRecvIndices.clear();
DistSupernodeLDL( orientation, front, symbSN.size );
}
#ifndef RELEASE
PopCallStack();
#endif
}
template void clique::numeric::DistLDL
( Orientation orientation,
symbolic::DistSymmFact& S,
const numeric::LocalSymmFact<float>& localL,
numeric::DistSymmFact<float>& distL );
template void clique::numeric::DistLDL
( Orientation orientation,
symbolic::DistSymmFact& S,
const numeric::LocalSymmFact<double>& localL,
numeric::DistSymmFact<double>& distL );
template void clique::numeric::DistLDL
( Orientation orientation,
symbolic::DistSymmFact& S,
const numeric::LocalSymmFact<std::complex<float> >& localL,
numeric::DistSymmFact<std::complex<float> >& distL );
template void clique::numeric::DistLDL
( Orientation orientation,
symbolic::DistSymmFact& S,
const numeric::LocalSymmFact<std::complex<double> >& localL,
numeric::DistSymmFact<std::complex<double> >& distL );
<commit_msg>Finishing the sketch of the distributed LDL.<commit_after>/*
Clique: a scalable implementation of the multifrontal algorithm
Copyright (C) 2011 Jack Poulson, Lexing Ying, and
The University of Texas at Austin
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 "clique.hpp"
using namespace elemental;
template<typename F> // F represents a real or complex field
void clique::numeric::DistLDL
( Orientation orientation,
symbolic::DistSymmFact& S, // can't be const due to map...
const numeric::LocalSymmFact<F>& localL,
numeric::DistSymmFact<F>& distL )
{
#ifndef RELEASE
PushCallStack("numeric::DistLDL");
if( orientation == NORMAL )
throw std::logic_error("LDL must be (conjugate-)transposed");
#endif
const int numSupernodes = S.supernodes.size();
if( numSupernodes == 0 )
return;
// The bottom front is already computed, so just view it
distL.fronts[0].LocalMatrix().LockedView( localL.fronts.back() );
// Perform the distributed portion of the factorization
std::vector<int>::const_iterator it;
for( unsigned k=1; k<numSupernodes; ++k )
{
const symbolic::DistSymmFactSupernode& childSymbSN = S.supernodes[k-1];
const symbolic::DistSymmFactSupernode& symbSN = S.supernodes[k];
const DistMatrix<F,MC,MR>& childFront = distL.fronts[k-1];
DistMatrix<F,MC,MR>& front = distL.fronts[k];
const bool computeRecvIndices = ( symbSN.childRecvIndices.size() == 0 );
// Grab this front's grid information
const Grid& grid = front.Grid();
mpi::Comm comm = grid.VCComm();
const unsigned commRank = mpi::CommRank( comm );
const unsigned commSize = mpi::CommSize( comm );
const unsigned gridHeight = grid.Height();
const unsigned gridWidth = grid.Width();
// Grab the child's grid information
const Grid& childGrid = childFront.Grid();
mpi::Comm childComm = childGrid.VCComm();
const unsigned childCommRank = mpi::CommRank( childComm );
const unsigned childCommSize = mpi::CommSize( childComm );
const unsigned childGridHeight = childGrid.Height();
const unsigned childGridWidth = childGrid.Width();
const unsigned childGridRow = childGrid.MCRank();
const unsigned childGridCol = childGrid.MRRank();
#ifndef RELEASE
if( front.Height() != symbSN.size+symbSN.lowerStruct.size() ||
front.Width() != symbSN.size+symbSN.lowerStruct.size() )
throw std::logic_error("Front was not the proper size");
#endif
// Pack our child's updates
DistMatrix<F,MC,MR> childUpdate(childGrid);
const int updateSize = childFront.Height()-childSymbSN.size;
childUpdate.LockedView
( childFront,
childSymbSN.size, childSymbSN.size, updateSize, updateSize );
const bool isLeftChild = ( commRank < commSize/2 );
it = std::max_element
( symbSN.numChildSendIndices.begin(),
symbSN.numChildSendIndices.end() );
const int sendPortionSize = std::max(*it,mpi::MIN_COLL_MSG);
std::vector<F> sendBuffer( sendPortionSize*commSize );
const std::vector<int>& myChildRelIndices =
( isLeftChild ? symbSN.leftChildRelIndices
: symbSN.rightChildRelIndices );
const int updateRowAlignment = childUpdate.RowAlignment();
const int updateColShift = childUpdate.ColShift();
const int updateRowShift = childUpdate.RowShift();
const int updateLocalHeight = childUpdate.LocalHeight();
const int updateLocalWidth = childUpdate.LocalWidth();
// Initialize the offsets to each process's chunk
std::vector<int> sendOffsets( commSize );
for( int proc=0; proc<commSize; ++proc )
sendOffsets[proc] = proc*sendPortionSize;
for( int jChildLocal=0; jChildLocal<updateLocalWidth; ++jChildLocal )
{
const int jChild = updateRowShift + jChildLocal*childGridWidth;
const int destGridCol = myChildRelIndices[jChild] % gridWidth;
const int align = (jChild+updateRowAlignment) % childGridHeight;
const int shift =
(childGridRow+childGridHeight-align) % childGridHeight;
const int localColShift =
(jChild+shift-updateColShift) / childGridHeight;
for( int iChildLocal=localColShift;
iChildLocal<updateLocalHeight; ++iChildLocal )
{
const int iChild = updateColShift + iChildLocal*childGridHeight;
const int destGridRow = myChildRelIndices[iChild] % gridHeight;
const int destRank = destGridRow + destGridCol*gridHeight;
sendBuffer[sendOffsets[destRank]++] =
childUpdate.GetLocalEntry(iChildLocal,jChildLocal);
}
}
// Reset the offsets to their original values
for( int proc=0; proc<commSize; ++proc )
sendOffsets[proc] = proc*sendPortionSize;
// AllToAll to send and receive the child updates
if( computeRecvIndices )
symbolic::ComputeRecvIndices( symbSN );
int recvPortionSize = mpi::MIN_COLL_MSG;
for( int i=0; i<commSize; ++i )
{
const int thisPortion = symbSN.childRecvIndices[i].size();
recvPortionSize = std::max(thisPortion,recvPortionSize);
}
std::vector<F> recvBuffer( recvPortionSize*commSize );
mpi::AllToAll
( &sendBuffer[0], sendPortionSize,
&recvBuffer[0], recvPortionSize, comm );
sendBuffer.clear();
// Unpack the child udpates (with an Axpy)
for( int proc=0; proc<commSize; ++proc )
{
const F* recvValues = &recvBuffer[proc*recvPortionSize];
const std::deque<int>& recvIndices = symbSN.childRecvIndices[proc];
for( int k=0; k<recvIndices.size(); ++k )
{
const int iFrontLocal = recvIndices[2*k+0];
const int jFrontLocal = recvIndices[2*k+1];
const F value = recvValues[k];
front.UpdateLocalEntry( iFrontLocal, jFrontLocal, value );
}
}
recvBuffer.clear();
symbSN.childRecvIndices.clear();
DistSupernodeLDL( orientation, front, symbSN.size );
}
#ifndef RELEASE
PopCallStack();
#endif
}
template void clique::numeric::DistLDL
( Orientation orientation,
symbolic::DistSymmFact& S,
const numeric::LocalSymmFact<float>& localL,
numeric::DistSymmFact<float>& distL );
template void clique::numeric::DistLDL
( Orientation orientation,
symbolic::DistSymmFact& S,
const numeric::LocalSymmFact<double>& localL,
numeric::DistSymmFact<double>& distL );
template void clique::numeric::DistLDL
( Orientation orientation,
symbolic::DistSymmFact& S,
const numeric::LocalSymmFact<std::complex<float> >& localL,
numeric::DistSymmFact<std::complex<float> >& distL );
template void clique::numeric::DistLDL
( Orientation orientation,
symbolic::DistSymmFact& S,
const numeric::LocalSymmFact<std::complex<double> >& localL,
numeric::DistSymmFact<std::complex<double> >& distL );
<|endoftext|> |
<commit_before>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "cMonsterConfig.h"
#include "cMonster.h"
#include "../iniFile/iniFile.h"
#include <cstdio>
//#include "../source/cprintf.h"
using namespace std;
struct cMonsterConfig::sAttributesStruct
{
string m_name;
float m_SightDistance;
float m_AttackDamage;
float m_AttackRange;
float m_AttackRate;
int m_MaxHealth;
};
struct cMonsterConfig::sMonsterConfigState
{
int TypeCount;
string MonsterTypes;
list< sAttributesStruct > AttributesList;
};
cMonsterConfig::cMonsterConfig(int TypeC)
: m_pState( new sMonsterConfigState )
{
m_pState->TypeCount = TypeC;
Initialize();
}
cMonsterConfig::~cMonsterConfig() {
delete m_pState;
}
void cMonsterConfig::Initialize() {
sAttributesStruct Attributes;
cIniFile SettingsIniFile("settings.ini");
cIniFile MonstersIniFile("monsters.ini");
if(!SettingsIniFile.ReadFile() || !MonstersIniFile.ReadFile()) {
printf("Error: Must have both settings.ini and monsters.ini to configure attributes\n\tusing default attributes \n");
return;
}
m_pState->MonsterTypes = SettingsIniFile.GetValue("Monsters","Types","");
if( m_pState->MonsterTypes.empty() ) {
printf("Error: No Monster types listed in config file, using default attributes \n");
return;
}
AStringVector SplitList = StringSplit(m_pState->MonsterTypes,",");
for(unsigned int i = 0; i < SplitList.size(); ++i) {
if(!SplitList[i].empty()) {
printf("Getting Attributes for: %s \n",SplitList[i].c_str());
Attributes.m_name = SplitList[i].c_str();
Attributes.m_AttackDamage = (float)MonstersIniFile.GetValueF(SplitList[i].c_str(),"AttackDamage",0);
printf("Got AttackDamage: %3.3f \n",Attributes.m_AttackDamage);
Attributes.m_AttackRange = (float)MonstersIniFile.GetValueF(SplitList[i].c_str(),"AttackRange",0);
printf("Got AttackRange: %3.3f \n",Attributes.m_AttackRange);
Attributes.m_SightDistance = (float)MonstersIniFile.GetValueF(SplitList[i].c_str(),"SightDistance",0);
printf("Got SightDistance: %3.3f \n",Attributes.m_SightDistance);
Attributes.m_AttackRate = (float)MonstersIniFile.GetValueF(SplitList[i].c_str(),"AttackRate",0);
printf("Got AttackRate: %3.3f \n",Attributes.m_AttackRate);
Attributes.m_MaxHealth = MonstersIniFile.GetValueI(SplitList[i].c_str(),"MaxHealth",0);
printf("Got MaxHealth: %d \n",Attributes.m_MaxHealth);
m_pState->AttributesList.push_front(Attributes);
}
}
}
void cMonsterConfig::AssignAttributes(cMonster *m, const char* n)
{
list<sAttributesStruct>::iterator itr;
for(itr = m_pState->AttributesList.begin(); itr != m_pState->AttributesList.end(); ++itr) {
if(itr->m_name.compare(n) == 0) {
//printf("found my attribs: %s :\n",itr->m_name.c_str());
m->SetAttackDamage(itr->m_AttackDamage);
m->SetAttackRange(itr->m_AttackRange);
m->SetSightDistance(itr->m_SightDistance);
m->SetAttackRate((int)itr->m_AttackRate);
m->SetMaxHealth((int)itr->m_MaxHealth);
}
}
}
cMonsterConfig *cMonsterConfig::Get() {
return this;
}
<commit_msg>cMonsterConfig: removed excessive logging<commit_after>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "cMonsterConfig.h"
#include "cMonster.h"
#include "../iniFile/iniFile.h"
//#include <cstdio>
struct cMonsterConfig::sAttributesStruct
{
AString m_name;
float m_SightDistance;
float m_AttackDamage;
float m_AttackRange;
float m_AttackRate;
int m_MaxHealth;
};
struct cMonsterConfig::sMonsterConfigState
{
int TypeCount;
AString MonsterTypes;
std::list< sAttributesStruct > AttributesList;
};
cMonsterConfig::cMonsterConfig(int TypeC)
: m_pState( new sMonsterConfigState )
{
m_pState->TypeCount = TypeC;
Initialize();
}
cMonsterConfig::~cMonsterConfig() {
delete m_pState;
}
void cMonsterConfig::Initialize() {
sAttributesStruct Attributes;
cIniFile SettingsIniFile("settings.ini");
cIniFile MonstersIniFile("monsters.ini");
if (!SettingsIniFile.ReadFile() || !MonstersIniFile.ReadFile())
{
LOGWARNING("cMonsterConfig: Must have both settings.ini and monsters.ini to configure attributes\n\tusing default attributes \n");
return;
}
m_pState->MonsterTypes = SettingsIniFile.GetValue("Monsters","Types","");
if ( m_pState->MonsterTypes.empty() )
{
LOGWARNING("cMonsterConfig: No Monster types listed in config file, using default attributes \n");
return;
}
AStringVector SplitList = StringSplit(m_pState->MonsterTypes,",");
for (unsigned int i = 0; i < SplitList.size(); ++i)
{
if (!SplitList[i].empty())
{
Attributes.m_name = SplitList[i].c_str();
Attributes.m_AttackDamage = (float)MonstersIniFile.GetValueF(SplitList[i].c_str(), "AttackDamage", 0);
Attributes.m_AttackRange = (float)MonstersIniFile.GetValueF(SplitList[i].c_str(), "AttackRange", 0);
Attributes.m_SightDistance = (float)MonstersIniFile.GetValueF(SplitList[i].c_str(), "SightDistance", 0);
Attributes.m_AttackRate = (float)MonstersIniFile.GetValueF(SplitList[i].c_str(), "AttackRate", 0);
Attributes.m_MaxHealth = MonstersIniFile.GetValueI(SplitList[i].c_str(), "MaxHealth", 0);
m_pState->AttributesList.push_front(Attributes);
}
} // for i - SplitList[]
}
void cMonsterConfig::AssignAttributes(cMonster *m, const char* n)
{
std::list<sAttributesStruct>::const_iterator itr;
for (itr = m_pState->AttributesList.begin(); itr != m_pState->AttributesList.end(); ++itr)
{
if(itr->m_name.compare(n) == 0)
{
m->SetAttackDamage (itr->m_AttackDamage);
m->SetAttackRange (itr->m_AttackRange);
m->SetSightDistance(itr->m_SightDistance);
m->SetAttackRate ((int)itr->m_AttackRate);
m->SetMaxHealth ((int)itr->m_MaxHealth);
}
} // for itr - m_pState->AttributesList[]
}
cMonsterConfig *cMonsterConfig::Get() {
return this;
}
<|endoftext|> |
<commit_before>#include <TCanvas.h>
#include <TFile.h>
#include <TH1.h>
#include <TH2.h>
#include <TLegend.h>
#include <TList.h>
#include <TString.h>
#include <TStyle.h>
#include <array>
using std::array;
/// Now it runs only with ROOT6
namespace {
array<TString,2> raw_sel{"_raw","_selected"};
array<TString,3> basic_hists_names{"Vtz","DeltaVtz","Centrality"};
array<TString,2> multiplicity_hists_names{"EstimCorrelation","MultCentCorrelation"};
array<TString,5> advanced_hists_names{"fTOFvsFB32","fTPCvsAll","fMultvsV0M","fTPCvsTrkl","fVZEROvsTPCout"};
array<TString,2> compare_titles{"Old","New"};
array<Color_t,2> compare_colors{kRed,kBlack};
array<Style_t,2> compare_fills{3345,3354};
};
template<typename T, int N> array<T*,N> getHistograms(TList* list, array<TString,N> names, TString &suffix) {
array<T*,N> histos{nullptr};
for (size_t iH = 0; iH < N; ++iH) {
histos[iH] = static_cast<T*>(list->FindObject((names[iH]+suffix).Data()));
}
return histos;
}
void CheckEventCuts(TString input_file_name = "AnalysisResults.root") {
gStyle->SetOptStat(0);
TFile input_file(input_file_name.Data());
TList* input_list = static_cast<TList*>(input_file.Get("_std"));
TCanvas* cv_basics[2]{nullptr};
TCanvas* cv_multiplicity[2]{nullptr};
TCanvas* cv_advanced[2]{nullptr};
for (int iC = 0; iC < 2; ++iC) {
cv_basics[iC] = new TCanvas(Form("cv_basics%s",raw_sel[iC].Data()));
cv_basics[iC]->Divide(2,2);
auto hist_basics = getHistograms<TH1,3>(input_list,basic_hists_names,raw_sel[iC]);
for (size_t iN = 0; iN < basic_hists_names.size(); ++iN) {
cv_basics[iC]->cd(iN+1);
hist_basics[iN]->DrawCopy();
}
cv_multiplicity[iC] = new TCanvas(Form("cv_multiplicity%s",raw_sel[iC].Data()));
cv_multiplicity[iC]->Divide(2);
auto hist_multiplicity = getHistograms<TH2,2>(input_list,multiplicity_hists_names,raw_sel[iC]);
for (size_t iN = 0; iN < hist_multiplicity.size(); ++iN) {
cv_multiplicity[iC]->cd(iN+1);
hist_multiplicity[iN]->DrawCopy("colz");
}
cv_advanced[iC] = new TCanvas(Form("cv_advanced%s",raw_sel[iC].Data()));
cv_advanced[iC]->Divide(3,2);
auto hist_advanced = getHistograms<TH2,5>(input_list,advanced_hists_names,raw_sel[iC]);
for (size_t iN = 0; iN < hist_advanced.size(); ++iN) {
cv_advanced[iC]->cd(iN+1);
hist_advanced[iC]->DrawCopy("colz");
}
}
TCanvas* cv_summary{new TCanvas("cv_summary")};
cv_summary->Divide(2);
cv_summary->cd(1);
TH1* hist_cut_stats = static_cast<TH1*>(input_list->FindObject("fCutStats"));
hist_cut_stats->DrawCopy();
cv_summary->cd(2);
TH1* hist_normalisation = static_cast<TH1*>(input_list->FindObject("fNormalisationHist"));
hist_normalisation->DrawCopy();
}
void CompareEventSelections(TString input_file_name0 = "oldAOD.root",
TString input_file_name1 = "newAOD.root") {
gStyle->SetOptStat(0);
gStyle->SetOptTitle(0);
array<TFile*,2> input_files{TFile::Open(input_file_name0.Data()),TFile::Open(input_file_name1.Data())};
array<TList*,2> input_lists{nullptr};
array<TH1*,2> hists_cut_stats{nullptr};
array<TH1*,2> hists_normalisation{nullptr};
array<double,2> number_of_events{-1.};
array<array<TH1*,3>,2> basics_hist{{nullptr}};
array<array<TH2*,2>,2> multiplicity_hist{{nullptr}};
TCanvas* cv_summary{new TCanvas("cv_summary","Summary",1000,700)};
cv_summary->Divide(2);
TCanvas* cv_basics = new TCanvas("cv_basics","Basic selections",1000,700);
cv_basics->Divide(2,2);
TCanvas* cv_multiplicity = new TCanvas("cv_multiplicity","Multiplicity selections",1000,700);
cv_multiplicity->Divide(2);
for (int iF = 0; iF < 2; ++iF) {
input_lists[iF] = static_cast<TList*>(input_files[iF]->Get("_std"));
hists_cut_stats[iF] = static_cast<TH1*>(input_lists[iF]->FindObject("fCutStats"));
hists_normalisation[iF] = static_cast<TH1*>(input_lists[iF]->FindObject("fNormalisationHist"));
number_of_events[iF] = hists_cut_stats[iF]->GetBinContent(4);
basics_hist[iF] = getHistograms<TH1,3>(input_lists[iF],basic_hists_names,raw_sel[1]);
multiplicity_hist[iF] = getHistograms<TH2,2>(input_lists[iF],multiplicity_hists_names,raw_sel[1]);
const double norm = 1000. / number_of_events[iF];
cv_summary->cd(1);
hists_cut_stats[iF]->SetTitle(compare_titles[iF].Data());
hists_cut_stats[iF]->UseCurrentStyle();
hists_cut_stats[iF]->Scale(norm);
hists_cut_stats[iF]->SetLineColor(compare_colors[iF]);
hists_cut_stats[iF]->SetFillStyle(compare_fills[iF]);
hists_cut_stats[iF]->SetFillColor(compare_colors[iF]);
hists_cut_stats[iF]->DrawCopy(iF ? "hist same" : "hist");
cv_summary->cd(2);
hists_normalisation[iF]->SetTitle(compare_titles[iF].Data());
hists_normalisation[iF]->UseCurrentStyle();
hists_normalisation[iF]->Scale(norm);
hists_normalisation[iF]->SetLineColor(compare_colors[iF]);
hists_normalisation[iF]->SetFillStyle(compare_fills[iF]);
hists_normalisation[iF]->SetFillColor(compare_colors[iF]);
hists_normalisation[iF]->DrawCopy(iF ? "hist same" : "hist");
for (size_t iH = 0; iH < basics_hist[iF].size(); ++iH) {
cv_basics->cd(iH+1);
basics_hist[iF][iH]->SetTitle(compare_titles[iF].Data());
basics_hist[iF][iH]->UseCurrentStyle();
basics_hist[iF][iH]->Scale(norm);
basics_hist[iF][iH]->SetLineColor(compare_colors[iF]);
basics_hist[iF][iH]->SetFillStyle(compare_fills[iF]);
basics_hist[iF][iH]->SetFillColor(compare_colors[iF]);
basics_hist[iF][iH]->DrawCopy(iF ? "same hist" : "hist");
}
for (size_t iH = 0; iH < multiplicity_hist[iF].size(); ++iH) {
cv_multiplicity->cd(iH+1)->SetLogz();
if (iH) cv_multiplicity->cd(iH+1)->SetLogy();
multiplicity_hist[iF][iH]->SetTitle(compare_titles[iF].Data());
multiplicity_hist[iF][iH]->UseCurrentStyle();
multiplicity_hist[iF][iH]->Scale(norm);
multiplicity_hist[iF][iH]->SetMarkerColor(compare_colors[iF]);
multiplicity_hist[iF][iH]->SetLineColor(compare_colors[iF]);
multiplicity_hist[iF][iH]->SetFillColor(compare_colors[iF]);
multiplicity_hist[iF][iH]->SetFillStyle(compare_fills[iF]);
multiplicity_hist[iF][iH]->DrawCopy(iF ? "same" : "");
}
}
cv_summary->cd(2)->BuildLegend();
cv_basics->cd(2)->BuildLegend(0.65);
cv_multiplicity->cd(2)->BuildLegend(0.16,0.16,0.4,0.3);
for (auto &file : input_files)
file->Close();
}<commit_msg>Event cuts checks macro working with ROOT5<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TCanvas.h>
#include <TFile.h>
#include <TH1.h>
#include <TH2.h>
#include <TLegend.h>
#include <TList.h>
#include <TString.h>
#include <TStyle.h>
#include <string>
#include <vector>
using std::string;
using std::vector;
#endif
namespace {
const string raw_sel[2] = {"_raw","_selected"};
enum {
n_basic_hists = 3,
n_multiplicity_hists = 2,
n_advanced_hists = 5
};
const string basic_hists_names[n_basic_hists] = {"Vtz","DeltaVtz","Centrality"};
const string multiplicity_hists_names[n_multiplicity_hists] = {"EstimCorrelation","MultCentCorrelation"};
const string advanced_hists_names[n_advanced_hists] = {"fTOFvsFB32","fTPCvsAll","fMultvsV0M","fTPCvsTrkl","fVZEROvsTPCout"};
const string compare_titles[2] = {"Old","New"};
const Color_t compare_colors[2] = {kRed,kBlack};
const Style_t compare_fills[2] = {3345,3354};
}
template<typename T> vector<T* > getHistograms(TList* list, const string* names, const int n_names, const string &suffix) {
vector<T*> histos(n_names,nullptr);
for (int iH = 0; iH < n_names; ++iH) {
histos[iH] = static_cast<T*>(list->FindObject((names[iH]+suffix).data()));
}
return histos;
}
void CheckEventCuts(string input_file_name = "AnalysisResults.root") {
gStyle->SetOptStat(0);
TFile input_file(input_file_name.data());
TList* input_list = static_cast<TList*>(input_file.Get("_std"));
TCanvas* cv_basics[2]{nullptr};
TCanvas* cv_multiplicity[2]{nullptr};
TCanvas* cv_advanced[2]{nullptr};
for (int iC = 0; iC < 2; ++iC) {
cv_basics[iC] = new TCanvas(Form("cv_basics%s",raw_sel[iC].data()));
cv_basics[iC]->Divide(2,2);
auto hist_basics = getHistograms<TH1>(input_list,basic_hists_names,n_basic_hists,raw_sel[iC]);
for (size_t iN = 0; iN < n_basic_hists; ++iN) {
cv_basics[iC]->cd(iN+1);
hist_basics[iN]->DrawCopy();
}
cv_multiplicity[iC] = new TCanvas(Form("cv_multiplicity%s",raw_sel[iC].data()));
cv_multiplicity[iC]->Divide(2);
auto hist_multiplicity = getHistograms<TH2>(input_list,multiplicity_hists_names,n_multiplicity_hists,raw_sel[iC]);
for (size_t iN = 0; iN < n_multiplicity_hists; ++iN) {
cv_multiplicity[iC]->cd(iN+1);
hist_multiplicity[iN]->DrawCopy("colz");
}
cv_advanced[iC] = new TCanvas(Form("cv_advanced%s",raw_sel[iC].data()));
cv_advanced[iC]->Divide(3,2);
auto hist_advanced = getHistograms<TH2>(input_list,advanced_hists_names,n_advanced_hists,raw_sel[iC]);
for (size_t iN = 0; iN < n_advanced_hists; ++iN) {
cv_advanced[iC]->cd(iN+1);
hist_advanced[iC]->DrawCopy("colz");
}
}
TCanvas* cv_summary{new TCanvas("cv_summary")};
cv_summary->Divide(2);
cv_summary->cd(1);
TH1* hist_cut_stats = static_cast<TH1*>(input_list->FindObject("fCutStats"));
hist_cut_stats->DrawCopy();
cv_summary->cd(2);
TH1* hist_normalisation = static_cast<TH1*>(input_list->FindObject("fNormalisationHist"));
hist_normalisation->DrawCopy();
}
void CompareEventSelections(string input_file_name0 = "oldAOD.root",
string input_file_name1 = "newAOD.root") {
gStyle->SetOptStat(0);
gStyle->SetOptTitle(0);
TFile* input_files[2]{TFile::Open(input_file_name0.data()),TFile::Open(input_file_name1.data())};
TList* input_lists[2]{nullptr};
TH1* hists_cut_stats[2]{nullptr};
TH1* hists_normalisation[2]{nullptr};
double number_of_events[2]{-1.};
vector<TH1*> basics_hist[2] = {vector<TH1*>(3,nullptr)};
vector<TH2*> multiplicity_hist[2] = {vector<TH2*>(2,nullptr)};
TCanvas* cv_summary{new TCanvas("cv_summary","Summary",1000,700)};
cv_summary->Divide(2);
TCanvas* cv_basics = new TCanvas("cv_basics","Basic selections",1000,700);
cv_basics->Divide(2,2);
TCanvas* cv_multiplicity = new TCanvas("cv_multiplicity","Multiplicity selections",1000,700);
cv_multiplicity->Divide(2);
for (int iF = 0; iF < 2; ++iF) {
input_lists[iF] = static_cast<TList*>(input_files[iF]->Get("_std"));
hists_cut_stats[iF] = static_cast<TH1*>(input_lists[iF]->FindObject("fCutStats"));
hists_normalisation[iF] = static_cast<TH1*>(input_lists[iF]->FindObject("fNormalisationHist"));
number_of_events[iF] = hists_cut_stats[iF]->GetBinContent(4);
basics_hist[iF] = getHistograms<TH1>(input_lists[iF],basic_hists_names,n_basic_hists,raw_sel[1]);
multiplicity_hist[iF] = getHistograms<TH2>(input_lists[iF],multiplicity_hists_names,n_multiplicity_hists,raw_sel[1]);
const double norm = 1000. / number_of_events[iF];
cv_summary->cd(1);
hists_cut_stats[iF]->SetTitle(compare_titles[iF].data());
hists_cut_stats[iF]->UseCurrentStyle();
hists_cut_stats[iF]->Scale(norm);
hists_cut_stats[iF]->SetLineColor(compare_colors[iF]);
hists_cut_stats[iF]->SetFillStyle(compare_fills[iF]);
hists_cut_stats[iF]->SetFillColor(compare_colors[iF]);
hists_cut_stats[iF]->DrawCopy(iF ? "hist same" : "hist");
cv_summary->cd(2);
hists_normalisation[iF]->SetTitle(compare_titles[iF].data());
hists_normalisation[iF]->UseCurrentStyle();
hists_normalisation[iF]->Scale(norm);
hists_normalisation[iF]->SetLineColor(compare_colors[iF]);
hists_normalisation[iF]->SetFillStyle(compare_fills[iF]);
hists_normalisation[iF]->SetFillColor(compare_colors[iF]);
hists_normalisation[iF]->DrawCopy(iF ? "hist same" : "hist");
for (size_t iH = 0; iH < n_basic_hists; ++iH) {
cv_basics->cd(iH+1);
basics_hist[iF][iH]->SetTitle(compare_titles[iF].data());
basics_hist[iF][iH]->UseCurrentStyle();
basics_hist[iF][iH]->Scale(norm);
basics_hist[iF][iH]->SetLineColor(compare_colors[iF]);
basics_hist[iF][iH]->SetFillStyle(compare_fills[iF]);
basics_hist[iF][iH]->SetFillColor(compare_colors[iF]);
basics_hist[iF][iH]->DrawCopy(iF ? "same hist" : "hist");
}
for (size_t iH = 0; iH < n_multiplicity_hists; ++iH) {
cv_multiplicity->cd(iH+1)->SetLogz();
if (iH) cv_multiplicity->cd(iH+1)->SetLogy();
multiplicity_hist[iF][iH]->SetTitle(compare_titles[iF].data());
multiplicity_hist[iF][iH]->UseCurrentStyle();
multiplicity_hist[iF][iH]->Scale(norm);
multiplicity_hist[iF][iH]->SetMarkerColor(compare_colors[iF]);
multiplicity_hist[iF][iH]->SetLineColor(compare_colors[iF]);
multiplicity_hist[iF][iH]->SetFillColor(compare_colors[iF]);
multiplicity_hist[iF][iH]->SetFillStyle(compare_fills[iF]);
multiplicity_hist[iF][iH]->DrawCopy(iF ? "same" : "");
}
}
cv_summary->cd(2)->BuildLegend();
cv_basics->cd(2)->BuildLegend(0.65);
cv_multiplicity->cd(2)->BuildLegend(0.16,0.16,0.4,0.3);
for (auto &file : input_files)
file->Close();
}<|endoftext|> |
<commit_before><commit_msg>Fix memory leak reported by Valgrind tests<commit_after><|endoftext|> |
<commit_before>#include "util/log/Logger.hpp"
const string Logger::MESSAGE_OK = string(" ... \033[1;32mOK\033[0m");
const string Logger::MESSAGE_FAIL = string(" ... \033[1;31mFail\033[0m");
const string Logger::COLOUR_PATTERN = string("\\\033\\[\\d+\\;?\\d*m");
Logger::Logger(string loggerName, bool noColour)
try : loggerName(loggerName)
, logEntry()
, colourRegex(Logger::COLOUR_PATTERN)
, noColour(noColour)
{
}
catch(std::regex_error)
{
noColour = false;
}
Logger::~Logger()
{
}
Logger & Logger::operator << (const string & message)
{
// If there's nothing in the stringstream yet, prepend with the logger name
if (logEntry.str().empty()) {
logEntry << "[" << loggerName << "] ";
}
// Output log message, stripping colours using regex replace if required.
logEntry << (noColour ? regex_replace(message, colourRegex, string("")) : message);
return *this;
}
Logger & Logger::operator << (const LoggerMode mode)
{
switch (mode) {
case endl:
// Output the stringstream to standard out and reset the stringstream.
// Be sure to use 'std::endl' as 'endl' will refer to LoggerMode::endl by default.
cout << logEntry.str() << std::endl;
logEntry.clear();
logEntry.str(string(""));
break;
case ok:
*this << MESSAGE_OK;
break;
case fail:
*this << MESSAGE_FAIL;
break;
default:
break;
}
return *this;
}
<commit_msg>invert nocolour value on exception - not the other way round<commit_after>#include "util/log/Logger.hpp"
const string Logger::MESSAGE_OK = string(" ... \033[1;32mOK\033[0m");
const string Logger::MESSAGE_FAIL = string(" ... \033[1;31mFail\033[0m");
const string Logger::COLOUR_PATTERN = string("\\\033\\[\\d+\\;?\\d*m");
Logger::Logger(string loggerName, bool noColour)
try : loggerName(loggerName)
, logEntry()
, colourRegex(Logger::COLOUR_PATTERN)
, noColour(noColour)
{
}
catch(std::regex_error)
{
noColour = true;
}
Logger::~Logger()
{
}
Logger & Logger::operator << (const string & message)
{
// If there's nothing in the stringstream yet, prepend with the logger name
if (logEntry.str().empty()) {
logEntry << "[" << loggerName << "] ";
}
// Output log message, stripping colours using regex replace if required.
logEntry << (noColour ? regex_replace(message, colourRegex, string("")) : message);
return *this;
}
Logger & Logger::operator << (const LoggerMode mode)
{
switch (mode) {
case endl:
// Output the stringstream to standard out and reset the stringstream.
// Be sure to use 'std::endl' as 'endl' will refer to LoggerMode::endl by default.
cout << logEntry.str() << std::endl;
logEntry.clear();
logEntry.str(string(""));
break;
case ok:
*this << MESSAGE_OK;
break;
case fail:
*this << MESSAGE_FAIL;
break;
default:
break;
}
return *this;
}
<|endoftext|> |
<commit_before>#include "data/Format.h"
#include "data/WaveformOf.h"
#include "util/Stream.h"
namespace blitzortung {
namespace data {
Format::Format(unsigned char numberOfBytes, unsigned char numberOfChannels, unsigned short numberOfSamples) :
sampleType_(Type::BYTE),
numberOfChannels_(numberOfChannels),
numberOfSamples_(numberOfSamples),
createWaveformWithTimestamp_(0),
createWaveformFromStream_(0),
logger_("data.Format")
{
updateSampleType(numberOfBytes);
updateFactoryMethod();
}
Format::Format() :
sampleType_(Type::BYTE),
numberOfChannels_(0),
numberOfSamples_(0),
createWaveformWithTimestamp_(0),
createWaveformFromStream_(0),
logger_("data.Format")
{
}
Format::Format(std::iostream& stream) :
sampleType_(Type::BYTE),
numberOfChannels_(0),
numberOfSamples_(0),
createWaveformWithTimestamp_(0),
createWaveformFromStream_(0),
logger_("data.Format")
{
fromStream(stream);
}
Format::~Format() = default;
Format& Format::operator=(const Format& other) {
numberOfChannels_ = other.numberOfChannels_;
numberOfSamples_ = other.numberOfSamples_;
sampleType_ = other.sampleType_;
createWaveformWithTimestamp_ = other.createWaveformWithTimestamp_;
createWaveformFromStream_ = other.createWaveformFromStream_;
logger_ = other.logger_;
return *this;
}
unsigned char Format::getNumberOfChannels() const {
return numberOfChannels_;
}
unsigned short Format::getNumberOfSamples() const {
return numberOfSamples_;
}
void Format::updateSampleType(unsigned char numberOfBytesPerSample) {
if (numberOfBytesPerSample == 1) {
sampleType_ = Type::BYTE;
} else if (numberOfBytesPerSample == 2) {
sampleType_ = Type::SHORT;
} else if (numberOfBytesPerSample == 4) {
sampleType_ = Type::INT;
} else {
// handle older format with number of bits per sample
if (numberOfBytesPerSample > 8) {
sampleType_ = Type::SHORT;
} else {
sampleType_ = Type::BYTE;
}
}
}
Format::Type Format::getDataType() const {
return sampleType_;
}
unsigned char Format::getNumberOfBytesPerSample() const {
return (unsigned char)(sampleType_);
}
unsigned int Format::getDataSize() const {
return getNumberOfBytesPerSample() * numberOfChannels_ * numberOfSamples_;
}
bool Format::isValid() const {
return getDataSize() > 0;
}
void Format::toStream(std::iostream& stream) const {
util::Stream::WriteValue(stream, numberOfSamples_);
util::Stream::WriteValue(stream, numberOfChannels_);
util::Stream::WriteValue(stream, (unsigned char)sampleType_);
}
void Format::fromStream(std::iostream& stream) {
util::Stream::ReadValue(stream, numberOfSamples_);
util::Stream::ReadValue(stream, numberOfChannels_);
{
unsigned char numberOfBytesPerSample;
util::Stream::ReadValue(stream, numberOfBytesPerSample);
updateSampleType(numberOfBytesPerSample);
}
updateFactoryMethod();
}
Waveform::AP Format::createWaveformChar_1_1(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 1, 1>(t0, dt));
}
Waveform::AP Format::createWaveformChar_1_1(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 1, 1>(date, stream));
}
Waveform::AP Format::createWaveformChar_64_1(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 64, 1>(t0, dt));
}
Waveform::AP Format::createWaveformChar_64_1(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 64, 1>(date, stream));
}
Waveform::AP Format::createWaveformChar_128_1(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 128, 1>(t0, dt));
}
Waveform::AP Format::createWaveformChar_128_1(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 128, 1>(date, stream));
}
Waveform::AP Format::createWaveformChar_256_1(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 256, 1>(t0, dt));
}
Waveform::AP Format::createWaveformChar_256_1(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 256, 1>(date, stream));
}
Waveform::AP Format::createWaveformChar_1_2(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 1, 2>(t0, dt));
}
Waveform::AP Format::createWaveformChar_1_2(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 1, 2>(date, stream));
}
Waveform::AP Format::createWaveformChar_64_2(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 64, 2>(t0, dt));
}
Waveform::AP Format::createWaveformChar_64_2(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 64, 2>(date, stream));
}
Waveform::AP Format::createWaveformChar_128_2(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 128, 2>(t0, dt));
}
Waveform::AP Format::createWaveformChar_128_2(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 128, 2>(date, stream));
}
Waveform::AP Format::createWaveformChar_256_2(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 256, 2>(t0, dt));
}
Waveform::AP Format::createWaveformChar_256_2(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 256, 2>(date, stream));
}
Waveform::AP Format::createWaveformShort_1_2(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed short, 1, 2>(t0, dt));
}
Waveform::AP Format::createWaveformShort_1_2(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed short, 1, 2>(date, stream));
}
Waveform::AP Format::createWaveform(const pt::ptime& t0, const pt::time_duration& dt) const {
return (*createWaveformWithTimestamp_)(t0, dt);
}
Waveform::AP Format::createWaveform(const gr::date& date, std::iostream& stream) const {
return (*createWaveformFromStream_)(date, stream);
}
void Format::updateFactoryMethod() {
switch (sampleType_) {
case Type::BYTE:
switch (numberOfChannels_) {
case 1:
switch (numberOfSamples_) {
case 1:
createWaveformWithTimestamp_ = &Format::createWaveformChar_1_1;
createWaveformFromStream_ = &Format::createWaveformChar_1_1;
break;
case 64:
createWaveformWithTimestamp_ = &Format::createWaveformChar_64_1;
createWaveformFromStream_ = &Format::createWaveformChar_64_1;
break;
case 128:
createWaveformWithTimestamp_ = &Format::createWaveformChar_128_1;
createWaveformFromStream_ = &Format::createWaveformChar_128_1;
break;
case 256:
createWaveformWithTimestamp_ = &Format::createWaveformChar_256_1;
createWaveformFromStream_ = &Format::createWaveformChar_256_1;
break;
default:
throw new exception::Base("unhandled number of samples");
}
break;
case 2:
switch (numberOfSamples_) {
case 1:
createWaveformWithTimestamp_ = &Format::createWaveformChar_1_2;
createWaveformFromStream_ = &Format::createWaveformChar_1_2;
break;
case 64:
createWaveformWithTimestamp_ = &Format::createWaveformChar_64_2;
createWaveformFromStream_ = &Format::createWaveformChar_64_2;
break;
case 128:
createWaveformWithTimestamp_ = &Format::createWaveformChar_128_2;
createWaveformFromStream_ = &Format::createWaveformChar_128_2;
break;
case 256:
createWaveformWithTimestamp_ = &Format::createWaveformChar_256_2;
createWaveformFromStream_ = &Format::createWaveformChar_256_2;
break;
default:
throw new exception::Base("unhandled number of samples");
}
break;
default:
throw new exception::Base("unhandled number of channels");
}
break;
case Type::SHORT:
switch (numberOfChannels_) {
case 2:
switch (numberOfSamples_) {
case 1:
createWaveformWithTimestamp_ = &Format::createWaveformShort_1_2;
createWaveformFromStream_ = &Format::createWaveformShort_1_2;
break;
default:
throw new exception::Base("unhandled number of samples");
}
break;
default:
throw new exception::Base("unhandled number of channels");
}
break;
default:
throw new exception::Base("unhandled sample type");
}
}
bool Format::operator==(const Format& other) const {
return sampleType_ == other.sampleType_ &&
numberOfSamples_ == other.numberOfSamples_ &&
numberOfChannels_ == other.numberOfChannels_;
}
bool Format::operator!=(const Format& other) const {
return !(*this == other);
}
std::ostream& operator<<(std::ostream& os, const Format& format) {
os << "(";
os << int(format.getNumberOfBytesPerSample()) << " byte(s), ";
os << int(format.getNumberOfChannels()) << " ch, ";
os << format.getNumberOfSamples() << " sample(s) = ";
os << format.getDataSize() << " bytes)";
return os;
}
}
}
<commit_msg>removed logger assignment<commit_after>#include "data/Format.h"
#include "data/WaveformOf.h"
#include "util/Stream.h"
namespace blitzortung {
namespace data {
Format::Format(unsigned char numberOfBytes, unsigned char numberOfChannels, unsigned short numberOfSamples) :
sampleType_(Type::BYTE),
numberOfChannels_(numberOfChannels),
numberOfSamples_(numberOfSamples),
createWaveformWithTimestamp_(0),
createWaveformFromStream_(0),
logger_("data.Format")
{
updateSampleType(numberOfBytes);
updateFactoryMethod();
}
Format::Format() :
sampleType_(Type::BYTE),
numberOfChannels_(0),
numberOfSamples_(0),
createWaveformWithTimestamp_(0),
createWaveformFromStream_(0),
logger_("data.Format")
{
}
Format::Format(std::iostream& stream) :
sampleType_(Type::BYTE),
numberOfChannels_(0),
numberOfSamples_(0),
createWaveformWithTimestamp_(0),
createWaveformFromStream_(0),
logger_("data.Format")
{
fromStream(stream);
}
Format::~Format() = default;
Format& Format::operator=(const Format& other) {
numberOfChannels_ = other.numberOfChannels_;
numberOfSamples_ = other.numberOfSamples_;
sampleType_ = other.sampleType_;
createWaveformWithTimestamp_ = other.createWaveformWithTimestamp_;
createWaveformFromStream_ = other.createWaveformFromStream_;
return *this;
}
unsigned char Format::getNumberOfChannels() const {
return numberOfChannels_;
}
unsigned short Format::getNumberOfSamples() const {
return numberOfSamples_;
}
void Format::updateSampleType(unsigned char numberOfBytesPerSample) {
if (numberOfBytesPerSample == 1) {
sampleType_ = Type::BYTE;
} else if (numberOfBytesPerSample == 2) {
sampleType_ = Type::SHORT;
} else if (numberOfBytesPerSample == 4) {
sampleType_ = Type::INT;
} else {
// handle older format with number of bits per sample
if (numberOfBytesPerSample > 8) {
sampleType_ = Type::SHORT;
} else {
sampleType_ = Type::BYTE;
}
}
}
Format::Type Format::getDataType() const {
return sampleType_;
}
unsigned char Format::getNumberOfBytesPerSample() const {
return (unsigned char)(sampleType_);
}
unsigned int Format::getDataSize() const {
return getNumberOfBytesPerSample() * numberOfChannels_ * numberOfSamples_;
}
bool Format::isValid() const {
return getDataSize() > 0;
}
void Format::toStream(std::iostream& stream) const {
util::Stream::WriteValue(stream, numberOfSamples_);
util::Stream::WriteValue(stream, numberOfChannels_);
util::Stream::WriteValue(stream, (unsigned char)sampleType_);
}
void Format::fromStream(std::iostream& stream) {
util::Stream::ReadValue(stream, numberOfSamples_);
util::Stream::ReadValue(stream, numberOfChannels_);
{
unsigned char numberOfBytesPerSample;
util::Stream::ReadValue(stream, numberOfBytesPerSample);
updateSampleType(numberOfBytesPerSample);
}
updateFactoryMethod();
}
Waveform::AP Format::createWaveformChar_1_1(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 1, 1>(t0, dt));
}
Waveform::AP Format::createWaveformChar_1_1(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 1, 1>(date, stream));
}
Waveform::AP Format::createWaveformChar_64_1(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 64, 1>(t0, dt));
}
Waveform::AP Format::createWaveformChar_64_1(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 64, 1>(date, stream));
}
Waveform::AP Format::createWaveformChar_128_1(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 128, 1>(t0, dt));
}
Waveform::AP Format::createWaveformChar_128_1(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 128, 1>(date, stream));
}
Waveform::AP Format::createWaveformChar_256_1(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 256, 1>(t0, dt));
}
Waveform::AP Format::createWaveformChar_256_1(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 256, 1>(date, stream));
}
Waveform::AP Format::createWaveformChar_1_2(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 1, 2>(t0, dt));
}
Waveform::AP Format::createWaveformChar_1_2(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 1, 2>(date, stream));
}
Waveform::AP Format::createWaveformChar_64_2(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 64, 2>(t0, dt));
}
Waveform::AP Format::createWaveformChar_64_2(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 64, 2>(date, stream));
}
Waveform::AP Format::createWaveformChar_128_2(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 128, 2>(t0, dt));
}
Waveform::AP Format::createWaveformChar_128_2(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 128, 2>(date, stream));
}
Waveform::AP Format::createWaveformChar_256_2(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed char, 256, 2>(t0, dt));
}
Waveform::AP Format::createWaveformChar_256_2(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed char, 256, 2>(date, stream));
}
Waveform::AP Format::createWaveformShort_1_2(const pt::ptime& t0, const pt::time_duration& dt) {
return Waveform::AP(new WaveformOf<signed short, 1, 2>(t0, dt));
}
Waveform::AP Format::createWaveformShort_1_2(const gr::date& date, std::iostream& stream) {
return Waveform::AP(new WaveformOf<signed short, 1, 2>(date, stream));
}
Waveform::AP Format::createWaveform(const pt::ptime& t0, const pt::time_duration& dt) const {
return (*createWaveformWithTimestamp_)(t0, dt);
}
Waveform::AP Format::createWaveform(const gr::date& date, std::iostream& stream) const {
return (*createWaveformFromStream_)(date, stream);
}
void Format::updateFactoryMethod() {
switch (sampleType_) {
case Type::BYTE:
switch (numberOfChannels_) {
case 1:
switch (numberOfSamples_) {
case 1:
createWaveformWithTimestamp_ = &Format::createWaveformChar_1_1;
createWaveformFromStream_ = &Format::createWaveformChar_1_1;
break;
case 64:
createWaveformWithTimestamp_ = &Format::createWaveformChar_64_1;
createWaveformFromStream_ = &Format::createWaveformChar_64_1;
break;
case 128:
createWaveformWithTimestamp_ = &Format::createWaveformChar_128_1;
createWaveformFromStream_ = &Format::createWaveformChar_128_1;
break;
case 256:
createWaveformWithTimestamp_ = &Format::createWaveformChar_256_1;
createWaveformFromStream_ = &Format::createWaveformChar_256_1;
break;
default:
throw new exception::Base("unhandled number of samples");
}
break;
case 2:
switch (numberOfSamples_) {
case 1:
createWaveformWithTimestamp_ = &Format::createWaveformChar_1_2;
createWaveformFromStream_ = &Format::createWaveformChar_1_2;
break;
case 64:
createWaveformWithTimestamp_ = &Format::createWaveformChar_64_2;
createWaveformFromStream_ = &Format::createWaveformChar_64_2;
break;
case 128:
createWaveformWithTimestamp_ = &Format::createWaveformChar_128_2;
createWaveformFromStream_ = &Format::createWaveformChar_128_2;
break;
case 256:
createWaveformWithTimestamp_ = &Format::createWaveformChar_256_2;
createWaveformFromStream_ = &Format::createWaveformChar_256_2;
break;
default:
throw new exception::Base("unhandled number of samples");
}
break;
default:
throw new exception::Base("unhandled number of channels");
}
break;
case Type::SHORT:
switch (numberOfChannels_) {
case 2:
switch (numberOfSamples_) {
case 1:
createWaveformWithTimestamp_ = &Format::createWaveformShort_1_2;
createWaveformFromStream_ = &Format::createWaveformShort_1_2;
break;
default:
throw new exception::Base("unhandled number of samples");
}
break;
default:
throw new exception::Base("unhandled number of channels");
}
break;
default:
throw new exception::Base("unhandled sample type");
}
}
bool Format::operator==(const Format& other) const {
return sampleType_ == other.sampleType_ &&
numberOfSamples_ == other.numberOfSamples_ &&
numberOfChannels_ == other.numberOfChannels_;
}
bool Format::operator!=(const Format& other) const {
return !(*this == other);
}
std::ostream& operator<<(std::ostream& os, const Format& format) {
os << "(";
os << int(format.getNumberOfBytesPerSample()) << " byte(s), ";
os << int(format.getNumberOfChannels()) << " ch, ";
os << format.getNumberOfSamples() << " sample(s) = ";
os << format.getDataSize() << " bytes)";
return os;
}
}
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-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, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: outofcore_process.cpp 7463 2012-10-05 05:03:04Z stfox88 $
* \author Justin Rosen
* \author Stephen Fox
*/
#include <pcl/common/time.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/pcl_macros.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/outofcore/outofcore.h>
#include <pcl/outofcore/outofcore_impl.h>
// todo: Read clouds as PointCloud2 so we don't need to define PointT explicitly.
// This also requires our octree to take PointCloud2 as an input.
typedef pcl::PointXYZ PointT;
using namespace pcl;
using namespace pcl::outofcore;
using namespace sensor_msgs;
using pcl::console::parse_argument;
using pcl::console::parse_file_extension_argument;
using pcl::console::find_switch;
using pcl::console::print_error;
using pcl::console::print_warn;
using pcl::console::print_info;
using pcl::console::print;
#include <boost/foreach.hpp>
typedef OutofcoreOctreeBase<> OctreeDisk;
typedef OutofcoreOctreeBaseNode<> OctreeDiskNode;
typedef OutofcoreBreadthFirstIterator<> OctreeBreadthFirstIterator;
typedef OutofcoreDepthFirstIterator<> OctreeDepthFirstIterator;
typedef Eigen::aligned_allocator<PointT> AlignedPointT;
void
printDepth(size_t depth)
{
for (int i=0; i < depth; i++)
PCL_INFO (" ");
}
void
printNode(OctreeDiskNode *)
{
//
}
int
outofcorePrint (boost::filesystem::path tree_root, size_t print_depth, bool bounding_box=false, bool breadth_first=false)
{
std::cout << boost::filesystem::absolute (tree_root) << std::endl;
OctreeDisk* octree;
octree = new OctreeDisk (tree_root, true);
Eigen::Vector3d min, max;
octree->getBoundingBox(min, max);
// Cloud bounding box
PCL_INFO (" Bounding Box: <%lf, %lf, %lf> - <%lf, %lf, %lf>\n", min[0], min[1], min[2], max[0], max[1], max[2]);
// Cloud depth
uint64_t depth = octree->getTreeDepth ();
PCL_INFO (" Depth: %ld\n", depth);
if (print_depth > depth)
print_depth = depth;
// Cloud point counts at each level
std::vector<boost::uint64_t> lodPoints = octree->getNumPointsVector ();
PCL_INFO (" Points:\n");
for (boost::uint64_t i = 0; i < lodPoints.size (); i++)
PCL_INFO (" %d: %d\n", i, lodPoints[i]);
// Cloud voxel side length
PCL_INFO(" Voxel Side Length: %d\n", octree->getVoxelSideLength ());
// Cloud voxel count
std::vector<PointT, AlignedPointT> voxel_centers;
octree->getOccupiedVoxelCenters(voxel_centers);
PCL_INFO(" Voxel Count: %d\n", voxel_centers.size ());
if (!breadth_first)
{
OctreeDisk::DepthFirstIterator depth_first_it (*octree);
while ( *depth_first_it !=0 )
{
OctreeDiskNode *node = *depth_first_it;
size_t node_depth = node->getDepth();
printDepth(node_depth);
std::string metadata_relative_file = node->getMetadataFilename ().string ();
boost::replace_first(metadata_relative_file, tree_root.parent_path ().string (), "");
PCL_INFO ("..%s\n", metadata_relative_file.c_str());
printDepth(node_depth);
std::string pcd_relative_file = node->getPCDFilename ().string ();
boost::replace_first(pcd_relative_file, tree_root.parent_path ().string (), "");
PCL_INFO (" PCD: ..%s\n", pcd_relative_file.c_str());
if (bounding_box)
{
Eigen::Vector3d min, max;
node->getBoundingBox(min, max);
printDepth(node_depth);
PCL_INFO (" Bounding Box: <%lf, %lf, %lf> - <%lf, %lf, %lf>\n", min[0], min[1], min[2], max[0], max[1], max[2]);
}
depth_first_it++;
}
}
else
{
OctreeDisk::BreadthFirstIterator breadth_first_it (*octree);
breadth_first_it.setMaxDepth (static_cast<unsigned int> (print_depth));
while ( *breadth_first_it !=0 )
{
OctreeDiskNode *node = *breadth_first_it;
size_t node_depth = node->getDepth();
printDepth(node_depth);
std::string metadata_relative_file = node->getMetadataFilename ().string ();
boost::replace_first(metadata_relative_file, tree_root.parent_path ().string (), "");
PCL_INFO ("..%s\n", metadata_relative_file.c_str());
printDepth(node_depth);
std::string pcd_relative_file = node->getPCDFilename ().string ();
boost::replace_first(pcd_relative_file, tree_root.parent_path ().string (), "");
PCL_INFO (" PCD: ..%s\n", pcd_relative_file.c_str());
if (bounding_box)
{
Eigen::Vector3d min, max;
node->getBoundingBox(min, max);
printDepth(node_depth);
PCL_INFO (" Bounding Box: <%lf, %lf, %lf> - <%lf, %lf, %lf>\n", min[0], min[1], min[2], max[0], max[1], max[2]);
}
breadth_first_it++;
}
}
return 0;
}
void
printHelp (int, char **argv)
{
print_info ("This program is used to process pcd fiels into an outofcore data structure viewable by the");
print_info ("pcl_outofcore_viewer\n\n");
print_info ("%s <options> <input_tree_dir> \n", argv[0]);
print_info ("\n");
print_info ("Options:\n");
print_info ("\t -depth <depth> \t Octree depth\n");
print_info ("\t -bounding_box \t Print bounding box info\n");
print_info ("\t -breadth \t Print nodes in breadth-first (Default depth-first)\n");
print_info ("\t -h \t Display help\n");
print_info ("\n");
}
int
main (int argc, char* argv[])
{
// Check for help (-h) flag
if (argc > 1)
{
if (find_switch (argc, argv, "-h"))
{
printHelp (argc, argv);
return (-1);
}
}
// If no arguments specified
if (argc - 1 < 1)
{
printHelp (argc, argv);
return (-1);
}
if (find_switch (argc, argv, "-v"))
console::setVerbosityLevel (console::L_DEBUG);
// Defaults
int depth = INT_MAX;
bool breadth_first = find_switch (argc, argv, "-breadth");
bool bounding_box = find_switch (argc, argv, "-bounding_box");
// Parse options
parse_argument (argc, argv, "-depth", depth);
// Parse non-option arguments
boost::filesystem::path tree_root (argv[argc - 1]);
// Check if a root directory was specified, use directory of pcd file
if (boost::filesystem::is_directory (tree_root))
{
boost::filesystem::directory_iterator diterend;
for (boost::filesystem::directory_iterator diter (tree_root); diter != diterend; ++diter)
{
const boost::filesystem::path& file = *diter;
if (!boost::filesystem::is_directory (file))
{
if (boost::filesystem::extension (file) == OctreeDiskNode::node_index_extension)
{
tree_root = file;
}
}
}
}
return outofcorePrint (tree_root, depth, bounding_box, breadth_first);
}
<commit_msg>* added a patch to display more statistics for @pcl_outofcore_print@ (thanks Gunnar!)<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-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, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: outofcore_process.cpp 7463 2012-10-05 05:03:04Z stfox88 $
* \author Justin Rosen
* \author Stephen Fox
*/
#include <pcl/common/time.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/pcl_macros.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/outofcore/outofcore.h>
#include <pcl/outofcore/outofcore_impl.h>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/variance.hpp>
namespace ba = boost::accumulators;
// todo: Read clouds as PointCloud2 so we don't need to define PointT explicitly.
// This also requires our octree to take PointCloud2 as an input.
typedef pcl::PointXYZ PointT;
using namespace pcl;
using namespace pcl::outofcore;
using namespace sensor_msgs;
using pcl::console::parse_argument;
using pcl::console::parse_file_extension_argument;
using pcl::console::find_switch;
using pcl::console::print_error;
using pcl::console::print_warn;
using pcl::console::print_info;
using pcl::console::print;
#include <boost/foreach.hpp>
typedef OutofcoreOctreeBase<> OctreeDisk;
typedef OutofcoreOctreeBaseNode<> OctreeDiskNode;
typedef OutofcoreBreadthFirstIterator<> OctreeBreadthFirstIterator;
typedef OutofcoreDepthFirstIterator<> OctreeDepthFirstIterator;
typedef Eigen::aligned_allocator<PointT> AlignedPointT;
void
printDepth(size_t depth)
{
for (int i=0; i < depth; i++)
PCL_INFO (" ");
}
void
printNode(OctreeDiskNode *)
{
//
}
int
outofcorePrint (boost::filesystem::path tree_root, size_t print_depth, bool bounding_box=false, bool pcd=false,
bool point_count=false, bool breadth_first=false)
{
std::cout << boost::filesystem::absolute (tree_root) << std::endl;
OctreeDisk* octree;
octree = new OctreeDisk (tree_root, true);
Eigen::Vector3d min, max;
octree->getBoundingBox(min, max);
// Cloud bounding box
PCL_INFO (" Bounding Box: <%lf, %lf, %lf> - <%lf, %lf, %lf>\n", min[0], min[1], min[2], max[0], max[1], max[2]);
// Cloud depth
uint64_t depth = octree->getTreeDepth ();
PCL_INFO (" Depth: %ld\n", depth);
if (print_depth > depth)
print_depth = depth;
// Cloud point counts at each level
std::vector<boost::uint64_t> lodPoints = octree->getNumPointsVector ();
PCL_INFO (" Points:\n");
for (boost::uint64_t i = 0; i < lodPoints.size (); i++)
PCL_INFO (" %d: %d\n", i, lodPoints[i]);
// Cloud voxel side length
PCL_INFO(" Voxel Side Length: %d\n", octree->getVoxelSideLength ());
// Cloud voxel count
std::vector<PointT, AlignedPointT> voxel_centers;
octree->getOccupiedVoxelCenters(voxel_centers);
PCL_INFO(" Voxel Count: %d\n", voxel_centers.size ());
// Point data for statistics
std::vector<boost::uint64_t> pointsPerVoxel;
ba::accumulator_set<boost::uint64_t, ba::features< ba::tag::min, ba::tag::max, ba::tag::mean, ba::tag::variance> > acc;
if (!breadth_first)
{
OctreeDisk::DepthFirstIterator depth_first_it (*octree);
while ( *depth_first_it !=0 )
{
OctreeDiskNode *node = *depth_first_it;
size_t node_depth = node->getDepth();
printDepth(node_depth);
std::string metadata_relative_file = node->getMetadataFilename ().string ();
boost::replace_first(metadata_relative_file, tree_root.parent_path ().string (), "");
PCL_INFO ("..%s\n", metadata_relative_file.c_str());
printDepth(node_depth);
if (pcd)
{
std::string pcd_relative_file = node->getPCDFilename ().string ();
boost::replace_first(pcd_relative_file, tree_root.parent_path ().string (), "");
PCL_INFO (" PCD: ..%s\n", pcd_relative_file.c_str());
}
if (bounding_box)
{
Eigen::Vector3d min, max;
node->getBoundingBox(min, max);
printDepth(node_depth);
PCL_INFO (" Bounding Box: <%lf, %lf, %lf> - <%lf, %lf, %lf>\n", min[0], min[1], min[2], max[0], max[1], max[2]);
}
if (point_count)
{
printDepth(node_depth);
PCL_INFO (" Points: %lu\n", node->getDataSize());
pointsPerVoxel.push_back( node->getDataSize());
acc(node->getDataSize());
}
depth_first_it++;
}
}
else
{
OctreeDisk::BreadthFirstIterator breadth_first_it (*octree);
breadth_first_it.setMaxDepth (static_cast<unsigned int> (print_depth));
while ( *breadth_first_it !=0 )
{
OctreeDiskNode *node = *breadth_first_it;
size_t node_depth = node->getDepth();
printDepth(node_depth);
std::string metadata_relative_file = node->getMetadataFilename ().string ();
boost::replace_first(metadata_relative_file, tree_root.parent_path ().string (), "");
PCL_INFO ("..%s\n", metadata_relative_file.c_str());
printDepth(node_depth);
if(pcd)
{
std::string pcd_relative_file = node->getPCDFilename ().string ();
boost::replace_first(pcd_relative_file, tree_root.parent_path ().string (), "");
PCL_INFO (" PCD: ..%s\n", pcd_relative_file.c_str());
}
if (bounding_box)
{
Eigen::Vector3d min, max;
node->getBoundingBox(min, max);
printDepth(node_depth);
PCL_INFO (" Bounding Box: <%lf, %lf, %lf> - <%lf, %lf, %lf>\n", min[0], min[1], min[2], max[0], max[1], max[2]);
}
if (point_count)
{
printDepth(node_depth);
PCL_INFO (" Points: %lu\n", node->getDataSize());
pointsPerVoxel.push_back( node->getDataSize());
acc(node->getDataSize());
}
breadth_first_it++;
}
}
if(point_count)
{
PCL_INFO("Points per Voxel:\n");
PCL_INFO("Min: %u, Max: %u, Mean: %f, StdDev %f\n", ba::min(acc),
ba::max(acc), ba::mean(acc), sqrt(ba::variance(acc)));
}
return 0;
}
void
printHelp (int, char **argv)
{
print_info ("This program is used to process pcd fiels into an outofcore data structure viewable by the");
print_info ("pcl_outofcore_viewer\n\n");
print_info ("%s <options> <input_tree_dir> \n", argv[0]);
print_info ("\n");
print_info ("Options:\n");
print_info ("\t -depth <depth> \t Octree depth\n");
print_info ("\t -bounding_box \t Print bounding box info\n");
print_info ("\t -point_count \t Print point count info\n");
print_info ("\t -pcd \t Print pcd file info\n");
print_info ("\t -breadth \t Print nodes in breadth-first (Default depth-first)\n");
print_info ("\t -h \t Display help\n");
print_info ("\n");
}
int
main (int argc, char* argv[])
{
// Check for help (-h) flag
if (argc > 1)
{
if (find_switch (argc, argv, "-h"))
{
printHelp (argc, argv);
return (-1);
}
}
// If no arguments specified
if (argc - 1 < 1)
{
printHelp (argc, argv);
return (-1);
}
if (find_switch (argc, argv, "-v"))
console::setVerbosityLevel (console::L_DEBUG);
// Defaults
int depth = INT_MAX;
bool breadth_first = find_switch (argc, argv, "-breadth");
bool bounding_box = find_switch (argc, argv, "-bounding_box");
bool pcd = find_switch (argc, argv, "-pcd");
bool point_count = find_switch (argc, argv, "-point_count");
// Parse options
parse_argument (argc, argv, "-depth", depth);
// Parse non-option arguments
boost::filesystem::path tree_root (argv[argc - 1]);
// Check if a root directory was specified, use directory of pcd file
if (boost::filesystem::is_directory (tree_root))
{
boost::filesystem::directory_iterator diterend;
for (boost::filesystem::directory_iterator diter (tree_root); diter != diterend; ++diter)
{
const boost::filesystem::path& file = *diter;
if (!boost::filesystem::is_directory (file))
{
if (boost::filesystem::extension (file) == OctreeDiskNode::node_index_extension)
{
tree_root = file;
}
}
}
}
return outofcorePrint (tree_root, depth, bounding_box, pcd, point_count, breadth_first);
}
<|endoftext|> |
<commit_before>/***********************************************************************
* 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/. *
***********************************************************************/
#include <Duck.hpp>
Duck::Duck(sf::Texture duck_textures[4], sf::Texture duckies_textures[4], Coord starting_coordinates, Direction initial_direction){
st_coordinates = starting_coordinates;
coordinates = starting_coordinates;
for(unsigned char i = 4 ; i--;){
duck_sprite[i].setTexture(duck_textures[i]);
}
direction = initial_direction;
for(unsigned char i = 4 ; i--;){
ducky_sprite[i].setTexture(duckies_textures[i]);
}
direction = initial_direction;
for(unsigned char i = DUCKIES_INITIAL_NUMBER; i--;){
duckies.push_back(Ducky(starting_coordinates, starting_coordinates, direction));
}
}
void Duck::damaged(){
duckies.pop_back();
coordinates = st_coordinates;
invulnerability = MOVES_INVULNERABLE;
for(unsigned char i = static_cast<unsigned char>(duckies.size()); i--;){
duckies[i].resetCoord();
}
}
void Duck::powerUp(sf::RenderWindow& window){
Coord new_coord = duckies.back().coordinates;
Direction new_dir;
switch(duckies.back().direction){
case UP:
new_dir = DOWN;
++new_coord.y;
break;
case LEFT:
new_dir = RIGHT;
++new_coord.x;
break;
case DOWN:
new_dir = UP;
--new_coord.y;
break;
case RIGHT:
default:
new_dir = LEFT;
--new_coord.x;
}
duckies.push_back(Ducky(new_coord, st_coordinates, new_dir));
ducky_sprite[duckies.back().direction].setPosition(static_cast<float>(duckies.back().coordinates.x * 32), static_cast<float>(duckies.back().coordinates.y * 32));
window.draw(ducky_sprite[duckies.back().direction]);
}
void Duck::move(sf::RenderWindow& window, Direction new_direction){
for(unsigned char i = static_cast<unsigned char>(duckies.size()); i > 0 ; i--){
if(duckies[i].coordinates != duckies[i - 1].coordinates)
/* FIXME : DARK MAGIC THAT RESULTS IN SIGSEV/SIGABRT WHENEVER THE GAME CLOSES */
duckies[i].move(duckies[i - 1].direction);
}
if(duckies.front().coordinates != coordinates){
duckies.front().move(direction);
}
switch(new_direction){
case UP:
--coordinates.y;
break;
case LEFT:
--coordinates.x;
break;
case DOWN:
++coordinates.y;
break;
case RIGHT:
++coordinates.x;
break;
default:
break;
}
direction = new_direction;
this->print(window);
}
unsigned char Duck::size(){
return static_cast<unsigned char>(duckies.size());
}
void Duck::print(sf::RenderWindow& window){
for(unsigned char i = static_cast<unsigned char>(duckies.size()); i--;){
ducky_sprite[duckies[i].direction].setPosition(static_cast<float>(duckies[i].coordinates.x * 32), static_cast<float>(duckies[i].coordinates.y * 32));
window.draw(ducky_sprite[duckies[i].direction]);
}
duck_sprite[direction].setPosition(static_cast<float>(coordinates.x * 32), static_cast<float>(coordinates.y * 32));
window.draw(duck_sprite[direction]);
}
<commit_msg>Fixing the dark magic<commit_after>/***********************************************************************
* 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/. *
***********************************************************************/
#include <Duck.hpp>
Duck::Duck(sf::Texture duck_textures[4], sf::Texture duckies_textures[4], Coord starting_coordinates, Direction initial_direction){
st_coordinates = starting_coordinates;
coordinates = starting_coordinates;
for(unsigned char i = 4 ; i--;){
duck_sprite[i].setTexture(duck_textures[i]);
}
direction = initial_direction;
for(unsigned char i = 4 ; i--;){
ducky_sprite[i].setTexture(duckies_textures[i]);
}
direction = initial_direction;
for(unsigned char i = DUCKIES_INITIAL_NUMBER; i--;){
duckies.push_back(Ducky(starting_coordinates, starting_coordinates, direction));
}
}
void Duck::damaged(){
duckies.pop_back();
coordinates = st_coordinates;
invulnerability = MOVES_INVULNERABLE;
for(unsigned char i = static_cast<unsigned char>(duckies.size()); i--;){
duckies[i].resetCoord();
}
}
void Duck::powerUp(sf::RenderWindow& window){
Coord new_coord = duckies.back().coordinates;
Direction new_dir;
switch(duckies.back().direction){
case UP:
new_dir = DOWN;
++new_coord.y;
break;
case LEFT:
new_dir = RIGHT;
++new_coord.x;
break;
case DOWN:
new_dir = UP;
--new_coord.y;
break;
case RIGHT:
default:
new_dir = LEFT;
--new_coord.x;
}
duckies.push_back(Ducky(new_coord, st_coordinates, new_dir));
ducky_sprite[duckies.back().direction].setPosition(static_cast<float>(duckies.back().coordinates.x * 32), static_cast<float>(duckies.back().coordinates.y * 32));
window.draw(ducky_sprite[duckies.back().direction]);
}
void Duck::move(sf::RenderWindow& window, Direction new_direction){
for(unsigned char i = static_cast<unsigned char>(duckies.size() - 1); i > 0 ; i--){
if(duckies[i].coordinates != duckies[i - 1].coordinates)
duckies[i].move(duckies[i - 1].direction);
}
if(duckies.front().coordinates != coordinates){
duckies.front().move(direction);
}
switch(new_direction){
case UP:
--coordinates.y;
break;
case LEFT:
--coordinates.x;
break;
case DOWN:
++coordinates.y;
break;
case RIGHT:
++coordinates.x;
break;
default:
break;
}
direction = new_direction;
this->print(window);
}
unsigned char Duck::size(){
return static_cast<unsigned char>(duckies.size());
}
void Duck::print(sf::RenderWindow& window){
for(unsigned char i = static_cast<unsigned char>(duckies.size()); i--;){
ducky_sprite[duckies[i].direction].setPosition(static_cast<float>(duckies[i].coordinates.x * 32), static_cast<float>(duckies[i].coordinates.y * 32));
window.draw(ducky_sprite[duckies[i].direction]);
}
duck_sprite[direction].setPosition(static_cast<float>(coordinates.x * 32), static_cast<float>(coordinates.y * 32));
window.draw(duck_sprite[direction]);
}
<|endoftext|> |
<commit_before>// Copyright 2010-2015 RethinkDB, all rights reserved.
#ifndef CONTAINERS_SEGMENTED_VECTOR_HPP_
#define CONTAINERS_SEGMENTED_VECTOR_HPP_
#include <stdio.h>
#include <utility>
#include <vector>
#include "errors.hpp"
template <class element_t, size_t ELEMENTS_PER_SEGMENT = (1 << 14)>
class segmented_vector_t {
public:
explicit segmented_vector_t(size_t size = 0) : size_(0) {
set_size(size);
}
segmented_vector_t(segmented_vector_t &&movee)
: segments_(std::move(movee.segments_)), size_(movee.size_) {
movee.segments_.clear();
movee.size_ = 0;
}
segmented_vector_t &operator=(segmented_vector_t &&movee) {
segmented_vector_t tmp(std::move(movee));
std::swap(segments_, tmp.segments_);
std::swap(size_, tmp.size_);
return *this;
}
~segmented_vector_t() {
set_size(0);
}
size_t size() const {
return size_;
}
bool empty() const {
return size_ == 0;
}
// Gets an element, without creating a segment_t if its segment doesn't exist.
// (Thus, this method doesn't return a reference.)
element_t get_sparsely(size_t index) const {
guarantee(index < size_, "index = %zu, size_ = %zu", index, size_);
const size_t segment_index = index / ELEMENTS_PER_SEGMENT;
segment_t *seg = segments_[segment_index];
if (seg == NULL) {
return element_t();
} else {
return seg->elements[index % ELEMENTS_PER_SEGMENT];
}
}
element_t &operator[](size_t index) {
return get_element(index);
}
const element_t &operator[](size_t index) const {
return get_element(index);
}
void push_back(const element_t &element) {
size_t old_size = size_;
set_size(old_size + 1);
(*this)[old_size] = element;
}
void push_back(element_t &&element) {
size_t old_size = size_;
set_size(old_size + 1);
(*this)[old_size] = std::move(element);
}
element_t &back() {
return (*this)[size_ - 1];
}
void pop_back() {
guarantee(size_ > 0);
set_size(size_ - 1);
}
void clear() {
set_size(0);
}
void resize_with_zeros(size_t new_size) {
set_size(new_size);
}
private:
// Gets a non-const element with a const function... which breaks the guarantees
// but compiles and lets this be called by both the const and non-const versions
// of operator[].
element_t &get_element(size_t index) const {
guarantee(index < size_, "index = %zu, size_ = %zu", index, size_);
const size_t segment_index = index / ELEMENTS_PER_SEGMENT;
segment_t *seg = segments_[segment_index];
if (seg == NULL) {
seg = new segment_t();
segments_[segment_index] = seg;
}
return seg->elements[index % ELEMENTS_PER_SEGMENT];
}
// Note: sometimes elements will be initialized before you ask the
// array to grow to that size (e.g. one hundred elements might be
// initialized even though the array might be of size 1).
void set_size(size_t new_size) {
{
const size_t num_segs = size_ != 0 ? ((size_ - 1) / ELEMENTS_PER_SEGMENT) + 1 : 0;
guarantee(num_segs == segments_.size());
}
const size_t new_num_segs = new_size != 0 ? ((new_size - 1) / ELEMENTS_PER_SEGMENT) + 1 : 0;
while (segments_.size() > new_num_segs) {
delete segments_.back();
segments_.pop_back();
}
while (segments_.size() < new_num_segs) {
segments_.push_back(NULL);
}
size_ = new_size;
}
struct segment_t {
segment_t() : elements() { } // Zero-initialize array.
element_t elements[ELEMENTS_PER_SEGMENT];
};
mutable std::vector<segment_t *> segments_;
size_t size_;
DISABLE_COPYING(segmented_vector_t);
};
#endif // CONTAINERS_SEGMENTED_VECTOR_HPP_
<commit_msg>Small optimization for single writes<commit_after>// Copyright 2010-2015 RethinkDB, all rights reserved.
#ifndef CONTAINERS_SEGMENTED_VECTOR_HPP_
#define CONTAINERS_SEGMENTED_VECTOR_HPP_
#include <stdio.h>
#include <utility>
#include <vector>
#include "errors.hpp"
template <class element_t, size_t ELEMENTS_PER_SEGMENT = (1 << 14)>
class segmented_vector_t {
public:
explicit segmented_vector_t(size_t size = 0) : size_(0) {
set_size(size);
}
segmented_vector_t(segmented_vector_t &&movee)
: segments_(std::move(movee.segments_)), size_(movee.size_) {
movee.segments_.clear();
movee.size_ = 0;
}
segmented_vector_t &operator=(segmented_vector_t &&movee) {
segmented_vector_t tmp(std::move(movee));
std::swap(segments_, tmp.segments_);
std::swap(size_, tmp.size_);
return *this;
}
~segmented_vector_t() {
set_size(0);
}
size_t size() const {
return size_;
}
bool empty() const {
return size_ == 0;
}
// Gets an element, without creating a segment_t if its segment doesn't exist.
// (Thus, this method doesn't return a reference.)
element_t get_sparsely(size_t index) const {
guarantee(index < size_, "index = %zu, size_ = %zu", index, size_);
const size_t segment_index = index / ELEMENTS_PER_SEGMENT;
segment_t *seg = segments_[segment_index];
if (seg == NULL) {
return element_t();
} else {
return seg->elements[index % ELEMENTS_PER_SEGMENT];
}
}
element_t &operator[](size_t index) {
return get_element(index);
}
const element_t &operator[](size_t index) const {
return get_element(index);
}
void push_back(const element_t &element) {
size_t old_size = size_;
set_size(old_size + 1);
(*this)[old_size] = element;
}
void push_back(element_t &&element) {
size_t old_size = size_;
set_size(old_size + 1);
(*this)[old_size] = std::move(element);
}
element_t &back() {
return (*this)[size_ - 1];
}
void pop_back() {
guarantee(size_ > 0);
set_size(size_ - 1);
}
void clear() {
set_size(0);
}
void resize_with_zeros(size_t new_size) {
set_size(new_size);
}
private:
// Gets a non-const element with a const function... which breaks the guarantees
// but compiles and lets this be called by both the const and non-const versions
// of operator[].
element_t &get_element(size_t index) const {
guarantee(index < size_, "index = %zu, size_ = %zu", index, size_);
const size_t segment_index = index / ELEMENTS_PER_SEGMENT;
segment_t *seg = segments_[segment_index];
if (seg == NULL) {
seg = new segment_t();
segments_[segment_index] = seg;
}
return seg->elements[index % ELEMENTS_PER_SEGMENT];
}
// Note: sometimes elements will be initialized before you ask the
// array to grow to that size (e.g. one hundred elements might be
// initialized even though the array might be of size 1).
void set_size(size_t new_size) {
const size_t new_num_segs = new_size != 0 ? ((new_size - 1) / ELEMENTS_PER_SEGMENT) + 1 : 0;
// Leave an additional segment when resizing to avoid allocating and
// deallocating large blocks at a boundary, i.e. 0 elements.
while (segments_.size() > new_num_segs + 1) {
delete segments_.back();
segments_.pop_back();
}
while (segments_.size() < new_num_segs) {
segments_.push_back(NULL);
}
size_ = new_size;
}
struct segment_t {
segment_t() : elements() { } // Zero-initialize array.
element_t elements[ELEMENTS_PER_SEGMENT];
};
mutable std::vector<segment_t *> segments_;
size_t size_;
DISABLE_COPYING(segmented_vector_t);
};
#endif // CONTAINERS_SEGMENTED_VECTOR_HPP_
<|endoftext|> |
<commit_before>#ifndef COMMON_H
#define COMMON_H 1
#include <cassert>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <sys/time.h>
#include <memcached/engine.h>
#include "config.h"
#if defined(HAVE_MEMORY)
# include <memory>
#endif
#if defined(HAVE_TR1_MEMORY)
# include <tr1/memory>
#endif
#if defined(HAVE_BOOST_SHARED_PTR_HPP)
# include <boost/shared_ptr.hpp>
#endif
#if defined(SHARED_PTR_NAMESPACE)
using SHARED_PTR_NAMESPACE::shared_ptr;
#else
# error No shared pointer implementation found!
#endif
// Stolen from http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
// Utility functions implemented in various modules.
extern EXTENSION_LOGGER_DESCRIPTOR *getLogger(void);
// Time handling functions
inline void advance_tv(struct timeval &tv, const double secs) {
double ip, fp;
fp = modf(secs, &ip);
int usec = static_cast<int>(fp * 1e6) + static_cast<int>(tv.tv_usec);
int quot = usec / 1000000;
int rem = usec % 1000000;
tv.tv_sec = static_cast<int>(ip) + tv.tv_sec + quot;
tv.tv_usec = rem;
}
inline bool less_tv(const struct timeval &tv1, const struct timeval &tv2) {
if (tv1.tv_sec == tv2.tv_sec) {
return tv1.tv_usec < tv2.tv_usec;
} else {
return tv1.tv_sec < tv2.tv_sec;
}
}
inline bool parseUint16(const char *in, uint16_t *out) {
assert(out != NULL);
errno = 0;
*out = 0;
char *endptr;
long num = strtol(in, &endptr, 10);
if (errno == ERANGE || num < 0 || num > UINT16_MAX) {
return false;
}
if (isspace(*endptr) || (*endptr == '\0' && endptr != in)) {
*out = static_cast<uint16_t>(num);
return true;
}
return false;
}
#endif /* COMMON_H */
<commit_msg>Compile fix: Linux doesn't get limits from limits.h.<commit_after>#ifndef COMMON_H
#define COMMON_H 1
#include <cassert>
#include <errno.h>
#include <stdint.h>
#include <limits.h>
#include <math.h>
#include <sys/time.h>
#include <memcached/engine.h>
#include "config.h"
#if defined(HAVE_MEMORY)
# include <memory>
#endif
#if defined(HAVE_TR1_MEMORY)
# include <tr1/memory>
#endif
#if defined(HAVE_BOOST_SHARED_PTR_HPP)
# include <boost/shared_ptr.hpp>
#endif
#if defined(SHARED_PTR_NAMESPACE)
using SHARED_PTR_NAMESPACE::shared_ptr;
#else
# error No shared pointer implementation found!
#endif
// Stolen from http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
// Utility functions implemented in various modules.
extern EXTENSION_LOGGER_DESCRIPTOR *getLogger(void);
// Time handling functions
inline void advance_tv(struct timeval &tv, const double secs) {
double ip, fp;
fp = modf(secs, &ip);
int usec = static_cast<int>(fp * 1e6) + static_cast<int>(tv.tv_usec);
int quot = usec / 1000000;
int rem = usec % 1000000;
tv.tv_sec = static_cast<int>(ip) + tv.tv_sec + quot;
tv.tv_usec = rem;
}
inline bool less_tv(const struct timeval &tv1, const struct timeval &tv2) {
if (tv1.tv_sec == tv2.tv_sec) {
return tv1.tv_usec < tv2.tv_usec;
} else {
return tv1.tv_sec < tv2.tv_sec;
}
}
inline bool parseUint16(const char *in, uint16_t *out) {
assert(out != NULL);
errno = 0;
*out = 0;
char *endptr;
long num = strtol(in, &endptr, 10);
if (errno == ERANGE || num < 0 || num > UINT16_MAX) {
return false;
}
if (isspace(*endptr) || (*endptr == '\0' && endptr != in)) {
*out = static_cast<uint16_t>(num);
return true;
}
return false;
}
#endif /* COMMON_H */
<|endoftext|> |
<commit_before>// Gavin Kyte
// Thu Nov 2 16:08:49 2017
#include <iostream>
#include <iomanip>
using namespace std;
template <class T> class AVLComparisonTree {
public:
struct Node {
Node* parent;
Node* left;
Node* right;
T value;
int height;
static const int numTypes = 2;
int typeCounter[2];
Node* sibling() {
Node* sib = nullptr;
if(this->parent) {
if(this->parent->value >= this->value) {
sib = this->parent->right;
} else {
sib = this->parent->left;
}
}
return sib;
}
Node(T value, Node* parent) {
this->value = value;
this->parent = parent;
left = nullptr;
right = nullptr;
height = 1;
typeCounter[0] = 0;
typeCounter[1] = 0;
}
};
Node* root;
int size;
AVLComparisonTree() {
root = nullptr;
size = 0;
}
// Takes value and type number for future comparison
void insert(T value, int type) {
if(!root) {
root = new Node(value, nullptr);
}
Node* nomad = root;
while(1) {
if(value < nomad->value && nomad->left){
nomad = nomad->left;
} else if(value < nomad->value && !nomad->left){
nomad->left = new Node(value, nomad);
} else if(value > nomad->value && nomad->right){
nomad = nomad->right;
} else if(value > nomad->value && !nomad->right){
nomad->right = new Node(value, nomad);
} else if(value == nomad->value) { // Always last case
nomad->typeCounter[type]++;
break;
}
}
while(nomad->parent) {
nomad = nomad->parent;
// balance calculated after nomad height is increased,
// and the initial difference can't be more than 1,
// thus the nomad is always +0, +1, or +2 relative to sibling
int balance = diff(nomad->left, nomad->right);
cout << "balance on "<<nomad->value<<": "<< balance << endl;
if(balance == 0) { // No change in parent's height factor
break;
} else if(balance == 1) { // Change parent's height
nomad->height++;
continue;
} else { // balance == 2
rotate(nomad);
}
}
size++;
}
// Handle nullptr exception for height calc
int height(Node* n) {
int heightValue = 0;
if(n)
heightValue = n->height;
return heightValue;
}
/**
* Helper method to calculate absolute value of height difference
* requires child to be non-null Node ptr, but sibling can be null
* returns +value which is likely 0, 1, or 2 if used correctly.
*/
int diff(Node* child, Node* sibling) {
int cHeight = 0;
if(child)
cHeight = child->height;
int sHeight = 0;
if(sibling)
sHeight = sibling->height;
int difference = cHeight - sHeight;
if(difference < 0) { // Is this ever going to happen?
difference = -1 * difference;
}
return difference;
}
void rotate(Node* parent) {
// Determine rotation type
cout<<"calling rotation"<<endl;
Node* child;
if(!parent) throw(1);
if(height(parent->left) > height(parent->right)) {
child = parent->left;
if(height(child->left) > height(child->right))
{cout<<"calling ll"<<endl;
llRotation(parent);}
else
{cout<<"calling lr"<<endl;
lrRotation(parent);}
} else {
child = parent->right;
if(height(child->left) > height(child->right))
{cout<<"calling rl"<<endl;
rlRotation(parent);}
else
{cout<<"calling rr"<<endl;
Node* result = rrRotation(parent);
if(parent == root){
root = result;
}}
}
}
void llRotation(Node* parent) {
Node* tmp = parent->left;
tmp->parent = parent->parent;
parent->parent = tmp;
parent->left = tmp->right;
tmp->right = parent;
if(tmp->parent && tmp->value < tmp->parent->value) {
tmp->parent->left = tmp;
} else if(tmp->parent) {
tmp->parent->right = tmp;
}
parent->height--;
}
void lrRotation(Node* parent) {
rrRotation(parent->left);
llRotation(parent);
}
void rlRotation(Node* parent) {
llRotation(parent->right);
rrRotation(parent);
}
Node* rrRotation(Node* A) {
Node* B = A->right;
B->parent = A->parent;
if(B->parent && B->value < B->parent->value) {
B->parent->left = B;
} else if(B->parent) {
B->parent->right = B;
}
A->right = B->left;
if(A->right)
A->right->parent = A;
B->left = A;
A->parent = B;
A->height--;
return B;
}
/**
* Display tree
*/
void display(Node *ptr, int level) {
int i;
if(ptr!=NULL) {
display(ptr->right, level + 1);
printf("\n");
if (ptr == root)
cout<<"Root -> ";
for (i = 0; i < level && ptr != root; i++)
cout<<" ";
cout<<ptr->value<<"("<<ptr->typeCounter[0]<<","<<ptr->typeCounter[1]<<")-h:"<<ptr->height;
display(ptr->left, level + 1);
}
}
void showANotB(Node* parent) {
if(!parent)
return;
if(parent->left) showANotB(parent->left);
for (int count = parent->typeCounter[0] - parent->typeCounter[1]; count > 0; count--) {
cout<<parent->value<<endl;
}
if(parent->right) showANotB(parent->right);
}
void showBNotA(Node* parent) {
if(!parent)
return;
if(parent->left) showBNotA(parent->left);
for (int count = parent->typeCounter[1] - parent->typeCounter[0]; count > 0; count--) {
cout<<parent->value<<endl;
}
if(parent->right) showBNotA(parent->right);
}
void showAAndB(Node* parent) {
if(!parent)
return;
if(parent->left) showAAndB(parent->left);
for (int count = 0; count < parent->typeCounter[0] && count < parent->typeCounter[1]; count++) {
cout<<parent->value<<endl;
}
if(parent->right) showAAndB(parent->right);
}
};
<commit_msg>Fix rotations<commit_after>// Gavin Kyte
// Thu Nov 2 16:08:49 2017
#include <iostream>
#include <iomanip>
using namespace std;
template <class T> class AVLComparisonTree {
public:
struct Node {
Node* parent;
Node* left;
Node* right;
T value;
int height;
static const int numTypes = 2;
int typeCounter[2];
Node* sibling() {
Node* sib = nullptr;
if(this->parent) {
if(this->parent->value >= this->value) {
sib = this->parent->right;
} else {
sib = this->parent->left;
}
}
return sib;
}
Node(T value, Node* parent) {
this->value = value;
this->parent = parent;
left = nullptr;
right = nullptr;
height = 1;
typeCounter[0] = 0;
typeCounter[1] = 0;
}
};
Node* root;
int size;
AVLComparisonTree() {
root = nullptr;
size = 0;
}
// Takes value and type number for future comparison
void insert(T value, int type) {
if(!root) {
root = new Node(value, nullptr);
}
Node* nomad = root;
while(1) {
if(value < nomad->value && nomad->left){
nomad = nomad->left;
} else if(value < nomad->value && !nomad->left){
nomad->left = new Node(value, nomad);
balance(nomad->left);
} else if(value > nomad->value && nomad->right){
nomad = nomad->right;
} else if(value > nomad->value && !nomad->right){
nomad->right = new Node(value, nomad);
balance(nomad->right);
} else if(value == nomad->value) { // Always last case
nomad->typeCounter[type]++;
break;
}
}
size++;
}
void balance(Node* nomad) {
while(nomad->parent) {
nomad = nomad->parent;
// balance calculated after nomad height is increased,
// and the initial difference can't be more than 1,
// thus the nomad is always +0, +1, or +2 relative to sibling
int balance = diff(nomad->left, nomad->right);
if(balance == 0) { // No change in parent's height factor
break;
} else if(balance == 1) { // Change parent's height
nomad->height++;
continue;
} else { // balance == 2
rotate(nomad);
}
}
}
// Handle nullptr exception for height calc
int height(Node* n) {
int heightValue = 0;
if(n)
heightValue = n->height;
return heightValue;
}
/**
* Helper method to calculate absolute value of height difference
* requires child to be non-null Node ptr, but sibling can be null
* returns +value which is likely 0, 1, or 2 if used correctly.
*/
int diff(Node* child, Node* sibling) {
int cHeight = 0;
if(child)
cHeight = child->height;
int sHeight = 0;
if(sibling)
sHeight = sibling->height;
int difference = cHeight - sHeight;
if(difference < 0) { // Is this ever going to happen?
difference = -1 * difference;
}
return difference;
}
void rotate(Node* parent) {
// Determine rotation type
Node* child;
Node* newParent;
if(!parent) throw(1);
if(height(parent->left) > height(parent->right)) {
child = parent->left;
if(height(child->left) > height(child->right))
newParent = llRotation(parent);
else
newParent = lrRotation(parent);
} else {
child = parent->right;
if(height(child->left) > height(child->right))
newParent = rlRotation(parent);
else
newParent = rrRotation(parent);
}
if(parent == root)
root = newParent;
}
Node* llRotation(Node* A) {
Node* B = A->left;
B->parent = A->parent;
if(B->parent && B->value < B->parent->value) {
B->parent->left = B;
} else if(B->parent) {
B->parent->right = B;
}
A->left = B->right;
if(A->left)
A->left->parent = A;
B->right = A;
A->parent = B;
A->height--;
return B;
}
Node* lrRotation(Node* parent) {
rrRotation(parent->left);
return llRotation(parent);
}
Node* rlRotation(Node* parent) {
llRotation(parent->right);
return rrRotation(parent);
}
Node* rrRotation(Node* A) {
Node* B = A->right;
B->parent = A->parent;
if(B->parent && B->value < B->parent->value) {
B->parent->left = B;
} else if(B->parent) {
B->parent->right = B;
}
A->right = B->left;
if(A->right)
A->right->parent = A;
B->left = A;
A->parent = B;
A->height--;
return B;
}
/**
* Display tree
*/
void display(Node *ptr, int level) {
int i;
if(ptr!=NULL) {
display(ptr->right, level + 1);
printf("\n");
if (ptr == root)
cout<<"Root -> ";
for (i = 0; i < level && ptr != root; i++)
cout<<" ";
cout<<ptr->value<<"("<<ptr->typeCounter[0]<<","<<ptr->typeCounter[1]<<")-h:"<<ptr->height;
display(ptr->left, level + 1);
}
}
void showANotB(Node* parent) {
if(!parent)
return;
if(parent->left) showANotB(parent->left);
for (int count = parent->typeCounter[0] - parent->typeCounter[1]; count > 0; count--) {
cout<<parent->value<<endl;
}
if(parent->right) showANotB(parent->right);
}
void showBNotA(Node* parent) {
if(!parent)
return;
if(parent->left) showBNotA(parent->left);
for (int count = parent->typeCounter[1] - parent->typeCounter[0]; count > 0; count--) {
cout<<parent->value<<endl;
}
if(parent->right) showBNotA(parent->right);
}
void showAAndB(Node* parent) {
if(!parent)
return;
if(parent->left) showAAndB(parent->left);
for (int count = 0; count < parent->typeCounter[0] && count < parent->typeCounter[1]; count++) {
cout<<parent->value<<endl;
}
if(parent->right) showAAndB(parent->right);
}
};
<|endoftext|> |
<commit_before>/****************************************************************
* Copyright (c) 2014, The Pennsylvania State University
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted for
* personal and commercial purposes provided that the
* following conditions are met:
*
* 1. Redistribution of source code must retain the
* above copyright notice, this list of conditions
* and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the
* above copyright notice, this list of conditions
* and the following disclaimer.
*
* 3. Neither the name of The Pennsylvania State University
* nor the names of its contributors may be used to
* endorse or promote products derived from this software
* without the specific prior written permission of The
* Pennsylvania State University.
*
* THIS SOFTWARE IS PROVIDED BY THE PENNSYLVANIA STATE UNIVERSITY
* "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT OF
* INTELLECTUAL PROPERTY ARE EXPRESSLY DISCLAIMED. IN NO EVENT
* SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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 "radfiledata.h"
#include "functions.h"
#include "logging.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <algorithm>
namespace stadic {
RadFileData::RadFileData()
{
}
RadFileData::RadFileData(const shared_vector<RadPrimitive> &primitives) : m_Primitives(primitives)
{
}
//Setters
bool RadFileData::addRad(std::string file)
{
std::ifstream iFile;
iFile.open(file);
if (!iFile.is_open()){
STADIC_ERROR("The opening of the rad file '"+file+"' failed.");
return false;
}
std::stringstream data;
data<<iFile.rdbuf();
shared_vector<RadPrimitive> primitives;
while (!data.eof()) {
try {
RadPrimitive *primitive = RadPrimitive::fromRad(data);
if(primitive == nullptr) {
break;
}
primitives.push_back(std::shared_ptr<RadPrimitive>(primitive));
} catch(const std::runtime_error &) {
return false;
}
}
iFile.close();
if(primitives.size() == 0) {
return false;
}
m_Primitives.insert(m_Primitives.end(),primitives.begin(),primitives.end());
return true;
}
/*
QPair<RadFileData*,RadFileData*> RadFileData::split(bool (*f)(RadPrimitive*))
{
std::vector<RadPrimitive*> in, out;
for(RadPrimitive *primitive : m_Primitives) {
if(f(primitive)) {
in.push_back(primitive);
} else {
out.push_back(primitive);
}
}
// Account for 0 size vectors
RadFileData *first = nullptr;
RadFileData *second = nullptr;
if (in.size() > 0) {
first = new RadFileData(in, this->parent());
}
if (out.size() > 0) {
second = new RadFileData(out, this->parent());
}
return QPair<RadFileData*,RadFileData*>(first,second);
}
*/
std::pair<shared_vector<RadPrimitive>, shared_vector<RadPrimitive> > RadFileData::split(const std::vector<std::string> &vector)
{
shared_vector<RadPrimitive> in, out;
for(std::shared_ptr<RadPrimitive> primitive : m_Primitives) {
if(primitive->isMaterial()) {
if(std::find(vector.begin(),vector.end(),primitive->name()) != vector.end()) {
in.push_back(primitive);
} else {
out.push_back(primitive);
}
} else if(primitive->isGeometry()) {
if(std::find(vector.begin(),vector.end(),primitive->modifier()) != vector.end()) {
in.push_back(primitive);
} else {
out.push_back(primitive);
}
} else {
out.push_back(primitive);
}
}
// In this new version, the caller is responsible for checking that the vectors actually contain something
return std::pair<shared_vector<RadPrimitive>, shared_vector<RadPrimitive>>(in, out);
}
/*
static bool checkLayer(RadPrimitive *primitive, const QString &name)
{
if(primitive->isMaterial() && primitive->name() == name) {
return true;
} else if(primitive->isGeometry() && primitive->modifier() == name) {
return true;
}
return false;
}
static bool checkLayers(RadPrimitive *primitive, const std::vector<QString> &names)
{
for (int i=0;i<names.size();i++){
if(primitive->isMaterial() && primitive->name() == names[i]) {
return true;
} else if(primitive->isGeometry() && primitive->modifier() == names[i]) {
return true;
}
}
return false;
}
*/
/*
bool RadFileData::removeLayer(const QString &layer, const QString &removing, const QString &rest)
{
QFile oFile1;
oFile1.setFileName(removing);
oFile1.open(QIODevice::WriteOnly | QIODevice::Text);
if (!oFile1.exists()){
STADIC_ERROR("The opening of the rad file named " + removing +" has failed.");
return false;
}
QFile oFile2;
oFile2.setFileName(rest);
oFile2.open(QIODevice::WriteOnly | QIODevice::Text);
if (!oFile2.exists()){
STADIC_ERROR("The opening of the rad file named " + rest +" has failed.");
return false;
}
//QPair<RadFileData*,RadFileData*> results = split(checkLayer,layer);
// Write out the two files
oFile1.close();
oFile2.close();
return false;
}
*/
bool RadFileData::blackOutLayer(std::string layer)
{
for(int i=0;i<m_Primitives.size();i++) {
if(m_Primitives[i]->modifier()==layer) {
m_Primitives[i]->setModifier("black");
}
}
return true;
}
bool RadFileData::writeRadFile(std::string file)
{
std::ofstream oFile;
oFile.open(file);
if (!oFile.is_open()){
STADIC_LOG(Severity::Error, "The opening of the rad file named " + file + " has failed.");
}
// Write a header
oFile << "## Radiance geometry file \"" + file + "\"" << std::endl;
// It would be nice to write out more detail about what is going on here. A minimum would be
// to write the date, time and the version of the library. We could also include the
// filenames of any files that were added with addRad (but we'd need to start storing that).
shared_vector<RadPrimitive> primitives=materials();
size_t count = primitives.size();
if(count > 0) {
oFile << "## Materials" << std::endl;
for(auto ptr : primitives) {
oFile << ptr->toRad() << std::endl;
}
}
primitives=geometry();
count += primitives.size();
if(primitives.size() > 0) {
oFile << "## Geometry" << std::endl;
for(auto ptr : primitives) {
oFile << ptr->toRad() << std::endl;
}
}
if(count != m_Primitives.size()) {
STADIC_LOG(Severity::Warning, "Only materials and geometry were written to " + file + ", "
+ toString(m_Primitives.size() - count) + " primitives were not written out");
}
oFile << "## End of Radiance geometry file \"" + file + "\"" << std::endl;
return true;
}
std::vector<double> RadFileData::surfaceNormal(std::string layer){
std::vector<double> normalVector;
for(int i=0;i<m_Primitives.size();i++) {
if(m_Primitives[i]->modifier()==layer && m_Primitives[i]->typeString()=="Polygon") {
std::vector<std::vector<double>> normalPoints;
for (int j=0;j<m_Primitives[i]->arg3().size();j++){
std::vector<double> temp;
for (int p=0;p<3;p++){
temp.push_back(atof(m_Primitives[i]->arg3()[j].c_str()));
j++;
}
normalPoints.push_back(temp);
}
double x=(normalPoints[2][1]-normalPoints[1][1])*(normalPoints[0][2]-normalPoints[1][2])-(normalPoints[2][2]-normalPoints[1][2])*(normalPoints[0][1]-normalPoints[1][2]);
double y=(normalPoints[2][0]-normalPoints[1][0])*(normalPoints[0][2]-normalPoints[1][2])-(normalPoints[2][2]-normalPoints[1][2])*(normalPoints[0][0]-normalPoints[1][0]);
double z=(normalPoints[2][0]-normalPoints[1][0])*(normalPoints[0][1]-normalPoints[1][1])-(normalPoints[2][1]-normalPoints[1][1])*(normalPoints[0][0]-normalPoints[1][0]);
double length=sqrt(x*x+y*y+z*z);
x=x/length;
y=y/length;
z=z/length;
normalVector.push_back(x);
normalVector.push_back(y);
normalVector.push_back(z);
return normalVector;
}
}
return normalVector;
}
bool RadFileData::addPrimitive(RadPrimitive *primitive)
{
m_Primitives.push_back(std::shared_ptr<RadPrimitive>(primitive));
return true;
}
//Getters
shared_vector<RadPrimitive> RadFileData::geometry() const
{
shared_vector<RadPrimitive> primitives;
for(auto primitive : m_Primitives) {
if(primitive->isGeometry()) {
primitives.push_back(primitive);
}
}
return primitives;
}
shared_vector<RadPrimitive> RadFileData::materials() const
{
shared_vector<RadPrimitive> primitives;
for(auto primitive : m_Primitives) {
if(primitive->isMaterial()) {
primitives.push_back(primitive);
}
}
return primitives;
}
shared_vector<RadPrimitive> RadFileData::primitives() const
{
return m_Primitives;
}
}
<commit_msg>Add math.h include in radfiledata.cpp<commit_after>/****************************************************************
* Copyright (c) 2014, The Pennsylvania State University
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted for
* personal and commercial purposes provided that the
* following conditions are met:
*
* 1. Redistribution of source code must retain the
* above copyright notice, this list of conditions
* and the following disclaimer.
*
* 2. Redistribution in binary form must reproduce the
* above copyright notice, this list of conditions
* and the following disclaimer.
*
* 3. Neither the name of The Pennsylvania State University
* nor the names of its contributors may be used to
* endorse or promote products derived from this software
* without the specific prior written permission of The
* Pennsylvania State University.
*
* THIS SOFTWARE IS PROVIDED BY THE PENNSYLVANIA STATE UNIVERSITY
* "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT OF
* INTELLECTUAL PROPERTY ARE EXPRESSLY DISCLAIMED. IN NO EVENT
* SHALL THE AUTHORS OR COPYRIGHT HOLDERS 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 "radfiledata.h"
#include "functions.h"
#include "logging.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <math.h>
namespace stadic {
RadFileData::RadFileData()
{
}
RadFileData::RadFileData(const shared_vector<RadPrimitive> &primitives) : m_Primitives(primitives)
{
}
//Setters
bool RadFileData::addRad(std::string file)
{
std::ifstream iFile;
iFile.open(file);
if (!iFile.is_open()){
STADIC_ERROR("The opening of the rad file '"+file+"' failed.");
return false;
}
std::stringstream data;
data<<iFile.rdbuf();
shared_vector<RadPrimitive> primitives;
while (!data.eof()) {
try {
RadPrimitive *primitive = RadPrimitive::fromRad(data);
if(primitive == nullptr) {
break;
}
primitives.push_back(std::shared_ptr<RadPrimitive>(primitive));
} catch(const std::runtime_error &) {
return false;
}
}
iFile.close();
if(primitives.size() == 0) {
return false;
}
m_Primitives.insert(m_Primitives.end(),primitives.begin(),primitives.end());
return true;
}
/*
QPair<RadFileData*,RadFileData*> RadFileData::split(bool (*f)(RadPrimitive*))
{
std::vector<RadPrimitive*> in, out;
for(RadPrimitive *primitive : m_Primitives) {
if(f(primitive)) {
in.push_back(primitive);
} else {
out.push_back(primitive);
}
}
// Account for 0 size vectors
RadFileData *first = nullptr;
RadFileData *second = nullptr;
if (in.size() > 0) {
first = new RadFileData(in, this->parent());
}
if (out.size() > 0) {
second = new RadFileData(out, this->parent());
}
return QPair<RadFileData*,RadFileData*>(first,second);
}
*/
std::pair<shared_vector<RadPrimitive>, shared_vector<RadPrimitive> > RadFileData::split(const std::vector<std::string> &vector)
{
shared_vector<RadPrimitive> in, out;
for(std::shared_ptr<RadPrimitive> primitive : m_Primitives) {
if(primitive->isMaterial()) {
if(std::find(vector.begin(),vector.end(),primitive->name()) != vector.end()) {
in.push_back(primitive);
} else {
out.push_back(primitive);
}
} else if(primitive->isGeometry()) {
if(std::find(vector.begin(),vector.end(),primitive->modifier()) != vector.end()) {
in.push_back(primitive);
} else {
out.push_back(primitive);
}
} else {
out.push_back(primitive);
}
}
// In this new version, the caller is responsible for checking that the vectors actually contain something
return std::pair<shared_vector<RadPrimitive>, shared_vector<RadPrimitive>>(in, out);
}
/*
static bool checkLayer(RadPrimitive *primitive, const QString &name)
{
if(primitive->isMaterial() && primitive->name() == name) {
return true;
} else if(primitive->isGeometry() && primitive->modifier() == name) {
return true;
}
return false;
}
static bool checkLayers(RadPrimitive *primitive, const std::vector<QString> &names)
{
for (int i=0;i<names.size();i++){
if(primitive->isMaterial() && primitive->name() == names[i]) {
return true;
} else if(primitive->isGeometry() && primitive->modifier() == names[i]) {
return true;
}
}
return false;
}
*/
/*
bool RadFileData::removeLayer(const QString &layer, const QString &removing, const QString &rest)
{
QFile oFile1;
oFile1.setFileName(removing);
oFile1.open(QIODevice::WriteOnly | QIODevice::Text);
if (!oFile1.exists()){
STADIC_ERROR("The opening of the rad file named " + removing +" has failed.");
return false;
}
QFile oFile2;
oFile2.setFileName(rest);
oFile2.open(QIODevice::WriteOnly | QIODevice::Text);
if (!oFile2.exists()){
STADIC_ERROR("The opening of the rad file named " + rest +" has failed.");
return false;
}
//QPair<RadFileData*,RadFileData*> results = split(checkLayer,layer);
// Write out the two files
oFile1.close();
oFile2.close();
return false;
}
*/
bool RadFileData::blackOutLayer(std::string layer)
{
for(int i=0;i<m_Primitives.size();i++) {
if(m_Primitives[i]->modifier()==layer) {
m_Primitives[i]->setModifier("black");
}
}
return true;
}
bool RadFileData::writeRadFile(std::string file)
{
std::ofstream oFile;
oFile.open(file);
if (!oFile.is_open()){
STADIC_LOG(Severity::Error, "The opening of the rad file named " + file + " has failed.");
}
// Write a header
oFile << "## Radiance geometry file \"" + file + "\"" << std::endl;
// It would be nice to write out more detail about what is going on here. A minimum would be
// to write the date, time and the version of the library. We could also include the
// filenames of any files that were added with addRad (but we'd need to start storing that).
shared_vector<RadPrimitive> primitives=materials();
size_t count = primitives.size();
if(count > 0) {
oFile << "## Materials" << std::endl;
for(auto ptr : primitives) {
oFile << ptr->toRad() << std::endl;
}
}
primitives=geometry();
count += primitives.size();
if(primitives.size() > 0) {
oFile << "## Geometry" << std::endl;
for(auto ptr : primitives) {
oFile << ptr->toRad() << std::endl;
}
}
if(count != m_Primitives.size()) {
STADIC_LOG(Severity::Warning, "Only materials and geometry were written to " + file + ", "
+ toString(m_Primitives.size() - count) + " primitives were not written out");
}
oFile << "## End of Radiance geometry file \"" + file + "\"" << std::endl;
return true;
}
std::vector<double> RadFileData::surfaceNormal(std::string layer){
std::vector<double> normalVector;
for(int i=0;i<m_Primitives.size();i++) {
if(m_Primitives[i]->modifier()==layer && m_Primitives[i]->typeString()=="Polygon") {
std::vector<std::vector<double>> normalPoints;
for (int j=0;j<m_Primitives[i]->arg3().size();j++){
std::vector<double> temp;
for (int p=0;p<3;p++){
temp.push_back(atof(m_Primitives[i]->arg3()[j].c_str()));
j++;
}
normalPoints.push_back(temp);
}
double x=(normalPoints[2][1]-normalPoints[1][1])*(normalPoints[0][2]-normalPoints[1][2])-(normalPoints[2][2]-normalPoints[1][2])*(normalPoints[0][1]-normalPoints[1][2]);
double y=(normalPoints[2][0]-normalPoints[1][0])*(normalPoints[0][2]-normalPoints[1][2])-(normalPoints[2][2]-normalPoints[1][2])*(normalPoints[0][0]-normalPoints[1][0]);
double z=(normalPoints[2][0]-normalPoints[1][0])*(normalPoints[0][1]-normalPoints[1][1])-(normalPoints[2][1]-normalPoints[1][1])*(normalPoints[0][0]-normalPoints[1][0]);
double length=sqrt(x*x+y*y+z*z);
x=x/length;
y=y/length;
z=z/length;
normalVector.push_back(x);
normalVector.push_back(y);
normalVector.push_back(z);
return normalVector;
}
}
return normalVector;
}
bool RadFileData::addPrimitive(RadPrimitive *primitive)
{
m_Primitives.push_back(std::shared_ptr<RadPrimitive>(primitive));
return true;
}
//Getters
shared_vector<RadPrimitive> RadFileData::geometry() const
{
shared_vector<RadPrimitive> primitives;
for(auto primitive : m_Primitives) {
if(primitive->isGeometry()) {
primitives.push_back(primitive);
}
}
return primitives;
}
shared_vector<RadPrimitive> RadFileData::materials() const
{
shared_vector<RadPrimitive> primitives;
for(auto primitive : m_Primitives) {
if(primitive->isMaterial()) {
primitives.push_back(primitive);
}
}
return primitives;
}
shared_vector<RadPrimitive> RadFileData::primitives() const
{
return m_Primitives;
}
}
<|endoftext|> |
<commit_before>#include "SharedMemory.h"
#include <iostream>
#include <sstream>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/stat.h> /* For mode constants */
#include <fcntl.h> /* For O_* constants */
#include <semaphore.h>
using namespace std;
SharedMemory::SharedMemory(key_t key, bool unloadLast): _key(key), _unloadLast(unloadLast)
{
_shmID = -1;
_mapped=NULL;
_length = NULL;
_sem=NULL;
_isAllocator = false;
_needsAllocation = true;
_unloadLast = true;
OpenIfExists();
}
SharedMemory::~SharedMemory()
{
try
{
int inUse = SharedObjectsUseCount() - 1;
Close();
if (inUse > 0 && _unloadLast)
{
cerr << inUse << " other job(s) are attached to the shared memory segment, will not remove it." <<endl;
}
else if (_unloadLast)
{
cerr << "No other jobs are attached to the shared memory segment, removing it."<<endl;
Clean();
};
}
catch (const SharedMemoryException & exc)
{
//cerr << exc.GetErrorCode() << " " << exc.GetErrorDetail() << endl;
Clean();
}
}
void SharedMemory::Allocate(size_t shmSize)
{
_exception.ClearError();
if (!_needsAllocation)
ThrowError(ErrorState::EALREADYALLOCATED);
CreateAndInitSharedObject(shmSize);
if (_exception.HasError() && _exception.GetErrorCode() != ErrorState::EEXISTS)
throw _exception;
_exception.ClearError(); // someone else came in first so retry open
OpenIfExists();
_isAllocator = true;
}
const char * SharedMemory::GetPosixObjectKey()
{
ostringstream key;
key << "/" << _key;
return key.str().c_str();
}
string SharedMemory::CounterName()
{
ostringstream counterName;
counterName << "/shared_use_counter" << _key;
return counterName.str();
}
void SharedMemory::CreateAndInitSharedObject(size_t shmSize)
{
unsigned long long toReserve = (unsigned long long) shmSize + sizeof(unsigned long long);
#ifdef POSIX_SHARED_MEM
_shmID=shm_open(GetPosixObjectKey(), O_CREAT | O_RDWR | O_EXCL , 0666);
#else
_shmID=shmget(_key, toReserve, IPC_CREAT | IPC_EXCL | SHM_NORESERVE | 0666); // _shmID = shmget(shmKey, shmSize, IPC_CREAT | SHM_NORESERVE | SHM_HUGETLB | 0666);
#endif
if (_shmID == -1)
{
switch (errno)
{
case EEXIST:
_exception.SetError(ErrorState::EEXISTS, 0);
break;
default:
ThrowError(ErrorState::EOPENFAILED, errno);
}
return;
}
#ifdef POSIX_SHARED_MEM
int err = ftruncate(_shmID, toReserve);
if (err == -1)
{
ThrowError(ErrorState::EFTRUNCATE);
}
#endif
}
void SharedMemory::OpenIfExists()
{
errno=0;
if (_shmID < 0){
#ifdef POSIX_SHARED_MEM
_shmID=shm_open(SharedMemory::GetPosixObjectKey(), O_RDWR, 0);
#else
_shmID=shmget(_key,0,0);
#endif
}
bool exists=_shmID>=0;
if (! (exists || errno == ENOENT))
ThrowError(EOPENFAILED, errno); // it's there but we couldn't get a handle
if (exists)
{
MapSharedObjectToMemory();
_needsAllocation = false;
}
}
#ifdef POSIX_SHARED_MEM
struct stat SharedMemory::GetSharedObjectInfo()
{
struct stat buf;
int err = fstat(_shmID, &buf);
if (err == -1)
ThrowError(EOPENFAILED, errno);
return buf;
}
#endif
void SharedMemory::MapSharedObjectToMemory()
{
#ifdef POSIX_SHARED_MEM
size_t size=0;
struct stat buf = SharedMemory::GetSharedObjectInfo();
size = (size_t) buf.st_size;
_mapped = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NORESERVE, _shmID, (off_t) 0);
#else
// size is not needed
_mapped= shmat(_shmID, NULL, 0);
#endif
if (_mapped==((void *) -1))
ThrowError(EMAPFAILED, errno);
SharedUseIncrement();
// set the length field
_length = (size_t *) _mapped;
#ifdef POSIX_SHARED_MEM
*_length = size;
#endif
}
void SharedMemory::Close()
{
if (_mapped != NULL)
{
#ifdef POSIX_SHARED_MEM
int ret = munmap(_mapped, (size_t) *_length);
if (ret == -1)
ThrowError(EMAPFAILED, errno);
#endif
_mapped = NULL;
SharedUseDecrement();
}
#ifdef POSIX_SHARED_MEM
if (_shmID != -1)
{
int err = close(_shmID);
_shmID=-1;
if (err == -1)
ThrowError(ECLOSE, errno);
}
#endif
}
void SharedMemory::Unlink()
{
if (!_needsAllocation)
{
int shmStatus=-1;
#ifdef POSIX_SHARED_MEM
shmStatus = shm_unlink(SharedMemory::GetPosixObjectKey());
#else
struct shmid_ds buf;
shmStatus=shmctl(_shmID,IPC_RMID,&buf);
#endif
if (shmStatus == -1)
ThrowError(EUNLINK, errno);
_needsAllocation = true;
}
}
void SharedMemory::Clean()
{
Close();
Unlink();
RemoveSharedCounter();
}
void SharedMemory::EnsureCounter()
{
if (_sem!= NULL)
return;
const char * counterName = SharedMemory::CounterName().c_str();
_sem = sem_open(counterName, O_CREAT, 0666, 0);
if (_sem == SEM_FAILED)
ThrowError(ECOUNTERCREATE, errno);
}
void SharedMemory::RemoveSharedCounter()
{
const char * counterName = SharedMemory::CounterName().c_str();
if (_sem != NULL)
{
int ret = sem_close(_sem);
if (ret == -1)
ThrowError(ECLOSE, errno);
ret = sem_unlink(counterName);
if (ret == -1)
ThrowError(ECOUNTERREMOVE, errno);
_sem = NULL;
}
}
void SharedMemory::SharedUseIncrement()
{
SharedMemory::EnsureCounter();
int ret = sem_post(_sem);
if (ret == -1)
ThrowError(ECOUNTERINC, errno);
cerr << "incremented shared memory fragment usage to " << SharedObjectsUseCount() << endl;
}
void SharedMemory::SharedUseDecrement()
{
SharedMemory::EnsureCounter();
int ret = sem_trywait(_sem);
if (ret == -1 && errno != EAGAIN)
ThrowError(ECOUNTERDEC, errno);
cerr << "decremented shared memory fragment usage to " << SharedObjectsUseCount() << endl;
}
int SharedMemory::SharedObjectsUseCount()
{
SharedMemory::EnsureCounter();
int sval=-1;
int ret = sem_getvalue(_sem, &sval);
if (ret == -1 || sval == -1)
ThrowError(ECOUNTERUSE, errno);
return sval;
}
<commit_msg>fix loadandkeep bug that removes the genome nevertheless<commit_after>#include "SharedMemory.h"
#include <iostream>
#include <sstream>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/stat.h> /* For mode constants */
#include <fcntl.h> /* For O_* constants */
#include <semaphore.h>
using namespace std;
SharedMemory::SharedMemory(key_t key, bool unloadLast): _key(key), _unloadLast(unloadLast)
{
_shmID = -1;
_mapped=NULL;
_length = NULL;
_sem=NULL;
_isAllocator = false;
_needsAllocation = true;
OpenIfExists();
}
SharedMemory::~SharedMemory()
{
try
{
int inUse = SharedObjectsUseCount() - 1;
Close();
if (inUse > 0 && _unloadLast)
{
cerr << inUse << " other job(s) are attached to the shared memory segment, will not remove it." <<endl;
}
else if (_unloadLast)
{
cerr << "No other jobs are attached to the shared memory segment, removing it."<<endl;
Clean();
};
}
catch (const SharedMemoryException & exc)
{
//cerr << exc.GetErrorCode() << " " << exc.GetErrorDetail() << endl;
Clean();
}
}
void SharedMemory::Allocate(size_t shmSize)
{
_exception.ClearError();
if (!_needsAllocation)
ThrowError(ErrorState::EALREADYALLOCATED);
CreateAndInitSharedObject(shmSize);
if (_exception.HasError() && _exception.GetErrorCode() != ErrorState::EEXISTS)
throw _exception;
_exception.ClearError(); // someone else came in first so retry open
OpenIfExists();
_isAllocator = true;
}
const char * SharedMemory::GetPosixObjectKey()
{
ostringstream key;
key << "/" << _key;
return key.str().c_str();
}
string SharedMemory::CounterName()
{
ostringstream counterName;
counterName << "/shared_use_counter" << _key;
return counterName.str();
}
void SharedMemory::CreateAndInitSharedObject(size_t shmSize)
{
unsigned long long toReserve = (unsigned long long) shmSize + sizeof(unsigned long long);
#ifdef POSIX_SHARED_MEM
_shmID=shm_open(GetPosixObjectKey(), O_CREAT | O_RDWR | O_EXCL , 0666);
#else
_shmID=shmget(_key, toReserve, IPC_CREAT | IPC_EXCL | SHM_NORESERVE | 0666); // _shmID = shmget(shmKey, shmSize, IPC_CREAT | SHM_NORESERVE | SHM_HUGETLB | 0666);
#endif
if (_shmID == -1)
{
switch (errno)
{
case EEXIST:
_exception.SetError(ErrorState::EEXISTS, 0);
break;
default:
ThrowError(ErrorState::EOPENFAILED, errno);
}
return;
}
#ifdef POSIX_SHARED_MEM
int err = ftruncate(_shmID, toReserve);
if (err == -1)
{
ThrowError(ErrorState::EFTRUNCATE);
}
#endif
}
void SharedMemory::OpenIfExists()
{
errno=0;
if (_shmID < 0){
#ifdef POSIX_SHARED_MEM
_shmID=shm_open(SharedMemory::GetPosixObjectKey(), O_RDWR, 0);
#else
_shmID=shmget(_key,0,0);
#endif
}
bool exists=_shmID>=0;
if (! (exists || errno == ENOENT))
ThrowError(EOPENFAILED, errno); // it's there but we couldn't get a handle
if (exists)
{
MapSharedObjectToMemory();
_needsAllocation = false;
}
}
#ifdef POSIX_SHARED_MEM
struct stat SharedMemory::GetSharedObjectInfo()
{
struct stat buf;
int err = fstat(_shmID, &buf);
if (err == -1)
ThrowError(EOPENFAILED, errno);
return buf;
}
#endif
void SharedMemory::MapSharedObjectToMemory()
{
#ifdef POSIX_SHARED_MEM
size_t size=0;
struct stat buf = SharedMemory::GetSharedObjectInfo();
size = (size_t) buf.st_size;
_mapped = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NORESERVE, _shmID, (off_t) 0);
#else
// size is not needed
_mapped= shmat(_shmID, NULL, 0);
#endif
if (_mapped==((void *) -1))
ThrowError(EMAPFAILED, errno);
SharedUseIncrement();
// set the length field
_length = (size_t *) _mapped;
#ifdef POSIX_SHARED_MEM
*_length = size;
#endif
}
void SharedMemory::Close()
{
if (_mapped != NULL)
{
#ifdef POSIX_SHARED_MEM
int ret = munmap(_mapped, (size_t) *_length);
if (ret == -1)
ThrowError(EMAPFAILED, errno);
#endif
_mapped = NULL;
SharedUseDecrement();
}
#ifdef POSIX_SHARED_MEM
if (_shmID != -1)
{
int err = close(_shmID);
_shmID=-1;
if (err == -1)
ThrowError(ECLOSE, errno);
}
#endif
}
void SharedMemory::Unlink()
{
if (!_needsAllocation)
{
int shmStatus=-1;
#ifdef POSIX_SHARED_MEM
shmStatus = shm_unlink(SharedMemory::GetPosixObjectKey());
#else
struct shmid_ds buf;
shmStatus=shmctl(_shmID,IPC_RMID,&buf);
#endif
if (shmStatus == -1)
ThrowError(EUNLINK, errno);
_needsAllocation = true;
}
}
void SharedMemory::Clean()
{
Close();
Unlink();
RemoveSharedCounter();
}
void SharedMemory::EnsureCounter()
{
if (_sem!= NULL)
return;
const char * counterName = SharedMemory::CounterName().c_str();
_sem = sem_open(counterName, O_CREAT, 0666, 0);
if (_sem == SEM_FAILED)
ThrowError(ECOUNTERCREATE, errno);
}
void SharedMemory::RemoveSharedCounter()
{
const char * counterName = SharedMemory::CounterName().c_str();
if (_sem != NULL)
{
int ret = sem_close(_sem);
if (ret == -1)
ThrowError(ECLOSE, errno);
ret = sem_unlink(counterName);
if (ret == -1)
ThrowError(ECOUNTERREMOVE, errno);
_sem = NULL;
}
}
void SharedMemory::SharedUseIncrement()
{
SharedMemory::EnsureCounter();
int ret = sem_post(_sem);
if (ret == -1)
ThrowError(ECOUNTERINC, errno);
cerr << "incremented shared memory fragment usage to " << SharedObjectsUseCount() << endl;
}
void SharedMemory::SharedUseDecrement()
{
SharedMemory::EnsureCounter();
int ret = sem_trywait(_sem);
if (ret == -1 && errno != EAGAIN)
ThrowError(ECOUNTERDEC, errno);
cerr << "decremented shared memory fragment usage to " << SharedObjectsUseCount() << endl;
}
int SharedMemory::SharedObjectsUseCount()
{
SharedMemory::EnsureCounter();
int sval=-1;
int ret = sem_getvalue(_sem, &sval);
if (ret == -1 || sval == -1)
ThrowError(ECOUNTERUSE, errno);
return sval;
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2013-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/datastructures/transferfunction.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/ports/imageport.h>
#include <inviwo/core/util/vectoroperations.h>
#include <math.h>
namespace inviwo {
TransferFunction::TransferFunction(int textureSize)
: TransferFunctionObservable()
, maskMin_(0.0f)
, maskMax_(1.0f)
, interpolationType_(InterpolationLinear)
, textureSize_(textureSize)
, invalidData_(true)
, data_(new Layer(uvec2(textureSize, 1), DataVec4FLOAT32::get())) {
// initialize with standard ramp
addPoint(vec2(0.0f,0.0f), vec4(0.0f,0.0f,0.0f,0.0f));
addPoint(vec2(1.0f,1.0f), vec4(1.0f,1.0f,1.0f,1.0f));
}
TransferFunction::TransferFunction(const TransferFunction& rhs)
: maskMin_(rhs.maskMin_)
, maskMax_(rhs.maskMax_)
, interpolationType_(rhs.interpolationType_)
, textureSize_(rhs.textureSize_)
, invalidData_(rhs.invalidData_)
, data_(new Layer(*rhs.data_)) {
for (int i = 0; i < rhs.getNumPoints(); i++) {
addPoint(rhs.getPoint(i)->getPos(), rhs.getPoint(i)->getRGBA());
}
}
TransferFunction& TransferFunction::operator=(const TransferFunction& rhs) {
if (this != &rhs) {
delete data_;
data_ = new Layer(*rhs.data_);
clearPoints();
textureSize_ = rhs.textureSize_;
maskMin_ = rhs.maskMin_;
maskMax_ = rhs.maskMax_;
interpolationType_ = rhs.interpolationType_;
for (int i = 0; i < rhs.getNumPoints(); i++) {
addPoint(rhs.getPoint(i)->getPos(), rhs.getPoint(i)->getRGBA());
}
}
invalidate();
return *this;
}
TransferFunction::~TransferFunction() {
clearPoints();
delete data_;
}
TransferFunctionDataPoint* TransferFunction::getPoint(int i) const {
return points_[i];
}
void TransferFunction::addPoint(const vec2& pos) {
// determine color
vec4 color = vec4(0.5f, 0.5f, 0.5f, pos.y);
if (points_.size() > 0) {
int leftNeighborID = 0;
int rightNeighborID = 0;
for (int i = 0; i < static_cast<int>(points_.size()); i++)
if (points_[i]->getPos().x <= pos.x)
leftNeighborID = i;
else if (rightNeighborID == 0 && points_[i]->getPos().x > pos.x)
rightNeighborID = i;
vec4 colorL = points_[leftNeighborID]->getRGBA();
vec4 colorR = points_[rightNeighborID]->getRGBA();
float a = 0.5f;
float denom = points_[rightNeighborID]->getPos().x - points_[leftNeighborID]->getPos().x;
if (denom > 0.0) a = (points_[rightNeighborID]->getPos().x - pos.x) / denom;
color = vec4(a * colorL.r + (1.0 - a) * colorR.r, a * colorL.g + (1.0 - a) * colorR.g,
a * colorL.b + (1.0 - a) * colorR.b, pos.y);
}
addPoint(pos, color);
}
void TransferFunction::addPoint(const vec2& pos, const vec4& color) {
addPoint(new TransferFunctionDataPoint(pos, color));
}
void TransferFunction::addPoint(TransferFunctionDataPoint* dataPoint) {
dataPoint->addObserver(this);
TFPoints::iterator pos = std::lower_bound(points_.begin(), points_.end(), dataPoint,
comparePtr<TransferFunctionDataPoint>);
points_.insert(pos, dataPoint);
invalidate();
notifyControlPointAdded(dataPoint);
}
void TransferFunction::removePoint(TransferFunctionDataPoint* dataPoint) {
TFPoints::iterator it = std::find(points_.begin(), points_.end(), dataPoint);
if (it != points_.end()) {
points_.erase(it);
invalidate();
notifyControlPointRemoved(dataPoint);
delete dataPoint;
}
}
void TransferFunction::clearPoints() {
invalidate();
while(points_.size() > 0) {
TransferFunctionDataPoint* dataPoint = points_.back();
points_.pop_back();
notifyControlPointRemoved(dataPoint);
delete dataPoint;
}
}
void TransferFunction::onTransferFunctionPointChange(const TransferFunctionDataPoint* p){
std::stable_sort(points_.begin(), points_.end(), comparePtr<TransferFunctionDataPoint>);
invalidate();
notifyControlPointChanged(p);
}
void TransferFunction::calcTransferValues() {
vec4* dataArray = static_cast<vec4*>(data_->getEditableRepresentation<LayerRAM>()->getData());
std::stable_sort(points_.begin(), points_.end(), comparePtr<TransferFunctionDataPoint>);
if (points_.size() == 0) { // in case of 0 points
for (int i = 0; i < textureSize_; i++) {
dataArray[i] = vec4((float)i / (textureSize_ - 1.0), (float)i / (textureSize_ - 1.0),
(float)i / (textureSize_ - 1.0), 1.0);
}
} else if (points_.size() == 1) { // in case of 1 point
for (int i = 0; i < textureSize_; ++i) {
dataArray[i] = points_[0]->getRGBA();
}
} else { // in case of more than 1 points
int leftX = static_cast<int>(ceil(points_.front()->getPos().x * (textureSize_ - 1)));
int rightX = static_cast<int>(ceil(points_.back()->getPos().x * (textureSize_ - 1)));
for (int i = 0; i <= leftX; i++) dataArray[i] = points_.front()->getRGBA();
for (int i = rightX; i < textureSize_; i++) dataArray[i] = points_.back()->getRGBA();
// if (interpolationType_==TransferFunction::InterpolationLinear) {
// linear interpolation
std::vector<TransferFunctionDataPoint*>::iterator pLeft = points_.begin();
std::vector<TransferFunctionDataPoint*>::iterator pRight = points_.begin() + 1;
while (pRight != points_.end()) {
int n = static_cast<int>(ceil((*pLeft)->getPos().x * (textureSize_ - 1)));
while (n < ceil((*pRight)->getPos().x * (textureSize_ - 1))) {
vec4 lrgba = (*pLeft)->getRGBA();
vec4 rrgba = (*pRight)->getRGBA();
float lx = (*pLeft)->getPos().x * (textureSize_ - 1);
float rx = (*pRight)->getPos().x * (textureSize_ - 1);
float alpha = (n - lx) / (rx - lx);
dataArray[n] = alpha * rrgba + (1.0f - alpha) * lrgba;
n++;
}
pLeft++;
pRight++;
}
//} else {
// cubic interpolation
// TODO: implement cubic interpolation
//}
}
for (int i = 0; i < int(maskMin_ * textureSize_); i++) dataArray[i].a = 0.0;
for (int i = int(maskMax_ * textureSize_); i < textureSize_; i++) dataArray[i].a = 0.0;
invalidData_ = false;
}
void TransferFunction::serialize(IvwSerializer& s) const {
s.serialize("maskMin", maskMin_);
s.serialize("maskMax", maskMax_);
s.serialize("dataPoints", points_, "point");
s.serialize("interpolationType_", static_cast<int>(interpolationType_));
}
void TransferFunction::deserialize(IvwDeserializer& d) {
d.deserialize("maskMin", maskMin_);
d.deserialize("maskMax", maskMax_);
d.deserialize("dataPoints", points_, "point");
for (auto& elem : points_) {
(elem)->addObserver(this);
}
int type = static_cast<int>(interpolationType_);
d.deserialize("interpolationType_", type);
interpolationType_ = static_cast<TransferFunction::InterpolationType>(type);
invalidate();
}
const Layer* TransferFunction::getData() const {
if (invalidData_) {
const_cast<TransferFunction*>(this)->calcTransferValues();
}
return data_;
}
void TransferFunction::invalidate() {
invalidData_ = true;
}
float TransferFunction::getMaskMin() const {
return maskMin_;
}
void TransferFunction::setMaskMin(float maskMin) {
maskMin_ = maskMin;
invalidate();
}
float TransferFunction::getMaskMax() const {
return maskMax_;
}
void TransferFunction::setMaskMax(float maskMax) {
maskMax_ = maskMax;
invalidate();
}
void TransferFunction::setInterpolationType(InterpolationType interpolationType) {
interpolationType_ = interpolationType;
invalidate();
}
inviwo::TransferFunction::InterpolationType TransferFunction::getInterpolationType() const {
return interpolationType_;
}
int TransferFunction::getTextureSize() {
return textureSize_;
}
int TransferFunction::getNumPoints() const {
return static_cast<int>(points_.size());
}
void TransferFunctionObservable::notifyControlPointAdded(TransferFunctionDataPoint* p) const {
for (ObserverSet::reverse_iterator it = observers_->rbegin(); it != observers_->rend(); ++it)
static_cast<TransferFunctionObserver*>(*it)->onControlPointAdded(p);
}
void TransferFunctionObservable::notifyControlPointRemoved(TransferFunctionDataPoint* p) const {
for (ObserverSet::reverse_iterator it = observers_->rbegin(); it != observers_->rend(); ++it)
static_cast<TransferFunctionObserver*>(*it)->onControlPointRemoved(p);
}
void TransferFunctionObservable::notifyControlPointChanged(const TransferFunctionDataPoint* p) const {
for (ObserverSet::reverse_iterator it = observers_->rbegin(); it != observers_->rend(); ++it)
static_cast<TransferFunctionObserver*>(*it)->onControlPointChanged(p);
}
bool operator==(const TransferFunction& lhs, const TransferFunction& rhs) {
return lhs.maskMin_ == rhs.maskMin_
&& lhs.maskMax_ == rhs.maskMax_
&& lhs.interpolationType_ == rhs.interpolationType_
&& lhs.points_ == rhs.points_;
}
bool operator!=(const TransferFunction& lhs, const TransferFunction& rhs) {
return !operator==(lhs, rhs);
}
}<commit_msg>Core: Prevent TF from unnecessarily reallocating Layer when assigned<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2013-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/datastructures/transferfunction.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <inviwo/core/datastructures/image/layer.h>
#include <inviwo/core/ports/imageport.h>
#include <inviwo/core/util/vectoroperations.h>
#include <math.h>
namespace inviwo {
TransferFunction::TransferFunction(int textureSize)
: TransferFunctionObservable()
, maskMin_(0.0f)
, maskMax_(1.0f)
, interpolationType_(InterpolationLinear)
, textureSize_(textureSize)
, invalidData_(true)
, data_(new Layer(uvec2(textureSize, 1), DataVec4FLOAT32::get())) {
// initialize with standard ramp
addPoint(vec2(0.0f,0.0f), vec4(0.0f,0.0f,0.0f,0.0f));
addPoint(vec2(1.0f,1.0f), vec4(1.0f,1.0f,1.0f,1.0f));
}
TransferFunction::TransferFunction(const TransferFunction& rhs)
: maskMin_(rhs.maskMin_)
, maskMax_(rhs.maskMax_)
, interpolationType_(rhs.interpolationType_)
, textureSize_(rhs.textureSize_)
, invalidData_(rhs.invalidData_)
, data_(new Layer(*rhs.data_)) {
for (int i = 0; i < rhs.getNumPoints(); i++) {
addPoint(rhs.getPoint(i)->getPos(), rhs.getPoint(i)->getRGBA());
}
}
TransferFunction& TransferFunction::operator=(const TransferFunction& rhs) {
if (this != &rhs) {
if (rhs.getData()->getDimensions() != data_->getDimensions()) {
delete data_;
data_ = new Layer(*rhs.data_);
}
clearPoints();
textureSize_ = rhs.textureSize_;
maskMin_ = rhs.maskMin_;
maskMax_ = rhs.maskMax_;
interpolationType_ = rhs.interpolationType_;
for (int i = 0; i < rhs.getNumPoints(); i++) {
addPoint(rhs.getPoint(i)->getPos(), rhs.getPoint(i)->getRGBA());
}
}
invalidate();
return *this;
}
TransferFunction::~TransferFunction() {
clearPoints();
delete data_;
}
TransferFunctionDataPoint* TransferFunction::getPoint(int i) const {
return points_[i];
}
void TransferFunction::addPoint(const vec2& pos) {
// determine color
vec4 color = vec4(0.5f, 0.5f, 0.5f, pos.y);
if (points_.size() > 0) {
int leftNeighborID = 0;
int rightNeighborID = 0;
for (int i = 0; i < static_cast<int>(points_.size()); i++)
if (points_[i]->getPos().x <= pos.x)
leftNeighborID = i;
else if (rightNeighborID == 0 && points_[i]->getPos().x > pos.x)
rightNeighborID = i;
vec4 colorL = points_[leftNeighborID]->getRGBA();
vec4 colorR = points_[rightNeighborID]->getRGBA();
float a = 0.5f;
float denom = points_[rightNeighborID]->getPos().x - points_[leftNeighborID]->getPos().x;
if (denom > 0.0) a = (points_[rightNeighborID]->getPos().x - pos.x) / denom;
color = vec4(a * colorL.r + (1.0 - a) * colorR.r, a * colorL.g + (1.0 - a) * colorR.g,
a * colorL.b + (1.0 - a) * colorR.b, pos.y);
}
addPoint(pos, color);
}
void TransferFunction::addPoint(const vec2& pos, const vec4& color) {
addPoint(new TransferFunctionDataPoint(pos, color));
}
void TransferFunction::addPoint(TransferFunctionDataPoint* dataPoint) {
dataPoint->addObserver(this);
TFPoints::iterator pos = std::lower_bound(points_.begin(), points_.end(), dataPoint,
comparePtr<TransferFunctionDataPoint>);
points_.insert(pos, dataPoint);
invalidate();
notifyControlPointAdded(dataPoint);
}
void TransferFunction::removePoint(TransferFunctionDataPoint* dataPoint) {
TFPoints::iterator it = std::find(points_.begin(), points_.end(), dataPoint);
if (it != points_.end()) {
points_.erase(it);
invalidate();
notifyControlPointRemoved(dataPoint);
delete dataPoint;
}
}
void TransferFunction::clearPoints() {
invalidate();
while(points_.size() > 0) {
TransferFunctionDataPoint* dataPoint = points_.back();
points_.pop_back();
notifyControlPointRemoved(dataPoint);
delete dataPoint;
}
}
void TransferFunction::onTransferFunctionPointChange(const TransferFunctionDataPoint* p){
std::stable_sort(points_.begin(), points_.end(), comparePtr<TransferFunctionDataPoint>);
invalidate();
notifyControlPointChanged(p);
}
void TransferFunction::calcTransferValues() {
vec4* dataArray = static_cast<vec4*>(data_->getEditableRepresentation<LayerRAM>()->getData());
std::stable_sort(points_.begin(), points_.end(), comparePtr<TransferFunctionDataPoint>);
if (points_.size() == 0) { // in case of 0 points
for (int i = 0; i < textureSize_; i++) {
dataArray[i] = vec4((float)i / (textureSize_ - 1.0), (float)i / (textureSize_ - 1.0),
(float)i / (textureSize_ - 1.0), 1.0);
}
} else if (points_.size() == 1) { // in case of 1 point
for (int i = 0; i < textureSize_; ++i) {
dataArray[i] = points_[0]->getRGBA();
}
} else { // in case of more than 1 points
int leftX = static_cast<int>(ceil(points_.front()->getPos().x * (textureSize_ - 1)));
int rightX = static_cast<int>(ceil(points_.back()->getPos().x * (textureSize_ - 1)));
for (int i = 0; i <= leftX; i++) dataArray[i] = points_.front()->getRGBA();
for (int i = rightX; i < textureSize_; i++) dataArray[i] = points_.back()->getRGBA();
// if (interpolationType_==TransferFunction::InterpolationLinear) {
// linear interpolation
std::vector<TransferFunctionDataPoint*>::iterator pLeft = points_.begin();
std::vector<TransferFunctionDataPoint*>::iterator pRight = points_.begin() + 1;
while (pRight != points_.end()) {
int n = static_cast<int>(ceil((*pLeft)->getPos().x * (textureSize_ - 1)));
while (n < ceil((*pRight)->getPos().x * (textureSize_ - 1))) {
vec4 lrgba = (*pLeft)->getRGBA();
vec4 rrgba = (*pRight)->getRGBA();
float lx = (*pLeft)->getPos().x * (textureSize_ - 1);
float rx = (*pRight)->getPos().x * (textureSize_ - 1);
float alpha = (n - lx) / (rx - lx);
dataArray[n] = alpha * rrgba + (1.0f - alpha) * lrgba;
n++;
}
pLeft++;
pRight++;
}
//} else {
// cubic interpolation
// TODO: implement cubic interpolation
//}
}
for (int i = 0; i < int(maskMin_ * textureSize_); i++) dataArray[i].a = 0.0;
for (int i = int(maskMax_ * textureSize_); i < textureSize_; i++) dataArray[i].a = 0.0;
invalidData_ = false;
}
void TransferFunction::serialize(IvwSerializer& s) const {
s.serialize("maskMin", maskMin_);
s.serialize("maskMax", maskMax_);
s.serialize("dataPoints", points_, "point");
s.serialize("interpolationType_", static_cast<int>(interpolationType_));
}
void TransferFunction::deserialize(IvwDeserializer& d) {
d.deserialize("maskMin", maskMin_);
d.deserialize("maskMax", maskMax_);
d.deserialize("dataPoints", points_, "point");
for (auto& elem : points_) {
(elem)->addObserver(this);
}
int type = static_cast<int>(interpolationType_);
d.deserialize("interpolationType_", type);
interpolationType_ = static_cast<TransferFunction::InterpolationType>(type);
invalidate();
}
const Layer* TransferFunction::getData() const {
if (invalidData_) {
const_cast<TransferFunction*>(this)->calcTransferValues();
}
return data_;
}
void TransferFunction::invalidate() {
invalidData_ = true;
}
float TransferFunction::getMaskMin() const {
return maskMin_;
}
void TransferFunction::setMaskMin(float maskMin) {
maskMin_ = maskMin;
invalidate();
}
float TransferFunction::getMaskMax() const {
return maskMax_;
}
void TransferFunction::setMaskMax(float maskMax) {
maskMax_ = maskMax;
invalidate();
}
void TransferFunction::setInterpolationType(InterpolationType interpolationType) {
interpolationType_ = interpolationType;
invalidate();
}
inviwo::TransferFunction::InterpolationType TransferFunction::getInterpolationType() const {
return interpolationType_;
}
int TransferFunction::getTextureSize() {
return textureSize_;
}
int TransferFunction::getNumPoints() const {
return static_cast<int>(points_.size());
}
void TransferFunctionObservable::notifyControlPointAdded(TransferFunctionDataPoint* p) const {
for (ObserverSet::reverse_iterator it = observers_->rbegin(); it != observers_->rend(); ++it)
static_cast<TransferFunctionObserver*>(*it)->onControlPointAdded(p);
}
void TransferFunctionObservable::notifyControlPointRemoved(TransferFunctionDataPoint* p) const {
for (ObserverSet::reverse_iterator it = observers_->rbegin(); it != observers_->rend(); ++it)
static_cast<TransferFunctionObserver*>(*it)->onControlPointRemoved(p);
}
void TransferFunctionObservable::notifyControlPointChanged(const TransferFunctionDataPoint* p) const {
for (ObserverSet::reverse_iterator it = observers_->rbegin(); it != observers_->rend(); ++it)
static_cast<TransferFunctionObserver*>(*it)->onControlPointChanged(p);
}
bool operator==(const TransferFunction& lhs, const TransferFunction& rhs) {
return lhs.maskMin_ == rhs.maskMin_
&& lhs.maskMax_ == rhs.maskMax_
&& lhs.interpolationType_ == rhs.interpolationType_
&& lhs.points_ == rhs.points_;
}
bool operator!=(const TransferFunction& lhs, const TransferFunction& rhs) {
return !operator==(lhs, rhs);
}
}<|endoftext|> |
<commit_before>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
** Header: AssemblyName.cpp
**
** Purpose: Implements AssemblyName (loader domain) architecture
**
**
**
===========================================================*/
#include "common.h"
#include <stdlib.h>
#include <shlwapi.h>
#include "assemblyname.hpp"
#include "field.h"
#include "strongname.h"
#include "eeconfig.h"
#ifndef URL_ESCAPE_AS_UTF8
#define URL_ESCAPE_AS_UTF8 0x00040000 // Percent-encode all non-ASCII characters as their UTF-8 equivalents.
#endif
FCIMPL1(Object*, AssemblyNameNative::GetFileInformation, StringObject* filenameUNSAFE)
{
FCALL_CONTRACT;
struct _gc
{
ASSEMBLYNAMEREF result;
STRINGREF filename;
} gc;
gc.result = NULL;
gc.filename = (STRINGREF) filenameUNSAFE;
HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
if (gc.filename == NULL)
COMPlusThrow(kArgumentNullException, W("ArgumentNull_FileName"));
if (gc.filename->GetStringLength() == 0)
COMPlusThrow(kArgumentException, W("Argument_EmptyFileName"));
gc.result = (ASSEMBLYNAMEREF) AllocateObject(MscorlibBinder::GetClass(CLASS__ASSEMBLY_NAME));
///////////////////////////////////////////////
SString sFileName(gc.filename->GetBuffer());
PEImageHolder pImage = PEImage::OpenImage(sFileName, MDInternalImport_NoCache);
// Allow AssemblyLoadContext.GetAssemblyName for native images on CoreCLR
if (pImage->HasNTHeaders() && pImage->HasCorHeader() && pImage->HasNativeHeader())
pImage->VerifyIsNIAssembly();
else
pImage->VerifyIsAssembly();
SString sUrl = sFileName;
PEAssembly::PathToUrl(sUrl);
AssemblySpec spec;
spec.InitializeSpec(TokenFromRid(mdtAssembly,1),pImage->GetMDImport(),NULL,TRUE);
spec.AssemblyNameInit(&gc.result, pImage);
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(gc.result);
}
FCIMPLEND
FCIMPL1(Object*, AssemblyNameNative::ToString, Object* refThisUNSAFE)
{
FCALL_CONTRACT;
OBJECTREF pObj = NULL;
ASSEMBLYNAMEREF pThis = (ASSEMBLYNAMEREF) (OBJECTREF) refThisUNSAFE;
HELPER_METHOD_FRAME_BEGIN_RET_1(pThis);
if (pThis == NULL)
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
Thread *pThread = GetThread();
CheckPointHolder cph(pThread->m_MarshalAlloc.GetCheckpoint()); //hold checkpoint for autorelease
AssemblySpec spec;
spec.InitializeSpec(&(pThread->m_MarshalAlloc), (ASSEMBLYNAMEREF*) &pThis, FALSE, FALSE);
StackSString name;
spec.GetFileOrDisplayName(ASM_DISPLAYF_VERSION |
ASM_DISPLAYF_CULTURE |
ASM_DISPLAYF_PUBLIC_KEY_TOKEN,
name);
pObj = (OBJECTREF) StringObject::NewString(name);
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(pObj);
}
FCIMPLEND
FCIMPL1(Object*, AssemblyNameNative::GetPublicKeyToken, Object* refThisUNSAFE)
{
FCALL_CONTRACT;
U1ARRAYREF orOutputArray = NULL;
OBJECTREF refThis = (OBJECTREF) refThisUNSAFE;
HELPER_METHOD_FRAME_BEGIN_RET_1(refThis);
if (refThis == NULL)
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
ASSEMBLYNAMEREF orThis = (ASSEMBLYNAMEREF)refThis;
U1ARRAYREF orPublicKey = orThis->GetPublicKey();
if (orPublicKey != NULL) {
DWORD cb = orPublicKey->GetNumComponents();
StrongNameBufferHolder<BYTE> pbToken;
if (cb) {
CQuickBytes qb;
BYTE *pbKey = (BYTE*) qb.AllocThrows(cb);
memcpy(pbKey, orPublicKey->GetDataPtr(), cb);
{
GCX_PREEMP();
if (!StrongNameTokenFromPublicKey(pbKey, cb, &pbToken, &cb))
COMPlusThrowHR(StrongNameErrorInfo());
}
}
orOutputArray = (U1ARRAYREF)AllocatePrimitiveArray(ELEMENT_TYPE_U1, cb);
memcpyNoGCRefs(orOutputArray->m_Array, pbToken, cb);
}
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(orOutputArray);
}
FCIMPLEND
FCIMPL3(void, AssemblyNameNative::Init, Object * refThisUNSAFE, OBJECTREF * pAssemblyRef, CLR_BOOL fRaiseResolveEvent)
{
FCALL_CONTRACT;
ASSEMBLYNAMEREF pThis = (ASSEMBLYNAMEREF) (OBJECTREF) refThisUNSAFE;
HRESULT hr = S_OK;
HELPER_METHOD_FRAME_BEGIN_1(pThis);
*pAssemblyRef = NULL;
if (pThis == NULL)
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
Thread * pThread = GetThread();
CheckPointHolder cph(pThread->m_MarshalAlloc.GetCheckpoint()); //hold checkpoint for autorelease
AssemblySpec spec;
hr = spec.InitializeSpec(&(pThread->m_MarshalAlloc), (ASSEMBLYNAMEREF *) &pThis, TRUE, FALSE);
if (SUCCEEDED(hr))
{
spec.AssemblyNameInit(&pThis,NULL);
}
else if ((hr == FUSION_E_INVALID_NAME) && fRaiseResolveEvent)
{
Assembly * pAssembly = GetAppDomain()->RaiseAssemblyResolveEvent(&spec, FALSE, FALSE);
if (pAssembly == NULL)
{
EEFileLoadException::Throw(&spec, hr);
}
else
{
*((OBJECTREF *) (&(*pAssemblyRef))) = pAssembly->GetExposedObject();
}
}
else
{
ThrowHR(hr);
}
HELPER_METHOD_FRAME_END();
}
FCIMPLEND
<commit_msg>Use flat layout for GetAssemblyName (#17052)<commit_after>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
** Header: AssemblyName.cpp
**
** Purpose: Implements AssemblyName (loader domain) architecture
**
**
**
===========================================================*/
#include "common.h"
#include <stdlib.h>
#include <shlwapi.h>
#include "assemblyname.hpp"
#include "field.h"
#include "strongname.h"
#include "eeconfig.h"
#ifndef URL_ESCAPE_AS_UTF8
#define URL_ESCAPE_AS_UTF8 0x00040000 // Percent-encode all non-ASCII characters as their UTF-8 equivalents.
#endif
FCIMPL1(Object*, AssemblyNameNative::GetFileInformation, StringObject* filenameUNSAFE)
{
FCALL_CONTRACT;
struct _gc
{
ASSEMBLYNAMEREF result;
STRINGREF filename;
} gc;
gc.result = NULL;
gc.filename = (STRINGREF) filenameUNSAFE;
HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc);
if (gc.filename == NULL)
COMPlusThrow(kArgumentNullException, W("ArgumentNull_FileName"));
if (gc.filename->GetStringLength() == 0)
COMPlusThrow(kArgumentException, W("Argument_EmptyFileName"));
gc.result = (ASSEMBLYNAMEREF) AllocateObject(MscorlibBinder::GetClass(CLASS__ASSEMBLY_NAME));
///////////////////////////////////////////////
SString sFileName(gc.filename->GetBuffer());
PEImageHolder pImage = PEImage::OpenImage(sFileName, MDInternalImport_NoCache);
// Load the temporary image using a flat layout, instead of
// waiting for it to happen during HasNTHeaders. This allows us to
// get the assembly name for images that contain native code for a
// non-native platform.
PEImageLayoutHolder pLayout(pImage->GetLayout(PEImageLayout::LAYOUT_FLAT, PEImage::LAYOUT_CREATEIFNEEDED));
// Allow AssemblyLoadContext.GetAssemblyName for native images on CoreCLR
if (pImage->HasNTHeaders() && pImage->HasCorHeader() && pImage->HasNativeHeader())
pImage->VerifyIsNIAssembly();
else
pImage->VerifyIsAssembly();
AssemblySpec spec;
spec.InitializeSpec(TokenFromRid(mdtAssembly,1),pImage->GetMDImport(),NULL,TRUE);
spec.AssemblyNameInit(&gc.result, pImage);
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(gc.result);
}
FCIMPLEND
FCIMPL1(Object*, AssemblyNameNative::ToString, Object* refThisUNSAFE)
{
FCALL_CONTRACT;
OBJECTREF pObj = NULL;
ASSEMBLYNAMEREF pThis = (ASSEMBLYNAMEREF) (OBJECTREF) refThisUNSAFE;
HELPER_METHOD_FRAME_BEGIN_RET_1(pThis);
if (pThis == NULL)
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
Thread *pThread = GetThread();
CheckPointHolder cph(pThread->m_MarshalAlloc.GetCheckpoint()); //hold checkpoint for autorelease
AssemblySpec spec;
spec.InitializeSpec(&(pThread->m_MarshalAlloc), (ASSEMBLYNAMEREF*) &pThis, FALSE, FALSE);
StackSString name;
spec.GetFileOrDisplayName(ASM_DISPLAYF_VERSION |
ASM_DISPLAYF_CULTURE |
ASM_DISPLAYF_PUBLIC_KEY_TOKEN,
name);
pObj = (OBJECTREF) StringObject::NewString(name);
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(pObj);
}
FCIMPLEND
FCIMPL1(Object*, AssemblyNameNative::GetPublicKeyToken, Object* refThisUNSAFE)
{
FCALL_CONTRACT;
U1ARRAYREF orOutputArray = NULL;
OBJECTREF refThis = (OBJECTREF) refThisUNSAFE;
HELPER_METHOD_FRAME_BEGIN_RET_1(refThis);
if (refThis == NULL)
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
ASSEMBLYNAMEREF orThis = (ASSEMBLYNAMEREF)refThis;
U1ARRAYREF orPublicKey = orThis->GetPublicKey();
if (orPublicKey != NULL) {
DWORD cb = orPublicKey->GetNumComponents();
StrongNameBufferHolder<BYTE> pbToken;
if (cb) {
CQuickBytes qb;
BYTE *pbKey = (BYTE*) qb.AllocThrows(cb);
memcpy(pbKey, orPublicKey->GetDataPtr(), cb);
{
GCX_PREEMP();
if (!StrongNameTokenFromPublicKey(pbKey, cb, &pbToken, &cb))
COMPlusThrowHR(StrongNameErrorInfo());
}
}
orOutputArray = (U1ARRAYREF)AllocatePrimitiveArray(ELEMENT_TYPE_U1, cb);
memcpyNoGCRefs(orOutputArray->m_Array, pbToken, cb);
}
HELPER_METHOD_FRAME_END();
return OBJECTREFToObject(orOutputArray);
}
FCIMPLEND
FCIMPL3(void, AssemblyNameNative::Init, Object * refThisUNSAFE, OBJECTREF * pAssemblyRef, CLR_BOOL fRaiseResolveEvent)
{
FCALL_CONTRACT;
ASSEMBLYNAMEREF pThis = (ASSEMBLYNAMEREF) (OBJECTREF) refThisUNSAFE;
HRESULT hr = S_OK;
HELPER_METHOD_FRAME_BEGIN_1(pThis);
*pAssemblyRef = NULL;
if (pThis == NULL)
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
Thread * pThread = GetThread();
CheckPointHolder cph(pThread->m_MarshalAlloc.GetCheckpoint()); //hold checkpoint for autorelease
AssemblySpec spec;
hr = spec.InitializeSpec(&(pThread->m_MarshalAlloc), (ASSEMBLYNAMEREF *) &pThis, TRUE, FALSE);
if (SUCCEEDED(hr))
{
spec.AssemblyNameInit(&pThis,NULL);
}
else if ((hr == FUSION_E_INVALID_NAME) && fRaiseResolveEvent)
{
Assembly * pAssembly = GetAppDomain()->RaiseAssemblyResolveEvent(&spec, FALSE, FALSE);
if (pAssembly == NULL)
{
EEFileLoadException::Throw(&spec, hr);
}
else
{
*((OBJECTREF *) (&(*pAssemblyRef))) = pAssembly->GetExposedObject();
}
}
else
{
ThrowHR(hr);
}
HELPER_METHOD_FRAME_END();
}
FCIMPLEND
<|endoftext|> |
<commit_before>#include "parser/expression.h"
#include "parser/ifstatement.h"
#include "parser/forstatement.h"
#include "parser/blockstatement.h"
#include "parser/returnstatement.h"
#include "vm/instruction.h"
#include "vm/instruction-builder.h"
#include "lexer/token.h"
namespace grok {
namespace parser {
using namespace grok::vm;
void NullLiteral::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::push>();
instr->data_type_ = d_null;
builder->AddInstruction(std::move(instr));
}
void ThisHolder::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::fetch>();
instr->data_type_ = d_name;
instr->str_ = "this";
builder->AddInstruction(std::move(instr));
instr = InstructionBuilder::Create<Instructions::pushim>();
instr->data_type_ = d_null;
builder->AddInstruction(std::move(instr));
}
void IntegralLiteral::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::push>();
instr->data_type_ = d_num;
instr->number_ = value_;
builder->AddInstruction(std::move(instr));
}
void StringLiteral::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::push>();
instr->data_type_ = d_str;
instr->str_ = str_;
builder->AddInstruction(std::move(instr));
}
void BooleanLiteral::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::push>();
instr->data_type_ = d_bool;
instr->boolean_ = pred_;
builder->AddInstruction(std::move(instr));
}
void Identifier::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::fetch>();
instr->data_type_ = d_name;
instr->str_ = name_;
builder->AddInstruction(std::move(instr));
instr = InstructionBuilder::Create<Instructions::pushim>();
instr->data_type_ = d_null;
builder->AddInstruction(std::move(instr));
}
void EmitBinaryOperator(BinaryExpression::Operator op,
std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::noop>();
switch (op) {
default:
throw std::runtime_error("unknown operator");
case PLUS:
instr->kind_ = Instructions::adds;
break;
case MINUS:
instr->kind_ = Instructions::subs;
break;
case MUL:
instr->kind_ = Instructions::muls;
break;
case DIV:
instr->kind_ = Instructions::divs;
break;
case SHR:
instr->kind_ = Instructions::shrs;
break;
case SHL:
instr->kind_ = Instructions::shls;
break;
case MOD:
instr->kind_ = Instructions::rems;
break;
case LT:
instr->kind_ = Instructions::lts;
break;
case GT:
instr->kind_ = Instructions::gts;
break;
case EQUAL:
instr->kind_ = Instructions::eqs;
break;
case NOTEQ:
instr->kind_ = Instructions::neqs;
break;
case BAND:
instr->kind_ = Instructions::bands;
break;
case BOR:
instr->kind_ = Instructions::bors;
break;
case OR:
instr->kind_ = Instructions::ors;
break;
case AND:
instr->kind_ = Instructions::ands;
break;
case XOR:
instr->kind_ = Instructions::xors;
break;
}
instr->data_type_ = d_null;
builder->AddInstruction(std::move(instr));
}
void BinaryExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
lhs_->emit(builder);
rhs_->emit(builder);
EmitBinaryOperator(op_, builder);
}
void AssignExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
// generate code for rhs
rhs_->emit(builder);
if (lhs_->ProduceRValue())
throw std::runtime_error("fatal: can't assign to an rvalue");
// first we check whether the lhs_ is an Identifier
auto maybe = dynamic_cast<Identifier*>(lhs_.get());
if (maybe) {
auto ns = InstructionBuilder::Create<Instructions::news>();
ns->data_type_ = d_name;
ns->str_ = maybe->GetName();
builder->AddInstruction(std::move(ns));
lhs_->emit(builder);
} else {
lhs_->emit(builder);
}
auto instr = InstructionBuilder::Create<Instructions::store>();
instr->data_type_ = d_null;
builder->AddInstruction(std::move(instr));
}
void TernaryExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
// now build the code for conditional expression
// result will be stored in the flags
first_->emit(builder);
// add a jmpz instruction at the end of this block
auto instr = InstructionBuilder::Create<Instructions::jmpz>();
instr->data_type_ = d_null;
instr->number_ = 0.0;
instr->jmp_addr_ = 0;
builder->AddInstruction(std::move(instr));
// now create a block that will handle the instructions for second_
builder->CreateBlock();
second_->emit(builder);
// add jmp instruction at the end of current block
instr = InstructionBuilder::Create<Instructions::jmp>();
builder->AddInstruction(std::move(instr));
// update the jmpz instruction which is currently in stack
builder->UpdateStackedJump();
// create another block for third_
builder->CreateBlock();
third_->emit(builder);
builder->EndBlockForJump();
// end the block
builder->EndBlock();
}
void CommaExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
for (auto &expr : exprs_) {
expr->emit(builder);
}
}
void IfStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
// code generation for if statement is almost same as that of ternary
condition_->emit(builder);
auto instr = InstructionBuilder::Create<Instructions::jmpz>();
instr->data_type_ = d_null;
instr->jmp_addr_ = 0;
builder->AddInstruction(std::move(instr));
// create a block that will hold if body
builder->CreateBlock();
body_->emit(builder);
builder->EndBlockForJump();
}
void IfElseStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
// same as that of ternary expression
// result of if condition will be stored in the flags
condition_->emit(builder);
// add a jmpz instruction at the end of current block
auto instr = InstructionBuilder::Create<Instructions::jmpz>();
instr->data_type_ = d_null;
instr->number_ = 0.0;
instr->jmp_addr_ = 0;
builder->AddInstruction(std::move(instr));
// now create a block that will hold instruction for `if` body
builder->CreateBlock();
body_->emit(builder);
// add jmp instruction at the end of current block used for skipping `else`
instr = InstructionBuilder::Create<Instructions::jmp>();
builder->AddInstruction(std::move(instr));
// update the jmpz instruction which is currently in stack
builder->UpdateStackedJump();
// create another block for `else` body
builder->CreateBlock();
else_->emit(builder);
builder->EndBlockForJump();
// end the block
builder->EndBlock();
}
void ForStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
// init code for `for`
init_->emit(builder);
// start of the condition_ instructions
auto cmp_blk_start = builder->CurrentLength();
condition_->emit(builder);
// insert a jmpz instruction at the end of the condition block
auto instr = InstructionBuilder::Create<Instructions::jmpz>();
instr->data_type_ = d_null;
instr->jmp_addr_ = 0; // to be calculate
auto instr_ptr = instr.get();
builder->AddInstruction(std::move(instr));
// end of the condition instructions
auto cmp_blk_end = builder->CurrentLength();
body_->emit(builder);
update_->emit(builder);
// insert a jmp back instruction
instr = InstructionBuilder::Create<Instructions::jmp>();
instr->data_type_ = d_null;
instr->jmp_addr_ = 0; // to be calculated later
auto jmp_back_ptr = instr.get();
builder->AddInstruction(std::move(instr));
// mark the end of the for loop
auto for_loop_end = builder->CurrentLength();
// update the jump instructions
instr_ptr->jmp_addr_ = for_loop_end - cmp_blk_end;
jmp_back_ptr->jmp_addr_ = -(for_loop_end - cmp_blk_start);
}
void BlockStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
for (auto &stmt : stmts_) {
stmt->emit(builder);
}
}
void ArgumentList::emit(std::shared_ptr<InstructionBuilder> builder)
{
for (auto &arg : args_) {
arg->emit(builder);
}
auto size = args_.size();
auto call_instr = InstructionBuilder::Create<Instructions::call>();
call_instr->data_type_ = d_num;
// number of args passed
call_instr->number_ = static_cast<double>(size);
builder->AddInstruction(std::move(call_instr));
}
void FunctionCallExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
// args will be on the top of the stack
// now store the address of the function
func_->emit(builder);
// generate code for args
for (auto &arg : args_) {
arg->emit(builder);
}
auto size = args_.size();
auto call_instr = InstructionBuilder::Create<Instructions::call>();
call_instr->data_type_ = d_num;
// number of args passed this will help in getting the actual
// function from the stack
call_instr->number_ = static_cast<double>(size);
builder->AddInstruction(std::move(call_instr));
}
void DotMemberExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto Property = mem_->GetName();
if (Property.length() == 0)
throw std::runtime_error("property should be a valid string"
"with length > 0");
// now the base object must lie in the stack, so we will
// replace the object with its property Property
auto repl = InstructionBuilder::Create<Instructions::replprop>();
repl->data_type_ = d_name;
repl->str_ = Property;
builder->AddInstruction(std::move(repl));
}
void IndexMemberExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
// now our array or the object lies in stack
// evaluating the expression inside bracket will add one more element
// to the stack. That element will be used in index operator
expr_->emit(builder); // result of this expression is on the stack
auto index = InstructionBuilder::Create<Instructions::index>();
index->data_type_ = d_null;
builder->AddInstruction(std::move(index));
}
void CallExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
func_->emit(builder);
if (members_.size() == 0)
return;
for (auto member = members_.begin();
member != members_.end(); ++member) {
(*member)->emit(builder);
}
}
void MemberExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
for (auto member = members_.begin();
member != members_.end(); ++member) {
(*member)->emit(builder);
}
}
void ReturnStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
if (builder->InsideFunction())
expr_->emit(builder);
else
throw std::runtime_error("return statement was not inside function");
auto ret = InstructionBuilder::Create<Instructions::ret>();
builder->AddInstruction(std::move(ret));
}
void NewExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto inst = InstructionBuilder::Create<Instructions::markst>();
builder->AddInstruction(std::move(inst));
// this function contains many hacks just to make `new` work
// TODO: Find a better logic to do this;
builder->flags &= 0x1;
member_->emit(builder);
auto instr = InstructionBuilder::Create<Instructions::pushthis>();
builder->AddInstruction(std::move(instr));
}
}
}
<commit_msg>Removed extraneous code<commit_after>#include "parser/expression.h"
#include "parser/ifstatement.h"
#include "parser/forstatement.h"
#include "parser/blockstatement.h"
#include "parser/returnstatement.h"
#include "vm/instruction.h"
#include "vm/instruction-builder.h"
#include "lexer/token.h"
namespace grok {
namespace parser {
using namespace grok::vm;
void NullLiteral::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::push>();
instr->data_type_ = d_null;
builder->AddInstruction(std::move(instr));
}
void ThisHolder::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::fetch>();
instr->data_type_ = d_name;
instr->str_ = "this";
builder->AddInstruction(std::move(instr));
instr = InstructionBuilder::Create<Instructions::pushim>();
instr->data_type_ = d_null;
builder->AddInstruction(std::move(instr));
}
void IntegralLiteral::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::push>();
instr->data_type_ = d_num;
instr->number_ = value_;
builder->AddInstruction(std::move(instr));
}
void StringLiteral::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::push>();
instr->data_type_ = d_str;
instr->str_ = str_;
builder->AddInstruction(std::move(instr));
}
void BooleanLiteral::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::push>();
instr->data_type_ = d_bool;
instr->boolean_ = pred_;
builder->AddInstruction(std::move(instr));
}
void Identifier::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::fetch>();
instr->data_type_ = d_name;
instr->str_ = name_;
builder->AddInstruction(std::move(instr));
instr = InstructionBuilder::Create<Instructions::pushim>();
instr->data_type_ = d_null;
builder->AddInstruction(std::move(instr));
}
void EmitBinaryOperator(BinaryExpression::Operator op,
std::shared_ptr<InstructionBuilder> builder)
{
auto instr = InstructionBuilder::Create<Instructions::noop>();
switch (op) {
default:
throw std::runtime_error("unknown operator");
case PLUS:
instr->kind_ = Instructions::adds;
break;
case MINUS:
instr->kind_ = Instructions::subs;
break;
case MUL:
instr->kind_ = Instructions::muls;
break;
case DIV:
instr->kind_ = Instructions::divs;
break;
case SHR:
instr->kind_ = Instructions::shrs;
break;
case SHL:
instr->kind_ = Instructions::shls;
break;
case MOD:
instr->kind_ = Instructions::rems;
break;
case LT:
instr->kind_ = Instructions::lts;
break;
case GT:
instr->kind_ = Instructions::gts;
break;
case EQUAL:
instr->kind_ = Instructions::eqs;
break;
case NOTEQ:
instr->kind_ = Instructions::neqs;
break;
case BAND:
instr->kind_ = Instructions::bands;
break;
case BOR:
instr->kind_ = Instructions::bors;
break;
case OR:
instr->kind_ = Instructions::ors;
break;
case AND:
instr->kind_ = Instructions::ands;
break;
case XOR:
instr->kind_ = Instructions::xors;
break;
}
instr->data_type_ = d_null;
builder->AddInstruction(std::move(instr));
}
void BinaryExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
lhs_->emit(builder);
rhs_->emit(builder);
EmitBinaryOperator(op_, builder);
}
void AssignExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
// generate code for rhs
rhs_->emit(builder);
if (lhs_->ProduceRValue())
throw std::runtime_error("fatal: can't assign to an rvalue");
// first we check whether the lhs_ is an Identifier
auto maybe = dynamic_cast<Identifier*>(lhs_.get());
if (maybe) {
auto ns = InstructionBuilder::Create<Instructions::news>();
ns->data_type_ = d_name;
ns->str_ = maybe->GetName();
builder->AddInstruction(std::move(ns));
lhs_->emit(builder);
} else {
lhs_->emit(builder);
}
auto instr = InstructionBuilder::Create<Instructions::store>();
instr->data_type_ = d_null;
builder->AddInstruction(std::move(instr));
}
void TernaryExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
// now build the code for conditional expression
// result will be stored in the flags
first_->emit(builder);
// add a jmpz instruction at the end of this block
auto instr = InstructionBuilder::Create<Instructions::jmpz>();
instr->data_type_ = d_null;
instr->number_ = 0.0;
instr->jmp_addr_ = 0;
builder->AddInstruction(std::move(instr));
// now create a block that will handle the instructions for second_
builder->CreateBlock();
second_->emit(builder);
// add jmp instruction at the end of current block
instr = InstructionBuilder::Create<Instructions::jmp>();
builder->AddInstruction(std::move(instr));
// update the jmpz instruction which is currently in stack
builder->UpdateStackedJump();
// create another block for third_
builder->CreateBlock();
third_->emit(builder);
builder->EndBlockForJump();
// end the block
builder->EndBlock();
}
void CommaExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
for (auto &expr : exprs_) {
expr->emit(builder);
}
}
void IfStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
// code generation for if statement is almost same as that of ternary
condition_->emit(builder);
auto instr = InstructionBuilder::Create<Instructions::jmpz>();
instr->data_type_ = d_null;
instr->jmp_addr_ = 0;
builder->AddInstruction(std::move(instr));
// create a block that will hold if body
builder->CreateBlock();
body_->emit(builder);
builder->EndBlockForJump();
}
void IfElseStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
// same as that of ternary expression
// result of if condition will be stored in the flags
condition_->emit(builder);
// add a jmpz instruction at the end of current block
auto instr = InstructionBuilder::Create<Instructions::jmpz>();
instr->data_type_ = d_null;
instr->number_ = 0.0;
instr->jmp_addr_ = 0;
builder->AddInstruction(std::move(instr));
// now create a block that will hold instruction for `if` body
builder->CreateBlock();
body_->emit(builder);
// add jmp instruction at the end of current block used for skipping `else`
instr = InstructionBuilder::Create<Instructions::jmp>();
builder->AddInstruction(std::move(instr));
// update the jmpz instruction which is currently in stack
builder->UpdateStackedJump();
// create another block for `else` body
builder->CreateBlock();
else_->emit(builder);
builder->EndBlockForJump();
// end the block
builder->EndBlock();
}
void ForStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
// init code for `for`
init_->emit(builder);
// start of the condition_ instructions
auto cmp_blk_start = builder->CurrentLength();
condition_->emit(builder);
// insert a jmpz instruction at the end of the condition block
auto instr = InstructionBuilder::Create<Instructions::jmpz>();
instr->data_type_ = d_null;
instr->jmp_addr_ = 0; // to be calculate
auto instr_ptr = instr.get();
builder->AddInstruction(std::move(instr));
// end of the condition instructions
auto cmp_blk_end = builder->CurrentLength();
body_->emit(builder);
update_->emit(builder);
// insert a jmp back instruction
instr = InstructionBuilder::Create<Instructions::jmp>();
instr->data_type_ = d_null;
instr->jmp_addr_ = 0; // to be calculated later
auto jmp_back_ptr = instr.get();
builder->AddInstruction(std::move(instr));
// mark the end of the for loop
auto for_loop_end = builder->CurrentLength();
// update the jump instructions
instr_ptr->jmp_addr_ = for_loop_end - cmp_blk_end;
jmp_back_ptr->jmp_addr_ = -(for_loop_end - cmp_blk_start);
}
void BlockStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
for (auto &stmt : stmts_) {
stmt->emit(builder);
}
}
void ArgumentList::emit(std::shared_ptr<InstructionBuilder> builder)
{
for (auto &arg : args_) {
arg->emit(builder);
}
auto size = args_.size();
auto call_instr = InstructionBuilder::Create<Instructions::call>();
call_instr->data_type_ = d_num;
// number of args passed
call_instr->number_ = static_cast<double>(size);
builder->AddInstruction(std::move(call_instr));
}
void FunctionCallExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
// args will be on the top of the stack
// now store the address of the function
func_->emit(builder);
// generate code for args
for (auto &arg : args_) {
arg->emit(builder);
}
auto size = args_.size();
auto call_instr = InstructionBuilder::Create<Instructions::call>();
call_instr->data_type_ = d_num;
// number of args passed this will help in getting the actual
// function from the stack
call_instr->number_ = static_cast<double>(size);
builder->AddInstruction(std::move(call_instr));
}
void DotMemberExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto Property = mem_->GetName();
if (Property.length() == 0)
throw std::runtime_error("property should be a valid string"
"with length > 0");
// now the base object must lie in the stack, so we will
// replace the object with its property Property
auto repl = InstructionBuilder::Create<Instructions::replprop>();
repl->data_type_ = d_name;
repl->str_ = Property;
builder->AddInstruction(std::move(repl));
}
void IndexMemberExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
// now our array or the object lies in stack
// evaluating the expression inside bracket will add one more element
// to the stack. That element will be used in index operator
expr_->emit(builder); // result of this expression is on the stack
auto index = InstructionBuilder::Create<Instructions::index>();
index->data_type_ = d_null;
builder->AddInstruction(std::move(index));
}
void CallExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
func_->emit(builder);
if (members_.size() == 0)
return;
for (auto member = members_.begin();
member != members_.end(); ++member) {
(*member)->emit(builder);
}
}
void MemberExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
for (auto member = members_.begin();
member != members_.end(); ++member) {
(*member)->emit(builder);
}
}
void ReturnStatement::emit(std::shared_ptr<InstructionBuilder> builder)
{
if (builder->InsideFunction())
expr_->emit(builder);
else
throw std::runtime_error("return statement was not inside function");
auto ret = InstructionBuilder::Create<Instructions::ret>();
builder->AddInstruction(std::move(ret));
}
void NewExpression::emit(std::shared_ptr<InstructionBuilder> builder)
{
auto inst = InstructionBuilder::Create<Instructions::markst>();
builder->AddInstruction(std::move(inst));
member_->emit(builder);
auto instr = InstructionBuilder::Create<Instructions::pushthis>();
builder->AddInstruction(std::move(instr));
}
}
}
<|endoftext|> |
<commit_before>#include "../headers/geom.h"
#include <typeinfo>
#include "../headers/geosAlgorithm.h"
namespace geos {
Polygon::Polygon(){
shell=new LinearRing();
holes=new vector<Geometry *>();
}
Polygon::Polygon(const Polygon &p): Geometry(p.precisionModel, p.SRID){
shell=new LinearRing(*p.shell);
holes=new vector<Geometry *>();
for(int i=0;i<(int)p.holes->size();i++) {
LinearRing *h=new LinearRing(* (LinearRing*)(*p.holes)[i]);
holes->push_back(h);
}
}
Polygon::Polygon(LinearRing *newShell, PrecisionModel* precisionModel, int SRID): Geometry(precisionModel, SRID) {
if (newShell==NULL)
newShell=new LinearRing(CoordinateListFactory::internalFactory->createCoordinateList(), precisionModel, SRID);
holes=new vector<Geometry *>();
if (hasNullElements(holes)) {
delete newShell;
delete holes;
throw new IllegalArgumentException("holes must not contain null elements");
}
if (newShell->isEmpty() && hasNonEmptyElements(holes)) {
delete newShell;
delete holes;
throw new IllegalArgumentException("shell is empty but holes are not");
}
shell=newShell;
}
Polygon::Polygon(LinearRing *newShell, vector<Geometry *> *newHoles,
PrecisionModel* precisionModel, int SRID):
Geometry(precisionModel, SRID) {
if (newShell==NULL)
newShell=new LinearRing(CoordinateListFactory::internalFactory->createCoordinateList(), precisionModel, SRID);
if (newHoles==NULL)
newHoles=new vector<Geometry *>();
if (hasNullElements(newHoles)) {
delete newShell;
delete newHoles;
throw new IllegalArgumentException("holes must not contain null elements");
}
if (newShell->isEmpty() && hasNonEmptyElements(newHoles)) {
delete newShell;
delete newHoles;
throw new IllegalArgumentException("shell is empty but holes are not");
}
shell=newShell;
holes=newHoles;
}
CoordinateList* Polygon::getCoordinates() const {
if (isEmpty()) {
return CoordinateListFactory::internalFactory->createCoordinateList();
}
CoordinateList *coordinates=CoordinateListFactory::internalFactory->createCoordinateList(getNumPoints());
int k = -1;
CoordinateList* shellCoordinates=shell->getCoordinates();
for (int x = 0; x < shellCoordinates->getSize(); x++) {
k++;
coordinates->setAt(shellCoordinates->getAt(x),k);
}
delete shellCoordinates;
for (unsigned int i = 0; i < holes->size(); i++) {
CoordinateList* childCoordinates=((LinearRing *)(*holes)[i])->getCoordinates();
for (int j = 0; j < childCoordinates->getSize(); j++) {
k++;
coordinates->setAt(childCoordinates->getAt(j),k);
}
delete childCoordinates;
}
return coordinates;
}
int Polygon::getNumPoints() const {
int numPoints = shell->getNumPoints();
for (unsigned int i = 0; i < holes->size(); i++) {
numPoints += ((LinearRing *)(*holes)[i])->getNumPoints();
}
return numPoints;
}
int Polygon::getDimension() const {
return 2;
}
int Polygon::getBoundaryDimension() const {
return 1;
}
bool Polygon::isEmpty() const {
return shell->isEmpty();
}
bool Polygon::isSimple() const {
return true;
}
const LineString* Polygon::getExteriorRing() const {
return shell;
}
int Polygon::getNumInteriorRing() const {
return (int)holes->size();
}
const LineString* Polygon::getInteriorRingN(int n) const {
return (LineString *) (*holes)[n];
}
string Polygon::getGeometryType() const {
return "Polygon";
}
Geometry* Polygon::getBoundary() const {
if (isEmpty()) {
return new GeometryCollection(NULL, precisionModel, SRID);
}
vector<Geometry *> *rings=new vector<Geometry *>(holes->size() + 1);
(*rings)[0]=new LineString(*shell);
for (unsigned int i=0; i<holes->size(); i++) {
(*rings)[i + 1] =new LineString(*(LineString*)(*holes)[i]);
}
return new MultiLineString(rings, precisionModel, SRID);
}
Envelope* Polygon::computeEnvelopeInternal() const {
return shell->getEnvelopeInternal();
}
bool Polygon::equalsExact(const Geometry *other, double tolerance) const {
if (!isEquivalentClass(other)) {
return false;
}
const Polygon* otherPolygon=dynamic_cast<const Polygon*>(other);
if (typeid(*shell)!=typeid(Geometry)) {
return false;
}
Geometry* thisShell=dynamic_cast<Geometry *>(shell);
if (typeid(*(otherPolygon->shell))!=typeid(Geometry)) {
return false;
}
Geometry* otherPolygonShell=dynamic_cast<Geometry *>(otherPolygon->shell);
if (!shell->equalsExact(otherPolygonShell, tolerance)) {
return false;
}
if (holes->size()!=otherPolygon->holes->size()) {
return false;
}
for (unsigned int i = 0; i < holes->size(); i++) {
if (typeid(*(*holes)[i])!=typeid(Geometry)) {
return false;
}
if (typeid(*((*(otherPolygon->holes))[i]))!=typeid(Geometry)) {
return false;
}
if (!((LinearRing *)(*holes)[i])->equalsExact((*(otherPolygon->holes))[i],tolerance)) {
return false;
}
}
return true;
}
void Polygon::apply_ro(CoordinateFilter *filter) const {
shell->apply_ro(filter);
for (unsigned int i = 0; i < holes->size(); i++) {
((LinearRing *)(*holes)[i])->apply_ro(filter);
}
}
void Polygon::apply_rw(CoordinateFilter *filter) {
shell->apply_rw(filter);
for (unsigned int i = 0; i < holes->size(); i++) {
((LinearRing *)(*holes)[i])->apply_rw(filter);
}
}
void Polygon::apply_rw(GeometryFilter *filter) {
filter->filter_rw(this);
}
void Polygon::apply_ro(GeometryFilter *filter) const {
filter->filter_ro(this);
}
Geometry* Polygon::convexHull() const {
return getExteriorRing()->convexHull();
}
void Polygon::normalize() {
normalize(shell, true);
for (unsigned int i = 0; i < holes->size(); i++) {
normalize((LinearRing *)(*holes)[i], false);
}
sort(holes->begin(),holes->end(),greaterThen);
}
int Polygon::compareToSameClass(const Geometry *p) const {
return shell->compareToSameClass(((Polygon*)p)->shell);
}
void Polygon::normalize(LinearRing *ring, bool clockwise) {
if (ring->isEmpty()) {
return;
}
CoordinateList* uniqueCoordinates=ring->getCoordinates();
uniqueCoordinates->deleteAt(uniqueCoordinates->getSize()-1);
const Coordinate* minCoordinate=CoordinateList::minCoordinate(ring->getCoordinates());
CoordinateList::scroll(uniqueCoordinates, minCoordinate);
uniqueCoordinates->add(uniqueCoordinates->getAt(0));
ring->setPoints(uniqueCoordinates);
if (cgAlgorithms->isCCW(ring->getCoordinates())==clockwise) {
CoordinateList::reverse(ring->getCoordinates());
}
}
const Coordinate* Polygon::getCoordinate() const {
return shell->getCoordinate();
}
/**
* Returns the area of this <code>Polygon</code>
*
*@return the area of the polygon
*/
double Polygon::getArea() const {
double area=0.0;
area+=fabs(CGAlgorithms::signedArea(shell->getCoordinates()));
for(unsigned int i=0;i<holes->size();i++) {
area-=fabs(CGAlgorithms::signedArea((*holes)[i]->getCoordinates()));
}
return area;
}
/**
* Returns the perimeter of this <code>Polygon</code>
*
*@return the perimeter of the polygon
*/
double Polygon::getLength() const {
double len=0.0;
len+=shell->getLength();
for(unsigned int i=0;i<holes->size();i++) {
len+=(*holes)[i]->getLength();
}
return len;
}
void Polygon::apply_ro(GeometryComponentFilter *filter) const {
filter->filter_ro(this);
shell->apply_ro(filter);
for(unsigned int i=0;i<holes->size();i++) {
(*holes)[i]->apply_ro(filter);
}
}
void Polygon::apply_rw(GeometryComponentFilter *filter) {
filter->filter_rw(this);
shell->apply_rw(filter);
for(unsigned int i=0;i<holes->size();i++) {
(*holes)[i]->apply_rw(filter);
}
}
Polygon::~Polygon(){
delete shell;
for(int i=0;i<(int)holes->size();i++) {
delete (*holes)[i];
}
delete holes;
}
}
<commit_msg>Memory leaks fixed. Partially due to getCoordinates() and GeometryCollection() changes, partially old dated.<commit_after>#include "../headers/geom.h"
#include <typeinfo>
#include "../headers/geosAlgorithm.h"
namespace geos {
Polygon::Polygon(){
shell=new LinearRing();
holes=new vector<Geometry *>();
}
Polygon::Polygon(const Polygon &p): Geometry(p.precisionModel, p.SRID){
shell=new LinearRing(*p.shell);
holes=new vector<Geometry *>();
for(int i=0;i<(int)p.holes->size();i++) {
LinearRing *h=new LinearRing(* (LinearRing*)(*p.holes)[i]);
holes->push_back(h);
}
}
Polygon::Polygon(LinearRing *newShell, PrecisionModel* precisionModel, int SRID): Geometry(precisionModel, SRID) {
if (newShell==NULL)
newShell=new LinearRing(CoordinateListFactory::internalFactory->createCoordinateList(), precisionModel, SRID);
holes=new vector<Geometry *>();
if (hasNullElements(holes)) {
delete newShell;
delete holes;
throw new IllegalArgumentException("holes must not contain null elements");
}
if (newShell->isEmpty() && hasNonEmptyElements(holes)) {
delete newShell;
delete holes;
throw new IllegalArgumentException("shell is empty but holes are not");
}
shell=newShell;
}
Polygon::Polygon(LinearRing *newShell, vector<Geometry *> *newHoles,
PrecisionModel* precisionModel, int SRID):
Geometry(precisionModel, SRID) {
if (newShell==NULL)
newShell=new LinearRing(CoordinateListFactory::internalFactory->createCoordinateList(), precisionModel, SRID);
if (newHoles==NULL)
newHoles=new vector<Geometry *>();
if (hasNullElements(newHoles)) {
delete newShell;
delete newHoles;
throw new IllegalArgumentException("holes must not contain null elements");
}
if (newShell->isEmpty() && hasNonEmptyElements(newHoles)) {
delete newShell;
delete newHoles;
throw new IllegalArgumentException("shell is empty but holes are not");
}
shell=newShell;
holes=newHoles;
}
CoordinateList* Polygon::getCoordinates() const {
if (isEmpty()) {
return CoordinateListFactory::internalFactory->createCoordinateList();
}
CoordinateList *coordinates=CoordinateListFactory::internalFactory->createCoordinateList(getNumPoints());
int k = -1;
CoordinateList* shellCoordinates=shell->getCoordinates();
for (int x = 0; x < shellCoordinates->getSize(); x++) {
k++;
coordinates->setAt(shellCoordinates->getAt(x),k);
}
delete shellCoordinates;
for (unsigned int i = 0; i < holes->size(); i++) {
CoordinateList* childCoordinates=((LinearRing *)(*holes)[i])->getCoordinates();
for (int j = 0; j < childCoordinates->getSize(); j++) {
k++;
coordinates->setAt(childCoordinates->getAt(j),k);
}
delete childCoordinates;
}
return coordinates;
}
int Polygon::getNumPoints() const {
int numPoints = shell->getNumPoints();
for (unsigned int i = 0; i < holes->size(); i++) {
numPoints += ((LinearRing *)(*holes)[i])->getNumPoints();
}
return numPoints;
}
int Polygon::getDimension() const {
return 2;
}
int Polygon::getBoundaryDimension() const {
return 1;
}
bool Polygon::isEmpty() const {
return shell->isEmpty();
}
bool Polygon::isSimple() const {
return true;
}
const LineString* Polygon::getExteriorRing() const {
return shell;
}
int Polygon::getNumInteriorRing() const {
return (int)holes->size();
}
const LineString* Polygon::getInteriorRingN(int n) const {
return (LineString *) (*holes)[n];
}
string Polygon::getGeometryType() const {
return "Polygon";
}
// Returns a newly allocated Geometry object
Geometry* Polygon::getBoundary() const {
if (isEmpty()) {
return new GeometryCollection(NULL, precisionModel, SRID);
}
vector<Geometry *> *rings=new vector<Geometry *>(holes->size() + 1);
(*rings)[0]=new LineString(*shell);
for (unsigned int i=0; i<holes->size(); i++) {
(*rings)[i + 1] =new LineString(*(LineString*)(*holes)[i]);
}
MultiLineString *ret = new MultiLineString(rings, precisionModel, SRID);
delete rings;
return ret;
}
Envelope* Polygon::computeEnvelopeInternal() const {
return shell->getEnvelopeInternal();
}
bool Polygon::equalsExact(const Geometry *other, double tolerance) const {
if (!isEquivalentClass(other)) {
return false;
}
const Polygon* otherPolygon=dynamic_cast<const Polygon*>(other);
if (typeid(*shell)!=typeid(Geometry)) {
return false;
}
Geometry* thisShell=dynamic_cast<Geometry *>(shell);
if (typeid(*(otherPolygon->shell))!=typeid(Geometry)) {
return false;
}
Geometry* otherPolygonShell=dynamic_cast<Geometry *>(otherPolygon->shell);
if (!shell->equalsExact(otherPolygonShell, tolerance)) {
return false;
}
if (holes->size()!=otherPolygon->holes->size()) {
return false;
}
for (unsigned int i = 0; i < holes->size(); i++) {
if (typeid(*(*holes)[i])!=typeid(Geometry)) {
return false;
}
if (typeid(*((*(otherPolygon->holes))[i]))!=typeid(Geometry)) {
return false;
}
if (!((LinearRing *)(*holes)[i])->equalsExact((*(otherPolygon->holes))[i],tolerance)) {
return false;
}
}
return true;
}
void Polygon::apply_ro(CoordinateFilter *filter) const {
shell->apply_ro(filter);
for (unsigned int i = 0; i < holes->size(); i++) {
((LinearRing *)(*holes)[i])->apply_ro(filter);
}
}
void Polygon::apply_rw(CoordinateFilter *filter) {
shell->apply_rw(filter);
for (unsigned int i = 0; i < holes->size(); i++) {
((LinearRing *)(*holes)[i])->apply_rw(filter);
}
}
void Polygon::apply_rw(GeometryFilter *filter) {
filter->filter_rw(this);
}
void Polygon::apply_ro(GeometryFilter *filter) const {
filter->filter_ro(this);
}
Geometry* Polygon::convexHull() const {
return getExteriorRing()->convexHull();
}
void Polygon::normalize() {
normalize(shell, true);
for (unsigned int i = 0; i < holes->size(); i++) {
normalize((LinearRing *)(*holes)[i], false);
}
sort(holes->begin(),holes->end(),greaterThen);
}
int Polygon::compareToSameClass(const Geometry *p) const {
return shell->compareToSameClass(((Polygon*)p)->shell);
}
void Polygon::normalize(LinearRing *ring, bool clockwise) {
if (ring->isEmpty()) {
return;
}
CoordinateList* uniqueCoordinates=ring->getCoordinates();
uniqueCoordinates->deleteAt(uniqueCoordinates->getSize()-1);
const Coordinate* minCoordinate=CoordinateList::minCoordinate(uniqueCoordinates);
CoordinateList::scroll(uniqueCoordinates, minCoordinate);
uniqueCoordinates->add(uniqueCoordinates->getAt(0));
if (cgAlgorithms->isCCW(uniqueCoordinates)==clockwise) {
CoordinateList::reverse(uniqueCoordinates);
}
ring->setPoints(uniqueCoordinates);
delete(uniqueCoordinates);
}
const Coordinate* Polygon::getCoordinate() const {
return shell->getCoordinate();
}
/**
* Returns the area of this <code>Polygon</code>
*
*@return the area of the polygon
*/
double Polygon::getArea() const {
double area=0.0;
area+=fabs(CGAlgorithms::signedArea(shell->getCoordinates()));
for(unsigned int i=0;i<holes->size();i++) {
area-=fabs(CGAlgorithms::signedArea((*holes)[i]->getCoordinates()));
}
return area;
}
/**
* Returns the perimeter of this <code>Polygon</code>
*
*@return the perimeter of the polygon
*/
double Polygon::getLength() const {
double len=0.0;
len+=shell->getLength();
for(unsigned int i=0;i<holes->size();i++) {
len+=(*holes)[i]->getLength();
}
return len;
}
void Polygon::apply_ro(GeometryComponentFilter *filter) const {
filter->filter_ro(this);
shell->apply_ro(filter);
for(unsigned int i=0;i<holes->size();i++) {
(*holes)[i]->apply_ro(filter);
}
}
void Polygon::apply_rw(GeometryComponentFilter *filter) {
filter->filter_rw(this);
shell->apply_rw(filter);
for(unsigned int i=0;i<holes->size();i++) {
(*holes)[i]->apply_rw(filter);
}
}
Polygon::~Polygon(){
delete shell;
for(int i=0;i<(int)holes->size();i++) {
delete (*holes)[i];
}
delete holes;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <cmath>
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TCanvas.h"
#include "TRandom3.h"
#include "TVector2.h"
#include "TVector3.h"
#include "TLorentzVector.h"
#include "detector.hpp"
/* Simulated experiment is a K_L->PiPi decay (CP violating)*/
const double K_energy_average /*GeV*/ = 2; // Around the value of Cronin-Fitch experiment
const double K_energy_sigma /*GeV*/ = 0.5;
const double K_path_average /* m */ = 15.34;
const double K_mass /*GeV*/ = 0.497611;
const double Pi_mass /*GeV*/ = 0.139570; // charged pi
const double Pi_energy_cm = K_mass/2;
const double Pi_momentum_mod_cm = sqrt(Pi_energy_cm*Pi_energy_cm - Pi_mass*Pi_mass);
/* Plots constants */
const double hits_bound /* m */ = 100;
TRandom rng;
using namespace std;
ostream& operator<<(ostream& ost, TVector2& vec)
{
return ost << vec.X() << " " << vec.Y();
}
ostream& operator<<(ostream& ost, TVector3& vec)
{
return ost << vec.X() << " " << vec.Y() << " " << vec.Z();
}
inline double generate_K_energy()
{
return max(K_mass, rng.Gaus(K_energy_average, K_energy_sigma));
}
inline double generate_K_path()
{
return rng.Exp(K_path_average);
}
inline double gamma_from_K_energy(double K_energy)
{
return K_energy/K_mass;
}
inline TVector3 generate_Pi_momentum_cm()
{
double x,y,z;
rng.Sphere(x, y, z, Pi_momentum_mod_cm);
return TVector3(x, y, z);
}
inline TVector2 line_propagation(TVector3 Pi_momentum, double z_end, double z_start, double x_start=0, double y_start=0)
{
double z_travelled = z_end - z_start;
double scale = z_travelled/Pi_momentum.Pz();
return TVector2(Pi_momentum.Px()*scale + x_start, Pi_momentum.Py()*scale + y_start);
}
inline TVector2 apply_chamber_smearing(TVector2 hit, double dx, double dy)
{
double x = rng.Gaus(hit.X(), dx);
double y = rng.Gaus(hit.Y(), dy);
return TVector2(x, y);
}
int experiment(int N_events = 1e5)
{
rng = TRandom3(12345); /* Fixed init */
// Histograms declaration
TCanvas* canv_K_energy = new TCanvas("canv_K_energy", "K energy distribution", 1000, 600);
TH1D* histo_K_energy = new TH1D("histo_K_energy", "K energy distribution; E (GeV); N",
200, K_mass, K_energy_average + 3* K_energy_sigma);
TCanvas* canv_K_path = new TCanvas("canv_K_path", "K path distribution", 1000, 600);
TH1D* histo_K_path = new TH1D("histo_K_path", "K path distribution; Path (m); N",
180, 0, 10*gamma_from_K_energy(K_energy_average)*K_path_average);
TCanvas* canv_Pi_momentum_cm = new TCanvas("canv_Pi_momentum_cm", "Pi momentum cm", 1000, 600);
TH3D* histo_Pi_momentum_cm = new TH3D("histo_Pi_momentum_cm", "Pi momentum cm; Px (GeV); Py (GeV); Pz (GeV)",
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm);
TCanvas* canv_Pi_pos = new TCanvas("canv_Pi_pos", "Pi pos", 1000, 600);
TH3D* histo_Pi_pos = new TH3D("histo_Pi_pos", "Pi pos; Px (GeV); Py (GeV); Pz (GeV)",
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, 0, +2*K_energy_average);
TCanvas* canv_hit_p1 = new TCanvas("canv_hit_p1", "Hit pos ch1", 1000, 600);
TH2D* histo_hit_p1 = new TH2D("histo_hit_p1", "Hit pos ch1; x (m); y (m); N",
200, -hits_bound, +hits_bound, 200, -hits_bound, +hits_bound);
TCanvas* canv_hit_p1_smeared = new TCanvas("canv_hit_p1_smeared", "Hit pos ch1 smeared", 1000, 600);
TH2D* histo_hit_p1_smeared = new TH2D("histo_hit_p1_smeared", "Hit pos ch1 smeared; x (m); y (m); N",
200, -hits_bound, +hits_bound, 200, -hits_bound, +hits_bound);
TCanvas* canv_hit_p3 = new TCanvas("canv_hit_p13", "Hit pos ch3", 1000, 600);
TH2D* histo_hit_p3 = new TH2D("histo_hit_p3", "Hit pos ch3; x (m); y (m); N",
200, -hits_bound, +hits_bound, 200, -hits_bound, +hits_bound);
// Out file
ofstream outfile;
outfile.open("experiment.txt");
// Main loop
for (int nev=0; nev<N_events; ++nev) {
// Generate K energy
double K_energy = generate_K_energy();
histo_K_energy->Fill(K_energy);
// Generate K path
double path_cm = generate_K_path();
double path = gamma_from_K_energy(K_energy)*path_cm;
histo_K_path->Fill(path);
// Discard K that have not decayed before the first chamber
if (path > z1) continue;
// Generate cm dynamic
TVector3 Pi_momentum_cm = generate_Pi_momentum_cm();
histo_Pi_momentum_cm->Fill(Pi_momentum_cm.Px(), Pi_momentum_cm.Py(), Pi_momentum_cm.Pz());
// Boost to lab frame
double K_beta_z = sqrt(1 - pow(K_mass/K_energy, 2));
// double x = K_mass/K_energy;
// double K_beta_z = 1 - pow(x, 2)/2 - pow(x, 4)/8 - pow(x, 6)/16;
TVector3 K_beta = TVector3(0, 0, K_beta_z);
TLorentzVector Pi_pos_4v = TLorentzVector( Pi_momentum_cm, Pi_energy_cm);
TLorentzVector Pi_neg_4v = TLorentzVector(-Pi_momentum_cm, Pi_energy_cm); // Momentum cons. in cm
Pi_pos_4v.Boost(K_beta);
Pi_neg_4v.Boost(K_beta);
TVector3 Pi_pos = Pi_pos_4v.Vect();
TVector3 Pi_neg = Pi_neg_4v.Vect();
histo_Pi_pos->Fill(Pi_pos.Px(), Pi_pos.Py(), Pi_pos.Pz());
// Calculate hit points in first two chambers
TVector2 hit_p1=line_propagation(Pi_pos, z1, path);
TVector2 hit_n1=line_propagation(Pi_neg, z1, path);
TVector2 hit_p2=line_propagation(Pi_pos, z2, path);
TVector2 hit_n2=line_propagation(Pi_neg, z2, path);
// Cut in detector acceptance (if they are accepted in ch1 they'll be accepted in all other chambers)
if ((abs(hit_p1.X()) < xcut && abs(hit_p1.Y()) < ycut) ||
(abs(hit_n1.X()) < xcut && abs(hit_n1.Y()) < ycut)) continue;
histo_hit_p1->Fill(hit_p1.X(), hit_p1.Y());
// Apply chamber smearing
TVector2 hit_p1_smeared = apply_chamber_smearing(hit_p1, dx, dy);
TVector2 hit_n1_smeared = apply_chamber_smearing(hit_n1, dx, dy);
TVector2 hit_p2_smeared = apply_chamber_smearing(hit_p2, dx, dy);
TVector2 hit_n2_smeared = apply_chamber_smearing(hit_n2, dx, dy);
histo_hit_p1_smeared->Fill(hit_p1_smeared.X(), hit_p1_smeared.Y());
// The magnetic field is schematized as a kick of magnitude p_kick
// applied at the center of the magnetic field region (z_kick)
// Find position at kick
TVector2 Pi_pos_position_kick = line_propagation(Pi_pos, z_kick, path);
TVector2 Pi_neg_position_kick = line_propagation(Pi_neg, z_kick, path);
TVector3 p_kick_vec = TVector3(p_kick, 0, 0);
// Find hits in last two chambers - p_kick is opposite due to charge
TVector2 hit_p3=line_propagation(Pi_pos + p_kick_vec, z3, z_kick, Pi_pos_position_kick.X(), Pi_pos_position_kick.Y());
TVector2 hit_n3=line_propagation(Pi_neg - p_kick_vec, z3, z_kick, Pi_neg_position_kick.X(), Pi_neg_position_kick.Y());
TVector2 hit_p4=line_propagation(Pi_pos + p_kick_vec, z4, z_kick, Pi_pos_position_kick.X(), Pi_pos_position_kick.Y());
TVector2 hit_n4=line_propagation(Pi_neg - p_kick_vec, z4, z_kick, Pi_neg_position_kick.X(), Pi_neg_position_kick.Y());
histo_hit_p3->Fill(hit_p3.X(), hit_p3.Y());
// Apply chamber smearing
TVector2 hit_p3_smeared = apply_chamber_smearing(hit_p3, dx, dy);
TVector2 hit_n3_smeared = apply_chamber_smearing(hit_n3, dx, dy);
TVector2 hit_p4_smeared = apply_chamber_smearing(hit_p4, dx, dy);
TVector2 hit_n4_smeared = apply_chamber_smearing(hit_n4, dx, dy);
// Write to file
outfile << nev << " ";
outfile << hit_p1_smeared << " ";
outfile << hit_n1_smeared << " ";
outfile << hit_p2_smeared << " ";
outfile << hit_n2_smeared << " ";
outfile << hit_p3_smeared << " ";
outfile << hit_n3_smeared << " ";
outfile << hit_p4_smeared << " ";
outfile << hit_n4_smeared << " ";
outfile << K_energy << " ";
outfile << path << " ";
outfile << Pi_pos << " ";
outfile << Pi_neg <<endl;
}
// Histogram drawing
canv_K_energy->cd();
histo_K_energy->Draw();
canv_K_path->cd();
canv_K_path->SetLogy();
histo_K_path->Draw();
canv_Pi_momentum_cm->cd();
histo_Pi_momentum_cm->Draw();
canv_Pi_pos->cd();
histo_Pi_pos->Draw();
canv_hit_p1->cd();
histo_hit_p1->Draw();
canv_hit_p1_smeared->cd();
histo_hit_p1_smeared->Draw();
canv_hit_p3->cd();
histo_hit_p3->Draw();
return 0;
}
int main(int argc, char** argv)
{
int N_events = 1e5;
if (argc>1) N_events = atoi(argv[1]);
return experiment(N_events);
}
<commit_msg>Added lifetime in cm histogram<commit_after>#include <iostream>
#include <fstream>
#include <cmath>
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TCanvas.h"
#include "TRandom3.h"
#include "TVector2.h"
#include "TVector3.h"
#include "TLorentzVector.h"
#include "detector.hpp"
/* Simulated experiment is a K_L->PiPi decay (CP violating)*/
const double K_energy_average /*GeV*/ = 2; // Around the value of Cronin-Fitch experiment
const double K_energy_sigma /*GeV*/ = 0.5;
const double K_path_average /* m */ = 15.34;
const double K_mass /*GeV*/ = 0.497611;
const double c /* m/ns */ = 0.3;
const double Pi_mass /*GeV*/ = 0.139570; // charged pi
const double Pi_energy_cm = K_mass/2;
const double Pi_momentum_mod_cm = sqrt(Pi_energy_cm*Pi_energy_cm - Pi_mass*Pi_mass);
/* Plots constants */
const double hits_bound /* m */ = 100;
TRandom rng;
using namespace std;
ostream& operator<<(ostream& ost, TVector2& vec)
{
return ost << vec.X() << " " << vec.Y();
}
ostream& operator<<(ostream& ost, TVector3& vec)
{
return ost << vec.X() << " " << vec.Y() << " " << vec.Z();
}
inline double generate_K_energy()
{
return max(K_mass, rng.Gaus(K_energy_average, K_energy_sigma));
}
inline double generate_K_path()
{
return rng.Exp(K_path_average);
}
inline double gamma_from_K_energy(double K_energy)
{
return K_energy/K_mass;
}
inline TVector3 generate_Pi_momentum_cm()
{
double x,y,z;
rng.Sphere(x, y, z, Pi_momentum_mod_cm);
return TVector3(x, y, z);
}
inline TVector2 line_propagation(TVector3 Pi_momentum, double z_end, double z_start, double x_start=0, double y_start=0)
{
double z_travelled = z_end - z_start;
double scale = z_travelled/Pi_momentum.Pz();
return TVector2(Pi_momentum.Px()*scale + x_start, Pi_momentum.Py()*scale + y_start);
}
inline TVector2 apply_chamber_smearing(TVector2 hit, double dx, double dy)
{
double x = rng.Gaus(hit.X(), dx);
double y = rng.Gaus(hit.Y(), dy);
return TVector2(x, y);
}
int experiment(int N_events = 1e5)
{
rng = TRandom3(12345); /* Fixed init */
// Histograms declaration
TCanvas* canv_K_energy = new TCanvas("canv_K_energy", "K energy distribution", 1000, 600);
TH1D* histo_K_energy = new TH1D("histo_K_energy", "K energy distribution; E (GeV); N",
200, K_mass, K_energy_average + 3* K_energy_sigma);
TCanvas* canv_K_lifetime = new TCanvas("canv_K_lifetime", "K lifetime distribution", 1000, 600);
TH1D* histo_K_lifetime = new TH1D("histo_K_lifetime", "K lifetime distribution; Lifetime (ns); N",
200, 0, 10*K_path_average/c);
TCanvas* canv_K_path = new TCanvas("canv_K_path", "K path distribution", 1000, 600);
TH1D* histo_K_path = new TH1D("histo_K_path", "K path distribution; Path (m); N",
200, 0, 10*gamma_from_K_energy(K_energy_average)*K_path_average);
TCanvas* canv_Pi_momentum_cm = new TCanvas("canv_Pi_momentum_cm", "Pi momentum cm", 1000, 600);
TH3D* histo_Pi_momentum_cm = new TH3D("histo_Pi_momentum_cm", "Pi momentum cm; Px (GeV); Py (GeV); Pz (GeV)",
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm);
TCanvas* canv_Pi_pos = new TCanvas("canv_Pi_pos", "Pi pos", 1000, 600);
TH3D* histo_Pi_pos = new TH3D("histo_Pi_pos", "Pi pos; Px (GeV); Py (GeV); Pz (GeV)",
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, -Pi_momentum_mod_cm, +Pi_momentum_mod_cm,
100, 0, +2*K_energy_average);
TCanvas* canv_hit_p1 = new TCanvas("canv_hit_p1", "Hit pos ch1", 1000, 600);
TH2D* histo_hit_p1 = new TH2D("histo_hit_p1", "Hit pos ch1; x (m); y (m); N",
200, -hits_bound, +hits_bound, 200, -hits_bound, +hits_bound);
TCanvas* canv_hit_p1_smeared = new TCanvas("canv_hit_p1_smeared", "Hit pos ch1 smeared", 1000, 600);
TH2D* histo_hit_p1_smeared = new TH2D("histo_hit_p1_smeared", "Hit pos ch1 smeared; x (m); y (m); N",
200, -hits_bound, +hits_bound, 200, -hits_bound, +hits_bound);
TCanvas* canv_hit_p3 = new TCanvas("canv_hit_p13", "Hit pos ch3", 1000, 600);
TH2D* histo_hit_p3 = new TH2D("histo_hit_p3", "Hit pos ch3; x (m); y (m); N",
200, -hits_bound, +hits_bound, 200, -hits_bound, +hits_bound);
// Out file
ofstream outfile;
outfile.open("experiment.txt");
// Main loop
for (int nev=0; nev<N_events; ++nev) {
// Generate K energy
double K_energy = generate_K_energy();
histo_K_energy->Fill(K_energy);
// Generate K path
double path_cm = generate_K_path();
histo_K_lifetime->Fill(path_cm/c);
double path = gamma_from_K_energy(K_energy)*path_cm;
histo_K_path->Fill(path);
// Discard K that have not decayed before the first chamber
if (path > z1) continue;
// Generate cm dynamic
TVector3 Pi_momentum_cm = generate_Pi_momentum_cm();
histo_Pi_momentum_cm->Fill(Pi_momentum_cm.Px(), Pi_momentum_cm.Py(), Pi_momentum_cm.Pz());
// Boost to lab frame
double K_beta_z = sqrt(1 - pow(K_mass/K_energy, 2));
// double x = K_mass/K_energy;
// double K_beta_z = 1 - pow(x, 2)/2 - pow(x, 4)/8 - pow(x, 6)/16;
TVector3 K_beta = TVector3(0, 0, K_beta_z);
TLorentzVector Pi_pos_4v = TLorentzVector( Pi_momentum_cm, Pi_energy_cm);
TLorentzVector Pi_neg_4v = TLorentzVector(-Pi_momentum_cm, Pi_energy_cm); // Momentum cons. in cm
Pi_pos_4v.Boost(K_beta);
Pi_neg_4v.Boost(K_beta);
TVector3 Pi_pos = Pi_pos_4v.Vect();
TVector3 Pi_neg = Pi_neg_4v.Vect();
histo_Pi_pos->Fill(Pi_pos.Px(), Pi_pos.Py(), Pi_pos.Pz());
// Calculate hit points in first two chambers
TVector2 hit_p1=line_propagation(Pi_pos, z1, path);
TVector2 hit_n1=line_propagation(Pi_neg, z1, path);
TVector2 hit_p2=line_propagation(Pi_pos, z2, path);
TVector2 hit_n2=line_propagation(Pi_neg, z2, path);
// Cut in detector acceptance (if they are accepted in ch1 they'll be accepted in all other chambers)
if ((abs(hit_p1.X()) < xcut && abs(hit_p1.Y()) < ycut) ||
(abs(hit_n1.X()) < xcut && abs(hit_n1.Y()) < ycut)) continue;
histo_hit_p1->Fill(hit_p1.X(), hit_p1.Y());
// Apply chamber smearing
TVector2 hit_p1_smeared = apply_chamber_smearing(hit_p1, dx, dy);
TVector2 hit_n1_smeared = apply_chamber_smearing(hit_n1, dx, dy);
TVector2 hit_p2_smeared = apply_chamber_smearing(hit_p2, dx, dy);
TVector2 hit_n2_smeared = apply_chamber_smearing(hit_n2, dx, dy);
histo_hit_p1_smeared->Fill(hit_p1_smeared.X(), hit_p1_smeared.Y());
// The magnetic field is schematized as a kick of magnitude p_kick
// applied at the center of the magnetic field region (z_kick)
// Find position at kick
TVector2 Pi_pos_position_kick = line_propagation(Pi_pos, z_kick, path);
TVector2 Pi_neg_position_kick = line_propagation(Pi_neg, z_kick, path);
TVector3 p_kick_vec = TVector3(p_kick, 0, 0);
// Find hits in last two chambers - p_kick is opposite due to charge
TVector2 hit_p3=line_propagation(Pi_pos + p_kick_vec, z3, z_kick, Pi_pos_position_kick.X(), Pi_pos_position_kick.Y());
TVector2 hit_n3=line_propagation(Pi_neg - p_kick_vec, z3, z_kick, Pi_neg_position_kick.X(), Pi_neg_position_kick.Y());
TVector2 hit_p4=line_propagation(Pi_pos + p_kick_vec, z4, z_kick, Pi_pos_position_kick.X(), Pi_pos_position_kick.Y());
TVector2 hit_n4=line_propagation(Pi_neg - p_kick_vec, z4, z_kick, Pi_neg_position_kick.X(), Pi_neg_position_kick.Y());
histo_hit_p3->Fill(hit_p3.X(), hit_p3.Y());
// Apply chamber smearing
TVector2 hit_p3_smeared = apply_chamber_smearing(hit_p3, dx, dy);
TVector2 hit_n3_smeared = apply_chamber_smearing(hit_n3, dx, dy);
TVector2 hit_p4_smeared = apply_chamber_smearing(hit_p4, dx, dy);
TVector2 hit_n4_smeared = apply_chamber_smearing(hit_n4, dx, dy);
// Write to file
outfile << nev << " ";
outfile << hit_p1_smeared << " ";
outfile << hit_n1_smeared << " ";
outfile << hit_p2_smeared << " ";
outfile << hit_n2_smeared << " ";
outfile << hit_p3_smeared << " ";
outfile << hit_n3_smeared << " ";
outfile << hit_p4_smeared << " ";
outfile << hit_n4_smeared << " ";
outfile << K_energy << " ";
outfile << path << " ";
outfile << Pi_pos << " ";
outfile << Pi_neg <<endl;
}
// Histogram drawing
canv_K_energy->cd();
histo_K_energy->Draw();
canv_K_lifetime->cd();
canv_K_lifetime->SetLogy();
histo_K_lifetime->Fit("expo");
histo_K_lifetime->Draw();
canv_K_path->cd();
canv_K_path->SetLogy();
histo_K_path->Draw();
canv_Pi_momentum_cm->cd();
histo_Pi_momentum_cm->Draw();
canv_Pi_pos->cd();
histo_Pi_pos->Draw();
canv_hit_p1->cd();
histo_hit_p1->Draw();
canv_hit_p1_smeared->cd();
histo_hit_p1_smeared->Draw();
canv_hit_p3->cd();
histo_hit_p3->Draw();
return 0;
}
int main(int argc, char** argv)
{
int N_events = 1e5;
if (argc>1) N_events = atoi(argv[1]);
return experiment(N_events);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestTemporalCache.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkActor.h"
#include "vtkCommand.h"
#include "vtkCompositeDataPipeline.h"
#include "vtkContourFilter.h"
#include "vtkInformation.h"
#include "vtkMultiGroupDataGeometryFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkSmartPointer.h"
#include "vtkTemporalDataSet.h"
#include "vtkTemporalDataSetCache.h"
#include "vtkTemporalFractal.h"
#include "vtkTemporalInterpolator.h"
#include "vtkThreshold.h"
class ExecuteCallback
: public vtkCommand
{
public:
static ExecuteCallback *New()
{ return new ExecuteCallback; }
virtual void Execute(vtkObject *caller, unsigned long, void*)
{
// count the number of time steps requested
vtkTemporalFractal *frac = vtkTemporalFractal::SafeDownCast(caller);
this->Count += frac->GetExecutive()->GetOutputInformation(0)
->Length(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS());
}
unsigned int Count;
};
//-------------------------------------------------------------------------
int main(int argc, char *argv[])
{
// we have to use a compsite pipeline
vtkCompositeDataPipeline* prototype = vtkCompositeDataPipeline::New();
vtkAlgorithm::SetDefaultExecutivePrototype(prototype);
prototype->Delete();
// create temporal fractals
vtkSmartPointer<vtkTemporalFractal> fractal =
vtkSmartPointer<vtkTemporalFractal>::New();
fractal->SetMaximumLevel(2);
fractal->DiscreteTimeStepsOn();
fractal->GenerateRectilinearGridsOn();
ExecuteCallback *executecb =ExecuteCallback::New();
executecb->Count = 0;
fractal->AddObserver(vtkCommand::StartEvent,executecb);
executecb->Delete();
// cache the data to prevent regenerating some of it
vtkSmartPointer<vtkTemporalDataSetCache> cache =
vtkSmartPointer<vtkTemporalDataSetCache>::New();
cache->SetInputConnection(fractal->GetOutputPort());
cache->SetCacheSize(2);
// interpolate if needed
vtkSmartPointer<vtkTemporalInterpolator> interp =
vtkSmartPointer<vtkTemporalInterpolator>::New();
//interp->SetInputConnection(fractal->GetOutputPort());
interp->SetInputConnection(cache->GetOutputPort());
// cache the data coming out of the interpolator
vtkSmartPointer<vtkTemporalDataSetCache> cache2 =
vtkSmartPointer<vtkTemporalDataSetCache>::New();
cache2->SetInputConnection(interp->GetOutputPort());
cache2->SetCacheSize(11);
vtkSmartPointer<vtkThreshold> contour =
vtkSmartPointer<vtkThreshold>::New();
//contour->SetInputConnection(interp->GetOutputPort());
contour->SetInputConnection(cache2->GetOutputPort());
contour->ThresholdByUpper(0.5);
vtkSmartPointer<vtkMultiGroupDataGeometryFilter> geom =
vtkSmartPointer<vtkMultiGroupDataGeometryFilter>::New();
geom->SetInputConnection(contour->GetOutputPort());
// map them
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(geom->GetOutputPort());
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWin =
vtkSmartPointer<vtkRenderWindow>::New();
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderer->AddActor( actor );
renderer->SetBackground(0.5, 0.5, 0.5);
renWin->AddRenderer( renderer );
renWin->SetSize( 300, 300 );
iren->SetRenderWindow( renWin );
renWin->Render();
// ask for some specific data points
vtkStreamingDemandDrivenPipeline *sdd =
vtkStreamingDemandDrivenPipeline::SafeDownCast(geom->GetExecutive());
double times[1];
times[0] = 0;
int i;
int j;
for (j = 0; j < 5; ++j)
{
for (i = 0; i < 11; ++i)
{
times[0] = i/2.0;
sdd->SetUpdateTimeSteps(0, times, 1);
mapper->Modified();
renderer->ResetCameraClippingRange();
renWin->Render();
}
}
vtkAlgorithm::SetDefaultExecutivePrototype(0);
if (executecb->Count == 8)
{
return 0;
}
return 1;
}
<commit_msg>COMP: fix compiler warning<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestTemporalCache.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkActor.h"
#include "vtkCommand.h"
#include "vtkCompositeDataPipeline.h"
#include "vtkContourFilter.h"
#include "vtkInformation.h"
#include "vtkMultiGroupDataGeometryFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkSmartPointer.h"
#include "vtkTemporalDataSet.h"
#include "vtkTemporalDataSetCache.h"
#include "vtkTemporalFractal.h"
#include "vtkTemporalInterpolator.h"
#include "vtkThreshold.h"
class ExecuteCallback
: public vtkCommand
{
public:
static ExecuteCallback *New()
{ return new ExecuteCallback; }
virtual void Execute(vtkObject *caller, unsigned long, void*)
{
// count the number of time steps requested
vtkTemporalFractal *frac = vtkTemporalFractal::SafeDownCast(caller);
this->Count += frac->GetExecutive()->GetOutputInformation(0)
->Length(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS());
}
unsigned int Count;
};
//-------------------------------------------------------------------------
int main(int , char *[])
{
// we have to use a compsite pipeline
vtkCompositeDataPipeline* prototype = vtkCompositeDataPipeline::New();
vtkAlgorithm::SetDefaultExecutivePrototype(prototype);
prototype->Delete();
// create temporal fractals
vtkSmartPointer<vtkTemporalFractal> fractal =
vtkSmartPointer<vtkTemporalFractal>::New();
fractal->SetMaximumLevel(2);
fractal->DiscreteTimeStepsOn();
fractal->GenerateRectilinearGridsOn();
ExecuteCallback *executecb =ExecuteCallback::New();
executecb->Count = 0;
fractal->AddObserver(vtkCommand::StartEvent,executecb);
executecb->Delete();
// cache the data to prevent regenerating some of it
vtkSmartPointer<vtkTemporalDataSetCache> cache =
vtkSmartPointer<vtkTemporalDataSetCache>::New();
cache->SetInputConnection(fractal->GetOutputPort());
cache->SetCacheSize(2);
// interpolate if needed
vtkSmartPointer<vtkTemporalInterpolator> interp =
vtkSmartPointer<vtkTemporalInterpolator>::New();
//interp->SetInputConnection(fractal->GetOutputPort());
interp->SetInputConnection(cache->GetOutputPort());
// cache the data coming out of the interpolator
vtkSmartPointer<vtkTemporalDataSetCache> cache2 =
vtkSmartPointer<vtkTemporalDataSetCache>::New();
cache2->SetInputConnection(interp->GetOutputPort());
cache2->SetCacheSize(11);
vtkSmartPointer<vtkThreshold> contour =
vtkSmartPointer<vtkThreshold>::New();
//contour->SetInputConnection(interp->GetOutputPort());
contour->SetInputConnection(cache2->GetOutputPort());
contour->ThresholdByUpper(0.5);
vtkSmartPointer<vtkMultiGroupDataGeometryFilter> geom =
vtkSmartPointer<vtkMultiGroupDataGeometryFilter>::New();
geom->SetInputConnection(contour->GetOutputPort());
// map them
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(geom->GetOutputPort());
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renWin =
vtkSmartPointer<vtkRenderWindow>::New();
vtkSmartPointer<vtkRenderWindowInteractor> iren =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderer->AddActor( actor );
renderer->SetBackground(0.5, 0.5, 0.5);
renWin->AddRenderer( renderer );
renWin->SetSize( 300, 300 );
iren->SetRenderWindow( renWin );
renWin->Render();
// ask for some specific data points
vtkStreamingDemandDrivenPipeline *sdd =
vtkStreamingDemandDrivenPipeline::SafeDownCast(geom->GetExecutive());
double times[1];
times[0] = 0;
int i;
int j;
for (j = 0; j < 5; ++j)
{
for (i = 0; i < 11; ++i)
{
times[0] = i/2.0;
sdd->SetUpdateTimeSteps(0, times, 1);
mapper->Modified();
renderer->ResetCameraClippingRange();
renWin->Render();
}
}
vtkAlgorithm::SetDefaultExecutivePrototype(0);
if (executecb->Count == 8)
{
return 0;
}
return 1;
}
<|endoftext|> |
<commit_before>/*
* Program.cxx
*
* Author
* Andrew Brown <adb1413@rit.edu>
*/
#include "config.h"
#include <stdexcept>
#include "glycerin/Program.hxx"
using namespace std;
namespace Glycerin {
/**
* Constructs a program wrapping an existing shader program.
*
* @param id ID of existing shader program to wrap
* @throws invalid_argument if ID is not an existing OpenGL shader program
*/
Program::Program(GLuint id) : _id(id) {
if (!glIsProgram(_id)) {
throw invalid_argument("[Program] ID not an existing OpenGL shader program!");
}
}
/**
* Destroys this program handle, leaving the underlying OpenGL shader program unaffected.
*
* @see @ref dispose
*/
Program::~Program() {
// empty
}
/**
* Constructs a program by copying another program.
*
* @param program Program to copy
*/
Program::Program(const Program& program) : _id(program._id) {
// pass
}
/**
* Retrieves all the active attributes in this program.
*
* @return Mapping of all the active attributes in this program by name
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetActiveAttrib.xml
*/
map<string,Attribute> Program::activeAttributes() const {
// Get number of active attributes
GLint num;
glGetProgramiv(_id, GL_ACTIVE_ATTRIBUTES, &num);
if (num == 0) {
return map<string,Attribute>();
}
// Make a buffer to hold name of an attribute
GLint len;
glGetProgramiv(_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &len);
char* const buf = new char[len];
// Make variables to hold size and type of an attribute
GLint size;
GLenum type;
// Put active attributes into a map
map<string,Attribute> attribs;
for (int i = 0; i < num; ++i) {
glGetActiveAttrib(_id, i, len, NULL, &size, &type, buf);
const GLint location = glGetAttribLocation(_id, buf);
const string name = buf;
const Attribute attrib(location, name, _id, size, type);
attribs.insert(pair<string,Attribute>(name, attrib));
}
// Delete the buffer
delete[] buf;
// Return the vector
return attribs;
}
/**
* Retrieves all the active uniforms in this program.
*
* @return Mapping of all the active uniforms in this program by name
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetActiveUniform.xml
*/
map<string,Uniform> Program::activeUniforms() const {
// Get number of active uniforms
GLint num;
glGetProgramiv(_id, GL_ACTIVE_UNIFORMS, &num);
if (num == 0) {
return map<string,Uniform>();
}
// Make a buffer to hold name of a uniform
GLint len;
glGetProgramiv(_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &len);
char* const buf = new char[len];
// Make variables to hold size and type of a uniform
GLint size;
GLenum type;
// Put active uniforms into a map
map<string,Uniform> uniforms;
for (int i = 0; i < num; ++i) {
glGetActiveUniform(_id, i, len, NULL, &size, &type, buf);
const GLint location = glGetUniformLocation(_id, buf);
const string name = buf;
const Uniform uniform(location, name, _id, size, type);
uniforms.insert(pair<string,Uniform>(name, uniform));
}
// Delete the buffer
delete[] buf;
// Return the vector
return uniforms;
}
/**
* Attaches a shader to this program.
*
* @param shader OpenGL identifier for the shader to attach
* @throw invalid_argument if shader is not valid
* @throw logic_error if shader is already attached
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glAttachShader.xml
*/
void Program::attachShader(GLuint shader) const {
attachShader(Shader::fromId(shader));
}
/**
* Attaches a shader to this program.
*
* @param shader Wrapper for an OpenGL shader
* @throw logic_error if shader is already attached
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glAttachShader.xml
*/
void Program::attachShader(const Shader &shader) const {
if (isAttached(shader)) {
throw logic_error("[Program] Shader is already attached!");
}
glAttachShader(_id, shader.id());
}
/**
* Determines the location of an attribute in this program.
*
* @param name Name of attribute to look up
* @return Location of the attribute in this program, or `-1` if attribute is not in this program
* @throws invalid_argument if name is empty
* @throws logic_error if program has not been linked yet
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetAttribLocation.xml
*/
GLint Program::attribLocation(const std::string &name) const {
if (name.empty()) {
throw invalid_argument("[Program] Name is empty!");
} else if (!linked()) {
throw logic_error("[Program] Program not linked yet!");
}
return glGetAttribLocation(_id, name.c_str());
}
/**
* Binds an attribute to a specific location.
*
* @param name Name of attribute
* @param location Location to bind to
* @throw invalid_argument if name is empty
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glBindAttribLocation.xml
*/
void Program::attribLocation(const std::string& name, GLuint location) const {
if (name.empty()) {
throw invalid_argument("[Program] Name is empty!");
}
glBindAttribLocation(_id, location, name.c_str());
}
/**
* Creates a new program.
*
* @return New program instance
* @throws runtime_error if program could not be created
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glCreateProgram.xml
*/
Program Program::create() {
// Create an ID
const GLuint id = glCreateProgram();
if (id == 0) {
throw runtime_error("[Program] Could not create program!");
}
// Make the program
return Program(id);
}
/**
* Detaches a shader from this program.
*
* @param shader Shader to detach
* @throws invalid_argument if shader is not a valid shader
* @throws logic_error if shader is not already attached
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glDetachShader.xml
*/
void Program::detachShader(GLuint shader) const {
detachShader(Shader::fromId(shader));
}
/**
* Detaches a shader from this program.
*
* @param shader Shader to detach
* @throws logic_error if shader is not already attached
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glDetachShader.xml
*/
void Program::detachShader(const Shader &shader) const {
if (!isAttached(shader)) {
throw logic_error("[Program] Shader not already attached!");
}
glDetachShader(_id, shader.id());
}
/**
* Deletes the underlying OpenGL shader program.
*
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glDeleteProgram.xml
*/
void Program::dispose() const {
glDeleteProgram(_id);
}
/**
* Determines the location of an output variable in this program.
*
* @param name Name of output variable to look up
* @return Location of output variable, or `-1` if name is not an active output variable
* @throws invalid_argument if name is empty
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetFragDataLocation.xml
*/
GLint Program::fragDataLocation(const std::string& name) const {
if (name.empty()) {
throw invalid_argument("[Program] Name is empty!");
}
return glGetFragDataLocation(_id, name.c_str());
}
/**
* Binds a fragment shader output variable to a location.
*
* @param name Name of output variable to bind
* @param location Location of draw buffer to bind to
* @throws invalid_argument if name is empty or starts with `gl_`
* @throws invalid_argument if location greater than `GL_MAX_DRAW_BUFFERS`
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glBindFragDataLocation.xml
*/
void Program::fragDataLocation(const std::string &name, GLuint location) const {
if (name.empty()) {
throw invalid_argument("[Program] Name is empty!");
} else if (name.find("gl_") == 0) {
throw invalid_argument("[Program] Name starts with 'gl_'!");
} else if (location > getMaxDrawBuffers()) {
throw invalid_argument("[Program] Location greater than GL_MAX_DRAW_BUFFERS!");
}
glBindFragDataLocation(_id, location, name.c_str());
}
/**
* Determines the ID of the underlying OpenGL shader program this program handle represents.
*
* @return ID of the underlying OpenGL shader program this program handle represents
*/
GLuint Program::id() const {
return _id;
}
/**
* Links this program.
*
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glLinkProgram.xml
*/
void Program::link() const {
glLinkProgram(_id);
}
/**
* Checks if this program is linked.
*
* @return `true` if this program is linked
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetProgram.xml
*/
bool Program::linked() const {
GLint linked;
glGetProgramiv(_id, GL_LINK_STATUS, &linked);
return linked;
}
/**
* Retrieves a copy of this program's log.
*
* @return Copy of this program's log
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetProgramInfoLog.xml
*/
string Program::log() const {
// Make a buffer big enough to hold the log
GLint len;
glGetProgramiv(_id, GL_INFO_LOG_LENGTH, &len);
GLchar* const buf = new GLchar[len + 1];
// Put the log into the buffer
GLint num;
glGetProgramInfoLog(_id, len, &num, buf);
buf[num] = '\0';
// Make a string from the buffer and then delete it
string str(buf);
delete[] buf;
// Return the string
return str;
}
/**
* Changes which OpenGL shader program this program represents.
*
* @param program Program to copy ID from
* @return Reference to this program to support chaining
*/
Program& Program::operator=(const Program& program) {
_id = program._id;
}
/**
* Checks if another program has the same ID as this one.
*
* @param program Program to check
* @return `true` if both programs have the same ID
*/
bool Program::operator==(const Program& program) const {
return _id == program._id;
}
/**
* Checks if another program has a different ID than this one.
*
* @param program Program to check
* @return `true` if programs have different IDs
*/
bool Program::operator!=(const Program& program) const {
return _id != program._id;
}
/**
* Checks if this program's ID is less than another program's ID.
*
* @param program Program to check
* @return `true` if this program's ID is less than the other program's ID
*/
bool Program::operator<(const Program& program) const {
return _id < program._id;
}
/**
* Retrieves all the shaders attached to this program.
*
* @return Vector of all the shaders attached to this program
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetAttachedShaders.xml
*/
vector<Shader> Program::shaders() const {
// Determine how many shaders are attached
GLint len;
glGetProgramiv(_id, GL_ATTACHED_SHADERS, &len);
if (len == 0) {
return vector<Shader>();
}
// Put attached shaders into array
GLuint* const arr = new GLuint[len];
glGetAttachedShaders(_id, len, NULL, arr);
// Add them to a vector
vector<Shader> vec;
for (int i = 0; i < len; ++i) {
const Shader shader = Shader::fromId(arr[i]);
vec.push_back(shader);
}
// Delete the array
delete[] arr;
// Return the vector
return vec;
}
/**
* Determines the location of a uniform in this program.
*
* @param name Name of uniform to look up
* @return Location of the uniform in this program, or `-1` if uniform is not in this program
* @throws invalid_argument if name is empty
* @throws logic_error if program has not been linked yet
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetUniformLocation.xml
*/
GLint Program::uniformLocation(const string& name) const {
if (name.empty()) {
throw invalid_argument("[Program] Name is empty!");
} else if (!linked()) {
throw logic_error("[Program] Program not linked yet!");
}
return glGetUniformLocation(_id, name.c_str());
}
/**
* Activates this program.
*
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glUseProgram.xml
*/
void Program::use() const {
glUseProgram(_id);
}
/**
* Checks if this program is valid.
*
* @return `true` if this program is valid
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetProgram.xml
*/
bool Program::valid() const {
GLint valid;
glGetProgramiv(_id, GL_VALIDATE_STATUS, &valid);
return valid;
}
/**
* Ensures this program is valid.
*
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glValidateProgram.xml
*/
void Program::validate() const {
glValidateProgram(_id);
}
/**
* Creates a program handle from the ID of an existing OpenGL program.
*
* @param id ID of existing OpenGL program
* @return Handle for OpenGL program
* @throws invalid_argument if ID is not an OpenGL program
*/
Program Program::fromId(const GLuint id) {
return Program(id);
}
// HELPERS
/**
* Checks if a shader is attached to this program.
*
* @param shader Shader to check
* @return `true` if shader is attached
*/
bool Program::isAttached(const Shader &shader) const {
const vector<Shader> attachedShaders = shaders();
vector<Shader>::const_iterator it = attachedShaders.begin();
while (it != attachedShaders.end()) {
if ((*it) == shader) {
return true;
}
++it;
}
return false;
}
/**
* Returns the value of GL_MAX_DRAW_BUFFERS.
*/
GLint Program::getMaxDrawBuffers() {
GLint value;
glGetIntegerv(GL_MAX_DRAW_BUFFERS, &value);
return value;
}
} /* namespace Glycerin */
<commit_msg>Sorted Program::fromId method (ref #32)<commit_after>/*
* Program.cxx
*
* Author
* Andrew Brown <adb1413@rit.edu>
*/
#include "config.h"
#include <stdexcept>
#include "glycerin/Program.hxx"
using namespace std;
namespace Glycerin {
/**
* Constructs a program wrapping an existing shader program.
*
* @param id ID of existing shader program to wrap
* @throws invalid_argument if ID is not an existing OpenGL shader program
*/
Program::Program(GLuint id) : _id(id) {
if (!glIsProgram(_id)) {
throw invalid_argument("[Program] ID not an existing OpenGL shader program!");
}
}
/**
* Destroys this program handle, leaving the underlying OpenGL shader program unaffected.
*
* @see @ref dispose
*/
Program::~Program() {
// empty
}
/**
* Constructs a program by copying another program.
*
* @param program Program to copy
*/
Program::Program(const Program& program) : _id(program._id) {
// pass
}
/**
* Retrieves all the active attributes in this program.
*
* @return Mapping of all the active attributes in this program by name
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetActiveAttrib.xml
*/
map<string,Attribute> Program::activeAttributes() const {
// Get number of active attributes
GLint num;
glGetProgramiv(_id, GL_ACTIVE_ATTRIBUTES, &num);
if (num == 0) {
return map<string,Attribute>();
}
// Make a buffer to hold name of an attribute
GLint len;
glGetProgramiv(_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &len);
char* const buf = new char[len];
// Make variables to hold size and type of an attribute
GLint size;
GLenum type;
// Put active attributes into a map
map<string,Attribute> attribs;
for (int i = 0; i < num; ++i) {
glGetActiveAttrib(_id, i, len, NULL, &size, &type, buf);
const GLint location = glGetAttribLocation(_id, buf);
const string name = buf;
const Attribute attrib(location, name, _id, size, type);
attribs.insert(pair<string,Attribute>(name, attrib));
}
// Delete the buffer
delete[] buf;
// Return the vector
return attribs;
}
/**
* Retrieves all the active uniforms in this program.
*
* @return Mapping of all the active uniforms in this program by name
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetActiveUniform.xml
*/
map<string,Uniform> Program::activeUniforms() const {
// Get number of active uniforms
GLint num;
glGetProgramiv(_id, GL_ACTIVE_UNIFORMS, &num);
if (num == 0) {
return map<string,Uniform>();
}
// Make a buffer to hold name of a uniform
GLint len;
glGetProgramiv(_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &len);
char* const buf = new char[len];
// Make variables to hold size and type of a uniform
GLint size;
GLenum type;
// Put active uniforms into a map
map<string,Uniform> uniforms;
for (int i = 0; i < num; ++i) {
glGetActiveUniform(_id, i, len, NULL, &size, &type, buf);
const GLint location = glGetUniformLocation(_id, buf);
const string name = buf;
const Uniform uniform(location, name, _id, size, type);
uniforms.insert(pair<string,Uniform>(name, uniform));
}
// Delete the buffer
delete[] buf;
// Return the vector
return uniforms;
}
/**
* Attaches a shader to this program.
*
* @param shader OpenGL identifier for the shader to attach
* @throw invalid_argument if shader is not valid
* @throw logic_error if shader is already attached
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glAttachShader.xml
*/
void Program::attachShader(GLuint shader) const {
attachShader(Shader::fromId(shader));
}
/**
* Attaches a shader to this program.
*
* @param shader Wrapper for an OpenGL shader
* @throw logic_error if shader is already attached
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glAttachShader.xml
*/
void Program::attachShader(const Shader &shader) const {
if (isAttached(shader)) {
throw logic_error("[Program] Shader is already attached!");
}
glAttachShader(_id, shader.id());
}
/**
* Determines the location of an attribute in this program.
*
* @param name Name of attribute to look up
* @return Location of the attribute in this program, or `-1` if attribute is not in this program
* @throws invalid_argument if name is empty
* @throws logic_error if program has not been linked yet
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetAttribLocation.xml
*/
GLint Program::attribLocation(const std::string &name) const {
if (name.empty()) {
throw invalid_argument("[Program] Name is empty!");
} else if (!linked()) {
throw logic_error("[Program] Program not linked yet!");
}
return glGetAttribLocation(_id, name.c_str());
}
/**
* Binds an attribute to a specific location.
*
* @param name Name of attribute
* @param location Location to bind to
* @throw invalid_argument if name is empty
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glBindAttribLocation.xml
*/
void Program::attribLocation(const std::string& name, GLuint location) const {
if (name.empty()) {
throw invalid_argument("[Program] Name is empty!");
}
glBindAttribLocation(_id, location, name.c_str());
}
/**
* Creates a new program.
*
* @return New program instance
* @throws runtime_error if program could not be created
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glCreateProgram.xml
*/
Program Program::create() {
// Create an ID
const GLuint id = glCreateProgram();
if (id == 0) {
throw runtime_error("[Program] Could not create program!");
}
// Make the program
return Program(id);
}
/**
* Detaches a shader from this program.
*
* @param shader Shader to detach
* @throws invalid_argument if shader is not a valid shader
* @throws logic_error if shader is not already attached
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glDetachShader.xml
*/
void Program::detachShader(GLuint shader) const {
detachShader(Shader::fromId(shader));
}
/**
* Detaches a shader from this program.
*
* @param shader Shader to detach
* @throws logic_error if shader is not already attached
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glDetachShader.xml
*/
void Program::detachShader(const Shader &shader) const {
if (!isAttached(shader)) {
throw logic_error("[Program] Shader not already attached!");
}
glDetachShader(_id, shader.id());
}
/**
* Deletes the underlying OpenGL shader program.
*
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glDeleteProgram.xml
*/
void Program::dispose() const {
glDeleteProgram(_id);
}
/**
* Determines the location of an output variable in this program.
*
* @param name Name of output variable to look up
* @return Location of output variable, or `-1` if name is not an active output variable
* @throws invalid_argument if name is empty
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetFragDataLocation.xml
*/
GLint Program::fragDataLocation(const std::string& name) const {
if (name.empty()) {
throw invalid_argument("[Program] Name is empty!");
}
return glGetFragDataLocation(_id, name.c_str());
}
/**
* Binds a fragment shader output variable to a location.
*
* @param name Name of output variable to bind
* @param location Location of draw buffer to bind to
* @throws invalid_argument if name is empty or starts with `gl_`
* @throws invalid_argument if location greater than `GL_MAX_DRAW_BUFFERS`
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glBindFragDataLocation.xml
*/
void Program::fragDataLocation(const std::string &name, GLuint location) const {
if (name.empty()) {
throw invalid_argument("[Program] Name is empty!");
} else if (name.find("gl_") == 0) {
throw invalid_argument("[Program] Name starts with 'gl_'!");
} else if (location > getMaxDrawBuffers()) {
throw invalid_argument("[Program] Location greater than GL_MAX_DRAW_BUFFERS!");
}
glBindFragDataLocation(_id, location, name.c_str());
}
/**
* Creates a program handle from the ID of an existing OpenGL program.
*
* @param id ID of existing OpenGL program
* @return Handle for OpenGL program
* @throws invalid_argument if ID is not an OpenGL program
*/
Program Program::fromId(const GLuint id) {
return Program(id);
}
/**
* Determines the ID of the underlying OpenGL shader program this program handle represents.
*
* @return ID of the underlying OpenGL shader program this program handle represents
*/
GLuint Program::id() const {
return _id;
}
/**
* Links this program.
*
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glLinkProgram.xml
*/
void Program::link() const {
glLinkProgram(_id);
}
/**
* Checks if this program is linked.
*
* @return `true` if this program is linked
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetProgram.xml
*/
bool Program::linked() const {
GLint linked;
glGetProgramiv(_id, GL_LINK_STATUS, &linked);
return linked;
}
/**
* Retrieves a copy of this program's log.
*
* @return Copy of this program's log
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetProgramInfoLog.xml
*/
string Program::log() const {
// Make a buffer big enough to hold the log
GLint len;
glGetProgramiv(_id, GL_INFO_LOG_LENGTH, &len);
GLchar* const buf = new GLchar[len + 1];
// Put the log into the buffer
GLint num;
glGetProgramInfoLog(_id, len, &num, buf);
buf[num] = '\0';
// Make a string from the buffer and then delete it
string str(buf);
delete[] buf;
// Return the string
return str;
}
/**
* Changes which OpenGL shader program this program represents.
*
* @param program Program to copy ID from
* @return Reference to this program to support chaining
*/
Program& Program::operator=(const Program& program) {
_id = program._id;
}
/**
* Checks if another program has the same ID as this one.
*
* @param program Program to check
* @return `true` if both programs have the same ID
*/
bool Program::operator==(const Program& program) const {
return _id == program._id;
}
/**
* Checks if another program has a different ID than this one.
*
* @param program Program to check
* @return `true` if programs have different IDs
*/
bool Program::operator!=(const Program& program) const {
return _id != program._id;
}
/**
* Checks if this program's ID is less than another program's ID.
*
* @param program Program to check
* @return `true` if this program's ID is less than the other program's ID
*/
bool Program::operator<(const Program& program) const {
return _id < program._id;
}
/**
* Retrieves all the shaders attached to this program.
*
* @return Vector of all the shaders attached to this program
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetAttachedShaders.xml
*/
vector<Shader> Program::shaders() const {
// Determine how many shaders are attached
GLint len;
glGetProgramiv(_id, GL_ATTACHED_SHADERS, &len);
if (len == 0) {
return vector<Shader>();
}
// Put attached shaders into array
GLuint* const arr = new GLuint[len];
glGetAttachedShaders(_id, len, NULL, arr);
// Add them to a vector
vector<Shader> vec;
for (int i = 0; i < len; ++i) {
const Shader shader = Shader::fromId(arr[i]);
vec.push_back(shader);
}
// Delete the array
delete[] arr;
// Return the vector
return vec;
}
/**
* Determines the location of a uniform in this program.
*
* @param name Name of uniform to look up
* @return Location of the uniform in this program, or `-1` if uniform is not in this program
* @throws invalid_argument if name is empty
* @throws logic_error if program has not been linked yet
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetUniformLocation.xml
*/
GLint Program::uniformLocation(const string& name) const {
if (name.empty()) {
throw invalid_argument("[Program] Name is empty!");
} else if (!linked()) {
throw logic_error("[Program] Program not linked yet!");
}
return glGetUniformLocation(_id, name.c_str());
}
/**
* Activates this program.
*
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glUseProgram.xml
*/
void Program::use() const {
glUseProgram(_id);
}
/**
* Checks if this program is valid.
*
* @return `true` if this program is valid
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glGetProgram.xml
*/
bool Program::valid() const {
GLint valid;
glGetProgramiv(_id, GL_VALIDATE_STATUS, &valid);
return valid;
}
/**
* Ensures this program is valid.
*
* @see http://www.opengl.org/sdk/docs/man3/xhtml/glValidateProgram.xml
*/
void Program::validate() const {
glValidateProgram(_id);
}
// HELPERS
/**
* Checks if a shader is attached to this program.
*
* @param shader Shader to check
* @return `true` if shader is attached
*/
bool Program::isAttached(const Shader &shader) const {
const vector<Shader> attachedShaders = shaders();
vector<Shader>::const_iterator it = attachedShaders.begin();
while (it != attachedShaders.end()) {
if ((*it) == shader) {
return true;
}
++it;
}
return false;
}
/**
* Returns the value of GL_MAX_DRAW_BUFFERS.
*/
GLint Program::getMaxDrawBuffers() {
GLint value;
glGetIntegerv(GL_MAX_DRAW_BUFFERS, &value);
return value;
}
} /* namespace Glycerin */
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <osg/NodeVisitor>
#include <osg/Billboard>
#include <osg/ClearNode>
#include <osg/ClipNode>
#include <osg/CoordinateSystemNode>
#include <osg/Geode>
#include <osg/Group>
#include <osg/LightSource>
#include <osg/LOD>
#include <osg/MatrixTransform>
#include <osg/OccluderNode>
#include <osg/OcclusionQueryNode>
#include <osg/PagedLOD>
#include <osg/PositionAttitudeTransform>
#include <osg/Projection>
#include <osg/ProxyNode>
#include <osg/Sequence>
#include <osg/Switch>
#include <osg/TexGenNode>
#include <osg/Transform>
#include <osg/Camera>
#include <osg/CameraView>
#include <osg/Geometry>
#include <stdlib.h>
using namespace osg;
NodeVisitor::NodeVisitor(TraversalMode tm):
Object(true)
{
_visitorType = NODE_VISITOR;
_traversalNumber = osg::UNINITIALIZED_FRAME_NUMBER;
_traversalMode = tm;
_traversalMask = 0xffffffff;
_nodeMaskOverride = 0x0;
}
NodeVisitor::NodeVisitor(VisitorType type,TraversalMode tm):
Object(true)
{
_visitorType = type;
_traversalNumber = osg::UNINITIALIZED_FRAME_NUMBER;
_traversalMode = tm;
_traversalMask = 0xffffffff;
_nodeMaskOverride = 0x0;
}
NodeVisitor::NodeVisitor(const NodeVisitor& nv, const osg::CopyOp& copyop):
Object(nv, copyop),
_visitorType(nv._visitorType),
_traversalNumber(nv._traversalNumber),
_traversalMode(nv._traversalMode),
_traversalMask(nv._traversalMask),
_nodeMaskOverride(nv._nodeMaskOverride)
{
}
NodeVisitor::~NodeVisitor()
{
// if (_traversalVisitor) detach from _traversalVisitor;
}
void NodeVisitor::apply(Drawable& drawable)
{
// It all ends here...
}
void NodeVisitor::apply(Geometry& drawable)
{
apply(static_cast<Drawable&>(drawable));
}
void NodeVisitor::apply(Node& node)
{
traverse(node);
}
void NodeVisitor::apply(Geode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(Billboard& node)
{
apply(static_cast<Geode&>(node));
}
void NodeVisitor::apply(Group& node)
{
apply(static_cast<Node&>(node));
}
void NodeVisitor::apply(ProxyNode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(Projection& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(CoordinateSystemNode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(ClipNode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(TexGenNode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(LightSource& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(Transform& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(Camera& node)
{
apply(static_cast<Transform&>(node));
}
void NodeVisitor::apply(CameraView& node)
{
apply(static_cast<Transform&>(node));
}
void NodeVisitor::apply(MatrixTransform& node)
{
apply(static_cast<Transform&>(node));
}
void NodeVisitor::apply(PositionAttitudeTransform& node)
{
apply(static_cast<Transform&>(node));
}
void NodeVisitor::apply(Switch& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(Sequence& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(LOD& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(PagedLOD& node)
{
apply(static_cast<LOD&>(node));
}
void NodeVisitor::apply(ClearNode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(OccluderNode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(OcclusionQueryNode& node)
{
apply(static_cast<Group&>(node));
}
<commit_msg>Changed the NodeVisitor::apply(Drawable&) to call apply(Node&)<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <osg/NodeVisitor>
#include <osg/Billboard>
#include <osg/ClearNode>
#include <osg/ClipNode>
#include <osg/CoordinateSystemNode>
#include <osg/Geode>
#include <osg/Group>
#include <osg/LightSource>
#include <osg/LOD>
#include <osg/MatrixTransform>
#include <osg/OccluderNode>
#include <osg/OcclusionQueryNode>
#include <osg/PagedLOD>
#include <osg/PositionAttitudeTransform>
#include <osg/Projection>
#include <osg/ProxyNode>
#include <osg/Sequence>
#include <osg/Switch>
#include <osg/TexGenNode>
#include <osg/Transform>
#include <osg/Camera>
#include <osg/CameraView>
#include <osg/Geometry>
#include <stdlib.h>
using namespace osg;
NodeVisitor::NodeVisitor(TraversalMode tm):
Object(true)
{
_visitorType = NODE_VISITOR;
_traversalNumber = osg::UNINITIALIZED_FRAME_NUMBER;
_traversalMode = tm;
_traversalMask = 0xffffffff;
_nodeMaskOverride = 0x0;
}
NodeVisitor::NodeVisitor(VisitorType type,TraversalMode tm):
Object(true)
{
_visitorType = type;
_traversalNumber = osg::UNINITIALIZED_FRAME_NUMBER;
_traversalMode = tm;
_traversalMask = 0xffffffff;
_nodeMaskOverride = 0x0;
}
NodeVisitor::NodeVisitor(const NodeVisitor& nv, const osg::CopyOp& copyop):
Object(nv, copyop),
_visitorType(nv._visitorType),
_traversalNumber(nv._traversalNumber),
_traversalMode(nv._traversalMode),
_traversalMask(nv._traversalMask),
_nodeMaskOverride(nv._nodeMaskOverride)
{
}
NodeVisitor::~NodeVisitor()
{
// if (_traversalVisitor) detach from _traversalVisitor;
}
void NodeVisitor::apply(Node& node)
{
traverse(node);
}
void NodeVisitor::apply(Drawable& drawable)
{
apply(static_cast<Node&>(drawable));
}
void NodeVisitor::apply(Geometry& drawable)
{
apply(static_cast<Drawable&>(drawable));
}
void NodeVisitor::apply(Geode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(Billboard& node)
{
apply(static_cast<Geode&>(node));
}
void NodeVisitor::apply(Group& node)
{
apply(static_cast<Node&>(node));
}
void NodeVisitor::apply(ProxyNode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(Projection& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(CoordinateSystemNode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(ClipNode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(TexGenNode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(LightSource& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(Transform& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(Camera& node)
{
apply(static_cast<Transform&>(node));
}
void NodeVisitor::apply(CameraView& node)
{
apply(static_cast<Transform&>(node));
}
void NodeVisitor::apply(MatrixTransform& node)
{
apply(static_cast<Transform&>(node));
}
void NodeVisitor::apply(PositionAttitudeTransform& node)
{
apply(static_cast<Transform&>(node));
}
void NodeVisitor::apply(Switch& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(Sequence& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(LOD& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(PagedLOD& node)
{
apply(static_cast<LOD&>(node));
}
void NodeVisitor::apply(ClearNode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(OccluderNode& node)
{
apply(static_cast<Group&>(node));
}
void NodeVisitor::apply(OcclusionQueryNode& node)
{
apply(static_cast<Group&>(node));
}
<|endoftext|> |
<commit_before>/* GNE - Game Networking Engine, a portable multithreaded networking library.
* Copyright (C) 2001 Jason Winnebeck (gillius@webzone.net)
* Project website: http://www.rit.edu/~jpw9607/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "gneintern.h"
#include "Timer.h"
#include "Time.h"
#include "TimerCallback.h"
//##ModelId=3AE868370122
Timer::Timer(TimerCallback* callback, int rate)
: running(false), callbackRate(rate), listener(callback) {
}
//##ModelId=3AE8686C00BE
Timer::~Timer() {
stopTimer();
delete(listener);
}
/**
* \todo write UNIX version
*/
//##ModelId=3AE86872030C
Time Timer::getCurrentTime() {
Time ret;
#ifdef WIN32
LARGE_INTEGER t, freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&t);
ret.setSec(int(t.QuadPart / freq.QuadPart));
ret.setuSec(int((t.QuadPart % freq.QuadPart) * 1000000 / freq.QuadPart));
#else
#error Need to port Timer::getCurrentTime()
#endif
return ret;
}
/**
* \todo write UNIX version
*/
//##ModelId=3AF4797001CC
Time Timer::getAbsoluteTime() {
Time ret;
#ifdef WIN32
_timeb t;
_ftime(&t);
ret.setSec(t.time);
ret.setuSec(t.millitm * 1000);
#else
#error Need to port Timer::getAbsoluteTime()
#endif
return ret;
}
//##ModelId=3AEB9AB50050
void Timer::startTimer() {
assert(running == false);
nextTime = getCurrentTime();
nextTime.setuSec(nextTime.getuSec() + callbackRate * 1000);
running = true;
start();
}
//##ModelId=3AEB9AB500BE
void Timer::stopTimer() {
if (running) {
running = false;
join();
}
}
/**
* \todo enable sleeping.
*/
//##ModelId=3AE868A30294
void Timer::run() {
while (running) {
while (nextTime > getCurrentTime()) {}
listener->timerCallback();
nextTime.setuSec(nextTime.getuSec() + callbackRate * 1000);
}
}
//##ModelId=3AED05E7029E
bool Timer::isRunning() {
return running;
}
<commit_msg>Optimized the timer's run function.<commit_after>/* GNE - Game Networking Engine, a portable multithreaded networking library.
* Copyright (C) 2001 Jason Winnebeck (gillius@webzone.net)
* Project website: http://www.rit.edu/~jpw9607/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "gneintern.h"
#include "Timer.h"
#include "Time.h"
#include "TimerCallback.h"
//##ModelId=3AE868370122
Timer::Timer(TimerCallback* callback, int rate)
: running(false), callbackRate(rate), listener(callback) {
}
//##ModelId=3AE8686C00BE
Timer::~Timer() {
stopTimer();
delete(listener);
}
/**
* \todo write UNIX version
*/
//##ModelId=3AE86872030C
Time Timer::getCurrentTime() {
Time ret;
#ifdef WIN32
LARGE_INTEGER t, freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&t);
ret.setSec(int(t.QuadPart / freq.QuadPart));
ret.setuSec(int((t.QuadPart % freq.QuadPart) * 1000000 / freq.QuadPart));
#else
#error Need to port Timer::getCurrentTime()
#endif
return ret;
}
/**
* \todo write UNIX version
*/
//##ModelId=3AF4797001CC
Time Timer::getAbsoluteTime() {
Time ret;
#ifdef WIN32
_timeb t;
_ftime(&t);
ret.setSec(t.time);
ret.setuSec(t.millitm * 1000);
#else
#error Need to port Timer::getAbsoluteTime()
#endif
return ret;
}
//##ModelId=3AEB9AB50050
void Timer::startTimer() {
assert(running == false);
nextTime = getCurrentTime();
nextTime += callbackRate * 1000;
running = true;
start();
}
//##ModelId=3AEB9AB500BE
void Timer::stopTimer() {
if (running) {
running = false;
join();
}
}
/**
* \todo enable sleeping.
*/
//##ModelId=3AE868A30294
void Timer::run() {
while (running) {
Time currTime, sleepTime;
currTime = getCurrentTime();
while (nextTime > currTime) {
sleepTime = nextTime - currTime;
Thread::sleep(sleepTime.getTotaluSec() / 1000);
currTime = getCurrentTime();
}
listener->timerCallback();
nextTime += callbackRate * 1000;
}
}
//##ModelId=3AED05E7029E
bool Timer::isRunning() {
return running;
}
<|endoftext|> |
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004 - 2008 Olof Naessn and Per Larsson
*
*
* Per Larsson a.k.a finalman
* Olof Naessn a.k.a jansem/yakslem
*
* Visit: http://guichan.sourceforge.net
*
* License: (BSD)
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Guichan 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/widgets/listbox.hpp"
#include "guichan/basiccontainer.hpp"
#include "guichan/font.hpp"
#include "guichan/graphics.hpp"
#include "guichan/key.hpp"
#include "guichan/listmodel.hpp"
#include "guichan/mouseinput.hpp"
#include "guichan/selectionlistener.hpp"
namespace gcn
{
ListBox::ListBox()
: mSelected(-1),
mListModel(NULL),
mWrappingEnabled(false)
{
setWidth(100);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
ListBox::ListBox(ListModel *listModel)
: mSelected(-1),
mWrappingEnabled(false)
{
setWidth(100);
setListModel(listModel);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
void ListBox::draw(Graphics* graphics)
{
graphics->setColor(getBackgroundColor());
graphics->fillRectangle(Rectangle(0, 0, getWidth(), getHeight()));
if (mListModel == NULL)
{
return;
}
graphics->setColor(getForegroundColor());
graphics->setFont(getFont());
// Check the current clip area so we don't draw unnecessary items
// that are not visible.
const ClipRectangle currentClipArea = graphics->getCurrentClipArea();
int fontHeight = getFont()->getHeight();
int i = currentClipArea.y / getFont()->getHeight();
int end = (currentClipArea.y + currentClipArea.height) / getFont()->getHeight();
if (end > mListModel->getNumberOfElements())
{
end = mListModel->getNumberOfElements();
}
int y = 0;
for (i = 0; i < end; ++i)
{
if (i == mSelected)
{
graphics->setColor(getSelectionColor());
graphics->fillRectangle(Rectangle(0, y, getWidth(), fontHeight));
graphics->setColor(getForegroundColor());
}
graphics->drawText(mListModel->getElementAt(i), 1, y);
y += fontHeight;
}
}
void ListBox::logic()
{
adjustSize();
}
int ListBox::getSelected() const
{
return mSelected;
}
void ListBox::setSelected(int selected)
{
if (mListModel == NULL)
{
mSelected = -1;
}
else
{
if (selected < 0)
{
mSelected = -1;
}
else if (selected >= mListModel->getNumberOfElements())
{
mSelected = mListModel->getNumberOfElements() - 1;
}
else
{
mSelected = selected;
}
Rectangle scroll;
if (mSelected < 0)
{
scroll.y = 0;
}
else
{
scroll.y = getFont()->getHeight() * mSelected;
}
scroll.height = getFont()->getHeight();
showPart(scroll);
}
distributeValueChangedEvent();
}
void ListBox::keyPressed(KeyEvent& keyEvent)
{
Key key = keyEvent.getKey();
if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE)
{
distributeActionEvent();
keyEvent.consume();
}
else if (key.getValue() == Key::UP)
{
setSelected(mSelected - 1);
if (mSelected == -1)
{
if (mWrappingEnabled)
{
setSelected(getListModel()->getNumberOfElements() - 1);
}
else
{
setSelected(0);
}
}
keyEvent.consume();
}
else if (key.getValue() == Key::DOWN)
{
if (mWrappingEnabled
&& getSelected() == getListModel()->getNumberOfElements() - 1)
{
setSelected(0);
}
else
{
setSelected(getSelected() + 1);
}
keyEvent.consume();
}
else if (key.getValue() == Key::HOME)
{
setSelected(0);
keyEvent.consume();
}
else if (key.getValue() == Key::END)
{
setSelected(getListModel()->getNumberOfElements() - 1);
keyEvent.consume();
}
}
void ListBox::mousePressed(MouseEvent& mouseEvent)
{
if (mouseEvent.getButton() == MouseEvent::LEFT)
{
setSelected(mouseEvent.getY() / getFont()->getHeight());
distributeActionEvent();
}
}
void ListBox::mouseWheelMovedUp(MouseEvent& mouseEvent)
{
if (isFocused())
{
if (getSelected() > 0 )
{
setSelected(getSelected() - 1);
}
mouseEvent.consume();
}
}
void ListBox::mouseWheelMovedDown(MouseEvent& mouseEvent)
{
if (isFocused())
{
setSelected(getSelected() + 1);
mouseEvent.consume();
}
}
void ListBox::mouseDragged(MouseEvent& mouseEvent)
{
mouseEvent.consume();
}
void ListBox::setListModel(ListModel *listModel)
{
mSelected = -1;
mListModel = listModel;
adjustSize();
}
ListModel* ListBox::getListModel()
{
return mListModel;
}
void ListBox::adjustSize()
{
if (mListModel != NULL)
{
setHeight(getFont()->getHeight() * mListModel->getNumberOfElements());
}
}
bool ListBox::isWrappingEnabled() const
{
return mWrappingEnabled;
}
void ListBox::setWrappingEnabled(bool wrappingEnabled)
{
mWrappingEnabled = wrappingEnabled;
}
void ListBox::addSelectionListener(SelectionListener* selectionListener)
{
mSelectionListeners.push_back(selectionListener);
}
void ListBox::removeSelectionListener(SelectionListener* selectionListener)
{
mSelectionListeners.remove(selectionListener);
}
void ListBox::distributeValueChangedEvent()
{
SelectionListenerIterator iter;
for (iter = mSelectionListeners.begin(); iter != mSelectionListeners.end(); ++iter)
{
SelectionEvent event(this);
(*iter)->valueChanged(event);
}
}
}
<commit_msg>A bug has been fixed where a list box didn't draw its elements correctly when having a negative y coordinate value due to an incorrect optimization.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004 - 2008 Olof Naessn and Per Larsson
*
*
* Per Larsson a.k.a finalman
* Olof Naessn a.k.a jansem/yakslem
*
* Visit: http://guichan.sourceforge.net
*
* License: (BSD)
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Guichan 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/widgets/listbox.hpp"
#include "guichan/basiccontainer.hpp"
#include "guichan/font.hpp"
#include "guichan/graphics.hpp"
#include "guichan/key.hpp"
#include "guichan/listmodel.hpp"
#include "guichan/mouseinput.hpp"
#include "guichan/selectionlistener.hpp"
namespace gcn
{
ListBox::ListBox()
: mSelected(-1),
mListModel(NULL),
mWrappingEnabled(false)
{
setWidth(100);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
ListBox::ListBox(ListModel *listModel)
: mSelected(-1),
mWrappingEnabled(false)
{
setWidth(100);
setListModel(listModel);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
void ListBox::draw(Graphics* graphics)
{
graphics->setColor(getBackgroundColor());
graphics->fillRectangle(Rectangle(0, 0, getWidth(), getHeight()));
if (mListModel == NULL)
{
return;
}
graphics->setColor(getForegroundColor());
graphics->setFont(getFont());
// Check the current clip area so we don't draw unnecessary items
// that are not visible.
const ClipRectangle currentClipArea = graphics->getCurrentClipArea();
int fontHeight = getFont()->getHeight();
// Calculate the number of rows to draw by checking the clip area.
// The addition of two makes covers a partial visible row at the top
// and a partial visible row at the bottom.
int numberOfRows = currentClipArea.height / fontHeight + 2;
if (numberOfRows > mListModel->getNumberOfElements())
{
numberOfRows = mListModel->getNumberOfElements();
}
// Calculate which row to start drawing. If the list box
// has a negative y coordinate value we should check if
// we should drop rows in the begining of the list as
// they might not be visible. A negative y value is very
// common if the list box for instance resides in a scroll
// area and the user has scrolled the list box downwards.
int startRow;
if (getY() < 0)
{
startRow = -1 * (getY() / fontHeight);
}
else
{
startRow = 0;
}
int i;
// The y coordinate where we start to draw the text is
// simply the y coordinate multiplied with the font height.
int y = fontHeight * startRow;
for (i = startRow; i < startRow + numberOfRows; ++i)
{
if (i == mSelected)
{
graphics->setColor(getSelectionColor());
graphics->fillRectangle(Rectangle(0, y, getWidth(), fontHeight));
graphics->setColor(getForegroundColor());
}
graphics->drawText(mListModel->getElementAt(i), 1, y);
y += fontHeight;
}
}
void ListBox::logic()
{
adjustSize();
}
int ListBox::getSelected() const
{
return mSelected;
}
void ListBox::setSelected(int selected)
{
if (mListModel == NULL)
{
mSelected = -1;
}
else
{
if (selected < 0)
{
mSelected = -1;
}
else if (selected >= mListModel->getNumberOfElements())
{
mSelected = mListModel->getNumberOfElements() - 1;
}
else
{
mSelected = selected;
}
Rectangle scroll;
if (mSelected < 0)
{
scroll.y = 0;
}
else
{
scroll.y = getFont()->getHeight() * mSelected;
}
scroll.height = getFont()->getHeight();
showPart(scroll);
}
distributeValueChangedEvent();
}
void ListBox::keyPressed(KeyEvent& keyEvent)
{
Key key = keyEvent.getKey();
if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE)
{
distributeActionEvent();
keyEvent.consume();
}
else if (key.getValue() == Key::UP)
{
setSelected(mSelected - 1);
if (mSelected == -1)
{
if (mWrappingEnabled)
{
setSelected(getListModel()->getNumberOfElements() - 1);
}
else
{
setSelected(0);
}
}
keyEvent.consume();
}
else if (key.getValue() == Key::DOWN)
{
if (mWrappingEnabled
&& getSelected() == getListModel()->getNumberOfElements() - 1)
{
setSelected(0);
}
else
{
setSelected(getSelected() + 1);
}
keyEvent.consume();
}
else if (key.getValue() == Key::HOME)
{
setSelected(0);
keyEvent.consume();
}
else if (key.getValue() == Key::END)
{
setSelected(getListModel()->getNumberOfElements() - 1);
keyEvent.consume();
}
}
void ListBox::mousePressed(MouseEvent& mouseEvent)
{
if (mouseEvent.getButton() == MouseEvent::LEFT)
{
setSelected(mouseEvent.getY() / getFont()->getHeight());
distributeActionEvent();
}
}
void ListBox::mouseWheelMovedUp(MouseEvent& mouseEvent)
{
if (isFocused())
{
if (getSelected() > 0 )
{
setSelected(getSelected() - 1);
}
mouseEvent.consume();
}
}
void ListBox::mouseWheelMovedDown(MouseEvent& mouseEvent)
{
if (isFocused())
{
setSelected(getSelected() + 1);
mouseEvent.consume();
}
}
void ListBox::mouseDragged(MouseEvent& mouseEvent)
{
mouseEvent.consume();
}
void ListBox::setListModel(ListModel *listModel)
{
mSelected = -1;
mListModel = listModel;
adjustSize();
}
ListModel* ListBox::getListModel()
{
return mListModel;
}
void ListBox::adjustSize()
{
if (mListModel != NULL)
{
setHeight(getFont()->getHeight() * mListModel->getNumberOfElements());
}
}
bool ListBox::isWrappingEnabled() const
{
return mWrappingEnabled;
}
void ListBox::setWrappingEnabled(bool wrappingEnabled)
{
mWrappingEnabled = wrappingEnabled;
}
void ListBox::addSelectionListener(SelectionListener* selectionListener)
{
mSelectionListeners.push_back(selectionListener);
}
void ListBox::removeSelectionListener(SelectionListener* selectionListener)
{
mSelectionListeners.remove(selectionListener);
}
void ListBox::distributeValueChangedEvent()
{
SelectionListenerIterator iter;
for (iter = mSelectionListeners.begin(); iter != mSelectionListeners.end(); ++iter)
{
SelectionEvent event(this);
(*iter)->valueChanged(event);
}
}
}
<|endoftext|> |
<commit_before>//
// Created by dar on 2/15/16.
//
#include <gui/GuiButton.h>
#include <gui/GuiText.h>
#include "MainMenu.h"
#include "Game.h"
#include <string>
#include <InputManager.h>
#include <logging.h>
#ifndef __ANDROID__
#include <SDL_keyboard.h>
#endif //__ANDROID__
MainMenu::MainMenu(std::function<bool(Window *window)> switchWindow) : Window(switchWindow) {
GuiButton *b = new GuiButton("Play", GUI_MIDDLE_CENTER, 0, -220, 375, 125, new int[2]{3, 11}, 2);
auto moveController = [=](const TouchPoint *const p) {
if (p->state == 1) {
if (b->canBeClicked(p)) {
this->switchWindow(new Game(switchWindow));
}
return false;
}
return true;
};
b->setOnClickListener(moveController);
this->guiElements.push_back(b);
b = new GuiButton("Settings", GUI_MIDDLE_CENTER, 0, -80, 375, 125, new int[2]{3, 11}, 2);
this->guiElements.push_back(b);
b = new GuiButton("About", GUI_MIDDLE_CENTER, 0, 60, 375, 125, new int[2]{3, 11}, 2);
this->guiElements.push_back(b);
b = new GuiButton("Exit", GUI_MIDDLE_CENTER, 0, 200, 375, 125, new int[2]{3, 11}, 2);
this->guiElements.push_back(b);
GuiText *t = new GuiText(std::string("Dev Build: ") + __DATE__ + " " + __TIME__, 15, 15, GUI_BOTTOM_LEFT, 32, 0, 0);
this->guiElements.push_back(t);
}
void MainMenu::reload(unsigned int windowWidth, unsigned int windowHeight) {
for (GuiElement *e : this->guiElements) {
e->reinit(windowWidth, windowHeight);
}
}
void MainMenu::tick(double deltaTime) {
}
void MainMenu::handleKeyboard(const Keypress *const keypress) {
//nothing
}
void MainMenu::handleClick(const TouchPoint *const p) {
bool clicked = false;
for (GuiElement *e : this->guiElements) {
if (GuiButton *b = dynamic_cast<GuiButton *>(e)) {
if (b->canBeClicked(p)) {
if (p->state == 1) this->resetButtons(p, b);
if ((p->state == 0 && (!b->isPressed()) || b->getTouchedBy() == p->id) ||
(b->getTouchedBy() == p->id && p->state == 2)) {
if (b->onClick(p)) {
clicked = true;
break;
}
}
}
}
}
if (!clicked) {
if (p->state == 1) {
this->resetButtons(p, nullptr);
}
}
}
MainMenu::~MainMenu() {
}
void MainMenu::resetButtons(const TouchPoint *const p, const GuiButton *const b) {
for (GuiElement *e : this->guiElements) {
if (GuiButton *b1 = dynamic_cast<GuiButton *>(e)) {
if (b1 != b) {
if (p == nullptr) {
b1->setPressed(false);
} else if (b1->getTouchedBy() == p->id) {
b1->onClick(p);
}
}
}
}
}<commit_msg>Added settings on-click event in main menu.<commit_after>//
// Created by dar on 2/15/16.
//
#include <gui/GuiButton.h>
#include <gui/GuiText.h>
#include "MainMenu.h"
#include "Game.h"
#include "Settings.h"
#include <string>
#include <InputManager.h>
#include <logging.h>
#ifndef __ANDROID__
#include <SDL_keyboard.h>
#endif //__ANDROID__
MainMenu::MainMenu(std::function<bool(Window *window)> switchWindow) : Window(switchWindow) {
GuiButton *b = new GuiButton("Play", GUI_MIDDLE_CENTER, 0, -220, 375, 125, new int[2]{3, 11}, 2);
auto playAction = [=](const TouchPoint *const p) {
if (p->state == 1) {
if (b->canBeClicked(p)) {
this->switchWindow(new Game(switchWindow));
}
return false;
}
return true;
};
b->setOnClickListener(playAction);
this->guiElements.push_back(b);
b = new GuiButton("Settings", GUI_MIDDLE_CENTER, 0, -80, 375, 125, new int[2]{3, 11}, 2);
auto settingsAction = [=](const TouchPoint *const p) {
if (p->state == 1) {
if (b->canBeClicked(p)) {
this->switchWindow(new Settings(switchWindow));
}
return false;
}
return true;
};
b->setOnClickListener(settingsAction);
this->guiElements.push_back(b);
b = new GuiButton("About", GUI_MIDDLE_CENTER, 0, 60, 375, 125, new int[2]{3, 11}, 2);
this->guiElements.push_back(b);
b = new GuiButton("Exit", GUI_MIDDLE_CENTER, 0, 200, 375, 125, new int[2]{3, 11}, 2);
this->guiElements.push_back(b);
GuiText *t = new GuiText(std::string("Dev Build: ") + __DATE__ + " " + __TIME__, 15, 15, GUI_BOTTOM_LEFT, 32, 0, 0);
this->guiElements.push_back(t);
}
void MainMenu::reload(unsigned int windowWidth, unsigned int windowHeight) {
for (GuiElement *e : this->guiElements) {
e->reinit(windowWidth, windowHeight);
}
}
void MainMenu::tick(double deltaTime) {
}
void MainMenu::handleKeyboard(const Keypress *const keypress) {
//nothing
}
void MainMenu::handleClick(const TouchPoint *const p) {
bool clicked = false;
for (GuiElement *e : this->guiElements) {
if (GuiButton *b = dynamic_cast<GuiButton *>(e)) {
if (b->canBeClicked(p)) {
if (p->state == 1) this->resetButtons(p, b);
if ((p->state == 0 && (!b->isPressed()) || b->getTouchedBy() == p->id) ||
(b->getTouchedBy() == p->id && p->state == 2)) {
if (b->onClick(p)) {
clicked = true;
break;
}
}
}
}
}
if (!clicked) {
if (p->state == 1) {
this->resetButtons(p, nullptr);
}
}
}
MainMenu::~MainMenu() {
}
void MainMenu::resetButtons(const TouchPoint *const p, const GuiButton *const b) {
for (GuiElement *e : this->guiElements) {
if (GuiButton *b1 = dynamic_cast<GuiButton *>(e)) {
if (b1 != b) {
if (p == nullptr) {
b1->setPressed(false);
} else if (b1->getTouchedBy() == p->id) {
b1->onClick(p);
}
}
}
}
}<|endoftext|> |
<commit_before>/*
* LinkBasedFileLock.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/FileLock.hpp>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <vector>
#include <core/SafeConvert.hpp>
#include <core/Algorithm.hpp>
#include <core/Thread.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <boost/foreach.hpp>
#include <boost/system/error_code.hpp>
namespace rstudio {
namespace core {
namespace {
const char * const kFileLockPrefix =
".rstudio-lock-41c29";
std::string pidString()
{
PidType pid = system::currentProcessId();
return safe_convert::numberToString((long) pid);
}
std::string makeHostName()
{
char buffer[256];
int status = ::gethostname(buffer, 255);
if (status)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
return std::string(buffer);
}
const std::string& hostName()
{
static std::string instance = makeHostName();
return instance;
}
std::string threadId()
{
std::stringstream ss;
ss << boost::this_thread::get_id();
return ss.str().substr(2);
}
std::string proxyLockFileName()
{
return std::string()
+ kFileLockPrefix
+ "-" + hostName()
+ "-" + pidString()
+ "-" + threadId();
}
bool isLockFileStale(const FilePath& lockFilePath)
{
return LinkBasedFileLock::isLockFileStale(lockFilePath);
}
} // end anonymous namespace
bool LinkBasedFileLock::isLockFileStale(const FilePath& lockFilePath)
{
double seconds = s_timeoutInterval.total_seconds();
double diff = ::difftime(::time(NULL), lockFilePath.lastWriteTime());
return diff >= seconds;
}
namespace {
void cleanStaleLockfiles(const FilePath& dir)
{
std::vector<FilePath> children;
Error error = dir.children(&children);
if (error)
LOG_ERROR(error);
BOOST_FOREACH(const FilePath& filePath, children)
{
if (boost::algorithm::starts_with(filePath.filename(), kFileLockPrefix) &&
isLockFileStale(filePath))
{
Error error = filePath.remove();
if (error)
LOG_ERROR(error);
}
}
}
class LockRegistration : boost::noncopyable
{
public:
void registerLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.insert(lockFilePath);
}
END_LOCK_MUTEX
}
void deregisterLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.erase(lockFilePath);
}
END_LOCK_MUTEX
}
void refreshLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
lockFilePath.setLastWriteTime();
}
}
END_LOCK_MUTEX
}
void clearLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
Error error = lockFilePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
registration_.clear();
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
std::set<FilePath> registration_;
};
LockRegistration& lockRegistration()
{
static LockRegistration instance;
return instance;
}
Error writeLockFile(const FilePath& lockFilePath)
{
#ifndef _WIN32
// generate proxy lockfile
FilePath proxyPath = lockFilePath.parent().complete(proxyLockFileName());
// since the proxy lockfile should be unique, it should _never_ be possible
// for a collision to be found. if that does happen, it must be a leftover
// from a previous process that crashed in this stage
if (proxyPath.exists())
{
Error error = proxyPath.remove();
if (error)
LOG_ERROR(error);
}
// write something to the file (to ensure it's created)
Error error = core::writeStringToFile(proxyPath, pidString());
if (error)
return error;
RemoveOnExitScope scope(proxyPath, ERROR_LOCATION);
// attempt to link to the desired location -- ignore return value
// and just stat our original link after, as that's a more reliable
// indicator of success on old NFS systems
::link(
proxyPath.absolutePathNative().c_str(),
lockFilePath.absolutePathNative().c_str());
struct stat info;
int errc = ::stat(proxyPath.absolutePathNative().c_str(), &info);
if (errc)
return systemError(errno, ERROR_LOCATION);
// assume that a failure here is the result of someone else
// acquiring the lock before we could
if (info.st_nlink != 2)
return fileExistsError(ERROR_LOCATION);
return Success();
#else
return systemError(boost::system::errc::function_not_supported, ERROR_LOCATION);
#endif
}
} // end anonymous namespace
struct LinkBasedFileLock::Impl
{
FilePath lockFilePath;
};
LinkBasedFileLock::LinkBasedFileLock()
: pImpl_(new Impl())
{
}
LinkBasedFileLock::~LinkBasedFileLock()
{
}
FilePath LinkBasedFileLock::lockFilePath() const
{
return pImpl_->lockFilePath;
}
bool LinkBasedFileLock::isLocked(const FilePath& lockFilePath) const
{
if (!lockFilePath.exists())
return false;
return !isLockFileStale(lockFilePath);
}
Error LinkBasedFileLock::acquire(const FilePath& lockFilePath)
{
// if the lock file exists...
if (lockFilePath.exists())
{
// ... and it's stale, it's a leftover lock from a previously
// (crashed?) process. remove it and acquire our own lock
if (isLockFileStale(lockFilePath))
{
// note that multiple processes may attempt to remove this
// file at the same time, so errors shouldn't be fatal
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
}
// ... it's not stale -- someone else has the lock, cannot proceed
else
{
return fileExistsError(ERROR_LOCATION);
}
}
// ensure the parent directory exists
Error error = lockFilePath.parent().ensureDirectory();
if (error)
return error;
// write the lock file -- this step _must_ be atomic and so only one
// competing process should be able to succeed here
error = writeLockFile(lockFilePath);
if (error)
return error;
// clean any other stale lockfiles in that directory
cleanStaleLockfiles(lockFilePath.parent());
// register our lock (for refresh)
pImpl_->lockFilePath = lockFilePath;
lockRegistration().registerLock(lockFilePath);
return Success();
}
Error LinkBasedFileLock::release()
{
const FilePath& lockFilePath = pImpl_->lockFilePath;
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
pImpl_->lockFilePath = FilePath();
lockRegistration().deregisterLock(lockFilePath);
return error;
}
void LinkBasedFileLock::refresh()
{
lockRegistration().refreshLocks();
}
void LinkBasedFileLock::cleanUp()
{
lockRegistration().clearLocks();
}
} // namespace core
} // namespace rstudio
<commit_msg>don't trim thread ID (no guarantee about hex representation)<commit_after>/*
* LinkBasedFileLock.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/FileLock.hpp>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <vector>
#include <core/SafeConvert.hpp>
#include <core/Algorithm.hpp>
#include <core/Thread.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/FilePath.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/System.hpp>
#include <boost/foreach.hpp>
#include <boost/system/error_code.hpp>
namespace rstudio {
namespace core {
namespace {
const char * const kFileLockPrefix =
".rstudio-lock-41c29";
std::string pidString()
{
PidType pid = system::currentProcessId();
return safe_convert::numberToString((long) pid);
}
std::string makeHostName()
{
char buffer[256];
int status = ::gethostname(buffer, 255);
if (status)
LOG_ERROR(systemError(errno, ERROR_LOCATION));
return std::string(buffer);
}
const std::string& hostName()
{
static std::string instance = makeHostName();
return instance;
}
std::string threadId()
{
std::stringstream ss;
ss << boost::this_thread::get_id();
return ss.str();
}
std::string proxyLockFileName()
{
return std::string()
+ kFileLockPrefix
+ "-" + hostName()
+ "-" + pidString()
+ "-" + threadId();
}
bool isLockFileStale(const FilePath& lockFilePath)
{
return LinkBasedFileLock::isLockFileStale(lockFilePath);
}
} // end anonymous namespace
bool LinkBasedFileLock::isLockFileStale(const FilePath& lockFilePath)
{
double seconds = s_timeoutInterval.total_seconds();
double diff = ::difftime(::time(NULL), lockFilePath.lastWriteTime());
return diff >= seconds;
}
namespace {
void cleanStaleLockfiles(const FilePath& dir)
{
std::vector<FilePath> children;
Error error = dir.children(&children);
if (error)
LOG_ERROR(error);
BOOST_FOREACH(const FilePath& filePath, children)
{
if (boost::algorithm::starts_with(filePath.filename(), kFileLockPrefix) &&
isLockFileStale(filePath))
{
Error error = filePath.remove();
if (error)
LOG_ERROR(error);
}
}
}
class LockRegistration : boost::noncopyable
{
public:
void registerLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.insert(lockFilePath);
}
END_LOCK_MUTEX
}
void deregisterLock(const FilePath& lockFilePath)
{
LOCK_MUTEX(mutex_)
{
registration_.erase(lockFilePath);
}
END_LOCK_MUTEX
}
void refreshLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
lockFilePath.setLastWriteTime();
}
}
END_LOCK_MUTEX
}
void clearLocks()
{
LOCK_MUTEX(mutex_)
{
BOOST_FOREACH(const FilePath& lockFilePath, registration_)
{
Error error = lockFilePath.removeIfExists();
if (error)
LOG_ERROR(error);
}
registration_.clear();
}
END_LOCK_MUTEX
}
private:
boost::mutex mutex_;
std::set<FilePath> registration_;
};
LockRegistration& lockRegistration()
{
static LockRegistration instance;
return instance;
}
Error writeLockFile(const FilePath& lockFilePath)
{
#ifndef _WIN32
// generate proxy lockfile
FilePath proxyPath = lockFilePath.parent().complete(proxyLockFileName());
// since the proxy lockfile should be unique, it should _never_ be possible
// for a collision to be found. if that does happen, it must be a leftover
// from a previous process that crashed in this stage
if (proxyPath.exists())
{
Error error = proxyPath.remove();
if (error)
LOG_ERROR(error);
}
// write something to the file (to ensure it's created)
Error error = core::writeStringToFile(proxyPath, pidString());
if (error)
return error;
RemoveOnExitScope scope(proxyPath, ERROR_LOCATION);
// attempt to link to the desired location -- ignore return value
// and just stat our original link after, as that's a more reliable
// indicator of success on old NFS systems
::link(
proxyPath.absolutePathNative().c_str(),
lockFilePath.absolutePathNative().c_str());
struct stat info;
int errc = ::stat(proxyPath.absolutePathNative().c_str(), &info);
if (errc)
return systemError(errno, ERROR_LOCATION);
// assume that a failure here is the result of someone else
// acquiring the lock before we could
if (info.st_nlink != 2)
return fileExistsError(ERROR_LOCATION);
return Success();
#else
return systemError(boost::system::errc::function_not_supported, ERROR_LOCATION);
#endif
}
} // end anonymous namespace
struct LinkBasedFileLock::Impl
{
FilePath lockFilePath;
};
LinkBasedFileLock::LinkBasedFileLock()
: pImpl_(new Impl())
{
}
LinkBasedFileLock::~LinkBasedFileLock()
{
}
FilePath LinkBasedFileLock::lockFilePath() const
{
return pImpl_->lockFilePath;
}
bool LinkBasedFileLock::isLocked(const FilePath& lockFilePath) const
{
if (!lockFilePath.exists())
return false;
return !isLockFileStale(lockFilePath);
}
Error LinkBasedFileLock::acquire(const FilePath& lockFilePath)
{
// if the lock file exists...
if (lockFilePath.exists())
{
// ... and it's stale, it's a leftover lock from a previously
// (crashed?) process. remove it and acquire our own lock
if (isLockFileStale(lockFilePath))
{
// note that multiple processes may attempt to remove this
// file at the same time, so errors shouldn't be fatal
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
}
// ... it's not stale -- someone else has the lock, cannot proceed
else
{
return fileExistsError(ERROR_LOCATION);
}
}
// ensure the parent directory exists
Error error = lockFilePath.parent().ensureDirectory();
if (error)
return error;
// write the lock file -- this step _must_ be atomic and so only one
// competing process should be able to succeed here
error = writeLockFile(lockFilePath);
if (error)
return error;
// clean any other stale lockfiles in that directory
cleanStaleLockfiles(lockFilePath.parent());
// register our lock (for refresh)
pImpl_->lockFilePath = lockFilePath;
lockRegistration().registerLock(lockFilePath);
return Success();
}
Error LinkBasedFileLock::release()
{
const FilePath& lockFilePath = pImpl_->lockFilePath;
Error error = lockFilePath.remove();
if (error)
LOG_ERROR(error);
pImpl_->lockFilePath = FilePath();
lockRegistration().deregisterLock(lockFilePath);
return error;
}
void LinkBasedFileLock::refresh()
{
lockRegistration().refreshLocks();
}
void LinkBasedFileLock::cleanUp()
{
lockRegistration().clearLocks();
}
} // namespace core
} // namespace rstudio
<|endoftext|> |
<commit_before>#include <GL/freeglut.h>
#include "MandelbrotSet.h"
#include "JuliaSet.h"
#include "Menus.h"
#define WIDTH 800
#define HEIGHT 600
MandelbrotSet* ms = new MandelbrotSet(WIDTH, HEIGHT);
JuliaSet* js = new JuliaSet(WIDTH / 2, HEIGHT);
GLint WindowID1, WindowID2;
void reshapeMandelbrot(int width, int height) {
glutReshapeWindow(WIDTH - 10, HEIGHT);
// ms->setWidth(width);
// ms->setHeight(height);
}
void reshapeJulia(int width, int height) {
glutReshapeWindow((WIDTH / 2) - 10, HEIGHT);
// js->setWidth(width);
// js->setHeight(height);
}
void displayMandelbrot() {
glClear(GL_COLOR_BUFFER_BIT);
ms->calculate();
glFlush();
}
void displayJulia() {
glClear(GL_COLOR_BUFFER_BIT);
js->calculate();
glFlush();
}
void mouseMandelbrot(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
ms->zoom(x, y);
ms->calculate();
glutPostRedisplay();
// } else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {
//
// float xMapped = js->min.r + ((js->max.r - js->min.r) / WIDTH) * x;
// float yMapped = js->min.i + ((js->max.i - js->min.i) / HEIGHT) * y;
// js->k.r = xMapped;
// js->k.i = yMapped;
// js->calculate();
// printf("This is the Julia Set for c %f", xMapped);
// printf(" + %f", yMapped);
// printf("i");
// glutSetWindow(WindowID2);
// glutPostRedisplay();
// glutSetWindow(WindowID1);
}
}
void mouseJulia(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
js->zoom(x, y);
js->calculate();
glutPostRedisplay();
}
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
// glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
// first window for Mandebrot Sets
glutInitWindowSize(WIDTH - 10, HEIGHT);
glutInitWindowPosition(50, 20);
WindowID1 = glutCreateWindow("Mandelbrot Set");
gluOrtho2D(0.0, WIDTH, 0.0, HEIGHT);
glClearColor(0.0, 0.0, 0.0, 1.0);
glutReshapeFunc(reshapeMandelbrot);
glutDisplayFunc(displayMandelbrot);
glutMouseFunc(mouseMandelbrot);
glutAttachMenu(GLUT_RIGHT_BUTTON);
createMenu();
// second Window for Julia Sets
glutInitWindowSize((WIDTH / 2) - 10, HEIGHT);
glutInitWindowPosition(900, 20);
WindowID2 = glutCreateWindow("Julia Set");
gluOrtho2D(0.0, (WIDTH / 2), 0.0, HEIGHT);
glutReshapeFunc(reshapeJulia);
glutDisplayFunc(displayJulia);
glutMouseFunc(mouseJulia);
glutMainLoop();
return EXIT_FAILURE;
}
<commit_msg>small change<commit_after>#include <GL/freeglut.h>
#include "MandelbrotSet.h"
#include "JuliaSet.h"
#include "Menus.h"
#define WIDTH 800
#define HEIGHT 600
MandelbrotSet* ms = new MandelbrotSet(WIDTH, HEIGHT);
JuliaSet* js = new JuliaSet(WIDTH / 2, HEIGHT);
GLint WindowID1, WindowID2;
void reshapeMandelbrot(int width, int height) {
glutReshapeWindow(WIDTH - 10, HEIGHT);
// ms->setWidth(width);
// ms->setHeight(height);
}
void reshapeJulia(int width, int height) {
glutReshapeWindow((WIDTH / 2) - 10, HEIGHT);
// js->setWidth(width);
// js->setHeight(height);
}
void displayMandelbrot() {
glClear(GL_COLOR_BUFFER_BIT);
ms->calculate();
glFlush();
}
void displayJulia() {
glClear(GL_COLOR_BUFFER_BIT);
js->calculate();
glFlush();
}
void mouseMandelbrot(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
ms->zoom(x, y);
ms->calculate();
glutPostRedisplay();
// } else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {
//
// float xMapped = js->min.r + ((js->max.r - js->min.r) / WIDTH) * x;
// float yMapped = js->min.i + ((js->max.i - js->min.i) / HEIGHT) * y;
// js->k.r = xMapped;
// js->k.i = yMapped;
// js->calculate();
// printf("This is the Julia Set for c %f", xMapped);
// printf(" + %f", yMapped);
// printf("i");
// glutSetWindow(WindowID2);
// glutPostRedisplay();
// glutSetWindow(WindowID1);
}
}
void mouseJulia(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
js->zoom(x, y);
js->calculate();
glutPostRedisplay();
}
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
// glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
// first window for Mandebrot Sets
glutInitWindowSize(WIDTH - 10, HEIGHT);
glutInitWindowPosition(50, 20);
WindowID1 = glutCreateWindow("Mandelbrot Set");
gluOrtho2D(0.0, WIDTH, 0.0, HEIGHT);
glClearColor(0.0, 0.0, 0.0, 1.0);
glutReshapeFunc(reshapeMandelbrot);
glutDisplayFunc(displayMandelbrot);
glutMouseFunc(mouseMandelbrot);
createMenu();
// second Window for Julia Sets
glutInitWindowSize((WIDTH / 2) - 10, HEIGHT);
glutInitWindowPosition(900, 20);
WindowID2 = glutCreateWindow("Julia Set");
gluOrtho2D(0.0, (WIDTH / 2), 0.0, HEIGHT);
glutReshapeFunc(reshapeJulia);
glutDisplayFunc(displayJulia);
glutMouseFunc(mouseJulia);
glutMainLoop();
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>/* vim: set ai et ts=4 sw=4: */
#include <HttpServer.h>
#include <PersistentStorage.h>
#include <PgsqlServer.h>
#include <TcpServer.h>
#include <atomic>
#include <iostream>
#include <map>
#include <signal.h>
#include <sstream>
#include <string>
#include <unistd.h>
#include <utility>
// TODO: support global 64-bit _rev in ::set, ::delete. Useful for snapshots,
// incremental backups and replication. Write
// a multithreaded test
// TODO: add a script that runs clang static analyzer + cppcheck
// TODO: plugable porotols, e.g. support Memcached protocol
// TODO: support rangescans
// TODO: script - run under MemorySanitizer + other kinds of sanitizers
// TODO: see `grep -r TODO ./`
// TODO: Keyspaces class
PersistentStorage storage;
static std::atomic_bool terminate_flag(false);
static void httpIndexGetHandler(const HttpRequest&, HttpResponse& resp) {
resp.setStatus(HTTP_STATUS_OK);
std::ostringstream oss;
oss << "HurmaDB is " << (terminate_flag.load() ? "terminating" : "running") << "!\n\n";
resp.setBody(oss.str());
}
static void httpKVGetHandler(const HttpRequest& req, HttpResponse& resp) {
bool found;
const std::string& key = req.getQueryMatch(0);
const std::string& value = storage.get(key, &found);
resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
resp.setBody(value);
}
static void httpKVGetRangeHandler(const HttpRequest& req, HttpResponse& resp) {
const std::string& key_from = req.getQueryMatch(0);
const std::string& key_to = req.getQueryMatch(1);
const std::string& value = storage.getRange(key_from, key_to);
resp.setStatus(HTTP_STATUS_OK);
resp.setBody(value);
}
static void httpKVPutHandler(const HttpRequest& req, HttpResponse& resp) {
const std::string& key = req.getQueryMatch(0);
const std::string& value = req.getBody();
bool ok = true;
try {
storage.set(key, value);
} catch(const std::runtime_error& e) {
// Most likely validation failed
ok = false;
}
resp.setStatus(ok ? HTTP_STATUS_OK : HTTP_STATUS_BAD_REQUEST);
}
static void httpKVDeleteHandler(const HttpRequest& req, HttpResponse& resp) {
bool found = false;
const std::string& key = req.getQueryMatch(0);
storage.del(key, &found);
resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
}
/* Required for generating code coverage report */
static void httpStopPutHandler(const HttpRequest&, HttpResponse& resp) {
terminate_flag.store(true);
resp.setStatus(HTTP_STATUS_OK);
}
int main(int argc, char** argv) {
int c;
int httpPort = 8080;
int pgsqlPort = 5332;
while((c = getopt(argc, argv, "p:h:")) != -1)
switch(c) {
case 'h':
httpPort = atoi(optarg);
break;
case 'p':
pgsqlPort = atoi(optarg);
break;
}
if(httpPort <= 0 || httpPort >= 65536) {
std::cerr << "Invalid httpPort number!" << std::endl;
return 2;
}
if(pgsqlPort <= 0 || pgsqlPort >= 65536) {
std::cerr << "Invalid pgsqlPort number!" << std::endl;
return 2;
}
HttpServer httpServer;
PgsqlServer pgsqlServer(&storage);
httpServer.addHandler(HTTP_GET, "(?i)^/$", &httpIndexGetHandler);
httpServer.addHandler(HTTP_PUT, "(?i)^/v1/_stop/?$", &httpStopPutHandler);
httpServer.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVGetHandler);
httpServer.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/([\\w-]+)/?$", &httpKVGetRangeHandler);
httpServer.addHandler(HTTP_PUT, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVPutHandler);
httpServer.addHandler(HTTP_DELETE, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVDeleteHandler);
pgsqlServer.listen("127.0.0.1", pgsqlPort);
httpServer.listen("127.0.0.1", httpPort);
while(!terminate_flag.load()) {
//Unlike POSIX accept() procedure none of these .accept methods is blocking
pgsqlServer.accept(terminate_flag);
httpServer.accept(terminate_flag);
}
return 0;
}
<commit_msg>Add TODO item<commit_after>/* vim: set ai et ts=4 sw=4: */
#include <HttpServer.h>
#include <PersistentStorage.h>
#include <PgsqlServer.h>
#include <TcpServer.h>
#include <atomic>
#include <iostream>
#include <map>
#include <signal.h>
#include <sstream>
#include <string>
#include <unistd.h>
#include <utility>
// TODO: support global 64-bit _rev in ::set, ::delete. Useful for snapshots,
// incremental backups and replication. Write
// a multithreaded test
// TODO: add a script that runs clang static analyzer + cppcheck
// TODO: plugable porotols, e.g. support Memcached protocol
// TODO: support rangescans
// TODO: script - run under MemorySanitizer + other kinds of sanitizers
// TODO: see `grep -r TODO ./`
// TODO: Keyspaces class
PersistentStorage storage;
static std::atomic_bool terminate_flag(false);
static void httpIndexGetHandler(const HttpRequest&, HttpResponse& resp) {
resp.setStatus(HTTP_STATUS_OK);
std::ostringstream oss;
oss << "HurmaDB is " << (terminate_flag.load() ? "terminating" : "running") << "!\n\n";
resp.setBody(oss.str());
}
static void httpKVGetHandler(const HttpRequest& req, HttpResponse& resp) {
bool found;
const std::string& key = req.getQueryMatch(0);
const std::string& value = storage.get(key, &found);
resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
resp.setBody(value);
}
static void httpKVGetRangeHandler(const HttpRequest& req, HttpResponse& resp) {
const std::string& key_from = req.getQueryMatch(0);
const std::string& key_to = req.getQueryMatch(1);
const std::string& value = storage.getRange(key_from, key_to);
resp.setStatus(HTTP_STATUS_OK);
resp.setBody(value);
}
static void httpKVPutHandler(const HttpRequest& req, HttpResponse& resp) {
const std::string& key = req.getQueryMatch(0);
const std::string& value = req.getBody();
bool ok = true;
try {
storage.set(key, value);
} catch(const std::runtime_error& e) {
// Most likely validation failed
ok = false;
}
resp.setStatus(ok ? HTTP_STATUS_OK : HTTP_STATUS_BAD_REQUEST);
}
static void httpKVDeleteHandler(const HttpRequest& req, HttpResponse& resp) {
bool found = false;
const std::string& key = req.getQueryMatch(0);
storage.del(key, &found);
resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
}
/* Required for generating code coverage report */
static void httpStopPutHandler(const HttpRequest&, HttpResponse& resp) {
terminate_flag.store(true);
resp.setStatus(HTTP_STATUS_OK);
}
int main(int argc, char** argv) {
int c;
int httpPort = 8080;
int pgsqlPort = 5332;
while((c = getopt(argc, argv, "p:h:")) != -1)
switch(c) {
case 'h':
httpPort = atoi(optarg);
break;
case 'p':
pgsqlPort = atoi(optarg);
break;
}
if(httpPort <= 0 || httpPort >= 65536) {
std::cerr << "Invalid httpPort number!" << std::endl;
return 2;
}
if(pgsqlPort <= 0 || pgsqlPort >= 65536) {
std::cerr << "Invalid pgsqlPort number!" << std::endl;
return 2;
}
HttpServer httpServer;
PgsqlServer pgsqlServer(&storage);
httpServer.addHandler(HTTP_GET, "(?i)^/$", &httpIndexGetHandler);
httpServer.addHandler(HTTP_PUT, "(?i)^/v1/_stop/?$", &httpStopPutHandler);
httpServer.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVGetHandler);
httpServer.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/([\\w-]+)/?$", &httpKVGetRangeHandler);
httpServer.addHandler(HTTP_PUT, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVPutHandler);
httpServer.addHandler(HTTP_DELETE, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVDeleteHandler);
pgsqlServer.listen("127.0.0.1", pgsqlPort);
httpServer.listen("127.0.0.1", httpPort);
// Unlike POSIX accept() procedure none of these .accept methods is blocking
while(!terminate_flag.load()) {
// TODO: This seems to be a bottleneck during test execution.
// Run every accept() on a separate thread to speed things up.
pgsqlServer.accept(terminate_flag);
httpServer.accept(terminate_flag);
}
return 0;
}
<|endoftext|> |
<commit_before>#include "SIO/SIOTrackerHitPlaneHandler.h"
// -- lcio headers
#include "EVENT/LCIO.h"
#include "IMPL/LCFlagImpl.h"
#include "EVENT/TrackerHitPlane.h"
#include "IOIMPL/TrackerHitPlaneIOImpl.h"
// -- sio headers
#include <sio/io_device.h>
#include <sio/version.h>
namespace SIO {
SIOTrackerHitPlaneHandler::SIOTrackerHitPlaneHandler() :
SIOObjectHandler( EVENT::LCIO::TRACKERHITPLANE ) {
/* nop */
}
//----------------------------------------------------------------------------
void SIOTrackerHitPlaneHandler::read( sio::read_device& device, EVENT::LCObject* objP, sio::version_type vers ) {
auto hit = dynamic_cast<IOIMPL::TrackerHitPlaneIOImpl*>(objP) ;
IMPL::LCFlagImpl lcFlag(_flag) ;
if( vers > SIO_VERSION_ENCODE( 1, 51) ) {
SIO_DATA( device , &(hit->_cellID0) , 1 ) ;
if( lcFlag.bitSet( EVENT::LCIO::RTHPBIT_ID1 ) ){
SIO_DATA( device , &(hit->_cellID1) , 1 ) ;
}
}
SIO_DATA( device, &(hit->_type) , 1 ) ;
SIO_DATA( device, hit->_pos , 3 ) ;
SIO_DATA( device, hit->_u , 2 ) ;
SIO_DATA( device, hit->_v , 2 ) ;
SIO_DATA( device, &(hit->_du) , 1 ) ;
SIO_DATA( device, &(hit->_dv) , 1 ) ;
SIO_DATA( device, &(hit->_EDep) , 1 ) ;
SIO_DATA( device, &(hit->_EDepError) , 1 ) ;
SIO_DATA( device, &(hit->_time) , 1 ) ;
SIO_DATA( device, &(hit->_quality) , 1 ) ;
int numberOfRawHits = 1 ;
SIO_DATA( device , &numberOfRawHits , 1 ) ;
hit->_rawHits.resize( numberOfRawHits ) ;
for( int i=0 ; i<numberOfRawHits ; i++ ) {
SIO_PNTR( device , &(hit->_rawHits[i] ) ) ;
}
SIO_PTAG( device , dynamic_cast<const EVENT::TrackerHitPlane*>(hit) ) ;
}
//----------------------------------------------------------------------------
void SIOTrackerHitPlaneHandler::write( sio::write_device& device, const EVENT::LCObject* obj ) {
auto hit = dynamic_cast<const EVENT::TrackerHitPlane*>(obj) ;
IMPL::LCFlagImpl lcFlag(_flag) ;
SIO_SDATA( device, hit->getCellID0() ) ;
if( lcFlag.bitSet( EVENT::LCIO::RTHPBIT_ID1 ) ){
SIO_SDATA( device, hit->getCellID1() ) ;
}
SIO_SDATA( device , hit->getType() ) ;
SIO_DATA( device, hit->getPosition() , 3 ) ;
SIO_DATA( device, hit->getU() , 2 ) ;
SIO_DATA( device, hit->getV() , 2 ) ;
SIO_SDATA( device, hit->getdU() ) ;
SIO_SDATA( device, hit->getdV() ) ;
SIO_SDATA( device, hit->getEDep() ) ;
SIO_SDATA( device, hit->getEDepError() ) ;
SIO_SDATA( device, hit->getTime() ) ;
SIO_SDATA( device, hit->getQuality() ) ;
const EVENT::LCObjectVec& rawHits = hit->getRawHits() ;
SIO_SDATA( device, rawHits.size() ) ;
for(unsigned int i=0; i < rawHits.size() ; i++){
SIO_PNTR( device , &(rawHits[i]) ) ;
}
SIO_PTAG( device , hit ) ;
}
//----------------------------------------------------------------------------
EVENT::LCObject *SIOTrackerHitPlaneHandler::create() const {
return new IOIMPL::TrackerHitPlaneIOImpl() ;
}
} // namespace
<commit_msg>Fixed TrackerHitPlane SIO streamer<commit_after>#include "SIO/SIOTrackerHitPlaneHandler.h"
// -- lcio headers
#include "EVENT/LCIO.h"
#include "IMPL/LCFlagImpl.h"
#include "EVENT/TrackerHitPlane.h"
#include "IOIMPL/TrackerHitPlaneIOImpl.h"
// -- sio headers
#include <sio/io_device.h>
#include <sio/version.h>
namespace SIO {
SIOTrackerHitPlaneHandler::SIOTrackerHitPlaneHandler() :
SIOObjectHandler( EVENT::LCIO::TRACKERHITPLANE ) {
/* nop */
}
//----------------------------------------------------------------------------
void SIOTrackerHitPlaneHandler::read( sio::read_device& device, EVENT::LCObject* objP, sio::version_type vers ) {
auto hit = dynamic_cast<IOIMPL::TrackerHitPlaneIOImpl*>(objP) ;
IMPL::LCFlagImpl lcFlag(_flag) ;
if( vers > SIO_VERSION_ENCODE( 1, 51) ) {
SIO_DATA( device , &(hit->_cellID0) , 1 ) ;
if( lcFlag.bitSet( EVENT::LCIO::RTHPBIT_ID1 ) ){
SIO_DATA( device , &(hit->_cellID1) , 1 ) ;
}
}
SIO_DATA( device, &(hit->_type) , 1 ) ;
SIO_DATA( device, hit->_pos , 3 ) ;
SIO_DATA( device, hit->_u , 2 ) ;
SIO_DATA( device, hit->_v , 2 ) ;
SIO_DATA( device, &(hit->_du) , 1 ) ;
SIO_DATA( device, &(hit->_dv) , 1 ) ;
SIO_DATA( device, &(hit->_EDep) , 1 ) ;
SIO_DATA( device, &(hit->_EDepError) , 1 ) ;
SIO_DATA( device, &(hit->_time) , 1 ) ;
SIO_DATA( device, &(hit->_quality) , 1 ) ;
int numberOfRawHits = 1 ;
SIO_DATA( device , &numberOfRawHits , 1 ) ;
hit->_rawHits.resize( numberOfRawHits ) ;
for( int i=0 ; i<numberOfRawHits ; i++ ) {
SIO_PNTR( device , &(hit->_rawHits[i] ) ) ;
}
SIO_PTAG( device , dynamic_cast<const EVENT::TrackerHitPlane*>(hit) ) ;
}
//----------------------------------------------------------------------------
void SIOTrackerHitPlaneHandler::write( sio::write_device& device, const EVENT::LCObject* obj ) {
auto hit = dynamic_cast<const EVENT::TrackerHitPlane*>(obj) ;
IMPL::LCFlagImpl lcFlag(_flag) ;
SIO_SDATA( device, hit->getCellID0() ) ;
if( lcFlag.bitSet( EVENT::LCIO::RTHPBIT_ID1 ) ){
SIO_SDATA( device, hit->getCellID1() ) ;
}
SIO_SDATA( device , hit->getType() ) ;
SIO_DATA( device, hit->getPosition() , 3 ) ;
SIO_DATA( device, hit->getU() , 2 ) ;
SIO_DATA( device, hit->getV() , 2 ) ;
SIO_SDATA( device, hit->getdU() ) ;
SIO_SDATA( device, hit->getdV() ) ;
SIO_SDATA( device, hit->getEDep() ) ;
SIO_SDATA( device, hit->getEDepError() ) ;
SIO_SDATA( device, hit->getTime() ) ;
SIO_SDATA( device, hit->getQuality() ) ;
const EVENT::LCObjectVec& rawHits = hit->getRawHits() ;
int nrawhits = rawHits.size() ;
SIO_SDATA( device, nrawhits ) ;
for(unsigned int i=0; i < rawHits.size() ; i++){
SIO_PNTR( device , &(rawHits[i]) ) ;
}
SIO_PTAG( device , hit ) ;
}
//----------------------------------------------------------------------------
EVENT::LCObject *SIOTrackerHitPlaneHandler::create() const {
return new IOIMPL::TrackerHitPlaneIOImpl() ;
}
} // namespace
<|endoftext|> |
<commit_before>// This file should match src/Console/Touch.cpp
#include "Touch.h"
// buttons
Bounce redButton = Bounce(BUTTON_RED, BUTTON_DEBOUNCE_TIME);
Bounce grnButton = Bounce(BUTTON_GRN, BUTTON_DEBOUNCE_TIME);
Bounce bluButton = Bounce(BUTTON_BLU, BUTTON_DEBOUNCE_TIME);
Bounce yelButton = Bounce(BUTTON_YEL, BUTTON_DEBOUNCE_TIME);
// MPR121 object instantiated in the library.
boolean Touch::begin() {
Serial << F("Touch: startup.") << endl;
// following Examples->BareConductive_MPR->SimpleTouch
// 0x5C is the MPR121 I2C address on the Bare Touch Board
Wire.begin();
boolean mprError = true;
while( mprError ) {
if (!MPR121.begin(MPR121_I2CADDR_DEFAULT)) {
Serial << F("Touch: error setting up MPR121: ");
switch (MPR121.getError()) {
case ADDRESS_UNKNOWN:
Serial << F("MPR121: did not respond at address") << endl;
break;
case READBACK_FAIL:
Serial << F("MPR121: readback failure") << endl;
break;
case OVERCURRENT_FLAG:
Serial << F("MPR121: overcurrent on REXT pin") << endl;
break;
case OUT_OF_RANGE:
Serial << F("MPR121: electrode out of range") << endl;
break;
case NOT_INITED:
Serial << F("MPR121: not initialised") << endl;
break;
default:
Serial << F("MPR121: unknown error") << endl;
break;
}
delay(1000);
}
else {
Serial << F("Touhc: MPR121: initialized.") << endl;
MPR121.reset();
Serial << F("Touch: MPR121: reset.") << endl;
// set the interrupt handler.
MPR121.setInterruptPin(TOUCH_IRQ);
// enable 13-th virtual proximity electrode, tying electrodes 0..3 together.
MPR121.setProxMode(PROX0_3);
Serial << F("Touch: MPR121 proximity enabled.") << endl;
// initial data update
MPR121.updateAll();
Serial << F("Touch: MPR121 data updaet.") << endl;
Serial << F("Touch: MPR121 initialization complete.") << endl;
mprError = false;
}
}
Serial << F("Touch: setting up hard buttons.") << endl;
pinMode(BUTTON_RED, INPUT_PULLUP);
pinMode(BUTTON_GRN, INPUT_PULLUP);
pinMode(BUTTON_BLU, INPUT_PULLUP);
pinMode(BUTTON_YEL, INPUT_PULLUP);
button[I_RED] = &redButton;
button[I_GRN] = &grnButton;
button[I_BLU] = &bluButton;
button[I_YEL] = &yelButton;
Serial << F("Button: startup complete.") << endl;
return ( true );
}
// Returns true if the state of a specific button has changed
// based on what it was previously.
boolean Touch::changed(byte index) {
boolean ret = false;
// capsense
static boolean previousState[N_COLORS];
MPR121.updateTouchData();
boolean currentState = MPR121.getTouchData(index);
if (previousState[index] != currentState) {
previousState[index] = currentState;
ret |= true;
}
// hard buttons
ret |= button[index]->update();
// return
return ( ret );
}
// returns true if any of the buttons are pressed.
boolean Touch::anyChanged() {
return (
changed(I_RED) ||
changed(I_GRN) ||
changed(I_BLU) ||
changed(I_YEL)
);
}
// returns true WHILE a specific sensor IS PRESSED
// this function will be called after touchChanged() asserts a change.
boolean Touch::pressed(byte index) {
boolean ret = false;
// capsense
MPR121.updateTouchData();
ret |= MPR121.getTouchData(index);
// hard buttons
// call the updater for debouncing first.
boolean toss = button[index]->update();
ret |= button[index]->read() == PRESSED_BUTTON;
// return
return ( ret );
}
// returns true if any of the buttons have switched states.
// avoid short-circuit eval so that each button gets an update
boolean Touch::anyPressed() {
return (
pressed(I_RED) ||
pressed(I_GRN) ||
pressed(I_BLU) ||
pressed(I_YEL)
);
}
// for distance/proximity, see http://cache.freescale.com/files/sensors/doc/app_note/AN3893.pdf
// returns "distance" an object is to the sensor, scaled [0, 32767]
// realistically, we have 10-bit resolution?
int Touch::distance(byte sensorIndex) {
// for this, we need the baseline and filtered data
boolean foo = MPR121.updateBaselineData();
boolean bar = MPR121.updateFilteredData();
// save the maximum delta we note
static int maxDelta[13] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
for (int i = 0; i < 13; i++ ) {
maxDelta[i] = max(maxDelta[i], MPR121.getBaselineData(i) - MPR121.getFilteredData(i));
}
// the larger the delta, the closer the object
int sensorDelta = MPR121.getBaselineData(sensorIndex) - MPR121.getFilteredData(sensorIndex);
// delta is zero at infinite distance, and very large (approaching baseline data) at zero distance, so distance has an inverse relationship with delta
// like many fields in a 3-D volume, the radiated energy decreses with the distance squared from the source.
// so, we'll take a stab at distance = 1/(delta^2)
const int maxInt = 32767;
const float calibrant = -2.0;
float distance = fscale(0, maxDelta[sensorIndex], maxInt, 0, sensorDelta, calibrant);
return ( int(distance) );
}
// snagged this from https://github.com/BareConductive/midi_theremin/blob/public/midi_theremin/midi_theremin.ino
// http://playground.arduino.cc/Main/Fscale
float fscale( float originalMin, float originalMax, float newBegin, float newEnd, float inputValue, float curve) {
float OriginalRange = 0;
float NewRange = 0;
float zeroRefCurVal = 0;
float normalizedCurVal = 0;
float rangedValue = 0;
boolean invFlag = 0;
// condition curve parameter
// limit range
if (curve > 10) curve = 10;
if (curve < -10) curve = -10;
curve = (curve * -.1) ; // - invert and scale - this seems more intuitive - postive numbers give more weight to high end on output
curve = pow(10, curve); // convert linear scale into lograthimic exponent for other pow function
/*
Serial.println(curve * 100, DEC); // multply by 100 to preserve resolution
Serial.println();
*/
// Check for out of range inputValues
if (inputValue < originalMin) {
inputValue = originalMin;
}
if (inputValue > originalMax) {
inputValue = originalMax;
}
// Zero Refference the values
OriginalRange = originalMax - originalMin;
if (newEnd > newBegin) {
NewRange = newEnd - newBegin;
}
else
{
NewRange = newBegin - newEnd;
invFlag = 1;
}
zeroRefCurVal = inputValue - originalMin;
normalizedCurVal = zeroRefCurVal / OriginalRange; // normalize to 0 - 1 float
/*
Serial.print(OriginalRange, DEC);
Serial.print(" ");
Serial.print(NewRange, DEC);
Serial.print(" ");
Serial.println(zeroRefCurVal, DEC);
Serial.println();
*/
// Check for originalMin > originalMax - the math for all other cases i.e. negative numbers seems to work out fine
if (originalMin > originalMax ) {
return 0;
}
if (invFlag == 0) {
rangedValue = (pow(normalizedCurVal, curve) * NewRange) + newBegin;
}
else // invert the ranges
{
rangedValue = newBegin - (pow(normalizedCurVal, curve) * NewRange);
}
return rangedValue;
}
Touch touch;
<commit_msg>Dinked.<commit_after>// This file should match src/Console/Touch.cpp
#include "Touch.h"
// buttons
Bounce redButton = Bounce(BUTTON_RED, BUTTON_DEBOUNCE_TIME);
Bounce grnButton = Bounce(BUTTON_GRN, BUTTON_DEBOUNCE_TIME);
Bounce bluButton = Bounce(BUTTON_BLU, BUTTON_DEBOUNCE_TIME);
Bounce yelButton = Bounce(BUTTON_YEL, BUTTON_DEBOUNCE_TIME);
// MPR121 object instantiated in the library.
boolean Touch::begin() {
Serial << F("Touch: startup.") << endl;
// following Examples->BareConductive_MPR->SimpleTouch
// 0x5A is the MPR121 I2C address on the Bare Touch Board
Wire.begin();
boolean mprError = true;
while( mprError ) {
if (!MPR121.begin(MPR121_I2CADDR_DEFAULT)) {
Serial << F("Touch: error setting up MPR121: ");
switch (MPR121.getError()) {
case ADDRESS_UNKNOWN:
Serial << F("MPR121: did not respond at address") << endl;
break;
case READBACK_FAIL:
Serial << F("MPR121: readback failure") << endl;
break;
case OVERCURRENT_FLAG:
Serial << F("MPR121: overcurrent on REXT pin") << endl;
break;
case OUT_OF_RANGE:
Serial << F("MPR121: electrode out of range") << endl;
break;
case NOT_INITED:
Serial << F("MPR121: not initialised") << endl;
break;
default:
Serial << F("MPR121: unknown error") << endl;
break;
}
delay(1000);
}
else {
Serial << F("Touhc: MPR121: initialized.") << endl;
MPR121.reset();
Serial << F("Touch: MPR121: reset.") << endl;
// set the interrupt handler.
MPR121.setInterruptPin(TOUCH_IRQ);
// enable 13-th virtual proximity electrode, tying electrodes 0..3 together.
MPR121.setProxMode(PROX0_3);
Serial << F("Touch: MPR121 proximity enabled.") << endl;
// initial data update
MPR121.updateAll();
Serial << F("Touch: MPR121 data updaet.") << endl;
Serial << F("Touch: MPR121 initialization complete.") << endl;
mprError = false;
}
}
Serial << F("Touch: setting up hard buttons.") << endl;
pinMode(BUTTON_RED, INPUT_PULLUP);
pinMode(BUTTON_GRN, INPUT_PULLUP);
pinMode(BUTTON_BLU, INPUT_PULLUP);
pinMode(BUTTON_YEL, INPUT_PULLUP);
button[I_RED] = &redButton;
button[I_GRN] = &grnButton;
button[I_BLU] = &bluButton;
button[I_YEL] = &yelButton;
Serial << F("Button: startup complete.") << endl;
return ( true );
}
// Returns true if the state of a specific button has changed
// based on what it was previously.
boolean Touch::changed(byte index) {
boolean ret = false;
// capsense
static boolean previousState[N_COLORS];
MPR121.updateTouchData();
boolean currentState = MPR121.getTouchData(index);
if (previousState[index] != currentState) {
previousState[index] = currentState;
ret |= true;
}
// hard buttons
ret |= button[index]->update();
// return
return ( ret );
}
// returns true if any of the buttons are pressed.
boolean Touch::anyChanged() {
return (
changed(I_RED) ||
changed(I_GRN) ||
changed(I_BLU) ||
changed(I_YEL)
);
}
// returns true WHILE a specific sensor IS PRESSED
// this function will be called after touchChanged() asserts a change.
boolean Touch::pressed(byte index) {
boolean ret = false;
// capsense
MPR121.updateTouchData();
ret |= MPR121.getTouchData(index);
// hard buttons
// call the updater for debouncing first.
boolean toss = button[index]->update();
ret |= button[index]->read() == PRESSED_BUTTON;
// return
return ( ret );
}
// returns true if any of the buttons have switched states.
// avoid short-circuit eval so that each button gets an update
boolean Touch::anyPressed() {
return (
pressed(I_RED) ||
pressed(I_GRN) ||
pressed(I_BLU) ||
pressed(I_YEL)
);
}
// for distance/proximity, see http://cache.freescale.com/files/sensors/doc/app_note/AN3893.pdf
// returns "distance" an object is to the sensor, scaled [0, 32767]
// realistically, we have 10-bit resolution?
int Touch::distance(byte sensorIndex) {
// for this, we need the baseline and filtered data
boolean foo = MPR121.updateBaselineData();
boolean bar = MPR121.updateFilteredData();
// save the maximum delta we note
static int maxDelta[13] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
for (int i = 0; i < 13; i++ ) {
maxDelta[i] = max(maxDelta[i], MPR121.getBaselineData(i) - MPR121.getFilteredData(i));
}
// the larger the delta, the closer the object
int sensorDelta = MPR121.getBaselineData(sensorIndex) - MPR121.getFilteredData(sensorIndex);
// delta is zero at infinite distance, and very large (approaching baseline data) at zero distance, so distance has an inverse relationship with delta
// like many fields in a 3-D volume, the radiated energy decreses with the distance squared from the source.
// so, we'll take a stab at distance = 1/(delta^2)
const int maxInt = 32767;
const float calibrant = -2.0;
float distance = fscale(0, maxDelta[sensorIndex], maxInt, 0, sensorDelta, calibrant);
return ( int(distance) );
}
// snagged this from https://github.com/BareConductive/midi_theremin/blob/public/midi_theremin/midi_theremin.ino
// http://playground.arduino.cc/Main/Fscale
float fscale( float originalMin, float originalMax, float newBegin, float newEnd, float inputValue, float curve) {
float OriginalRange = 0;
float NewRange = 0;
float zeroRefCurVal = 0;
float normalizedCurVal = 0;
float rangedValue = 0;
boolean invFlag = 0;
// condition curve parameter
// limit range
if (curve > 10) curve = 10;
if (curve < -10) curve = -10;
curve = (curve * -.1) ; // - invert and scale - this seems more intuitive - postive numbers give more weight to high end on output
curve = pow(10, curve); // convert linear scale into lograthimic exponent for other pow function
/*
Serial.println(curve * 100, DEC); // multply by 100 to preserve resolution
Serial.println();
*/
// Check for out of range inputValues
if (inputValue < originalMin) {
inputValue = originalMin;
}
if (inputValue > originalMax) {
inputValue = originalMax;
}
// Zero Refference the values
OriginalRange = originalMax - originalMin;
if (newEnd > newBegin) {
NewRange = newEnd - newBegin;
}
else
{
NewRange = newBegin - newEnd;
invFlag = 1;
}
zeroRefCurVal = inputValue - originalMin;
normalizedCurVal = zeroRefCurVal / OriginalRange; // normalize to 0 - 1 float
/*
Serial.print(OriginalRange, DEC);
Serial.print(" ");
Serial.print(NewRange, DEC);
Serial.print(" ");
Serial.println(zeroRefCurVal, DEC);
Serial.println();
*/
// Check for originalMin > originalMax - the math for all other cases i.e. negative numbers seems to work out fine
if (originalMin > originalMax ) {
return 0;
}
if (invFlag == 0) {
rangedValue = (pow(normalizedCurVal, curve) * NewRange) + newBegin;
}
else // invert the ranges
{
rangedValue = newBegin - (pow(normalizedCurVal, curve) * NewRange);
}
return rangedValue;
}
Touch touch;
<|endoftext|> |
<commit_before>#include "application.h"
#include "module/deamon_module.h"
#ifndef WIN32
# include <string.h>
#endif/*WIN32*/
DeamonApplication::DeamonApplication()
{
}
DeamonApplication::~DeamonApplication()
{
}
void DeamonApplication::OnModuleCreationFailed(Twainet::Module module)
{
if(strcmp(Twainet::GetModuleName(module).m_name, COORDINATOR_NAME) == 0)
{
Stop();
}
}
void DeamonApplication::OnServerCreationFailed(Twainet::Module module)
{
if(strcmp(Twainet::GetModuleName(module).m_name, COORDINATOR_NAME) == 0)
{
Stop();
}
}
void DeamonApplication::InitializeApplication()
{
DeamonModule* module = new DeamonModule;
module->Create();
module->Init();
AddModule(module);
}
std::string DeamonApplication::GetAppName()
{
return "TwainetDeamon";
}
std::string DeamonApplication::GetDescription()
{
return "Twainet deamon application";
}<commit_msg>fix deamon<commit_after>#include "application.h"
#include "module/deamon_module.h"
#ifndef WIN32
# include <string.h>
#endif/*WIN32*/
DeamonApplication::DeamonApplication()
{
}
DeamonApplication::~DeamonApplication()
{
}
void DeamonApplication::OnModuleCreationFailed(Twainet::Module module)
{
if(strcmp(Twainet::GetModuleName(module).m_name, COORDINATOR_NAME) == 0)
{
Stop();
}
}
void DeamonApplication::OnServerCreationFailed(Twainet::Module module)
{
if(strcmp(Twainet::GetModuleName(module).m_name, COORDINATOR_NAME) == 0)
{
Stop();
}
}
void DeamonApplication::InitializeApplication()
{
DeamonModule* module = new DeamonModule;
AddModule(module);
module->Init();
}
std::string DeamonApplication::GetAppName()
{
return "TwainetDeamon";
}
std::string DeamonApplication::GetDescription()
{
return "Twainet deamon application";
}<|endoftext|> |
<commit_before>#include "ContentWindow.h"
#include "Content.h"
#include "DisplayGroup.h"
#include "main.h"
qreal ContentWindow::zCounter_ = 0;
ContentWindow::ContentWindow()
{
initialized_ = false;
}
ContentWindow::ContentWindow(boost::shared_ptr<Content> content)
{
// defaults
initialized_ = false;
// default position / size
x_ = y_ = 0.;
w_ = h_ = 0.25;
// default to centered
centerX_ = 0.5;
centerY_ = 0.5;
// default to no zoom
zoom_ = 1.;
// default window state
resizing_ = false;
selected_ = false;
// set content object
content_ = content;
}
boost::shared_ptr<Content> ContentWindow::getContent()
{
return content_;
}
boost::shared_ptr<DisplayGroup> ContentWindow::getDisplayGroup()
{
return displayGroup_.lock();
}
void ContentWindow::setDisplayGroup(boost::shared_ptr<DisplayGroup> displayGroup)
{
displayGroup_ = displayGroup;
}
void ContentWindow::setCoordinates(double x, double y, double w, double h)
{
x_ = x;
y_ = y;
w_ = w;
h_ = h;
setRect(x_, y_, w_, h_);
// force synchronization
if(getDisplayGroup() != NULL)
{
getDisplayGroup()->sendDisplayGroup();
}
}
void ContentWindow::getCoordinates(double &x, double &y, double &w, double &h)
{
x = x_;
y = y_;
w = w_;
h = h_;
}
void ContentWindow::setCenterCoordinates(double centerX, double centerY)
{
centerX_ = centerX;
centerY_ = centerY;
// force synchronization
if(getDisplayGroup() != NULL)
{
getDisplayGroup()->sendDisplayGroup();
}
}
void ContentWindow::getCenterCoordinates(double ¢erX, double ¢erY)
{
centerX = centerX_;
centerY = centerY_;
}
void ContentWindow::setZoom(double zoom)
{
zoom_ = zoom;
// force synchronization
if(getDisplayGroup() != NULL)
{
getDisplayGroup()->sendDisplayGroup();
}
}
double ContentWindow::getZoom()
{
return zoom_;
}
void ContentWindow::fixAspectRatio()
{
int contentWidth, contentHeight;
content_->getDimensions(contentWidth, contentHeight);
double aspect = (double)contentWidth / (double)contentHeight;
double screenAspect = (double)g_configuration->getTotalWidth() / (double)g_configuration->getTotalHeight();
aspect /= screenAspect;
if(aspect > w_ / h_)
{
h_ = w_ / aspect;
}
else if(aspect <= w_ / h_)
{
w_ = h_ * aspect;
}
QRectF r = rect();
// the rect() isn't set until the first paint after serialization, so we need to make sure the (x,y) coordinates are correct
// todo: this shouldn't be necessary, and should be fixed later...
if(r.x() == 0. && r.y() == 0.)
{
r.setX(x_);
r.setY(y_);
}
r.setWidth(w_);
r.setHeight(h_);
setRect(r);
// setRect() won't cause an itemChange event, so trigger one manually
itemChange(ItemPositionChange, 0);
}
void ContentWindow::render()
{
content_->render(shared_from_this());
// render the border
double horizontalBorder = 5. / (double)g_configuration->getTotalHeight(); // 5 pixels
double verticalBorder = (double)g_configuration->getTotalHeight() / (double)g_configuration->getTotalWidth() * horizontalBorder;
glPushAttrib(GL_CURRENT_BIT);
// color the border based on window state
if(selected_ == true)
{
glColor4f(1,0,0,1);
}
else
{
glColor4f(1,1,1,1);
}
GLWindow::drawRectangle(x_-verticalBorder,y_-horizontalBorder,w_+2.*verticalBorder,h_+2.*horizontalBorder);
glPopAttrib();
}
void ContentWindow::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
if(initialized_ == false)
{
// on first paint, initialize
// note that we can't call some of these in the constructor, since they wouldn't then be called after de-serialization
setRect(x_, y_, w_, h_);
// graphics items are movable and fire events on geometry changes
setFlag(QGraphicsItem::ItemIsMovable, true);
setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
// default fill color / opacity
setBrush(QBrush(QColor(0, 0, 0, 128)));
// default border
setPen(QPen(QColor(0,0,0)));
// new items at the front
zCounter_ = zCounter_ + 1;
setZValue(zCounter_);
// force synchronization of display group since this is a new window
getDisplayGroup()->sendDisplayGroup();
initialized_ = true;
}
QGraphicsRectItem::paint(painter, option, widget);
// default pen
QPen pen;
// button dimensions
float buttonWidth, buttonHeight;
getButtonDimensions(buttonWidth, buttonHeight);
// draw close button
QRectF closeRect(rect().x() + rect().width() - buttonWidth, rect().y(), buttonWidth, buttonHeight);
pen.setColor(QColor(255,0,0));
painter->setPen(pen);
painter->drawRect(closeRect);
painter->drawLine(QPointF(rect().x() + rect().width() - buttonWidth, rect().y()), QPointF(rect().x() + rect().width(), rect().y() + buttonHeight));
painter->drawLine(QPointF(rect().x() + rect().width(), rect().y()), QPointF(rect().x() + rect().width() - buttonWidth, rect().y() + buttonHeight));
// resize indicator
QRectF resizeRect(rect().x() + rect().width() - buttonWidth, rect().y() + rect().height() - buttonHeight, buttonWidth, buttonHeight);
pen.setColor(QColor(128,128,128));
painter->setPen(pen);
painter->drawRect(resizeRect);
painter->drawLine(QPointF(rect().x() + rect().width(), rect().y() + rect().height() - buttonHeight), QPointF(rect().x() + rect().width() - buttonWidth, rect().y() + rect().height()));
// text label
// set the font
float fontSize = 24.;
QFont font;
font.setPixelSize(fontSize);
painter->setFont(font);
// color the text black
pen.setColor(QColor(0,0,0));
painter->setPen(pen);
// scale the text size down to the height of the graphics view
// and, calculate the bounding rectangle for the text based on this scale
float verticalTextScale = 1. / (float)scene()->views()[0]->height();
float horizontalTextScale = (float)scene()->views()[0]->height() / (float)scene()->views()[0]->width() * verticalTextScale;
painter->scale(horizontalTextScale, verticalTextScale);
QRectF textBoundingRect = QRectF(rect().x() / horizontalTextScale, rect().y() / verticalTextScale, rect().width() / horizontalTextScale, rect().height() / verticalTextScale);
// get the label and render it
QString label(content_->getURI().c_str());
QString labelSection = label.section("/", -1, -1).prepend(" ");
painter->drawText(textBoundingRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, labelSection);
}
void ContentWindow::mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
// handle mouse movements differently depending on selected mode of item
if(selected_ == false)
{
if(event->buttons().testFlag(Qt::LeftButton) == true)
{
if(resizing_ == true)
{
QRectF r = rect();
QPointF eventPos = event->pos();
r.setBottomRight(eventPos);
setRect(r);
// setRect() won't cause an itemChange event, so trigger one manually
itemChange(ItemPositionChange, 0);
if(g_mainWindow->getConstrainAspectRatio() == true)
{
fixAspectRatio();
}
}
else
{
QPointF delta = event->pos() - event->lastPos();
moveBy(delta.x(), delta.y());
}
}
}
else
{
// handle zooms / pans
QPointF delta = event->scenePos() - event->lastScenePos();
if(event->buttons().testFlag(Qt::RightButton) == true)
{
// increment zoom
// if this is a touch event, use cross-product for determining change in zoom (counterclockwise rotation == zoom in, etc.)
// otherwise, use y as the change in zoom
double zoomDelta;
if(event->modifiers().testFlag(Qt::AltModifier) == true)
{
zoomDelta = (event->scenePos().x()-0.5) * delta.y() - (event->scenePos().y()-0.5) * delta.x();
zoomDelta *= 2.;
}
else
{
zoomDelta = delta.y();
}
zoom_ *= (1. - zoomDelta);
setZoom(zoom_);
}
else if(event->buttons().testFlag(Qt::LeftButton) == true)
{
// pan (move center coordinates)
centerX_ += 2.*delta.x() / zoom_;
centerY_ += 2.*delta.y() / zoom_;
setCenterCoordinates(centerX_, centerY_);
}
}
}
void ContentWindow::mousePressEvent(QGraphicsSceneMouseEvent * event)
{
// button dimensions
float buttonWidth, buttonHeight;
getButtonDimensions(buttonWidth, buttonHeight);
// item rectangle and event position
QRectF r = rect();
QPointF eventPos = event->pos();
// check to see if user clicked on the close button
if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()) - eventPos.y()) <= buttonHeight)
{
getDisplayGroup()->removeContentWindow(shared_from_this());
return;
}
// check to see if user clicked on the resize button
if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()+r.height()) - eventPos.y()) <= buttonHeight)
{
resizing_ = true;
}
// move content to front of display group
getDisplayGroup()->moveContentWindowToFront(shared_from_this());
// and to the front of the GUI display
zCounter_ = zCounter_ + 1;
setZValue(zCounter_);
QGraphicsItem::mousePressEvent(event);
}
void ContentWindow::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event)
{
selected_ = !selected_;
// set the pen
QPen p = pen();
if(selected_ == true)
{
p.setColor(QColor(255,0,0));
}
else
{
p.setColor(QColor(0,0,0));
}
setPen(p);
QGraphicsItem::mouseDoubleClickEvent(event);
}
void ContentWindow::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)
{
resizing_ = false;
QGraphicsItem::mouseReleaseEvent(event);
}
QVariant ContentWindow::itemChange(GraphicsItemChange change, const QVariant &value)
{
if(change == ItemPositionChange)
{
QRectF r = mapRectToScene(rect());
x_ = r.x() / scene()->width();
y_ = r.y() / scene()->height();
w_ = r.width() / scene()->width();
h_ = r.height() / scene()->height();
// note that we don't have to call sendDisplayGroup() here
// the display group is already updated due to the marker (cursor) changing
}
return QGraphicsItem::itemChange(change, value);
}
void ContentWindow::getButtonDimensions(float &width, float &height)
{
float sceneFraction = 0.05;
width = sceneFraction * scene()->height();
height = sceneFraction * scene()->height();
// clamp to rect dimensions
if(width > 0.5 * rect().width())
{
width = 0.49 * rect().width();
}
if(height > 0.5 * rect().height())
{
height = 0.49 * rect().height();
}
}
<commit_msg>ContentWindow buttons are now 1/8 of the total tiled display height, and are constrained to be square.<commit_after>#include "ContentWindow.h"
#include "Content.h"
#include "DisplayGroup.h"
#include "main.h"
qreal ContentWindow::zCounter_ = 0;
ContentWindow::ContentWindow()
{
initialized_ = false;
}
ContentWindow::ContentWindow(boost::shared_ptr<Content> content)
{
// defaults
initialized_ = false;
// default position / size
x_ = y_ = 0.;
w_ = h_ = 0.25;
// default to centered
centerX_ = 0.5;
centerY_ = 0.5;
// default to no zoom
zoom_ = 1.;
// default window state
resizing_ = false;
selected_ = false;
// set content object
content_ = content;
}
boost::shared_ptr<Content> ContentWindow::getContent()
{
return content_;
}
boost::shared_ptr<DisplayGroup> ContentWindow::getDisplayGroup()
{
return displayGroup_.lock();
}
void ContentWindow::setDisplayGroup(boost::shared_ptr<DisplayGroup> displayGroup)
{
displayGroup_ = displayGroup;
}
void ContentWindow::setCoordinates(double x, double y, double w, double h)
{
x_ = x;
y_ = y;
w_ = w;
h_ = h;
setRect(x_, y_, w_, h_);
// force synchronization
if(getDisplayGroup() != NULL)
{
getDisplayGroup()->sendDisplayGroup();
}
}
void ContentWindow::getCoordinates(double &x, double &y, double &w, double &h)
{
x = x_;
y = y_;
w = w_;
h = h_;
}
void ContentWindow::setCenterCoordinates(double centerX, double centerY)
{
centerX_ = centerX;
centerY_ = centerY;
// force synchronization
if(getDisplayGroup() != NULL)
{
getDisplayGroup()->sendDisplayGroup();
}
}
void ContentWindow::getCenterCoordinates(double ¢erX, double ¢erY)
{
centerX = centerX_;
centerY = centerY_;
}
void ContentWindow::setZoom(double zoom)
{
zoom_ = zoom;
// force synchronization
if(getDisplayGroup() != NULL)
{
getDisplayGroup()->sendDisplayGroup();
}
}
double ContentWindow::getZoom()
{
return zoom_;
}
void ContentWindow::fixAspectRatio()
{
int contentWidth, contentHeight;
content_->getDimensions(contentWidth, contentHeight);
double aspect = (double)contentWidth / (double)contentHeight;
double screenAspect = (double)g_configuration->getTotalWidth() / (double)g_configuration->getTotalHeight();
aspect /= screenAspect;
if(aspect > w_ / h_)
{
h_ = w_ / aspect;
}
else if(aspect <= w_ / h_)
{
w_ = h_ * aspect;
}
QRectF r = rect();
// the rect() isn't set until the first paint after serialization, so we need to make sure the (x,y) coordinates are correct
// todo: this shouldn't be necessary, and should be fixed later...
if(r.x() == 0. && r.y() == 0.)
{
r.setX(x_);
r.setY(y_);
}
r.setWidth(w_);
r.setHeight(h_);
setRect(r);
// setRect() won't cause an itemChange event, so trigger one manually
itemChange(ItemPositionChange, 0);
}
void ContentWindow::render()
{
content_->render(shared_from_this());
// render the border
double horizontalBorder = 5. / (double)g_configuration->getTotalHeight(); // 5 pixels
double verticalBorder = (double)g_configuration->getTotalHeight() / (double)g_configuration->getTotalWidth() * horizontalBorder;
glPushAttrib(GL_CURRENT_BIT);
// color the border based on window state
if(selected_ == true)
{
glColor4f(1,0,0,1);
}
else
{
glColor4f(1,1,1,1);
}
GLWindow::drawRectangle(x_-verticalBorder,y_-horizontalBorder,w_+2.*verticalBorder,h_+2.*horizontalBorder);
glPopAttrib();
}
void ContentWindow::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
if(initialized_ == false)
{
// on first paint, initialize
// note that we can't call some of these in the constructor, since they wouldn't then be called after de-serialization
setRect(x_, y_, w_, h_);
// graphics items are movable and fire events on geometry changes
setFlag(QGraphicsItem::ItemIsMovable, true);
setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
// default fill color / opacity
setBrush(QBrush(QColor(0, 0, 0, 128)));
// default border
setPen(QPen(QColor(0,0,0)));
// new items at the front
zCounter_ = zCounter_ + 1;
setZValue(zCounter_);
// force synchronization of display group since this is a new window
getDisplayGroup()->sendDisplayGroup();
initialized_ = true;
}
QGraphicsRectItem::paint(painter, option, widget);
// default pen
QPen pen;
// button dimensions
float buttonWidth, buttonHeight;
getButtonDimensions(buttonWidth, buttonHeight);
// draw close button
QRectF closeRect(rect().x() + rect().width() - buttonWidth, rect().y(), buttonWidth, buttonHeight);
pen.setColor(QColor(255,0,0));
painter->setPen(pen);
painter->drawRect(closeRect);
painter->drawLine(QPointF(rect().x() + rect().width() - buttonWidth, rect().y()), QPointF(rect().x() + rect().width(), rect().y() + buttonHeight));
painter->drawLine(QPointF(rect().x() + rect().width(), rect().y()), QPointF(rect().x() + rect().width() - buttonWidth, rect().y() + buttonHeight));
// resize indicator
QRectF resizeRect(rect().x() + rect().width() - buttonWidth, rect().y() + rect().height() - buttonHeight, buttonWidth, buttonHeight);
pen.setColor(QColor(128,128,128));
painter->setPen(pen);
painter->drawRect(resizeRect);
painter->drawLine(QPointF(rect().x() + rect().width(), rect().y() + rect().height() - buttonHeight), QPointF(rect().x() + rect().width() - buttonWidth, rect().y() + rect().height()));
// text label
// set the font
float fontSize = 24.;
QFont font;
font.setPixelSize(fontSize);
painter->setFont(font);
// color the text black
pen.setColor(QColor(0,0,0));
painter->setPen(pen);
// scale the text size down to the height of the graphics view
// and, calculate the bounding rectangle for the text based on this scale
float verticalTextScale = 1. / (float)scene()->views()[0]->height();
float horizontalTextScale = (float)scene()->views()[0]->height() / (float)scene()->views()[0]->width() * verticalTextScale;
painter->scale(horizontalTextScale, verticalTextScale);
QRectF textBoundingRect = QRectF(rect().x() / horizontalTextScale, rect().y() / verticalTextScale, rect().width() / horizontalTextScale, rect().height() / verticalTextScale);
// get the label and render it
QString label(content_->getURI().c_str());
QString labelSection = label.section("/", -1, -1).prepend(" ");
painter->drawText(textBoundingRect, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, labelSection);
}
void ContentWindow::mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
// handle mouse movements differently depending on selected mode of item
if(selected_ == false)
{
if(event->buttons().testFlag(Qt::LeftButton) == true)
{
if(resizing_ == true)
{
QRectF r = rect();
QPointF eventPos = event->pos();
r.setBottomRight(eventPos);
setRect(r);
// setRect() won't cause an itemChange event, so trigger one manually
itemChange(ItemPositionChange, 0);
if(g_mainWindow->getConstrainAspectRatio() == true)
{
fixAspectRatio();
}
}
else
{
QPointF delta = event->pos() - event->lastPos();
moveBy(delta.x(), delta.y());
}
}
}
else
{
// handle zooms / pans
QPointF delta = event->scenePos() - event->lastScenePos();
if(event->buttons().testFlag(Qt::RightButton) == true)
{
// increment zoom
// if this is a touch event, use cross-product for determining change in zoom (counterclockwise rotation == zoom in, etc.)
// otherwise, use y as the change in zoom
double zoomDelta;
if(event->modifiers().testFlag(Qt::AltModifier) == true)
{
zoomDelta = (event->scenePos().x()-0.5) * delta.y() - (event->scenePos().y()-0.5) * delta.x();
zoomDelta *= 2.;
}
else
{
zoomDelta = delta.y();
}
zoom_ *= (1. - zoomDelta);
setZoom(zoom_);
}
else if(event->buttons().testFlag(Qt::LeftButton) == true)
{
// pan (move center coordinates)
centerX_ += 2.*delta.x() / zoom_;
centerY_ += 2.*delta.y() / zoom_;
setCenterCoordinates(centerX_, centerY_);
}
}
}
void ContentWindow::mousePressEvent(QGraphicsSceneMouseEvent * event)
{
// button dimensions
float buttonWidth, buttonHeight;
getButtonDimensions(buttonWidth, buttonHeight);
// item rectangle and event position
QRectF r = rect();
QPointF eventPos = event->pos();
// check to see if user clicked on the close button
if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()) - eventPos.y()) <= buttonHeight)
{
getDisplayGroup()->removeContentWindow(shared_from_this());
return;
}
// check to see if user clicked on the resize button
if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()+r.height()) - eventPos.y()) <= buttonHeight)
{
resizing_ = true;
}
// move content to front of display group
getDisplayGroup()->moveContentWindowToFront(shared_from_this());
// and to the front of the GUI display
zCounter_ = zCounter_ + 1;
setZValue(zCounter_);
QGraphicsItem::mousePressEvent(event);
}
void ContentWindow::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event)
{
selected_ = !selected_;
// set the pen
QPen p = pen();
if(selected_ == true)
{
p.setColor(QColor(255,0,0));
}
else
{
p.setColor(QColor(0,0,0));
}
setPen(p);
QGraphicsItem::mouseDoubleClickEvent(event);
}
void ContentWindow::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)
{
resizing_ = false;
QGraphicsItem::mouseReleaseEvent(event);
}
QVariant ContentWindow::itemChange(GraphicsItemChange change, const QVariant &value)
{
if(change == ItemPositionChange)
{
QRectF r = mapRectToScene(rect());
x_ = r.x() / scene()->width();
y_ = r.y() / scene()->height();
w_ = r.width() / scene()->width();
h_ = r.height() / scene()->height();
// note that we don't have to call sendDisplayGroup() here
// the display group is already updated due to the marker (cursor) changing
}
return QGraphicsItem::itemChange(change, value);
}
void ContentWindow::getButtonDimensions(float &width, float &height)
{
float sceneHeightFraction = 0.125;
double screenAspect = (double)g_configuration->getTotalWidth() / (double)g_configuration->getTotalHeight();
width = sceneHeightFraction / screenAspect;
height = sceneHeightFraction;
// clamp to half rect dimensions
if(width > 0.5 * w_)
{
width = 0.49 * w_;
}
if(height > 0.5 * h_)
{
height = 0.49 * h_;
}
}
<|endoftext|> |
<commit_before>/*
* Markdown.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef CORE_MARKDOWN_MARKDOWN_HPP
#define CORE_MARKDOWN_MARKDOWN_HPP
#include <string>
namespace core {
class Error;
class FilePath;
namespace markdown {
struct Extensions
{
Extensions()
: noIntraEmphasis(true),
tables(true),
fencedCode(true),
autolink(true),
laxSpacing(true),
spaceHeaders(true),
strikethrough(true),
superscript(true),
ignoreMath(true)
{
}
bool noIntraEmphasis;
bool tables;
bool fencedCode;
bool autolink;
bool laxSpacing;
bool spaceHeaders;
bool strikethrough;
bool superscript;
bool ignoreMath;
};
struct HTMLOptions
{
HTMLOptions()
: useXHTML(true),
hardWrap(true),
safelink(true),
smartypants(true),
toc(false),
skipHTML(false),
skipStyle(false),
skipImages(false),
skipLinks(false),
escape(false)
{
}
bool useXHTML;
bool hardWrap;
bool safelink;
bool smartypants;
bool toc;
bool skipHTML;
bool skipStyle;
bool skipImages;
bool skipLinks;
bool escape;
};
// render markdown to HTML -- assumes UTF-8 encoding
Error markdownToHTML(const FilePath& markdownFile,
const Extensions& extensions,
const HTMLOptions& htmlOptions,
const FilePath& htmlFile);
// render markdown to HTML -- assumes UTF-8 encoding
Error markdownToHTML(const FilePath& markdownFile,
const Extensions& extensions,
const HTMLOptions& htmlOptions,
std::string* pHTMLOutput);
// render markdown to HTML -- assumes UTF-8 encoding
Error markdownToHTML(const std::string& markdownInput,
const Extensions& extensions,
const HTMLOptions& htmlOptions,
std::string* pHTMLOutput);
} // namespace markdown
} // namespace core
#endif // CORE_MARKDOWN_MARKDOWN_HPP
<commit_msg>default safelink to false in markdown processing<commit_after>/*
* Markdown.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef CORE_MARKDOWN_MARKDOWN_HPP
#define CORE_MARKDOWN_MARKDOWN_HPP
#include <string>
namespace core {
class Error;
class FilePath;
namespace markdown {
struct Extensions
{
Extensions()
: noIntraEmphasis(true),
tables(true),
fencedCode(true),
autolink(true),
laxSpacing(true),
spaceHeaders(true),
strikethrough(true),
superscript(true),
ignoreMath(true)
{
}
bool noIntraEmphasis;
bool tables;
bool fencedCode;
bool autolink;
bool laxSpacing;
bool spaceHeaders;
bool strikethrough;
bool superscript;
bool ignoreMath;
};
struct HTMLOptions
{
HTMLOptions()
: useXHTML(true),
hardWrap(true),
smartypants(true),
safelink(false),
toc(false),
skipHTML(false),
skipStyle(false),
skipImages(false),
skipLinks(false),
escape(false)
{
}
bool useXHTML;
bool hardWrap;
bool smartypants;
bool safelink;
bool toc;
bool skipHTML;
bool skipStyle;
bool skipImages;
bool skipLinks;
bool escape;
};
// render markdown to HTML -- assumes UTF-8 encoding
Error markdownToHTML(const FilePath& markdownFile,
const Extensions& extensions,
const HTMLOptions& htmlOptions,
const FilePath& htmlFile);
// render markdown to HTML -- assumes UTF-8 encoding
Error markdownToHTML(const FilePath& markdownFile,
const Extensions& extensions,
const HTMLOptions& htmlOptions,
std::string* pHTMLOutput);
// render markdown to HTML -- assumes UTF-8 encoding
Error markdownToHTML(const std::string& markdownInput,
const Extensions& extensions,
const HTMLOptions& htmlOptions,
std::string* pHTMLOutput);
} // namespace markdown
} // namespace core
#endif // CORE_MARKDOWN_MARKDOWN_HPP
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include "ADIS16477.hpp"
#include <px4_getopt.h>
#define ADIS16477_DEVICE_PATH_ACCEL "/dev/adis16477_accel"
#define ADIS16477_DEVICE_PATH_GYRO "/dev/adis16477_gyro"
extern "C" { __EXPORT int adis16477_main(int argc, char *argv[]); }
/**
* Local functions in support of the shell command.
*/
namespace adis16477
{
ADIS16477 *g_dev;
void start(enum Rotation rotation);
void test();
void reset();
void info();
void usage();
/**
* Start the driver.
*/
void
start(enum Rotation rotation)
{
int fd = -1;
if (g_dev != nullptr)
/* if already started, the still command succeeded */
{
errx(0, "already started");
}
/* create the driver */
#if defined(PX4_SPIDEV_ADIS16477)
g_dev = new ADIS16477(PX4_SPI_BUS_SENSOR1, ADIS16477_DEVICE_PATH_ACCEL, ADIS16477_DEVICE_PATH_GYRO,
PX4_SPIDEV_ADIS16477, rotation);
#else
PX4_ERR("External SPI not available");
exit(0);
#endif
if (g_dev == nullptr) {
goto fail;
}
if (OK != (g_dev)->init()) {
goto fail;
}
/* set the poll rate to default, starts automatic data collection */
fd = px4_open(ADIS16477_DEVICE_PATH_ACCEL, O_RDONLY);
if (fd < 0) {
goto fail;
}
if (px4_ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0) {
goto fail;
}
px4_close(fd);
exit(0);
fail:
if (g_dev != nullptr) {
delete g_dev;
g_dev = nullptr;
}
errx(1, "driver start failed");
}
/**
* Perform some basic functional tests on the driver;
* make sure we can collect data from the sensor in polled
* and automatic modes.
*/
void
test()
{
sensor_accel_s a_report{};
sensor_gyro_s g_report{};
ssize_t sz;
/* get the driver */
int fd = px4_open(ADIS16477_DEVICE_PATH_ACCEL, O_RDONLY);
if (fd < 0) {
err(1, "%s open failed", ADIS16477_DEVICE_PATH_ACCEL);
}
/* get the gyro driver */
int fd_gyro = px4_open(ADIS16477_DEVICE_PATH_GYRO, O_RDONLY);
if (fd_gyro < 0) {
err(1, "%s open failed", ADIS16477_DEVICE_PATH_GYRO);
}
/* do a simple demand read */
sz = read(fd, &a_report, sizeof(a_report));
if (sz != sizeof(a_report)) {
PX4_ERR("ret: %d, expected: %d", sz, sizeof(a_report));
err(1, "immediate acc read failed");
}
print_message(a_report);
/* do a simple demand read */
sz = px4_read(fd_gyro, &g_report, sizeof(g_report));
if (sz != sizeof(g_report)) {
warnx("ret: %d, expected: %d", sz, sizeof(g_report));
err(1, "immediate gyro read failed");
}
print_message(g_report);
px4_close(fd_gyro);
px4_close(fd);
reset();
errx(0, "PASS");
}
/**
* Reset the driver.
*/
void
reset()
{
int fd = px4_open(ADIS16477_DEVICE_PATH_ACCEL, O_RDONLY);
if (fd < 0) {
err(1, "open failed");
}
if (px4_ioctl(fd, SENSORIOCRESET, 0) < 0) {
err(1, "driver reset failed");
}
if (px4_ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0) {
err(1, "driver poll restart failed");
}
px4_close(fd);
exit(0);
}
/**
* Print a little info about the driver.
*/
void
info()
{
if (g_dev == nullptr) {
errx(1, "driver not running");
}
printf("state @ %p\n", g_dev);
g_dev->print_info();
exit(0);
}
void
usage()
{
PX4_INFO("missing command: try 'start', 'test', 'info', 'reset'");
PX4_INFO("options:");
PX4_INFO(" -R rotation");
}
}
// namespace
int
adis16477_main(int argc, char *argv[])
{
enum Rotation rotation = ROTATION_NONE;
int myoptind = 1;
int ch;
const char *myoptarg = nullptr;
/* start options */
while ((ch = px4_getopt(argc, argv, "R:", &myoptind, &myoptarg)) != EOF) {
switch (ch) {
case 'R':
rotation = (enum Rotation)atoi(optarg);
break;
default:
adis16477::usage();
return 0;
}
}
if (myoptind >= argc) {
adis16477::usage();
return -1;
}
const char *verb = argv[myoptind];
/*
* Start/load the driver.
*/
if (!strcmp(verb, "start")) {
adis16477::start(rotation);
}
/*
* Test the driver/device.
*/
if (!strcmp(verb, "test")) {
adis16477::test();
}
/*
* Reset the driver.
*/
if (!strcmp(verb, "reset")) {
adis16477::reset();
}
/*
* Print driver information.
*/
if (!strcmp(verb, "info")) {
adis16477::info();
}
adis16477::usage();
exit(1);
}
<commit_msg>Fixed using myoptarg instead of optarg<commit_after>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include "ADIS16477.hpp"
#include <px4_getopt.h>
#define ADIS16477_DEVICE_PATH_ACCEL "/dev/adis16477_accel"
#define ADIS16477_DEVICE_PATH_GYRO "/dev/adis16477_gyro"
extern "C" { __EXPORT int adis16477_main(int argc, char *argv[]); }
/**
* Local functions in support of the shell command.
*/
namespace adis16477
{
ADIS16477 *g_dev;
void start(enum Rotation rotation);
void test();
void reset();
void info();
void usage();
/**
* Start the driver.
*/
void
start(enum Rotation rotation)
{
int fd = -1;
if (g_dev != nullptr)
/* if already started, the still command succeeded */
{
errx(0, "already started");
}
/* create the driver */
#if defined(PX4_SPIDEV_ADIS16477)
g_dev = new ADIS16477(PX4_SPI_BUS_SENSOR1, ADIS16477_DEVICE_PATH_ACCEL, ADIS16477_DEVICE_PATH_GYRO,
PX4_SPIDEV_ADIS16477, rotation);
#else
PX4_ERR("External SPI not available");
exit(0);
#endif
if (g_dev == nullptr) {
goto fail;
}
if (OK != (g_dev)->init()) {
goto fail;
}
/* set the poll rate to default, starts automatic data collection */
fd = px4_open(ADIS16477_DEVICE_PATH_ACCEL, O_RDONLY);
if (fd < 0) {
goto fail;
}
if (px4_ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0) {
goto fail;
}
px4_close(fd);
exit(0);
fail:
if (g_dev != nullptr) {
delete g_dev;
g_dev = nullptr;
}
errx(1, "driver start failed");
}
/**
* Perform some basic functional tests on the driver;
* make sure we can collect data from the sensor in polled
* and automatic modes.
*/
void
test()
{
sensor_accel_s a_report{};
sensor_gyro_s g_report{};
ssize_t sz;
/* get the driver */
int fd = px4_open(ADIS16477_DEVICE_PATH_ACCEL, O_RDONLY);
if (fd < 0) {
err(1, "%s open failed", ADIS16477_DEVICE_PATH_ACCEL);
}
/* get the gyro driver */
int fd_gyro = px4_open(ADIS16477_DEVICE_PATH_GYRO, O_RDONLY);
if (fd_gyro < 0) {
err(1, "%s open failed", ADIS16477_DEVICE_PATH_GYRO);
}
/* do a simple demand read */
sz = read(fd, &a_report, sizeof(a_report));
if (sz != sizeof(a_report)) {
PX4_ERR("ret: %d, expected: %d", sz, sizeof(a_report));
err(1, "immediate acc read failed");
}
print_message(a_report);
/* do a simple demand read */
sz = px4_read(fd_gyro, &g_report, sizeof(g_report));
if (sz != sizeof(g_report)) {
warnx("ret: %d, expected: %d", sz, sizeof(g_report));
err(1, "immediate gyro read failed");
}
print_message(g_report);
px4_close(fd_gyro);
px4_close(fd);
reset();
errx(0, "PASS");
}
/**
* Reset the driver.
*/
void
reset()
{
int fd = px4_open(ADIS16477_DEVICE_PATH_ACCEL, O_RDONLY);
if (fd < 0) {
err(1, "open failed");
}
if (px4_ioctl(fd, SENSORIOCRESET, 0) < 0) {
err(1, "driver reset failed");
}
if (px4_ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0) {
err(1, "driver poll restart failed");
}
px4_close(fd);
exit(0);
}
/**
* Print a little info about the driver.
*/
void
info()
{
if (g_dev == nullptr) {
errx(1, "driver not running");
}
printf("state @ %p\n", g_dev);
g_dev->print_info();
exit(0);
}
void
usage()
{
PX4_INFO("missing command: try 'start', 'test', 'info', 'reset'");
PX4_INFO("options:");
PX4_INFO(" -R rotation");
}
}
// namespace
int
adis16477_main(int argc, char *argv[])
{
enum Rotation rotation = ROTATION_NONE;
int myoptind = 1;
int ch;
const char *myoptarg = nullptr;
/* start options */
while ((ch = px4_getopt(argc, argv, "R:", &myoptind, &myoptarg)) != EOF) {
switch (ch) {
case 'R':
rotation = (enum Rotation)atoi(myoptarg);
break;
default:
adis16477::usage();
return 0;
}
}
if (myoptind >= argc) {
adis16477::usage();
return -1;
}
const char *verb = argv[myoptind];
/*
* Start/load the driver.
*/
if (!strcmp(verb, "start")) {
adis16477::start(rotation);
}
/*
* Test the driver/device.
*/
if (!strcmp(verb, "test")) {
adis16477::test();
}
/*
* Reset the driver.
*/
if (!strcmp(verb, "reset")) {
adis16477::reset();
}
/*
* Print driver information.
*/
if (!strcmp(verb, "info")) {
adis16477::info();
}
adis16477::usage();
exit(1);
}
<|endoftext|> |
<commit_before>#ifndef __EXTENSION_EXPLICIT_COUNTERSTRATEGY_HPP
#define __EXTENSION_EXPLICIT_COUNTERSTRATEGY_HPP
#include "gr1context.hpp"
#include <string>
/**
* A class that computes an explicit state counterstrategy for an unrealizable specification
*/
template<class T> class XExtractExplicitCounterStrategy : public T {
protected:
// New variables
std::string outputFilename;
// Inherited stuff used
using T::mgr;
using T::strategyDumpingData;
using T::livenessGuarantees;
using T::livenessAssumptions;
using T::varVectorPre;
using T::varVectorPost;
using T::varCubePostOutput;
using T::varCubePostInput;
using T::varCubePreOutput;
using T::varCubePreInput;
using T::varCubePre;
using T::safetyEnv;
using T::safetySys;
using T::winningPositions;
using T::initEnv;
using T::initSys;
using T::preVars;
using T::postVars;
using T::variableTypes;
using T::variables;
using T::variableNames;
using T::realizable;
using T::determinize;
XExtractExplicitCounterStrategy<T>(std::list<std::string> &filenames) : T(filenames) {
if (filenames.size()==0) {
outputFilename = "";
} else {
outputFilename = filenames.front();
filenames.pop_front();
}
}
public:
/**
* @brief Compute and print out (to stdout) an explicit-state counter strategy that is winning for
* the environment. The output is compatible with the old JTLV output of LTLMoP.
* This function requires that the unrealizability of the specification has already been
* detected and that the variables "strategyDumpingData" and
* "winningPositions" have been filled by the synthesis algorithm with meaningful data.
* @param outputStream - Where the strategy shall be printed to.
*/
void execute() {
T::execute();
if (!realizable) {
if (outputFilename=="") {
computeAndPrintExplicitStateStrategy(std::cout);
} else {
std::ofstream of(outputFilename.c_str());
if (of.fail()) {
SlugsException ex(false);
ex << "Error: Could not open output file'" << outputFilename << "\n";
throw ex;
}
computeAndPrintExplicitStateStrategy(of);
if (of.fail()) {
SlugsException ex(false);
ex << "Error: Writing to output file'" << outputFilename << "failed. \n";
throw ex;
}
of.close();
}
}
}
void computeAndPrintExplicitStateStrategy(std::ostream &outputStream) {
// We don't want any reordering from this point onwards, as
// the BDD manipulations from this point onwards are 'kind of simple'.
mgr.setAutomaticOptimisation(false);
// List of states in existance so far. The first map
// maps from a BF node pointer (for the pre variable valuation) and a goal
// to a state number. The vector then contains the concrete valuation.
std::map<std::pair<size_t, std::pair<unsigned int, unsigned int> >, unsigned int > lookupTableForPastStates;
std::vector<BF> bfsUsedInTheLookupTable;
std::list<std::pair<size_t, std::pair<unsigned int, unsigned int> > > todoList;
// Prepare positional strategies for the individual goals
std::vector<std::vector<BF> > positionalStrategiesForTheIndividualGoals(livenessAssumptions.size());
for (unsigned int i=0;i<livenessAssumptions.size();i++) {
//BF casesCovered = mgr.constantFalse();
std::vector<BF> strategy(livenessGuarantees.size()+1);
for (unsigned int j=0;j<livenessGuarantees.size()+1;j++) {
strategy[j] = mgr.constantFalse();
}
for (auto it = strategyDumpingData.begin();it!=strategyDumpingData.end();it++) {
if (boost::get<0>(*it) == i) {
//Have to cover each guarantee (since the winning strategy depends on which guarantee is being pursued)
//Essentially, the choice of which guarantee to pursue can be thought of as a system "move".
//The environment always to chooses that prevent the appropriate guarantee.
if (strategy[boost::get<1>(*it)].isFalse()) {
strategy[boost::get<1>(*it)] = boost::get<2>(*it);
}
}
}
positionalStrategiesForTheIndividualGoals[i] = strategy;
//BF_newDumpDot(*this,strategy,"PreInput PreOutput PostInput PostOutput","/tmp/generalStrategy.dot");
}
// Prepare initial to-do list from the allowed initial states. Select a single initial input valuation.
BF todoInit = (winningPositions & initEnv & initSys);
while (!(todoInit.isFalse())) {
BF concreteState = determinize(todoInit,preVars);
//find which liveness guarantee is being prevented (finds the first liveness in order specified)
unsigned int found_j_index = 0;
for (unsigned int j=0;j<livenessGuarantees.size();j++) {
if (!(concreteState & !livenessGuarantees[j] & positionalStrategiesForTheIndividualGoals[0][j]).isFalse()) {
found_j_index = j;
break;
}
}
std::pair<size_t, std::pair<unsigned int, unsigned int> > lookup = std::pair<size_t, std::pair<unsigned int, unsigned int> >(concreteState.getHashCode(),std::pair<unsigned int, unsigned int>(0,found_j_index));
lookupTableForPastStates[lookup] = bfsUsedInTheLookupTable.size();
bfsUsedInTheLookupTable.push_back(concreteState);
//from now on use the same initial input valuation (but consider all other initial output valuations)
todoInit &= concreteState.ExistAbstract(varCubePreOutput) & !concreteState;
todoList.push_back(lookup);
}
// Extract strategy
while (todoList.size()>0) {
std::pair<size_t, std::pair<unsigned int, unsigned int> > current = todoList.front();
todoList.pop_front();
unsigned int stateNum = lookupTableForPastStates[current];
BF currentPossibilities = bfsUsedInTheLookupTable[stateNum];
// Print state information
outputStream << "State " << stateNum << " with rank (" << current.second.first << "," << current.second.second << ") -> <";
bool first = true;
for (unsigned int i=0;i<variables.size();i++) {
if (variableTypes[i] < PostInput) {
if (first) {
first = false;
} else {
outputStream << ", ";
}
outputStream << variableNames[i] << ":";
outputStream << (((currentPossibilities & variables[i]).isFalse())?"0":"1");
}
}
outputStream << ">\n\tWith successors : ";
first = true;
currentPossibilities &= positionalStrategiesForTheIndividualGoals[current.second.first][current.second.second];
BF remainingTransitions = ((currentPossibilities & safetySys).ExistAbstract(varCubePre));
//check if there exists inputs that force a safety violation in the next time step
if ((remainingTransitions & safetySys).isFalse() | !(remainingTransitions & ((mgr.constantFalse())).UnivAbstract(varCubePostOutput).ExistAbstract(varCubePostInput)).isFalse()) {
addDeadlocked(remainingTransitions & ((mgr.constantFalse())).UnivAbstract(varCubePostOutput).ExistAbstract(varCubePostInput), current, bfsUsedInTheLookupTable, lookupTableForPastStates, outputStream);
} else {
BF inputCaptured = mgr.constantTrue();
// Switching goals
while (!(remainingTransitions & safetySys).isFalse()) {
BF newCombination;
if ((remainingTransitions & livenessAssumptions[current.second.first]).isFalse()) {
newCombination = determinize(remainingTransitions & safetySys, postVars);
} else {
newCombination = determinize((remainingTransitions & safetySys & livenessAssumptions[current.second.first]),postVars);
}
// Jump as much forward in the liveness assumption list as possible ("stuttering avoidance")
unsigned int nextLivenessAssumption = current.second.first;
bool firstTry = true;
while (((nextLivenessAssumption != current.second.first) | firstTry) && !((livenessAssumptions[nextLivenessAssumption] & newCombination).isFalse())) {
nextLivenessAssumption = (nextLivenessAssumption + 1) % livenessAssumptions.size();
firstTry = false;
}
//Mark which input has been captured by this case. Use the same input for other successors
inputCaptured = newCombination.ExistAbstract(varCubePostOutput);
remainingTransitions &= inputCaptured;
remainingTransitions &= !newCombination;
newCombination = newCombination.SwapVariables(varVectorPre,varVectorPost);
if (nextLivenessAssumption != current.second.second) {
unsigned int found_j_index = 0;
for (unsigned int j=0;j<livenessGuarantees.size();j++) {
if (!(newCombination & !livenessGuarantees[j] & positionalStrategiesForTheIndividualGoals[current.second.first][j]).isFalse()) {
found_j_index = j;
break;
}
}
current.second.second = found_j_index;
}
unsigned int tn;
std::pair<size_t, std::pair<unsigned int, unsigned int> > target;
target = std::pair<size_t, std::pair<unsigned int, unsigned int> >(newCombination.getHashCode(),std::pair<unsigned int, unsigned int>(nextLivenessAssumption, current.second.second));
if (lookupTableForPastStates.count(target)==0) {
tn = lookupTableForPastStates[target] = bfsUsedInTheLookupTable.size();
bfsUsedInTheLookupTable.push_back(newCombination);
todoList.push_back(target);
} else {
tn = lookupTableForPastStates[target];
}
// Print
if (first) {
first = false;
} else {
outputStream << ", ";
}
outputStream << tn;
}
}
outputStream << "\n";
}
}
//This function adds a new successor-less "state" that captures the deadlock-causing input values
//The outputvalues are omitted (indeed, no valuation exists that satisfies the system safeties)
//Format compatible with JTLV counterstrategy
void addDeadlocked(BF remainingTransitions, std::pair<size_t, std::pair<unsigned int, unsigned int> > current, std::vector<BF> &bfsUsedInTheLookupTable, std::map<std::pair<size_t, std::pair<unsigned int, unsigned int> >, unsigned int > &lookupTableForPastStates, std::ostream &outputStream) {
BF newCombination;
if ((remainingTransitions & livenessAssumptions[current.second.first]).isFalse()) {
newCombination = determinize(remainingTransitions,postVars) ;
} else {
newCombination = determinize((remainingTransitions & livenessAssumptions[current.second.first]),postVars) ;
}
newCombination = newCombination.SwapVariables(varVectorPre,varVectorPost);
newCombination = newCombination.UnivAbstract(varCubePreInput);
std::pair<size_t, std::pair<unsigned int, unsigned int> > target = std::pair<size_t, std::pair<unsigned int, unsigned int> >(newCombination.getHashCode(),std::pair<unsigned int, unsigned int>(current.second.first, current.second.second));
unsigned int tn;
if (lookupTableForPastStates.count(target)==0) {
tn = lookupTableForPastStates[target] = bfsUsedInTheLookupTable.size();
bfsUsedInTheLookupTable.push_back(newCombination);
outputStream << tn << "\n";
//Note that since we are printing here, we usually end up with the states being printed out of order.
//TOTO: print in order
outputStream << "State " << tn << " with rank (" << current.second.first << "," << current.second.second << ") -> <";
bool first = true;
for (unsigned int i=0;i<variables.size();i++) {
if (variableTypes[i] < PreOutput) {
if (first) {
first = false;
} else {
outputStream << ", ";
}
outputStream << variableNames[i] << ":";
outputStream << (((newCombination & variables[i]).isFalse())?"0":"1");
}
}
outputStream << ">\n\tWith no successors.";
} else {
tn = lookupTableForPastStates[target];
outputStream << tn;
}
}
static GR1Context* makeInstance(std::list<std::string> &filenames) {
return new XExtractExplicitCounterStrategy<T>(filenames);
}
};
#endif
<commit_msg>env move for deadlock has to obey safetyEnv<commit_after>#ifndef __EXTENSION_EXPLICIT_COUNTERSTRATEGY_HPP
#define __EXTENSION_EXPLICIT_COUNTERSTRATEGY_HPP
#include "gr1context.hpp"
#include <string>
/**
* A class that computes an explicit state counterstrategy for an unrealizable specification
*/
template<class T> class XExtractExplicitCounterStrategy : public T {
protected:
// New variables
std::string outputFilename;
// Inherited stuff used
using T::mgr;
using T::strategyDumpingData;
using T::livenessGuarantees;
using T::livenessAssumptions;
using T::varVectorPre;
using T::varVectorPost;
using T::varCubePostOutput;
using T::varCubePostInput;
using T::varCubePreOutput;
using T::varCubePreInput;
using T::varCubePre;
using T::safetyEnv;
using T::safetySys;
using T::winningPositions;
using T::initEnv;
using T::initSys;
using T::preVars;
using T::postVars;
using T::variableTypes;
using T::variables;
using T::variableNames;
using T::realizable;
using T::determinize;
XExtractExplicitCounterStrategy<T>(std::list<std::string> &filenames) : T(filenames) {
if (filenames.size()==0) {
outputFilename = "";
} else {
outputFilename = filenames.front();
filenames.pop_front();
}
}
public:
/**
* @brief Compute and print out (to stdout) an explicit-state counter strategy that is winning for
* the environment. The output is compatible with the old JTLV output of LTLMoP.
* This function requires that the unrealizability of the specification has already been
* detected and that the variables "strategyDumpingData" and
* "winningPositions" have been filled by the synthesis algorithm with meaningful data.
* @param outputStream - Where the strategy shall be printed to.
*/
void execute() {
T::execute();
if (!realizable) {
if (outputFilename=="") {
computeAndPrintExplicitStateStrategy(std::cout);
} else {
std::ofstream of(outputFilename.c_str());
if (of.fail()) {
SlugsException ex(false);
ex << "Error: Could not open output file'" << outputFilename << "\n";
throw ex;
}
computeAndPrintExplicitStateStrategy(of);
if (of.fail()) {
SlugsException ex(false);
ex << "Error: Writing to output file'" << outputFilename << "failed. \n";
throw ex;
}
of.close();
}
}
}
void computeAndPrintExplicitStateStrategy(std::ostream &outputStream) {
// We don't want any reordering from this point onwards, as
// the BDD manipulations from this point onwards are 'kind of simple'.
mgr.setAutomaticOptimisation(false);
// List of states in existance so far. The first map
// maps from a BF node pointer (for the pre variable valuation) and a goal
// to a state number. The vector then contains the concrete valuation.
std::map<std::pair<size_t, std::pair<unsigned int, unsigned int> >, unsigned int > lookupTableForPastStates;
std::vector<BF> bfsUsedInTheLookupTable;
std::list<std::pair<size_t, std::pair<unsigned int, unsigned int> > > todoList;
// Prepare positional strategies for the individual goals
std::vector<std::vector<BF> > positionalStrategiesForTheIndividualGoals(livenessAssumptions.size());
for (unsigned int i=0;i<livenessAssumptions.size();i++) {
//BF casesCovered = mgr.constantFalse();
std::vector<BF> strategy(livenessGuarantees.size()+1);
for (unsigned int j=0;j<livenessGuarantees.size()+1;j++) {
strategy[j] = mgr.constantFalse();
}
for (auto it = strategyDumpingData.begin();it!=strategyDumpingData.end();it++) {
if (boost::get<0>(*it) == i) {
//Have to cover each guarantee (since the winning strategy depends on which guarantee is being pursued)
//Essentially, the choice of which guarantee to pursue can be thought of as a system "move".
//The environment always to chooses that prevent the appropriate guarantee.
if (strategy[boost::get<1>(*it)].isFalse()) {
strategy[boost::get<1>(*it)] = boost::get<2>(*it);
}
}
}
positionalStrategiesForTheIndividualGoals[i] = strategy;
//BF_newDumpDot(*this,strategy,"PreInput PreOutput PostInput PostOutput","/tmp/generalStrategy.dot");
}
// Prepare initial to-do list from the allowed initial states. Select a single initial input valuation.
BF todoInit = (winningPositions & initEnv & initSys);
while (!(todoInit.isFalse())) {
BF concreteState = determinize(todoInit,preVars);
//find which liveness guarantee is being prevented (finds the first liveness in order specified)
unsigned int found_j_index = 0;
for (unsigned int j=0;j<livenessGuarantees.size();j++) {
if (!(concreteState & !livenessGuarantees[j] & positionalStrategiesForTheIndividualGoals[0][j]).isFalse()) {
found_j_index = j;
break;
}
}
std::pair<size_t, std::pair<unsigned int, unsigned int> > lookup = std::pair<size_t, std::pair<unsigned int, unsigned int> >(concreteState.getHashCode(),std::pair<unsigned int, unsigned int>(0,found_j_index));
lookupTableForPastStates[lookup] = bfsUsedInTheLookupTable.size();
bfsUsedInTheLookupTable.push_back(concreteState);
//from now on use the same initial input valuation (but consider all other initial output valuations)
todoInit &= concreteState.ExistAbstract(varCubePreOutput) & !concreteState;
todoList.push_back(lookup);
}
// Extract strategy
while (todoList.size()>0) {
std::pair<size_t, std::pair<unsigned int, unsigned int> > current = todoList.front();
todoList.pop_front();
unsigned int stateNum = lookupTableForPastStates[current];
BF currentPossibilities = bfsUsedInTheLookupTable[stateNum];
// Print state information
outputStream << "State " << stateNum << " with rank (" << current.second.first << "," << current.second.second << ") -> <";
bool first = true;
for (unsigned int i=0;i<variables.size();i++) {
if (variableTypes[i] < PostInput) {
if (first) {
first = false;
} else {
outputStream << ", ";
}
outputStream << variableNames[i] << ":";
outputStream << (((currentPossibilities & variables[i]).isFalse())?"0":"1");
}
}
outputStream << ">\n\tWith successors : ";
first = true;
currentPossibilities &= positionalStrategiesForTheIndividualGoals[current.second.first][current.second.second];
BF remainingTransitions = ((currentPossibilities & safetyEnv).ExistAbstract(varCubePre));
BF safetyEnvPost = safetyEnv.SwapVariables(varVectorPre,varVectorPost);
//check if there exists inputs that force a safety violation in the next time step
if ((remainingTransitions & safetySys).isFalse()) {
addDeadlocked(remainingTransitions, current, bfsUsedInTheLookupTable, lookupTableForPastStates, outputStream);
} else if (!(remainingTransitions & safetyEnvPost & (safetyEnv&!safetySys).UnivAbstract(varCubePostOutput).ExistAbstract(varCubePostInput)).isFalse()) {
addDeadlocked(remainingTransitions & safetyEnvPost & (safetyEnv&!safetySys).UnivAbstract(varCubePostOutput).ExistAbstract(varCubePostInput), current, bfsUsedInTheLookupTable, lookupTableForPastStates, outputStream);
} else {
BF inputCaptured = mgr.constantTrue();
// Switching goals
while (!(remainingTransitions & safetySys).isFalse()) {
BF newCombination;
if ((remainingTransitions & livenessAssumptions[current.second.first]).isFalse()) {
newCombination = determinize(remainingTransitions & safetySys, postVars);
} else {
newCombination = determinize((remainingTransitions & safetySys & livenessAssumptions[current.second.first]),postVars);
}
// Jump as much forward in the liveness assumption list as possible ("stuttering avoidance")
unsigned int nextLivenessAssumption = current.second.first;
bool firstTry = true;
while (((nextLivenessAssumption != current.second.first) | firstTry) && !((livenessAssumptions[nextLivenessAssumption] & newCombination).isFalse())) {
nextLivenessAssumption = (nextLivenessAssumption + 1) % livenessAssumptions.size();
firstTry = false;
}
//Mark which input has been captured by this case. Use the same input for other successors
remainingTransitions &= newCombination.ExistAbstract(varCubePreOutput) & !newCombination;
newCombination = newCombination.SwapVariables(varVectorPre,varVectorPost);
if (nextLivenessAssumption != current.second.second) {
unsigned int found_j_index = 0;
for (unsigned int j=0;j<livenessGuarantees.size();j++) {
if (!(newCombination & !livenessGuarantees[j] & positionalStrategiesForTheIndividualGoals[current.second.first][j]).isFalse()) {
found_j_index = j;
break;
}
}
current.second.second = found_j_index;
}
unsigned int tn;
std::pair<size_t, std::pair<unsigned int, unsigned int> > target;
target = std::pair<size_t, std::pair<unsigned int, unsigned int> >(newCombination.getHashCode(),std::pair<unsigned int, unsigned int>(nextLivenessAssumption, current.second.second));
if (lookupTableForPastStates.count(target)==0) {
tn = lookupTableForPastStates[target] = bfsUsedInTheLookupTable.size();
bfsUsedInTheLookupTable.push_back(newCombination);
todoList.push_back(target);
} else {
tn = lookupTableForPastStates[target];
}
// Print
if (first) {
first = false;
} else {
outputStream << ", ";
}
outputStream << tn;
}
}
outputStream << "\n";
}
}
//This function adds a new successor-less "state" that captures the deadlock-causing input values
//The outputvalues are omitted (indeed, no valuation exists that satisfies the system safeties)
//Format compatible with JTLV counterstrategy
void addDeadlocked(BF remainingTransitions, std::pair<size_t, std::pair<unsigned int, unsigned int> > current, std::vector<BF> &bfsUsedInTheLookupTable, std::map<std::pair<size_t, std::pair<unsigned int, unsigned int> >, unsigned int > &lookupTableForPastStates, std::ostream &outputStream) {
if (!(remainingTransitions & livenessAssumptions[current.second.first]).isFalse()) {
remainingTransitions &= livenessAssumptions[current.second.first];
}
BF newCombination = determinize(remainingTransitions & (!safetySys).UnivAbstract(varCubePostOutput), postVars) ;
newCombination = newCombination.SwapVariables(varVectorPre,varVectorPost) & safetyEnv;
newCombination = newCombination.ExistAbstract(varCubePreOutput);
std::pair<size_t, std::pair<unsigned int, unsigned int> > target = std::pair<size_t, std::pair<unsigned int, unsigned int> >(newCombination.getHashCode(),std::pair<unsigned int, unsigned int>(current.second.first, current.second.second));
unsigned int tn;
if (lookupTableForPastStates.count(target)==0) {
tn = lookupTableForPastStates[target] = bfsUsedInTheLookupTable.size();
bfsUsedInTheLookupTable.push_back(newCombination);
outputStream << tn << "\n";
//Note that since we are printing here, we usually end up with the states being printed out of order.
//TOTO: print in order
outputStream << "State " << tn << " with rank (" << current.second.first << "," << current.second.second << ") -> <";
bool first = true;
for (unsigned int i=0;i<variables.size();i++) {
if (variableTypes[i] < PreOutput) {
if (first) {
first = false;
} else {
outputStream << ", ";
}
outputStream << variableNames[i] << ":";
outputStream << (((newCombination & variables[i]).isFalse())?"0":"1");
}
}
outputStream << ">\n\tWith no successors.";
} else {
tn = lookupTableForPastStates[target];
outputStream << tn;
}
}
static GR1Context* makeInstance(std::list<std::string> &filenames) {
return new XExtractExplicitCounterStrategy<T>(filenames);
}
};
#endif
<|endoftext|> |
<commit_before>#ifndef EBITEN_GRAPHICS_DETAIL_OPENGL_DEVICE_HPP
#define EBITEN_GRAPHICS_DETAIL_OPENGL_DEVICE_HPP
#include "ebiten/frames/frame.hpp"
#include "ebiten/graphics/detail/opengl/graphics_context.hpp"
#include "ebiten/graphics/detail/opengl/initialize_opengl.hpp"
#include "ebiten/graphics/detail/opengl/texture_factory.hpp"
#include "ebiten/graphics/sprite.hpp"
#include "ebiten/util/noncopyable.hpp"
#include <OpenGL/gl.h>
#include <cassert>
#include <functional>
namespace ebiten {
namespace graphics {
namespace detail {
class device : private ebiten::util::noncopyable {
public:
typedef frames::frame frame_type;
typedef detail::texture_factory texture_factory_type;
typedef detail::graphics_context graphics_context_type;
private:
std::size_t const screen_width_;
std::size_t const screen_height_;
std::size_t const window_scale_;
std::function<void(device&)> drawing_sprites_func_;
frames::frame frame_;
graphics_context_type graphics_context_;
texture_factory_type texture_factory_;
std::unique_ptr<texture const> offscreen_texture_;
GLuint framebuffer_;
public:
device(std::size_t screen_width,
std::size_t screen_height,
std::size_t window_scale,
std::function<void(device&)> const& drawing_sprites_func)
: screen_width_(screen_width),
screen_height_(screen_height),
window_scale_(window_scale),
drawing_sprites_func_(drawing_sprites_func),
frame_(screen_width * window_scale, screen_height * window_scale),
graphics_context_(),
texture_factory_() {
initialize_opengl(this->frame_, std::bind(&device::update, this));
this->offscreen_texture_ = texture_factory().create(screen_width, screen_height);
this->framebuffer_ = generate_frame_buffer();
::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, this->framebuffer_);
::glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
GL_COLOR_ATTACHMENT0_EXT,
GL_TEXTURE_2D,
this->offscreen_texture_->id(),
0);
if (::glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) != GL_FRAMEBUFFER_COMPLETE_EXT) {
throw std::runtime_error("framebuffer is not supported completely");
}
::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}
void
update() {
float const offscreen_width = static_cast<float>(this->offscreen_texture_->width());
float const offscreen_height = static_cast<float>(this->offscreen_texture_->height());
float const offscreen_tu = offscreen_width / this->offscreen_texture_->texture_width();
float const offscreen_tv = offscreen_height / this->offscreen_texture_->texture_height();
float const offscreen_vertex[4][3] = {{0, 0, 0},
{offscreen_width, 0, 0},
{offscreen_width, offscreen_height, 0},
{0, offscreen_height, 0}};
float const window_scale_f = static_cast<float>(this->window_scale_);
float const offscreen_geo[] = {window_scale_f, 0, 0, 0,
0, window_scale_f, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1};
// render sprites to the offscreen
::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, this->framebuffer_);
::glClearColor(0, 0, 0, 1);
::glClear(GL_COLOR_BUFFER_BIT);
::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
::glEnable(GL_TEXTURE_2D);
::glEnable(GL_BLEND);
::glViewport(0, 0, this->screen_width_, this->screen_height_);
::glMatrixMode(GL_PROJECTION);
::glLoadIdentity();
::glOrtho(0, this->screen_width_, 0, this->screen_height_, 0, 1);
this->drawing_sprites_func_(*this);
::glFlush();
::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
// render the offscreen to the screen
::glClearColor(0, 0, 0, 1);
::glClear(GL_COLOR_BUFFER_BIT);
::glEnable(GL_TEXTURE_2D);
::glDisable(GL_BLEND);
::glViewport(0, 0,
this->screen_width_ * this->window_scale_,
this->screen_height_ * this->window_scale_);
::glMatrixMode(GL_PROJECTION);
::glLoadIdentity();
::glOrtho(0, this->screen_width_ * this->window_scale_,
this->screen_height_ * this->window_scale_, 0,
0, 1);
::glMatrixMode(GL_MODELVIEW);
::glLoadMatrixf(offscreen_geo);
::glBindTexture(GL_TEXTURE_2D, this->offscreen_texture_->id());
::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
{
::glBegin(GL_QUADS);
::glTexCoord2f(0, 0);
::glVertex3fv(offscreen_vertex[0]);
::glTexCoord2f(offscreen_tu, 0);
::glVertex3fv(offscreen_vertex[1]);
::glTexCoord2f(offscreen_tu, offscreen_tv);
::glVertex3fv(offscreen_vertex[2]);
::glTexCoord2f(0, offscreen_tv);
::glVertex3fv(offscreen_vertex[3]);
::glEnd();
}
::glBindTexture(GL_TEXTURE_2D, 0);
::glFlush();
}
frame_type&
frame() {
return this->frame_;
}
graphics_context_type&
graphics_context() {
return this->graphics_context_;
}
texture_factory_type&
texture_factory() {
return this->texture_factory_;
}
private:
static GLuint
generate_frame_buffer() {
GLuint framebuffer = 0;
::glGenFramebuffersEXT(1, &framebuffer);
assert(framebuffer);
return framebuffer;
}
};
}
}
}
#endif
<commit_msg>Removed device#generate_framebuffer<commit_after>#ifndef EBITEN_GRAPHICS_DETAIL_OPENGL_DEVICE_HPP
#define EBITEN_GRAPHICS_DETAIL_OPENGL_DEVICE_HPP
#include "ebiten/frames/frame.hpp"
#include "ebiten/graphics/detail/opengl/graphics_context.hpp"
#include "ebiten/graphics/detail/opengl/initialize_opengl.hpp"
#include "ebiten/graphics/detail/opengl/texture_factory.hpp"
#include "ebiten/graphics/sprite.hpp"
#include "ebiten/util/noncopyable.hpp"
#include <OpenGL/gl.h>
#include <cassert>
#include <functional>
namespace ebiten {
namespace graphics {
namespace detail {
class device : private ebiten::util::noncopyable {
public:
typedef frames::frame frame_type;
typedef detail::texture_factory texture_factory_type;
typedef detail::graphics_context graphics_context_type;
private:
std::size_t const screen_width_;
std::size_t const screen_height_;
std::size_t const window_scale_;
std::function<void(device&)> drawing_sprites_func_;
frames::frame frame_;
graphics_context_type graphics_context_;
texture_factory_type texture_factory_;
std::unique_ptr<texture const> offscreen_texture_;
GLuint framebuffer_;
public:
device(std::size_t screen_width,
std::size_t screen_height,
std::size_t window_scale,
std::function<void(device&)> const& drawing_sprites_func)
: screen_width_(screen_width),
screen_height_(screen_height),
window_scale_(window_scale),
drawing_sprites_func_(drawing_sprites_func),
frame_(screen_width * window_scale, screen_height * window_scale),
graphics_context_(),
texture_factory_() {
initialize_opengl(this->frame_, std::bind(&device::update, this));
this->offscreen_texture_ = texture_factory().create(screen_width, screen_height);
::glGenFramebuffersEXT(1, &this->framebuffer_);
assert(this->framebuffer_);
::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, this->framebuffer_);
::glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
GL_COLOR_ATTACHMENT0_EXT,
GL_TEXTURE_2D,
this->offscreen_texture_->id(),
0);
if (::glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) != GL_FRAMEBUFFER_COMPLETE_EXT) {
throw std::runtime_error("framebuffer is not supported completely");
}
::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}
void
update() {
float const offscreen_width = static_cast<float>(this->offscreen_texture_->width());
float const offscreen_height = static_cast<float>(this->offscreen_texture_->height());
float const offscreen_tu = offscreen_width / this->offscreen_texture_->texture_width();
float const offscreen_tv = offscreen_height / this->offscreen_texture_->texture_height();
float const offscreen_vertex[4][3] = {{0, 0, 0},
{offscreen_width, 0, 0},
{offscreen_width, offscreen_height, 0},
{0, offscreen_height, 0}};
float const window_scale_f = static_cast<float>(this->window_scale_);
float const offscreen_geo[] = {window_scale_f, 0, 0, 0,
0, window_scale_f, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1};
// render sprites to the offscreen
::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, this->framebuffer_);
::glClearColor(0, 0, 0, 1);
::glClear(GL_COLOR_BUFFER_BIT);
::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
::glEnable(GL_TEXTURE_2D);
::glEnable(GL_BLEND);
::glViewport(0, 0, this->screen_width_, this->screen_height_);
::glMatrixMode(GL_PROJECTION);
::glLoadIdentity();
::glOrtho(0, this->screen_width_, 0, this->screen_height_, 0, 1);
this->drawing_sprites_func_(*this);
::glFlush();
::glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
// render the offscreen to the screen
::glClearColor(0, 0, 0, 1);
::glClear(GL_COLOR_BUFFER_BIT);
::glEnable(GL_TEXTURE_2D);
::glDisable(GL_BLEND);
::glViewport(0, 0,
this->screen_width_ * this->window_scale_,
this->screen_height_ * this->window_scale_);
::glMatrixMode(GL_PROJECTION);
::glLoadIdentity();
::glOrtho(0, this->screen_width_ * this->window_scale_,
this->screen_height_ * this->window_scale_, 0,
0, 1);
::glMatrixMode(GL_MODELVIEW);
::glLoadMatrixf(offscreen_geo);
::glBindTexture(GL_TEXTURE_2D, this->offscreen_texture_->id());
::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
{
::glBegin(GL_QUADS);
::glTexCoord2f(0, 0);
::glVertex3fv(offscreen_vertex[0]);
::glTexCoord2f(offscreen_tu, 0);
::glVertex3fv(offscreen_vertex[1]);
::glTexCoord2f(offscreen_tu, offscreen_tv);
::glVertex3fv(offscreen_vertex[2]);
::glTexCoord2f(0, offscreen_tv);
::glVertex3fv(offscreen_vertex[3]);
::glEnd();
}
::glBindTexture(GL_TEXTURE_2D, 0);
::glFlush();
}
frame_type&
frame() {
return this->frame_;
}
graphics_context_type&
graphics_context() {
return this->graphics_context_;
}
texture_factory_type&
texture_factory() {
return this->texture_factory_;
}
};
}
}
}
#endif
<|endoftext|> |
<commit_before>#include "Instruction_X86.h"
#include "CodeGenRegVm_X86.h"
int x86Argument::Decode(CodeGenRegVmStateContext &ctx, char *buf, bool x64, bool useMmWord, bool skipSize)
{
char *curr = buf;
if(type == argNumber)
{
if(ctx.vsAsmStyle)
curr += sprintf(curr, "%x%s", num, num > 9 ? "h" : "");
else
curr += sprintf(curr, "%d", num);
}
else if(type == argReg)
{
strcpy(curr, (x64 ? x64RegText : x86RegText)[reg]);
curr += strlen(curr);
}
else if(type == argXmmReg)
{
strcpy(curr, x86XmmRegText[xmmArg]);
curr += strlen(curr);
}
else if(type == argLabel)
{
curr += sprintf(curr, "'0x%x'", labelID);
}
else if(type == argPtrLabel)
{
curr += sprintf(curr, "['0x%x'+%d]", labelID, ptrNum);
}
else if(type == argPtr)
{
if(!skipSize)
{
strcpy(curr, (useMmWord ? x86XmmSizeText : x86SizeText)[ptrSize]);
curr += strlen(curr);
if(ctx.vsAsmStyle)
{
*curr++ = ' ';
*curr++ = 'p';
*curr++ = 't';
*curr++ = 'r';
}
*curr++ = ' ';
}
*curr++ = '[';
*curr = 0;
if(!ctx.vsAsmStyle)
{
if(ptrIndex != rNONE)
{
strcpy(curr, (x64 ? x64RegText : x86RegText)[ptrIndex]);
curr += strlen(curr);
}
if(ptrMult > 1)
curr += sprintf(curr, "*%d", ptrMult);
}
if(ptrBase != rNONE)
{
if(ctx.vsAsmStyle)
curr += sprintf(curr, "%s", (x64 ? x64RegText : x86RegText)[ptrBase]);
else if(ptrIndex != rNONE)
curr += sprintf(curr, " + %s", (x64 ? x64RegText : x86RegText)[ptrBase]);
else
curr += sprintf(curr, "%s", (x64 ? x64RegText : x86RegText)[ptrBase]);
}
if(ctx.vsAsmStyle)
{
if(ptrIndex != rNONE)
{
if(ptrBase != rNONE)
*curr++ = '+';
strcpy(curr, (x64 ? x64RegText : x86RegText)[ptrIndex]);
curr += strlen(curr);
}
if(ptrMult > 1)
curr += sprintf(curr, "*%d", ptrMult);
}
if(ptrIndex == rNONE && ptrBase == rNONE && ctx.vsAsmStyle)
curr += sprintf(curr, "%x%s", ptrNum, ptrNum > 9 ? "h" : "");
else if(ptrIndex == rNONE && ptrBase == rNONE && ptrNum >= uintptr_t(ctx.tempStackArrayBase) && ptrNum < uintptr_t(ctx.tempStackArrayEnd))
curr += sprintf(curr, "vmState.tempStackArrayBase+%d", unsigned(ptrNum - uintptr_t(ctx.tempStackArrayBase)));
else if(ptrIndex == rNONE && ptrBase == rNONE)
curr += sprintf(curr, "%d", ptrNum);
else if(ptrNum != 0 && ctx.vsAsmStyle)
curr += sprintf(curr, "+%x%s", ptrNum, ptrNum > 9 ? "h" : "");
else if(ptrNum != 0)
curr += sprintf(curr, "%+d", ptrNum);
*curr++ = ']';
*curr = 0;
}
else if(type == argImm64)
{
if(imm64Arg == uintptr_t(&ctx))
curr += sprintf(curr, "&vmState");
else if(imm64Arg == uintptr_t(&ctx.tempStackArrayBase))
curr += sprintf(curr, "&vmState.tempStackArrayBase");
else if(ctx.vsAsmStyle)
curr += sprintf(curr, "%llXh", (unsigned long long)imm64Arg);
else
curr += sprintf(curr, "%lld", (long long)imm64Arg);
}
return (int)(curr - buf);
}
int x86Instruction::Decode(CodeGenRegVmStateContext &ctx, char *buf)
{
char *curr = buf;
if(ctx.vsAsmStyle)
*curr++ = ' ';
if(name == o_label)
{
curr += sprintf(curr, "0x%p:", (void*)(intptr_t)labelID);
}
else if(name == o_other)
{
strcpy(curr, " ; ");
curr += strlen(curr);
strcpy(curr, comment);
curr += strlen(curr);
}
else
{
strcpy(curr, x86CmdText[name]);
curr += strlen(curr);
if(ctx.vsAsmStyle)
{
for(unsigned width = (unsigned)strlen(x86CmdText[name]); width < 11; width++)
*curr++ = ' ';
}
}
if(name != o_none)
{
if(argA.type != x86Argument::argNone)
{
*curr++ = ' ';
bool usex64 = name >= o_mov64 || name == o_movsxd || ((argA.type == x86Argument::argPtr || name == o_call || name == o_push || name == o_pop) && sizeof(void*) == 8) || (argB.type == x86Argument::argPtr && argB.ptrSize == sQWORD && name != o_cvttsd2si);
bool useMmWord = ctx.vsAsmStyle && argB.type == x86Argument::argXmmReg;
curr += argA.Decode(ctx, curr, usex64, useMmWord, name == o_lea);
}
if(argB.type != x86Argument::argNone)
{
*curr++ = ',';
if(!ctx.vsAsmStyle)
*curr++ = ' ';
bool usex64 = name >= o_mov64 || (argB.type == x86Argument::argPtr && sizeof(void*) == 8) || name == o_movsxd || (argA.type == x86Argument::argPtr && argA.ptrSize == sQWORD);
bool useMmWord = ctx.vsAsmStyle && (argA.type == x86Argument::argXmmReg || name == o_cvttsd2si || name == o_cvttsd2si64);
curr += argB.Decode(ctx, curr, usex64, useMmWord, name == o_lea);
}
}
if(ctx.vsAsmStyle)
{
*curr++ = ' ';
*curr++ = ' ';
*curr = 0;
}
return (int)(curr-buf);
}
<commit_msg>jit: fixed compilation warning<commit_after>#include "Instruction_X86.h"
#include "CodeGenRegVm_X86.h"
int x86Argument::Decode(CodeGenRegVmStateContext &ctx, char *buf, bool x64, bool useMmWord, bool skipSize)
{
char *curr = buf;
if(type == argNumber)
{
if(ctx.vsAsmStyle)
curr += sprintf(curr, "%x%s", num, num > 9 ? "h" : "");
else
curr += sprintf(curr, "%d", num);
}
else if(type == argReg)
{
strcpy(curr, (x64 ? x64RegText : x86RegText)[reg]);
curr += strlen(curr);
}
else if(type == argXmmReg)
{
strcpy(curr, x86XmmRegText[xmmArg]);
curr += strlen(curr);
}
else if(type == argLabel)
{
curr += sprintf(curr, "'0x%x'", labelID);
}
else if(type == argPtrLabel)
{
curr += sprintf(curr, "['0x%x'+%d]", labelID, ptrNum);
}
else if(type == argPtr)
{
if(!skipSize)
{
strcpy(curr, (useMmWord ? x86XmmSizeText : x86SizeText)[ptrSize]);
curr += strlen(curr);
if(ctx.vsAsmStyle)
{
*curr++ = ' ';
*curr++ = 'p';
*curr++ = 't';
*curr++ = 'r';
}
*curr++ = ' ';
}
*curr++ = '[';
*curr = 0;
if(!ctx.vsAsmStyle)
{
if(ptrIndex != rNONE)
{
strcpy(curr, (x64 ? x64RegText : x86RegText)[ptrIndex]);
curr += strlen(curr);
}
if(ptrMult > 1)
curr += sprintf(curr, "*%d", ptrMult);
}
if(ptrBase != rNONE)
{
if(ctx.vsAsmStyle)
curr += sprintf(curr, "%s", (x64 ? x64RegText : x86RegText)[ptrBase]);
else if(ptrIndex != rNONE)
curr += sprintf(curr, " + %s", (x64 ? x64RegText : x86RegText)[ptrBase]);
else
curr += sprintf(curr, "%s", (x64 ? x64RegText : x86RegText)[ptrBase]);
}
if(ctx.vsAsmStyle)
{
if(ptrIndex != rNONE)
{
if(ptrBase != rNONE)
*curr++ = '+';
strcpy(curr, (x64 ? x64RegText : x86RegText)[ptrIndex]);
curr += strlen(curr);
}
if(ptrMult > 1)
curr += sprintf(curr, "*%d", ptrMult);
}
if(ptrIndex == rNONE && ptrBase == rNONE && ctx.vsAsmStyle)
curr += sprintf(curr, "%x%s", ptrNum, ptrNum > 9 ? "h" : "");
else if(ptrIndex == rNONE && ptrBase == rNONE && uintptr_t(ptrNum) >= uintptr_t(ctx.tempStackArrayBase) && uintptr_t(ptrNum) < uintptr_t(ctx.tempStackArrayEnd))
curr += sprintf(curr, "vmState.tempStackArrayBase+%d", unsigned(ptrNum - uintptr_t(ctx.tempStackArrayBase)));
else if(ptrIndex == rNONE && ptrBase == rNONE)
curr += sprintf(curr, "%d", ptrNum);
else if(ptrNum != 0 && ctx.vsAsmStyle)
curr += sprintf(curr, "+%x%s", ptrNum, ptrNum > 9 ? "h" : "");
else if(ptrNum != 0)
curr += sprintf(curr, "%+d", ptrNum);
*curr++ = ']';
*curr = 0;
}
else if(type == argImm64)
{
if(imm64Arg == uintptr_t(&ctx))
curr += sprintf(curr, "&vmState");
else if(imm64Arg == uintptr_t(&ctx.tempStackArrayBase))
curr += sprintf(curr, "&vmState.tempStackArrayBase");
else if(ctx.vsAsmStyle)
curr += sprintf(curr, "%llXh", (unsigned long long)imm64Arg);
else
curr += sprintf(curr, "%lld", (long long)imm64Arg);
}
return (int)(curr - buf);
}
int x86Instruction::Decode(CodeGenRegVmStateContext &ctx, char *buf)
{
char *curr = buf;
if(ctx.vsAsmStyle)
*curr++ = ' ';
if(name == o_label)
{
curr += sprintf(curr, "0x%p:", (void*)(intptr_t)labelID);
}
else if(name == o_other)
{
strcpy(curr, " ; ");
curr += strlen(curr);
strcpy(curr, comment);
curr += strlen(curr);
}
else
{
strcpy(curr, x86CmdText[name]);
curr += strlen(curr);
if(ctx.vsAsmStyle)
{
for(unsigned width = (unsigned)strlen(x86CmdText[name]); width < 11; width++)
*curr++ = ' ';
}
}
if(name != o_none)
{
if(argA.type != x86Argument::argNone)
{
*curr++ = ' ';
bool usex64 = name >= o_mov64 || name == o_movsxd || ((argA.type == x86Argument::argPtr || name == o_call || name == o_push || name == o_pop) && sizeof(void*) == 8) || (argB.type == x86Argument::argPtr && argB.ptrSize == sQWORD && name != o_cvttsd2si);
bool useMmWord = ctx.vsAsmStyle && argB.type == x86Argument::argXmmReg;
curr += argA.Decode(ctx, curr, usex64, useMmWord, name == o_lea);
}
if(argB.type != x86Argument::argNone)
{
*curr++ = ',';
if(!ctx.vsAsmStyle)
*curr++ = ' ';
bool usex64 = name >= o_mov64 || (argB.type == x86Argument::argPtr && sizeof(void*) == 8) || name == o_movsxd || (argA.type == x86Argument::argPtr && argA.ptrSize == sQWORD);
bool useMmWord = ctx.vsAsmStyle && (argA.type == x86Argument::argXmmReg || name == o_cvttsd2si || name == o_cvttsd2si64);
curr += argB.Decode(ctx, curr, usex64, useMmWord, name == o_lea);
}
}
if(ctx.vsAsmStyle)
{
*curr++ = ' ';
*curr++ = ' ';
*curr = 0;
}
return (int)(curr-buf);
}
<|endoftext|> |
<commit_before>// ConfigFile.cpp
#include "ConfigFile.h"
using std::string;
ConfigFile::ConfigFile( string filename, string delimiter,
string comment, string sentry )
: myDelimiter(delimiter), myComment(comment), mySentry(sentry)
{
// Construct a ConfigFile, getting keys and values from given file
std::ifstream in( filename.c_str() );
if( !in ) throw file_not_found( filename );
in >> (*this);
}
ConfigFile::ConfigFile()
: myDelimiter( string(1,'=') ), myComment( string(1,'#') )
{
// Construct a ConfigFile without a file; empty
}
void ConfigFile::remove( const string& key )
{
// Remove key and its value
myContents.erase( myContents.find( key ) );
return;
}
bool ConfigFile::keyExists( const string& key ) const
{
// Indicate whether key is found
mapci p = myContents.find( key );
return ( p != myContents.end() );
}
/* static */
void ConfigFile::trim( string& s )
{
// Remove leading and trailing whitespace
static const char whitespace[] = " \n\t\v\r\f";
s.erase( 0, s.find_first_not_of(whitespace) );
s.erase( s.find_last_not_of(whitespace) + 1U );
}
std::ostream& operator<<( std::ostream& os, const ConfigFile& cf )
{
// Save a ConfigFile to os
for( ConfigFile::mapci p = cf.myContents.begin();
p != cf.myContents.end();
++p )
{
os << p->first << " " << cf.myDelimiter << " ";
os << p->second << std::endl;
}
return os;
}
std::istream& operator>>( std::istream& is, ConfigFile& cf )
{
// Load a ConfigFile from is
// Read in keys and values, keeping internal whitespace
typedef string::size_type pos;
const string& delim = cf.myDelimiter; // separator
const string& comm = cf.myComment; // comment
const string& sentry = cf.mySentry; // end of file sentry
const pos skip = delim.length(); // length of separator
string nextline = ""; // might need to read ahead to see where value ends
while( is || nextline.length() > 0 )
{
// Read an entire line at a time
string line;
if( nextline.length() > 0 )
{
line = nextline; // we read ahead; use it now
nextline = "";
}
else
{
std::getline( is, line );
}
// Ignore comments
line = line.substr( 0, line.find(comm) );
// Check for end of file sentry
if( sentry != "" && line.find(sentry) != string::npos ) return is;
// Parse the line if it contains a delimiter
pos delimPos = line.find( delim );
if( delimPos < string::npos )
{
// Extract the key
string key = line.substr( 0, delimPos );
line.replace( 0, delimPos+skip, "" );
// See if value continues on the next line
// Stop at blank line, next line with a key, end of stream,
// or end of file sentry
bool terminate = false;
while( !terminate && is )
{
std::getline( is, nextline );
terminate = true;
string nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy == "" ) continue;
nextline = nextline.substr( 0, nextline.find(comm) );
if( nextline.find(delim) != string::npos )
continue;
if( sentry != "" && nextline.find(sentry) != string::npos )
continue;
nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy != "" ) line += "\n";
line += nextline;
terminate = false;
}
// Store key and value
ConfigFile::trim(key);
ConfigFile::trim(line);
cf.myContents[key] = line; // overwrites if key is repeated
}
}
return is;
}
<commit_msg>TEST:configFile test modify<commit_after>// ConfigFile.cpp
#include "ConfigFile.h"
using std::string;
ConfigFile::ConfigFile( string filename, string delimiter,
string comment, string sentry )
: myDelimiter(delimiter), myComment(comment), mySentry(sentry)
{
// Construct a ConfigFile, getting keys and values from given file
std::ifstream in( filename.c_str() );
if( !in ) throw file_not_found( filename );
in >> (*this);
}
ConfigFile::ConfigFile()
: myDelimiter( string(1,'=') ), myComment( string(1,'#') )
{
// Construct a ConfigFile without a file; empty
}
void ConfigFile::remove( const string& key )
{
// Remove key and its value
myContents.erase( myContents.find( key ) );
return;
}
bool ConfigFile::keyExists( const string& key ) const
{
// Indicate whether key is found
mapci p = myContents.find( key );
return ( p != myContents.end() );
}
/* static */
void ConfigFile::trim( string& s )
{
// Remove leading and trailing whitespace
static const char whitespace[] = " \n\t\v\r\f";
s.erase( 0, s.find_first_not_of(whitespace) );
s.erase( s.find_last_not_of(whitespace) + 1U );
}
std::ostream& operator<<( std::ostream& os, const ConfigFile& cf )
{
// Save a ConfigFile to os
for( ConfigFile::mapci p = cf.myContents.begin();
p != cf.myContents.end();
++p )
{
os << p->first << " " << cf.myDelimiter << " ";
os << p->second << std::endl;
}
return os;
}
std::istream& operator>>( std::istream& is, ConfigFile& cf )
{
// Load a ConfigFile from is
// Read in keys and values, keeping internal whitespace
typedef string::size_type pos;
const string& delim = cf.myDelimiter; // separator
const string& comm = cf.myComment; // comment
const string& sentry = cf.mySentry; // end of file sentry
const pos skip = delim.length(); // length of separator
string nextline = ""; // might need to read ahead to see where value ends
while( is || nextline.length() > 0 )
{
// Read an entire line at a time
string line;
if( nextline.length() > 0 )
{
line = nextline; // we read ahead; use it now
nextline = "";
}
else
{
std::getline( is, line );
}
// Ignore comments
line = line.substr( 0, line.find(comm) );
// Check for end of file sentry
if( sentry != "" && line.find(sentry) != string::npos ) return is;
// Parse the line if it contains a delimiter
pos delimPos = line.find( delim );
if( delimPos < string::npos )
{
// Extract the key
string key = line.substr( 0, delimPos );
line.replace( 0, delimPos+skip, "" );
// See if value continues on the next line
// Stop at blank line, next line with a key, end of stream,
// or end of file sentry
bool terminate = false;
while( !terminate && is )
{
std::getline( is, nextline );
terminate = true;
string nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy == "" ) continue;
nextline = nextline.substr( 0, nextline.find(comm) );
if( nextline.find(delim) != string::npos )
continue;
if( sentry != "" && nextline.find(sentry) != string::npos )
continue;
nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy != "" ) line += "\n";
line += nextline;
terminate = false;
}
// Store key and value
ConfigFile::trim(key);
ConfigFile::trim(line);
cf.myContents[key] = line; // overwrites if key is repeated
}
}
return is;
}
<|endoftext|> |
<commit_before>
#include <SAX/ArabicaConfig.h>
#ifndef ARABICA_NO_CODECVT_SPECIALISATIONS
#include <Utils/impl/codecvt_specialisations.h>
namespace std
{
codecvt<char, wchar_t, mbstate_t>::
~codecvt()
{
} // ~codecvt
////////////////////////////////////////////////////////////////////////
codecvt_base::result
codecvt<char, wchar_t, mbstate_t>::
do_out(mbstate_t&, const char* from, const char* from_end, const char*& from_next,
wchar_t* to, wchar_t* to_limit, wchar_t*& to_next) const
{
int limit = std::max<int>(from_end - from, to_limit - to);
from_next = from;
to_next = to;
while(limit--)
*to_next++ = static_cast<wchar_t>(*from_next++);
return codecvt_base::ok;
} // do_out
codecvt_base::result
codecvt<char, wchar_t, mbstate_t>::
do_in(mbstate_t&, const wchar_t* from, const wchar_t* from_end, const wchar_t*& from_next,
char* to, char* to_limit, char*& to_next) const
{
int limit = std::max<int>(from_end - from, to_limit - to);
from_next = from;
to_next = to;
while(limit--)
*to_next++ = static_cast<char>(*from_next++);
return codecvt_base::ok;
} // do_in
codecvt_base::result
codecvt<char, wchar_t, mbstate_t>::
do_unshift(mbstate_t&, wchar_t* to, wchar_t* to_limit, wchar_t*& to_next) const
{
to_next = to;
return codecvt_base::noconv;
} // do_unshift
int
codecvt<char, wchar_t, mbstate_t>::
do_encoding() const throw()
{
return 1;
} // do_encoding
bool
codecvt<char, wchar_t, mbstate_t>::
do_always_noconv() const throw()
{
return false;
} // do_always_noconv
int
codecvt<char, wchar_t, mbstate_t>::
do_length(const mbstate_t&, const wchar_t* from, const wchar_t* end, size_t max) const
{
return std::min<int>(max, (end - from));
} // do_length
int
codecvt<char, wchar_t, mbstate_t>::
do_max_length() const throw()
{
return 1;
} // do_max_length
} // namespace std
#endif
<commit_msg>exclude from build if now wchar_t<commit_after>
#include <SAX/ArabicaConfig.h>
#ifndef ARABICA_NO_CODECVT_SPECIALISATIONS
#ifndef ARABICA_NO_WCHAR_T
#include <Utils/impl/codecvt_specialisations.h>
namespace std
{
codecvt<char, wchar_t, mbstate_t>::
~codecvt()
{
} // ~codecvt
////////////////////////////////////////////////////////////////////////
codecvt_base::result
codecvt<char, wchar_t, mbstate_t>::
do_out(mbstate_t&, const char* from, const char* from_end, const char*& from_next,
wchar_t* to, wchar_t* to_limit, wchar_t*& to_next) const
{
int limit = std::max<int>(from_end - from, to_limit - to);
from_next = from;
to_next = to;
while(limit--)
*to_next++ = static_cast<wchar_t>(*from_next++);
return codecvt_base::ok;
} // do_out
codecvt_base::result
codecvt<char, wchar_t, mbstate_t>::
do_in(mbstate_t&, const wchar_t* from, const wchar_t* from_end, const wchar_t*& from_next,
char* to, char* to_limit, char*& to_next) const
{
int limit = std::max<int>(from_end - from, to_limit - to);
from_next = from;
to_next = to;
while(limit--)
*to_next++ = static_cast<char>(*from_next++);
return codecvt_base::ok;
} // do_in
codecvt_base::result
codecvt<char, wchar_t, mbstate_t>::
do_unshift(mbstate_t&, wchar_t* to, wchar_t* to_limit, wchar_t*& to_next) const
{
to_next = to;
return codecvt_base::noconv;
} // do_unshift
int
codecvt<char, wchar_t, mbstate_t>::
do_encoding() const throw()
{
return 1;
} // do_encoding
bool
codecvt<char, wchar_t, mbstate_t>::
do_always_noconv() const throw()
{
return false;
} // do_always_noconv
int
codecvt<char, wchar_t, mbstate_t>::
do_length(const mbstate_t&, const wchar_t* from, const wchar_t* end, size_t max) const
{
return std::min<int>(max, (end - from));
} // do_length
int
codecvt<char, wchar_t, mbstate_t>::
do_max_length() const throw()
{
return 1;
} // do_max_length
} // namespace std
#endif
#endif
<|endoftext|> |
<commit_before>#include "CMainMenuState.h"
#include "CMainState.h"
#include "ColorMappers.h"
#include "CGUILoadingWidget.h"
#include "CDataLoadingThread.h"
#include "SciDataManager.h"
CMainMenuState::CMainMenuState()
{}
void CMainMenuState::begin()
{
Context->GUIContext->setupMenuState();
}
void CMainMenuState::end()
{
Context->GUIContext->clear();
}
#include "CGlyphSceneObject.h"
void CMainMenuState::OnRenderStart(float const Elapsed)
{
// Let loading thread run
sf::sleep(sf::seconds(0.05f));
Thread.Sync();
Context->GUIContext->draw(Elapsed, true);
CApplication::get().swapBuffers();
}
void CMainMenuState::OnWindowResized(SWindowResizedEvent const & Event)
{
Context->GUIContext->getCanvas()->SetSize(Event.Size.X, Event.Size.Y);
Context->GUIContext->getCanvas()->Invalidate();
Context->GUIContext->getCanvas()->InvalidateChildren(true);
}
void CMainMenuState::loadData(std::string const & FileName)
{
DataSetName = FileName;
std::stringstream s;
s << "Datasets/";
s << FileName;
Thread.Context = Context;
Context->GUIContext->addWidget(Thread.LoadingWidget = new CGUILoadingWidget("Loading data and initializing scene elements"));
Thread.Run(s.str());
}
void CMainMenuState::createDataSet()
{
SciDataParserCSV * Parser1 = new SciDataParserSmartTether();
Parser1->Manager = Context->DataManager;
Parser1->FieldDelim = ',';
Parser1->ValueDelim = ',';
/*Parser1->FieldNames = false;
std::vector<std::string> Fields;
Fields.push_back("GPGGA Base Position");
Fields.push_back("x");
Fields.push_back("y");
Fields.push_back("n");
Fields.push_back("z");
Fields.push_back("e");
Parser1->Fields = Fields;*/
Parser1->load("smarttether10.csv");
int counter = 0;
for (auto Value : Context->DataManager->getRawValues().getValues())
Value.addField("timeStamp") = counter++;
//Context->DataManager->createGridDataFromRawValues(FullRange, 5.0, "Avg Oxy");
Context->DataManager->writeToFile("Datasets/VallettaMCC1.dat");
}
<commit_msg>+ Added Tomia dataset<commit_after>#include "CMainMenuState.h"
#include "CMainState.h"
#include "ColorMappers.h"
#include "CGUILoadingWidget.h"
#include "CDataLoadingThread.h"
#include "SciDataManager.h"
CMainMenuState::CMainMenuState()
{}
void CMainMenuState::begin()
{
Context->GUIContext->setupMenuState();
}
void CMainMenuState::end()
{
Context->GUIContext->clear();
}
#include "CGlyphSceneObject.h"
void CMainMenuState::OnRenderStart(float const Elapsed)
{
// Let loading thread run
sf::sleep(sf::seconds(0.05f));
Thread.Sync();
Context->GUIContext->draw(Elapsed, true);
CApplication::get().swapBuffers();
}
void CMainMenuState::OnWindowResized(SWindowResizedEvent const & Event)
{
Context->GUIContext->getCanvas()->SetSize(Event.Size.X, Event.Size.Y);
Context->GUIContext->getCanvas()->Invalidate();
Context->GUIContext->getCanvas()->InvalidateChildren(true);
}
void CMainMenuState::loadData(std::string const & FileName)
{
DataSetName = FileName;
std::stringstream s;
s << "Datasets/";
s << FileName;
Thread.Context = Context;
Context->GUIContext->addWidget(Thread.LoadingWidget = new CGUILoadingWidget("Loading data and initializing scene elements"));
Thread.Run(s.str());
}
void CMainMenuState::createDataSet()
{
SciDataParserCSV * Parser1 = new SciDataParserSmartTether();
Parser1->Manager = Context->DataManager;
Parser1->FieldDelim = ',';
Parser1->ValueDelim = ',';
/*Parser1->FieldNames = false;
std::vector<std::string> Fields;
Fields.push_back("GPGGA Base Position");
Fields.push_back("x");
Fields.push_back("y");
Fields.push_back("n");
Fields.push_back("z");
Fields.push_back("e");
Parser1->Fields = Fields;*/
Parser1->load("2013_03_20_01_20_04.csv");
int counter = 0;
for (auto Value : Context->DataManager->getRawValues().getValues())
Value.addField("timeStamp") = counter++;
//Context->DataManager->createGridDataFromRawValues(FullRange, 5.0, "Avg Oxy");
Context->DataManager->writeToFile("Datasets/TomiaDeiCappuccini.dat");
}
<|endoftext|> |
<commit_before>// KMail startup and initialize code
// Author: Stefan Taferner <taferner@alpin.or.at>
#include <qstring.h>
#include <qdir.h>
#include "kmglobal.h"
#include "kmmainwin.h"
#include "kmacctmgr.h"
#include "kmfoldermgr.h"
#include "kmfilteraction.h"
#include "kmfolder.h"
#include "kmsender.h"
#include "kbusyptr.h"
#include "kmfiltermgr.h"
#include "kmversion.h"
#include "kmmessage.h"
#include <kapp.h>
#include <stdio.h>
#include <stdlib.h>
#include <kmsgbox.h>
#include <klocale.h>
#include <kstdaccel.h>
#include <kmidentity.h>
#include <dirent.h>
#include <sys/stat.h>
KBusyPtr* kbp = NULL;
KApplication* app = NULL;
KMAcctMgr* acctMgr = NULL;
KMFolderMgr* folderMgr = NULL;
KMFilterMgr* filterMgr = NULL;
KMSender* msgSender = NULL;
KLocale* nls = NULL;
KMFolder* inboxFolder = NULL;
KMFolder* outboxFolder = NULL;
KMFolder* queuedFolder = NULL;
KMFolder* sentFolder = NULL;
KMFolder* trashFolder = NULL;
KStdAccel* keys = NULL;
KMIdentity* identity = NULL;
KMFilterActionDict* filterActionDict = NULL;
bool shuttingDown = FALSE;
const char* aboutText =
"KMail [" KMAIL_VERSION "] by\n\n"
"Stefan Taferner <taferner@kde.org>,\n"
"Markus Wbben <markus.wuebben@kde.org>\n\n"
"based on the work of:\n"
"Lynx <lynx@topaz.hknet.com>,\n"
"Stephan Meyer <Stephan.Meyer@pobox.com>,\n"
"and the above authors.\n\n"
"This program is covered by the GPL.";
static msg_handler oldMsgHandler = NULL;
//-----------------------------------------------------------------------------
// Message handler
static void kmailMsgHandler(QtMsgType aType, const char* aMsg)
{
QString appName = app->appName();
switch (aType)
{
case QtDebugMsg:
fprintf(stderr, "%s: %s\n", (const char*)app->appName(), aMsg);
break;
case QtWarningMsg:
fprintf(stderr, "%s: %s\n", (const char*)app->appName(), aMsg);
KMsgBox::message(NULL, appName+" "+nls->translate("warning"), aMsg,
KMsgBox::EXCLAMATION);
break;
case QtFatalMsg:
fprintf(stderr, appName+" "+nls->translate("fatal error")+": %s\n", aMsg);
KMsgBox::message(NULL, appName+" "+nls->translate("fatal error"),
aMsg, KMsgBox::STOP);
abort();
}
}
//-----------------------------------------------------------------------------
void testDir( const char *_name )
{
DIR *dp;
QString c = getenv("HOME");
c += _name;
dp = opendir(c.data());
if (dp == NULL)
::mkdir(c.data(), S_IRWXU);
else
closedir(dp);
}
//-----------------------------------------------------------------------------
static void transferMail(void)
{
QDir dir = QDir::home();
int rc;
// This function is for all the whiners who think that KMail is
// broken because they cannot read mail with pine and do not
// know how to fix this problem with a simple symbolic link =;-)
if (!dir.cd("KMail")) return;
rc = KMsgBox::yesNo(NULL, app->appName()+" "+nls->translate("warning"),
nls->translate(
"The directory ~/KMail exists. From now on, KMail uses the\n"
"directory ~/Mail for it's messages.\n"
"KMail can move the contents of the directory ~/KMail into\n"
"~/Mail, but this will replace existing files with the same\n"
"name in the directory ~/Mail (e.g. inbox).\n\n"
"Shall KMail move the mail folders now ?"),
KMsgBox::QUESTION);
if (rc != 1) return;
dir.cd("/"); // otherwise we lock the directory
testDir("/Mail");
system("mv -f ~/KMail/* ~/Mail");
system("mv -f ~/KMail/.??* ~/Mail");
system("rmdir ~/KMail");
}
//-----------------------------------------------------------------------------
static void init(int argc, char *argv[])
{
QString acctPath, foldersPath;
KConfig* cfg;
app = new KApplication(argc, argv, "kmail");
nls = app->getLocale();
kbp = new KBusyPtr;
cfg = app->getConfig();
keys = new KStdAccel(cfg);
oldMsgHandler = qInstallMsgHandler(kmailMsgHandler);
testDir("/.kde");
testDir("/.kde/share");
testDir("/.kde/share/config");
testDir("/.kde/share/apps");
testDir("/.kde/share/apps/kmail");
identity = new KMIdentity;
transferMail();
cfg->setGroup("General");
foldersPath = cfg->readEntry("folders",
QDir::homeDirPath() + QString("/Mail"));
acctPath = cfg->readEntry("accounts", foldersPath + "/.kmail-accounts");
folderMgr = new KMFolderMgr(foldersPath);
acctMgr = new KMAcctMgr(acctPath);
filterMgr = new KMFilterMgr;
filterActionDict = new KMFilterActionDict;
inboxFolder = (KMFolder*)folderMgr->findOrCreate(
cfg->readEntry("inboxFolder", "inbox"));
//inboxFolder->open();
outboxFolder = folderMgr->findOrCreate(cfg->readEntry("outboxFolder", "outbox"));
outboxFolder->setType("out");
outboxFolder->open();
sentFolder = folderMgr->findOrCreate(cfg->readEntry("sentFolder", "sent_mail"));
sentFolder->setType("st");
sentFolder->open();
trashFolder = folderMgr->findOrCreate(cfg->readEntry("trashFolder", "trash"));
trashFolder->setType("tr");
trashFolder->open();
acctMgr->readConfig();
filterMgr->readConfig();
KMMessage::readConfig();
msgSender = new KMSender;
}
//-----------------------------------------------------------------------------
static void cleanup(void)
{
shuttingDown = TRUE;
if (inboxFolder) inboxFolder->close(TRUE);
if (outboxFolder) outboxFolder->close(TRUE);
if (sentFolder) sentFolder->close(TRUE);
if (trashFolder) trashFolder->close(TRUE);
if (msgSender) delete msgSender;
if (filterMgr) delete filterMgr;
if (acctMgr) delete acctMgr;
if (folderMgr) delete folderMgr;
if (kbp) delete kbp;
qInstallMsgHandler(oldMsgHandler);
app->getConfig()->sync();
}
//-----------------------------------------------------------------------------
main(int argc, char *argv[])
{
KMMainWin* mainWin;
init(argc, argv);
mainWin = new KMMainWin;
mainWin->show();
app->exec();
cleanup();
}
<commit_msg>New feature: kmail joe@home.org now opens kmail with a composer for a message to joe@home.org<commit_after>// KMail startup and initialize code
// Author: Stefan Taferner <taferner@alpin.or.at>
#include <qstring.h>
#include <qdir.h>
#include "kmglobal.h"
#include "kmmainwin.h"
#include "kmacctmgr.h"
#include "kmfoldermgr.h"
#include "kmfilteraction.h"
#include "kmfolder.h"
#include "kmsender.h"
#include "kbusyptr.h"
#include "kmfiltermgr.h"
#include "kmversion.h"
#include "kmmessage.h"
#include "kmcomposewin.h"
#include <kapp.h>
#include <stdio.h>
#include <stdlib.h>
#include <kmsgbox.h>
#include <klocale.h>
#include <kstdaccel.h>
#include <kmidentity.h>
#include <dirent.h>
#include <sys/stat.h>
KBusyPtr* kbp = NULL;
KApplication* app = NULL;
KMAcctMgr* acctMgr = NULL;
KMFolderMgr* folderMgr = NULL;
KMFilterMgr* filterMgr = NULL;
KMSender* msgSender = NULL;
KLocale* nls = NULL;
KMFolder* inboxFolder = NULL;
KMFolder* outboxFolder = NULL;
KMFolder* queuedFolder = NULL;
KMFolder* sentFolder = NULL;
KMFolder* trashFolder = NULL;
KStdAccel* keys = NULL;
KMIdentity* identity = NULL;
KMFilterActionDict* filterActionDict = NULL;
bool shuttingDown = FALSE;
const char* aboutText =
"KMail [" KMAIL_VERSION "] by\n\n"
"Stefan Taferner <taferner@kde.org>,\n"
"Markus Wbben <markus.wuebben@kde.org>\n\n"
"based on the work of:\n"
"Lynx <lynx@topaz.hknet.com>,\n"
"Stephan Meyer <Stephan.Meyer@pobox.com>,\n"
"and the above authors.\n\n"
"This program is covered by the GPL.";
static msg_handler oldMsgHandler = NULL;
//-----------------------------------------------------------------------------
// Message handler
static void kmailMsgHandler(QtMsgType aType, const char* aMsg)
{
QString appName = app->appName();
switch (aType)
{
case QtDebugMsg:
fprintf(stderr, "%s: %s\n", (const char*)app->appName(), aMsg);
break;
case QtWarningMsg:
fprintf(stderr, "%s: %s\n", (const char*)app->appName(), aMsg);
KMsgBox::message(NULL, appName+" "+nls->translate("warning"), aMsg,
KMsgBox::EXCLAMATION);
break;
case QtFatalMsg:
fprintf(stderr, appName+" "+nls->translate("fatal error")+": %s\n", aMsg);
KMsgBox::message(NULL, appName+" "+nls->translate("fatal error"),
aMsg, KMsgBox::STOP);
abort();
}
}
//-----------------------------------------------------------------------------
void testDir( const char *_name )
{
DIR *dp;
QString c = getenv("HOME");
c += _name;
dp = opendir(c.data());
if (dp == NULL)
::mkdir(c.data(), S_IRWXU);
else
closedir(dp);
}
//-----------------------------------------------------------------------------
static void transferMail(void)
{
QDir dir = QDir::home();
int rc;
// This function is for all the whiners who think that KMail is
// broken because they cannot read mail with pine and do not
// know how to fix this problem with a simple symbolic link =;-)
if (!dir.cd("KMail")) return;
rc = KMsgBox::yesNo(NULL, app->appName()+" "+nls->translate("warning"),
nls->translate(
"The directory ~/KMail exists. From now on, KMail uses the\n"
"directory ~/Mail for it's messages.\n"
"KMail can move the contents of the directory ~/KMail into\n"
"~/Mail, but this will replace existing files with the same\n"
"name in the directory ~/Mail (e.g. inbox).\n\n"
"Shall KMail move the mail folders now ?"),
KMsgBox::QUESTION);
if (rc != 1) return;
dir.cd("/"); // otherwise we lock the directory
testDir("/Mail");
system("mv -f ~/KMail/* ~/Mail");
system("mv -f ~/KMail/.??* ~/Mail");
system("rmdir ~/KMail");
}
//-----------------------------------------------------------------------------
static void init(int argc, char *argv[])
{
QString acctPath, foldersPath;
KConfig* cfg;
app = new KApplication(argc, argv, "kmail");
nls = app->getLocale();
kbp = new KBusyPtr;
cfg = app->getConfig();
keys = new KStdAccel(cfg);
oldMsgHandler = qInstallMsgHandler(kmailMsgHandler);
testDir("/.kde");
testDir("/.kde/share");
testDir("/.kde/share/config");
testDir("/.kde/share/apps");
testDir("/.kde/share/apps/kmail");
identity = new KMIdentity;
transferMail();
cfg->setGroup("General");
foldersPath = cfg->readEntry("folders",
QDir::homeDirPath() + QString("/Mail"));
acctPath = cfg->readEntry("accounts", foldersPath + "/.kmail-accounts");
folderMgr = new KMFolderMgr(foldersPath);
acctMgr = new KMAcctMgr(acctPath);
filterMgr = new KMFilterMgr;
filterActionDict = new KMFilterActionDict;
inboxFolder = (KMFolder*)folderMgr->findOrCreate(
cfg->readEntry("inboxFolder", "inbox"));
//inboxFolder->open();
outboxFolder = folderMgr->findOrCreate(cfg->readEntry("outboxFolder", "outbox"));
outboxFolder->setType("out");
outboxFolder->open();
sentFolder = folderMgr->findOrCreate(cfg->readEntry("sentFolder", "sent_mail"));
sentFolder->setType("st");
sentFolder->open();
trashFolder = folderMgr->findOrCreate(cfg->readEntry("trashFolder", "trash"));
trashFolder->setType("tr");
trashFolder->open();
acctMgr->readConfig();
filterMgr->readConfig();
KMMessage::readConfig();
msgSender = new KMSender;
}
//-----------------------------------------------------------------------------
static void cleanup(void)
{
shuttingDown = TRUE;
if (inboxFolder) inboxFolder->close(TRUE);
if (outboxFolder) outboxFolder->close(TRUE);
if (sentFolder) sentFolder->close(TRUE);
if (trashFolder) trashFolder->close(TRUE);
if (msgSender) delete msgSender;
if (filterMgr) delete filterMgr;
if (acctMgr) delete acctMgr;
if (folderMgr) delete folderMgr;
if (kbp) delete kbp;
qInstallMsgHandler(oldMsgHandler);
app->getConfig()->sync();
}
//-----------------------------------------------------------------------------
main(int argc, char *argv[])
{
KMMainWin* mainWin;
KMComposeWin* comp;
init(argc, argv);
mainWin = new KMMainWin;
mainWin->show();
if (argc > 1)
{
KMComposeWin *win;
KMMessage* msg = new KMMessage;
msg->initHeader();
msg->setTo(argv[1]);
win = new KMComposeWin(msg);
win->show();
}
app->exec();
cleanup();
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/hwpf/fapi2/include/error_info_defs.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2011,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file error_info_defs.H
/// @brief Defines to support the Error Information class
///
#ifndef FAPI2_ERRORINFO_DEFS_H_
#define FAPI2_ERRORINFO_DEFS_H_
#include <stdint.h>
#include <target.H>
#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)
#include <variable_buffer.H>
#include <utility>
#endif
namespace fapi2
{
///
/// @brief Type to hold the ffdc data to be sent to hostboot
///
/// Note: Typical data sent seems to be register/addresss info
/// rather than use extra space converting stuff just
/// send a uint64 always
///
struct sbeFfdc_t
{
uint32_t size;
uint64_t data;
} __attribute__((packed));
// 10 entries limits the size of SbeFfdcData_t to 128 bytes
enum
{
MAX_SBE_FFDC_ENTRIES = 10
};
// Data type for SBE ffdc buffer sent through fifo
typedef struct
{
uint32_t fapiRc; // Return code from failure
uint32_t ffdcLength; // length of Fapi FFDC data (in bytes)
struct sbeFfdc_t ffdcData[MAX_SBE_FFDC_ENTRIES]; // fapi FFDC data
} SbeFfdcData_t; // 128 bytes
///
/// @brief Type to hold the ffdc element in the ffdc class
/// Needed so that the size can be squirled away before the
/// macro is called.
///
struct ffdc_struct
{
const void* ptr;
size_t size;
};
class ffdc_t
{
public:
ffdc_t(void)
{}
void operator=(const ffdc_t& i )
{
iv_value.ptr = i.ptr();
iv_value.size = i.size();
}
operator const void* () const
{
return iv_value.ptr;
}
operator uint8_t() const
{
return *(reinterpret_cast<const uint8_t*>(iv_value.ptr));
}
size_t size(void) const
{
return iv_value.size;
}
size_t& size(void)
{
return iv_value.size;
}
const void* ptr(void) const
{
return iv_value.ptr;
}
const void*& ptr(void)
{
return iv_value.ptr;
}
private:
struct ffdc_struct iv_value = {}; //init to zero
};
///
/// @brief Enumeration of ErrorInfo FFDC sizes that are used to indicate a
/// special type that cannot simply be memcopied
enum ErrorInfoFfdcSize
{
EI_FFDC_SIZE_BUF = 0xffff, // fapi2::buffer<T>
EI_FFDC_SIZE_TARGET = 0xfffe, // fapi2::Target
EI_FFDC_SIZE_VBUF = 0xfffd, // fapi2::variable_buffer
EI_FFDC_MAX_SIZE = 0x1000, // Limit regular FFDC capture to 4kb
};
///
/// @brief Enumeration of error log severity.
///
enum errlSeverity_t
{
FAPI2_ERRL_SEV_UNDEFINED = 0x00, /// Used internally by ffdc mechanism
FAPI2_ERRL_SEV_RECOVERED = 0x10, /// Not seen by customer
FAPI2_ERRL_SEV_PREDICTIVE = 0x20, /// Error recovered but customer will see
FAPI2_ERRL_SEV_UNRECOVERABLE = 0x40 /// Unrecoverable, general
};
///
/// @brief Enumeration of ErrorInfo types
///
enum ErrorInfoType
{
EI_TYPE_FFDC = 0,
EI_TYPE_HW_CALLOUT = 1,
EI_TYPE_PROCEDURE_CALLOUT = 2,
EI_TYPE_BUS_CALLOUT = 3,
EI_TYPE_CDG = 4, // Target Callout/Deconfig/GARD
EI_TYPE_CHILDREN_CDG = 5, // Children Callout/Deconfig/GARD
EI_TYPE_COLLECT_TRACE = 6,
EI_LAST_TYPE = EI_TYPE_COLLECT_TRACE + 1,
};
#ifndef MINIMUM_FFDC
///
/// @enum HwCallout
///
/// This enumeration defines the possible Hardware Callouts that are not
/// represented by fapi2::Targets
///
/// Note that platform code may depend on the enum values starting at 0 and
/// incrementing in order to efficiently convert to a platform callout value
/// so do not reorder without consulting all platforms
///
namespace HwCallouts
{
enum HwCallout
{
// Where indicated, a HW Callout in FAPI Error XML must include a
// reference target that is used to identify the HW. e.g. for
// TOD_CLOCK, the proc chip that the clock is attached to must be
// specified
TOD_CLOCK = 0, // Include proc-chip ref (or child chiplet)
MEM_REF_CLOCK = 1, // Include membuf-chip ref (or child chiplet)
PROC_REF_CLOCK = 2, // Include proc-chip ref (or child chiplet)
PCI_REF_CLOCK = 3, // Include proc-chip ref (or child chiplet)
FLASH_CONTROLLER_PART = 4,
PNOR_PART = 5,
SBE_SEEPROM_PART = 6,
VPD_PART = 7,
LPC_SLAVE_PART = 8,
GPIO_EXPANDER_PART = 9,
SPIVID_SLAVE_PART = 10,
};
}
///
/// @enum ProcedureCallout
///
/// This enumeration defines the possible Procedure Callouts
/// These instruct the customer/customer-engineer what to do
///
/// Note that platform code may depend on the enum values starting at 0 and
/// incrementing in order to efficiently convert to a platform callout value
/// so do not reorder without consulting all platforms
///
namespace ProcedureCallouts
{
enum ProcedureCallout
{
CODE = 0, // Code problem
LVL_SUPPORT = 1, // Call next level of support
MEMORY_PLUGGING_ERROR = 2, // DIMM Plugging error
BUS_CALLOUT = 3, // Bus Called Out
};
}
///
/// @enum CalloutPriority
///
/// This enumeration defines the possible Procedure and Target callout priorities
///
/// Note that platform code may depend on the enum values starting at 0 and
/// incrementing in order to efficiently convert to a platform priority value
/// so do not reorder without consulting all platforms
///
namespace CalloutPriorities
{
enum CalloutPriority
{
LOW = 0,
MEDIUM = 1,
HIGH = 2,
};
}
///
/// @enum CollectTrace
///
/// This enumeration defines the possible firmware traces to collect
///
namespace CollectTraces
{
const uint32_t TRACE_SIZE = 256; // limit collected trace size
enum CollectTrace
{
FSI = 1,
SCOM = 2,
SCAN = 3,
MBOX = 4,
};
}
// NOTE - this assumes no buffer_t or variable_buffers are passed
// data is converted to a uint64_t when placed into the sbe ffdc
// buffer
inline fapi2::ffdc_t getFfdcData( sbeFfdc_t& i_sbeFfdc )
{
fapi2::ffdc_t temp;
temp.size() = static_cast<size_t>(i_sbeFfdc.size);
if(temp.size() == EI_FFDC_SIZE_TARGET)
{
#ifdef FAPI2_ENABLE_PLATFORM_GET_TARGET
uint64_t targetData = i_sbeFfdc.data;
fapi2::TargetType type = static_cast<fapi2::TargetType>(targetData >> 32);
uint8_t instance = static_cast<uint8_t>(targetData & 0xFFFFFFFF);
// call hostboot to get the fapi2 target reference
temp.ptr() = static_cast<void*>(getTarget<TARGET_TYPE_ALL>(type, instance));
#endif
}
else
{
// adjust the pointer based on the data size.
temp.ptr() = static_cast<void*>(reinterpret_cast<uint8_t*>(&i_sbeFfdc.data) +
(sizeof(uint64_t) - i_sbeFfdc.size));
}
return temp;
}
#endif
///
/// @brief Get FFDC Size
///
/// This is called by the FAPI_SET_HWP_ERROR macro to find out the size of
/// FFDC data. If the data is of a special type that is handled differently
/// than types that are simply memcopied then it is handled by a template
/// specialization.
/// If this function template is instantiated with a pointer, the compile
/// will fail.
///
/// @return uint16_t. Size of the FFDC data
///
template<typename T>
inline uint16_t getErrorInfoFfdcSize(const T&)
{
static_assert(sizeof(T) <= EI_FFDC_MAX_SIZE,
"FFDC too large to capture");
return sizeof(T);
}
#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)
///
/// @brief Compile error if caller tries to get the FFDC size of a pointer
///
template<typename T>
inline uint16_t getErrorInfoFfdcSize(const T*)
{
static_assert(std::is_pointer<T>::value,
"pointer passed to getErrorInfoFfdcSize");
return 0;
}
#endif
///
/// @brief Get FFDC Size specialization for fapi2::Target
///
template<fapi2::TargetType T, typename V>
inline uint16_t getErrorInfoFfdcSize(const fapi2::Target<T, V>&)
{
return EI_FFDC_SIZE_TARGET;
}
#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)
///
/// @brief Get FFDC Size specialization for variable buffers
///
template<>
inline uint16_t getErrorInfoFfdcSize(const fapi2::variable_buffer& i_thing)
{
// Limit a variable buffer to 4kb bytes, and we can memcpy the storage.
return std::min(static_cast<uint32_t>(EI_FFDC_MAX_SIZE),
i_thing.getLength<uint8_t>());
}
#endif
};
#endif // FAPI2_ERRORINFO_DEFS_H_
<commit_msg>Enable and fix error log variable_buffer support.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/hwpf/fapi2/include/error_info_defs.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2011,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file error_info_defs.H
/// @brief Defines to support the Error Information class
///
#ifndef FAPI2_ERRORINFO_DEFS_H_
#define FAPI2_ERRORINFO_DEFS_H_
#include <stdint.h>
#include <target.H>
#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)
#include <variable_buffer.H>
#include <utility>
#endif
namespace fapi2
{
///
/// @brief Type to hold the ffdc data to be sent to hostboot
///
/// Note: Typical data sent seems to be register/addresss info
/// rather than use extra space converting stuff just
/// send a uint64 always
///
struct sbeFfdc_t
{
uint32_t size;
uint64_t data;
} __attribute__((packed));
// 10 entries limits the size of SbeFfdcData_t to 128 bytes
enum
{
MAX_SBE_FFDC_ENTRIES = 10
};
// Data type for SBE ffdc buffer sent through fifo
typedef struct
{
uint32_t fapiRc; // Return code from failure
uint32_t ffdcLength; // length of Fapi FFDC data (in bytes)
struct sbeFfdc_t ffdcData[MAX_SBE_FFDC_ENTRIES]; // fapi FFDC data
} SbeFfdcData_t; // 128 bytes
///
/// @brief Type to hold the ffdc element in the ffdc class
/// Needed so that the size can be squirled away before the
/// macro is called.
///
struct ffdc_struct
{
const void* ptr;
size_t size;
};
class ffdc_t
{
public:
ffdc_t(void)
{}
void operator=(const ffdc_t& i )
{
iv_value.ptr = i.ptr();
iv_value.size = i.size();
}
operator const void* () const
{
return iv_value.ptr;
}
operator uint8_t() const
{
return *(reinterpret_cast<const uint8_t*>(iv_value.ptr));
}
size_t size(void) const
{
return iv_value.size;
}
size_t& size(void)
{
return iv_value.size;
}
const void* ptr(void) const
{
return iv_value.ptr;
}
const void*& ptr(void)
{
return iv_value.ptr;
}
private:
struct ffdc_struct iv_value = {}; //init to zero
};
///
/// @brief Enumeration of ErrorInfo FFDC sizes that are used to indicate a
/// special type that cannot simply be memcopied
enum ErrorInfoFfdcSize
{
EI_FFDC_SIZE_BUF = 0xffff, // fapi2::buffer<T>
EI_FFDC_SIZE_TARGET = 0xfffe, // fapi2::Target
EI_FFDC_SIZE_VBUF = 0xfffd, // fapi2::variable_buffer
EI_FFDC_MAX_SIZE = 0x1000, // Limit regular FFDC capture to 4kb
};
///
/// @brief Enumeration of error log severity.
///
enum errlSeverity_t
{
FAPI2_ERRL_SEV_UNDEFINED = 0x00, /// Used internally by ffdc mechanism
FAPI2_ERRL_SEV_RECOVERED = 0x10, /// Not seen by customer
FAPI2_ERRL_SEV_PREDICTIVE = 0x20, /// Error recovered but customer will see
FAPI2_ERRL_SEV_UNRECOVERABLE = 0x40 /// Unrecoverable, general
};
///
/// @brief Enumeration of ErrorInfo types
///
enum ErrorInfoType
{
EI_TYPE_FFDC = 0,
EI_TYPE_HW_CALLOUT = 1,
EI_TYPE_PROCEDURE_CALLOUT = 2,
EI_TYPE_BUS_CALLOUT = 3,
EI_TYPE_CDG = 4, // Target Callout/Deconfig/GARD
EI_TYPE_CHILDREN_CDG = 5, // Children Callout/Deconfig/GARD
EI_TYPE_COLLECT_TRACE = 6,
EI_LAST_TYPE = EI_TYPE_COLLECT_TRACE + 1,
};
#ifndef MINIMUM_FFDC
///
/// @enum HwCallout
///
/// This enumeration defines the possible Hardware Callouts that are not
/// represented by fapi2::Targets
///
/// Note that platform code may depend on the enum values starting at 0 and
/// incrementing in order to efficiently convert to a platform callout value
/// so do not reorder without consulting all platforms
///
namespace HwCallouts
{
enum HwCallout
{
// Where indicated, a HW Callout in FAPI Error XML must include a
// reference target that is used to identify the HW. e.g. for
// TOD_CLOCK, the proc chip that the clock is attached to must be
// specified
TOD_CLOCK = 0, // Include proc-chip ref (or child chiplet)
MEM_REF_CLOCK = 1, // Include membuf-chip ref (or child chiplet)
PROC_REF_CLOCK = 2, // Include proc-chip ref (or child chiplet)
PCI_REF_CLOCK = 3, // Include proc-chip ref (or child chiplet)
FLASH_CONTROLLER_PART = 4,
PNOR_PART = 5,
SBE_SEEPROM_PART = 6,
VPD_PART = 7,
LPC_SLAVE_PART = 8,
GPIO_EXPANDER_PART = 9,
SPIVID_SLAVE_PART = 10,
};
}
///
/// @enum ProcedureCallout
///
/// This enumeration defines the possible Procedure Callouts
/// These instruct the customer/customer-engineer what to do
///
/// Note that platform code may depend on the enum values starting at 0 and
/// incrementing in order to efficiently convert to a platform callout value
/// so do not reorder without consulting all platforms
///
namespace ProcedureCallouts
{
enum ProcedureCallout
{
CODE = 0, // Code problem
LVL_SUPPORT = 1, // Call next level of support
MEMORY_PLUGGING_ERROR = 2, // DIMM Plugging error
BUS_CALLOUT = 3, // Bus Called Out
};
}
///
/// @enum CalloutPriority
///
/// This enumeration defines the possible Procedure and Target callout priorities
///
/// Note that platform code may depend on the enum values starting at 0 and
/// incrementing in order to efficiently convert to a platform priority value
/// so do not reorder without consulting all platforms
///
namespace CalloutPriorities
{
enum CalloutPriority
{
LOW = 0,
MEDIUM = 1,
HIGH = 2,
};
}
///
/// @enum CollectTrace
///
/// This enumeration defines the possible firmware traces to collect
///
namespace CollectTraces
{
const uint32_t TRACE_SIZE = 256; // limit collected trace size
enum CollectTrace
{
FSI = 1,
SCOM = 2,
SCAN = 3,
MBOX = 4,
};
}
// NOTE - this assumes no buffer_t or variable_buffers are passed
// data is converted to a uint64_t when placed into the sbe ffdc
// buffer
inline fapi2::ffdc_t getFfdcData( sbeFfdc_t& i_sbeFfdc )
{
fapi2::ffdc_t temp;
temp.size() = static_cast<size_t>(i_sbeFfdc.size);
if(temp.size() == EI_FFDC_SIZE_TARGET)
{
#ifdef FAPI2_ENABLE_PLATFORM_GET_TARGET
uint64_t targetData = i_sbeFfdc.data;
fapi2::TargetType type = static_cast<fapi2::TargetType>(targetData >> 32);
uint8_t instance = static_cast<uint8_t>(targetData & 0xFFFFFFFF);
// call hostboot to get the fapi2 target reference
temp.ptr() = static_cast<void*>(getTarget<TARGET_TYPE_ALL>(type, instance));
#endif
}
else
{
// adjust the pointer based on the data size.
temp.ptr() = static_cast<void*>(reinterpret_cast<uint8_t*>(&i_sbeFfdc.data) +
(sizeof(uint64_t) - i_sbeFfdc.size));
}
return temp;
}
#endif
///
/// @brief Get FFDC Size
///
/// This is called by the FAPI_SET_HWP_ERROR macro to find out the size of
/// FFDC data. If the data is of a special type that is handled differently
/// than types that are simply memcopied then it is handled by a template
/// specialization.
/// If this function template is instantiated with a pointer, the compile
/// will fail.
///
/// @return uint16_t. Size of the FFDC data
///
template<typename T>
inline uint16_t getErrorInfoFfdcSize(const T&)
{
static_assert(sizeof(T) <= EI_FFDC_MAX_SIZE,
"FFDC too large to capture");
return sizeof(T);
}
#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)
///
/// @brief Compile error if caller tries to get the FFDC size of a pointer
///
template<typename T>
inline uint16_t getErrorInfoFfdcSize(const T*)
{
static_assert(std::is_pointer<T>::value,
"pointer passed to getErrorInfoFfdcSize");
return 0;
}
#endif
///
/// @brief Get FFDC Size specialization for fapi2::Target
///
template<fapi2::TargetType T, typename V>
inline uint16_t getErrorInfoFfdcSize(const fapi2::Target<T, V>&)
{
return EI_FFDC_SIZE_TARGET;
}
#if !defined(MINIMUM_FFDC) && !defined(FAPI2_NO_FFDC)
///
/// @brief Get FFDC Size specialization for variable buffers
///
template<>
inline uint16_t getErrorInfoFfdcSize(const fapi2::variable_buffer& i_thing)
{
// Limit a variable buffer to 4kb bytes, and we can memcpy the storage.
return std::min(static_cast<uint32_t>(EI_FFDC_MAX_SIZE),
i_thing.getLength<uint8_t>());
}
#endif
///
/// @brief Get FFDC Size specialization for ffdc_t
///
template<>
inline uint16_t getErrorInfoFfdcSize(const fapi2::ffdc_t& i_ffdc)
{
return static_cast<uint16_t>(i_ffdc.size());
}
};
#endif // FAPI2_ERRORINFO_DEFS_H_
<|endoftext|> |
<commit_before>/*
nsjail - config parsing
-----------------------------------------
Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
extern "C" {
#include "common.h"
#include <fcntl.h>
#include <stdio.h>
#include <sys/mount.h>
#include <sys/personality.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "caps.h"
#include "cmdline.h"
#include "config.h"
#include "log.h"
#include "mount.h"
#include "user.h"
#include "util.h"
}
#include <fstream>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <string>
#include <vector>
#include "config.pb.h"
#define DUP_IF_SET(njc, val) (njc.has_##val() ? njc.val().c_str() : NULL)
static __rlim64_t configRLimit(int res, const nsjail::RLimit& rl, const uint64_t val, unsigned long mul = 1UL)
{
if (rl == nsjail::RLimit::VALUE) {
return (val * mul);
}
if (rl == nsjail::RLimit::SOFT) {
return cmdlineParseRLimit(res, "soft", mul);
}
if (rl == nsjail::RLimit::HARD) {
return cmdlineParseRLimit(res, "hard", mul);
}
if (rl == nsjail::RLimit::INF) {
return RLIM64_INFINITY;
}
LOG_F("Unknown rlimit value type for rlimit:%d", res);
abort();
}
static bool configParseInternal(struct nsjconf_t* nsjconf,
const nsjail::NsJailConfig& njc)
{
switch (njc.mode()) {
case nsjail::Mode::LISTEN:
nsjconf->mode = MODE_LISTEN_TCP;
break;
case nsjail::Mode::ONCE:
nsjconf->mode = MODE_STANDALONE_ONCE;
break;
case nsjail::Mode::RERUN:
nsjconf->mode = MODE_STANDALONE_RERUN;
break;
case nsjail::Mode::EXECVE:
nsjconf->mode = MODE_STANDALONE_EXECVE;
break;
default:
LOG_E("Uknown running mode: %d", njc.mode());
return false;
}
nsjconf->chroot = DUP_IF_SET(njc, chroot_dir);
nsjconf->is_root_rw = njc.is_root_rw();
nsjconf->hostname = njc.hostname().c_str();
nsjconf->cwd = njc.cwd().c_str();
nsjconf->port = njc.port();
nsjconf->bindhost = njc.bindhost().c_str();
nsjconf->max_conns_per_ip = njc.max_conns_per_ip();
nsjconf->tlimit = njc.time_limit();
nsjconf->max_cpus = njc.max_cpus();
nsjconf->daemonize = njc.daemon();
if (njc.has_log_fd()) {
nsjconf->log_fd = njc.log_fd();
}
nsjconf->logfile = DUP_IF_SET(njc, log_file);
if (njc.has_log_level()) {
switch (njc.log_level()) {
case nsjail::LogLevel::DEBUG:
nsjconf->loglevel = DEBUG;
break;
case nsjail::LogLevel::INFO:
nsjconf->loglevel = INFO;
break;
case nsjail::LogLevel::WARNING:
nsjconf->loglevel = WARNING;
break;
case nsjail::LogLevel::ERROR:
nsjconf->loglevel = ERROR;
break;
case nsjail::LogLevel::FATAL:
nsjconf->loglevel = FATAL;
break;
default:
LOG_E("Unknown log_level: %d", njc.log_level());
return false;
}
}
if (njc.has_log_fd() || njc.has_log_file() || njc.has_log_level()) {
if (logInitLogFile(nsjconf) == false) {
return false;
}
}
nsjconf->keep_env = njc.keep_env();
for (ssize_t i = 0; i < njc.envar_size(); i++) {
struct charptr_t* p = reinterpret_cast<charptr_t*>(utilMalloc(sizeof(struct charptr_t)));
p->val = njc.envar(i).c_str();
TAILQ_INSERT_TAIL(&nsjconf->envs, p, pointers);
}
nsjconf->keep_caps = njc.keep_caps();
for (ssize_t i = 0; i < njc.cap_size(); i++) {
struct ints_t* f = reinterpret_cast<struct ints_t*>(utilMalloc(sizeof(struct ints_t)));
f->val = capsNameToVal(njc.cap(i).c_str());
if (f->val == -1) {
return false;
}
TAILQ_INSERT_HEAD(&nsjconf->caps, f, pointers);
}
nsjconf->is_silent = njc.silent();
nsjconf->skip_setsid = njc.skip_setsid();
for (ssize_t i = 0; i < njc.pass_fd_size(); i++) {
struct ints_t* f = reinterpret_cast<struct ints_t*>(utilMalloc(sizeof(struct ints_t)));
f->val = njc.pass_fd(i);
TAILQ_INSERT_HEAD(&nsjconf->open_fds, f, pointers);
}
nsjconf->disable_no_new_privs = njc.disable_no_new_privs();
nsjconf->rl_as = configRLimit(RLIMIT_AS, njc.rlimit_as_type(), njc.rlimit_as(), 1024UL * 1024UL);
nsjconf->rl_core = configRLimit(RLIMIT_CORE, njc.rlimit_core_type(), njc.rlimit_core(), 1024UL * 1024UL);
nsjconf->rl_cpu = configRLimit(RLIMIT_CPU, njc.rlimit_cpu_type(), njc.rlimit_cpu());
nsjconf->rl_fsize = configRLimit(RLIMIT_FSIZE, njc.rlimit_fsize_type(), njc.rlimit_fsize(), 1024UL * 1024UL);
nsjconf->rl_nofile = configRLimit(RLIMIT_NOFILE, njc.rlimit_nofile_type(), njc.rlimit_nofile());
nsjconf->rl_nproc = configRLimit(RLIMIT_NPROC, njc.rlimit_nproc_type(), njc.rlimit_nproc());
nsjconf->rl_stack = configRLimit(RLIMIT_STACK, njc.rlimit_stack_type(), njc.rlimit_stack(), 1024UL * 1024UL);
if (njc.persona_addr_compat_layout()) {
nsjconf->personality |= ADDR_COMPAT_LAYOUT;
}
if (njc.persona_mmap_page_zero()) {
nsjconf->personality |= MMAP_PAGE_ZERO;
}
if (njc.persona_read_implies_exec()) {
nsjconf->personality |= READ_IMPLIES_EXEC;
}
if (njc.persona_addr_limit_3gb()) {
nsjconf->personality |= ADDR_LIMIT_3GB;
}
if (njc.persona_addr_no_randomize()) {
nsjconf->personality |= ADDR_NO_RANDOMIZE;
}
nsjconf->clone_newnet = njc.clone_newnet();
nsjconf->clone_newuser = njc.clone_newuser();
nsjconf->clone_newns = njc.clone_newns();
nsjconf->clone_newpid = njc.clone_newpid();
nsjconf->clone_newipc = njc.clone_newipc();
nsjconf->clone_newuts = njc.clone_newuts();
nsjconf->clone_newcgroup = njc.clone_newcgroup();
for (ssize_t i = 0; i < njc.uidmap_size(); i++) {
if (userParseId(nsjconf, DUP_IF_SET(njc.uidmap(i), inside_id), DUP_IF_SET(njc.uidmap(i), outside_id),
njc.uidmap(i).count(), false /* is_gid */,
njc.uidmap(i).use_newidmap())
== false) {
return false;
}
}
for (ssize_t i = 0; i < njc.gidmap_size(); i++) {
if (userParseId(nsjconf, DUP_IF_SET(njc.gidmap(i), inside_id), DUP_IF_SET(njc.gidmap(i), outside_id),
njc.gidmap(i).count(), true /* is_gid */,
njc.gidmap(i).use_newidmap())
== false) {
return false;
}
}
nsjconf->mount_proc = njc.mount_proc();
for (ssize_t i = 0; i < njc.mount_size(); i++) {
const char* src = (njc.mount(i).has_src()) ? njc.mount(i).src().c_str() : NULL;
const char* src_env = (njc.mount(i).has_prefix_src_env()) ? njc.mount(i).prefix_src_env().c_str() : NULL;
const char* dst = (njc.mount(i).has_dst()) ? njc.mount(i).dst().c_str() : NULL;
const char* dst_env = (njc.mount(i).has_prefix_dst_env()) ? njc.mount(i).prefix_dst_env().c_str() : NULL;
const char* fstype = (njc.mount(i).has_fstype()) ? njc.mount(i).fstype().c_str() : NULL;
const char* options = (njc.mount(i).has_options()) ? njc.mount(i).options().c_str() : NULL;
uintptr_t flags = (njc.mount(i).rw() == false) ? MS_RDONLY : 0;
flags |= njc.mount(i).is_bind() ? (MS_BIND | MS_REC) : 0;
bool mandatory = njc.mount(i).mandatory();
isDir_t isDir = NS_DIR_MAYBE;
if (njc.mount(i).has_is_dir()) {
isDir = njc.mount(i).is_dir() ? NS_DIR_YES : NS_DIR_NO;
}
const char* src_content = NULL;
size_t src_content_len = 0;
if (njc.mount(i).has_src_content()) {
src_content = njc.mount(i).src_content().data();
src_content_len = njc.mount(i).src_content().size();
}
if (mountAddMountPt(nsjconf, src, dst, fstype, options, flags, isDir,
mandatory, src_env, dst_env, src_content,
src_content_len, njc.mount(i).is_symlink())
== false) {
LOG_E("Couldn't add mountpoint for src:'%s' dst:'%s'", src, dst);
return false;
}
}
if (njc.has_seccomp_policy_file()) {
if ((nsjconf->kafel_file = fopen(njc.seccomp_policy_file().c_str(), "rb")) == NULL) {
PLOG_W("Couldn't open file with seccomp policy '%s'",
njc.seccomp_policy_file().c_str());
return false;
}
}
std::string kafel_string;
for (ssize_t i = 0; i < njc.seccomp_string().size(); i++) {
kafel_string += njc.seccomp_string(i);
}
nsjconf->kafel_string = njc.seccomp_string().size() > 0
? utilStrDup(kafel_string.c_str())
: NULL;
nsjconf->cgroup_mem_max = njc.cgroup_mem_max();
nsjconf->cgroup_mem_mount = njc.cgroup_mem_mount().c_str();
nsjconf->cgroup_mem_parent = njc.cgroup_mem_parent().c_str();
nsjconf->cgroup_pids_max = njc.cgroup_pids_max();
nsjconf->cgroup_pids_mount = njc.cgroup_pids_mount().c_str();
nsjconf->cgroup_pids_parent = njc.cgroup_pids_parent().c_str();
nsjconf->iface_no_lo = njc.iface_no_lo();
nsjconf->iface_vs = DUP_IF_SET(njc, macvlan_iface);
nsjconf->iface_vs_ip = njc.macvlan_vs_ip().c_str();
nsjconf->iface_vs_nm = njc.macvlan_vs_nm().c_str();
nsjconf->iface_vs_gw = njc.macvlan_vs_gw().c_str();
if (njc.has_exec_bin()) {
std::vector<const char*>* argv = new std::vector<const char*>;
if (njc.exec_bin().has_arg0()) {
argv->push_back(njc.exec_bin().arg0().c_str());
} else {
argv->push_back(njc.exec_bin().path().c_str());
}
for (ssize_t i = 0; i < njc.exec_bin().arg().size(); i++) {
argv->push_back(njc.exec_bin().arg(i).c_str());
}
argv->push_back(nullptr);
nsjconf->exec_file = DUP_IF_SET(njc.exec_bin(), path);
nsjconf->argv = argv->data();
}
return true;
}
static void LogHandler(google::protobuf::LogLevel level, const char* filename, int line, const std::string& message)
{
LOG_W("config.cc: '%s'", message.c_str());
}
extern "C" bool configParse(struct nsjconf_t* nsjconf, const char* file)
{
LOG_I("Parsing configuration from '%s'", file);
int fd = open(file, O_RDONLY);
if (fd == -1) {
PLOG_W("Couldn't open config file '%s'", file);
return false;
}
SetLogHandler(LogHandler);
google::protobuf::io::FileInputStream input(fd);
input.SetCloseOnDelete(true);
static nsjail::NsJailConfig nsc;
auto parser = google::protobuf::TextFormat::Parser();
if (!parser.Parse(&input, &nsc)) {
LOG_W("Couldn't parse file '%s' from Text into ProtoBuf", file);
return false;
}
if (!configParseInternal(nsjconf, nsc)) {
LOG_W("Couldn't parse the ProtoBuf");
return false;
}
LOG_D("Parsed config:\n'%s'", nsc.DebugString().c_str());
return true;
}
<commit_msg>config: make argv static to avoid using heap<commit_after>/*
nsjail - config parsing
-----------------------------------------
Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
extern "C" {
#include "common.h"
#include <fcntl.h>
#include <stdio.h>
#include <sys/mount.h>
#include <sys/personality.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "caps.h"
#include "cmdline.h"
#include "config.h"
#include "log.h"
#include "mount.h"
#include "user.h"
#include "util.h"
}
#include <fstream>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <string>
#include <vector>
#include "config.pb.h"
#define DUP_IF_SET(njc, val) (njc.has_##val() ? njc.val().c_str() : NULL)
static __rlim64_t configRLimit(int res, const nsjail::RLimit& rl, const uint64_t val, unsigned long mul = 1UL)
{
if (rl == nsjail::RLimit::VALUE) {
return (val * mul);
}
if (rl == nsjail::RLimit::SOFT) {
return cmdlineParseRLimit(res, "soft", mul);
}
if (rl == nsjail::RLimit::HARD) {
return cmdlineParseRLimit(res, "hard", mul);
}
if (rl == nsjail::RLimit::INF) {
return RLIM64_INFINITY;
}
LOG_F("Unknown rlimit value type for rlimit:%d", res);
abort();
}
static bool configParseInternal(struct nsjconf_t* nsjconf,
const nsjail::NsJailConfig& njc)
{
switch (njc.mode()) {
case nsjail::Mode::LISTEN:
nsjconf->mode = MODE_LISTEN_TCP;
break;
case nsjail::Mode::ONCE:
nsjconf->mode = MODE_STANDALONE_ONCE;
break;
case nsjail::Mode::RERUN:
nsjconf->mode = MODE_STANDALONE_RERUN;
break;
case nsjail::Mode::EXECVE:
nsjconf->mode = MODE_STANDALONE_EXECVE;
break;
default:
LOG_E("Uknown running mode: %d", njc.mode());
return false;
}
nsjconf->chroot = DUP_IF_SET(njc, chroot_dir);
nsjconf->is_root_rw = njc.is_root_rw();
nsjconf->hostname = njc.hostname().c_str();
nsjconf->cwd = njc.cwd().c_str();
nsjconf->port = njc.port();
nsjconf->bindhost = njc.bindhost().c_str();
nsjconf->max_conns_per_ip = njc.max_conns_per_ip();
nsjconf->tlimit = njc.time_limit();
nsjconf->max_cpus = njc.max_cpus();
nsjconf->daemonize = njc.daemon();
if (njc.has_log_fd()) {
nsjconf->log_fd = njc.log_fd();
}
nsjconf->logfile = DUP_IF_SET(njc, log_file);
if (njc.has_log_level()) {
switch (njc.log_level()) {
case nsjail::LogLevel::DEBUG:
nsjconf->loglevel = DEBUG;
break;
case nsjail::LogLevel::INFO:
nsjconf->loglevel = INFO;
break;
case nsjail::LogLevel::WARNING:
nsjconf->loglevel = WARNING;
break;
case nsjail::LogLevel::ERROR:
nsjconf->loglevel = ERROR;
break;
case nsjail::LogLevel::FATAL:
nsjconf->loglevel = FATAL;
break;
default:
LOG_E("Unknown log_level: %d", njc.log_level());
return false;
}
}
if (njc.has_log_fd() || njc.has_log_file() || njc.has_log_level()) {
if (logInitLogFile(nsjconf) == false) {
return false;
}
}
nsjconf->keep_env = njc.keep_env();
for (ssize_t i = 0; i < njc.envar_size(); i++) {
struct charptr_t* p = reinterpret_cast<charptr_t*>(utilMalloc(sizeof(struct charptr_t)));
p->val = njc.envar(i).c_str();
TAILQ_INSERT_TAIL(&nsjconf->envs, p, pointers);
}
nsjconf->keep_caps = njc.keep_caps();
for (ssize_t i = 0; i < njc.cap_size(); i++) {
struct ints_t* f = reinterpret_cast<struct ints_t*>(utilMalloc(sizeof(struct ints_t)));
f->val = capsNameToVal(njc.cap(i).c_str());
if (f->val == -1) {
return false;
}
TAILQ_INSERT_HEAD(&nsjconf->caps, f, pointers);
}
nsjconf->is_silent = njc.silent();
nsjconf->skip_setsid = njc.skip_setsid();
for (ssize_t i = 0; i < njc.pass_fd_size(); i++) {
struct ints_t* f = reinterpret_cast<struct ints_t*>(utilMalloc(sizeof(struct ints_t)));
f->val = njc.pass_fd(i);
TAILQ_INSERT_HEAD(&nsjconf->open_fds, f, pointers);
}
nsjconf->disable_no_new_privs = njc.disable_no_new_privs();
nsjconf->rl_as = configRLimit(RLIMIT_AS, njc.rlimit_as_type(), njc.rlimit_as(), 1024UL * 1024UL);
nsjconf->rl_core = configRLimit(RLIMIT_CORE, njc.rlimit_core_type(), njc.rlimit_core(), 1024UL * 1024UL);
nsjconf->rl_cpu = configRLimit(RLIMIT_CPU, njc.rlimit_cpu_type(), njc.rlimit_cpu());
nsjconf->rl_fsize = configRLimit(RLIMIT_FSIZE, njc.rlimit_fsize_type(), njc.rlimit_fsize(), 1024UL * 1024UL);
nsjconf->rl_nofile = configRLimit(RLIMIT_NOFILE, njc.rlimit_nofile_type(), njc.rlimit_nofile());
nsjconf->rl_nproc = configRLimit(RLIMIT_NPROC, njc.rlimit_nproc_type(), njc.rlimit_nproc());
nsjconf->rl_stack = configRLimit(RLIMIT_STACK, njc.rlimit_stack_type(), njc.rlimit_stack(), 1024UL * 1024UL);
if (njc.persona_addr_compat_layout()) {
nsjconf->personality |= ADDR_COMPAT_LAYOUT;
}
if (njc.persona_mmap_page_zero()) {
nsjconf->personality |= MMAP_PAGE_ZERO;
}
if (njc.persona_read_implies_exec()) {
nsjconf->personality |= READ_IMPLIES_EXEC;
}
if (njc.persona_addr_limit_3gb()) {
nsjconf->personality |= ADDR_LIMIT_3GB;
}
if (njc.persona_addr_no_randomize()) {
nsjconf->personality |= ADDR_NO_RANDOMIZE;
}
nsjconf->clone_newnet = njc.clone_newnet();
nsjconf->clone_newuser = njc.clone_newuser();
nsjconf->clone_newns = njc.clone_newns();
nsjconf->clone_newpid = njc.clone_newpid();
nsjconf->clone_newipc = njc.clone_newipc();
nsjconf->clone_newuts = njc.clone_newuts();
nsjconf->clone_newcgroup = njc.clone_newcgroup();
for (ssize_t i = 0; i < njc.uidmap_size(); i++) {
if (userParseId(nsjconf, DUP_IF_SET(njc.uidmap(i), inside_id), DUP_IF_SET(njc.uidmap(i), outside_id),
njc.uidmap(i).count(), false /* is_gid */,
njc.uidmap(i).use_newidmap())
== false) {
return false;
}
}
for (ssize_t i = 0; i < njc.gidmap_size(); i++) {
if (userParseId(nsjconf, DUP_IF_SET(njc.gidmap(i), inside_id), DUP_IF_SET(njc.gidmap(i), outside_id),
njc.gidmap(i).count(), true /* is_gid */,
njc.gidmap(i).use_newidmap())
== false) {
return false;
}
}
nsjconf->mount_proc = njc.mount_proc();
for (ssize_t i = 0; i < njc.mount_size(); i++) {
const char* src = (njc.mount(i).has_src()) ? njc.mount(i).src().c_str() : NULL;
const char* src_env = (njc.mount(i).has_prefix_src_env()) ? njc.mount(i).prefix_src_env().c_str() : NULL;
const char* dst = (njc.mount(i).has_dst()) ? njc.mount(i).dst().c_str() : NULL;
const char* dst_env = (njc.mount(i).has_prefix_dst_env()) ? njc.mount(i).prefix_dst_env().c_str() : NULL;
const char* fstype = (njc.mount(i).has_fstype()) ? njc.mount(i).fstype().c_str() : NULL;
const char* options = (njc.mount(i).has_options()) ? njc.mount(i).options().c_str() : NULL;
uintptr_t flags = (njc.mount(i).rw() == false) ? MS_RDONLY : 0;
flags |= njc.mount(i).is_bind() ? (MS_BIND | MS_REC) : 0;
bool mandatory = njc.mount(i).mandatory();
isDir_t isDir = NS_DIR_MAYBE;
if (njc.mount(i).has_is_dir()) {
isDir = njc.mount(i).is_dir() ? NS_DIR_YES : NS_DIR_NO;
}
const char* src_content = NULL;
size_t src_content_len = 0;
if (njc.mount(i).has_src_content()) {
src_content = njc.mount(i).src_content().data();
src_content_len = njc.mount(i).src_content().size();
}
if (mountAddMountPt(nsjconf, src, dst, fstype, options, flags, isDir,
mandatory, src_env, dst_env, src_content,
src_content_len, njc.mount(i).is_symlink())
== false) {
LOG_E("Couldn't add mountpoint for src:'%s' dst:'%s'", src, dst);
return false;
}
}
if (njc.has_seccomp_policy_file()) {
if ((nsjconf->kafel_file = fopen(njc.seccomp_policy_file().c_str(), "rb")) == NULL) {
PLOG_W("Couldn't open file with seccomp policy '%s'",
njc.seccomp_policy_file().c_str());
return false;
}
}
std::string kafel_string;
for (ssize_t i = 0; i < njc.seccomp_string().size(); i++) {
kafel_string += njc.seccomp_string(i);
}
nsjconf->kafel_string = njc.seccomp_string().size() > 0
? utilStrDup(kafel_string.c_str())
: NULL;
nsjconf->cgroup_mem_max = njc.cgroup_mem_max();
nsjconf->cgroup_mem_mount = njc.cgroup_mem_mount().c_str();
nsjconf->cgroup_mem_parent = njc.cgroup_mem_parent().c_str();
nsjconf->cgroup_pids_max = njc.cgroup_pids_max();
nsjconf->cgroup_pids_mount = njc.cgroup_pids_mount().c_str();
nsjconf->cgroup_pids_parent = njc.cgroup_pids_parent().c_str();
nsjconf->iface_no_lo = njc.iface_no_lo();
nsjconf->iface_vs = DUP_IF_SET(njc, macvlan_iface);
nsjconf->iface_vs_ip = njc.macvlan_vs_ip().c_str();
nsjconf->iface_vs_nm = njc.macvlan_vs_nm().c_str();
nsjconf->iface_vs_gw = njc.macvlan_vs_gw().c_str();
if (njc.has_exec_bin()) {
static std::vector<const char*> argv;
if (njc.exec_bin().has_arg0()) {
argv.push_back(njc.exec_bin().arg0().c_str());
} else {
argv.push_back(njc.exec_bin().path().c_str());
}
for (ssize_t i = 0; i < njc.exec_bin().arg().size(); i++) {
argv.push_back(njc.exec_bin().arg(i).c_str());
}
argv.push_back(nullptr);
nsjconf->exec_file = DUP_IF_SET(njc.exec_bin(), path);
nsjconf->argv = argv.data();
}
return true;
}
static void LogHandler(google::protobuf::LogLevel level, const char* filename, int line, const std::string& message)
{
LOG_W("config.cc: '%s'", message.c_str());
}
extern "C" bool configParse(struct nsjconf_t* nsjconf, const char* file)
{
LOG_I("Parsing configuration from '%s'", file);
int fd = open(file, O_RDONLY);
if (fd == -1) {
PLOG_W("Couldn't open config file '%s'", file);
return false;
}
SetLogHandler(LogHandler);
google::protobuf::io::FileInputStream input(fd);
input.SetCloseOnDelete(true);
static nsjail::NsJailConfig nsc;
auto parser = google::protobuf::TextFormat::Parser();
if (!parser.Parse(&input, &nsc)) {
LOG_W("Couldn't parse file '%s' from Text into ProtoBuf", file);
return false;
}
if (!configParseInternal(nsjconf, nsc)) {
LOG_W("Couldn't parse the ProtoBuf");
return false;
}
LOG_D("Parsed config:\n'%s'", nsc.DebugString().c_str());
return true;
}
<|endoftext|> |
<commit_before>#include "core.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm-c/Linker.h"
extern "C" {
API_EXPORT(int)
LLVMPY_LinkModules(LLVMModuleRef Dest, LLVMModuleRef Src, const char **Err)
{
using namespace llvm;
std::string errorstring;
llvm::raw_string_ostream errstream(errorstring);
Module *D = unwrap(Dest);
LLVMContext &Ctx = D->getContext();
// This exists at the change to LLVM 6.x
// Link error diagnostics end up with a call to abort()
// install this handler to instead extract the reason for failure
// and report it.
class ReportNotAbortDiagnosticHandler: public DiagnosticHandler {
public:
ReportNotAbortDiagnosticHandler(llvm::raw_string_ostream &s):
raw_stream(s) {}
bool handleDiagnostics(const DiagnosticInfo &DI) override
{
llvm::DiagnosticPrinterRawOStream DP(raw_stream);
DI.print(DP);
return true;
}
private:
llvm::raw_string_ostream& raw_stream;
};
// save current handler as "old"
auto OldDiagnosticHandler = Ctx.getDiagnosticHandler();
// set the handler to a new one
Ctx.setDiagnosticHandler(llvm::make_unique<ReportNotAbortDiagnosticHandler>(errstream));
// link
bool failed = LLVMLinkModules2(Dest, Src);
// put old handler back
Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
// if linking failed extract the reason for the failure
if (failed) {
errstream.flush();
*Err = LLVMPY_CreateString(errorstring.c_str());
}
return failed;
}
} // end extern "C"
<commit_msg>Use std::make_unique on LLVM 10<commit_after>#include "core.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm-c/Linker.h"
extern "C" {
API_EXPORT(int)
LLVMPY_LinkModules(LLVMModuleRef Dest, LLVMModuleRef Src, const char **Err)
{
using namespace llvm;
std::string errorstring;
llvm::raw_string_ostream errstream(errorstring);
Module *D = unwrap(Dest);
LLVMContext &Ctx = D->getContext();
// This exists at the change to LLVM 6.x
// Link error diagnostics end up with a call to abort()
// install this handler to instead extract the reason for failure
// and report it.
class ReportNotAbortDiagnosticHandler: public DiagnosticHandler {
public:
ReportNotAbortDiagnosticHandler(llvm::raw_string_ostream &s):
raw_stream(s) {}
bool handleDiagnostics(const DiagnosticInfo &DI) override
{
llvm::DiagnosticPrinterRawOStream DP(raw_stream);
DI.print(DP);
return true;
}
private:
llvm::raw_string_ostream& raw_stream;
};
// save current handler as "old"
auto OldDiagnosticHandler = Ctx.getDiagnosticHandler();
// set the handler to a new one
#if LLVM_VERSION_MAJOR >= 10
Ctx.setDiagnosticHandler(std::make_unique<ReportNotAbortDiagnosticHandler>(errstream));
#else
Ctx.setDiagnosticHandler(llvm::make_unique<ReportNotAbortDiagnosticHandler>(errstream));
#endif
// link
bool failed = LLVMLinkModules2(Dest, Src);
// put old handler back
Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
// if linking failed extract the reason for the failure
if (failed) {
errstream.flush();
*Err = LLVMPY_CreateString(errorstring.c_str());
}
return failed;
}
} // end extern "C"
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
* Authors:
* - Paul Asmuth <paul@zscale.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <eventql/transport/http/status_servlet.h>
#include <eventql/db/PartitionReplication.h>
#include <eventql/server/server_stats.h>
#include <eventql/eventql.h>
#include "eventql/util/application.h"
#include "eventql/eventql.h"
namespace eventql {
static const String kStyleSheet = R"(
<style type="text/css">
body, table {
font-size: 14px;
line-height: 20px;
font-weight: normal;
font-style: normal;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
padding: 0;
margin: 0;
}
body {
padding: 0 30px 30px 30px;
}
em {
font-style: normal;
font-weight: bold;
}
table td {
padding: 6px 8px;
}
table[border="0"] td {
padding: 6px 8px 6px 0;
}
h1 {
margin: 40px 0 20px 0;
}
h2, h3 {
margin: 30px 0 15px 0;
}
.menu {
border-bottom: 2px solid #000;
padding: 6px 0;
}
.menu a {
margin-right: 12px;
color: #06c;
}
</style>
)";
static const String kMainMenu = R"(
<div class="menu">
<a href="/zstatus/">Dashboard</a>
<a href="/zstatus/db/">DB</a>
</div>
)";
StatusServlet::StatusServlet(
ServerCfg* config,
PartitionMap* pmap,
ConfigDirectory* cdir,
http::HTTPServerStats* http_server_stats,
http::HTTPClientStats* http_client_stats) :
config_(config),
pmap_(pmap),
cdir_(cdir),
http_server_stats_(http_server_stats),
http_client_stats_(http_client_stats) {}
void StatusServlet::handleHTTPRequest(
http::HTTPRequest* request,
http::HTTPResponse* response) {
URI url(request->uri());
static const String kPathPrefix = "/zstatus/";
auto path_parts = StringUtil::split(
url.path().substr(kPathPrefix.size()),
"/");
if (path_parts.size() == 2 && path_parts[0] == "db") {
renderNamespacePage(
path_parts[1],
request,
response);
return;
}
if (path_parts.size() == 3 && path_parts[0] == "db") {
renderTablePage(
path_parts[1],
path_parts[2],
request,
response);
return;
}
if (path_parts.size() == 4 && path_parts[0] == "db") {
renderPartitionPage(
path_parts[1],
path_parts[2],
SHA1Hash::fromHexString(path_parts[3]),
request,
response);
return;
}
renderDashboard(request, response);
}
void StatusServlet::renderDashboard(
http::HTTPRequest* request,
http::HTTPResponse* response) {
http::HTTPResponse res;
auto zs = z1stats();
String html;
html += kStyleSheet;
html += kMainMenu;
html += StringUtil::format(
"<h1>EventQL $0 ($1)</h1>",
kVersionString,
kBuildID);
html += "<table cellspacing=0 border=1>";
html += StringUtil::format(
"<tr><td><em>Version</em></td><td align='left'>$0 — $1.$2.$3</td></tr>",
kVersionString,
kVersionMajor,
kVersionMinor,
kVersionPatch);
html += StringUtil::format(
"<tr><td><em>Build-ID</em></td><td align='left'>$0</td></tr>",
kBuildID);
html += StringUtil::format(
"<tr><td><em>Memory Usage - Current</em></td><td align='right'>$0 MB</td></tr>",
Application::getCurrentMemoryUsage() / (1024.0 * 1024.0));
html += StringUtil::format(
"<tr><td><em>Memory Usage - Peak</em></td><td align='right'>$0 MB</td></tr>",
Application::getPeakMemoryUsage() / (1024.0 * 1024.0));
html += "</table>";
html += "<h3>Partitions</h3>";
html += "<table cellspacing=0 border=1>";
html += StringUtil::format(
"<tr><td><em>Number of Partitions</em></td><td align='right'>$0</td></tr>",
zs->num_partitions.get());
html += StringUtil::format(
"<tr><td><em>Number of Partitions - Loaded</em></td><td align='right'>$0</td></tr>",
zs->num_partitions_loaded.get());
html += StringUtil::format(
"<tr><td><em>Number of Dirty Partitions</em></td><td align='right'>$0</td></tr>",
zs->compaction_queue_length.get());
html += StringUtil::format(
"<tr><td><em>LSMTableIndexCache size</em></td><td align='right'>$0 MB</td></tr>",
config_->idx_cache->size() / (1024.0 * 1024.0));
html += "</table>";
html += "<h3>Replication</h3>";
html += "<table cellspacing=0 border=1>";
html += StringUtil::format(
"<tr><td><em>Replication Queue Length</em></td><td align='right'>$0</td></tr>",
zs->replication_queue_length.get());
html += "</table>";
html += "<h3>HTTP</h3>";
html += "<table cellspacing=0 border=1>";
html += StringUtil::format(
"<tr><td><em>Server Connections - Current</em></td><td align='right'>$0</td></tr>",
http_server_stats_->current_connections.get());
html += StringUtil::format(
"<tr><td><em>Server Connections - Total</em></td><td align='right'>$0</td></tr>",
http_server_stats_->total_connections.get());
html += StringUtil::format(
"<tr><td><em>Server Requests - Current</em></td><td align='right'>$0</td></tr>",
http_server_stats_->current_requests.get());
html += StringUtil::format(
"<tr><td><em>Server Requests - Total</em></td><td align='right'>$0</td></tr>",
http_server_stats_->total_requests.get());
html += StringUtil::format(
"<tr><td><em>Server Bytes Received</em></td><td align='right'>$0 MB</td></tr>",
http_server_stats_->received_bytes.get() / (1024.0 * 1024.0));
html += StringUtil::format(
"<tr><td><em>Server Bytes Sent</em></td><td align='right'>$0 MB</td></tr>",
http_server_stats_->sent_bytes.get() / (1024.0 * 1024.0));
html += StringUtil::format(
"<tr><td><em>Client Connections - Current</em></td><td align='right'>$0</td></tr>",
http_client_stats_->current_connections.get());
html += StringUtil::format(
"<tr><td><em>Client Connections - Total</em></td><td align='right'>$0</td></tr>",
http_client_stats_->total_connections.get());
html += StringUtil::format(
"<tr><td><em>Client Requests - Current</em></td><td align='right'>$0</td></tr>",
http_client_stats_->current_requests.get());
html += StringUtil::format(
"<tr><td><em>Client Requests - Total</em></td><td align='right'>$0</td></tr>",
http_client_stats_->total_requests.get());
html += StringUtil::format(
"<tr><td><em>Client Bytes Received</em></td><td align='right'>$0 MB</td></tr>",
http_client_stats_->received_bytes.get() / (1024.0 * 1024.0));
html += StringUtil::format(
"<tr><td><em>Client Bytes Sent</em></td><td align='right'>$0 MB</td></tr>",
http_client_stats_->sent_bytes.get() / (1024.0 * 1024.0));
html += "</table>";
html += "<h3>MapReduce</h3>";
html += "<table cellspacing=0 border=1>";
html += StringUtil::format(
"<tr><td><em>Number of Map Tasks - Running</em></td><td align='right'>$0</td></tr>",
zs->mapreduce_num_map_tasks.get());
html += StringUtil::format(
"<tr><td><em>Number of Reduce Tasks - Running</em></td><td align='right'>$0</td></tr>",
zs->mapreduce_num_reduce_tasks.get());
html += StringUtil::format(
"<tr><td><em>Reduce Memory Used</em></td><td align='right'>$0 MB</td></tr>",
zs->mapreduce_reduce_memory.get() / (1024.0 * 1024.0));
html += "</table>";
html += "<h3>Servers</h3>";
html += "<table cellspacing=0 border=1>";
for (const auto& server : cdir_->listServers()) {
html += StringUtil::format(
"<tr><td><em>$0</em></td><td><pre>$1</pre></td></tr>",
server.server_id(),
server.DebugString());
}
html += "</table>";
html += "<h3>Cluster Config</h3>";
html += StringUtil::format(
"<table cellspacing=0 border=1><tr><td><pre>$0</pre></td></tr></table>",
cdir_->getClusterConfig().DebugString());
response->setStatus(http::kStatusOK);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addBody(html);
}
void StatusServlet::renderNamespacePage(
const String& db_namespace,
http::HTTPRequest* request,
http::HTTPResponse* response) {
String html;
html += kStyleSheet;
html += kMainMenu;
html += StringUtil::format(
"<h2>Namespace: <span style='font-weight:normal'>$0</span></h2>",
db_namespace);
response->setStatus(http::kStatusOK);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addBody(html);
}
void StatusServlet::renderTablePage(
const String& db_namespace,
const String& table_name,
http::HTTPRequest* request,
http::HTTPResponse* response) {
String html;
html += kStyleSheet;
html += kMainMenu;
html += StringUtil::format(
"<h2>Table: <span style='font-weight:normal'>"
"<a href='/zstatus/db/$0'>$0</a> —"
"$1</span></h2>",
db_namespace,
table_name);
auto table = pmap_->findTable(
db_namespace,
table_name);
if (table.isEmpty()) {
html += "ERROR: TABLE NOT FOUND!";
} else {
html += "<h3>TableDefinition</h3>";
html += StringUtil::format(
"<pre>$0</pre>",
table.get()->config().DebugString());
}
response->setStatus(http::kStatusOK);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addBody(html);
}
void StatusServlet::renderPartitionPage(
const String& db_namespace,
const String& table_name,
const SHA1Hash& partition_key,
http::HTTPRequest* request,
http::HTTPResponse* response) {
String html;
html += kStyleSheet;
html += kMainMenu;
html += StringUtil::format(
"<h2>Partition: <span style='font-weight:normal'>"
"<a href='/zstatus/db/$0'>$0</a> —"
"<a href='/zstatus/db/$0/$1'>$1</a> —"
"$2</span></h2>",
db_namespace,
table_name,
partition_key.toString());
auto partition = pmap_->findPartition(
db_namespace,
table_name,
partition_key);
auto snap = partition.get()->getSnapshot();
if (partition.isEmpty()) {
html += "ERROR: PARTITION NOT FOUND!";
} else {
html += "<table cellspacing=0 border=0>";
html += StringUtil::format(
"<tr><td><em>Number of Records</em></td><td align='right'>$0</td></tr>",
snap->nrecs);
html += "</table>";
html += "<h3>PartitionInfo</h3>";
html += StringUtil::format(
"<pre>$0</pre>",
partition.get()->getInfo().DebugString());
html += "<h3>PartitionState</h3>";
html += StringUtil::format("<pre>$0</pre>", snap->state.DebugString());
auto repl_state = PartitionReplication::fetchReplicationState(snap);
html += "<h3>ReplicationState</h3>";
html += StringUtil::format("<pre>$0</pre>", repl_state.DebugString());
html += "<h3>TableDefinition</h3>";
html += StringUtil::format(
"<pre>$0</pre>",
partition.get()->getTable()->config().DebugString());
}
response->setStatus(http::kStatusOK);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addBody(html);
}
}
<commit_msg>display keyrange in status servlet<commit_after>/**
* Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
* Authors:
* - Paul Asmuth <paul@zscale.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <eventql/transport/http/status_servlet.h>
#include <eventql/db/PartitionReplication.h>
#include <eventql/server/server_stats.h>
#include <eventql/eventql.h>
#include "eventql/util/application.h"
#include "eventql/eventql.h"
namespace eventql {
static const String kStyleSheet = R"(
<style type="text/css">
body, table {
font-size: 14px;
line-height: 20px;
font-weight: normal;
font-style: normal;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
padding: 0;
margin: 0;
}
body {
padding: 0 30px 30px 30px;
}
em {
font-style: normal;
font-weight: bold;
}
table td {
padding: 6px 8px;
}
table[border="0"] td {
padding: 6px 8px 6px 0;
}
h1 {
margin: 40px 0 20px 0;
}
h2, h3 {
margin: 30px 0 15px 0;
}
.menu {
border-bottom: 2px solid #000;
padding: 6px 0;
}
.menu a {
margin-right: 12px;
color: #06c;
}
</style>
)";
static const String kMainMenu = R"(
<div class="menu">
<a href="/zstatus/">Dashboard</a>
<a href="/zstatus/db/">DB</a>
</div>
)";
StatusServlet::StatusServlet(
ServerCfg* config,
PartitionMap* pmap,
ConfigDirectory* cdir,
http::HTTPServerStats* http_server_stats,
http::HTTPClientStats* http_client_stats) :
config_(config),
pmap_(pmap),
cdir_(cdir),
http_server_stats_(http_server_stats),
http_client_stats_(http_client_stats) {}
void StatusServlet::handleHTTPRequest(
http::HTTPRequest* request,
http::HTTPResponse* response) {
URI url(request->uri());
static const String kPathPrefix = "/zstatus/";
auto path_parts = StringUtil::split(
url.path().substr(kPathPrefix.size()),
"/");
if (path_parts.size() == 2 && path_parts[0] == "db") {
renderNamespacePage(
path_parts[1],
request,
response);
return;
}
if (path_parts.size() == 3 && path_parts[0] == "db") {
renderTablePage(
path_parts[1],
path_parts[2],
request,
response);
return;
}
if (path_parts.size() == 4 && path_parts[0] == "db") {
renderPartitionPage(
path_parts[1],
path_parts[2],
SHA1Hash::fromHexString(path_parts[3]),
request,
response);
return;
}
renderDashboard(request, response);
}
void StatusServlet::renderDashboard(
http::HTTPRequest* request,
http::HTTPResponse* response) {
http::HTTPResponse res;
auto zs = z1stats();
String html;
html += kStyleSheet;
html += kMainMenu;
html += StringUtil::format(
"<h1>EventQL $0 ($1)</h1>",
kVersionString,
kBuildID);
html += "<table cellspacing=0 border=1>";
html += StringUtil::format(
"<tr><td><em>Version</em></td><td align='left'>$0 — $1.$2.$3</td></tr>",
kVersionString,
kVersionMajor,
kVersionMinor,
kVersionPatch);
html += StringUtil::format(
"<tr><td><em>Build-ID</em></td><td align='left'>$0</td></tr>",
kBuildID);
html += StringUtil::format(
"<tr><td><em>Memory Usage - Current</em></td><td align='right'>$0 MB</td></tr>",
Application::getCurrentMemoryUsage() / (1024.0 * 1024.0));
html += StringUtil::format(
"<tr><td><em>Memory Usage - Peak</em></td><td align='right'>$0 MB</td></tr>",
Application::getPeakMemoryUsage() / (1024.0 * 1024.0));
html += "</table>";
html += "<h3>Partitions</h3>";
html += "<table cellspacing=0 border=1>";
html += StringUtil::format(
"<tr><td><em>Number of Partitions</em></td><td align='right'>$0</td></tr>",
zs->num_partitions.get());
html += StringUtil::format(
"<tr><td><em>Number of Partitions - Loaded</em></td><td align='right'>$0</td></tr>",
zs->num_partitions_loaded.get());
html += StringUtil::format(
"<tr><td><em>Number of Dirty Partitions</em></td><td align='right'>$0</td></tr>",
zs->compaction_queue_length.get());
html += StringUtil::format(
"<tr><td><em>LSMTableIndexCache size</em></td><td align='right'>$0 MB</td></tr>",
config_->idx_cache->size() / (1024.0 * 1024.0));
html += "</table>";
html += "<h3>Replication</h3>";
html += "<table cellspacing=0 border=1>";
html += StringUtil::format(
"<tr><td><em>Replication Queue Length</em></td><td align='right'>$0</td></tr>",
zs->replication_queue_length.get());
html += "</table>";
html += "<h3>HTTP</h3>";
html += "<table cellspacing=0 border=1>";
html += StringUtil::format(
"<tr><td><em>Server Connections - Current</em></td><td align='right'>$0</td></tr>",
http_server_stats_->current_connections.get());
html += StringUtil::format(
"<tr><td><em>Server Connections - Total</em></td><td align='right'>$0</td></tr>",
http_server_stats_->total_connections.get());
html += StringUtil::format(
"<tr><td><em>Server Requests - Current</em></td><td align='right'>$0</td></tr>",
http_server_stats_->current_requests.get());
html += StringUtil::format(
"<tr><td><em>Server Requests - Total</em></td><td align='right'>$0</td></tr>",
http_server_stats_->total_requests.get());
html += StringUtil::format(
"<tr><td><em>Server Bytes Received</em></td><td align='right'>$0 MB</td></tr>",
http_server_stats_->received_bytes.get() / (1024.0 * 1024.0));
html += StringUtil::format(
"<tr><td><em>Server Bytes Sent</em></td><td align='right'>$0 MB</td></tr>",
http_server_stats_->sent_bytes.get() / (1024.0 * 1024.0));
html += StringUtil::format(
"<tr><td><em>Client Connections - Current</em></td><td align='right'>$0</td></tr>",
http_client_stats_->current_connections.get());
html += StringUtil::format(
"<tr><td><em>Client Connections - Total</em></td><td align='right'>$0</td></tr>",
http_client_stats_->total_connections.get());
html += StringUtil::format(
"<tr><td><em>Client Requests - Current</em></td><td align='right'>$0</td></tr>",
http_client_stats_->current_requests.get());
html += StringUtil::format(
"<tr><td><em>Client Requests - Total</em></td><td align='right'>$0</td></tr>",
http_client_stats_->total_requests.get());
html += StringUtil::format(
"<tr><td><em>Client Bytes Received</em></td><td align='right'>$0 MB</td></tr>",
http_client_stats_->received_bytes.get() / (1024.0 * 1024.0));
html += StringUtil::format(
"<tr><td><em>Client Bytes Sent</em></td><td align='right'>$0 MB</td></tr>",
http_client_stats_->sent_bytes.get() / (1024.0 * 1024.0));
html += "</table>";
html += "<h3>MapReduce</h3>";
html += "<table cellspacing=0 border=1>";
html += StringUtil::format(
"<tr><td><em>Number of Map Tasks - Running</em></td><td align='right'>$0</td></tr>",
zs->mapreduce_num_map_tasks.get());
html += StringUtil::format(
"<tr><td><em>Number of Reduce Tasks - Running</em></td><td align='right'>$0</td></tr>",
zs->mapreduce_num_reduce_tasks.get());
html += StringUtil::format(
"<tr><td><em>Reduce Memory Used</em></td><td align='right'>$0 MB</td></tr>",
zs->mapreduce_reduce_memory.get() / (1024.0 * 1024.0));
html += "</table>";
html += "<h3>Servers</h3>";
html += "<table cellspacing=0 border=1>";
for (const auto& server : cdir_->listServers()) {
html += StringUtil::format(
"<tr><td><em>$0</em></td><td><pre>$1</pre></td></tr>",
server.server_id(),
server.DebugString());
}
html += "</table>";
html += "<h3>Cluster Config</h3>";
html += StringUtil::format(
"<table cellspacing=0 border=1><tr><td><pre>$0</pre></td></tr></table>",
cdir_->getClusterConfig().DebugString());
response->setStatus(http::kStatusOK);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addBody(html);
}
void StatusServlet::renderNamespacePage(
const String& db_namespace,
http::HTTPRequest* request,
http::HTTPResponse* response) {
String html;
html += kStyleSheet;
html += kMainMenu;
html += StringUtil::format(
"<h2>Namespace: <span style='font-weight:normal'>$0</span></h2>",
db_namespace);
response->setStatus(http::kStatusOK);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addBody(html);
}
void StatusServlet::renderTablePage(
const String& db_namespace,
const String& table_name,
http::HTTPRequest* request,
http::HTTPResponse* response) {
String html;
html += kStyleSheet;
html += kMainMenu;
html += StringUtil::format(
"<h2>Table: <span style='font-weight:normal'>"
"<a href='/zstatus/db/$0'>$0</a> —"
"$1</span></h2>",
db_namespace,
table_name);
auto table = pmap_->findTable(
db_namespace,
table_name);
if (table.isEmpty()) {
html += "ERROR: TABLE NOT FOUND!";
} else {
html += "<h3>TableDefinition</h3>";
html += StringUtil::format(
"<pre>$0</pre>",
table.get()->config().DebugString());
}
response->setStatus(http::kStatusOK);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addBody(html);
}
void StatusServlet::renderPartitionPage(
const String& db_namespace,
const String& table_name,
const SHA1Hash& partition_key,
http::HTTPRequest* request,
http::HTTPResponse* response) {
String html;
html += kStyleSheet;
html += kMainMenu;
html += StringUtil::format(
"<h2>Partition: <span style='font-weight:normal'>"
"<a href='/zstatus/db/$0'>$0</a> —"
"<a href='/zstatus/db/$0/$1'>$1</a> —"
"$2</span></h2>",
db_namespace,
table_name,
partition_key.toString());
auto partition = pmap_->findPartition(
db_namespace,
table_name,
partition_key);
if (partition.isEmpty()) {
html += "ERROR: PARTITION NOT FOUND!";
} else {
auto table = partition.get()->getTable();
auto snap = partition.get()->getSnapshot();
auto state = snap->state;
if (table->partitionerType() == TBL_PARTITION_TIMEWINDOW &&
state.partition_keyrange_begin().size() == 8 &&
state.partition_keyrange_end().size() == 8) {
uint64_t ts_begin;
uint64_t ts_end;
memcpy((char*) &ts_begin, state.partition_keyrange_begin().data(), 8);
memcpy((char*) &ts_end, state.partition_keyrange_end().data(), 8);
html += StringUtil::format(
"<span><em>Keyrange:</em> $0 [$1] - $2 [$3]</span> — ",
UnixTime(ts_begin),
ts_begin,
UnixTime(ts_end),
ts_end);
}
html += StringUtil::format(
"<span><em>Number of Records</em>: $0</span>",
snap->nrecs);
html += "<h3>PartitionInfo</h3>";
html += StringUtil::format(
"<pre>$0</pre>",
partition.get()->getInfo().DebugString());
html += "<h3>PartitionState</h3>";
html += StringUtil::format("<pre>$0</pre>", snap->state.DebugString());
auto repl_state = PartitionReplication::fetchReplicationState(snap);
html += "<h3>ReplicationState</h3>";
html += StringUtil::format("<pre>$0</pre>", repl_state.DebugString());
html += "<h3>TableDefinition</h3>";
html += StringUtil::format(
"<pre>$0</pre>",
partition.get()->getTable()->config().DebugString());
}
response->setStatus(http::kStatusOK);
response->addHeader("Content-Type", "text/html; charset=utf-8");
response->addBody(html);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 1997-2019 The CSE Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
// strpak.h -- extended string functions
#if !defined( _STRPAK_H)
#define _STRPAK_H
// definitions for strpathparts()
const int STRPPDRIVE = 1;
const int STRPPDIR = 2;
const int STRPPFNAME = 4;
const int STRPPEXT = 8;
///////////////////////////////////////////////////////////////////////////
// public fcns
///////////////////////////////////////////////////////////////////////////
// char type wrappers re VS2008 and later
// WHY: VS2008 char type fcns assert if !(0 <= c <= 0xff).
// The following causes assert
// const char* s;
// int c = *s; // c is < 0 if *s is 128 - 255
// if (isspace( c)) // can assert
// isxxxxxW are provided with explicit arg types
#include <ctype.h>
#define charTypeW( fcn) \
inline int fcn##W( int c) { return fcn( c); } \
inline int fcn##W( char c) { return fcn( (unsigned char)c); } \
inline int fcn##W( unsigned char c) { return fcn( (unsigned char)c); }
#define charTypeErr( fcn) Should_use_##fcn##W
charTypeW( isspace)
#define isspace charTypeErr( isspace)
charTypeW( iscntrl)
#define iscntrl charTypeErr( iscntrl)
charTypeW( isalpha)
#define isalpha charTypeErr( isalpha)
charTypeW( isdigit)
#define isdigit charTypeErr( isdigit)
charTypeW( isalnum)
#define isalnum charTypeErr( isalnum)
charTypeW( ispunct)
#define ispunct charTypeErr( ispunct)
charTypeW( isprint)
#define isprint charTypeErr( isprint)
charTypeW( isupper)
#define isupper charTypeErr( isupper)
charTypeW( islower)
#define islower charTypeErr( islower)
inline int intC( const char* p) { return int( (unsigned char)*p); }
/*------------------------- FUNCTION DECLARATIONS -------------------------*/
int strCheckPtr( DMP p);
char * strxtok( char *tokbuf, const char* &p, const char* delims, int wsflag);
int strTokSplit( char* str, const char* delims, const char* toks[], int dimToks);
void * FC memsetPass( void * * pdest, char c, USI n);
void * FC memcpyPass( void * * pdest, const void * src, USI n);
char * FC strncpy0( char *d, const char *s, size_t l);
inline char* strTrimB( char* s)
{ while (isspaceW( *s)) s++; return s; }
inline const char* strTrimB( const char* s)
{ while (isspaceW( *s)) s++; return s; }
char* strTrimB( char* d, const char* s);
char* strTrimE( char* d, const char* s);
char* strTrimEX( char* d, const char* s, const char* ex);
char* strTrimE( char* s);
char* strTrim( char* s1, const char* s2, int s2Len=999999);
inline char* strTrim( char* s) { return strTrim( s, s); } // trim in place
int strLineLen( const char *s);
int strJoinLen( const char *s1, const char *s2);
char * FC strpad( char *s, const char *pads, SI n);
char* strSpacePad( char* d, size_t n, const char* s=NULL);
char * FC strffix( const char *name, const char *ext);
char* strffix2( const char* name, const char* ext, int options=0);
char * FC strtPathCat( const char *path, const char *namExt);
char * FC strpathparts( const char *path, int partswanted, char* pcombo=NULL);
char * FC strtBsDouble( char *s);
char * FC strBsUnDouble( char *s);
char * FC strsave( const char *s);
char * strsave( char* &p, const char *s);
char * FC strtemp( size_t n);
char * FC strtempPop( char *anS);
char * FC strtmp( const char *s);
char * CDEC strtcat( const char *s, ... );
char * CDEC strntcat( SI n, ...);
const char* scWrapIf( const char* s1, const char* s2, const char* tween);
const char* strtprintf( const char *format, ...);
const char* strtvprintf( const char *format, va_list ap=NULL);
SI FC strlstin( const char *list, const char *str);
const char* strOrdinal( int number);
#if 0 // out of service
x const int STRTRIGHT = 0; // truncate right end of string (keep first char)
x const int STRTLEFT = 1; // truncate left end of string (keep last char)
x char * FC strntrim( char *s1, char *s2, SI n);
x char * FC strtrend( char *s1, char *s2);
x char * FC strtrunc( char *str, SI maxlen, SI mode);
x char * FC strstrch( char *s1, char *s2, char *s3);
x char * FC strpadsp( char *dest, char *source, SI n);
x char * FC strindx( char *s1, char *s2);
x char tolowerx( char *p );
#endif
// WStr variants
WStr& WStrUpper( WStr& s);
WStr& WStrLower( WStr& s);
WStr WStrPrintf( const char* mOrH, ...);
WStr WStrVprintf( const char* mOrH, va_list ap=NULL);
WStr WStrFmtFloatDTZ( double v, int maxPrec, int minPrec=0);
WStr WStrDTZ( const WStr& s, int minPrec=0);
int strDecode( const char* s, const char* fmt, void *p, int erOp=IGN,
const char* what=NULL, const char** pMsg=NULL);
inline int strDecode( const char* s, double &v, int erOp=IGN,
const char* what=NULL, const char** pMsg=NULL)
{ return strDecode( s, "%lg%1s", &v, erOp, what, pMsg); }
inline int strDecode( const char* s, float &v, int erOp=IGN,
const char* what=NULL, const char** pMsg=NULL)
{ return strDecode( s, "%g%1s", &v, erOp, what, pMsg); }
inline int strDecode( const char* s, int &v, int erOp=IGN,
const char* what=NULL, const char** pMsg=NULL)
{ return strDecode( s, "%d%1s", &v, erOp, what, pMsg); }
inline int strDecode( const char* s, DWORD &v, int erOp=IGN,
const char* what=NULL, const char** pMsg=NULL)
{ return strDecode( s, "%u%1s", &v, erOp, what, pMsg); }
inline BOOL IsNumber( const char* s)
{ double v; return strDecode( s, v) == 1; }
inline BOOL IsInteger( const char* s)
{ int v; return strDecode( s, v) == 1; }
BOOL IsBlank( const char* s, int len=999999);
char* strFill( char* d, const char* s, int len=-1);
const char* strSuffix(int n, int options = 0);
char* strTranslateEscapes( char* d, const char* s=NULL);
char* strCatIf( char* d, size_t dSize, const char* brk, const char* s, int options=0);
char* strDeBar( char* d, const char* s=NULL);
char* strDeQuote( char* d, const char* s=NULL);
char* strDeWS( char* d, const char* s=NULL);
char* strCase( char* s, const char toCases[3]);
char* strCase( char* d, const char* s, const char toCases[3]);
char* strPluralize( char* d, const char* word, bool bPlural=true);
char* strRemoveCRLF(char* str);
int strReplace2( char* s, char cFrom, char sTo, int options=0);
int strReplace( char* str, const char* sOld, const char* sNew,
BOOL bCaseSens=FALSE);
char* stristr( const char* str1, const char* str2);
BOOL strMatch( const char* s1, const char* s2);
#endif // _STRPAK_H
// end of strpak.h
<commit_msg>Add comment explaining fcn##W functions.<commit_after>// Copyright (c) 1997-2019 The CSE Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
// strpak.h -- extended string functions
#if !defined( _STRPAK_H)
#define _STRPAK_H
// definitions for strpathparts()
const int STRPPDRIVE = 1;
const int STRPPDIR = 2;
const int STRPPFNAME = 4;
const int STRPPEXT = 8;
///////////////////////////////////////////////////////////////////////////
// public fcns
///////////////////////////////////////////////////////////////////////////
// char type wrappers re VS2008 and later
// WHY: VS2008 char type fcns assert if !(0 <= c <= 0xff).
// The following causes assert
// const char* s;
// int c = *s; // c is < 0 if *s is 128 - 255
// if (isspace( c)) // can assert
// isxxxxxW are provided with explicit arg types
#include <ctype.h>
#define charTypeW( fcn) \
inline int fcn##W( int c) { return fcn( c); } \
inline int fcn##W( char c) { return fcn( (unsigned char)c); } \
inline int fcn##W( unsigned char c) { return fcn( (unsigned char)c); }
// The redefinition of standard functions defined below end on a W
// to specify that it uses the declaration above for proper casting.
#define charTypeErr( fcn) Should_use_##fcn##W
charTypeW( isspace)
#define isspace charTypeErr( isspace)
charTypeW( iscntrl)
#define iscntrl charTypeErr( iscntrl)
charTypeW( isalpha)
#define isalpha charTypeErr( isalpha)
charTypeW( isdigit)
#define isdigit charTypeErr( isdigit)
charTypeW( isalnum)
#define isalnum charTypeErr( isalnum)
charTypeW( ispunct)
#define ispunct charTypeErr( ispunct)
charTypeW( isprint)
#define isprint charTypeErr( isprint)
charTypeW( isupper)
#define isupper charTypeErr( isupper)
charTypeW( islower)
#define islower charTypeErr( islower)
inline int intC( const char* p) { return int( (unsigned char)*p); }
/*------------------------- FUNCTION DECLARATIONS -------------------------*/
int strCheckPtr( DMP p);
char * strxtok( char *tokbuf, const char* &p, const char* delims, int wsflag);
int strTokSplit( char* str, const char* delims, const char* toks[], int dimToks);
void * FC memsetPass( void * * pdest, char c, USI n);
void * FC memcpyPass( void * * pdest, const void * src, USI n);
char * FC strncpy0( char *d, const char *s, size_t l);
inline char* strTrimB( char* s)
{ while (isspaceW( *s)) s++; return s; }
inline const char* strTrimB( const char* s)
{ while (isspaceW( *s)) s++; return s; }
char* strTrimB( char* d, const char* s);
char* strTrimE( char* d, const char* s);
char* strTrimEX( char* d, const char* s, const char* ex);
char* strTrimE( char* s);
char* strTrim( char* s1, const char* s2, int s2Len=999999);
inline char* strTrim( char* s) { return strTrim( s, s); } // trim in place
int strLineLen( const char *s);
int strJoinLen( const char *s1, const char *s2);
char * FC strpad( char *s, const char *pads, SI n);
char* strSpacePad( char* d, size_t n, const char* s=NULL);
char * FC strffix( const char *name, const char *ext);
char* strffix2( const char* name, const char* ext, int options=0);
char * FC strtPathCat( const char *path, const char *namExt);
char * FC strpathparts( const char *path, int partswanted, char* pcombo=NULL);
char * FC strtBsDouble( char *s);
char * FC strBsUnDouble( char *s);
char * FC strsave( const char *s);
char * strsave( char* &p, const char *s);
char * FC strtemp( size_t n);
char * FC strtempPop( char *anS);
char * FC strtmp( const char *s);
char * CDEC strtcat( const char *s, ... );
char * CDEC strntcat( SI n, ...);
const char* scWrapIf( const char* s1, const char* s2, const char* tween);
const char* strtprintf( const char *format, ...);
const char* strtvprintf( const char *format, va_list ap=NULL);
SI FC strlstin( const char *list, const char *str);
const char* strOrdinal( int number);
#if 0 // out of service
x const int STRTRIGHT = 0; // truncate right end of string (keep first char)
x const int STRTLEFT = 1; // truncate left end of string (keep last char)
x char * FC strntrim( char *s1, char *s2, SI n);
x char * FC strtrend( char *s1, char *s2);
x char * FC strtrunc( char *str, SI maxlen, SI mode);
x char * FC strstrch( char *s1, char *s2, char *s3);
x char * FC strpadsp( char *dest, char *source, SI n);
x char * FC strindx( char *s1, char *s2);
x char tolowerx( char *p );
#endif
// WStr variants
WStr& WStrUpper( WStr& s);
WStr& WStrLower( WStr& s);
WStr WStrPrintf( const char* mOrH, ...);
WStr WStrVprintf( const char* mOrH, va_list ap=NULL);
WStr WStrFmtFloatDTZ( double v, int maxPrec, int minPrec=0);
WStr WStrDTZ( const WStr& s, int minPrec=0);
int strDecode( const char* s, const char* fmt, void *p, int erOp=IGN,
const char* what=NULL, const char** pMsg=NULL);
inline int strDecode( const char* s, double &v, int erOp=IGN,
const char* what=NULL, const char** pMsg=NULL)
{ return strDecode( s, "%lg%1s", &v, erOp, what, pMsg); }
inline int strDecode( const char* s, float &v, int erOp=IGN,
const char* what=NULL, const char** pMsg=NULL)
{ return strDecode( s, "%g%1s", &v, erOp, what, pMsg); }
inline int strDecode( const char* s, int &v, int erOp=IGN,
const char* what=NULL, const char** pMsg=NULL)
{ return strDecode( s, "%d%1s", &v, erOp, what, pMsg); }
inline int strDecode( const char* s, DWORD &v, int erOp=IGN,
const char* what=NULL, const char** pMsg=NULL)
{ return strDecode( s, "%u%1s", &v, erOp, what, pMsg); }
inline BOOL IsNumber( const char* s)
{ double v; return strDecode( s, v) == 1; }
inline BOOL IsInteger( const char* s)
{ int v; return strDecode( s, v) == 1; }
BOOL IsBlank( const char* s, int len=999999);
char* strFill( char* d, const char* s, int len=-1);
const char* strSuffix(int n, int options = 0);
char* strTranslateEscapes( char* d, const char* s=NULL);
char* strCatIf( char* d, size_t dSize, const char* brk, const char* s, int options=0);
char* strDeBar( char* d, const char* s=NULL);
char* strDeQuote( char* d, const char* s=NULL);
char* strDeWS( char* d, const char* s=NULL);
char* strCase( char* s, const char toCases[3]);
char* strCase( char* d, const char* s, const char toCases[3]);
char* strPluralize( char* d, const char* word, bool bPlural=true);
char* strRemoveCRLF(char* str);
int strReplace2( char* s, char cFrom, char sTo, int options=0);
int strReplace( char* str, const char* sOld, const char* sNew,
BOOL bCaseSens=FALSE);
char* stristr( const char* str1, const char* str2);
BOOL strMatch( const char* s1, const char* s2);
#endif // _STRPAK_H
// end of strpak.h
<|endoftext|> |
<commit_before>// -*-c++-*- Copyright (C) 2010 osgPango Development Team
// $Id$
#include <cmath>
#include <sstream>
#include <osg/AlphaFunc>
#include <osg/Depth>
#include <osg/Texture2D>
#include <osg/Geode>
#include <osgCairo/Util>
#include <osgPango/GlyphRenderer>
namespace osgPango {
osg::Vec4 GlyphRenderer::getExtraGlyphExtents() const {
if(!_layers.size()) return osg::Vec4(0.0f, 0.0f, 0.0f, 0.0f);
osg::Vec4 result = _layers[0]->getExtraGlyphExtents();
for(unsigned int i = 1; i < _layers.size(); ++i) {
osg::Vec4 extents = _layers[i]->getExtraGlyphExtents();
result[0] = std::max(result[0], extents[0]);
result[1] = std::max(result[1], extents[1]);
result[2] = std::max(result[2], extents[2]);
result[3] = std::max(result[3], extents[3]);
}
return result;
}
bool GlyphRenderer::renderLayer(
unsigned int layer,
osgCairo::Surface* surface,
const osgCairo::Glyph& glyph,
unsigned int width,
unsigned int height
) {
if(layer < _layers.size()) return _layers[layer]->render(surface, glyph, width, height);
else return false;
}
bool GlyphRenderer::updateOrCreateState(int pass, osg::Geode* geode) {
static const char* VERTEX_SHADER =
"#version 120\n"
"varying vec4 pangoTexCoord;"
"void main() {"
" pangoTexCoord = gl_MultiTexCoord0;"
" gl_Position = ftransform();"
"}"
;
static const char* FRAGMENT_SHADER =
"#version 120\n"
"varying vec4 pangoTexCoord;"
"uniform vec3 pangoColor[8];"
"uniform sampler2D pangoTex0;"
"uniform sampler2D pangoTex1;"
"uniform sampler2D pangoTex2;"
"uniform float pangoAlpha;"
"vec4 osgPango_GetFragment(vec4, sampler2D[8], vec3[8], float);"
"void main() {"
" sampler2D textures[8];"
" textures[0] = pangoTex0;"
" textures[1] = pangoTex1;"
" textures[2] = pangoTex2;"
" gl_FragColor = osgPango_GetFragment(pangoTexCoord, textures, pangoColor, pangoAlpha);"
"}"
;
// XXX: OMG OMG OMG
// XXX: OMG OMG OMG
// XXX: OMG OMG OMG
// XXX: OMG OMG OMG
// XXX: OMG OMG OMG
// XXX: OMG OMG OMG
// XXX: OMG OMG OMG
// XXX: OMG OMG OMG
// XXX: OMG OMG OMG
// JAROMIR! We cannot go down this route (below)! :) That code would be impossible to understand
// and maintain. Lets see if we can come up with a way to to have each Renderer compile it's own
// GetFragment() GLSL function, and have the default fragment shader's main() call that function:
//
// gl_FragColor = osgPango_GetFragment();
//
// We will probably need to SLIGHTLY change the API further in order to achieve this.
/*
std::ostringstream fragment;
fragment
<< "varying vec4 pangoTexCoord;" << std::endl
<< "uniform float pangoAlpha;" << std::endl
<< "uniform vec3 pangoColor[" << _layers.size() << "];" << std::endl
;
for(unsigned int i = 0; i < _layers.size(); ++i) fragment
<< "uniform sampler2D pangoTex" << i << ";" << std::endl
;
fragment << "void main() {" << std::endl;
for(unsigned int i = 0; i < _layers.size(); ++i) fragment
<< " float tex" << i << " = texture2D(pangoTex" << i <<", pangoTexCoord.st).a;" << std::endl
;
for(unsigned int i = 0; i < _layers.size(); ++i) {
if(i == 0) {
fragment
<< " vec3 color0 = pangoColor[0].rgb * tex0;" << std::endl
<< " float alpha = tex0;" << std::endl
;
}
else {
fragment
<< " vec3 color" << i << " = pangoColor[" << i << "].rgb * tex"
<< i << " + color" << i - 1 << " * (1.0 - tex" << i << ");" << std::endl
<< " alpha = alpha + tex" << i << ";" << std::endl
;
}
}
fragment
<< " gl_FragColor = vec4(color" << _layers.size() - 1 <<", alpha * pangoAlpha);" << std::endl
<<"}" << std::endl
;
*/
osg::Program* program = new osg::Program();
osg::Shader* vert = new osg::Shader(osg::Shader::VERTEX, VERTEX_SHADER);
osg::Shader* frag = new osg::Shader(osg::Shader::FRAGMENT, FRAGMENT_SHADER);
vert->setName("pangoRendererVert");
frag->setName("pangoRendererFrag");
program->setName("pangoRenderer");
program->addShader(vert);
program->addShader(frag);
osg::StateSet* state = geode->getOrCreateStateSet();
state->setAttributeAndModes(program);
state->setMode(GL_BLEND, osg::StateAttribute::ON);
state->setAttributeAndModes(new osg::AlphaFunc(osg::AlphaFunc::GEQUAL, 0.01f));
state->setAttribute(new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false));
state->getOrCreateUniform("pangoAlpha", osg::Uniform::FLOAT)->set(1.0f);
for(unsigned int i = 0; i < _layers.size(); ++i) {
std::ostringstream str;
str << "pangoTex" << i;
state->getOrCreateUniform(str.str(), osg::Uniform::INT)->set(static_cast<int>(i));
}
return true;
}
bool GlyphRenderer::updateOrCreateState(
osg::Geometry* geometry,
const GlyphGeometryState& ggs
) {
if(
ggs.textures.size() != _layers.size() ||
ggs.colors.size() != _layers.size()
) return false;
osg::Uniform* pangoColor = new osg::Uniform(
osg::Uniform::FLOAT_VEC3,
"pangoColor",
_layers.size()
);
osg::StateSet* state = geometry->getOrCreateStateSet();
state->addUniform(pangoColor);
for(unsigned int i = 0; i < _layers.size(); ++i) {
pangoColor->setElement(i, ggs.colors[i]);
state->setTextureAttributeAndModes(i, ggs.textures[i], osg::StateAttribute::ON);
}
return true;
}
void GlyphRenderer::addLayer(GlyphLayer *layer) {
_layers.push_back(layer);
}
void GlyphRenderer::removeLayer(unsigned int index) {
if(index < _layers.size()) _layers.erase(_layers.begin() + index);
}
void GlyphRenderer::replaceLayer(unsigned int index, GlyphLayer* layer) {
if(index < _layers.size()) _layers[index] = layer;
}
GlyphRendererDefault::GlyphRendererDefault() {
addLayer(new GlyphLayer());
}
bool GlyphRendererDefault::updateOrCreateState(int pass, osg::Geode* geode) {
if(!GlyphRenderer::updateOrCreateState(pass, geode)) return false;
osg::StateSet* state = geode->getOrCreateStateSet();
osg::Program* program = dynamic_cast<osg::Program*>(state->getAttribute(osg::StateAttribute::PROGRAM));
if(!program) return false;
const char* GET_FRAGMENT =
"#version 120\n"
"vec4 osgPango_GetFragment(vec4 coord, sampler2D textures[8], vec3 colors[8], float alpha) {"
" float tex0 = texture2D(textures[0], coord.st).a;"
" vec3 color0 = colors[0].rgb * tex0;"
" float alpha0 = tex0;"
" return vec4(color0, alpha0 * alpha);"
"}"
;
osg::Shader* frag = new osg::Shader(osg::Shader::FRAGMENT, GET_FRAGMENT);
program->addShader(frag);
return true;
}
GlyphRendererOutline::GlyphRendererOutline(unsigned int outline) {
addLayer(new GlyphLayer());
addLayer(new GlyphLayerOutline(outline));
}
bool GlyphRendererOutline::updateOrCreateState(int pass, osg::Geode* geode) {
if(!GlyphRenderer::updateOrCreateState(pass, geode)) return false;
osg::StateSet* state = geode->getOrCreateStateSet();
osg::Program* program = dynamic_cast<osg::Program*>(state->getAttribute(osg::StateAttribute::PROGRAM));
if(!program) return false;
const char* GET_FRAGMENT =
"#version 120\n"
"vec4 osgPango_GetFragment(vec4 coord, sampler2D textures[8], vec3 colors[8], float alpha) {"
" float tex0 = texture2D(textures[1], coord.st).a;"
" float tex1 = texture2D(textures[0], coord.st).a;"
" vec3 color0 = colors[1].rgb * tex0;"
" vec3 color1 = colors[0].rgb * tex1 + color0 * (1.0 - tex1);"
" float alpha0 = tex0;"
" float alpha1 = tex0 + tex1;"
" return vec4(color1, alpha1 * alpha);"
"}"
;
osg::Shader* frag = new osg::Shader(osg::Shader::FRAGMENT, GET_FRAGMENT);
program->addShader(frag);
return true;
}
GlyphRendererShadowOffset::GlyphRendererShadowOffset(int offsetX, int offsetY) {
unsigned int xt = 0;
unsigned int yt = 0;
if(offsetX < 0) xt = std::abs(offsetX);
if(offsetY < 0) yt = std::abs(offsetY);
addLayer(new GlyphLayer());
addLayer(new GlyphLayerShadowOffset(offsetX, offsetY));
}
bool GlyphRendererShadowOffset::updateOrCreateState(int pass, osg::Geode* geode) {
if(!GlyphRenderer::updateOrCreateState(pass, geode)) return false;
osg::StateSet* state = geode->getOrCreateStateSet();
osg::Program* program = dynamic_cast<osg::Program*>(state->getAttribute(osg::StateAttribute::PROGRAM));
if(!program) return false;
const char* GET_FRAGMENT =
"#version 120\n"
"vec4 osgPango_GetFragment(vec4 coord, sampler2D textures[8], vec3 colors[8], float alpha) {"
" float tex0 = texture2D(textures[1], coord.st).a;"
" float tex1 = texture2D(textures[0], coord.st).a;"
" vec3 color0 = colors[1].rgb * tex0;"
" vec3 color1 = colors[0].rgb * tex1 + color0 * (1.0 - tex1);"
" float alpha0 = tex0;"
" float alpha1 = tex0 + tex1;"
" return vec4(color1, alpha1 * alpha);"
"}"
;
osg::Shader* frag = new osg::Shader(osg::Shader::FRAGMENT, GET_FRAGMENT);
program->addShader(frag);
return true;
}
GlyphRendererShadowGaussian::GlyphRendererShadowGaussian(unsigned int radius) {
addLayer(new GlyphLayer());
addLayer(new GlyphLayerShadowGaussian(radius));
}
bool GlyphRendererShadowGaussian::updateOrCreateState(int pass, osg::Geode* geode) {
if(!GlyphRenderer::updateOrCreateState(pass, geode)) return false;
osg::StateSet* state = geode->getOrCreateStateSet();
osg::Program* program = dynamic_cast<osg::Program*>(state->getAttribute(osg::StateAttribute::PROGRAM));
if(!program) return false;
const char* GET_FRAGMENT =
"#version 120\n"
"vec4 osgPango_GetFragment(vec4 coord, sampler2D textures[8], vec3 colors[8], float alpha) {"
" float tex0 = texture2D(textures[1], coord.st).a;"
" float tex1 = texture2D(textures[0], coord.st).a;"
" vec3 color0 = colors[1].rgb * tex0;"
" vec3 color1 = colors[0].rgb * tex1 + color0 * (1.0 - tex1);"
" float alpha0 = tex0;"
" float alpha1 = tex0 + tex1;"
" return vec4(color1, alpha1 * alpha);"
"}"
;
osg::Shader* frag = new osg::Shader(osg::Shader::FRAGMENT, GET_FRAGMENT);
program->addShader(frag);
return true;
}
}
<commit_msg>Cleanup GLSL part in GlyphRenderer, preparation for shader generator.<commit_after>// -*-c++-*- Copyright (C) 2010 osgPango Development Team
// $Id$
#include <cmath>
#include <sstream>
#include <osg/AlphaFunc>
#include <osg/Depth>
#include <osg/Texture2D>
#include <osg/Geode>
#include <osgCairo/Util>
#include <osgPango/GlyphRenderer>
namespace osgPango {
osg::Vec4 GlyphRenderer::getExtraGlyphExtents() const {
if(!_layers.size()) return osg::Vec4(0.0f, 0.0f, 0.0f, 0.0f);
osg::Vec4 result = _layers[0]->getExtraGlyphExtents();
for(unsigned int i = 1; i < _layers.size(); ++i) {
osg::Vec4 extents = _layers[i]->getExtraGlyphExtents();
result[0] = std::max(result[0], extents[0]);
result[1] = std::max(result[1], extents[1]);
result[2] = std::max(result[2], extents[2]);
result[3] = std::max(result[3], extents[3]);
}
return result;
}
bool GlyphRenderer::renderLayer(
unsigned int layer,
osgCairo::Surface* surface,
const osgCairo::Glyph& glyph,
unsigned int width,
unsigned int height
) {
if(layer < _layers.size()) return _layers[layer]->render(surface, glyph, width, height);
else return false;
}
bool GlyphRenderer::updateOrCreateState(int pass, osg::Geode* geode) {
static const char* VERTEX_SHADER =
"#version 120\n"
"varying vec4 pangoTexCoord;"
"void main() {"
" pangoTexCoord = gl_MultiTexCoord0;"
" gl_Position = ftransform();"
"}"
;
static const char* FRAGMENT_SHADER =
"#version 120\n"
"varying vec4 pangoTexCoord;"
"uniform vec3 pangoColor[8];"
"uniform sampler2D pangoTexture[8];"
"uniform float pangoAlpha;"
"vec4 osgPango_GetFragment(vec4, sampler2D[8], vec3[8], float);"
"void main() {"
" gl_FragColor = osgPango_GetFragment(pangoTexCoord, pangoTexture, pangoColor, pangoAlpha);"
"}"
;
osg::Program* program = new osg::Program();
osg::Shader* vert = new osg::Shader(osg::Shader::VERTEX, VERTEX_SHADER);
osg::Shader* frag = new osg::Shader(osg::Shader::FRAGMENT, FRAGMENT_SHADER);
vert->setName("pangoRendererVert");
frag->setName("pangoRendererFrag");
program->setName("pangoRenderer");
program->addShader(vert);
program->addShader(frag);
osg::StateSet* state = geode->getOrCreateStateSet();
state->setAttributeAndModes(program);
osg::Uniform* pangoTexture = new osg::Uniform(
osg::Uniform::INT,
"pangoTexture",
_layers.size()
);
for(unsigned int i = 0; i < _layers.size(); ++i)
pangoTexture->setElement(i, static_cast<int>(i));;
state->getOrCreateUniform("pangoAlpha", osg::Uniform::FLOAT)->set(1.0f);
state->addUniform(pangoTexture);
state->setMode(GL_BLEND, osg::StateAttribute::ON);
state->setAttributeAndModes(new osg::AlphaFunc(osg::AlphaFunc::GEQUAL, 0.01f));
state->setAttribute(new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false));
return true;
}
bool GlyphRenderer::updateOrCreateState(
osg::Geometry* geometry,
const GlyphGeometryState& ggs
) {
if(
ggs.textures.size() != _layers.size() ||
ggs.colors.size() != _layers.size()
) return false;
osg::Uniform* pangoColor = new osg::Uniform(
osg::Uniform::FLOAT_VEC3,
"pangoColor",
_layers.size()
);
osg::StateSet* state = geometry->getOrCreateStateSet();
state->addUniform(pangoColor);
for(unsigned int i = 0; i < _layers.size(); ++i) {
pangoColor->setElement(i, ggs.colors[i]);
state->setTextureAttributeAndModes(i, ggs.textures[i], osg::StateAttribute::ON);
}
return true;
}
void GlyphRenderer::addLayer(GlyphLayer *layer) {
_layers.push_back(layer);
}
void GlyphRenderer::removeLayer(unsigned int index) {
if(index < _layers.size()) _layers.erase(_layers.begin() + index);
}
void GlyphRenderer::replaceLayer(unsigned int index, GlyphLayer* layer) {
if(index < _layers.size()) _layers[index] = layer;
}
GlyphRendererDefault::GlyphRendererDefault() {
addLayer(new GlyphLayer());
}
bool GlyphRendererDefault::updateOrCreateState(int pass, osg::Geode* geode) {
if(!GlyphRenderer::updateOrCreateState(pass, geode)) return false;
osg::StateSet* state = geode->getOrCreateStateSet();
osg::Program* program = dynamic_cast<osg::Program*>(state->getAttribute(osg::StateAttribute::PROGRAM));
if(!program) return false;
// TODO: move this to pango shader generator
const char* GET_FRAGMENT =
"#version 120\n"
"vec4 osgPango_GetFragment(vec4 coord, sampler2D textures[8], vec3 colors[8], float alpha) {"
" float tex0 = texture2D(textures[0], coord.st).a;"
" vec3 color0 = colors[0].rgb * tex0;"
" float alpha0 = tex0;"
" return vec4(color0, alpha0 * alpha);"
"}"
;
osg::Shader* frag = new osg::Shader(osg::Shader::FRAGMENT, GET_FRAGMENT);
program->addShader(frag);
return true;
}
GlyphRendererOutline::GlyphRendererOutline(unsigned int outline) {
addLayer(new GlyphLayer());
addLayer(new GlyphLayerOutline(outline));
}
bool GlyphRendererOutline::updateOrCreateState(int pass, osg::Geode* geode) {
if(!GlyphRenderer::updateOrCreateState(pass, geode)) return false;
osg::StateSet* state = geode->getOrCreateStateSet();
osg::Program* program = dynamic_cast<osg::Program*>(state->getAttribute(osg::StateAttribute::PROGRAM));
if(!program) return false;
// TODO: move this to pango shader generator
const char* GET_FRAGMENT =
"#version 120\n"
"vec4 osgPango_GetFragment(vec4 coord, sampler2D textures[8], vec3 colors[8], float alpha) {"
" float tex0 = texture2D(textures[1], coord.st).a;"
" float tex1 = texture2D(textures[0], coord.st).a;"
" vec3 color0 = colors[1].rgb * tex0;"
" vec3 color1 = colors[0].rgb * tex1 + color0 * (1.0 - tex1);"
" float alpha0 = tex0;"
" float alpha1 = tex0 + tex1;"
" return vec4(color1, alpha1 * alpha);"
"}"
;
osg::Shader* frag = new osg::Shader(osg::Shader::FRAGMENT, GET_FRAGMENT);
program->addShader(frag);
return true;
}
GlyphRendererShadowOffset::GlyphRendererShadowOffset(int offsetX, int offsetY) {
unsigned int xt = 0;
unsigned int yt = 0;
if(offsetX < 0) xt = std::abs(offsetX);
if(offsetY < 0) yt = std::abs(offsetY);
addLayer(new GlyphLayer());
addLayer(new GlyphLayerShadowOffset(offsetX, offsetY));
}
bool GlyphRendererShadowOffset::updateOrCreateState(int pass, osg::Geode* geode) {
if(!GlyphRenderer::updateOrCreateState(pass, geode)) return false;
osg::StateSet* state = geode->getOrCreateStateSet();
osg::Program* program = dynamic_cast<osg::Program*>(state->getAttribute(osg::StateAttribute::PROGRAM));
if(!program) return false;
// TODO: move this to pango shader generator
const char* GET_FRAGMENT =
"#version 120\n"
"vec4 osgPango_GetFragment(vec4 coord, sampler2D textures[8], vec3 colors[8], float alpha) {"
" float tex0 = texture2D(textures[1], coord.st).a;"
" float tex1 = texture2D(textures[0], coord.st).a;"
" vec3 color0 = colors[1].rgb * tex0;"
" vec3 color1 = colors[0].rgb * tex1 + color0 * (1.0 - tex1);"
" float alpha0 = tex0;"
" float alpha1 = tex0 + tex1;"
" return vec4(color1, alpha1 * alpha);"
"}"
;
osg::Shader* frag = new osg::Shader(osg::Shader::FRAGMENT, GET_FRAGMENT);
program->addShader(frag);
return true;
}
GlyphRendererShadowGaussian::GlyphRendererShadowGaussian(unsigned int radius) {
addLayer(new GlyphLayer());
addLayer(new GlyphLayerShadowGaussian(radius));
}
bool GlyphRendererShadowGaussian::updateOrCreateState(int pass, osg::Geode* geode) {
if(!GlyphRenderer::updateOrCreateState(pass, geode)) return false;
osg::StateSet* state = geode->getOrCreateStateSet();
osg::Program* program = dynamic_cast<osg::Program*>(state->getAttribute(osg::StateAttribute::PROGRAM));
if(!program) return false;
// TODO: move this to pango shader generator
const char* GET_FRAGMENT =
"#version 120\n"
"vec4 osgPango_GetFragment(vec4 coord, sampler2D textures[8], vec3 colors[8], float alpha) {"
" float tex0 = texture2D(textures[1], coord.st).a;"
" float tex1 = texture2D(textures[0], coord.st).a;"
" vec3 color0 = colors[1].rgb * tex0;"
" vec3 color1 = colors[0].rgb * tex1 + color0 * (1.0 - tex1);"
" float alpha0 = tex0;"
" float alpha1 = tex0 + tex1;"
" return vec4(color1, alpha1 * alpha);"
"}"
;
osg::Shader* frag = new osg::Shader(osg::Shader::FRAGMENT, GET_FRAGMENT);
program->addShader(frag);
return true;
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2002-2012 The ANGLE 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.
//
// VertexDataManager.h: Defines the VertexDataManager, a class that
// runs the Buffer translation process.
#include "libANGLE/renderer/d3d/VertexDataManager.h"
#include "libANGLE/Buffer.h"
#include "libANGLE/Program.h"
#include "libANGLE/State.h"
#include "libANGLE/VertexAttribute.h"
#include "libANGLE/VertexArray.h"
#include "libANGLE/renderer/d3d/BufferD3D.h"
#include "libANGLE/renderer/d3d/VertexBuffer.h"
namespace
{
enum { INITIAL_STREAM_BUFFER_SIZE = 1024*1024 };
// This has to be at least 4k or else it fails on ATI cards.
enum { CONSTANT_VERTEX_BUFFER_SIZE = 4096 };
}
namespace rx
{
static int ElementsInBuffer(const gl::VertexAttribute &attrib, unsigned int size)
{
// Size cannot be larger than a GLsizei
if (size > static_cast<unsigned int>(std::numeric_limits<int>::max()))
{
size = static_cast<unsigned int>(std::numeric_limits<int>::max());
}
GLsizei stride = static_cast<GLsizei>(ComputeVertexAttributeStride(attrib));
return (size - attrib.offset % stride +
(stride - static_cast<GLsizei>(ComputeVertexAttributeTypeSize(attrib)))) /
stride;
}
VertexDataManager::CurrentValueState::CurrentValueState()
: buffer(nullptr),
offset(0)
{
data.FloatValues[0] = std::numeric_limits<float>::quiet_NaN();
data.FloatValues[1] = std::numeric_limits<float>::quiet_NaN();
data.FloatValues[2] = std::numeric_limits<float>::quiet_NaN();
data.FloatValues[3] = std::numeric_limits<float>::quiet_NaN();
data.Type = GL_FLOAT;
}
VertexDataManager::CurrentValueState::~CurrentValueState()
{
SafeDelete(buffer);
}
VertexDataManager::VertexDataManager(BufferFactoryD3D *factory)
: mFactory(factory),
mStreamingBuffer(nullptr),
// TODO(jmadill): use context caps
mCurrentValueCache(gl::MAX_VERTEX_ATTRIBS)
{
mStreamingBuffer = new StreamingVertexBufferInterface(factory, INITIAL_STREAM_BUFFER_SIZE);
if (!mStreamingBuffer)
{
ERR("Failed to allocate the streaming vertex buffer.");
}
// TODO(jmadill): use context caps
mActiveEnabledAttributes.reserve(gl::MAX_VERTEX_ATTRIBS);
mActiveDisabledAttributes.reserve(gl::MAX_VERTEX_ATTRIBS);
}
VertexDataManager::~VertexDataManager()
{
SafeDelete(mStreamingBuffer);
}
void VertexDataManager::hintUnmapAllResources(const std::vector<gl::VertexAttribute> &vertexAttributes)
{
mStreamingBuffer->getVertexBuffer()->hintUnmapResource();
for (const TranslatedAttribute *translated : mActiveEnabledAttributes)
{
gl::Buffer *buffer = translated->attribute->buffer.get();
BufferD3D *storage = buffer ? GetImplAs<BufferD3D>(buffer) : nullptr;
StaticVertexBufferInterface *staticBuffer = storage ? storage->getStaticVertexBuffer() : nullptr;
if (staticBuffer)
{
staticBuffer->getVertexBuffer()->hintUnmapResource();
}
}
for (auto ¤tValue : mCurrentValueCache)
{
if (currentValue.buffer != nullptr)
{
currentValue.buffer->getVertexBuffer()->hintUnmapResource();
}
}
}
gl::Error VertexDataManager::prepareVertexData(const gl::State &state,
GLint start,
GLsizei count,
std::vector<TranslatedAttribute> *translatedAttribs,
GLsizei instances)
{
if (!mStreamingBuffer)
{
return gl::Error(GL_OUT_OF_MEMORY, "Internal streaming vertex buffer is unexpectedly NULL.");
}
// Compute active enabled and active disable attributes, for speed.
// TODO(jmadill): don't recompute if there was no state change
const gl::VertexArray *vertexArray = state.getVertexArray();
const gl::Program *program = state.getProgram();
const auto &vertexAttributes = vertexArray->getVertexAttributes();
mActiveEnabledAttributes.clear();
mActiveDisabledAttributes.clear();
translatedAttribs->clear();
for (size_t attribIndex = 0; attribIndex < vertexAttributes.size(); ++attribIndex)
{
if (program->isAttribLocationActive(attribIndex))
{
// Resize automatically puts in empty attribs
translatedAttribs->resize(attribIndex + 1);
TranslatedAttribute *translated = &(*translatedAttribs)[attribIndex];
// Record the attribute now
translated->active = true;
translated->attribute = &vertexAttributes[attribIndex];
translated->currentValueType =
state.getVertexAttribCurrentValue(static_cast<unsigned int>(attribIndex)).Type;
translated->divisor = vertexAttributes[attribIndex].divisor;
if (vertexAttributes[attribIndex].enabled)
{
mActiveEnabledAttributes.push_back(translated);
// Also invalidate static buffers that don't contain matching attributes
invalidateMatchingStaticData(
vertexAttributes[attribIndex],
state.getVertexAttribCurrentValue(static_cast<unsigned int>(attribIndex)));
}
else
{
mActiveDisabledAttributes.push_back(attribIndex);
}
}
}
// Reserve the required space in the buffers
for (const TranslatedAttribute *activeAttrib : mActiveEnabledAttributes)
{
gl::Error error = reserveSpaceForAttrib(*activeAttrib, count, instances);
if (error.isError())
{
return error;
}
}
// Perform the vertex data translations
for (TranslatedAttribute *activeAttrib : mActiveEnabledAttributes)
{
gl::Error error = storeAttribute(activeAttrib, start, count, instances);
if (error.isError())
{
hintUnmapAllResources(vertexAttributes);
return error;
}
}
for (size_t attribIndex : mActiveDisabledAttributes)
{
if (mCurrentValueCache[attribIndex].buffer == nullptr)
{
mCurrentValueCache[attribIndex].buffer = new StreamingVertexBufferInterface(mFactory, CONSTANT_VERTEX_BUFFER_SIZE);
}
gl::Error error = storeCurrentValue(
state.getVertexAttribCurrentValue(static_cast<unsigned int>(attribIndex)),
&(*translatedAttribs)[attribIndex], &mCurrentValueCache[attribIndex]);
if (error.isError())
{
hintUnmapAllResources(vertexAttributes);
return error;
}
}
// Hint to unmap all the resources
hintUnmapAllResources(vertexAttributes);
for (const TranslatedAttribute *activeAttrib : mActiveEnabledAttributes)
{
gl::Buffer *buffer = activeAttrib->attribute->buffer.get();
if (buffer)
{
BufferD3D *bufferD3D = GetImplAs<BufferD3D>(buffer);
size_t typeSize = ComputeVertexAttributeTypeSize(*activeAttrib->attribute);
bufferD3D->promoteStaticUsage(count * static_cast<int>(typeSize));
}
}
return gl::Error(GL_NO_ERROR);
}
void VertexDataManager::invalidateMatchingStaticData(const gl::VertexAttribute &attrib,
const gl::VertexAttribCurrentValueData ¤tValue) const
{
gl::Buffer *buffer = attrib.buffer.get();
if (buffer)
{
BufferD3D *bufferImpl = GetImplAs<BufferD3D>(buffer);
StaticVertexBufferInterface *staticBuffer = bufferImpl->getStaticVertexBuffer();
if (staticBuffer &&
staticBuffer->getBufferSize() > 0 &&
!staticBuffer->lookupAttribute(attrib, NULL) &&
!staticBuffer->directStoragePossible(attrib, currentValue.Type))
{
bufferImpl->invalidateStaticData();
}
}
}
gl::Error VertexDataManager::reserveSpaceForAttrib(const TranslatedAttribute &translatedAttrib,
GLsizei count,
GLsizei instances) const
{
const gl::VertexAttribute &attrib = *translatedAttrib.attribute;
gl::Buffer *buffer = attrib.buffer.get();
BufferD3D *bufferImpl = buffer ? GetImplAs<BufferD3D>(buffer) : NULL;
StaticVertexBufferInterface *staticBuffer = bufferImpl ? bufferImpl->getStaticVertexBuffer() : NULL;
VertexBufferInterface *vertexBuffer = staticBuffer ? staticBuffer : static_cast<VertexBufferInterface*>(mStreamingBuffer);
if (!vertexBuffer->directStoragePossible(attrib, translatedAttrib.currentValueType))
{
if (staticBuffer)
{
if (staticBuffer->getBufferSize() == 0)
{
int totalCount =
ElementsInBuffer(attrib, static_cast<unsigned int>(bufferImpl->getSize()));
gl::Error error = staticBuffer->reserveVertexSpace(attrib, totalCount, 0);
if (error.isError())
{
return error;
}
}
}
else
{
size_t totalCount = ComputeVertexAttributeElementCount(attrib, count, instances);
ASSERT(!bufferImpl ||
ElementsInBuffer(attrib, static_cast<unsigned int>(bufferImpl->getSize())) >=
totalCount);
gl::Error error = mStreamingBuffer->reserveVertexSpace(
attrib, static_cast<GLsizei>(totalCount), instances);
if (error.isError())
{
return error;
}
}
}
return gl::Error(GL_NO_ERROR);
}
gl::Error VertexDataManager::storeAttribute(TranslatedAttribute *translated,
GLint start,
GLsizei count,
GLsizei instances)
{
const gl::VertexAttribute &attrib = *translated->attribute;
gl::Buffer *buffer = attrib.buffer.get();
ASSERT(buffer || attrib.pointer);
ASSERT(attrib.enabled);
BufferD3D *storage = buffer ? GetImplAs<BufferD3D>(buffer) : NULL;
StaticVertexBufferInterface *staticBuffer = storage ? storage->getStaticVertexBuffer() : NULL;
VertexBufferInterface *vertexBuffer = staticBuffer ? staticBuffer : static_cast<VertexBufferInterface*>(mStreamingBuffer);
bool directStorage = vertexBuffer->directStoragePossible(attrib, translated->currentValueType);
// Instanced vertices do not apply the 'start' offset
GLint firstVertexIndex = (instances > 0 && attrib.divisor > 0 ? 0 : start);
translated->vertexBuffer = vertexBuffer->getVertexBuffer();
if (directStorage)
{
translated->storage = storage;
translated->serial = storage->getSerial();
translated->stride = static_cast<unsigned int>(ComputeVertexAttributeStride(attrib));
translated->offset = static_cast<unsigned int>(attrib.offset + translated->stride * firstVertexIndex);
return gl::Error(GL_NO_ERROR);
}
// Compute source data pointer
const uint8_t *sourceData = nullptr;
if (buffer)
{
gl::Error error = storage->getData(&sourceData);
if (error.isError())
{
return error;
}
sourceData += static_cast<int>(attrib.offset);
}
else
{
sourceData = static_cast<const uint8_t*>(attrib.pointer);
}
unsigned int streamOffset = 0;
unsigned int outputElementSize = 0;
if (staticBuffer)
{
gl::Error error = staticBuffer->getVertexBuffer()->getSpaceRequired(attrib, 1, 0, &outputElementSize);
if (error.isError())
{
return error;
}
if (!staticBuffer->lookupAttribute(attrib, &streamOffset))
{
// Convert the entire buffer
int totalCount =
ElementsInBuffer(attrib, static_cast<unsigned int>(storage->getSize()));
int startIndex = static_cast<int>(attrib.offset) /
static_cast<int>(ComputeVertexAttributeStride(attrib));
error = staticBuffer->storeVertexAttributes(attrib,
translated->currentValueType,
-startIndex,
totalCount,
0,
&streamOffset,
sourceData);
if (error.isError())
{
return error;
}
}
unsigned int firstElementOffset =
(static_cast<unsigned int>(attrib.offset) /
static_cast<unsigned int>(ComputeVertexAttributeStride(attrib))) *
outputElementSize;
unsigned int startOffset = (instances == 0 || attrib.divisor == 0) ? firstVertexIndex * outputElementSize : 0;
if (streamOffset + firstElementOffset + startOffset < streamOffset)
{
return gl::Error(GL_OUT_OF_MEMORY);
}
streamOffset += firstElementOffset + startOffset;
}
else
{
size_t totalCount = ComputeVertexAttributeElementCount(attrib, count, instances);
gl::Error error = mStreamingBuffer->getVertexBuffer()->getSpaceRequired(attrib, 1, 0, &outputElementSize);
if (error.isError())
{
return error;
}
error = mStreamingBuffer->storeVertexAttributes(
attrib, translated->currentValueType, firstVertexIndex,
static_cast<GLsizei>(totalCount), instances, &streamOffset, sourceData);
if (error.isError())
{
return error;
}
}
translated->storage = nullptr;
translated->serial = vertexBuffer->getSerial();
translated->stride = outputElementSize;
translated->offset = streamOffset;
return gl::Error(GL_NO_ERROR);
}
gl::Error VertexDataManager::storeCurrentValue(const gl::VertexAttribCurrentValueData ¤tValue,
TranslatedAttribute *translated,
CurrentValueState *cachedState)
{
if (cachedState->data != currentValue)
{
const gl::VertexAttribute &attrib = *translated->attribute;
gl::Error error = cachedState->buffer->reserveVertexSpace(attrib, 1, 0);
if (error.isError())
{
return error;
}
const uint8_t *sourceData = reinterpret_cast<const uint8_t*>(currentValue.FloatValues);
unsigned int streamOffset;
error = cachedState->buffer->storeVertexAttributes(attrib, currentValue.Type, 0, 1, 0, &streamOffset, sourceData);
if (error.isError())
{
return error;
}
cachedState->data = currentValue;
cachedState->offset = streamOffset;
}
translated->storage = NULL;
translated->vertexBuffer = cachedState->buffer->getVertexBuffer();
translated->serial = cachedState->buffer->getSerial();
translated->divisor = 0;
translated->stride = 0;
translated->offset = static_cast<unsigned int>(cachedState->offset);
return gl::Error(GL_NO_ERROR);
}
}
<commit_msg>Fix unsigned/signed comparison in VertexDataManager.<commit_after>//
// Copyright (c) 2002-2012 The ANGLE 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.
//
// VertexDataManager.h: Defines the VertexDataManager, a class that
// runs the Buffer translation process.
#include "libANGLE/renderer/d3d/VertexDataManager.h"
#include "libANGLE/Buffer.h"
#include "libANGLE/Program.h"
#include "libANGLE/State.h"
#include "libANGLE/VertexAttribute.h"
#include "libANGLE/VertexArray.h"
#include "libANGLE/renderer/d3d/BufferD3D.h"
#include "libANGLE/renderer/d3d/VertexBuffer.h"
namespace
{
enum { INITIAL_STREAM_BUFFER_SIZE = 1024*1024 };
// This has to be at least 4k or else it fails on ATI cards.
enum { CONSTANT_VERTEX_BUFFER_SIZE = 4096 };
}
namespace rx
{
static int ElementsInBuffer(const gl::VertexAttribute &attrib, unsigned int size)
{
// Size cannot be larger than a GLsizei
if (size > static_cast<unsigned int>(std::numeric_limits<int>::max()))
{
size = static_cast<unsigned int>(std::numeric_limits<int>::max());
}
GLsizei stride = static_cast<GLsizei>(ComputeVertexAttributeStride(attrib));
return (size - attrib.offset % stride +
(stride - static_cast<GLsizei>(ComputeVertexAttributeTypeSize(attrib)))) /
stride;
}
VertexDataManager::CurrentValueState::CurrentValueState()
: buffer(nullptr),
offset(0)
{
data.FloatValues[0] = std::numeric_limits<float>::quiet_NaN();
data.FloatValues[1] = std::numeric_limits<float>::quiet_NaN();
data.FloatValues[2] = std::numeric_limits<float>::quiet_NaN();
data.FloatValues[3] = std::numeric_limits<float>::quiet_NaN();
data.Type = GL_FLOAT;
}
VertexDataManager::CurrentValueState::~CurrentValueState()
{
SafeDelete(buffer);
}
VertexDataManager::VertexDataManager(BufferFactoryD3D *factory)
: mFactory(factory),
mStreamingBuffer(nullptr),
// TODO(jmadill): use context caps
mCurrentValueCache(gl::MAX_VERTEX_ATTRIBS)
{
mStreamingBuffer = new StreamingVertexBufferInterface(factory, INITIAL_STREAM_BUFFER_SIZE);
if (!mStreamingBuffer)
{
ERR("Failed to allocate the streaming vertex buffer.");
}
// TODO(jmadill): use context caps
mActiveEnabledAttributes.reserve(gl::MAX_VERTEX_ATTRIBS);
mActiveDisabledAttributes.reserve(gl::MAX_VERTEX_ATTRIBS);
}
VertexDataManager::~VertexDataManager()
{
SafeDelete(mStreamingBuffer);
}
void VertexDataManager::hintUnmapAllResources(const std::vector<gl::VertexAttribute> &vertexAttributes)
{
mStreamingBuffer->getVertexBuffer()->hintUnmapResource();
for (const TranslatedAttribute *translated : mActiveEnabledAttributes)
{
gl::Buffer *buffer = translated->attribute->buffer.get();
BufferD3D *storage = buffer ? GetImplAs<BufferD3D>(buffer) : nullptr;
StaticVertexBufferInterface *staticBuffer = storage ? storage->getStaticVertexBuffer() : nullptr;
if (staticBuffer)
{
staticBuffer->getVertexBuffer()->hintUnmapResource();
}
}
for (auto ¤tValue : mCurrentValueCache)
{
if (currentValue.buffer != nullptr)
{
currentValue.buffer->getVertexBuffer()->hintUnmapResource();
}
}
}
gl::Error VertexDataManager::prepareVertexData(const gl::State &state,
GLint start,
GLsizei count,
std::vector<TranslatedAttribute> *translatedAttribs,
GLsizei instances)
{
if (!mStreamingBuffer)
{
return gl::Error(GL_OUT_OF_MEMORY, "Internal streaming vertex buffer is unexpectedly NULL.");
}
// Compute active enabled and active disable attributes, for speed.
// TODO(jmadill): don't recompute if there was no state change
const gl::VertexArray *vertexArray = state.getVertexArray();
const gl::Program *program = state.getProgram();
const auto &vertexAttributes = vertexArray->getVertexAttributes();
mActiveEnabledAttributes.clear();
mActiveDisabledAttributes.clear();
translatedAttribs->clear();
for (size_t attribIndex = 0; attribIndex < vertexAttributes.size(); ++attribIndex)
{
if (program->isAttribLocationActive(attribIndex))
{
// Resize automatically puts in empty attribs
translatedAttribs->resize(attribIndex + 1);
TranslatedAttribute *translated = &(*translatedAttribs)[attribIndex];
// Record the attribute now
translated->active = true;
translated->attribute = &vertexAttributes[attribIndex];
translated->currentValueType =
state.getVertexAttribCurrentValue(static_cast<unsigned int>(attribIndex)).Type;
translated->divisor = vertexAttributes[attribIndex].divisor;
if (vertexAttributes[attribIndex].enabled)
{
mActiveEnabledAttributes.push_back(translated);
// Also invalidate static buffers that don't contain matching attributes
invalidateMatchingStaticData(
vertexAttributes[attribIndex],
state.getVertexAttribCurrentValue(static_cast<unsigned int>(attribIndex)));
}
else
{
mActiveDisabledAttributes.push_back(attribIndex);
}
}
}
// Reserve the required space in the buffers
for (const TranslatedAttribute *activeAttrib : mActiveEnabledAttributes)
{
gl::Error error = reserveSpaceForAttrib(*activeAttrib, count, instances);
if (error.isError())
{
return error;
}
}
// Perform the vertex data translations
for (TranslatedAttribute *activeAttrib : mActiveEnabledAttributes)
{
gl::Error error = storeAttribute(activeAttrib, start, count, instances);
if (error.isError())
{
hintUnmapAllResources(vertexAttributes);
return error;
}
}
for (size_t attribIndex : mActiveDisabledAttributes)
{
if (mCurrentValueCache[attribIndex].buffer == nullptr)
{
mCurrentValueCache[attribIndex].buffer = new StreamingVertexBufferInterface(mFactory, CONSTANT_VERTEX_BUFFER_SIZE);
}
gl::Error error = storeCurrentValue(
state.getVertexAttribCurrentValue(static_cast<unsigned int>(attribIndex)),
&(*translatedAttribs)[attribIndex], &mCurrentValueCache[attribIndex]);
if (error.isError())
{
hintUnmapAllResources(vertexAttributes);
return error;
}
}
// Hint to unmap all the resources
hintUnmapAllResources(vertexAttributes);
for (const TranslatedAttribute *activeAttrib : mActiveEnabledAttributes)
{
gl::Buffer *buffer = activeAttrib->attribute->buffer.get();
if (buffer)
{
BufferD3D *bufferD3D = GetImplAs<BufferD3D>(buffer);
size_t typeSize = ComputeVertexAttributeTypeSize(*activeAttrib->attribute);
bufferD3D->promoteStaticUsage(count * static_cast<int>(typeSize));
}
}
return gl::Error(GL_NO_ERROR);
}
void VertexDataManager::invalidateMatchingStaticData(const gl::VertexAttribute &attrib,
const gl::VertexAttribCurrentValueData ¤tValue) const
{
gl::Buffer *buffer = attrib.buffer.get();
if (buffer)
{
BufferD3D *bufferImpl = GetImplAs<BufferD3D>(buffer);
StaticVertexBufferInterface *staticBuffer = bufferImpl->getStaticVertexBuffer();
if (staticBuffer &&
staticBuffer->getBufferSize() > 0 &&
!staticBuffer->lookupAttribute(attrib, NULL) &&
!staticBuffer->directStoragePossible(attrib, currentValue.Type))
{
bufferImpl->invalidateStaticData();
}
}
}
gl::Error VertexDataManager::reserveSpaceForAttrib(const TranslatedAttribute &translatedAttrib,
GLsizei count,
GLsizei instances) const
{
const gl::VertexAttribute &attrib = *translatedAttrib.attribute;
gl::Buffer *buffer = attrib.buffer.get();
BufferD3D *bufferImpl = buffer ? GetImplAs<BufferD3D>(buffer) : NULL;
StaticVertexBufferInterface *staticBuffer = bufferImpl ? bufferImpl->getStaticVertexBuffer() : NULL;
VertexBufferInterface *vertexBuffer = staticBuffer ? staticBuffer : static_cast<VertexBufferInterface*>(mStreamingBuffer);
if (!vertexBuffer->directStoragePossible(attrib, translatedAttrib.currentValueType))
{
if (staticBuffer)
{
if (staticBuffer->getBufferSize() == 0)
{
int totalCount =
ElementsInBuffer(attrib, static_cast<unsigned int>(bufferImpl->getSize()));
gl::Error error = staticBuffer->reserveVertexSpace(attrib, totalCount, 0);
if (error.isError())
{
return error;
}
}
}
else
{
size_t totalCount = ComputeVertexAttributeElementCount(attrib, count, instances);
ASSERT(!bufferImpl ||
ElementsInBuffer(attrib, static_cast<unsigned int>(bufferImpl->getSize())) >=
static_cast<int>(totalCount));
gl::Error error = mStreamingBuffer->reserveVertexSpace(
attrib, static_cast<GLsizei>(totalCount), instances);
if (error.isError())
{
return error;
}
}
}
return gl::Error(GL_NO_ERROR);
}
gl::Error VertexDataManager::storeAttribute(TranslatedAttribute *translated,
GLint start,
GLsizei count,
GLsizei instances)
{
const gl::VertexAttribute &attrib = *translated->attribute;
gl::Buffer *buffer = attrib.buffer.get();
ASSERT(buffer || attrib.pointer);
ASSERT(attrib.enabled);
BufferD3D *storage = buffer ? GetImplAs<BufferD3D>(buffer) : NULL;
StaticVertexBufferInterface *staticBuffer = storage ? storage->getStaticVertexBuffer() : NULL;
VertexBufferInterface *vertexBuffer = staticBuffer ? staticBuffer : static_cast<VertexBufferInterface*>(mStreamingBuffer);
bool directStorage = vertexBuffer->directStoragePossible(attrib, translated->currentValueType);
// Instanced vertices do not apply the 'start' offset
GLint firstVertexIndex = (instances > 0 && attrib.divisor > 0 ? 0 : start);
translated->vertexBuffer = vertexBuffer->getVertexBuffer();
if (directStorage)
{
translated->storage = storage;
translated->serial = storage->getSerial();
translated->stride = static_cast<unsigned int>(ComputeVertexAttributeStride(attrib));
translated->offset = static_cast<unsigned int>(attrib.offset + translated->stride * firstVertexIndex);
return gl::Error(GL_NO_ERROR);
}
// Compute source data pointer
const uint8_t *sourceData = nullptr;
if (buffer)
{
gl::Error error = storage->getData(&sourceData);
if (error.isError())
{
return error;
}
sourceData += static_cast<int>(attrib.offset);
}
else
{
sourceData = static_cast<const uint8_t*>(attrib.pointer);
}
unsigned int streamOffset = 0;
unsigned int outputElementSize = 0;
if (staticBuffer)
{
gl::Error error = staticBuffer->getVertexBuffer()->getSpaceRequired(attrib, 1, 0, &outputElementSize);
if (error.isError())
{
return error;
}
if (!staticBuffer->lookupAttribute(attrib, &streamOffset))
{
// Convert the entire buffer
int totalCount =
ElementsInBuffer(attrib, static_cast<unsigned int>(storage->getSize()));
int startIndex = static_cast<int>(attrib.offset) /
static_cast<int>(ComputeVertexAttributeStride(attrib));
error = staticBuffer->storeVertexAttributes(attrib,
translated->currentValueType,
-startIndex,
totalCount,
0,
&streamOffset,
sourceData);
if (error.isError())
{
return error;
}
}
unsigned int firstElementOffset =
(static_cast<unsigned int>(attrib.offset) /
static_cast<unsigned int>(ComputeVertexAttributeStride(attrib))) *
outputElementSize;
unsigned int startOffset = (instances == 0 || attrib.divisor == 0) ? firstVertexIndex * outputElementSize : 0;
if (streamOffset + firstElementOffset + startOffset < streamOffset)
{
return gl::Error(GL_OUT_OF_MEMORY);
}
streamOffset += firstElementOffset + startOffset;
}
else
{
size_t totalCount = ComputeVertexAttributeElementCount(attrib, count, instances);
gl::Error error = mStreamingBuffer->getVertexBuffer()->getSpaceRequired(attrib, 1, 0, &outputElementSize);
if (error.isError())
{
return error;
}
error = mStreamingBuffer->storeVertexAttributes(
attrib, translated->currentValueType, firstVertexIndex,
static_cast<GLsizei>(totalCount), instances, &streamOffset, sourceData);
if (error.isError())
{
return error;
}
}
translated->storage = nullptr;
translated->serial = vertexBuffer->getSerial();
translated->stride = outputElementSize;
translated->offset = streamOffset;
return gl::Error(GL_NO_ERROR);
}
gl::Error VertexDataManager::storeCurrentValue(const gl::VertexAttribCurrentValueData ¤tValue,
TranslatedAttribute *translated,
CurrentValueState *cachedState)
{
if (cachedState->data != currentValue)
{
const gl::VertexAttribute &attrib = *translated->attribute;
gl::Error error = cachedState->buffer->reserveVertexSpace(attrib, 1, 0);
if (error.isError())
{
return error;
}
const uint8_t *sourceData = reinterpret_cast<const uint8_t*>(currentValue.FloatValues);
unsigned int streamOffset;
error = cachedState->buffer->storeVertexAttributes(attrib, currentValue.Type, 0, 1, 0, &streamOffset, sourceData);
if (error.isError())
{
return error;
}
cachedState->data = currentValue;
cachedState->offset = streamOffset;
}
translated->storage = NULL;
translated->vertexBuffer = cachedState->buffer->getVertexBuffer();
translated->serial = cachedState->buffer->getSerial();
translated->divisor = 0;
translated->stride = 0;
translated->offset = static_cast<unsigned int>(cachedState->offset);
return gl::Error(GL_NO_ERROR);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 libmv authors.
//
// 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 "euclidean_resection.h"
#include "libmv/numeric/numeric.h"
#include "libmv/logging/logging.h"
#include "testing/testing.h"
using namespace libmv::resection;
using namespace libmv;
// Generates all necessary inputs and desigred outputs for
// the EuclideanResection.
void CreateCameraSystem(const Mat3& KK,
const Mat3X& x_image,
const Vec& X_distances,
const Mat3& R_input,
const Vec3& T_input,
Mat2X *x_cam,
Mat3X *X_world,
Mat3 *R_expected,
Vec3 *T_expected) {
int num_points = x_image.cols();
Mat3X x_unit_cam(3,num_points);
x_unit_cam = KK.inverse() * x_image;
// Normalized camera coordinates to be used as an input to the PnP function.
*x_cam = x_unit_cam.block(0,0,2,num_points);
//instead of NormalizeColumnVectors(&x_unit_cam);
for (int i = 0; i < num_points; ++i){
x_unit_cam.col(i).normalize();
}
// Create the 3D points int he camera system.
Mat X_camera(3, num_points);
for (int ii = 0; ii < num_points; ++ii) {
X_camera.col(ii) = X_distances(ii) * x_unit_cam.col(ii);
}
//Apply the transfomration to the camera 3D points
Mat translation_matrix(3, num_points);
translation_matrix.row(0).setConstant(T_input(0));
translation_matrix.row(1).setConstant(T_input(1));
translation_matrix.row(2).setConstant(T_input(2));
*X_world = R_input * X_camera + translation_matrix;
// Expected variables for comparison.
*R_expected = R_input.transpose();
*T_expected = *R_expected * ( - T_input);
};
TEST(AbsoluteOrientation, QuaternionSlution) {
srand((unsigned)time(0));
int num_points = 4;
Mat X;
Mat Xp;
X = 100 * Mat::Random(3,num_points);
// Create random translation and rotation.
Mat3 R_input;
R_input = Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitZ())
* Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitZ());
Vec3 t_input;
t_input.setRandom();
t_input=100*t_input;
Mat translation_matrix(3, num_points);
translation_matrix.row(0).setConstant(t_input(0));
translation_matrix.row(1).setConstant(t_input(1));
translation_matrix.row(2).setConstant(t_input(2));
// Create Xp as Xp = R * X + t.
Xp = R_input * X + translation_matrix;
// Output variables.
Mat3 R;
Vec3 t;
AbsoluteOrientation(X,Xp,&R,&t);
EXPECT_MATRIX_NEAR(t, t_input, 1e-6);
EXPECT_MATRIX_NEAR(R, R_input, 1e-8);
}
TEST(EuclideanResection, Points4KnownImagePointsRandomTranslationRotation) {
// In this test only the translation and rottion are random.
// The image points are selected from a real case and are well conditioned.
Vec2i image_dimensions;
image_dimensions << 1600, 1200;
srand((unsigned)time(0));
Mat3 KK;
KK << 2796.813000676695538, 0, 804.489474977057966,
0 , 2796.483860262341295, 641.641715857649729,
0, 0, 1;
int num_points = 4;
Mat3X x_image(3, num_points);
// Image points.
x_image << 1164.06, 734.948, 749.599, 430.727,
681.386, 844.59, 496.315, 580.775,
1, 1, 1, 1;
// Normalized camera coordinates to be used as an input to the PnP function.
Mat2X x_cam;
Vec X_distances(num_points); // a vector of the 4 distances to the 3D points
X_distances << 100 * Vec::Random(num_points).cwise().abs();
//Transformation variables
Mat3 R_input;
R_input = Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitZ())
* Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitZ());
Vec3 T_input;
T_input.setRandom();
T_input=100 * T_input;
Mat3 R_expected;
Vec3 T_expected;
Mat3X X_world;
// Create the camera system.
CreateCameraSystem(KK, x_image, X_distances, R_input, T_input,
&x_cam, &X_world, &R_expected, &T_expected);
Mat3 R_output;
Vec3 T_output;
EuclideanResection(x_cam, X_world, &R_output, &T_output);
EXPECT_MATRIX_NEAR(T_output, T_expected, 1e-6);
EXPECT_MATRIX_NEAR(R_output, R_expected, 1e-7);
}
TEST(EuclideanResection, Points6AllRandomInput) {
int num_points = 6;
Vec2i image_dimensions;
image_dimensions << 1600, 1200;
srand((unsigned)time(0));
Mat3 KK;
KK << 2796.813000676695538, 0, 804.489474977057966,
0 , 2796.483860262341295, 641.641715857649729,
0, 0, 1;
Mat3X x_image(3, num_points);
// Randomly create the image points.
x_image.row(0) = image_dimensions(0) * Vec::Random(num_points).cwise().abs()
+ Vec::Random(num_points);
x_image.row(1) = image_dimensions(1) * Vec::Random(num_points).cwise().abs()
+ Vec::Random(num_points);
x_image.row(2).setOnes();
// Normalized camera coordinates to be used as an input to the PnP function.
Mat2X x_cam;
Vec X_distances(num_points); // a vector of the 4 distances to the 3D points
X_distances << 100 * Vec::Random(num_points).cwise().abs();
// Transformation variables.
Mat3 R_input;
R_input = Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitZ())
* Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitZ());
Vec3 T_input;
T_input.setRandom();
T_input=100 * T_input;
Mat3 R_expected;
Vec3 T_expected;
Mat3X X_world;
// Create the camera system.
CreateCameraSystem(KK, x_image, X_distances, R_input, T_input,
&x_cam, &X_world, &R_expected, &T_expected);
Mat3 R_output;
Vec3 T_output;
EuclideanResection(x_cam, X_world, &R_output, &T_output);
EXPECT_MATRIX_NEAR(T_output, T_expected, 1e-6);
EXPECT_MATRIX_NEAR(R_output, R_expected, 1e-7);
}
<commit_msg>Correct a typing error. Fix precision of Points4KnownImagePointsRandomTranslationRotation to make the test run fine on windows.<commit_after>// Copyright (c) 2009 libmv authors.
//
// 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 "euclidean_resection.h"
#include "libmv/numeric/numeric.h"
#include "libmv/logging/logging.h"
#include "testing/testing.h"
using namespace libmv::resection;
using namespace libmv;
// Generates all necessary inputs and desigred outputs for
// the EuclideanResection.
void CreateCameraSystem(const Mat3& KK,
const Mat3X& x_image,
const Vec& X_distances,
const Mat3& R_input,
const Vec3& T_input,
Mat2X *x_cam,
Mat3X *X_world,
Mat3 *R_expected,
Vec3 *T_expected) {
int num_points = x_image.cols();
Mat3X x_unit_cam(3,num_points);
x_unit_cam = KK.inverse() * x_image;
// Normalized camera coordinates to be used as an input to the PnP function.
*x_cam = x_unit_cam.block(0,0,2,num_points);
//instead of NormalizeColumnVectors(&x_unit_cam);
for (int i = 0; i < num_points; ++i){
x_unit_cam.col(i).normalize();
}
// Create the 3D points int he camera system.
Mat X_camera(3, num_points);
for (int ii = 0; ii < num_points; ++ii) {
X_camera.col(ii) = X_distances(ii) * x_unit_cam.col(ii);
}
//Apply the transformation to the camera 3D points
Mat translation_matrix(3, num_points);
translation_matrix.row(0).setConstant(T_input(0));
translation_matrix.row(1).setConstant(T_input(1));
translation_matrix.row(2).setConstant(T_input(2));
*X_world = R_input * X_camera + translation_matrix;
// Expected variables for comparison.
*R_expected = R_input.transpose();
*T_expected = *R_expected * ( - T_input);
};
TEST(AbsoluteOrientation, QuaternionSlution) {
srand((unsigned)time(0));
int num_points = 4;
Mat X;
Mat Xp;
X = 100 * Mat::Random(3,num_points);
// Create random translation and rotation.
Mat3 R_input;
R_input = Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitZ())
* Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitZ());
Vec3 t_input;
t_input.setRandom();
t_input=100*t_input;
Mat translation_matrix(3, num_points);
translation_matrix.row(0).setConstant(t_input(0));
translation_matrix.row(1).setConstant(t_input(1));
translation_matrix.row(2).setConstant(t_input(2));
// Create Xp as Xp = R * X + t.
Xp = R_input * X + translation_matrix;
// Output variables.
Mat3 R;
Vec3 t;
AbsoluteOrientation(X,Xp,&R,&t);
EXPECT_MATRIX_NEAR(t, t_input, 1e-6);
EXPECT_MATRIX_NEAR(R, R_input, 1e-8);
}
TEST(EuclideanResection, Points4KnownImagePointsRandomTranslationRotation) {
// In this test only the translation and rottion are random.
// The image points are selected from a real case and are well conditioned.
Vec2i image_dimensions;
image_dimensions << 1600, 1200;
srand((unsigned)time(0));
Mat3 KK;
KK << 2796.813000676695538, 0, 804.489474977057966,
0 , 2796.483860262341295, 641.641715857649729,
0, 0, 1;
int num_points = 4;
Mat3X x_image(3, num_points);
// Image points.
x_image << 1164.06, 734.948, 749.599, 430.727,
681.386, 844.59, 496.315, 580.775,
1, 1, 1, 1;
// Normalized camera coordinates to be used as an input to the PnP function.
Mat2X x_cam;
Vec X_distances(num_points); // a vector of the 4 distances to the 3D points
X_distances << 100 * Vec::Random(num_points).cwise().abs();
// Transformation variables
Mat3 R_input;
R_input = Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitZ())
* Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitZ());
Vec3 T_input;
T_input.setRandom();
T_input=100 * T_input;
Mat3 R_expected;
Vec3 T_expected;
Mat3X X_world;
// Create the camera system.
CreateCameraSystem(KK, x_image, X_distances, R_input, T_input,
&x_cam, &X_world, &R_expected, &T_expected);
Mat3 R_output;
Vec3 T_output;
EuclideanResection(x_cam, X_world, &R_output, &T_output);
EXPECT_MATRIX_NEAR(T_output, T_expected, 1e-5);
EXPECT_MATRIX_NEAR(R_output, R_expected, 1e-7);
}
TEST(EuclideanResection, Points6AllRandomInput) {
int num_points = 6;
Vec2i image_dimensions;
image_dimensions << 1600, 1200;
srand((unsigned)time(0));
Mat3 KK;
KK << 2796.813000676695538, 0, 804.489474977057966,
0 , 2796.483860262341295, 641.641715857649729,
0, 0, 1;
Mat3X x_image(3, num_points);
// Randomly create the image points.
x_image.row(0) = image_dimensions(0) * Vec::Random(num_points).cwise().abs()
+ Vec::Random(num_points);
x_image.row(1) = image_dimensions(1) * Vec::Random(num_points).cwise().abs()
+ Vec::Random(num_points);
x_image.row(2).setOnes();
// Normalized camera coordinates to be used as an input to the PnP function.
Mat2X x_cam;
Vec X_distances(num_points); // a vector of the 4 distances to the 3D points
X_distances << 100 * Vec::Random(num_points).cwise().abs();
// Transformation variables.
Mat3 R_input;
R_input = Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitZ())
* Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitY())
* Eigen::AngleAxisd(rand(), Eigen::Vector3d::UnitZ());
Vec3 T_input;
T_input.setRandom();
T_input=100 * T_input;
Mat3 R_expected;
Vec3 T_expected;
Mat3X X_world;
// Create the camera system.
CreateCameraSystem(KK, x_image, X_distances, R_input, T_input,
&x_cam, &X_world, &R_expected, &T_expected);
Mat3 R_output;
Vec3 T_output;
EuclideanResection(x_cam, X_world, &R_output, &T_output);
EXPECT_MATRIX_NEAR(T_output, T_expected, 1e-6);
EXPECT_MATRIX_NEAR(R_output, R_expected, 1e-7);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <random>
#include <folly/Traits.h>
#include <folly/container/Array.h>
#include <folly/portability/GTest.h>
#include <thrift/lib/cpp2/BadFieldAccess.h>
#include <thrift/lib/cpp2/protocol/Serializer.h>
#include <thrift/test/lazy_deserialization/gen-cpp2/simple_types.h>
#include <thrift/test/lazy_deserialization/gen-cpp2/terse_writes_types.h>
constexpr int kIterationCount = folly::kIsDebug ? 50'000 : 500'000;
constexpr int kListMaxSize = 10;
namespace apache::thrift::test {
std::mt19937 rng;
std::vector<int32_t> randomField() {
std::vector<int32_t> ret(rng() % kListMaxSize);
std::generate(ret.begin(), ret.end(), std::ref(rng));
return ret;
}
template <class Serializer, class Struct>
std::string randomSerializedStruct() {
Struct s;
s.field4_ref() = randomField();
return Serializer::template serialize<std::string>(s);
}
template <class Struct, class LazyStruct>
void randomTestWithSeed(int seed) {
rng.seed(seed);
Struct foo;
LazyStruct lazyFoo;
constexpr bool kIsOptional = folly::detail::is_instantiation_of_v<
optional_field_ref,
std::remove_reference_t<decltype(foo.field4_ref())>>;
auto create = [](const std::vector<int32_t>& field4) {
std::pair<Struct, LazyStruct> ret;
ret.first.field4_ref() = field4;
ret.second.field4_ref() = field4;
return ret;
};
for (int i = 0; i < kIterationCount; i++) {
auto arg = randomField();
std::vector<std::function<void()>> methods = {
[&] {
EXPECT_EQ(
foo.field4_ref().has_value(), lazyFoo.field4_ref().has_value());
},
[&] {
EXPECT_EQ(
foo.field4_ref().emplace(arg), lazyFoo.field4_ref().emplace(arg));
},
[&] { foo.field4_ref() = arg, lazyFoo.field4_ref() = arg; },
[&] {
if (foo.field4_ref().has_value() || !kIsOptional) {
EXPECT_EQ(foo.field4_ref().value(), lazyFoo.field4_ref().value());
} else {
EXPECT_THROW(foo.field4_ref().value(), bad_field_access);
EXPECT_THROW(lazyFoo.field4_ref().value(), bad_field_access);
}
},
[&] {
if (foo.field4_ref().has_value() || !kIsOptional) {
EXPECT_EQ(*foo.field4_ref(), *lazyFoo.field4_ref());
} else {
EXPECT_THROW(*foo.field4_ref(), bad_field_access);
EXPECT_THROW(*lazyFoo.field4_ref(), bad_field_access);
}
},
[&] { EXPECT_EQ(foo.field4_ref(), lazyFoo.field4_ref()); },
[&] {
auto [foo2, lazyFoo2] = create(arg);
EXPECT_EQ(foo < foo2, lazyFoo < lazyFoo2);
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
EXPECT_EQ(foo > foo2, lazyFoo > lazyFoo2);
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
EXPECT_EQ(foo <= foo2, lazyFoo <= lazyFoo2);
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
EXPECT_EQ(foo >= foo2, lazyFoo >= lazyFoo2);
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
EXPECT_EQ(foo == foo2, lazyFoo == lazyFoo2);
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
EXPECT_EQ(foo != foo2, lazyFoo != lazyFoo2);
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
foo = foo2;
lazyFoo = lazyFoo2;
EXPECT_EQ(foo, foo2);
EXPECT_EQ(lazyFoo, lazyFoo2);
EXPECT_EQ(foo.field4_ref(), lazyFoo.field4_ref());
EXPECT_EQ(foo2.field4_ref(), lazyFoo2.field4_ref());
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
foo2 = foo;
lazyFoo2 = lazyFoo;
EXPECT_EQ(foo, foo2);
EXPECT_EQ(lazyFoo, lazyFoo2);
EXPECT_EQ(foo.field4_ref(), lazyFoo.field4_ref());
EXPECT_EQ(foo2.field4_ref(), lazyFoo2.field4_ref());
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
foo = std::move(foo2);
lazyFoo = std::move(lazyFoo2);
EXPECT_EQ(foo.field4_ref(), lazyFoo.field4_ref());
EXPECT_EQ(foo2.field4_ref(), lazyFoo2.field4_ref());
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
foo2 = std::move(foo);
lazyFoo2 = std::move(lazyFoo);
EXPECT_EQ(foo.field4_ref(), lazyFoo.field4_ref());
EXPECT_EQ(foo2.field4_ref(), lazyFoo2.field4_ref());
},
[&] {
auto foo2 = foo;
auto lazyFoo2 = lazyFoo;
EXPECT_EQ(foo, foo2);
EXPECT_EQ(lazyFoo, lazyFoo2);
EXPECT_EQ(foo.field4_ref(), lazyFoo.field4_ref());
EXPECT_EQ(foo2.field4_ref(), lazyFoo2.field4_ref());
},
[&] {
auto foo2 = std::move(foo);
auto lazyFoo2 = std::move(lazyFoo);
EXPECT_EQ(foo.field4_ref(), lazyFoo.field4_ref());
EXPECT_EQ(foo2.field4_ref(), lazyFoo2.field4_ref());
},
};
if constexpr (kIsOptional) {
methods.push_back([&] {
EXPECT_EQ(bool(foo.field4_ref()), bool(lazyFoo.field4_ref()));
});
methods.push_back([&] {
EXPECT_EQ(
foo.field4_ref().value_or(arg), lazyFoo.field4_ref().value_or(arg));
});
methods.push_back([&] {
foo.field4_ref().reset();
lazyFoo.field4_ref().reset();
EXPECT_FALSE(foo.field4_ref().has_value());
EXPECT_FALSE(lazyFoo.field4_ref().has_value());
});
}
auto addSerializationMethods = [&](auto ser) {
using Serializer = decltype(ser);
methods.push_back([&] {
auto s = randomSerializedStruct<Serializer, Struct>();
Serializer::deserialize(s, foo);
Serializer::deserialize(s, lazyFoo);
});
methods.push_back([&] {
auto s = randomSerializedStruct<Serializer, LazyStruct>();
Serializer::deserialize(s, foo);
Serializer::deserialize(s, lazyFoo);
});
methods.push_back([&] {
auto s = randomSerializedStruct<Serializer, Struct>();
foo = Serializer::template deserialize<Struct>(s);
lazyFoo = Serializer::template deserialize<LazyStruct>(s);
});
methods.push_back([&] {
auto s = randomSerializedStruct<Serializer, LazyStruct>();
foo = Serializer::template deserialize<Struct>(s);
lazyFoo = Serializer::template deserialize<LazyStruct>(s);
});
methods.push_back([&] {
foo = Serializer::template deserialize<Struct>(
Serializer::template serialize<std::string>(foo));
lazyFoo = Serializer::template deserialize<LazyStruct>(
Serializer::template serialize<std::string>(lazyFoo));
});
};
addSerializationMethods(CompactSerializer{});
addSerializationMethods(BinarySerializer{});
// Choose a random method and call it
methods[rng() % methods.size()]();
}
}
class RandomTestWithSeed : public testing::TestWithParam<int> {};
TEST_P(RandomTestWithSeed, test) {
randomTestWithSeed<Foo, LazyFoo>(GetParam());
randomTestWithSeed<OptionalFoo, OptionalLazyFoo>(GetParam());
randomTestWithSeed<TerseFoo, TerseLazyFoo>(GetParam());
randomTestWithSeed<TerseOptionalFoo, TerseOptionalLazyFoo>(GetParam());
}
INSTANTIATE_TEST_CASE_P(
RandomTest,
RandomTestWithSeed,
testing::Range(0, folly::kIsDebug ? 10 : 1000));
} // namespace apache::thrift::test
<commit_msg>fix issue in unit-test that we use moved-from object<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <random>
#include <folly/Traits.h>
#include <folly/container/Array.h>
#include <folly/portability/GTest.h>
#include <thrift/lib/cpp2/BadFieldAccess.h>
#include <thrift/lib/cpp2/protocol/Serializer.h>
#include <thrift/test/lazy_deserialization/gen-cpp2/simple_types.h>
#include <thrift/test/lazy_deserialization/gen-cpp2/terse_writes_types.h>
constexpr int kIterationCount = folly::kIsDebug ? 50'000 : 500'000;
constexpr int kListMaxSize = 10;
namespace apache::thrift::test {
std::mt19937 rng;
std::vector<int32_t> randomField() {
std::vector<int32_t> ret(rng() % kListMaxSize);
std::generate(ret.begin(), ret.end(), std::ref(rng));
return ret;
}
template <class Serializer, class Struct>
std::string randomSerializedStruct() {
Struct s;
s.field4_ref() = randomField();
return Serializer::template serialize<std::string>(s);
}
template <class Struct, class LazyStruct>
void randomTestWithSeed(int seed) {
rng.seed(seed);
Struct foo;
LazyStruct lazyFoo;
constexpr bool kIsOptional = folly::detail::is_instantiation_of_v<
optional_field_ref,
std::remove_reference_t<decltype(foo.field4_ref())>>;
auto create = [](const std::vector<int32_t>& field4) {
std::pair<Struct, LazyStruct> ret;
ret.first.field4_ref() = field4;
ret.second.field4_ref() = field4;
return ret;
};
for (int i = 0; i < kIterationCount; i++) {
auto arg = randomField();
std::vector<std::function<void()>> methods = {
[&] {
EXPECT_EQ(
foo.field4_ref().has_value(), lazyFoo.field4_ref().has_value());
},
[&] {
EXPECT_EQ(
foo.field4_ref().emplace(arg), lazyFoo.field4_ref().emplace(arg));
},
[&] { foo.field4_ref() = arg, lazyFoo.field4_ref() = arg; },
[&] {
if (foo.field4_ref().has_value() || !kIsOptional) {
EXPECT_EQ(foo.field4_ref().value(), lazyFoo.field4_ref().value());
} else {
EXPECT_THROW(foo.field4_ref().value(), bad_field_access);
EXPECT_THROW(lazyFoo.field4_ref().value(), bad_field_access);
}
},
[&] {
if (foo.field4_ref().has_value() || !kIsOptional) {
EXPECT_EQ(*foo.field4_ref(), *lazyFoo.field4_ref());
} else {
EXPECT_THROW(*foo.field4_ref(), bad_field_access);
EXPECT_THROW(*lazyFoo.field4_ref(), bad_field_access);
}
},
[&] { EXPECT_EQ(foo.field4_ref(), lazyFoo.field4_ref()); },
[&] {
auto [foo2, lazyFoo2] = create(arg);
EXPECT_EQ(foo < foo2, lazyFoo < lazyFoo2);
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
EXPECT_EQ(foo > foo2, lazyFoo > lazyFoo2);
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
EXPECT_EQ(foo <= foo2, lazyFoo <= lazyFoo2);
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
EXPECT_EQ(foo >= foo2, lazyFoo >= lazyFoo2);
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
EXPECT_EQ(foo == foo2, lazyFoo == lazyFoo2);
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
EXPECT_EQ(foo != foo2, lazyFoo != lazyFoo2);
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
foo = foo2;
lazyFoo = lazyFoo2;
EXPECT_EQ(foo, foo2);
EXPECT_EQ(lazyFoo, lazyFoo2);
EXPECT_EQ(foo.field4_ref(), lazyFoo.field4_ref());
EXPECT_EQ(foo2.field4_ref(), lazyFoo2.field4_ref());
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
foo2 = foo;
lazyFoo2 = lazyFoo;
EXPECT_EQ(foo, foo2);
EXPECT_EQ(lazyFoo, lazyFoo2);
EXPECT_EQ(foo.field4_ref(), lazyFoo.field4_ref());
EXPECT_EQ(foo2.field4_ref(), lazyFoo2.field4_ref());
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
foo = std::move(foo2);
lazyFoo = std::move(lazyFoo2);
EXPECT_EQ(foo.field4_ref(), lazyFoo.field4_ref());
},
[&] {
auto [foo2, lazyFoo2] = create(arg);
foo2 = std::move(foo);
lazyFoo2 = std::move(lazyFoo);
EXPECT_EQ(foo2.field4_ref(), lazyFoo2.field4_ref());
// Put `foo` and `lazyFoo` back to original state
foo = std::move(foo2);
lazyFoo = std::move(lazyFoo2);
},
[&] {
auto foo2 = foo;
auto lazyFoo2 = lazyFoo;
EXPECT_EQ(foo, foo2);
EXPECT_EQ(lazyFoo, lazyFoo2);
EXPECT_EQ(foo.field4_ref(), lazyFoo.field4_ref());
EXPECT_EQ(foo2.field4_ref(), lazyFoo2.field4_ref());
},
[&] {
auto foo2 = std::move(foo);
auto lazyFoo2 = std::move(lazyFoo);
EXPECT_EQ(foo2.field4_ref(), lazyFoo2.field4_ref());
// Put `foo` and `lazyFoo` back to original state
foo = std::move(foo2);
lazyFoo = std::move(lazyFoo2);
},
};
if constexpr (kIsOptional) {
methods.push_back([&] {
EXPECT_EQ(bool(foo.field4_ref()), bool(lazyFoo.field4_ref()));
});
methods.push_back([&] {
EXPECT_EQ(
foo.field4_ref().value_or(arg), lazyFoo.field4_ref().value_or(arg));
});
methods.push_back([&] {
foo.field4_ref().reset();
lazyFoo.field4_ref().reset();
EXPECT_FALSE(foo.field4_ref().has_value());
EXPECT_FALSE(lazyFoo.field4_ref().has_value());
});
}
auto addSerializationMethods = [&](auto ser) {
using Serializer = decltype(ser);
methods.push_back([&] {
auto s = randomSerializedStruct<Serializer, Struct>();
Serializer::deserialize(s, foo);
Serializer::deserialize(s, lazyFoo);
});
methods.push_back([&] {
auto s = randomSerializedStruct<Serializer, LazyStruct>();
Serializer::deserialize(s, foo);
Serializer::deserialize(s, lazyFoo);
});
methods.push_back([&] {
auto s = randomSerializedStruct<Serializer, Struct>();
foo = Serializer::template deserialize<Struct>(s);
lazyFoo = Serializer::template deserialize<LazyStruct>(s);
});
methods.push_back([&] {
auto s = randomSerializedStruct<Serializer, LazyStruct>();
foo = Serializer::template deserialize<Struct>(s);
lazyFoo = Serializer::template deserialize<LazyStruct>(s);
});
methods.push_back([&] {
foo = Serializer::template deserialize<Struct>(
Serializer::template serialize<std::string>(foo));
lazyFoo = Serializer::template deserialize<LazyStruct>(
Serializer::template serialize<std::string>(lazyFoo));
});
};
addSerializationMethods(CompactSerializer{});
addSerializationMethods(BinarySerializer{});
// Choose a random method and call it
methods[rng() % methods.size()]();
}
}
class RandomTestWithSeed : public testing::TestWithParam<int> {};
TEST_P(RandomTestWithSeed, test) {
randomTestWithSeed<Foo, LazyFoo>(GetParam());
randomTestWithSeed<OptionalFoo, OptionalLazyFoo>(GetParam());
randomTestWithSeed<TerseFoo, TerseLazyFoo>(GetParam());
randomTestWithSeed<TerseOptionalFoo, TerseOptionalLazyFoo>(GetParam());
}
INSTANTIATE_TEST_CASE_P(
RandomTest,
RandomTestWithSeed,
testing::Range(0, folly::kIsDebug ? 10 : 1000));
} // namespace apache::thrift::test
<|endoftext|> |
<commit_before>/* unzipcomp.cpp
Copyright (C) 2003 Tommi Mäkitalo
This file is part of tntnet.
Tntnet 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.
Tntnet 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 tntnet; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
#include "unzip.h"
#include <tnt/component.h>
#include <tnt/http.h>
#include <fstream>
#include <cxxtools/thread.h>
#include "unzip_pp.h"
namespace tnt
{
class urlmapper;
class comploader;
}
static Mutex mutex;
static tnt::component* theComponent = 0;
static unsigned refs = 0;
////////////////////////////////////////////////////////////////////////
// prototypes for external functions
//
extern "C"
{
tnt::component* create_unzip(const tnt::compident& ci,
const tnt::urlmapper& um, tnt::comploader& cl);
}
////////////////////////////////////////////////////////////////////////
// componentdeclaration
//
class unzipcomp : public tnt::component
{
static std::string document_root;
protected:
virtual ~unzipcomp() { };
public:
virtual unsigned operator() (tnt::httpRequest& request,
tnt::httpReply& reply, query_params& qparam);
virtual bool drop();
};
////////////////////////////////////////////////////////////////////////
// external functions
//
tnt::component* create_unzip(const tnt::compident& ci,
const tnt::urlmapper& um, tnt::comploader& cl)
{
MutexLock lock(mutex);
if (theComponent == 0)
{
theComponent = new unzipcomp();
refs = 1;
}
else
++refs;
return theComponent;
}
////////////////////////////////////////////////////////////////////////
// componentdefinition
//
unsigned unzipcomp::operator() (tnt::httpRequest& request,
tnt::httpReply& reply, query_params& qparams)
{
std::string pi = request.getPathInfo();
if (request.getArgsCount() < 1)
reply.throwError(HTTP_INTERNAL_SERVER_ERROR, "missing archive name");
unzipFile f(request.getArg(0));
unzipFileStream in(f, pi, false);
// set Content-Type
if (request.getArgs().size() > 1)
reply.setContentType(request.getArg(1));
std::copy(std::istreambuf_iterator<char>(in),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(reply.out()));
return HTTP_OK;
}
bool unzipcomp::drop()
{
MutexLock lock(mutex);
if (--refs == 0)
{
delete this;
theComponent = 0;
return true;
}
else
return false;
}
<commit_msg>leerer Mime-type-Parameter wird ignoriert<commit_after>/* unzipcomp.cpp
Copyright (C) 2003 Tommi Mäkitalo
This file is part of tntnet.
Tntnet 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.
Tntnet 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 tntnet; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
#include "unzip.h"
#include <tnt/component.h>
#include <tnt/http.h>
#include <fstream>
#include <cxxtools/thread.h>
#include "unzip_pp.h"
namespace tnt
{
class urlmapper;
class comploader;
}
static Mutex mutex;
static tnt::component* theComponent = 0;
static unsigned refs = 0;
////////////////////////////////////////////////////////////////////////
// prototypes for external functions
//
extern "C"
{
tnt::component* create_unzip(const tnt::compident& ci,
const tnt::urlmapper& um, tnt::comploader& cl);
}
////////////////////////////////////////////////////////////////////////
// componentdeclaration
//
class unzipcomp : public tnt::component
{
static std::string document_root;
protected:
virtual ~unzipcomp() { };
public:
virtual unsigned operator() (tnt::httpRequest& request,
tnt::httpReply& reply, query_params& qparam);
virtual bool drop();
};
////////////////////////////////////////////////////////////////////////
// external functions
//
tnt::component* create_unzip(const tnt::compident& ci,
const tnt::urlmapper& um, tnt::comploader& cl)
{
MutexLock lock(mutex);
if (theComponent == 0)
{
theComponent = new unzipcomp();
refs = 1;
}
else
++refs;
return theComponent;
}
////////////////////////////////////////////////////////////////////////
// componentdefinition
//
unsigned unzipcomp::operator() (tnt::httpRequest& request,
tnt::httpReply& reply, query_params& qparams)
{
std::string pi = request.getPathInfo();
if (request.getArgsCount() < 1)
reply.throwError(HTTP_INTERNAL_SERVER_ERROR, "missing archive name");
unzipFile f(request.getArg(0));
unzipFileStream in(f, pi, false);
// set Content-Type
if (request.getArgs().size() > 1 && request.getArg(1).size() > 0)
reply.setContentType(request.getArg(1));
std::copy(std::istreambuf_iterator<char>(in),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(reply.out()));
return HTTP_OK;
}
bool unzipcomp::drop()
{
MutexLock lock(mutex);
if (--refs == 0)
{
delete this;
theComponent = 0;
return true;
}
else
return false;
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <iostream>
#include <limits>
#include <map>
#include <regex>
#include <string>
#include <vector>
#include <cmath>
// TODO: Replace this as soon as possible with a more modern option
// parser interface.
#include <getopt.h>
#include "distances/Wasserstein.hh"
#include "persistenceDiagrams/IO.hh"
#include "persistenceDiagrams/PersistenceDiagram.hh"
#include "persistenceDiagrams/PersistenceIndicatorFunction.hh"
#include "utilities/Filesystem.hh"
using DataType = double;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
using PersistenceIndicatorFunction = aleph::math::StepFunction<DataType>;
/*
Auxiliary structure for describing a data set. I need this in order to
figure out the corresponding dimension of the persistence diagram.
*/
struct DataSet
{
std::string name;
std::string filename;
unsigned dimension;
PersistenceDiagram persistenceDiagram;
PersistenceIndicatorFunction persistenceIndicatorFunction;
};
// Calculates the distance between two data sets. This requires enumerating all
// dimensions, and finding the corresponding persistence indicator function. If
// no such function exists, the function uses the norm of the function.
double distance( const std::vector<DataSet>& dataSet1, const std::vector<DataSet>& dataSet2, unsigned minDimension, unsigned maxDimension )
{
auto getPersistenceIndicatorFunction = [] ( const std::vector<DataSet>& dataSet, unsigned dimension )
{
auto it = std::find_if( dataSet.begin(), dataSet.end(),
[&dimension] ( const DataSet& dataSet )
{
return dataSet.dimension == dimension;
} );
if( it != dataSet.end() )
return PersistenceIndicatorFunction( it->persistenceIndicatorFunction );
else
return PersistenceIndicatorFunction();
};
double d = 0.0;
for( unsigned dimension = minDimension; dimension <= maxDimension; dimension++ )
{
auto f = getPersistenceIndicatorFunction( dataSet1, dimension );
auto g = getPersistenceIndicatorFunction( dataSet2, dimension );
g = g * (-1.0);
d = d + (f+g).integral();
}
return d;
}
double wassersteinDistance( const std::vector<DataSet>& dataSet1, const std::vector<DataSet>& dataSet2, unsigned minDimension, unsigned maxDimension, double power )
{
auto getPersistenceDiagram = [] ( const std::vector<DataSet>& dataSet, unsigned dimension )
{
auto it = std::find_if( dataSet.begin(), dataSet.end(),
[&dimension] ( const DataSet& dataSet )
{
return dataSet.dimension == dimension;
} );
if( it != dataSet.end() )
return PersistenceDiagram( it->persistenceDiagram );
else
return PersistenceDiagram();
};
double d = 0.0;
for( unsigned dimension = minDimension; dimension <= maxDimension; dimension++ )
{
auto D1 = getPersistenceDiagram( dataSet1, dimension );
auto D2 = getPersistenceDiagram( dataSet2, dimension );
d += aleph::distances::wassersteinDistance( D1, D2, power );
}
d = std::pow( d, 1.0 / d );
return d;
}
int main( int argc, char** argv )
{
static option commandLineOptions[] =
{
{ "power" , required_argument, nullptr, 'p' },
{ "wasserstein", no_argument , nullptr, 'w' },
{ nullptr , 0 , nullptr, 0 }
};
double power = 2.0;
bool useWassersteinDistance = false;
int option = 0;
while( ( option = getopt_long( argc, argv, "p:w", commandLineOptions, nullptr ) ) != -1 )
{
switch( option )
{
case 'p':
power = std::stod( optarg );
break;
case 'w':
useWassersteinDistance = true;
break;
default:
break;
}
}
if( ( argc - optind ) <= 1 )
{
// TODO: Show usage
return -1;
}
// Maps filenames to indices. I need this to ensure that the internal
// ordering of files coincides with the shell's ordering.
std::map<std::string, unsigned> filenameMap;
std::vector< std::vector<DataSet> > dataSets;
// TODO: Make this regular expression more, well, 'expressive' and
// support more methods of specifying a dimension.
std::regex reDataSetPrefix( "(.*)_k([[:digit:]]+)\\.txt" );
std::smatch matches;
// Get filenames & prefixes ------------------------------------------
unsigned minDimension = std::numeric_limits<unsigned>::max();
unsigned maxDimension = 0;
{
std::vector<std::string> filenames;
filenames.reserve( argc - 1 );
unsigned index = 0;
for( int i = optind; i < argc; i++ )
{
filenames.push_back( argv[i] );
if( std::regex_match( filenames.back(), matches, reDataSetPrefix ) )
{
auto name = matches[1];
if( filenameMap.find( name ) == filenameMap.end() )
filenameMap[ name ] = index++;
}
}
dataSets.resize( filenameMap.size() );
for( auto&& filename : filenames )
{
if( std::regex_match( filename, matches, reDataSetPrefix ) )
{
auto name = matches[1];
auto dimension = unsigned( std::stoul( matches[2] ) );
dataSets.at( filenameMap[name] ).push_back( { name, filename, dimension, {}, {} } );
minDimension = std::min( minDimension, dimension );
maxDimension = std::max( maxDimension, dimension );
}
}
}
// Load persistence diagrams & calculate indicator functions ---------
std::vector<PersistenceDiagram> persistenceDiagrams;
for( auto&& sets : dataSets )
{
for( auto&& dataSet : sets )
{
std::cerr << "* Processing '" << dataSet.filename << "'...";
dataSet.persistenceDiagram = aleph::load<DataType>( dataSet.filename );
// FIXME: This is only required in order to ensure that the
// persistence indicator function has a finite integral; it
// can be solved more elegantly by using a special value to
// indicate infinite intervals.
dataSet.persistenceDiagram.removeUnpaired();
dataSet.persistenceIndicatorFunction
= aleph::persistenceIndicatorFunction( dataSet.persistenceDiagram );
std::cerr << "finished\n";
}
}
// Calculate all distances -------------------------------------------
std::vector< std::vector<double> > distances;
distances.resize( dataSets.size(), std::vector<double>( dataSets.size() ) );
std::size_t row = 0;
for( auto it1 = dataSets.begin(); it1 != dataSets.end(); ++it1, ++row )
{
std::size_t col = 0;
for( auto it2 = std::next( it1 ); it2 != dataSets.end(); ++it2, ++col )
{
double d = 0.0;
if( useWassersteinDistance )
d = wassersteinDistance( *it1, *it2, minDimension, maxDimension, power );
else
d = distance( *it1, *it2, minDimension, maxDimension );
distances[row][col] = d;
distances[col][row] = d;
std::cerr << "D[" << row << "][" << col << "]: " << d << "\n";
}
}
}
<commit_msg>Implemented matrix storing<commit_after>#include <algorithm>
#include <iostream>
#include <limits>
#include <map>
#include <regex>
#include <string>
#include <vector>
#include <cmath>
// TODO: Replace this as soon as possible with a more modern option
// parser interface.
#include <getopt.h>
#include "distances/Wasserstein.hh"
#include "persistenceDiagrams/IO.hh"
#include "persistenceDiagrams/PersistenceDiagram.hh"
#include "persistenceDiagrams/PersistenceIndicatorFunction.hh"
#include "utilities/Filesystem.hh"
using DataType = double;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
using PersistenceIndicatorFunction = aleph::math::StepFunction<DataType>;
/*
Auxiliary structure for describing a data set. I need this in order to
figure out the corresponding dimension of the persistence diagram.
*/
struct DataSet
{
std::string name;
std::string filename;
unsigned dimension;
PersistenceDiagram persistenceDiagram;
PersistenceIndicatorFunction persistenceIndicatorFunction;
};
void storeMatrix( const std::vector< std::vector<double> >& M, std::ostream& out )
{
if( M.empty() )
return;
auto rows = M.size();
auto cols = M.front().size();
for( decltype(rows) row = 0; row < rows; row++ )
{
for( decltype(cols) col = 0; col < cols; col++ )
{
if( col != 0 )
out << " ";
out << M[row][col];
}
out << "\n";
}
}
// Calculates the distance between two data sets. This requires enumerating all
// dimensions, and finding the corresponding persistence indicator function. If
// no such function exists, the function uses the norm of the function.
double distance( const std::vector<DataSet>& dataSet1, const std::vector<DataSet>& dataSet2, unsigned minDimension, unsigned maxDimension )
{
auto getPersistenceIndicatorFunction = [] ( const std::vector<DataSet>& dataSet, unsigned dimension )
{
auto it = std::find_if( dataSet.begin(), dataSet.end(),
[&dimension] ( const DataSet& dataSet )
{
return dataSet.dimension == dimension;
} );
if( it != dataSet.end() )
return PersistenceIndicatorFunction( it->persistenceIndicatorFunction );
else
return PersistenceIndicatorFunction();
};
double d = 0.0;
for( unsigned dimension = minDimension; dimension <= maxDimension; dimension++ )
{
auto f = getPersistenceIndicatorFunction( dataSet1, dimension );
auto g = getPersistenceIndicatorFunction( dataSet2, dimension );
g = g * (-1.0);
d = d + (f+g).integral();
}
return d;
}
double wassersteinDistance( const std::vector<DataSet>& dataSet1, const std::vector<DataSet>& dataSet2, unsigned minDimension, unsigned maxDimension, double power )
{
auto getPersistenceDiagram = [] ( const std::vector<DataSet>& dataSet, unsigned dimension )
{
auto it = std::find_if( dataSet.begin(), dataSet.end(),
[&dimension] ( const DataSet& dataSet )
{
return dataSet.dimension == dimension;
} );
if( it != dataSet.end() )
return PersistenceDiagram( it->persistenceDiagram );
else
return PersistenceDiagram();
};
double d = 0.0;
for( unsigned dimension = minDimension; dimension <= maxDimension; dimension++ )
{
auto D1 = getPersistenceDiagram( dataSet1, dimension );
auto D2 = getPersistenceDiagram( dataSet2, dimension );
d += aleph::distances::wassersteinDistance( D1, D2, power );
}
d = std::pow( d, 1.0 / d );
return d;
}
int main( int argc, char** argv )
{
static option commandLineOptions[] =
{
{ "power" , required_argument, nullptr, 'p' },
{ "wasserstein", no_argument , nullptr, 'w' },
{ nullptr , 0 , nullptr, 0 }
};
double power = 2.0;
bool useWassersteinDistance = false;
int option = 0;
while( ( option = getopt_long( argc, argv, "p:w", commandLineOptions, nullptr ) ) != -1 )
{
switch( option )
{
case 'p':
power = std::stod( optarg );
break;
case 'w':
useWassersteinDistance = true;
break;
default:
break;
}
}
if( ( argc - optind ) <= 1 )
{
// TODO: Show usage
return -1;
}
// Maps filenames to indices. I need this to ensure that the internal
// ordering of files coincides with the shell's ordering.
std::map<std::string, unsigned> filenameMap;
std::vector< std::vector<DataSet> > dataSets;
// TODO: Make this regular expression more, well, 'expressive' and
// support more methods of specifying a dimension.
std::regex reDataSetPrefix( "(.*)_k([[:digit:]]+)\\.txt" );
std::smatch matches;
// Get filenames & prefixes ------------------------------------------
unsigned minDimension = std::numeric_limits<unsigned>::max();
unsigned maxDimension = 0;
{
std::vector<std::string> filenames;
filenames.reserve( argc - 1 );
unsigned index = 0;
for( int i = optind; i < argc; i++ )
{
filenames.push_back( argv[i] );
if( std::regex_match( filenames.back(), matches, reDataSetPrefix ) )
{
auto name = matches[1];
if( filenameMap.find( name ) == filenameMap.end() )
filenameMap[ name ] = index++;
}
}
dataSets.resize( filenameMap.size() );
for( auto&& filename : filenames )
{
if( std::regex_match( filename, matches, reDataSetPrefix ) )
{
auto name = matches[1];
auto dimension = unsigned( std::stoul( matches[2] ) );
dataSets.at( filenameMap[name] ).push_back( { name, filename, dimension, {}, {} } );
minDimension = std::min( minDimension, dimension );
maxDimension = std::max( maxDimension, dimension );
}
}
}
// Load persistence diagrams & calculate indicator functions ---------
std::vector<PersistenceDiagram> persistenceDiagrams;
for( auto&& sets : dataSets )
{
for( auto&& dataSet : sets )
{
std::cerr << "* Processing '" << dataSet.filename << "'...";
dataSet.persistenceDiagram = aleph::load<DataType>( dataSet.filename );
// FIXME: This is only required in order to ensure that the
// persistence indicator function has a finite integral; it
// can be solved more elegantly by using a special value to
// indicate infinite intervals.
dataSet.persistenceDiagram.removeUnpaired();
dataSet.persistenceIndicatorFunction
= aleph::persistenceIndicatorFunction( dataSet.persistenceDiagram );
std::cerr << "finished\n";
}
}
// Calculate all distances -------------------------------------------
std::vector< std::vector<double> > distances;
distances.resize( dataSets.size(), std::vector<double>( dataSets.size() ) );
std::size_t row = 0;
for( auto it1 = dataSets.begin(); it1 != dataSets.end(); ++it1, ++row )
{
std::size_t col = 0;
for( auto it2 = std::next( it1 ); it2 != dataSets.end(); ++it2, ++col )
{
double d = 0.0;
if( useWassersteinDistance )
d = wassersteinDistance( *it1, *it2, minDimension, maxDimension, power );
else
d = distance( *it1, *it2, minDimension, maxDimension );
distances[row][col] = d;
distances[col][row] = d;
}
}
std::cerr << "Storing matrix...";
storeMatrix( distances, std::cout );
std::cerr << "finished\n";
}
<|endoftext|> |
<commit_before><commit_msg>cleanup of debug cruft<commit_after><|endoftext|> |
<commit_before>/**
** \file libport/path.cc
** \brief path: implements file libport/path.hh
*/
#include <iostream>
#include <sys/stat.h>
#include <cctype>
#include <libport/contract.hh>
#include <libport/finally.hh>
#include <libport/path.hh>
// Implementation detail: if path_ is empty and absolute_ is false,
// then the path is '.'
namespace libport
{
path::path (const std::string& p)
{
init (p);
}
path::path (const char* p)
{
init (p);
}
void
path::test_absolute (std::string& p)
{
absolute_ = false;
#if defined WIN32
// Under Win32, absolute paths start with a letter followed by
// ':\'
absolute_ = p.length() >= 3;
absolute_ = absolute_ && isalpha(p[0]);
absolute_ = absolute_ && (p[1] == ':');
absolute_ = absolute_ && (p[2] == '\\');
if (absolute_)
{
volume_ = p[0];
p = p.erase(0, 2);
}
#endif
// Under unix, absolute paths start with a slash
if (!absolute_)
{
absolute_ = (p.length() > 0) && (p[0] == '/');
if (absolute_)
p = p.erase(0, 0);
}
}
void
path::init (std::string p)
{
if (p.empty())
throw invalid_path("Path can't be empty.");
test_absolute(p);
// Cut directories on / and \.
std::string::size_type pos_s = p.find('/');
std::string::size_type pos_b = p.find('\\');
for (;
pos_s != std::string::npos || pos_b != std::string::npos;
pos_s = p.find('/'), pos_b = p.find('\\'))
{
std::string::size_type pos =
pos_s == std::string::npos ? pos_b :
pos_b == std::string::npos ? pos_s :
std::min(pos_s, pos_b);
std::string dir;
dir = p.substr (0, pos);
p.erase (0, pos + 1);
this->append_dir (dir);
}
this->append_dir (p);
}
path&
path::operator= (const path& rhs)
{
absolute_ = rhs.absolute_;
path_ = rhs.path_;
#if WIN32
volume_ = rhs.volume_;
#endif
return *this;
}
path&
path::operator/= (const path& rhs)
{
if (rhs.absolute_get())
throw invalid_path(
"Rhs of concatenation is absolute: " + rhs.to_string());
for (path_type::const_iterator dir = rhs.path_.begin ();
dir != rhs.path_.end ();
++dir)
{
this->append_dir (*dir);
}
return *this;
}
path
path::operator/ (const std::string& rhs) const
{
path ret = *this;
return ret /= rhs;
}
path::operator std::string () const
{
return to_string();
}
std::string
path::to_string () const
{
std::string path_str;
char separator = separator_;
if (absolute_)
{
#ifdef WIN32
if (volume_ != "")
{
path_str = volume_ + ":\\" + path_str;
separator = '\\';
}
else
#endif
{
path_str = "/" + path_str;
separator = '/';
}
}
else if (path_.empty())
return ".";
bool first = true;
for (path_type::const_iterator dir = path_.begin ();
dir != path_.end ();
++dir)
{
if (first)
first = false;
else
path_str += separator;
path_str += *dir;
}
return path_str;
}
bool
path::operator== (const path& rhs) const
{
return path_ == rhs.path_;
}
std::ostream&
path::dump (std::ostream& ostr) const
{
ostr << this->operator std::string ();
return ostr;
}
void
path::append_dir (const std::string& dir)
{
precondition(dir.find (separator_) == std::string::npos);
if (dir != "" && dir != ".")
{
if (dir == "..")
{
if (path_.empty () || *path_.rbegin () == "..")
path_.push_back ("..");
else
path_.pop_back ();
}
else
{
path_.push_back (dir);
}
}
}
std::string
path::basename () const
{
// basename of / is /, basename of . is .
if (path_.empty())
return *this;
return path_.back();
}
path
path::dirname () const
{
// dirname of / is /, dirname of . is .
if (path_.empty())
return *this;
std::string last = path_.back();
// The const cast here is justified since the modification is
// systematically reverted
const_cast<path*>(this)->path_.pop_back();
libport::Finally finally(
boost::bind(&path_type::push_back,
boost::ref(const_cast<path*>(this)->path_), last));
path res = path_.empty() ? "." : *this;
return res;
}
bool path::exists () const
{
struct stat buf;
return 0 == stat (to_string().c_str(), &buf);
}
}
<commit_msg>Better detection of windows case in path.cc.<commit_after>/**
** \file libport/path.cc
** \brief path: implements file libport/path.hh
*/
#include <iostream>
#include <sys/stat.h>
#include <cctype>
#include <libport/detect-win32.h>
#include <libport/contract.hh>
#include <libport/finally.hh>
#include <libport/path.hh>
// Implementation detail: if path_ is empty and absolute_ is false,
// then the path is '.'
namespace libport
{
path::path (const std::string& p)
{
init (p);
}
path::path (const char* p)
{
init (p);
}
void
path::test_absolute (std::string& p)
{
absolute_ = false;
#if defined WIN32
// Under Win32, absolute paths start with a letter followed by
// ':\'
absolute_ = p.length() >= 3;
absolute_ = absolute_ && isalpha(p[0]);
absolute_ = absolute_ && (p[1] == ':');
absolute_ = absolute_ && (p[2] == '\\');
if (absolute_)
{
volume_ = p[0];
p = p.erase(0, 2);
}
#endif
// Under unix, absolute paths start with a slash
if (!absolute_)
{
absolute_ = (p.length() > 0) && (p[0] == '/');
if (absolute_)
p = p.erase(0, 0);
}
}
void
path::init (std::string p)
{
if (p.empty())
throw invalid_path("Path can't be empty.");
test_absolute(p);
// Cut directories on / and \.
std::string::size_type pos_s = p.find('/');
std::string::size_type pos_b = p.find('\\');
for (;
pos_s != std::string::npos || pos_b != std::string::npos;
pos_s = p.find('/'), pos_b = p.find('\\'))
{
std::string::size_type pos =
pos_s == std::string::npos ? pos_b :
pos_b == std::string::npos ? pos_s :
std::min(pos_s, pos_b);
std::string dir;
dir = p.substr (0, pos);
p.erase (0, pos + 1);
this->append_dir (dir);
}
this->append_dir (p);
}
path&
path::operator= (const path& rhs)
{
absolute_ = rhs.absolute_;
path_ = rhs.path_;
#if defined WIN32
volume_ = rhs.volume_;
#endif
return *this;
}
path&
path::operator/= (const path& rhs)
{
if (rhs.absolute_get())
throw invalid_path(
"Rhs of concatenation is absolute: " + rhs.to_string());
for (path_type::const_iterator dir = rhs.path_.begin ();
dir != rhs.path_.end ();
++dir)
{
this->append_dir (*dir);
}
return *this;
}
path
path::operator/ (const std::string& rhs) const
{
path ret = *this;
return ret /= rhs;
}
path::operator std::string () const
{
return to_string();
}
std::string
path::to_string () const
{
std::string path_str;
char separator = separator_;
if (absolute_)
{
#ifdef WIN32
if (volume_ != "")
{
path_str = volume_ + ":\\" + path_str;
separator = '\\';
}
else
#endif
{
path_str = "/" + path_str;
separator = '/';
}
}
else if (path_.empty())
return ".";
bool first = true;
for (path_type::const_iterator dir = path_.begin ();
dir != path_.end ();
++dir)
{
if (first)
first = false;
else
path_str += separator;
path_str += *dir;
}
return path_str;
}
bool
path::operator== (const path& rhs) const
{
return path_ == rhs.path_;
}
std::ostream&
path::dump (std::ostream& ostr) const
{
ostr << this->operator std::string ();
return ostr;
}
void
path::append_dir (const std::string& dir)
{
precondition(dir.find (separator_) == std::string::npos);
if (dir != "" && dir != ".")
{
if (dir == "..")
{
if (path_.empty () || *path_.rbegin () == "..")
path_.push_back ("..");
else
path_.pop_back ();
}
else
{
path_.push_back (dir);
}
}
}
std::string
path::basename () const
{
// basename of / is /, basename of . is .
if (path_.empty())
return *this;
return path_.back();
}
path
path::dirname () const
{
// dirname of / is /, dirname of . is .
if (path_.empty())
return *this;
std::string last = path_.back();
// The const cast here is justified since the modification is
// systematically reverted
const_cast<path*>(this)->path_.pop_back();
libport::Finally finally(
boost::bind(&path_type::push_back,
boost::ref(const_cast<path*>(this)->path_), last));
path res = path_.empty() ? "." : *this;
return res;
}
bool path::exists () const
{
struct stat buf;
return 0 == stat (to_string().c_str(), &buf);
}
}
<|endoftext|> |
<commit_before>// Copyright (C) 2016 Jrme Leclercq, Arnaud Cadot
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/LuaBinding.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
/*!
* \brief Binds SDK module to Lua
*/
void LuaBinding::BindSDK()
{
/*********************************** Ndk::Application **********************************/
#ifndef NDK_SERVER
//application.SetMethod("AddWindow", &Application::AddWindow);
#endif
application.BindMethod("AddWorld", [] (Nz::LuaInstance& instance, Application* application) -> int
{
instance.Push(application->AddWorld().CreateHandle());
return 1;
});
application.BindMethod("GetUpdateTime", &Application::GetUpdateTime);
application.BindMethod("Quit", &Application::Quit);
/*********************************** Ndk::Console **********************************/
#ifndef NDK_SERVER
consoleClass.Inherit<Nz::Node>(nodeClass, [] (ConsoleHandle* handle) -> Nz::Node*
{
return handle->GetObject();
});
consoleClass.BindMethod("AddLine", &Console::AddLine, Nz::Color::White);
consoleClass.BindMethod("Clear", &Console::Clear);
consoleClass.BindMethod("GetCharacterSize", &Console::GetCharacterSize);
consoleClass.BindMethod("GetHistory", &Console::GetHistory);
consoleClass.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground);
consoleClass.BindMethod("GetInput", &Console::GetInput);
consoleClass.BindMethod("GetInputBackground", &Console::GetInputBackground);
consoleClass.BindMethod("GetSize", &Console::GetSize);
consoleClass.BindMethod("GetTextFont", &Console::GetTextFont);
consoleClass.BindMethod("IsVisible", &Console::IsVisible);
consoleClass.BindMethod("SendCharacter", &Console::SendCharacter);
//consoleClass.SetMethod("SendEvent", &Console::SendEvent);
consoleClass.BindMethod("SetCharacterSize", &Console::SetCharacterSize);
consoleClass.BindMethod("SetSize", &Console::SetSize);
consoleClass.BindMethod("SetTextFont", &Console::SetTextFont);
consoleClass.BindMethod("Show", &Console::Show, true);
#endif
/*********************************** Ndk::Entity **********************************/
entityClass.BindMethod("Enable", &Entity::Enable);
entityClass.BindMethod("GetId", &Entity::GetId);
entityClass.BindMethod("GetWorld", &Entity::GetWorld);
entityClass.BindMethod("Kill", &Entity::Kill);
entityClass.BindMethod("IsEnabled", &Entity::IsEnabled);
entityClass.BindMethod("IsValid", &Entity::IsValid);
entityClass.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents);
entityClass.BindMethod("__tostring", &EntityHandle::ToString);
entityClass.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int
{
ComponentBinding* binding = QueryComponentIndex(instance);
return binding->adder(instance, handle);
});
entityClass.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int
{
ComponentBinding* binding = QueryComponentIndex(instance);
return binding->getter(instance, handle->GetComponent(binding->index));
});
entityClass.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int
{
ComponentBinding* binding = QueryComponentIndex(instance);
handle->RemoveComponent(binding->index);
return 0;
});
/*********************************** Ndk::NodeComponent **********************************/
nodeComponent.Inherit<Nz::Node>(nodeClass, [] (NodeComponentHandle* handle) -> Nz::Node*
{
return handle->GetObject();
});
/*********************************** Ndk::VelocityComponent **********************************/
velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)
{
std::size_t length;
const char* member = lua.CheckString(1, &length);
if (std::strcmp(member, "Linear") == 0)
{
lua.Push(instance->linearVelocity);
return true;
}
return false;
});
velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)
{
std::size_t length;
const char* member = lua.CheckString(1, &length);
int argIndex = 2;
if (std::strcmp(member, "Linear") == 0)
{
instance->linearVelocity = lua.Check<Nz::Vector3f>(&argIndex);
return true;
}
return false;
});
/*********************************** Ndk::World **********************************/
worldClass.BindMethod("CreateEntity", &World::CreateEntity);
worldClass.BindMethod("CreateEntities", &World::CreateEntities);
worldClass.BindMethod("Clear", &World::Clear);
#ifndef NDK_SERVER
/*********************************** Ndk::GraphicsComponent **********************************/
graphicsComponent.BindMethod("Attach", &GraphicsComponent::Attach, 0);
#endif
// Components functions
m_componentBinding.resize(BaseComponent::GetMaxComponentIndex());
BindComponent<NodeComponent>("Node");
BindComponent<VelocityComponent>("Velocity");
#ifndef NDK_SERVER
BindComponent<GraphicsComponent>("Graphics");
#endif
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the SDK classes
*/
void LuaBinding::RegisterSDK(Nz::LuaInstance& instance)
{
// Classes
application.Register(instance);
entityClass.Register(instance);
nodeComponent.Register(instance);
velocityComponent.Register(instance);
worldClass.Register(instance);
#ifndef NDK_SERVER
consoleClass.Register(instance);
graphicsComponent.Register(instance);
#endif
// Enums
// ComponentType (fake enumeration to expose component indexes)
instance.PushTable(0, m_componentBinding.size());
{
for (const ComponentBinding& entry : m_componentBinding)
{
if (entry.name.IsEmpty())
continue;
instance.PushField(entry.name, entry.index);
}
}
instance.SetGlobal("ComponentType");
}
/*!
* \brief Gets the index of the component
* \return A pointer to the binding linked to a component
*
* \param instance Lua instance that will interact with the component
* \param argIndex Index of the component
*/
LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex)
{
switch (instance.GetType(argIndex))
{
case Nz::LuaType_Number:
{
ComponentIndex componentIndex = instance.Check<ComponentIndex>(&argIndex);
if (componentIndex > m_componentBinding.size())
{
instance.Error("Invalid component index");
return nullptr;
}
ComponentBinding& binding = m_componentBinding[componentIndex];
if (binding.name.IsEmpty())
{
instance.Error("Invalid component index");
return nullptr;
}
return &binding;
}
case Nz::LuaType_String:
{
const char* key = instance.CheckString(argIndex);
auto it = m_componentBindingByName.find(key);
if (it == m_componentBindingByName.end())
{
instance.Error("Invalid component name");
return nullptr;
}
return &m_componentBinding[it->second];
}
}
instance.Error("Invalid component index at #" + Nz::String::Number(argIndex));
return nullptr;
}
}
<commit_msg>Sdk/Binding: Fix Entity::Enable default argument<commit_after>// Copyright (C) 2016 Jrme Leclercq, Arnaud Cadot
// This file is part of the "Nazara Development Kit"
// For conditions of distribution and use, see copyright notice in Prerequesites.hpp
#include <NDK/LuaBinding.hpp>
#include <NDK/LuaAPI.hpp>
namespace Ndk
{
/*!
* \brief Binds SDK module to Lua
*/
void LuaBinding::BindSDK()
{
/*********************************** Ndk::Application **********************************/
#ifndef NDK_SERVER
//application.SetMethod("AddWindow", &Application::AddWindow);
#endif
application.BindMethod("AddWorld", [] (Nz::LuaInstance& instance, Application* application) -> int
{
instance.Push(application->AddWorld().CreateHandle());
return 1;
});
application.BindMethod("GetUpdateTime", &Application::GetUpdateTime);
application.BindMethod("Quit", &Application::Quit);
/*********************************** Ndk::Console **********************************/
#ifndef NDK_SERVER
consoleClass.Inherit<Nz::Node>(nodeClass, [] (ConsoleHandle* handle) -> Nz::Node*
{
return handle->GetObject();
});
consoleClass.BindMethod("AddLine", &Console::AddLine, Nz::Color::White);
consoleClass.BindMethod("Clear", &Console::Clear);
consoleClass.BindMethod("GetCharacterSize", &Console::GetCharacterSize);
consoleClass.BindMethod("GetHistory", &Console::GetHistory);
consoleClass.BindMethod("GetHistoryBackground", &Console::GetHistoryBackground);
consoleClass.BindMethod("GetInput", &Console::GetInput);
consoleClass.BindMethod("GetInputBackground", &Console::GetInputBackground);
consoleClass.BindMethod("GetSize", &Console::GetSize);
consoleClass.BindMethod("GetTextFont", &Console::GetTextFont);
consoleClass.BindMethod("IsVisible", &Console::IsVisible);
consoleClass.BindMethod("SendCharacter", &Console::SendCharacter);
//consoleClass.SetMethod("SendEvent", &Console::SendEvent);
consoleClass.BindMethod("SetCharacterSize", &Console::SetCharacterSize);
consoleClass.BindMethod("SetSize", &Console::SetSize);
consoleClass.BindMethod("SetTextFont", &Console::SetTextFont);
consoleClass.BindMethod("Show", &Console::Show, true);
#endif
/*********************************** Ndk::Entity **********************************/
entityClass.BindMethod("Enable", &Entity::Enable, true);
entityClass.BindMethod("GetId", &Entity::GetId);
entityClass.BindMethod("GetWorld", &Entity::GetWorld);
entityClass.BindMethod("Kill", &Entity::Kill);
entityClass.BindMethod("IsEnabled", &Entity::IsEnabled);
entityClass.BindMethod("IsValid", &Entity::IsValid);
entityClass.BindMethod("RemoveAllComponents", &Entity::RemoveAllComponents);
entityClass.BindMethod("__tostring", &EntityHandle::ToString);
entityClass.BindMethod("AddComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int
{
ComponentBinding* binding = QueryComponentIndex(instance);
return binding->adder(instance, handle);
});
entityClass.BindMethod("GetComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int
{
ComponentBinding* binding = QueryComponentIndex(instance);
return binding->getter(instance, handle->GetComponent(binding->index));
});
entityClass.BindMethod("RemoveComponent", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int
{
ComponentBinding* binding = QueryComponentIndex(instance);
handle->RemoveComponent(binding->index);
return 0;
});
/*********************************** Ndk::NodeComponent **********************************/
nodeComponent.Inherit<Nz::Node>(nodeClass, [] (NodeComponentHandle* handle) -> Nz::Node*
{
return handle->GetObject();
});
/*********************************** Ndk::VelocityComponent **********************************/
velocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)
{
std::size_t length;
const char* member = lua.CheckString(1, &length);
if (std::strcmp(member, "Linear") == 0)
{
lua.Push(instance->linearVelocity);
return true;
}
return false;
});
velocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)
{
std::size_t length;
const char* member = lua.CheckString(1, &length);
int argIndex = 2;
if (std::strcmp(member, "Linear") == 0)
{
instance->linearVelocity = lua.Check<Nz::Vector3f>(&argIndex);
return true;
}
return false;
});
/*********************************** Ndk::World **********************************/
worldClass.BindMethod("CreateEntity", &World::CreateEntity);
worldClass.BindMethod("CreateEntities", &World::CreateEntities);
worldClass.BindMethod("Clear", &World::Clear);
#ifndef NDK_SERVER
/*********************************** Ndk::GraphicsComponent **********************************/
graphicsComponent.BindMethod("Attach", &GraphicsComponent::Attach, 0);
#endif
// Components functions
m_componentBinding.resize(BaseComponent::GetMaxComponentIndex());
BindComponent<NodeComponent>("Node");
BindComponent<VelocityComponent>("Velocity");
#ifndef NDK_SERVER
BindComponent<GraphicsComponent>("Graphics");
#endif
}
/*!
* \brief Registers the classes that will be used by the Lua instance
*
* \param instance Lua instance that will interact with the SDK classes
*/
void LuaBinding::RegisterSDK(Nz::LuaInstance& instance)
{
// Classes
application.Register(instance);
entityClass.Register(instance);
nodeComponent.Register(instance);
velocityComponent.Register(instance);
worldClass.Register(instance);
#ifndef NDK_SERVER
consoleClass.Register(instance);
graphicsComponent.Register(instance);
#endif
// Enums
// ComponentType (fake enumeration to expose component indexes)
instance.PushTable(0, m_componentBinding.size());
{
for (const ComponentBinding& entry : m_componentBinding)
{
if (entry.name.IsEmpty())
continue;
instance.PushField(entry.name, entry.index);
}
}
instance.SetGlobal("ComponentType");
}
/*!
* \brief Gets the index of the component
* \return A pointer to the binding linked to a component
*
* \param instance Lua instance that will interact with the component
* \param argIndex Index of the component
*/
LuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex)
{
switch (instance.GetType(argIndex))
{
case Nz::LuaType_Number:
{
ComponentIndex componentIndex = instance.Check<ComponentIndex>(&argIndex);
if (componentIndex > m_componentBinding.size())
{
instance.Error("Invalid component index");
return nullptr;
}
ComponentBinding& binding = m_componentBinding[componentIndex];
if (binding.name.IsEmpty())
{
instance.Error("Invalid component index");
return nullptr;
}
return &binding;
}
case Nz::LuaType_String:
{
const char* key = instance.CheckString(argIndex);
auto it = m_componentBindingByName.find(key);
if (it == m_componentBindingByName.end())
{
instance.Error("Invalid component name");
return nullptr;
}
return &m_componentBinding[it->second];
}
}
instance.Error("Invalid component index at #" + Nz::String::Number(argIndex));
return nullptr;
}
}
<|endoftext|> |
<commit_before>#include "cursor.h"
#include "window.h"
#include "node.h"
#include "tree.h"
#include "space.h"
#include "border.h"
#include "axlib/axlib.h"
#define internal static
extern std::map<std::string, space_info> WindowTree;
extern ax_state AXState;
extern ax_application *FocusedApplication;
extern kwm_settings KWMSettings;
extern kwm_border MarkedBorder;
internal bool DragMoveWindow = false;
internal tree_node *MarkedNode = NULL;
internal inline CGPoint
GetCursorPos()
{
CGEventRef Event = CGEventCreate(NULL);
CGPoint Cursor = CGEventGetLocation(Event);
CFRelease(Event);
return Cursor;
}
internal bool
IsCursorInsideRect(double X, double Y, double Width, double Height)
{
CGPoint Cursor = GetCursorPos();
if(Cursor.x >= X &&
Cursor.x <= X + Width &&
Cursor.y >= Y &&
Cursor.y <= Y + Height)
return true;
return false;
}
internal inline void
ClearMarkedNode()
{
MarkedNode = NULL;
ClearBorder(&MarkedBorder);
}
EVENT_CALLBACK(Callback_AXEvent_MouseMoved)
{
FocusWindowBelowCursor();
}
EVENT_CALLBACK(Callback_AXEvent_LeftMouseDown)
{
if((FocusedApplication && FocusedApplication->Focus) &&
(IsCursorInsideRect(FocusedApplication->Focus->Position.x,
FocusedApplication->Focus->Position.y,
FocusedApplication->Focus->Size.width,
FocusedApplication->Focus->Size.height)))
{
DEBUG("AXEvent_LeftMouseDown");
DragMoveWindow = true;
}
}
EVENT_CALLBACK(Callback_AXEvent_LeftMouseUp)
{
if(DragMoveWindow)
{
DEBUG("AXEvent_LeftMouseUp");
DragMoveWindow = false;
/* NOTE(koekeishiya): DragMoveWindow can only be true if the LeftMouseDown event
* was triggered on top of a window. Thus, we assume that the FocusedApplication
* and its Focus can never be NULL here. */
ax_window *Window = FocusedApplication->Focus;
if(MarkedNode && MarkedNode->WindowID != Window->ID)
{
ax_display *Display = AXLibWindowDisplay(Window);
tree_node *Node = GetTreeNodeFromWindowIDOrLinkNode(WindowTree[Display->Space->Identifier].RootNode, Window->ID);
if(Node)
{
SwapNodeWindowIDs(Node, MarkedNode);
}
}
ClearMarkedNode();
}
}
EVENT_CALLBACK(Callback_AXEvent_LeftMouseDragged)
{
CGPoint *Cursor = (CGPoint *) Event->Context;
if(DragMoveWindow)
{
DEBUG("AXEvent_LeftMouseDragged");
/* NOTE(koekeishiya): DragMoveWindow can only be true if the LeftMouseDown event
* was triggered on top of a window. Thus, we assume that the FocusedApplication
* and its Focus can never be NULL here. */
ax_window *Window = FocusedApplication->Focus;
if(AXLibHasFlags(Window, AXWindow_Floating))
{
double X = Cursor->x - Window->Size.width / 2;
double Y = Cursor->y - Window->Size.height / 2;
AXLibSetWindowPosition(Window->Ref, X, Y);
}
else
{
ax_display *Display = AXLibWindowDisplay(Window);
MarkedNode = GetTreeNodeForPoint(WindowTree[Display->Space->Identifier].RootNode, Cursor);
if(MarkedNode)
{
UpdateBorder(&MarkedBorder, MarkedNode);
}
}
}
free(Cursor);
}
void MoveCursorToCenterOfTreeNode(tree_node *Node)
{
if((HasFlags(&KWMSettings, Settings_MouseFollowsFocus)) &&
(!IsCursorInsideRect(Node->Container.X, Node->Container.Y,
Node->Container.Width, Node->Container.Height)))
{
CGWarpMouseCursorPosition(CGPointMake(Node->Container.X + Node->Container.Width / 2,
Node->Container.Y + Node->Container.Height / 2));
}
}
void MoveCursorToCenterOfLinkNode(link_node *Link)
{
if((HasFlags(&KWMSettings, Settings_MouseFollowsFocus)) &&
(!IsCursorInsideRect(Link->Container.X, Link->Container.Y,
Link->Container.Width, Link->Container.Height)))
{
CGWarpMouseCursorPosition(CGPointMake(Link->Container.X + Link->Container.Width / 2,
Link->Container.Y + Link->Container.Height / 2));
}
}
void MoveCursorToCenterOfWindow(ax_window *Window)
{
if((HasFlags(&KWMSettings, Settings_MouseFollowsFocus)) &&
(!IsCursorInsideRect(Window->Position.x, Window->Position.y,
Window->Size.width, Window->Size.height)))
{
CGWarpMouseCursorPosition(CGPointMake(Window->Position.x + Window->Size.width / 2,
Window->Position.y + Window->Size.height / 2));
}
}
void MoveCursorToCenterOfFocusedWindow()
{
if(FocusedApplication && FocusedApplication->Focus)
MoveCursorToCenterOfWindow(FocusedApplication->Focus);
}
void FocusWindowBelowCursor()
{
ax_application *Application = AXLibGetFocusedApplication();
ax_window *FocusedWindow = NULL;
if(Application)
{
FocusedWindow = Application->Focus;
if((FocusedWindow) && (IsCursorInsideRect(FocusedWindow->Position.x, FocusedWindow->Position.y,
FocusedWindow->Size.width, FocusedWindow->Size.height)))
return;
}
uint32_t WindowID = AXLibGetWindowBelowCursor();
if(WindowID == 0)
return;
std::map<pid_t, ax_application>::iterator It;
for(It = AXState.Applications.begin(); It != AXState.Applications.end(); ++It)
{
ax_application *Application = &It->second;
ax_window *Window = AXLibFindApplicationWindow(Application, WindowID);
if(Window)
{
if((AXLibIsWindowStandard(Window)) ||
(AXLibIsWindowCustom(Window)))
{
if(Application == Window->Application)
{
if(FocusedWindow != Window)
AXLibSetFocusedWindow(Window);
}
else
{
AXLibSetFocusedWindow(Window);
}
}
return;
}
}
}
<commit_msg>#469 - only call updateborder if the marked node changed<commit_after>#include "cursor.h"
#include "window.h"
#include "node.h"
#include "tree.h"
#include "space.h"
#include "border.h"
#include "axlib/axlib.h"
#define internal static
extern std::map<std::string, space_info> WindowTree;
extern ax_state AXState;
extern ax_application *FocusedApplication;
extern kwm_settings KWMSettings;
extern kwm_border MarkedBorder;
internal bool DragMoveWindow = false;
internal tree_node *MarkedNode = NULL;
internal inline CGPoint
GetCursorPos()
{
CGEventRef Event = CGEventCreate(NULL);
CGPoint Cursor = CGEventGetLocation(Event);
CFRelease(Event);
return Cursor;
}
internal bool
IsCursorInsideRect(double X, double Y, double Width, double Height)
{
CGPoint Cursor = GetCursorPos();
if(Cursor.x >= X &&
Cursor.x <= X + Width &&
Cursor.y >= Y &&
Cursor.y <= Y + Height)
return true;
return false;
}
internal inline void
ClearMarkedNode()
{
MarkedNode = NULL;
ClearBorder(&MarkedBorder);
}
EVENT_CALLBACK(Callback_AXEvent_MouseMoved)
{
FocusWindowBelowCursor();
}
EVENT_CALLBACK(Callback_AXEvent_LeftMouseDown)
{
if((FocusedApplication && FocusedApplication->Focus) &&
(IsCursorInsideRect(FocusedApplication->Focus->Position.x,
FocusedApplication->Focus->Position.y,
FocusedApplication->Focus->Size.width,
FocusedApplication->Focus->Size.height)))
{
DEBUG("AXEvent_LeftMouseDown");
DragMoveWindow = true;
}
}
EVENT_CALLBACK(Callback_AXEvent_LeftMouseUp)
{
if(DragMoveWindow)
{
DEBUG("AXEvent_LeftMouseUp");
DragMoveWindow = false;
/* NOTE(koekeishiya): DragMoveWindow can only be true if the LeftMouseDown event
* was triggered on top of a window. Thus, we assume that the FocusedApplication
* and its Focus can never be NULL here. */
ax_window *Window = FocusedApplication->Focus;
if(MarkedNode && MarkedNode->WindowID != Window->ID)
{
ax_display *Display = AXLibWindowDisplay(Window);
tree_node *Node = GetTreeNodeFromWindowIDOrLinkNode(WindowTree[Display->Space->Identifier].RootNode, Window->ID);
if(Node)
{
SwapNodeWindowIDs(Node, MarkedNode);
}
}
ClearMarkedNode();
}
}
EVENT_CALLBACK(Callback_AXEvent_LeftMouseDragged)
{
CGPoint *Cursor = (CGPoint *) Event->Context;
if(DragMoveWindow)
{
DEBUG("AXEvent_LeftMouseDragged");
/* NOTE(koekeishiya): DragMoveWindow can only be true if the LeftMouseDown event
* was triggered on top of a window. Thus, we assume that the FocusedApplication
* and its Focus can never be NULL here. */
ax_window *Window = FocusedApplication->Focus;
if(AXLibHasFlags(Window, AXWindow_Floating))
{
double X = Cursor->x - Window->Size.width / 2;
double Y = Cursor->y - Window->Size.height / 2;
AXLibSetWindowPosition(Window->Ref, X, Y);
}
else
{
ax_display *Display = AXLibWindowDisplay(Window);
tree_node *NewNode = GetTreeNodeForPoint(WindowTree[Display->Space->Identifier].RootNode, Cursor);
if(NewNode && NewNode != MarkedNode)
{
MarkedNode = NewNode;
UpdateBorder(&MarkedBorder, MarkedNode);
}
}
}
free(Cursor);
}
void MoveCursorToCenterOfTreeNode(tree_node *Node)
{
if((HasFlags(&KWMSettings, Settings_MouseFollowsFocus)) &&
(!IsCursorInsideRect(Node->Container.X, Node->Container.Y,
Node->Container.Width, Node->Container.Height)))
{
CGWarpMouseCursorPosition(CGPointMake(Node->Container.X + Node->Container.Width / 2,
Node->Container.Y + Node->Container.Height / 2));
}
}
void MoveCursorToCenterOfLinkNode(link_node *Link)
{
if((HasFlags(&KWMSettings, Settings_MouseFollowsFocus)) &&
(!IsCursorInsideRect(Link->Container.X, Link->Container.Y,
Link->Container.Width, Link->Container.Height)))
{
CGWarpMouseCursorPosition(CGPointMake(Link->Container.X + Link->Container.Width / 2,
Link->Container.Y + Link->Container.Height / 2));
}
}
void MoveCursorToCenterOfWindow(ax_window *Window)
{
if((HasFlags(&KWMSettings, Settings_MouseFollowsFocus)) &&
(!IsCursorInsideRect(Window->Position.x, Window->Position.y,
Window->Size.width, Window->Size.height)))
{
CGWarpMouseCursorPosition(CGPointMake(Window->Position.x + Window->Size.width / 2,
Window->Position.y + Window->Size.height / 2));
}
}
void MoveCursorToCenterOfFocusedWindow()
{
if(FocusedApplication && FocusedApplication->Focus)
MoveCursorToCenterOfWindow(FocusedApplication->Focus);
}
void FocusWindowBelowCursor()
{
ax_application *Application = AXLibGetFocusedApplication();
ax_window *FocusedWindow = NULL;
if(Application)
{
FocusedWindow = Application->Focus;
if((FocusedWindow) && (IsCursorInsideRect(FocusedWindow->Position.x, FocusedWindow->Position.y,
FocusedWindow->Size.width, FocusedWindow->Size.height)))
return;
}
uint32_t WindowID = AXLibGetWindowBelowCursor();
if(WindowID == 0)
return;
std::map<pid_t, ax_application>::iterator It;
for(It = AXState.Applications.begin(); It != AXState.Applications.end(); ++It)
{
ax_application *Application = &It->second;
ax_window *Window = AXLibFindApplicationWindow(Application, WindowID);
if(Window)
{
if((AXLibIsWindowStandard(Window)) ||
(AXLibIsWindowCustom(Window)))
{
if(Application == Window->Application)
{
if(FocusedWindow != Window)
AXLibSetFocusedWindow(Window);
}
else
{
AXLibSetFocusedWindow(Window);
}
}
return;
}
}
}
<|endoftext|> |
<commit_before>/*
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include <random>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <cmath>
#include "particle_filter.h"
#include "helper_functions.h"
using namespace std;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
// TODO: Set the number of particles. Initialize all particles to first position (based on estimates of
// x, y, theta and their uncertainties from GPS) and all weights to 1.
// set number of particles
num_particles = 10;
//initialize all particles to first position
for (int i = 0; i < num_particles; i++){
Particle this_particle = {i, x, y, theta, 1};
particles.push_back(this_particle);
}
default_random_engine gen;
// Add random Gaussian noise to each particle.
normal_distribution<double> N_x_init(0, std[0]);
normal_distribution<double> N_y_init(0, std[1]);
normal_distribution<double> N_theta_init(0, std[2]);
// NOTE: Consult particle_filter.h for more information about this method (and others in this file).
for (int i = 0; i < num_particles; i++){
particles[i].x += N_x_init(gen);
particles[i].y += N_y_init(gen);
particles[i].theta += N_theta_init(gen);
}
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) {
// TODO: Add measurements to each particle and add random Gaussian noise.
// NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful.
// http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
// http://www.cplusplus.com/reference/random/default_random_engine/
default_random_engine gen;
normal_distribution<double> N_x(0,std_pos[0]);
normal_distribution<double> N_y(0,std_pos[1]);
normal_distribution<double> N_theta(0,std_pos[2]);
// if yaw rate not equal to 0
if (yaw_rate != 0){
for (int i = 0; i < num_particles; i++){
particles[i].x += (velocity/yaw_rate) * (sin(particles[i].theta+yaw_rate*delta_t)-sin(particles[i].theta));
//add noise to x
particles[i].x += N_x(gen);
particles[i].y += (velocity/yaw_rate) * (cos(particles[i].theta)-cos(particles[i].theta+yaw_rate*delta_t));
//add noise to y
particles[i].y += N_y(gen);
particles[i].theta += yaw_rate * delta_t;
particles[i].theta += N_theta(gen);
}
}
}
void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) {
// TODO: Find the predicted measurement that is closest to each observed measurement and assign the
// observed measurement to this particular landmark.
// NOTE: this method will NOT be called by the grading code. But you will probably find it useful to
// implement this method and use it as a helper during the updateWeights phase.
for (int i = 0; i < observations.size(); i++){
double smallest_distance = numeric_limits<double>::max();
for (int j = 0; j < predicted.size();j++){
double this_dist = dist(observations[i].x,observations[i].y,predicted[j].x,predicted[j].y);
if (this_dist < smallest_distance){
smallest_distance = this_dist;
observations[i].id = predicted[j].id;
}
}
}
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
std::vector<LandmarkObs> observations, Map map_landmarks) {
// TODO: Update the weights of each particle using a mult-variate Gaussian distribution. You can read
// more about this distribution here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution
// NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located
// according to the MAP'S coordinate system. You will need to transform between the two systems.
// Keep in mind that this transformation requires both rotation AND translation (but no scaling).
// The following is a good resource for the theory:
// https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
// and the following is a good resource for the actual equation to implement (look at equation
// 3.33. Note that you'll need to switch the minus sign in that equation to a plus to account
// for the fact that the map's y-axis actually points downwards.)
// http://planning.cs.uiuc.edu/node99.html
// loop through each particle
for (int p = 0; p < num_particles; p++){
double px = particles[p].x;
double py = particles[p].y;
double ptheta = particles[p].theta;
std::vector<LandmarkObs> predicted;
for (int l =0; l < map_landmarks.landmark_list.size();l++){
if (dist(map_landmarks.landmark_list[l].x_f,map_landmarks.landmark_list[l].y_f,px,py) < sensor_range){
predicted.push_back(LandmarkObs {map_landmarks.landmark_list[l].id_i, map_landmarks.landmark_list[l].x_f,map_landmarks.landmark_list[l].y_f});
}
}
// update weights
double this_weight = 1.;
//convert observations from vehicle coordinate system to map coordinate system
for (int i = 0; i < observations.size();i++){
observations[i].x += (cos(ptheta) + sin(ptheta));
observations[i].y += (sin(ptheta) + cos(ptheta));
}
//determine nearest landmarks
this->dataAssociation(predicted,observations);
for (int i = 0; i < observations.size();i++){
double landmarkx = map_landmarks.landmark_list[observations[i].id].x_f;
double landmarky = map_landmarks.landmark_list[observations[i].id].y_f;
double stdx = std_landmark[0];
double stdy = std_landmark[1];
double stdx2 = pow(stdx,2);
double stdy2 = pow(stdy,2);
//update weight for each observation
this_weight *= (1/(2*M_PI*stdx*stdy)*exp(-1*( pow(px-landmarkx,2)/(2*stdx2)+(pow(py-landmarky,2)/(2*stdy2)))));
}
particles[p].weight = this_weight;
}
}
void ParticleFilter::resample() {
// TODO: Resample particles with replacement with probability proportional to their weight.
// NOTE: You may find std::discrete_distribution helpful here.
// http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
}
void ParticleFilter::write(std::string filename) {
// You don't need to modify this file.
std::ofstream dataFile;
dataFile.open(filename, std::ios::app);
for (int i = 0; i < num_particles; ++i) {
dataFile << particles[i].x << " " << particles[i].y << " " << particles[i].theta << "\n";
}
dataFile.close();
}
<commit_msg>Filled in resample method of ParticleFilter:<commit_after>/*
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include <random>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <cmath>
#include "particle_filter.h"
#include "helper_functions.h"
#include "map"
using namespace std;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
// TODO: Set the number of particles. Initialize all particles to first position (based on estimates of
// x, y, theta and their uncertainties from GPS) and all weights to 1.
// set number of particles
num_particles = 10;
//initialize all particles to first position
for (int i = 0; i < num_particles; i++){
Particle this_particle = {i, x, y, theta, 1};
particles.push_back(this_particle);
}
default_random_engine gen;
// Add random Gaussian noise to each particle.
normal_distribution<double> N_x_init(0, std[0]);
normal_distribution<double> N_y_init(0, std[1]);
normal_distribution<double> N_theta_init(0, std[2]);
// NOTE: Consult particle_filter.h for more information about this method (and others in this file).
for (int i = 0; i < num_particles; i++){
particles[i].x += N_x_init(gen);
particles[i].y += N_y_init(gen);
particles[i].theta += N_theta_init(gen);
}
is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) {
// TODO: Add measurements to each particle and add random Gaussian noise.
// NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful.
// http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
// http://www.cplusplus.com/reference/random/default_random_engine/
default_random_engine gen;
normal_distribution<double> N_x(0,std_pos[0]);
normal_distribution<double> N_y(0,std_pos[1]);
normal_distribution<double> N_theta(0,std_pos[2]);
// if yaw rate not equal to 0
if (yaw_rate != 0){
for (int i = 0; i < num_particles; i++){
particles[i].x += (velocity/yaw_rate) * (sin(particles[i].theta+yaw_rate*delta_t)-sin(particles[i].theta));
//add noise to x
particles[i].x += N_x(gen);
particles[i].y += (velocity/yaw_rate) * (cos(particles[i].theta)-cos(particles[i].theta+yaw_rate*delta_t));
//add noise to y
particles[i].y += N_y(gen);
particles[i].theta += yaw_rate * delta_t;
particles[i].theta += N_theta(gen);
}
}
}
void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) {
// TODO: Find the predicted measurement that is closest to each observed measurement and assign the
// observed measurement to this particular landmark.
// NOTE: this method will NOT be called by the grading code. But you will probably find it useful to
// implement this method and use it as a helper during the updateWeights phase.
for (int i = 0; i < observations.size(); i++){
double smallest_distance = numeric_limits<double>::max();
for (int j = 0; j < predicted.size();j++){
double this_dist = dist(observations[i].x,observations[i].y,predicted[j].x,predicted[j].y);
if (this_dist < smallest_distance){
smallest_distance = this_dist;
observations[i].id = predicted[j].id;
}
}
}
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
std::vector<LandmarkObs> observations, Map map_landmarks) {
// TODO: Update the weights of each particle using a mult-variate Gaussian distribution. You can read
// more about this distribution here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution
// NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located
// according to the MAP'S coordinate system. You will need to transform between the two systems.
// Keep in mind that this transformation requires both rotation AND translation (but no scaling).
// The following is a good resource for the theory:
// https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
// and the following is a good resource for the actual equation to implement (look at equation
// 3.33. Note that you'll need to switch the minus sign in that equation to a plus to account
// for the fact that the map's y-axis actually points downwards.)
// http://planning.cs.uiuc.edu/node99.html
// loop through each particle
for (int p = 0; p < num_particles; p++){
double px = particles[p].x;
double py = particles[p].y;
double ptheta = particles[p].theta;
std::vector<LandmarkObs> predicted;
for (int l =0; l < map_landmarks.landmark_list.size();l++){
if (dist(map_landmarks.landmark_list[l].x_f,map_landmarks.landmark_list[l].y_f,px,py) < sensor_range){
predicted.push_back(LandmarkObs {map_landmarks.landmark_list[l].id_i, map_landmarks.landmark_list[l].x_f,map_landmarks.landmark_list[l].y_f});
}
}
// update weights
double this_weight = 1.;
//convert observations from vehicle coordinate system to map coordinate system
for (int i = 0; i < observations.size();i++){
observations[i].x += (cos(ptheta) - sin(ptheta));
observations[i].y += (sin(ptheta) + cos(ptheta));
}
//determine nearest landmarks
this->dataAssociation(predicted,observations);
for (int i = 0; i < observations.size();i++){
double landmarkx = map_landmarks.landmark_list[observations[i].id].x_f;
double landmarky = map_landmarks.landmark_list[observations[i].id].y_f;
double stdx = std_landmark[0];
double stdy = std_landmark[1];
double stdx2 = pow(stdx,2);
double stdy2 = pow(stdy,2);
//update weight for each observation
this_weight *= (1/(2*M_PI*stdx*stdy)*exp(-1*( pow(px-landmarkx,2)/(2*stdx2)+(pow(py-landmarky,2)/(2*stdy2)))));
}
particles[p].weight = this_weight;
}
}
void ParticleFilter::resample() {
// TODO: Resample particles with replacement with probability proportional to their weight.
// NOTE: You may find std::discrete_distribution helpful here.
// http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
// Setup the weights (in this case linearly weighted)
std::vector<int> weights;
for(int i=0; i<num_particles; i++) {
weights.push_back(particles[i].weight);
}
std::vector<Particle> particles_new;
std::random_device rd;
std::mt19937 gen(rd());
std::discrete_distribution<> d(weights.begin(), weights.end());
std::map<int, int> m;
for(int n=0; n<num_particles; n++) {
particles_new.push_back(particles[d(gen)]);
}
particles = particles_new;
}
void ParticleFilter::write(std::string filename) {
// You don't need to modify this file.
std::ofstream dataFile;
dataFile.open(filename, std::ios::app);
for (int i = 0; i < num_particles; ++i) {
dataFile << particles[i].x << " " << particles[i].y << " " << particles[i].theta << "\n";
}
dataFile.close();
}
<|endoftext|> |
<commit_before>
#pragma once
#include <vector>
#include "geometry/perspective.hpp"
#include "numerics/root_finders.hpp"
#include "quantities/named_quantities.hpp"
namespace principia {
namespace geometry {
namespace internal_perspective {
using geometry::InnerProduct;
using numerics::SolveQuadraticEquation;
using quantities::Product;
template<typename FromFrame, typename ToFrame, typename Scalar,
template<typename, typename> class LinearMap>
Perspective<FromFrame, ToFrame, Scalar, LinearMap>::Perspective(
AffineMap<ToFrame, FromFrame, Scalar, LinearMap> const& from_camera,
Scalar const& focal)
: from_camera_(from_camera),
to_camera_(from_camera.Inverse()),
camera_(from_camera_(ToFrame::origin)),
focal_(focal) {}
template<typename FromFrame,
typename ToFrame,
typename Scalar,
template<typename, typename> class LinearMap>
Perspective<FromFrame, ToFrame, Scalar, LinearMap>::Perspective(
AffineMap<FromFrame, ToFrame, Scalar, LinearMap> const& to_camera,
Scalar const& focal)
: from_camera_(to_camera.Inverse()),
to_camera_(to_camera),
camera_(from_camera_(ToFrame::origin)),
focal_(focal) {}
template<typename FromFrame,
typename ToFrame,
typename Scalar,
template<typename, typename> class LinearMap>
std::experimental::optional<RP2Point<Scalar, ToFrame>>
Perspective<FromFrame, ToFrame, Scalar, LinearMap>::operator()(
Point<Vector<Scalar, FromFrame>> const& point) const {
Point<Vector<Scalar, ToFrame>> const point_in_camera = to_camera_(point);
Vector<Scalar, ToFrame> const displacement_in_camera =
point_in_camera - ToFrame::origin;
R3Element<Scalar> const coordinates_in_camera =
displacement_in_camera.coordinates();
if (coordinates_in_camera.z < Scalar()) {
// Do not project points that are behind the camera.
return std::experimental::nullopt;
} else {
// This is the actual pinhole camera projection.
return RP2Point<Scalar, ToFrame>(coordinates_in_camera.x,
coordinates_in_camera.y,
coordinates_in_camera.z / focal_);
}
}
template<typename FromFrame,
typename ToFrame,
typename Scalar,
template<typename, typename> class LinearMap>
bool Perspective<FromFrame, ToFrame, Scalar, LinearMap>::IsHiddenBySphere(
Point<Vector<Scalar, FromFrame>> const& point,
Sphere<Scalar, FromFrame> const& sphere) const {
using Displacement = Vector<Scalar, FromFrame>;
Displacement const camera_to_centre = sphere.centre() - camera_;
Displacement const camera_to_point = point - camera_;
Displacement const centre_to_point = point - sphere.centre();
Product<Scalar, Scalar> const& r² = sphere.radius²();
Product<Scalar, Scalar> const camera_to_centre² =
InnerProduct(camera_to_centre, camera_to_centre);
Product<Scalar, Scalar> const camera_to_point² =
InnerProduct(camera_to_point, camera_to_point);
Product<Scalar, Scalar> const centre_to_point² =
InnerProduct(centre_to_point, centre_to_point);
// If the point lies in the sphere then surely it is hidden.
bool const is_in_sphere = centre_to_point² < r²;
if (is_in_sphere) {
return true;
}
// Squared distance between the camera and the horizon, i.e., the circle
// where the cone from the camera tangents the sphere. Plain Πυθαγόρας.
Product<Scalar, Scalar> const camera_to_horizon² = camera_to_centre² - r²;
// This implicitly gives the cosine of the angle between the centre and the
// point as seen from the camera.
Product<Scalar, Scalar> const inner_product =
InnerProduct(camera_to_point, camera_to_centre);
// This effectively compares the square cosines of (1) the angle between the
// centre and the point as seen from the camera and (2) the angle of the cone.
// If the point does not lie in the cone then surely it is visible.
bool const is_in_cone =
inner_product * inner_product > camera_to_horizon² * camera_to_point²;
if (!is_in_cone) {
return false;
}
// This effectively compares (1) the distance from the camera to the plane of
// the horizon (the plane where the cone tangents the sphere) and (2) the
// distance from the camera to the projection of the point on the axis camera-
// centre.
bool const is_in_front_of_horizon = inner_product < camera_to_horizon²;
return !is_in_front_of_horizon;
}
template<typename FromFrame,
typename ToFrame,
typename Scalar,
template<typename, typename> class LinearMap>
std::vector<Segment<Vector<Scalar, FromFrame>>>
Perspective<FromFrame, ToFrame, Scalar, LinearMap>::VisibleSegments(
Segment<Vector<Scalar, FromFrame>> const& segment,
Sphere<Scalar, FromFrame> const& sphere) const {
// K is the position of the camera, A and B the extremities of the segment,
// C the centre of the sphere.
Point<Vector<Scalar, FromFrame>> const& K = camera_;
Point<Vector<Scalar, FromFrame>> const& A = segment.first;
Point<Vector<Scalar, FromFrame>> const& B = segment.second;
Point<Vector<Scalar, FromFrame>> const& C = sphere.centre();
// H is the projection of C on the plane KAB. It is such that:
// KH = ɑ * KA + β * KB
// where ɑ and β are computed by solving the linear system:
// KA.KH = KA.KC = ɑ * KA² + β * KA.KB
// KB.KH = KB.KC = ɑ * KA.KB + β * KB²
Vector<Scalar, FromFrame> const KA = A - K;
Vector<Scalar, FromFrame> const KB = B - K;
Vector<Scalar, FromFrame> const KC = C - K;
auto const KA² = InnerProduct(KA, KA);
auto const KB² = InnerProduct(KB, KB);
auto const KAKB = InnerProduct(KA, KB);
auto const KAKC = InnerProduct(KA, KC);
auto const KBKC = InnerProduct(KB, KC);
auto const determinant = KA² * KB² - KAKB * KAKB;
double const ɑ = (KB² * KAKC - KAKB * KBKC) / determinant;
double const β = (KA² * KBKC - KAKB * KAKC) / determinant;
Vector<Scalar, FromFrame> const KH = ɑ * KA + β * KB;
// The basic check: if H is outside the sphere, there is no intersection and
// thus no hiding.
Vector<Scalar, FromFrame> const CH = KH - KC;
auto const CH² = InnerProduct(CH, CH);
if (CH² >= sphere.radius²()) {
return {segment};
}
// TODO(phl): See if an early exit is possible/easy here when ɑ + β ≫ 1.
// P is a point of the plane KAB where a line going through K is tangent to
// the circle formed by the intersection of the sphere with the plane KAB. It
// is such that:
// PH = γ * KA + δ * KB
// where γ and δ are computed by solving the system:
// PH² = r²
// PH.KH = r²
// where r² = R² - CH² is the square of the radius of the above-mentioned
// circle. There are two such points because the sphere intersects the plane.
auto const r² = sphere.radius²() - CH²;
auto const KAKH = InnerProduct(KA, KH);
auto const KBKH = InnerProduct(KB, KH);
auto const a0 = r² * (r² * KA² - KAKH * KAKH);
auto const a1 = 2.0 * r² * (KAKB * KAKH - KA² * KBKH);
auto const a2 =
KB² * KAKH * KAKH - 2.0 * KAKB * KAKH * KBKH + KA² * KBKH * KBKH;
std::set<double> δs = SolveQuadraticEquation(/*origin=*/0.0, a0, a1, a2);
CHECK_EQ(2, δs.size());
// The λs define points R where the line AB intersects the cone+sphere system,
// according to the formula:
// KR = KA + λ * AB
// There can be between 0 and 4 values of λ.
std::set<double> λs;
// For each solution of the above quadratic equation, compute the value of λ,
// if any.
for (double const δ : δs) {
double const γ = (r² - δ * KBKH) / KAKH;
Vector<Scalar, FromFrame> const PH = γ * KA + δ * KB;
// The value of γ + δ determines where P lies with respect to the line AB.
// If it is behind as seen from K, there is no intersection.
if (γ + δ < 1) {
auto const KAPH = InnerProduct(KA, PH);
auto const ABPH = InnerProduct(AB, PH);
double const λ = -KAPH / ABPH;
λs.insert(λ);
}
}
// Q is the intersection of the sphere with the line AB. It is such that:
// KQ = KA + μ * AB
// where μ is computed by solving a quadratic equation:
// CQ² = R² = (KQ - KC)² = (μ * AB - AC)²
Vector<Scalar, FromFrame> const AB = B - A;
Vector<Scalar, FromFrame> const AC = C - A;
auto const AB² = InnerProduct(AB, AB);
auto const AC² = InnerProduct(AC, AC);
auto const ABAC = InnerProduct(AB, AC);
std::set<double> μs = SolveQuadraticEquation(/*origin=*/0.0,
/*a0=*/AC² - sphere.radius²(),
/*a1=*/-2.0 * ABAC,
/*a2=*/AB²);
λs.insert(μs.begin(), μs.end());
// Now we have all the possible intersection of the cone+sphere with the line
// AB. Determine which ones fall in the segment AB and compute the final
// result.
if (λs.size() < 2) {
// The cone+sphere doesn't intersect the line AB or is tangent to it. There
// is no hiding.
return {segment};
}
double const λ_min = *λs.begin();
double const λ_max = *λs.rbegin();
if (λ_min <= 0.0 && λ_max >= 1.0) {
// The cone+sphere swallows the segment.
return {};
}
if (λ_min > 0.0 && λ_max < 1.0) {
// The cone+sphere hides the middle of the segment.
return {{A, A + λ_min * AB }, {A + λ_max * AB, B }};
}
if (λ_min <= 0.0) {
// The cone+sphere hides the beginning of the segment.
return {{A + λ_max * AB, B }};
}
{
CHECK_GE(λ_max, 1.0);
// The cone+sphere hides the end of the segment.
return {{A, A + λ_min * AB }};
}
}
} // namespace internal_perspective
} // namespace geometry
} // namespace principia
<commit_msg>Full implementation.<commit_after>
#pragma once
#include <vector>
#include "geometry/perspective.hpp"
#include "numerics/root_finders.hpp"
#include "quantities/named_quantities.hpp"
namespace principia {
namespace geometry {
namespace internal_perspective {
using geometry::InnerProduct;
using numerics::SolveQuadraticEquation;
using quantities::Product;
template<typename FromFrame, typename ToFrame, typename Scalar,
template<typename, typename> class LinearMap>
Perspective<FromFrame, ToFrame, Scalar, LinearMap>::Perspective(
AffineMap<ToFrame, FromFrame, Scalar, LinearMap> const& from_camera,
Scalar const& focal)
: from_camera_(from_camera),
to_camera_(from_camera.Inverse()),
camera_(from_camera_(ToFrame::origin)),
focal_(focal) {}
template<typename FromFrame,
typename ToFrame,
typename Scalar,
template<typename, typename> class LinearMap>
Perspective<FromFrame, ToFrame, Scalar, LinearMap>::Perspective(
AffineMap<FromFrame, ToFrame, Scalar, LinearMap> const& to_camera,
Scalar const& focal)
: from_camera_(to_camera.Inverse()),
to_camera_(to_camera),
camera_(from_camera_(ToFrame::origin)),
focal_(focal) {}
template<typename FromFrame,
typename ToFrame,
typename Scalar,
template<typename, typename> class LinearMap>
std::experimental::optional<RP2Point<Scalar, ToFrame>>
Perspective<FromFrame, ToFrame, Scalar, LinearMap>::operator()(
Point<Vector<Scalar, FromFrame>> const& point) const {
Point<Vector<Scalar, ToFrame>> const point_in_camera = to_camera_(point);
Vector<Scalar, ToFrame> const displacement_in_camera =
point_in_camera - ToFrame::origin;
R3Element<Scalar> const coordinates_in_camera =
displacement_in_camera.coordinates();
if (coordinates_in_camera.z < Scalar()) {
// Do not project points that are behind the camera.
return std::experimental::nullopt;
} else {
// This is the actual pinhole camera projection.
return RP2Point<Scalar, ToFrame>(coordinates_in_camera.x,
coordinates_in_camera.y,
coordinates_in_camera.z / focal_);
}
}
template<typename FromFrame,
typename ToFrame,
typename Scalar,
template<typename, typename> class LinearMap>
bool Perspective<FromFrame, ToFrame, Scalar, LinearMap>::IsHiddenBySphere(
Point<Vector<Scalar, FromFrame>> const& point,
Sphere<Scalar, FromFrame> const& sphere) const {
using Displacement = Vector<Scalar, FromFrame>;
Displacement const camera_to_centre = sphere.centre() - camera_;
Displacement const camera_to_point = point - camera_;
Displacement const centre_to_point = point - sphere.centre();
Product<Scalar, Scalar> const& r² = sphere.radius²();
Product<Scalar, Scalar> const camera_to_centre² =
InnerProduct(camera_to_centre, camera_to_centre);
Product<Scalar, Scalar> const camera_to_point² =
InnerProduct(camera_to_point, camera_to_point);
Product<Scalar, Scalar> const centre_to_point² =
InnerProduct(centre_to_point, centre_to_point);
// If the point lies in the sphere then surely it is hidden.
bool const is_in_sphere = centre_to_point² < r²;
if (is_in_sphere) {
return true;
}
// Squared distance between the camera and the horizon, i.e., the circle
// where the cone from the camera tangents the sphere. Plain Πυθαγόρας.
Product<Scalar, Scalar> const camera_to_horizon² = camera_to_centre² - r²;
// This implicitly gives the cosine of the angle between the centre and the
// point as seen from the camera.
Product<Scalar, Scalar> const inner_product =
InnerProduct(camera_to_point, camera_to_centre);
// This effectively compares the square cosines of (1) the angle between the
// centre and the point as seen from the camera and (2) the angle of the cone.
// If the point does not lie in the cone then surely it is visible.
bool const is_in_cone =
inner_product * inner_product > camera_to_horizon² * camera_to_point²;
if (!is_in_cone) {
return false;
}
// This effectively compares (1) the distance from the camera to the plane of
// the horizon (the plane where the cone tangents the sphere) and (2) the
// distance from the camera to the projection of the point on the axis camera-
// centre.
bool const is_in_front_of_horizon = inner_product < camera_to_horizon²;
return !is_in_front_of_horizon;
}
template<typename FromFrame,
typename ToFrame,
typename Scalar,
template<typename, typename> class LinearMap>
std::vector<Segment<Vector<Scalar, FromFrame>>>
Perspective<FromFrame, ToFrame, Scalar, LinearMap>::VisibleSegments(
Segment<Vector<Scalar, FromFrame>> const& segment,
Sphere<Scalar, FromFrame> const& sphere) const {
// K is the position of the camera, A and B the extremities of the segment,
// C the centre of the sphere.
Point<Vector<Scalar, FromFrame>> const& K = camera_;
Point<Vector<Scalar, FromFrame>> const& A = segment.first;
Point<Vector<Scalar, FromFrame>> const& B = segment.second;
Point<Vector<Scalar, FromFrame>> const& C = sphere.centre();
// H is the projection of C on the plane KAB. It is such that:
// KH = ɑ * KA + β * KB
// where ɑ and β are computed by solving the linear system:
// KA.KH = KA.KC = ɑ * KA² + β * KA.KB
// KB.KH = KB.KC = ɑ * KA.KB + β * KB²
Vector<Scalar, FromFrame> const KA = A - K;
Vector<Scalar, FromFrame> const KB = B - K;
Vector<Scalar, FromFrame> const KC = C - K;
auto const KA² = InnerProduct(KA, KA);
auto const KB² = InnerProduct(KB, KB);
auto const KAKB = InnerProduct(KA, KB);
auto const KAKC = InnerProduct(KA, KC);
auto const KBKC = InnerProduct(KB, KC);
auto const determinant = KA² * KB² - KAKB * KAKB;
double const ɑ = (KB² * KAKC - KAKB * KBKC) / determinant;
double const β = (KA² * KBKC - KAKB * KAKC) / determinant;
Vector<Scalar, FromFrame> const KH = ɑ * KA + β * KB;
// The basic check: if H is outside or on the sphere, there is no intersection
// and thus no hiding.
Vector<Scalar, FromFrame> const CH = KH - KC;
auto const CH² = InnerProduct(CH, CH);
if (CH² >= sphere.radius²()) {
return {segment};
}
// TODO(phl): See if an early exit is possible/easy here when ɑ + β ≫ 1.
// P is a point of the plane KAB where a line going through K is tangent to
// the circle formed by the intersection of the sphere with the plane KAB. It
// is such that:
// PH = γ * KA + δ * KB
// where γ and δ are computed by solving the system:
// PH² = r²
// PH.KH = r²
// where r² = R² - CH² is the square of the radius of the above-mentioned
// circle. There are two such points because the sphere intersects the plane.
auto const r² = sphere.radius²() - CH²;
auto const KAKH = InnerProduct(KA, KH);
auto const KBKH = InnerProduct(KB, KH);
auto const a0 = r² * (r² * KA² - KAKH * KAKH);
auto const a1 = 2.0 * r² * (KAKB * KAKH - KA² * KBKH);
auto const a2 =
KB² * KAKH * KAKH - 2.0 * KAKB * KAKH * KBKH + KA² * KBKH * KBKH;
std::set<double> δs = SolveQuadraticEquation(/*origin=*/0.0, a0, a1, a2);
CHECK_EQ(2, δs.size());
// The λs define points Q where the line AB intersects the cone+sphere system,
// according to the formula:
// KQ = KA + λ * AB
// There can be between 0 and 4 values of λ.
std::set<double> λs;
// For each solution of the above quadratic equation, compute the value of λ,
// if any.
Vector<Scalar, FromFrame> const AB = B - A;
for (double const δ : δs) {
double const γ = (r² - δ * KBKH) / KAKH;
Vector<Scalar, FromFrame> const PH = γ * KA + δ * KB;
// The value of γ + δ determines where P lies with respect to the line AB.
// If it is behind as seen from K, there is no intersection.
if (γ + δ < 1) {
auto const KAPH = InnerProduct(KA, PH);
auto const ABPH = InnerProduct(AB, PH);
double const λ = -KAPH / ABPH;
λs.insert(λ);
}
}
// Q is the intersection of the sphere with the line AB. It is such that:
// KQ = KA + μ * AB
// where μ is computed by solving a quadratic equation:
// CQ² = R² = (KQ - KC)² = (μ * AB - AC)²
Vector<Scalar, FromFrame> const AC = C - A;
auto const AB² = InnerProduct(AB, AB);
auto const AC² = InnerProduct(AC, AC);
auto const ABAC = InnerProduct(AB, AC);
std::set<double> μs = SolveQuadraticEquation(/*origin=*/0.0,
/*a0=*/AC² - sphere.radius²(),
/*a1=*/-2.0 * ABAC,
/*a2=*/AB²);
// Merge and sort all the intersections.
λs.insert(μs.begin(), μs.end());
// Now we have all the possible intersections of the cone+sphere with the line
// AB. Determine which ones fall in the segment AB and compute the final
// result.
if (λs.size() < 2) {
// The cone+sphere doesn't intersect the line AB or is tangent to it. There
// is no hiding.
return {segment};
}
double const λ_min = *λs.begin();
double const λ_max = *λs.rbegin();
if (λ_min <= 0.0 && λ_max >= 1.0) {
// The cone+sphere swallows the segment.
return {};
}
if (λ_min > 0.0 && λ_max < 1.0) {
// The cone+sphere hides the middle of the segment.
return {{A, A + λ_min * AB }, {A + λ_max * AB, B }};
}
if (λ_min <= 0.0) {
// The cone+sphere hides the beginning of the segment.
return {{A + λ_max * AB, B }};
}
{
CHECK_GE(λ_max, 1.0);
// The cone+sphere hides the end of the segment.
return {{A, A + λ_min * AB }};
}
}
} // namespace internal_perspective
} // namespace geometry
} // namespace principia
<|endoftext|> |
<commit_before>#include "Tree.hpp"
#include <stdexcept>
#include <iostream>
#include "pll_util.hpp"
#include "epa_pll_util.hpp"
#include "file_io.hpp"
#include "Sequence.hpp"
#include "optimize.hpp"
#include "calculation.hpp"
using namespace std;
Tree::Tree(const string& tree_file, const MSA& msa, Model& model, Options options,
const MSA& query)
: ref_msa_(msa), query_msa_(query), model_(model), options_(options)
{
//parse, build tree
nums_ = Tree_Numbers();
tie(partition_, tree_) = build_partition_from_file(tree_file, model_, nums_, ref_msa_.num_sites());
// split msa if no separate query msa was supplied
if (query.num_sites() == 0)
split_combined_msa(ref_msa_, query_msa_, tree_, nums_.tip_nodes);
valid_map_ = vector<tuple<unsigned int, unsigned int>>(nums_.tip_nodes);
link_tree_msa(tree_, partition_, ref_msa_, nums_.tip_nodes, valid_map_);
// for(auto tp : valid_map_)
// {
// unsigned int i, j;
// tie(i,j) = tp;
// cout << "(" << i << ", " << j << ")" << endl;
//
// }
compute_and_set_empirical_frequencies(partition_);
// perform branch length and model optimization on the reference tree
optimize(model_, tree_, partition_, nums_, options_.opt_branches, options_.opt_model);
precompute_clvs(tree_, partition_, nums_);
}
double Tree::ref_tree_logl()
{
return pll_compute_edge_loglikelihood (partition_, tree_->clv_index,
tree_->scaler_index,
tree_->back->clv_index,
tree_->back->scaler_index,
tree_->pmatrix_index, 0);
}
Tree::~Tree()
{
// free data segment of tree nodes
utree_free_node_data(tree_);
pll_partition_destroy(partition_);
pll_utree_destroy(tree_);
}
PQuery_Set Tree::place() const
{
// get all edges
vector<pll_utree_t *> branches(nums_.branches);
auto num_traversed = utree_query_branches(tree_, &branches[0]);
// build all tiny trees with corresponding edges
vector<Tiny_Tree> insertion_trees;
for (auto node : branches)
insertion_trees.emplace_back(node, partition_, model_, !options_.prescoring);
/* clarification: last arg here is a flag specifying whether to optimize the branches.
we don't want that if the mode is prescoring */
// output class
PQuery_Set pquerys(get_numbered_newick_string(tree_));
// place all s on every edge
double logl, distal, pendant;
for (auto const &s : query_msa_)// make sure a reference, not a copy, is returned
{
pquerys.emplace_back(s);
for (unsigned int i = 0; i < num_traversed; ++i)
{
tie(logl, distal, pendant) = insertion_trees[i].place(s);
pquerys.back().emplace_back(
i, // branch_id
logl, // likelihood
pendant, // pendant length
distal // distal length
);
}
}
// now that everything has been placed, we can compute the likelihood weight ratio
compute_and_set_lwr(pquerys);
/* prescoring was chosen: perform a second round, but only on candidate edges identified
during the first run */
// TODO for MPI: think about how to split up the work, probably build list of sequences
// per branch, then pass
if (options_.prescoring)
{
discard_by_accumulated_threshold(pquerys, 0.95);// TODO outside input? constant?
for (auto &pq : pquerys)
for (auto &placement : pq)
{
unsigned int id = placement.branch_id();
insertion_trees[id].opt_branches(true); // TODO only needs to be done once
tie(logl, distal, pendant) = insertion_trees[id].place(pq.sequence());
placement.likelihood(logl);
placement.pendant_length(pendant);
placement.distal_length(distal);
}
compute_and_set_lwr(pquerys);
}
// finally, trim the output
if (options_.acc_threshold)
discard_by_accumulated_threshold(pquerys, options_.support_threshold);
else
discard_by_support_threshold(pquerys, options_.support_threshold);
return pquerys;
}
<commit_msg>removed a comment<commit_after>#include "Tree.hpp"
#include <stdexcept>
#include <iostream>
#include "pll_util.hpp"
#include "epa_pll_util.hpp"
#include "file_io.hpp"
#include "Sequence.hpp"
#include "optimize.hpp"
#include "calculation.hpp"
using namespace std;
Tree::Tree(const string& tree_file, const MSA& msa, Model& model, Options options,
const MSA& query)
: ref_msa_(msa), query_msa_(query), model_(model), options_(options)
{
//parse, build tree
nums_ = Tree_Numbers();
tie(partition_, tree_) = build_partition_from_file(tree_file, model_, nums_, ref_msa_.num_sites());
// split msa if no separate query msa was supplied
if (query.num_sites() == 0)
split_combined_msa(ref_msa_, query_msa_, tree_, nums_.tip_nodes);
valid_map_ = vector<tuple<unsigned int, unsigned int>>(nums_.tip_nodes);
link_tree_msa(tree_, partition_, ref_msa_, nums_.tip_nodes, valid_map_);
compute_and_set_empirical_frequencies(partition_);
// perform branch length and model optimization on the reference tree
optimize(model_, tree_, partition_, nums_, options_.opt_branches, options_.opt_model);
precompute_clvs(tree_, partition_, nums_);
}
double Tree::ref_tree_logl()
{
return pll_compute_edge_loglikelihood (partition_, tree_->clv_index,
tree_->scaler_index,
tree_->back->clv_index,
tree_->back->scaler_index,
tree_->pmatrix_index, 0);
}
Tree::~Tree()
{
// free data segment of tree nodes
utree_free_node_data(tree_);
pll_partition_destroy(partition_);
pll_utree_destroy(tree_);
}
PQuery_Set Tree::place() const
{
// get all edges
vector<pll_utree_t *> branches(nums_.branches);
auto num_traversed = utree_query_branches(tree_, &branches[0]);
// build all tiny trees with corresponding edges
vector<Tiny_Tree> insertion_trees;
for (auto node : branches)
insertion_trees.emplace_back(node, partition_, model_, !options_.prescoring);
/* clarification: last arg here is a flag specifying whether to optimize the branches.
we don't want that if the mode is prescoring */
// output class
PQuery_Set pquerys(get_numbered_newick_string(tree_));
// place all s on every edge
double logl, distal, pendant;
for (auto const &s : query_msa_)// make sure a reference, not a copy, is returned
{
pquerys.emplace_back(s);
for (unsigned int i = 0; i < num_traversed; ++i)
{
tie(logl, distal, pendant) = insertion_trees[i].place(s);
pquerys.back().emplace_back(
i, // branch_id
logl, // likelihood
pendant, // pendant length
distal // distal length
);
}
}
// now that everything has been placed, we can compute the likelihood weight ratio
compute_and_set_lwr(pquerys);
/* prescoring was chosen: perform a second round, but only on candidate edges identified
during the first run */
// TODO for MPI: think about how to split up the work, probably build list of sequences
// per branch, then pass
if (options_.prescoring)
{
discard_by_accumulated_threshold(pquerys, 0.95);// TODO outside input? constant?
for (auto &pq : pquerys)
for (auto &placement : pq)
{
unsigned int id = placement.branch_id();
insertion_trees[id].opt_branches(true); // TODO only needs to be done once
tie(logl, distal, pendant) = insertion_trees[id].place(pq.sequence());
placement.likelihood(logl);
placement.pendant_length(pendant);
placement.distal_length(distal);
}
compute_and_set_lwr(pquerys);
}
// finally, trim the output
if (options_.acc_threshold)
discard_by_accumulated_threshold(pquerys, options_.support_threshold);
else
discard_by_support_threshold(pquerys, options_.support_threshold);
return pquerys;
}
<|endoftext|> |
<commit_before><commit_msg>Remove 20 second delay in ocmb_check_for_ready<commit_after><|endoftext|> |
<commit_before>#include "MultiArcGraph.h"
using namespace std;
using namespace table;
MultiArcGraph::MultiArcGraph(int _id) : Graph(1, _id) {
setNodeSizeMethod(SizeMethod::SIZE_FROM_DEGREE);
}
MultiArcGraph::MultiArcGraph(const MultiArcGraph & other)
: Graph(other), edge_attributes(other.edge_attributes) {
}
std::shared_ptr<Graph>
MultiArcGraph::createSimilar() const {
std::shared_ptr<Graph> graph(new MultiArcGraph(getId()));
graph->setLocationGraphValid(false);
graph->setAlpha3(getAlpha2());
graph->setTemporal(isTemporal());
graph->setPersonality(getPersonality());
graph->setHasTextures(hasTextures());
graph->setNodeSizeMethod(getNodeSizeMethod());
graph->setClusterVisibility(getClusterVisibility());
graph->setNodeVisibility(getNodeVisibility());
graph->setEdgeVisibility(getEdgeVisibility());
graph->setRegionVisibility(getRegionVisibility());
graph->setLabelVisibility(getLabelVisibility());
for (auto it = getNodeData().getColumns().begin(); it != getNodeData().getColumns().end(); it++) {
if (it->first != "posts") {
graph->getNodeData().addColumn(it->second->create());
}
}
return graph;
}
<commit_msg>remove namespace table, remove default node size method, use original graph nodes when cloning<commit_after>#include "MultiArcGraph.h"
using namespace std;
MultiArcGraph::MultiArcGraph(int _id) : Graph(1, _id) {
}
MultiArcGraph::MultiArcGraph(const MultiArcGraph & other)
: Graph(other), edge_attributes(other.edge_attributes) {
}
std::shared_ptr<Graph>
MultiArcGraph::createSimilar() const {
std::shared_ptr<Graph> graph(new MultiArcGraph(getId()));
graph->setLocationGraphValid(false);
graph->setTemporal(isTemporal());
graph->setPersonality(getPersonality());
graph->setHasTextures(hasTextures());
graph->setClusterVisibility(getClusterVisibility());
graph->setNodeVisibility(getNodeVisibility());
graph->setEdgeVisibility(getEdgeVisibility());
graph->setRegionVisibility(getRegionVisibility());
graph->setLabelVisibility(getLabelVisibility());
graph->setNodeArray(nodes);
return graph;
}
<|endoftext|> |
<commit_before>#include "ast.hpp"
#include "sexpr.hpp"
#include "either.hpp"
#include "repl.hpp"
#include <map>
#include <functional>
namespace ast {
struct syntax_error: std::runtime_error {
syntax_error(std::string what): std::runtime_error("syntax error: " + what) { }
};
symbol arg::name() const {
return match(*this, [](symbol self) { return self; });
}
////////////////////////////////////////////////////////////////////////////////
// sexpr list parser monad
template<class T>
struct success {
using value_type = T;
value_type value;
sexpr::list rest;
};
template<class T>
using result = either<std::string, success<T>>;
template<class T>
static result<T> make_success(T value, sexpr::list rest) {
return success<T>{value, rest};
}
template<class T>
using monad = std::function<result<T>(sexpr::list)>;
template<class Parser>
using value = typename std::result_of<Parser(sexpr::list)>::type::value_type::value_type;
static const auto pop = [](sexpr::list list) -> result<sexpr> {
if(list) {
return make_success(list->head, list->tail);
}
return std::string("empty list");
};
static const auto empty = [](sexpr::list list) -> result<unit> {
if(list) {
return std::string("non-empty list");
}
return make_success(unit{}, list);
};
template<class T>
static auto expect(sexpr self) {
return [=](sexpr::list rest) -> result<T> {
return match(self,
[=](T expected) -> result<T> {
return make_success(expected, rest);
},
[=](auto) -> result<T> {
return std::string("type error");
});
};
}
template<class LHS, class Func, class=value<LHS>>
static auto bind(LHS lhs, Func func) {
return [=](sexpr::list args) {
return lhs(args) >>= [=](auto head) {
return func(head.value)(head.rest);
};
};
};
template<class LHS, class Func, class=value<LHS>>
static auto map(LHS lhs, Func func) {
return [=](sexpr::list args) {
return lhs(args) >>= [=](auto head) {
return make_success(func(head.value), head.rest);
};
};
};
static const auto pure = [](auto value) {
return [=](sexpr::list rest) { return make_success(value, rest); };
};
template<class Parser, class Func, class=value<Parser>>
static auto operator>>=(Parser parser, Func func) { return bind(parser, func); }
template<class LHS, class RHS, class=value<LHS>, class=value<RHS>>
static auto operator>>(LHS lhs, RHS rhs) {
return lhs >>= [rhs](auto) {
return rhs;
};
}
template<class Parser, class Func, class=value<Parser>>
static auto operator|=(Parser parser, Func func) { return map(parser, func); }
static const auto coproduct = [](auto lhs, auto rhs) {
return [=](sexpr::list args) {
if(auto res = lhs(args)) {
return res;
} else return rhs(args);
};
};
template<class LHS, class RHS, class=value<LHS>, class=value<RHS>>
static auto operator|(LHS lhs, RHS rhs) {
return coproduct(lhs, rhs);
}
template<class T, class Def>
struct fixpoint {
const Def def;
result<T> operator()(sexpr::list args) const {
return def(*this)(args);
};
};
template<class T, class Def>
static fixpoint<T, Def> fix(const Def& def) { return {def}; }
static const auto run = [](auto parser, sexpr::list args) {
if(auto result = parser(args)) {
return result.right().value;
} else {
throw syntax_error(result.left());
}
};
template<class T>
static auto fail(std::string what) {
return [=](sexpr::list) -> result<T> {
return what;
};
};
static auto check_list = [](auto func) {
using func_type = decltype(func);
using result_type = typename std::result_of<func_type(sexpr)>::type;
using value_type = value<result_type>;
using list_type = list<value_type>;
return fix<list_type>([=](auto self) {
return (empty >> pure(list_type{}))
| ((pop >>= func) >>= [=](auto first) {
return self >>= [=](auto rest) {
return pure(first %= rest);
};
});
});
};
////////////////////////////////////////////////////////////////////////////////
// check function arguments
static const auto check_args = check_list([](sexpr item) {
return expect<symbol>(item) |= [](symbol name) {
return ast::arg{name};
};
});
// check function definition
static const auto check_abs =
((pop >>= expect<sexpr::list>) >>= [](sexpr::list args) {
return pop >>= [=](sexpr body) {
return empty >> [=](sexpr::list) -> result<expr> {
return (check_args |= [=](list<ast::arg> args) -> expr {
return abs{args, check(body)};
})(args);
};
};
}) | fail<expr>("(fn (`sym`...) `expr`)");
// conditionals
static const auto check_cond = (pop >>= [](sexpr pred) {
return pop >>= [=](sexpr conseq) {
return pop >>= [=](sexpr alt) {
const expr res = cond{check(pred), check(conseq), check(alt)};
return empty >> pure(res);
};
};
}) | fail<expr>("(if `expr` `expr` `expr`)");
// definition
static const auto check_def = ((pop >>= expect<symbol>) >>= [](symbol name) {
return pop >>= [=](sexpr value) {
return empty >> pure(def{name, check(value)});
};
}) | fail<def>("(`sym` `expr`) expected for definition");
static const auto check_defs = check_list([](sexpr item) {
// TODO prevent redefinitions
return (expect<sexpr::list>(item) |= [](sexpr::list def) {
return run(check_def, def);
}) | fail<def>("((`sym` `expr`)...) expected for definitions");
});
// let
static const auto check_let = ((pop >>= expect<sexpr::list>) >>= [](sexpr::list defs) {
return pop >>= [=](sexpr body) {
const expr res = let{run(check_defs, defs), check(body)};
return empty >> pure(res);
};
}) | fail<expr>("(let ((`sym` `expr`)...) `expr`)");
// open
static const auto check_open = pop >>= [](sexpr arg) {
const expr res = open{check(arg)};
return empty >> pure(res);
};
// record
static const auto check_record = check_defs >>= [](list<ast::def> defs) {
const expr res = record{defs};
return pure(res);
};
// special forms
using special_type = std::function<result<expr>(sexpr::list)>;
static const std::map<symbol, special_type> special = {
{"fn", check_abs},
{"if", check_cond},
{"let", check_let},
{"open", check_open},
{"record", check_record},
};
static expr check_app(sexpr func, sexpr::list args) {
return app{check(func), foldr(args, list<expr>(), [](auto head, auto tail) {
return check(head) %= tail;
})};
}
expr check(const sexpr& e) {
return match(
e,
[](auto self) -> expr { return lit{self}; },
[](attrib self) -> expr {
return attr{check(self.arg), self.name};
},
[](symbol self) -> expr {
static const std::map<symbol, expr> special = {
{"true", lit{true}},
{"false", lit{false}},
};
const auto it = special.find(self);
if(it != special.end()) return it->second;
return var{self};
},
[](sexpr::list self) -> expr {
if(!self) {
throw syntax_error("empty list in application");
}
return match(
self->head,
[=](symbol first) -> expr {
const auto it = special.find(first);
if(it != special.end()) {
return run(it->second, self->tail);
}
return check_app(first, self->tail);
},
[=](sexpr func) -> expr { return check_app(func, self->tail); });
});
}
}
// template<class Cont>
// static void handle(Cont cont, std::ostream& err=std::cerr) try {
// return cont();
// } catch(std::exception& e) {
// err << e.what() << std::endl;
// };
// int main(int, char**) {
// const auto parser = sexpr::parser() >>= drop(parser::eos);
// repl([&](const char* input) {
// return handle([&] {
// const auto s = parser::run(parser, input);
// std::clog << s << std::endl;
// const auto e = ast::check(s);
// });
// });
// return 0;
// }
<commit_msg>slightly cleaner<commit_after>#include "ast.hpp"
#include "sexpr.hpp"
#include "either.hpp"
#include "repl.hpp"
#include <map>
#include <functional>
namespace ast {
struct syntax_error: std::runtime_error {
syntax_error(std::string what): std::runtime_error("syntax error: " + what) { }
};
symbol arg::name() const {
return match(*this, [](symbol self) { return self; });
}
////////////////////////////////////////////////////////////////////////////////
// sexpr list parser monad
template<class T>
struct success {
using value_type = T;
value_type value;
sexpr::list rest;
};
template<class T>
using result = either<std::string, success<T>>;
template<class T>
static result<T> make_success(T value, sexpr::list rest) {
return success<T>{value, rest};
}
template<class T>
using monad = std::function<result<T>(sexpr::list)>;
template<class Parser>
using value = typename std::result_of<Parser(sexpr::list)>::type::value_type::value_type;
static const auto pop = [](sexpr::list list) -> result<sexpr> {
if(list) {
return make_success(list->head, list->tail);
}
return std::string("empty list");
};
static const auto empty = [](sexpr::list list) -> result<unit> {
if(list) {
return std::string("non-empty list");
}
return make_success(unit{}, list);
};
template<class T>
static auto expect(sexpr self) {
return [=](sexpr::list rest) -> result<T> {
return match(self,
[=](T expected) -> result<T> {
return make_success(expected, rest);
},
[=](auto) -> result<T> {
return std::string("type error");
});
};
}
template<class LHS, class Func, class=value<LHS>>
static auto bind(LHS lhs, Func func) {
return [=](sexpr::list args) {
return lhs(args) >>= [=](auto head) {
return func(head.value)(head.rest);
};
};
};
template<class LHS, class Func, class=value<LHS>>
static auto map(LHS lhs, Func func) {
return [=](sexpr::list args) {
return lhs(args) >>= [=](auto head) {
return make_success(func(head.value), head.rest);
};
};
};
static const auto pure = [](auto value) {
return [=](sexpr::list rest) { return make_success(value, rest); };
};
template<class Parser, class Func, class=value<Parser>>
static auto operator>>=(Parser parser, Func func) { return bind(parser, func); }
template<class LHS, class RHS, class=value<LHS>, class=value<RHS>>
static auto operator>>(LHS lhs, RHS rhs) {
return lhs >>= [rhs](auto) {
return rhs;
};
}
template<class Parser, class Func, class=value<Parser>>
static auto operator|=(Parser parser, Func func) { return map(parser, func); }
static const auto coproduct = [](auto lhs, auto rhs) {
return [=](sexpr::list args) {
if(auto res = lhs(args)) {
return res;
} else return rhs(args);
};
};
template<class LHS, class RHS, class=value<LHS>, class=value<RHS>>
static auto operator|(LHS lhs, RHS rhs) {
return coproduct(lhs, rhs);
}
template<class T, class Def>
struct fixpoint {
const Def def;
result<T> operator()(sexpr::list args) const {
return def(*this)(args);
};
};
template<class T, class Def>
static fixpoint<T, Def> fix(const Def& def) { return {def}; }
static const auto run = [](auto parser, sexpr::list args) {
if(auto result = parser(args)) {
return result.right().value;
} else {
throw syntax_error(result.left());
}
};
template<class T>
static auto fail(std::string what) {
return [=](sexpr::list) -> result<T> {
return what;
};
};
template<class M>
static auto sequence(list<M> ms) -> monad<list<value<M>>> {
const monad<list<value<M>>> init = pure(list<value<M>>());
return foldr(ms, init, [](auto head, auto tail) {
return head >>= [=](auto head) {
return tail >>= [=](auto tail) {
return pure(head %= tail);
};
};
});
}
static auto check_list = [](auto func) {
return [=](sexpr::list xs) {
return sequence(map(xs, func))(xs);
};
};
////////////////////////////////////////////////////////////////////////////////
// check function arguments
static const auto check_args = check_list([](sexpr item) {
return expect<symbol>(item) |= [](symbol name) {
return ast::arg{name};
};
});
// check function definition
static const auto check_abs =
((pop >>= expect<sexpr::list>) >>= [](sexpr::list args) {
return pop >>= [=](sexpr body) {
return empty >> [=](sexpr::list) -> result<expr> {
return (check_args |= [=](list<ast::arg> args) -> expr {
return abs{args, check(body)};
})(args);
};
};
}) | fail<expr>("(fn (`sym`...) `expr`)");
// conditionals
static const auto check_cond = (pop >>= [](sexpr pred) {
return pop >>= [=](sexpr conseq) {
return pop >>= [=](sexpr alt) {
const expr res = cond{check(pred), check(conseq), check(alt)};
return empty >> pure(res);
};
};
}) | fail<expr>("(if `expr` `expr` `expr`)");
// definition
static const auto check_def = ((pop >>= expect<symbol>) >>= [](symbol name) {
return pop >>= [=](sexpr value) {
return empty >> pure(def{name, check(value)});
};
}) | fail<def>("(`sym` `expr`) expected for definition");
static const auto check_defs = check_list([](sexpr item) {
// TODO prevent redefinitions
return (expect<sexpr::list>(item) |= [](sexpr::list def) {
return run(check_def, def);
}) | fail<def>("((`sym` `expr`)...) expected for definitions");
});
// let
static const auto check_let = ((pop >>= expect<sexpr::list>) >>= [](sexpr::list defs) {
return pop >>= [=](sexpr body) {
const expr res = let{run(check_defs, defs), check(body)};
return empty >> pure(res);
};
}) | fail<expr>("(let ((`sym` `expr`)...) `expr`)");
// open
static const auto check_open = pop >>= [](sexpr arg) {
const expr res = open{check(arg)};
return empty >> pure(res);
};
// record
static const auto check_record = check_defs >>= [](list<ast::def> defs) {
const expr res = record{defs};
return pure(res);
};
// special forms
using special_type = std::function<result<expr>(sexpr::list)>;
static const std::map<symbol, special_type> special = {
{"fn", check_abs},
{"if", check_cond},
{"let", check_let},
{"open", check_open},
{"record", check_record},
};
static expr check_app(sexpr func, sexpr::list args) {
return app{check(func), foldr(args, list<expr>(), [](auto head, auto tail) {
return check(head) %= tail;
})};
}
expr check(const sexpr& e) {
return match(
e,
[](auto self) -> expr { return lit{self}; },
[](attrib self) -> expr {
return attr{check(self.arg), self.name};
},
[](symbol self) -> expr {
static const std::map<symbol, expr> special = {
{"true", lit{true}},
{"false", lit{false}},
};
const auto it = special.find(self);
if(it != special.end()) return it->second;
return var{self};
},
[](sexpr::list self) -> expr {
if(!self) {
throw syntax_error("empty list in application");
}
return match(
self->head,
[=](symbol first) -> expr {
const auto it = special.find(first);
if(it != special.end()) {
return run(it->second, self->tail);
}
return check_app(first, self->tail);
},
[=](sexpr func) -> expr { return check_app(func, self->tail); });
});
}
}
// template<class Cont>
// static void handle(Cont cont, std::ostream& err=std::cerr) try {
// return cont();
// } catch(std::exception& e) {
// err << e.what() << std::endl;
// };
// int main(int, char**) {
// const auto parser = sexpr::parser() >>= drop(parser::eos);
// repl([&](const char* input) {
// return handle([&] {
// const auto s = parser::run(parser, input);
// std::clog << s << std::endl;
// const auto e = ast::check(s);
// });
// });
// return 0;
// }
<|endoftext|> |
<commit_before>#include <CQHistoryLineEdit.h>
#include <CHistory.h>
#include <QKeyEvent>
CQHistoryLineEdit::
CQHistoryLineEdit(QWidget *parent) :
QLineEdit(parent)
{
history_ = std::make_unique<CHistory>();
connect(this, SIGNAL(returnPressed()), this, SLOT(execSlot()));
}
CQHistoryLineEdit::
~CQHistoryLineEdit()
{
}
void
CQHistoryLineEdit::
execSlot()
{
QString str = text();
emit exec(str);
QString str1 = str.simplified();
if (str1.length())
history_->addCommand(str1.toStdString());
setText("");
}
void
CQHistoryLineEdit::
keyPressEvent(QKeyEvent *event)
{
int key = event->key();
switch (key) {
case Qt::Key_Up: {
std::string cmd;
if (history_->getPrevCommand(cmd))
setText(cmd.c_str());
break;
}
case Qt::Key_Down: {
std::string cmd;
if (history_->getNextCommand(cmd))
setText(cmd.c_str());
break;
}
default:
QLineEdit::keyPressEvent(event);
break;
}
}
<commit_msg>new files<commit_after>#include <CQHistoryLineEdit.h>
#include <CHistory.h>
#include <QKeyEvent>
CQHistoryLineEdit::
CQHistoryLineEdit(QWidget *parent) :
QLineEdit(parent)
{
history_ = std::make_unique<CHistory>();
connect(this, SIGNAL(returnPressed()), this, SLOT(execSlot()));
}
CQHistoryLineEdit::
~CQHistoryLineEdit()
{
}
void
CQHistoryLineEdit::
execSlot()
{
QString str = text();
emit exec(str);
QString str1 = str.trimmed();
if (str1.length())
history_->addCommand(str1.toStdString());
setText("");
}
void
CQHistoryLineEdit::
keyPressEvent(QKeyEvent *event)
{
int key = event->key();
switch (key) {
case Qt::Key_Up: {
std::string cmd;
if (history_->getPrevCommand(cmd))
setText(cmd.c_str());
break;
}
case Qt::Key_Down: {
std::string cmd;
if (history_->getNextCommand(cmd))
setText(cmd.c_str());
break;
}
default:
QLineEdit::keyPressEvent(event);
break;
}
}
<|endoftext|> |
<commit_before>#include <cmath>
//
// Created by Pablo Rodriguez on 3/5/17.
//
int pow(int x, int y) {if(y==1)return x; int res = 1; while(y>0) {res*=x;y--;}return res;}
int main() {
int x = 2;
const int length=5;
int m [length] = {0,1,2,3,4};
//empieza
int e = 1; // contador cantidad de pisos
int dos_pow_e = 1;//eficiencia dos a la e
int n = log2(length); // cantidad pisos
while (e<=n)
{
for (int i=0; i+ dos_pow_e< length;i += 2*dos_pow_e)
{
m[i] += m[i+dos_pow_e]*pow(x,dos_pow_e);
}
e++; dos_pow_e *= 2;
}
if (log2(length) > (double) n) // si no es potencia de 2 le suma el ultimo
m[0] += m[pow(2,n)]*pow(x,dos_pow_e);
return m[0];
}<commit_msg>Function Estrins<commit_after>#include <cmath>
//
// Created by Pablo Rodriguez on 3/5/17.
//
int pow(int x, int y) {if(y==1)return x; int res = 1; while(y>0) {res*=x;y--;}return res;}
int estrins(int x, const int length, int m[]) {
//empieza
int e = 1; // contador cantidad de pisos
int dos_pow_e = 1;//eficiencia dos a la e
int n = log2(length); // cantidad pisos
while (e<=n)
{
for (int i=0; i+ dos_pow_e< length;i += 2*dos_pow_e)
{
m[i] += m[i+dos_pow_e]*pow(x,dos_pow_e);
}
e++; dos_pow_e *= 2;
}
if (log2(length) > (double) n) // si no es potencia de 2 le suma el ultimo
m[0] += m[pow(2,n)]*pow(x,dos_pow_e);
return m[0];
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <atlbase.h>
#include <atlapp.h>
#include <atlmisc.h>
#include "app/gfx/icon_util.h"
#include "base/gfx/size.h"
#include "base/scoped_ptr.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "skia/include/SkBitmap.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
static const wchar_t* const kSmallIconName = L"icon_util\\16_X_16_icon.ico";
static const wchar_t* const kLargeIconName = L"icon_util\\128_X_128_icon.ico";
static const wchar_t* const kTempIconFilename = L"temp_test_icon.ico";
class IconUtilTest : public testing::Test {
public:
IconUtilTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_data_directory_);
}
~IconUtilTest() {}
static const int kSmallIconWidth = 16;
static const int kSmallIconHeight = 16;
static const int kLargeIconWidth = 128;
static const int kLargeIconHeight = 128;
// Given a file name for an .ico file and an image dimentions, this
// function loads the icon and returns an HICON handle.
HICON LoadIconFromFile(const std::wstring& filename,
int width,
int height) {
HICON icon =
static_cast<HICON>(LoadImage(NULL,
filename.c_str(),
IMAGE_ICON,
width,
height,
LR_LOADTRANSPARENT | LR_LOADFROMFILE));
return icon;
}
protected:
// The root directory for test files.
std::wstring test_data_directory_;
private:
DISALLOW_EVIL_CONSTRUCTORS(IconUtilTest);
};
};
// The following test case makes sure IconUtil::SkBitmapFromHICON fails
// gracefully when called with invalid input parameters.
TEST_F(IconUtilTest, TestIconToBitmapInvalidParameters) {
std::wstring icon_filename(test_data_directory_);
file_util::AppendToPath(&icon_filename, kSmallIconName);
gfx::Size icon_size(kSmallIconWidth, kSmallIconHeight);
HICON icon = LoadIconFromFile(icon_filename,
icon_size.width(),
icon_size.height());
ASSERT_TRUE(icon != NULL);
// Invalid size parameter.
gfx::Size invalid_icon_size(kSmallIconHeight, 0);
EXPECT_EQ(IconUtil::CreateSkBitmapFromHICON(icon, invalid_icon_size),
static_cast<SkBitmap*>(NULL));
// Invalid icon.
EXPECT_EQ(IconUtil::CreateSkBitmapFromHICON(NULL, icon_size),
static_cast<SkBitmap*>(NULL));
// The following code should succeed.
scoped_ptr<SkBitmap> bitmap;
bitmap.reset(IconUtil::CreateSkBitmapFromHICON(icon, icon_size));
EXPECT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
::DestroyIcon(icon);
}
// The following test case makes sure IconUtil::CreateHICONFromSkBitmap fails
// gracefully when called with invalid input parameters.
TEST_F(IconUtilTest, TestBitmapToIconInvalidParameters) {
HICON icon = NULL;
scoped_ptr<SkBitmap> bitmap;
// Wrong bitmap format.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kA8_Config, kSmallIconWidth, kSmallIconHeight);
icon = IconUtil::CreateHICONFromSkBitmap(*bitmap);
EXPECT_EQ(icon, static_cast<HICON>(NULL));
// Invalid bitmap size.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kARGB_8888_Config, 0, 0);
icon = IconUtil::CreateHICONFromSkBitmap(*bitmap);
EXPECT_EQ(icon, static_cast<HICON>(NULL));
// Valid bitmap configuration but no pixels allocated.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kARGB_8888_Config,
kSmallIconWidth,
kSmallIconHeight);
icon = IconUtil::CreateHICONFromSkBitmap(*bitmap);
EXPECT_TRUE(icon == NULL);
}
// The following test case makes sure IconUtil::CreateIconFileFromSkBitmap
// fails gracefully when called with invalid input parameters.
TEST_F(IconUtilTest, TestCreateIconFileInvalidParameters) {
scoped_ptr<SkBitmap> bitmap;
std::wstring valid_icon_filename(test_data_directory_);
file_util::AppendToPath(&valid_icon_filename, kSmallIconName);
std::wstring invalid_icon_filename(L"C:\\<>?.ico");
// Wrong bitmap format.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kA8_Config, kSmallIconWidth, kSmallIconHeight);
EXPECT_FALSE(IconUtil::CreateIconFileFromSkBitmap(*bitmap,
valid_icon_filename));
// Invalid bitmap size.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kARGB_8888_Config, 0, 0);
EXPECT_FALSE(IconUtil::CreateIconFileFromSkBitmap(*bitmap,
valid_icon_filename));
// Bitmap with no allocated pixels.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kARGB_8888_Config,
kSmallIconWidth,
kSmallIconHeight);
EXPECT_FALSE(IconUtil::CreateIconFileFromSkBitmap(*bitmap,
valid_icon_filename));
// Invalid file name.
bitmap->allocPixels();
// Setting the pixels to black.
memset(bitmap->getPixels(), 0, bitmap->width() * bitmap->height() * 4);
EXPECT_FALSE(IconUtil::CreateIconFileFromSkBitmap(*bitmap,
invalid_icon_filename));
}
// This test case makes sure that when we load an icon from disk and convert
// the HICON into a bitmap, the bitmap has the expected format and dimentions.
TEST_F(IconUtilTest, TestCreateSkBitmapFromHICON) {
scoped_ptr<SkBitmap> bitmap;
std::wstring small_icon_filename(test_data_directory_);
file_util::AppendToPath(&small_icon_filename, kSmallIconName);
gfx::Size small_icon_size(kSmallIconWidth, kSmallIconHeight);
HICON small_icon = LoadIconFromFile(small_icon_filename,
small_icon_size.width(),
small_icon_size.height());
ASSERT_NE(small_icon, static_cast<HICON>(NULL));
bitmap.reset(IconUtil::CreateSkBitmapFromHICON(small_icon, small_icon_size));
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
EXPECT_EQ(bitmap->width(), small_icon_size.width());
EXPECT_EQ(bitmap->height(), small_icon_size.height());
EXPECT_EQ(bitmap->config(), SkBitmap::kARGB_8888_Config);
::DestroyIcon(small_icon);
std::wstring large_icon_filename(test_data_directory_);
file_util::AppendToPath(&large_icon_filename, kLargeIconName);
gfx::Size large_icon_size(kLargeIconWidth, kLargeIconHeight);
HICON large_icon = LoadIconFromFile(large_icon_filename,
large_icon_size.width(),
large_icon_size.height());
ASSERT_NE(large_icon, static_cast<HICON>(NULL));
bitmap.reset(IconUtil::CreateSkBitmapFromHICON(large_icon, large_icon_size));
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
EXPECT_EQ(bitmap->width(), large_icon_size.width());
EXPECT_EQ(bitmap->height(), large_icon_size.height());
EXPECT_EQ(bitmap->config(), SkBitmap::kARGB_8888_Config);
::DestroyIcon(large_icon);
}
// This test case makes sure that when an HICON is created from an SkBitmap,
// the returned handle is valid and refers to an icon with the expected
// dimentions color depth etc.
TEST_F(IconUtilTest, TestBasicCreateHICONFromSkBitmap) {
scoped_ptr<SkBitmap> bitmap;
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kARGB_8888_Config,
kSmallIconWidth,
kSmallIconHeight);
bitmap->allocPixels();
HICON icon = IconUtil::CreateHICONFromSkBitmap(*bitmap);
EXPECT_NE(icon, static_cast<HICON>(NULL));
ICONINFO icon_info;
ASSERT_TRUE(::GetIconInfo(icon, &icon_info));
EXPECT_TRUE(icon_info.fIcon);
// Now that have the icon information, we should obtain the specification of
// the icon's bitmap and make sure it matches the specification of the
// SkBitmap we started with.
//
// The bitmap handle contained in the icon information is a handle to a
// compatible bitmap so we need to call ::GetDIBits() in order to retrieve
// the bitmap's header information.
BITMAPINFO bitmap_info;
::ZeroMemory(&bitmap_info, sizeof(BITMAPINFO));
bitmap_info.bmiHeader.biSize = sizeof(BITMAPINFO);
HDC hdc = ::GetDC(NULL);
int result = ::GetDIBits(hdc,
icon_info.hbmColor,
0,
kSmallIconWidth,
NULL,
&bitmap_info,
DIB_RGB_COLORS);
ASSERT_GT(result, 0);
EXPECT_EQ(bitmap_info.bmiHeader.biWidth, kSmallIconWidth);
EXPECT_EQ(bitmap_info.bmiHeader.biHeight, kSmallIconHeight);
EXPECT_EQ(bitmap_info.bmiHeader.biPlanes, 1);
EXPECT_EQ(bitmap_info.bmiHeader.biBitCount, 32);
::ReleaseDC(NULL, hdc);
::DestroyIcon(icon);
}
// The following test case makes sure IconUtil::CreateIconFileFromSkBitmap
// creates a valid .ico file given an SkBitmap.
TEST_F(IconUtilTest, TestCreateIconFile) {
scoped_ptr<SkBitmap> bitmap;
std::wstring icon_filename(test_data_directory_);
file_util::AppendToPath(&icon_filename, kTempIconFilename);
// Allocating the bitmap.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kARGB_8888_Config,
kSmallIconWidth,
kSmallIconHeight);
bitmap->allocPixels();
// Setting the pixels to black.
memset(bitmap->getPixels(), 0, bitmap->width() * bitmap->height() * 4);
EXPECT_TRUE(IconUtil::CreateIconFileFromSkBitmap(*bitmap,
icon_filename));
// We are currently only testing that it is possible to load an icon from
// the .ico file we just created. We don't really check the additional icon
// images created by IconUtil::CreateIconFileFromSkBitmap.
HICON icon = LoadIconFromFile(icon_filename,
kSmallIconWidth,
kSmallIconHeight);
EXPECT_NE(icon, static_cast<HICON>(NULL));
if (icon != NULL) {
::DestroyIcon(icon);
}
}
<commit_msg>Remove unneeded ATL header includes.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/gfx/icon_util.h"
#include "base/gfx/size.h"
#include "base/scoped_ptr.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "skia/include/SkBitmap.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
static const wchar_t* const kSmallIconName = L"icon_util\\16_X_16_icon.ico";
static const wchar_t* const kLargeIconName = L"icon_util\\128_X_128_icon.ico";
static const wchar_t* const kTempIconFilename = L"temp_test_icon.ico";
class IconUtilTest : public testing::Test {
public:
IconUtilTest() {
PathService::Get(chrome::DIR_TEST_DATA, &test_data_directory_);
}
~IconUtilTest() {}
static const int kSmallIconWidth = 16;
static const int kSmallIconHeight = 16;
static const int kLargeIconWidth = 128;
static const int kLargeIconHeight = 128;
// Given a file name for an .ico file and an image dimentions, this
// function loads the icon and returns an HICON handle.
HICON LoadIconFromFile(const std::wstring& filename,
int width,
int height) {
HICON icon =
static_cast<HICON>(LoadImage(NULL,
filename.c_str(),
IMAGE_ICON,
width,
height,
LR_LOADTRANSPARENT | LR_LOADFROMFILE));
return icon;
}
protected:
// The root directory for test files.
std::wstring test_data_directory_;
private:
DISALLOW_EVIL_CONSTRUCTORS(IconUtilTest);
};
};
// The following test case makes sure IconUtil::SkBitmapFromHICON fails
// gracefully when called with invalid input parameters.
TEST_F(IconUtilTest, TestIconToBitmapInvalidParameters) {
std::wstring icon_filename(test_data_directory_);
file_util::AppendToPath(&icon_filename, kSmallIconName);
gfx::Size icon_size(kSmallIconWidth, kSmallIconHeight);
HICON icon = LoadIconFromFile(icon_filename,
icon_size.width(),
icon_size.height());
ASSERT_TRUE(icon != NULL);
// Invalid size parameter.
gfx::Size invalid_icon_size(kSmallIconHeight, 0);
EXPECT_EQ(IconUtil::CreateSkBitmapFromHICON(icon, invalid_icon_size),
static_cast<SkBitmap*>(NULL));
// Invalid icon.
EXPECT_EQ(IconUtil::CreateSkBitmapFromHICON(NULL, icon_size),
static_cast<SkBitmap*>(NULL));
// The following code should succeed.
scoped_ptr<SkBitmap> bitmap;
bitmap.reset(IconUtil::CreateSkBitmapFromHICON(icon, icon_size));
EXPECT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
::DestroyIcon(icon);
}
// The following test case makes sure IconUtil::CreateHICONFromSkBitmap fails
// gracefully when called with invalid input parameters.
TEST_F(IconUtilTest, TestBitmapToIconInvalidParameters) {
HICON icon = NULL;
scoped_ptr<SkBitmap> bitmap;
// Wrong bitmap format.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kA8_Config, kSmallIconWidth, kSmallIconHeight);
icon = IconUtil::CreateHICONFromSkBitmap(*bitmap);
EXPECT_EQ(icon, static_cast<HICON>(NULL));
// Invalid bitmap size.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kARGB_8888_Config, 0, 0);
icon = IconUtil::CreateHICONFromSkBitmap(*bitmap);
EXPECT_EQ(icon, static_cast<HICON>(NULL));
// Valid bitmap configuration but no pixels allocated.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kARGB_8888_Config,
kSmallIconWidth,
kSmallIconHeight);
icon = IconUtil::CreateHICONFromSkBitmap(*bitmap);
EXPECT_TRUE(icon == NULL);
}
// The following test case makes sure IconUtil::CreateIconFileFromSkBitmap
// fails gracefully when called with invalid input parameters.
TEST_F(IconUtilTest, TestCreateIconFileInvalidParameters) {
scoped_ptr<SkBitmap> bitmap;
std::wstring valid_icon_filename(test_data_directory_);
file_util::AppendToPath(&valid_icon_filename, kSmallIconName);
std::wstring invalid_icon_filename(L"C:\\<>?.ico");
// Wrong bitmap format.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kA8_Config, kSmallIconWidth, kSmallIconHeight);
EXPECT_FALSE(IconUtil::CreateIconFileFromSkBitmap(*bitmap,
valid_icon_filename));
// Invalid bitmap size.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kARGB_8888_Config, 0, 0);
EXPECT_FALSE(IconUtil::CreateIconFileFromSkBitmap(*bitmap,
valid_icon_filename));
// Bitmap with no allocated pixels.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kARGB_8888_Config,
kSmallIconWidth,
kSmallIconHeight);
EXPECT_FALSE(IconUtil::CreateIconFileFromSkBitmap(*bitmap,
valid_icon_filename));
// Invalid file name.
bitmap->allocPixels();
// Setting the pixels to black.
memset(bitmap->getPixels(), 0, bitmap->width() * bitmap->height() * 4);
EXPECT_FALSE(IconUtil::CreateIconFileFromSkBitmap(*bitmap,
invalid_icon_filename));
}
// This test case makes sure that when we load an icon from disk and convert
// the HICON into a bitmap, the bitmap has the expected format and dimentions.
TEST_F(IconUtilTest, TestCreateSkBitmapFromHICON) {
scoped_ptr<SkBitmap> bitmap;
std::wstring small_icon_filename(test_data_directory_);
file_util::AppendToPath(&small_icon_filename, kSmallIconName);
gfx::Size small_icon_size(kSmallIconWidth, kSmallIconHeight);
HICON small_icon = LoadIconFromFile(small_icon_filename,
small_icon_size.width(),
small_icon_size.height());
ASSERT_NE(small_icon, static_cast<HICON>(NULL));
bitmap.reset(IconUtil::CreateSkBitmapFromHICON(small_icon, small_icon_size));
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
EXPECT_EQ(bitmap->width(), small_icon_size.width());
EXPECT_EQ(bitmap->height(), small_icon_size.height());
EXPECT_EQ(bitmap->config(), SkBitmap::kARGB_8888_Config);
::DestroyIcon(small_icon);
std::wstring large_icon_filename(test_data_directory_);
file_util::AppendToPath(&large_icon_filename, kLargeIconName);
gfx::Size large_icon_size(kLargeIconWidth, kLargeIconHeight);
HICON large_icon = LoadIconFromFile(large_icon_filename,
large_icon_size.width(),
large_icon_size.height());
ASSERT_NE(large_icon, static_cast<HICON>(NULL));
bitmap.reset(IconUtil::CreateSkBitmapFromHICON(large_icon, large_icon_size));
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
EXPECT_EQ(bitmap->width(), large_icon_size.width());
EXPECT_EQ(bitmap->height(), large_icon_size.height());
EXPECT_EQ(bitmap->config(), SkBitmap::kARGB_8888_Config);
::DestroyIcon(large_icon);
}
// This test case makes sure that when an HICON is created from an SkBitmap,
// the returned handle is valid and refers to an icon with the expected
// dimentions color depth etc.
TEST_F(IconUtilTest, TestBasicCreateHICONFromSkBitmap) {
scoped_ptr<SkBitmap> bitmap;
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kARGB_8888_Config,
kSmallIconWidth,
kSmallIconHeight);
bitmap->allocPixels();
HICON icon = IconUtil::CreateHICONFromSkBitmap(*bitmap);
EXPECT_NE(icon, static_cast<HICON>(NULL));
ICONINFO icon_info;
ASSERT_TRUE(::GetIconInfo(icon, &icon_info));
EXPECT_TRUE(icon_info.fIcon);
// Now that have the icon information, we should obtain the specification of
// the icon's bitmap and make sure it matches the specification of the
// SkBitmap we started with.
//
// The bitmap handle contained in the icon information is a handle to a
// compatible bitmap so we need to call ::GetDIBits() in order to retrieve
// the bitmap's header information.
BITMAPINFO bitmap_info;
::ZeroMemory(&bitmap_info, sizeof(BITMAPINFO));
bitmap_info.bmiHeader.biSize = sizeof(BITMAPINFO);
HDC hdc = ::GetDC(NULL);
int result = ::GetDIBits(hdc,
icon_info.hbmColor,
0,
kSmallIconWidth,
NULL,
&bitmap_info,
DIB_RGB_COLORS);
ASSERT_GT(result, 0);
EXPECT_EQ(bitmap_info.bmiHeader.biWidth, kSmallIconWidth);
EXPECT_EQ(bitmap_info.bmiHeader.biHeight, kSmallIconHeight);
EXPECT_EQ(bitmap_info.bmiHeader.biPlanes, 1);
EXPECT_EQ(bitmap_info.bmiHeader.biBitCount, 32);
::ReleaseDC(NULL, hdc);
::DestroyIcon(icon);
}
// The following test case makes sure IconUtil::CreateIconFileFromSkBitmap
// creates a valid .ico file given an SkBitmap.
TEST_F(IconUtilTest, TestCreateIconFile) {
scoped_ptr<SkBitmap> bitmap;
std::wstring icon_filename(test_data_directory_);
file_util::AppendToPath(&icon_filename, kTempIconFilename);
// Allocating the bitmap.
bitmap.reset(new SkBitmap);
ASSERT_NE(bitmap.get(), static_cast<SkBitmap*>(NULL));
bitmap->setConfig(SkBitmap::kARGB_8888_Config,
kSmallIconWidth,
kSmallIconHeight);
bitmap->allocPixels();
// Setting the pixels to black.
memset(bitmap->getPixels(), 0, bitmap->width() * bitmap->height() * 4);
EXPECT_TRUE(IconUtil::CreateIconFileFromSkBitmap(*bitmap,
icon_filename));
// We are currently only testing that it is possible to load an icon from
// the .ico file we just created. We don't really check the additional icon
// images created by IconUtil::CreateIconFileFromSkBitmap.
HICON icon = LoadIconFromFile(icon_filename,
kSmallIconWidth,
kSmallIconHeight);
EXPECT_NE(icon, static_cast<HICON>(NULL));
if (icon != NULL) {
::DestroyIcon(icon);
}
}
<|endoftext|> |
<commit_before>#include <vtkPolyData.h>
#include <vtkMultiBlockPLOT3DReader.h>
#include <vtkMultiBlockDataSet.h>
#include <vtkSmartPointer.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkStructuredGridGeometryFilter.h>
int main ( int argc, char *argv[] )
{
if(argc < 3)
{
std::cout << "Required parameters: XYZFilename.bin QFileName.bin" << std::endl;
return EXIT_FAILURE;
}
std::string xyzFilename = argv[1];
std::string qFilename = argv[2];
vtkSmartPointer<vtkMultiBlockPLOT3DReader> reader =
vtkSmartPointer<vtkMultiBlockPLOT3DReader>::New();
reader->SetXYZFileName(xyzFilename.c_str());
reader->SetQFileName(qFilename.c_str());
reader->SetScalarFunctionNumber(100);
reader->SetVectorFunctionNumber(202);
reader->Update();
vtkSmartPointer<vtkStructuredGridGeometryFilter> geometryFilter =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
geometryFilter->SetInputData(reader->GetOutput()->GetBlock(0));
geometryFilter->Update();
// Visualize
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(geometryFilter->GetOutputPort());
mapper->ScalarVisibilityOff();
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
renderer->AddActor(actor);
renderer->SetBackground(.3, .6, .3); // Background color green
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
<commit_msg>Update ReadPLOT3D.cxx<commit_after>#include <vtkPolyData.h>
#include <vtkMultiBlockPLOT3DReader.h>
#include <vtkMultiBlockDataSet.h>
#include <vtkSmartPointer.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkStructuredGridGeometryFilter.h>
int main ( int argc, char *argv[] )
{
if(argc < 3)
{
std::cout << "Required parameters: XYZFilename.bin QFileName.bin e.g combxyz.bin combq.bin" << std::endl;
return EXIT_FAILURE;
}
std::string xyzFilename = argv[1];
std::string qFilename = argv[2];
vtkSmartPointer<vtkMultiBlockPLOT3DReader> reader =
vtkSmartPointer<vtkMultiBlockPLOT3DReader>::New();
reader->SetXYZFileName(xyzFilename.c_str());
reader->SetQFileName(qFilename.c_str());
reader->SetScalarFunctionNumber(100);
reader->SetVectorFunctionNumber(202);
reader->Update();
vtkSmartPointer<vtkStructuredGridGeometryFilter> geometryFilter =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
geometryFilter->SetInputData(reader->GetOutput()->GetBlock(0));
geometryFilter->Update();
// Visualize
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(geometryFilter->GetOutputPort());
mapper->ScalarVisibilityOff();
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
renderer->AddActor(actor);
renderer->SetBackground(.3, .6, .3); // Background color green
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#pragma once
/*
MIT License
Copyright (c) 2017 Blockchain-VCS
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 "platform.hpp" // Platform Specific Stuff NOTE: Must Always be the first include in a file
#include <map> // std::map
#include <string> // std::string
#include <ctime> // time_t localtime() struct tm* asctime()
#include <chrono> // std::chrono::high_resolution_clock, std::chrono::duration_cast, std::chrono::nanoseconds
#include <stdexcept> // throw throw std::runtime_error()
#include "transactions/transaction.hpp"
#include "transactions/transactiondata.hpp"
namespace BlockchainCpp {
class BlockData {
public:
virtual std::string computeHash() = 0;
virtual std::vector<unsigned char> toBytes() = 0;
virtual std::string toString() = 0;
virtual bool verify() = 0;
virtual bool lock() = 0;
protected:
std::string hash = "";
std::map<std::string, Transaction<TransactionData*>*> transactions = std::map<std::string, Transaction<TransactionData*>*>();
unsigned long size = -1;
unsigned long transactionCount = -1;
unsigned long bits = -1;
time_t timeCreated = -1;
time_t timeRecieved = -1;
time_t timeLocked = -1;
private:
};
}<commit_msg>Fix Variable Ordering<commit_after>#pragma once
/*
MIT License
Copyright (c) 2017 Blockchain-VCS
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 "platform.hpp" // Platform Specific Stuff NOTE: Must Always be the first include in a file
#include <map> // std::map
#include <string> // std::string
#include <ctime> // time_t localtime() struct tm* asctime()
#include <chrono> // std::chrono::high_resolution_clock, std::chrono::duration_cast, std::chrono::nanoseconds
#include <stdexcept> // throw throw std::runtime_error()
#include "transactions/transaction.hpp"
#include "transactions/transactiondata.hpp"
namespace BlockchainCpp {
class BlockData {
public:
virtual std::string computeHash() = 0;
virtual std::vector<unsigned char> toBytes() = 0;
virtual std::string toString() = 0;
virtual bool verify() = 0;
virtual bool lock() = 0;
protected:
std::string hash = "";
unsigned long transactionCount = -1;
std::map<std::string, Transaction<TransactionData*>*> transactions = std::map<std::string, Transaction<TransactionData*>*>();
unsigned long size = -1;
unsigned long bits = -1;
time_t timeCreated = -1;
time_t timeRecieved = -1;
time_t timeLocked = -1;
private:
};
}<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013 Daniel Mansfield
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef AREA_HPP
#define AREA_HPP
#include "entity.hpp"
#include "inventory.hpp"
#include "creature.hpp"
#include "dialogue.hpp"
#include <vector>
// Movement is achieved through the use of areas, which are contained
// units of space consisting of an inventory, a list of creatures and
// a dialogue
class Area : public Entity
{
public:
// Dialogue is run whenever the area is entered
Dialogue dialogue;
// Items contained within the area. Not split into individual containers
// for simplicity
Inventory items;
// Creatures contained within the area. Currently this is limited
// to just one creature due to how the battle system works, but it
// made sense to set it up as a vector from the start to simplify
// things later
std::vector<Creature*> creatures;
// true if the player has visited the area, and hence it needs saving
bool visited;
Area(std::string id, Dialogue dialogue, Inventory items,
std::vector<Creature*> creatures) : Entity(id)
{
this->dialogue = dialogue;
this->items = items;
this->creatures = creatures;
this->visited = false;
}
Area() : Entity("nullid")
{
}
Area(std::string id, JsonBox::Value v,
std::map<std::string, Item>& itemAtlas,
std::map<std::string, Weapon>& weaponAtlas,
std::map<std::string, Armour>& armourAtlas,
std::map<std::string, Creature>& creatureAtlas) : Entity(id)
{
this->load(id, v, itemAtlas, weaponAtlas, armourAtlas, creatureAtlas);
this->visited = false;
}
// Search the area for items and give them to the searcher, notifying
// them of their rewards
void search(Creature& player)
{
std::cout << "You find:" << std::endl;
this->items.print();
player.inventory.merge(&(this->items));
this->items.clear();
return;
}
void load(std::string id, JsonBox::Value v,
std::map<std::string, Item>& itemAtlas,
std::map<std::string, Weapon>& weaponAtlas,
std::map<std::string, Armour>& armourAtlas,
std::map<std::string, Creature>& creatureAtlas)
{
JsonBox::Object o = v.getObject();
// Build the dialogue
// This is an optional parameter because it will not be saved
// when the area is modified
if(o.find("dialogue") != o.end())
{
JsonBox::Object dialogue = o["dialogue"].getObject();
std::string dialogue_description = dialogue["description"].getString();
std::vector<std::string> dialogue_choices;
for(auto choice : dialogue["choices"].getArray())
{
dialogue_choices.push_back(choice.getString());
}
this->dialogue = Dialogue(dialogue_description, dialogue_choices);
}
// Build the inventory
this->items = Inventory(o["inventory"], itemAtlas, weaponAtlas, armourAtlas);
// Build the creature list
for(auto creature : o["creatures"].getArray())
{
this->creatures.push_back(&creatureAtlas[creature.getString()]);
}
Entity::load(id, v);
return;
}
JsonBox::Object to_json()
{
JsonBox::Object o;
// We don't need to save the dialogue because it doesn't change
// Save the inventory
o["inventory"] = this->items.to_json().getValue();
// Save the creatures
JsonBox::Array a;
for(auto creature : this->creatures)
{
a.push_back(JsonBox::String(creature->id));
}
o["creatures"] = a.getValue();
return o;
}
};
#endif /* AREA_HPP */
<commit_msg>Fixed awful mistakes in the `Area` saving<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013 Daniel Mansfield
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef AREA_HPP
#define AREA_HPP
#include "entity.hpp"
#include "inventory.hpp"
#include "creature.hpp"
#include "dialogue.hpp"
#include <vector>
// Movement is achieved through the use of areas, which are contained
// units of space consisting of an inventory, a list of creatures and
// a dialogue
class Area : public Entity
{
public:
// Dialogue is run whenever the area is entered
Dialogue dialogue;
// Items contained within the area. Not split into individual containers
// for simplicity
Inventory items;
// Creatures contained within the area. Currently this is limited
// to just one creature due to how the battle system works, but it
// made sense to set it up as a vector from the start to simplify
// things later
std::vector<Creature*> creatures;
// true if the player has visited the area, and hence it needs saving
bool visited;
Area(std::string id, Dialogue dialogue, Inventory items,
std::vector<Creature*> creatures) : Entity(id)
{
this->dialogue = dialogue;
this->items = items;
this->creatures = creatures;
this->visited = false;
}
Area() : Entity("nullid")
{
}
Area(std::string id, JsonBox::Value v,
std::map<std::string, Item>& itemAtlas,
std::map<std::string, Weapon>& weaponAtlas,
std::map<std::string, Armour>& armourAtlas,
std::map<std::string, Creature>& creatureAtlas) : Entity(id)
{
this->load(id, v, itemAtlas, weaponAtlas, armourAtlas, creatureAtlas);
this->visited = false;
}
// Search the area for items and give them to the searcher, notifying
// them of their rewards
void search(Creature& player)
{
std::cout << "You find:" << std::endl;
this->items.print();
player.inventory.merge(&(this->items));
this->items.clear();
return;
}
void load(std::string id, JsonBox::Value v,
std::map<std::string, Item>& itemAtlas,
std::map<std::string, Weapon>& weaponAtlas,
std::map<std::string, Armour>& armourAtlas,
std::map<std::string, Creature>& creatureAtlas)
{
JsonBox::Object o = v.getObject();
// Build the dialogue
// This is an optional parameter because it will not be saved
// when the area is modified
if(o.find("dialogue") != o.end())
{
JsonBox::Object dialogue = o["dialogue"].getObject();
std::string dialogue_description = dialogue["description"].getString();
std::vector<std::string> dialogue_choices;
for(auto choice : dialogue["choices"].getArray())
{
dialogue_choices.push_back(choice.getString());
}
this->dialogue = Dialogue(dialogue_description, dialogue_choices);
}
// Build the inventory
this->items = Inventory(o["inventory"], itemAtlas, weaponAtlas, armourAtlas);
// Build the creature list
for(auto creature : o["creatures"].getArray())
{
this->creatures.push_back(&creatureAtlas[creature.getString()]);
}
Entity::load(id, v);
return;
}
JsonBox::Object to_json()
{
JsonBox::Object o;
// We don't need to save the dialogue because it doesn't change
// Save the inventory
o["inventory"] = this->items.to_json();
// Save the creatures
JsonBox::Array a;
for(auto creature : this->creatures)
{
a.push_back(JsonBox::Value(creature->id));
}
o["creatures"] = a;
return o;
}
};
#endif /* AREA_HPP */
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include "PointContactDZ.h"
#include "iostream"
#include "Units.h"
using namespace GeFiCa;
using namespace std;
//for the case which point contact may not fall right on the grid, it will case
//a great different potential on space close to point contact the current
//design does not include when point contact is close to boundary of the whole
//detector.
PointContactDZ::PointContactDZ(int nd, int nz, const char *name,
const char *title) : RhoZ(nd, nz, name, title),
Height(5*cm),
Radius(3*cm),
PointContactH(0.01*cm),
PointContactR(0.1*cm),
HoleH(0),
HoleInnerR(0),
HoleOuterR(0),
TaperW(0.3*cm),
TaperH(0.3*cm),
CornerW(0.3*cm),
CornerH(0.3*cm),
WrapArroundR(0.5*cm) {};
//_____________________________________________________________________________
//
void PointContactDZ::SetBoundary()
{
for(int i=0;i<n;i++)
{
if(fC2[i]-PointContactH<fdC2m[i]&&fC2[i]>PointContactH&&fC1[i]<PointContactR&&fC1[i]>-PointContactR)
{
fdC2m[i]=fC2[i]-PointContactH;
}
if(fC1[i]-PointContactR<fdC1m[i]&&fC1[i]>0&&fC2[i]<PointContactH)
{
fdC1m[i]=fC1[i]-PointContactR;
}
if(-fC1[i]-PointContactR<fdC1p[i]&&fC1[i]<0&&fC2[i]<PointContactH)
{
fdC1p[i]=-fC1[i]-PointContactR;
}
if(WrapArroundR-fC1[i]<fdC1p[i]&&fC1[i]<WrapArroundR)
{
fdC1p[i]=WrapArroundR-fC1[i];
}
if(WrapArroundR+fC1[i]<fdC1p[i]&&fC1[i]>-WrapArroundR)
{
fdC1p[i]=WrapArroundR+fC1[i];
}
}
double k=TaperH/(TaperW);
double b=-(Radius-TaperW)*k;
for(int i=0;i<n;i++)
{
if(fC2[i]<=fC1[i]*k+b)
{
fIsFixed[i]=true;
fV[i]=V0;
}
if(fC2[i]<=-fC1[i]*k+b)
{
fIsFixed[i]=true;
fV[i]=V0;
}
if(fC2[i]-(fC1[i]*k+b)<fdC2m[i])
{
fdC2m[i]=fC2[i]-(k*fC1[i]+b);
fdC1p[i]=fC2[i]-b-k*fC1[i];
}
if(fC2[i]-(-k*fC1[i]+b)<fdC2m[i])
{
fdC2m[i]=fC2[i]-(-fC1[i]*k+b);
fdC1m[i]=-fC2[i]*k+b-fC1[i];
}
}
double x1=HoleOuterR,
y1=Height,
x2=HoleInnerR,
y2=Height-HoleH,
x3=Radius-CornerW,
y3=Height,
x4=Radius,
y4=Height-CornerH;
// y = k x + b
double k1=(y1-y2)/(x1-x2);
double b1=y1-k1*x1;
double k2=(y3-y4)/(x3-x4);
double b2=y3-k2*x3;
for (int i=0;i<n;i++) {
//right side of hole
if(fC1[i]-fC2[i]/k1+b1/k1<fdC1m[i] && fC2[i]>y2 &&
fC1[i]-fC2[i]/k1+b1/k1>0) fdC1m[i]=fC1[i]-fC2[i]/k1+b1/k1;
//left corner
if(fC1[i]+fC2[i]/k2-b2/k2>0 && fC1[i]+fC2[i]/k2-b2/k2<fdC1m[i] &&
fC2[i]>y4) fdC1m[i]=fC1[i]+fC2[i]/k2-b2/k2;
//left side of hole
if(-fC1[i]-fC2[i]/k1+b1/k1>0&&-fC1[i]-fC2[i]/k1+b1/k1<fdC1p[i]&&fC2[i]>y2)
fdC1p[i]=-fC1[i]-fC2[i]/k1+b1/k1;
//right corner
if(-fC1[i]+fC2[i]/k2-b2/k2>0&&-fC1[i]+fC2[i]/k2-b2/k2<fdC1p[i]&&fC2[i]>y4)
fdC1p[i]=-fC1[i]+fC2[i]/k2-b2/k2;
//down right side of hole
if(-fC2[i]+fC1[i]*k1+b1>0&&-fC2[i]+fC1[i]*k1+b1<fdC2p[i]&&fC2[i]>y2)
fdC2p[i]=-fC2[i]+fC1[i]*k1+b1;
//down right of corner
if(-fC2[i]-fC1[i]*k2+b2>0&&-fC2[i]-fC1[i]*k2+b2<fdC2p[i]&&fC2[i]>y4)
fdC2p[i]=-fC2[i]-fC1[i]*k2+b2;
//down left side of hole
if(-fC2[i]-fC1[i]*k1+b1>0&&-fC2[i]-fC1[i]*k1+b1<fdC2p[i]&&fC2[i]>y2)
fdC2p[i]=-fC2[i]-fC1[i]*k1+b1;
//down left of corner
if(-fC2[i]+fC1[i]*k2+b2>0&&-fC2[i]+fC1[i]*k2+b2<fdC2p[i]&&fC2[i]>y4)
fdC2p[i]=-fC2[i]+fC1[i]*k2+b2;
//down center of hole
if(y2-fC2[i]<fdC2p[i]&&fC1[i]>-HoleInnerR&&fC1[i]<HoleInnerR)
fdC2p[i]=y2-fC2[i];
}
}
//_____________________________________________________________________________
//
void PointContactDZ::Initialize()
{
// we want no grid point right on z-axis
if (n1%2==1) Fatal("Initialize", "Number of points in D cannot be odd!");
SetStepLength(2*Radius/(n1-1),Height/(n2-1));
for(int i=n;i-->0;) fC1[i]=fC1[i]-Radius;
// set initial potential values
for(int i=n;i-->0;) {
fV[i]=(V0+V1)/2;
// set potential for inner electrodes
if(fC1[i]>=-PointContactR && fC1[i]<=RointContactR
&& fC2[i]<=PointContactH) {
fV[i]=V1;
fIsFixed[i]=true;
}
}
// set potential for outer electrodes
for(int i=n-1;i>=n-n1;i--) {
fIsFixed[i]=true;
fV[i]=V0;
}
for(int i=0;i<n-n1;i=i+n1) {
fIsFixed[i]=true;
fIsFixed[i+n1-1]=true;
fV[i]=V0;
fV[i+n1-1]=V0;
}
for (int i=0;i<n1;i++) {
if(fC1[i]>=WrapArroundR||fC1[i]<=-WrapArroundR) {
fIsFixed[i]=true;
fV[i]=V0;
}
}
double x1=HoleOuterR,
y1=Height,
x2=HoleInnerR,
y2=Height-HoleH,
x3=Radius-CornerW,
y3=Height,
x4=Radius,
y4=Height-CornerH;
double k1=(y1-y2)/(x1-x2);
double b1=y1-k1*x1;
double k2=(y3-y4)/(x3-x4);
double b2=(y3-k2*x3);
for (int i=0;i<n;i++) {
if(((fC2[i]>-k1*(fC1[i])+b1
&& fC2[i]>y2)||(fC2[i]>-k2*(fC1[i])+b2))&&fC1[i]<0) {
fIsFixed[i]=true;
fV[i]=V0;
}
if(((fC2[i]>k1*(fC1[i])+b1
&& fC2[i]>y2)||(fC2[i]>k2*(fC1[i])+b2))&&fC1[i]>0) {
fIsFixed[i]=true;
fV[i]=V0;
}
}
SetBoundary();
}
//_____________________________________________________________________________
//
bool PointContactDZ::CalculateField(int idx)
{
if (!XY::CalculateField(idx)) return false;
if (fC2[idx]>PointContactH-fdC2m[idx]
&& fC2[idx]<PointContactH+fdC2p[idx]) // PC top boundary
fE2[idx]=(fV[idx]-fV[idx+n1])/fdC2p[idx];
if (fC1[idx]>-PointContactR-fdC1m[idx]
&& fC1[idx]<-PointContactR+fdC1p[idx]) // PC left boundary
fE1[idx]=(fV[idx]-fV[idx-1])/fdC1m[idx];
if (fC1[idx]>PointContactR-fdC1m[idx]
&& fC1[idx]<PointContactR+fdC1p[idx]) // PC right boundary
fE1[idx]=(fV[idx]-fV[idx+1])/fdC1p[idx];
return true;
}
//_____________________________________________________________________________
//
#include <fstream>
bool PointContactDZ::SaveFieldAsFieldgen(const char * fout)
{
ofstream outfile(fout);
outfile<<"# height "<< Height;
outfile<<"\n# xtal_radius "<<Radius;
outfile<<"\n# pc_length "<<PointContactH;
outfile<<"\n# pc_radius "<<PointContactR;
outfile<<"\n# wrap_around_radius "<<WrapArroundR;
outfile<<"\n# grid size on r "<<fdC1p[0];
outfile<<"\n# grid size on z "<<fdC2p[0];
outfile<<"\n# impurity_z0 "<<fImpurity[0];
outfile<<"\n# xtal_HV "<<V1;
outfile<<"\n# max_iterations "<<MaxIterations;
outfile<<"\n# ";
outfile<<"\n## r (mm), z (mm), V (V), E (V/cm), E_r (V/cm), E_z (V/cm)";
for (int i=0;i<n;i++) {
double E=sqrt(fE1[i]*fE1[i]+fE2[i]*fE2[i]);
outfile<<"\n"<<fC1[i]<<" "<<fC2[i]<<" "<<fV[i]<<" "<<E<<" "<<fE1[i]<<" "<<fE2[i];
}
outfile.close();
return true;
}
<commit_msg>bug fixed<commit_after>#include <stdlib.h>
#include "PointContactDZ.h"
#include "iostream"
#include "Units.h"
using namespace GeFiCa;
using namespace std;
//for the case which point contact may not fall right on the grid, it will case
//a great different potential on space close to point contact the current
//design does not include when point contact is close to boundary of the whole
//detector.
PointContactDZ::PointContactDZ(int nd, int nz, const char *name,
const char *title) : RhoZ(nd, nz, name, title),
Height(5*cm),
Radius(3*cm),
PointContactH(0.01*cm),
PointContactR(0.1*cm),
HoleH(0),
HoleInnerR(0),
HoleOuterR(0),
TaperW(0.3*cm),
TaperH(0.3*cm),
CornerW(0.3*cm),
CornerH(0.3*cm),
WrapArroundR(0.5*cm) {};
//_____________________________________________________________________________
//
void PointContactDZ::SetBoundary()
{
for(int i=0;i<n;i++)
{
if(fC2[i]-PointContactH<fdC2m[i]&&fC2[i]>PointContactH&&fC1[i]<PointContactR&&fC1[i]>-PointContactR)
{
fdC2m[i]=fC2[i]-PointContactH;
}
if(fC1[i]-PointContactR<fdC1m[i]&&fC1[i]>0&&fC2[i]<PointContactH)
{
fdC1m[i]=fC1[i]-PointContactR;
}
if(-fC1[i]-PointContactR<fdC1p[i]&&fC1[i]<0&&fC2[i]<PointContactH)
{
fdC1p[i]=-fC1[i]-PointContactR;
}
if(WrapArroundR-fC1[i]<fdC1p[i]&&fC1[i]<WrapArroundR)
{
fdC1p[i]=WrapArroundR-fC1[i];
}
if(WrapArroundR+fC1[i]<fdC1p[i]&&fC1[i]>-WrapArroundR)
{
fdC1p[i]=WrapArroundR+fC1[i];
}
}
double k=TaperH/(TaperW);
double b=-(Radius-TaperW)*k;
for(int i=0;i<n;i++)
{
if(fC2[i]<=fC1[i]*k+b)
{
fIsFixed[i]=true;
fV[i]=V0;
}
if(fC2[i]<=-fC1[i]*k+b)
{
fIsFixed[i]=true;
fV[i]=V0;
}
if(fC2[i]-(fC1[i]*k+b)<fdC2m[i])
{
fdC2m[i]=fC2[i]-(k*fC1[i]+b);
fdC1p[i]=fC2[i]-b-k*fC1[i];
}
if(fC2[i]-(-k*fC1[i]+b)<fdC2m[i])
{
fdC2m[i]=fC2[i]-(-fC1[i]*k+b);
fdC1m[i]=-fC2[i]*k+b-fC1[i];
}
}
double x1=HoleOuterR,
y1=Height,
x2=HoleInnerR,
y2=Height-HoleH,
x3=Radius-CornerW,
y3=Height,
x4=Radius,
y4=Height-CornerH;
// y = k x + b
double k1=(y1-y2)/(x1-x2);
double b1=y1-k1*x1;
double k2=(y3-y4)/(x3-x4);
double b2=y3-k2*x3;
for (int i=0;i<n;i++) {
//right side of hole
if(fC1[i]-fC2[i]/k1+b1/k1<fdC1m[i] && fC2[i]>y2 &&
fC1[i]-fC2[i]/k1+b1/k1>0) fdC1m[i]=fC1[i]-fC2[i]/k1+b1/k1;
//left corner
if(fC1[i]+fC2[i]/k2-b2/k2>0 && fC1[i]+fC2[i]/k2-b2/k2<fdC1m[i] &&
fC2[i]>y4) fdC1m[i]=fC1[i]+fC2[i]/k2-b2/k2;
//left side of hole
if(-fC1[i]-fC2[i]/k1+b1/k1>0&&-fC1[i]-fC2[i]/k1+b1/k1<fdC1p[i]&&fC2[i]>y2)
fdC1p[i]=-fC1[i]-fC2[i]/k1+b1/k1;
//right corner
if(-fC1[i]+fC2[i]/k2-b2/k2>0&&-fC1[i]+fC2[i]/k2-b2/k2<fdC1p[i]&&fC2[i]>y4)
fdC1p[i]=-fC1[i]+fC2[i]/k2-b2/k2;
//down right side of hole
if(-fC2[i]+fC1[i]*k1+b1>0&&-fC2[i]+fC1[i]*k1+b1<fdC2p[i]&&fC2[i]>y2)
fdC2p[i]=-fC2[i]+fC1[i]*k1+b1;
//down right of corner
if(-fC2[i]-fC1[i]*k2+b2>0&&-fC2[i]-fC1[i]*k2+b2<fdC2p[i]&&fC2[i]>y4)
fdC2p[i]=-fC2[i]-fC1[i]*k2+b2;
//down left side of hole
if(-fC2[i]-fC1[i]*k1+b1>0&&-fC2[i]-fC1[i]*k1+b1<fdC2p[i]&&fC2[i]>y2)
fdC2p[i]=-fC2[i]-fC1[i]*k1+b1;
//down left of corner
if(-fC2[i]+fC1[i]*k2+b2>0&&-fC2[i]+fC1[i]*k2+b2<fdC2p[i]&&fC2[i]>y4)
fdC2p[i]=-fC2[i]+fC1[i]*k2+b2;
//down center of hole
if(y2-fC2[i]<fdC2p[i]&&fC1[i]>-HoleInnerR&&fC1[i]<HoleInnerR)
fdC2p[i]=y2-fC2[i];
}
}
//_____________________________________________________________________________
//
void PointContactDZ::Initialize()
{
// we want no grid point right on z-axis
if (n1%2==1) Fatal("Initialize", "Number of points in D cannot be odd!");
SetStepLength(2*Radius/(n1-1),Height/(n2-1));
for(int i=n;i-->0;) fC1[i]=fC1[i]-Radius;
// set initial potential values
for(int i=n;i-->0;) {
fV[i]=(V0+V1)/2;
// set potential for inner electrodes
if(fC1[i]>=-PointContactR && fC1[i]<=PointContactR
&& fC2[i]<=PointContactH) {
fV[i]=V1;
fIsFixed[i]=true;
}
}
// set potential for outer electrodes
for(int i=n-1;i>=n-n1;i--) {
fIsFixed[i]=true;
fV[i]=V0;
}
for(int i=0;i<n-n1;i=i+n1) {
fIsFixed[i]=true;
fIsFixed[i+n1-1]=true;
fV[i]=V0;
fV[i+n1-1]=V0;
}
for (int i=0;i<n1;i++) {
if(fC1[i]>=WrapArroundR||fC1[i]<=-WrapArroundR) {
fIsFixed[i]=true;
fV[i]=V0;
}
}
double x1=HoleOuterR,
y1=Height,
x2=HoleInnerR,
y2=Height-HoleH,
x3=Radius-CornerW,
y3=Height,
x4=Radius,
y4=Height-CornerH;
double k1=(y1-y2)/(x1-x2);
double b1=y1-k1*x1;
double k2=(y3-y4)/(x3-x4);
double b2=(y3-k2*x3);
for (int i=0;i<n;i++) {
if(((fC2[i]>-k1*(fC1[i])+b1
&& fC2[i]>y2)||(fC2[i]>-k2*(fC1[i])+b2))&&fC1[i]<0) {
fIsFixed[i]=true;
fV[i]=V0;
}
if(((fC2[i]>k1*(fC1[i])+b1
&& fC2[i]>y2)||(fC2[i]>k2*(fC1[i])+b2))&&fC1[i]>0) {
fIsFixed[i]=true;
fV[i]=V0;
}
}
SetBoundary();
}
//_____________________________________________________________________________
//
bool PointContactDZ::CalculateField(int idx)
{
if (!XY::CalculateField(idx)) return false;
if (fC2[idx]>PointContactH-fdC2m[idx]
&& fC2[idx]<PointContactH+fdC2p[idx]) // PC top boundary
fE2[idx]=(fV[idx]-fV[idx+n1])/fdC2p[idx];
if (fC1[idx]>-PointContactR-fdC1m[idx]
&& fC1[idx]<-PointContactR+fdC1p[idx]) // PC left boundary
fE1[idx]=(fV[idx]-fV[idx-1])/fdC1m[idx];
if (fC1[idx]>PointContactR-fdC1m[idx]
&& fC1[idx]<PointContactR+fdC1p[idx]) // PC right boundary
fE1[idx]=(fV[idx]-fV[idx+1])/fdC1p[idx];
return true;
}
//_____________________________________________________________________________
//
#include <fstream>
bool PointContactDZ::SaveFieldAsFieldgen(const char * fout)
{
ofstream outfile(fout);
outfile<<"# height "<< Height;
outfile<<"\n# xtal_radius "<<Radius;
outfile<<"\n# pc_length "<<PointContactH;
outfile<<"\n# pc_radius "<<PointContactR;
outfile<<"\n# wrap_around_radius "<<WrapArroundR;
outfile<<"\n# grid size on r "<<fdC1p[0];
outfile<<"\n# grid size on z "<<fdC2p[0];
outfile<<"\n# impurity_z0 "<<fImpurity[0];
outfile<<"\n# xtal_HV "<<V1;
outfile<<"\n# max_iterations "<<MaxIterations;
outfile<<"\n# ";
outfile<<"\n## r (mm), z (mm), V (V), E (V/cm), E_r (V/cm), E_z (V/cm)";
for (int i=0;i<n;i++) {
double E=sqrt(fE1[i]*fE1[i]+fE2[i]*fE2[i]);
outfile<<"\n"<<fC1[i]<<" "<<fC2[i]<<" "<<fV[i]<<" "<<E<<" "<<fE1[i]<<" "<<fE2[i];
}
outfile.close();
return true;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#include "paddle/fluid/operators/unfold_op.h"
namespace paddle {
namespace operators {
class UnfoldOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X",
"Tensor, "
"the input of unfold op. "
"The format of X is [N, C_in, H, W], "
"where N is the batch size, C_in is the input channels, "
"H is the height and W is the width");
AddOutput(
"Y",
"Tensor, "
"the output of unfold op. "
"The format of Y is [N, C_in*filter_height*filter_width, "
"output_height*output_width], where N is the batch size, "
"C_in is the input channels of X, filter_height and filter_width is "
"height and width of the filtering kernel, output_height and "
"output_width "
"is the calculated height and width of output feature map.");
AddAttr<std::vector<int>>(
"kernel_sizes",
"vector<int>, the kernel sizes of the convolution operator.");
AddAttr<std::vector<int>>(
"strides", "vector<int>, the strides of the convolution operator.");
AddAttr<std::vector<int>>(
"paddings",
"vector<int>, the paddings applied to pad the feature map.");
AddAttr<std::vector<int>>(
"dilations", "vector<int>, the dilations of the convolution operator.");
AddComment(R"DOC(
**Unfold Operator**
This Operator is used to extract sliding local blocks from a batched input tensor, also known
as im2col when operated on batched 2D image tensor. For each block under the convolution filter,
all element will be rearranged as a column. While the convolution filter sliding over the input
feature map, a series of such columns will be formed.
)DOC");
}
};
class UnfoldOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE_EQ(
ctx->HasInput("X"), true,
platform::errors::NotFound("Input(X) of UnfoldOp should not be null"));
PADDLE_ENFORCE_EQ(
ctx->HasOutput("Y"), true,
platform::errors::NotFound("Output(Y) of UnfoldOp should not be null"));
auto in_dims = ctx->GetInputDim("X");
std::vector<int> kernel_sizes =
ctx->Attrs().Get<std::vector<int>>("kernel_sizes");
std::vector<int> strides = ctx->Attrs().Get<std::vector<int>>("strides");
std::vector<int> paddings = ctx->Attrs().Get<std::vector<int>>("paddings");
std::vector<int> dilations =
ctx->Attrs().Get<std::vector<int>>("dilations");
// Only [N, C, H, W] input supported now
PADDLE_ENFORCE_EQ(
in_dims.size(), 4,
platform::errors::InvalidArgument(
"Input should be 4-D tensor of format [N, C, H, W], but get %u",
in_dims.size()));
PADDLE_ENFORCE_EQ(
in_dims.size() - kernel_sizes.size(), 2U,
platform::errors::InvalidArgument(
"The dims of X should be larger than that of kernel_sizes "
"by a number of 2, due to the batch size and input channel dim. "
"But recieved dims(X:%u) - dims(kernel_sizes:%u) != 2",
in_dims.size(), kernel_sizes.size()));
PADDLE_ENFORCE_EQ(
strides.size(), kernel_sizes.size(),
platform::errors::InvalidArgument(
"The dims of strides should be the same with that of kernel_sizes. "
"But recieved dims(strides: %u) != dims(kernel_sizes: %u).",
strides.size(), kernel_sizes.size()));
PADDLE_ENFORCE_EQ(
paddings.size(), 2 * strides.size(),
platform::errors::InvalidArgument(
"The dims of paddings should be 2 times of that of strides. "
"But recieved dims(paddings: %u) != 2*dims(strides: %u).",
paddings.size(), strides.size()));
PADDLE_ENFORCE_EQ(
strides.size(), dilations.size(),
platform::errors::InvalidArgument(
"The dims of strides should be the same with that of dilations. "
"But recieved dims(strides: %u) != dims(dilations: %u).",
strides.size(), dilations.size()));
// check kernel_sizes
PADDLE_ENFORCE_GT(kernel_sizes[0], 0,
platform::errors::InvalidArgument(
"The `kernel_sizes` should be greater than zero, "
"but recieved kernel_height: %d kernel_width: %d.",
kernel_sizes[0], kernel_sizes[1]));
PADDLE_ENFORCE_GT(kernel_sizes[1], 0,
platform::errors::InvalidArgument(
"The `kernel_sizes` should be greater than zero, "
"but recieved kernel_height: %d kernel_width: %d.",
kernel_sizes[0], kernel_sizes[1]));
// check strides
PADDLE_ENFORCE_GT(strides[0], 0,
platform::errors::InvalidArgument(
"The `strides` should be greater than zero, "
"but recieved strides_height: %d strides_width: %d.",
strides[0], strides[1]));
PADDLE_ENFORCE_GT(strides[1], 0,
platform::errors::InvalidArgument(
"The `strides` should be greater than zero, "
"but recieved strides_height: %d strides_width: %d.",
strides[0], strides[1]));
// check dilations
PADDLE_ENFORCE_GT(
dilations[0], 0,
platform::errors::InvalidArgument(
"The `dilations` should be greater than zero, "
"but recieved dilations_height: %d dilations_width: %d.",
dilations[0], dilations[1]));
PADDLE_ENFORCE_GT(
dilations[1], 0,
platform::errors::InvalidArgument(
"The `dilations` should be greater than zero, "
"but recieved dilations_height: %d dilations_width: %d.",
dilations[0], dilations[1]));
std::vector<int> out_dims;
out_dims.push_back(in_dims[0]);
int output_channels = in_dims[1] * kernel_sizes[0] * kernel_sizes[1];
out_dims.push_back(output_channels);
int output_height =
CalcOutputSize(in_dims[2], kernel_sizes[0], dilations[0], paddings[0],
paddings[2], strides[0]);
int output_width = CalcOutputSize(in_dims[3], kernel_sizes[1], dilations[1],
paddings[1], paddings[3], strides[1]);
// check output height and width
PADDLE_ENFORCE_GT(
output_height, 0,
platform::errors::InvalidArgument(
"The sliding blocks calculated from input spatial size (%d, %d), "
"kernel_sizes (%d, %d), strides (%d, %d), dilations (%d, %d), "
"is (%d, %d), which should be a positive integer.",
in_dims[2], in_dims[3], kernel_sizes[0], kernel_sizes[1],
strides[0], strides[1], dilations[0], dilations[1], output_height,
output_width));
PADDLE_ENFORCE_GT(
output_width, 0,
platform::errors::InvalidArgument(
"The sliding blocks calculated from input spatial size (%d, %d), "
"kernel_sizes (%d, %d), strides (%d, %d), dilations (%d, %d), "
"is (%d, %d), which should be a positive integer.",
in_dims[2], in_dims[3], kernel_sizes[0], kernel_sizes[1],
strides[0], strides[1], dilations[0], dilations[1], output_height,
output_width));
int output_col_length = output_height * output_width;
out_dims.push_back(output_col_length);
ctx->SetOutputDim("Y", framework::make_ddim(out_dims));
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(
OperatorWithKernel::IndicateVarDataType(ctx, "X"),
ctx.device_context());
}
};
class UnfoldGradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE_EQ(
ctx->HasInput(framework::GradVarName("Y")), true,
platform::errors::NotFound("The gradient of Y should not be null"));
PADDLE_ENFORCE_EQ(
ctx->HasInput("X"), true,
platform::errors::NotFound("The input X should not be null"));
PADDLE_ENFORCE_EQ(
ctx->HasOutput(framework::GradVarName("X")), true,
platform::errors::NotFound("The gradient of X should not be null"));
ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
ctx, framework::GradVarName("Y")),
ctx.device_context());
}
};
template <typename T>
class UnfoldGradMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
protected:
void Apply(GradOpPtr<T> op) const override {
op->SetType("unfold_grad");
op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y"));
op->SetInput("X", this->Input("X"));
op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
op->SetAttrMap(this->Attrs());
}
};
DECLARE_NO_NEED_BUFFER_VARS_INFERER(UnfoldGradOpNoNeedBufferVarsInferer, "X");
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(unfold, ops::UnfoldOp, ops::UnfoldOpMaker,
ops::UnfoldGradMaker<paddle::framework::OpDesc>,
ops::UnfoldGradMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(unfold_grad, ops::UnfoldGradOp,
ops::UnfoldGradOpNoNeedBufferVarsInferer);
REGISTER_OP_CPU_KERNEL(
unfold, ops::UnfoldOpKernel<paddle::platform::CPUDeviceContext, float>,
ops::UnfoldOpKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
unfold_grad,
ops::UnfoldGradOpKernel<paddle::platform::CPUDeviceContext, float>,
ops::UnfoldGradOpKernel<paddle::platform::CPUDeviceContext, double>);
<commit_msg>[bug fix] fix unfold runtime bug (#38819)<commit_after>/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#include "paddle/fluid/operators/unfold_op.h"
namespace paddle {
namespace operators {
class UnfoldOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X",
"Tensor, "
"the input of unfold op. "
"The format of X is [N, C_in, H, W], "
"where N is the batch size, C_in is the input channels, "
"H is the height and W is the width");
AddOutput(
"Y",
"Tensor, "
"the output of unfold op. "
"The format of Y is [N, C_in*filter_height*filter_width, "
"output_height*output_width], where N is the batch size, "
"C_in is the input channels of X, filter_height and filter_width is "
"height and width of the filtering kernel, output_height and "
"output_width "
"is the calculated height and width of output feature map.");
AddAttr<std::vector<int>>(
"kernel_sizes",
"vector<int>, the kernel sizes of the convolution operator.");
AddAttr<std::vector<int>>(
"strides", "vector<int>, the strides of the convolution operator.");
AddAttr<std::vector<int>>(
"paddings",
"vector<int>, the paddings applied to pad the feature map.");
AddAttr<std::vector<int>>(
"dilations", "vector<int>, the dilations of the convolution operator.");
AddComment(R"DOC(
**Unfold Operator**
This Operator is used to extract sliding local blocks from a batched input tensor, also known
as im2col when operated on batched 2D image tensor. For each block under the convolution filter,
all element will be rearranged as a column. While the convolution filter sliding over the input
feature map, a series of such columns will be formed.
)DOC");
}
};
class UnfoldOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE_EQ(
ctx->HasInput("X"), true,
platform::errors::NotFound("Input(X) of UnfoldOp should not be null"));
PADDLE_ENFORCE_EQ(
ctx->HasOutput("Y"), true,
platform::errors::NotFound("Output(Y) of UnfoldOp should not be null"));
auto in_dims = ctx->GetInputDim("X");
std::vector<int> kernel_sizes =
ctx->Attrs().Get<std::vector<int>>("kernel_sizes");
std::vector<int> strides = ctx->Attrs().Get<std::vector<int>>("strides");
std::vector<int> paddings = ctx->Attrs().Get<std::vector<int>>("paddings");
std::vector<int> dilations =
ctx->Attrs().Get<std::vector<int>>("dilations");
// Only [N, C, H, W] input supported now
PADDLE_ENFORCE_EQ(
in_dims.size(), 4,
platform::errors::InvalidArgument(
"Input should be 4-D tensor of format [N, C, H, W], but get %u",
in_dims.size()));
PADDLE_ENFORCE_EQ(
in_dims.size() - kernel_sizes.size(), 2U,
platform::errors::InvalidArgument(
"The dims of X should be larger than that of kernel_sizes "
"by a number of 2, due to the batch size and input channel dim. "
"But recieved dims(X:%u) - dims(kernel_sizes:%u) != 2",
in_dims.size(), kernel_sizes.size()));
PADDLE_ENFORCE_EQ(
strides.size(), kernel_sizes.size(),
platform::errors::InvalidArgument(
"The dims of strides should be the same with that of kernel_sizes. "
"But recieved dims(strides: %u) != dims(kernel_sizes: %u).",
strides.size(), kernel_sizes.size()));
PADDLE_ENFORCE_EQ(
paddings.size(), 2 * strides.size(),
platform::errors::InvalidArgument(
"The dims of paddings should be 2 times of that of strides. "
"But recieved dims(paddings: %u) != 2*dims(strides: %u).",
paddings.size(), strides.size()));
PADDLE_ENFORCE_EQ(
strides.size(), dilations.size(),
platform::errors::InvalidArgument(
"The dims of strides should be the same with that of dilations. "
"But recieved dims(strides: %u) != dims(dilations: %u).",
strides.size(), dilations.size()));
// check kernel_sizes
PADDLE_ENFORCE_GT(kernel_sizes[0], 0,
platform::errors::InvalidArgument(
"The `kernel_sizes` should be greater than zero, "
"but recieved kernel_height: %d kernel_width: %d.",
kernel_sizes[0], kernel_sizes[1]));
PADDLE_ENFORCE_GT(kernel_sizes[1], 0,
platform::errors::InvalidArgument(
"The `kernel_sizes` should be greater than zero, "
"but recieved kernel_height: %d kernel_width: %d.",
kernel_sizes[0], kernel_sizes[1]));
// check strides
PADDLE_ENFORCE_GT(strides[0], 0,
platform::errors::InvalidArgument(
"The `strides` should be greater than zero, "
"but recieved strides_height: %d strides_width: %d.",
strides[0], strides[1]));
PADDLE_ENFORCE_GT(strides[1], 0,
platform::errors::InvalidArgument(
"The `strides` should be greater than zero, "
"but recieved strides_height: %d strides_width: %d.",
strides[0], strides[1]));
// check dilations
PADDLE_ENFORCE_GT(
dilations[0], 0,
platform::errors::InvalidArgument(
"The `dilations` should be greater than zero, "
"but recieved dilations_height: %d dilations_width: %d.",
dilations[0], dilations[1]));
PADDLE_ENFORCE_GT(
dilations[1], 0,
platform::errors::InvalidArgument(
"The `dilations` should be greater than zero, "
"but recieved dilations_height: %d dilations_width: %d.",
dilations[0], dilations[1]));
bool contain_unknown_dim = framework::contain_unknown_dim(in_dims);
bool check = ctx->IsRuntime() || !contain_unknown_dim;
if (check) {
std::vector<int> out_dims;
out_dims.push_back(in_dims[0]);
int output_channels = in_dims[1] * kernel_sizes[0] * kernel_sizes[1];
out_dims.push_back(output_channels);
int output_height =
CalcOutputSize(in_dims[2], kernel_sizes[0], dilations[0], paddings[0],
paddings[2], strides[0]);
int output_width =
CalcOutputSize(in_dims[3], kernel_sizes[1], dilations[1], paddings[1],
paddings[3], strides[1]);
// check output height and width
PADDLE_ENFORCE_GT(
output_height, 0,
platform::errors::InvalidArgument(
"The sliding blocks calculated from input spatial size "
"(%d, %d), kernel_sizes (%d, %d), strides (%d, %d), "
"dilations (%d, %d), is (%d, %d), which should be a "
"positive integer.",
in_dims[2], in_dims[3], kernel_sizes[0], kernel_sizes[1],
strides[0], strides[1], dilations[0], dilations[1], output_height,
output_width));
PADDLE_ENFORCE_GT(
output_width, 0,
platform::errors::InvalidArgument(
"The sliding blocks calculated from input spatial size "
"(%d, %d), kernel_sizes (%d, %d), strides (%d, %d), "
"dilations (%d, %d), is (%d, %d), which should be a "
"positive integer.",
in_dims[2], in_dims[3], kernel_sizes[0], kernel_sizes[1],
strides[0], strides[1], dilations[0], dilations[1], output_height,
output_width));
int output_col_length = output_height * output_width;
out_dims.push_back(output_col_length);
ctx->SetOutputDim("Y", framework::make_ddim(out_dims));
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(
OperatorWithKernel::IndicateVarDataType(ctx, "X"),
ctx.device_context());
}
};
class UnfoldGradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE_EQ(
ctx->HasInput(framework::GradVarName("Y")), true,
platform::errors::NotFound("The gradient of Y should not be null"));
PADDLE_ENFORCE_EQ(
ctx->HasInput("X"), true,
platform::errors::NotFound("The input X should not be null"));
PADDLE_ENFORCE_EQ(
ctx->HasOutput(framework::GradVarName("X")), true,
platform::errors::NotFound("The gradient of X should not be null"));
ctx->SetOutputDim(framework::GradVarName("X"), ctx->GetInputDim("X"));
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
ctx, framework::GradVarName("Y")),
ctx.device_context());
}
};
template <typename T>
class UnfoldGradMaker : public framework::SingleGradOpMaker<T> {
public:
using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
protected:
void Apply(GradOpPtr<T> op) const override {
op->SetType("unfold_grad");
op->SetInput(framework::GradVarName("Y"), this->OutputGrad("Y"));
op->SetInput("X", this->Input("X"));
op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
op->SetAttrMap(this->Attrs());
}
};
DECLARE_NO_NEED_BUFFER_VARS_INFERER(UnfoldGradOpNoNeedBufferVarsInferer, "X");
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(unfold, ops::UnfoldOp, ops::UnfoldOpMaker,
ops::UnfoldGradMaker<paddle::framework::OpDesc>,
ops::UnfoldGradMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(unfold_grad, ops::UnfoldGradOp,
ops::UnfoldGradOpNoNeedBufferVarsInferer);
REGISTER_OP_CPU_KERNEL(
unfold, ops::UnfoldOpKernel<paddle::platform::CPUDeviceContext, float>,
ops::UnfoldOpKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
unfold_grad,
ops::UnfoldGradOpKernel<paddle::platform::CPUDeviceContext, float>,
ops::UnfoldGradOpKernel<paddle::platform::CPUDeviceContext, double>);
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.